diff --git a/TODO.md b/TODO.md index 6564b9d6..a8cb98b9 100644 --- a/TODO.md +++ b/TODO.md @@ -726,6 +726,14 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern löschen (`editors/splitJoin.ts`, App) — dort ersetzt `cutSegment` per `replace` mit NEUER id (hängt an statt zu ersetzen; beim Port prüfen); Fang-Kandidaten aus dem Modell (`tools/snapping.ts`: `baseSegments`, Kreise, Raum-Anker; Nahmodus ab 2000 Zeichnungen) → `snap.rs`. + ✅ (29.10.) **Einfügen im Kern** ([K4] S3): `cmd_paste.rs` (`{cmd: "paste", clip, levelId, stamp}`): Klone mit neuen + ids `prefix-stamp-k` auf dem aktiven Geschoss, an denselben Koordinaten; Öffnungen an die mitkopierte Wirtswand + umgehängt (ohne sie weggelassen); Rechnung auf rohem JSON (unbekannte Felder, Schlüsselreihenfolge bleiben). Die + Zwischenablage (Sammeln, Text-Format, Speicher) bleibt in TS; `pasteElementClipboard(project, clip, level)` ist + Fassade (neue ids für die Nachauswahl aus den `add`-Ops), die Tastatur ruft sie in `applyChange((p) => …)`. + Gleichheit (einmalig, Test gelöscht): 400 Zufallsprojekte × Zufallsauswahl, Ops gleich bis auf die ids (Verweise + Öffnung → Wand konsistent). Offen (gab es auch vorher nicht): Versatz beim wiederholten Einfügen, Gruppen + mitkopieren, Einfügen in die aktive Gruppe (`activeGroupOps`). Nicht in der Tauri-App geprüft. **Leistung nach der Zusammenführung (29.10.)** — erledigt damit die Offen-Punkte der Griffe/Objekt-Info: (a) **id-Suche indiziert:** der Positions-Index des Dokuments (`PosCache`) wird ab der ersten Suche gebaut (Listen ≥ 32), überlebt `add` am Ende und ist über `Lookup` (`Document::lookup`) auch für die Wurzel-Abfragen da — Griffe diff --git a/src-tauri/core/src/cmd_paste.rs b/src-tauri/core/src/cmd_paste.rs new file mode 100644 index 00000000..a18830e0 --- /dev/null +++ b/src-tauri/core/src/cmd_paste.rs @@ -0,0 +1,109 @@ +//! Einfügen der Element-Zwischenablage im Kern ([K4] S3, vorher `pasteElementClipboard` in +//! `editors/elementClipboard.ts`). Die Zwischenablage selbst (tief kopierte Elemente je Bauteil-Art) +//! hält die TS-Hülle; die Anfrage trägt sie mit (`{cmd: "paste", clip, levelId, stamp}`). +//! +//! Einfügen = Klone mit neuen ids (`prefix-stamp-k`, [`IdGen`]) auf dem aktiven Geschoss, an +//! denselben Modell-Koordinaten (kein Versatz, wie das bisherige Verhalten). Verweise: eine Öffnung +//! hängt an ihrer Wirtswand (`hostWallId`) und wird auf die neue Wand umgehängt; ohne mitkopierte +//! Wirtswand fällt sie weg (keine Öffnung ohne Wirt). Gruppen-Mitgliedschaften werden nicht +//! mitkopiert (die Klone sind neue, ungruppierte Elemente). +//! +//! Rechnung auf rohem JSON (`{...e, id, floorId}`: vorhandene Schlüssel behalten ihre Stelle, +//! fehlende kommen ans Ende, unbekannte Felder bleiben). + +use crate::cmd_transform::IdGen; +use crate::grips::{arr, field, with_all}; +use crate::ops::{id_of, Op}; +use serde_json::Value; +use std::collections::HashMap; + +/// Listen der Zwischenablage: (Schlüssel in `clip`, Projekt-Liste, id-Präfix, Geschoss-Feld). +/// Reihenfolge = Reihenfolge der ids und der Ops (Wände vor Öffnungen). +const LISTS: [(&str, &str, &str, &str); 9] = [ + ("walls", "walls", "W", "floorId"), + ("drawings", "drawings2d", "dr2d", "levelId"), + ("ceilings", "ceilings", "C", "floorId"), + ("roofs", "roofs", "RF", "floorId"), + ("openings", "openings", "O", ""), + ("stairs", "stairs", "ST", "floorId"), + ("rooms", "rooms", "RM", "floorId"), + ("extrudedSolids", "extrudedSolids", "extrude", "levelId"), + ("columns", "columns", "column", "floorId"), +]; + +/// Ops des Einfügens: je Liste ein `add` (leere Listen ohne Op). +pub fn paste_ops(clip: &Value, level_id: &str, stamp: &str) -> Vec { + let mut ids = IdGen::new(stamp); + let mut wall_ids: HashMap = HashMap::new(); + let level = Value::String(level_id.to_owned()); + let mut ops = Vec::new(); + for (key, collection, prefix, level_field) in LISTS { + let mut items = Vec::new(); + for e in arr(field(clip, key)) { + if level_field.is_empty() { + // Öffnung: nur mit mitkopierter Wirtswand, umgehängt. + let host = field(e, "hostWallId").and_then(Value::as_str).and_then(|h| wall_ids.get(h)); + let Some(host) = host else { continue }; + let host = Value::String(host.clone()); + items.push(with_all(e, vec![("id", Value::String(ids.next(prefix))), ("hostWallId", host)])); + continue; + } + let id = ids.next(prefix); + if key == "walls" { + if let Some(old) = id_of(e) { + wall_ids.insert(old.to_owned(), id.clone()); + } + } + items.push(with_all(e, vec![("id", Value::String(id)), (level_field, level.clone())])); + } + if !items.is_empty() { + ops.push(Op::Add { collection: collection.into(), items, at: None }); + } + } + ops +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn klone_mit_neuen_ids_auf_dem_aktiven_geschoss_oeffnung_umgehaengt() { + let clip = json!({ + "walls": [ + {"id": "w1", "type": "wall", "floorId": "eg", "start": {"x": 0, "y": 0}, "end": {"x": 5, "y": 0}, "extra": 1}, + {"id": "w2", "type": "wall", "start": {"x": 0, "y": 1}, "end": {"x": 5, "y": 1}} + ], + "drawings": [{"id": "d1", "levelId": "eg", "geom": {"shape": "line"}}], + "openings": [ + {"id": "o1", "hostWallId": "w1", "position": 1.5}, + {"id": "o2", "hostWallId": "w9"} + ], + "columns": [{"id": "c1", "floorId": "eg"}], + "rooms": [] + }); + let ops: Vec = paste_ops(&clip, "og", "s").iter().map(Op::to_json).collect(); + assert_eq!(ops.len(), 4); + assert_eq!(ops[0]["collection"], "walls"); + let walls = ops[0]["items"].as_array().unwrap(); + assert_eq!(walls[0], json!({"id": "W-s-1", "type": "wall", "floorId": "og", "start": {"x": 0, "y": 0}, "end": {"x": 5, "y": 0}, "extra": 1})); + // Fehlendes Geschoss-Feld kommt ans Ende (wie `{...w, id, floorId}`). + assert_eq!(walls[1].as_object().unwrap().keys().collect::>(), ["id", "type", "start", "end", "floorId"]); + assert_eq!(ops[1]["collection"], "drawings2d"); + assert_eq!(ops[1]["items"][0]["id"], "dr2d-s-3"); + assert_eq!(ops[1]["items"][0]["levelId"], "og"); + // Öffnung o1 an die neue Wand, o2 (Wirtswand nicht kopiert) fällt weg. + assert_eq!(ops[2]["collection"], "openings"); + assert_eq!(ops[2]["items"], json!([{"id": "O-s-4", "hostWallId": "W-s-1", "position": 1.5}])); + assert_eq!(ops[3]["collection"], "columns"); + assert_eq!(ops[3]["items"][0], json!({"id": "column-s-5", "floorId": "og"})); + } + + #[test] + fn leere_oder_kaputte_zwischenablage_ergibt_nichts() { + assert!(paste_ops(&json!({}), "og", "s").is_empty()); + assert!(paste_ops(&json!(null), "og", "s").is_empty()); + assert!(paste_ops(&json!({"walls": 3, "openings": [{"id": "o"}]}), "og", "s").is_empty()); + } +} diff --git a/src-tauri/core/src/commands.rs b/src-tauri/core/src/commands.rs index a617e85a..812f292f 100644 --- a/src-tauri/core/src/commands.rs +++ b/src-tauri/core/src/commands.rs @@ -26,6 +26,7 @@ pub fn ops(root: &Map, text: &str) -> Result, String> { "align" => crate::cmd_transform::align_ops(root, &ids("ids"), &s("mode")), "distribute" => crate::cmd_transform::distribute_ops(root, &ids("ids"), &s("axis")), "defblock" => crate::cmd_transform::defblock_ops(root, &parse(&v, cmd)?), + "paste" => crate::cmd_paste::paste_ops(v.get("clip").unwrap_or(&Value::Null), &s("levelId"), &s("stamp")), other => return Err(format!("Unbekannter Befehl: {other}")), }) } diff --git a/src-tauri/core/src/lib.rs b/src-tauri/core/src/lib.rs index f4e0a899..27c7e7cf 100644 --- a/src-tauri/core/src/lib.rs +++ b/src-tauri/core/src/lib.rs @@ -92,6 +92,7 @@ pub mod commands; pub mod cmd_transform; pub mod cmd_edit; pub mod polyline_vertex; +pub mod cmd_paste; #[cfg(feature = "web")] mod web; diff --git a/src/editors/elementClipboard.test.ts b/src/editors/elementClipboard.test.ts index 62c29c60..ce11f054 100644 --- a/src/editors/elementClipboard.test.ts +++ b/src/editors/elementClipboard.test.ts @@ -122,7 +122,7 @@ describe("pasteElementClipboard", () => { it("fügt Wand + Öffnung mit NEUEN, verknüpften IDs auf dem aktiven Geschoss ein", () => { const p = project(); const clip = collectElementClipboard(p, { ...emptySel(), wallIds: ["w1"] })!; - const { ops, pastedIds } = pasteElementClipboard(clip, "og"); + const { ops, pastedIds } = pasteElementClipboard(p, clip, "og"); const next = applyOps(p, ops); expect(next.walls.length).toBe(2); expect(next.openings!.length).toBe(2); @@ -139,7 +139,7 @@ describe("pasteElementClipboard", () => { it("Originale bleiben unverändert (immutabel)", () => { const p = project(); const clip = collectElementClipboard(p, { ...emptySel(), wallIds: ["w1"] })!; - pasteElementClipboard(clip, "og"); + pasteElementClipboard(p, clip, "og"); expect(p.walls.length).toBe(1); expect(p.walls[0].id).toBe("w1"); }); diff --git a/src/editors/elementClipboard.ts b/src/editors/elementClipboard.ts index e954f728..6afffcd3 100644 --- a/src/editors/elementClipboard.ts +++ b/src/editors/elementClipboard.ts @@ -30,8 +30,8 @@ import type { Stair, Wall, } from "../model/types"; -import { uniqueId } from "../tools/types"; -import { addItems } from "../core"; +import { uniqueStamp } from "../tools/types"; +import { documentFor } from "../core/document"; import type { CoreOp } from "../core"; /** Auswahl-IDs je Bauteil-Art, wie sie die 9 Auswahl-Kanäle des Stores liefern. */ @@ -144,94 +144,47 @@ export interface PastedIds { columnIds: string[]; } +/** Projekt-Liste → Feld in {@link PastedIds}. */ +const PASTED_KEY: Record = { + walls: "wallIds", + drawings2d: "drawingIds", + ceilings: "ceilingIds", + roofs: "roofIds", + openings: "openingIds", + stairs: "stairIds", + rooms: "roomIds", + extrudedSolids: "extrudedSolidIds", + columns: "columnIds", +}; + /** - * Fügt eine Zwischenablage ins Projekt ein: Klone mit neuen IDs auf dem - * AKTIVEN Geschoss (`activeLevelId`), an denselben Modell-Koordinaten. Liefert - * die Ops (Anhängen je Liste) + die neuen IDs (für die Nachauswahl). + * Fügt eine Zwischenablage ins Projekt ein ([K4] S3: gerechnet im Kern, `cmd_paste.rs`): Klone mit + * neuen IDs auf dem AKTIVEN Geschoss (`activeLevelId`), an denselben Modell-Koordinaten; Öffnungen + * an die mitkopierte Wirtswand umgehängt. Liefert die Ops (Anhängen je Liste) + die neuen IDs (für + * die Nachauswahl). `project` bestimmt nur das Kern-Dokument der Anfrage. */ export function pasteElementClipboard( + project: Project, clip: ElementClipboard, activeLevelId: string, ): { ops: CoreOp[]; pastedIds: PastedIds } { - const wallIdMap = new Map(); - const newWalls: Wall[] = clip.walls.map((w) => { - const id = uniqueId("W"); - wallIdMap.set(w.id, id); - return { ...w, id, floorId: activeLevelId }; - }); - const newDrawings: Drawing2D[] = clip.drawings.map((d) => ({ - ...d, - id: uniqueId("dr2d"), - levelId: activeLevelId, - })); - const newCeilings: Ceiling[] = clip.ceilings.map((c) => ({ - ...c, - id: uniqueId("C"), - floorId: activeLevelId, - })); - const newRoofs: Roof[] = clip.roofs.map((r) => ({ - ...r, - id: uniqueId("RF"), - floorId: activeLevelId, - })); - // Nur Öffnungen mit einer erfolgreich mitkopierten Wirtswand ergeben eine - // gültige neue Öffnung (sollte durch `collectElementClipboard` immer - // gegeben sein — Map-Miss defensiv übersprungen statt eine kaputte - // Öffnung ohne Wirt zu erzeugen). - const newOpenings: Opening[] = []; - for (const o of clip.openings) { - const hostWallId = wallIdMap.get(o.hostWallId); - if (!hostWallId) continue; - newOpenings.push({ ...o, id: uniqueId("O"), hostWallId }); - } - const newStairs: Stair[] = clip.stairs.map((s) => ({ - ...s, - id: uniqueId("ST"), - floorId: activeLevelId, - })); - const newRooms: Room[] = clip.rooms.map((r) => ({ - ...r, - id: uniqueId("RM"), - floorId: activeLevelId, - })); - const newExtrudedSolids: ExtrudedSolid[] = clip.extrudedSolids.map((s) => ({ - ...s, - id: uniqueId("extrude"), - levelId: activeLevelId, - })); - const newColumns: Column[] = clip.columns.map((c) => ({ - ...c, - id: uniqueId("column"), - floorId: activeLevelId, - })); - - // Wände vor Öffnungen (Wirtswand zuerst), sonst Reihenfolge der Projekt-Listen. - const ops: CoreOp[] = [ - ...addItems("walls", newWalls), - ...addItems("drawings2d", newDrawings), - ...addItems("ceilings", newCeilings), - ...addItems("roofs", newRoofs), - ...addItems("openings", newOpenings), - ...addItems("stairs", newStairs), - ...addItems("rooms", newRooms), - ...addItems("extrudedSolids", newExtrudedSolids), - ...addItems("columns", newColumns), - ]; - - return { - ops, - pastedIds: { - wallIds: newWalls.map((w) => w.id), - drawingIds: newDrawings.map((d) => d.id), - ceilingIds: newCeilings.map((c) => c.id), - roofIds: newRoofs.map((r) => r.id), - openingIds: newOpenings.map((o) => o.id), - stairIds: newStairs.map((s) => s.id), - roomIds: newRooms.map((r) => r.id), - extrudedSolidIds: newExtrudedSolids.map((s) => s.id), - columnIds: newColumns.map((c) => c.id), - }, + const ops = documentFor(project).cmdOps({ cmd: "paste", clip, levelId: activeLevelId, stamp: uniqueStamp() }); + const pastedIds: PastedIds = { + wallIds: [], + drawingIds: [], + ceilingIds: [], + roofIds: [], + openingIds: [], + stairIds: [], + roomIds: [], + extrudedSolidIds: [], + columnIds: [], }; + for (const op of ops) { + const key = op.kind === "add" ? PASTED_KEY[op.collection] : undefined; + if (op.kind === "add" && key) for (const e of op.items) pastedIds[key].push((e as { id: string }).id); + } + return { ops, pastedIds }; } export { EMPTY_CLIPBOARD }; diff --git a/src/state/useKeyboardShortcuts.ts b/src/state/useKeyboardShortcuts.ts index 4d081eec..f2adc4ec 100644 --- a/src/state/useKeyboardShortcuts.ts +++ b/src/state/useKeyboardShortcuts.ts @@ -28,7 +28,7 @@ import { isClipboardEmpty, pasteElementClipboard, } from "../editors/elementClipboard"; -import type { ElementClipboard, ElementSelectionIds } from "../editors/elementClipboard"; +import type { ElementClipboard, ElementSelectionIds, PastedIds } from "../editors/elementClipboard"; import { parseClipboardText, serializeClipboardText } from "../editors/elementClipboardSerialize"; import { matchesShortcut, type ShortcutId, type ShortcutOverrides } from "./keyboardShortcuts"; @@ -549,7 +549,7 @@ export function useElementClipboardShortcut( setElementClipboard: (c: ElementClipboard | null) => void, activeLevelId: string, project: Project, - applyChange: (ops: readonly CoreOp[]) => void, + applyChange: (ops: readonly CoreOp[] | ((p: Project) => readonly CoreOp[])) => void, setSelected: { wallIds: (ids: string[]) => void; drawingIds: (ids: string[]) => void; @@ -588,8 +588,15 @@ export function useElementClipboardShortcut( e.preventDefault(); const paste = (clip: ElementClipboard | null) => { if (!clip || isClipboardEmpty(clip)) return; - const { ops, pastedIds } = pasteElementClipboard(clip, activeLevelId); - applyChange(ops); + // Kern rechnet auf dem aktuellen Store-Projekt; die neuen ids für die Nachauswahl. + const out: { ids?: PastedIds } = {}; + applyChange((p) => { + const r = pasteElementClipboard(p, clip, activeLevelId); + out.ids = r.pastedIds; + return r.ops; + }); + const pastedIds = out.ids; + if (!pastedIds) return; setSelected.wallIds(pastedIds.wallIds); setSelected.drawingIds(pastedIds.drawingIds); setSelected.ceilingIds(pastedIds.ceilingIds);