diff --git a/TODO.md b/TODO.md index 4901c811..fd4657d2 100644 --- a/TODO.md +++ b/TODO.md @@ -360,7 +360,13 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern **Abschluss (29.10.):** Rechnung liegt im Kern; TS hält Oberfläche, Zustandsautomaten der Befehle, Netz-Abrufe, DOM-/jsPDF-Aufbau und dünne Fassaden. Bewusst in TS: `model/color.ts` (Farbmischer der UI), Sicht-Culling/Ansichts- Transformation/GPU-Cache der Plan-Ansicht, Werkzeug-Vorschau aus UI-Zustand. Rest-Pendenzen: STEP-Import (truck), - Import-Ops als JSON zurück (42 MB beim 150k-Kataster), Undo-Liste in der UI [84]. Nicht auf dem Mac getestet. + Import-Ops als JSON zurück (42 MB beim 150k-Kataster). Nicht auf dem Mac getestet. + **[84] Undo-Verlauf als Liste ✅ (29.10.):** Schritte tragen eine Beschriftung im Kern (`Step.label`, `History::set_label` für den + nächsten neuen Schritt; Koaleszenz/Gruppen behalten die des ersten; `doc_history_label/labels/jump`, `Document::history_jump` = + mehrere Schritte in einem Aufruf). TS: `withHistoryLabel`/`labelCommit` (`historySlice.ts`), Standard aus Befehl (`history.cmd.`), + Griff, Import oder den Ops (`history.op.:`); Anzeige `historyLabelText`. Panel `HistoryPanel` (Bearbeiten > Verlauf, + nicht im Standard-Layout), jüngster oben, Wiederholen-Schritte gedimmt, Klick = `jumpHistory`. Offen: Beschriftungen für + Eigenschafts-Änderungen aus Panels sind nur „X ändern" (kein Feldname); kein Tastenkürzel; nicht auf dem Mac getestet. Ziel (Entscheid 28.10., Maintainer): nur die UI bleibt TS, alles andere Rust. Vorgehen in Stufen, jede verdrahtet und mit Gleichheitstest gegen die TS-Fassung, die im selben Schritt verschwindet: - ✅ **S1 Dokument im Kern** (28.10.): `document.rs` hält das Projekt als JSON-Baum, `core/document.ts` spiegelt jede @@ -1333,7 +1339,7 @@ Reihenfolge = Abhängigkeiten. Neue Geometrie entsteht in Rust ([K]). Alle ○: [27] Punktwolken (Leser ✅ [B9], Anzeige ◐ s. u., Modell offen) · [28] Phasen · [29] Bauteillisten (◐, Export vorhanden) · [43] Verknüpfte Modelle · [44] Aus Datei einfügen · [45] Favoriten · [68] Gelände mit Baugrube (= [T6]) · [71] U-Werte · [72] Graue Energie KBOB · [73] eBKP-H · [74] SIA 500 · [75] Fluchtwege VKF · [83] Befehlspalette · -[84] Undo-Verlauf · [85] Makro-Rekorder · [86] Pipette · [87] Fang mit Begründung · [48] Web-Worker +[85] Makro-Rekorder · [86] Pipette · [87] Fang mit Begründung · [48] Web-Worker (◐, DXF-Parser, IFC-Import) · [52] Icons (◐, `CommandIcon.tsx`) · [56] Startparameter · [89] Git-freundliches Format · [90] Versionsvergleich · [91] Assistent · [92] Speckle. diff --git a/e2e/drawing.spec.ts b/e2e/drawing.spec.ts index 77457559..c62c8290 100644 --- a/e2e/drawing.spec.ts +++ b/e2e/drawing.spec.ts @@ -103,3 +103,41 @@ test("Mehrmals ganz zurück und wieder vor: Redo bleibt vollständig", async ({ // „Neues Projekt" ist nicht rückgängig zu machen (Verlauf beginnt neu). await expect(page.locator(".project-name")).toHaveText("Leeres Projekt"); }); + +// [84] Verlaufsliste: Klick auf einen Eintrag springt zu diesem Stand (mehrere Schritte in einem Aufruf). +test("Verlauf-Panel: Klick springt zum Schritt", async ({ page }) => { + await startNewProject(page); + await openTab(page, "Elemente"); + for (const [a, b] of [["0,0", "5,0"], ["5,0", "5,4"], ["5,4", "0,4"]]) { + await page.getByRole("button", { name: "Wand", exact: true }).click(); + // Das Werkzeug bleibt nach dem Befehl gewählt: ein zweiter Klick schaltet es ab, dann erneut wählen. + if (!(await page.locator(".cmdline-prompt").textContent())?.includes("Startpunkt")) { + await page.getByRole("button", { name: "Wand", exact: true }).click(); + } + await expect(page.locator(".cmdline-prompt")).toHaveText("Startpunkt der Wand:"); + await commandInput(page).focus(); + await typeCommand(page, a!); + await typeCommand(page, b!); + await finishCommand(page); + } + await expect(elementRows(page)).toHaveCount(3); + await blurFocus(page); + + await page.getByRole("button", { name: "Bearbeiten", exact: true }).click(); + await page.getByRole("option", { name: "Verlauf" }).click(); + const entries = page.getByTestId("history-entry"); + // Jüngster oben: drei Wand-Schritte + Ausgangsstand. + await expect(entries).toHaveCount(4); + await expect(entries.first()).toContainText("Wand zeichnen"); + await expect(entries.first()).toHaveAttribute("aria-selected", "true"); + await expect(entries.last()).toContainText("Ausgangsstand"); + + // Erster Wand-Eintrag (vorletzte Zeile) → eine Wand; die späteren Schritte bleiben als Wiederholen stehen. + await entries.nth(2).click(); + await expect(elementRows(page)).toHaveCount(1); + await expect(entries).toHaveCount(4); + await expect(entries.nth(2)).toHaveAttribute("aria-selected", "true"); + // Oberster Eintrag → wieder alle drei. + await entries.first().click(); + await expect(elementRows(page)).toHaveCount(3); +}); diff --git a/src-tauri/core/src/document.rs b/src-tauri/core/src/document.rs index f30c9e0e..fd06147d 100644 --- a/src-tauri/core/src/document.rs +++ b/src-tauri/core/src/document.rs @@ -630,22 +630,41 @@ impl Document { /// Einen Schritt zurück; liefert die angewendeten Ops (für die TS-Leseansicht), `None` = nichts. /// Die dabei entstehenden Inversen sind der Redo-Schritt. pub fn undo(&mut self) -> Option> { - let ops = self.history.pop_undo()?.ops; - let applied = ops.clone(); - let redo = self.apply_inverting(ops); - self.history.push_redo(Step::new(redo)); + let step = self.history.pop_undo()?; + let applied = step.ops.clone(); + let redo = self.apply_inverting(step.ops); + self.history.push_redo(Step::new(redo).labeled(step.label)); Some(applied) } /// Einen Schritt vor; liefert die angewendeten Ops, `None` = nichts. pub fn redo(&mut self) -> Option> { - let ops = self.history.pop_redo()?.ops; - let applied = ops.clone(); - let undo = self.apply_inverting(ops); - self.history.push_undo(Step::new(undo)); + let step = self.history.pop_redo()?; + let applied = step.ops.clone(); + let undo = self.apply_inverting(step.ops); + self.history.push_undo(Step::new(undo).labeled(step.label)); Some(applied) } + /// Springt im Verlauf auf Undo-Tiefe `target` (0 = Anfang, `undo_depth + redo_depth` = Ende): + /// mehrere Schritte in einem Aufruf. Liefert alle angewendeten Ops in Reihenfolge (die + /// [`Document::last_hits`] gelten für diese Folge); `None` = schon dort oder ausserhalb. + pub fn history_jump(&mut self, target: usize) -> Option> { + let (u, r) = (self.history.undo_depth(), self.history.redo_depth()); + if target == u || target > u + r { + return None; + } + let mut all = Vec::new(); + let mut hits = Vec::new(); + for _ in 0..u.abs_diff(target) { + let ops = if target < u { self.undo() } else { self.redo() }?; + all.extend(ops); + hits.extend_from_slice(&self.last_hits); + } + self.last_hits = hits; + Some(all) + } + pub fn history(&self) -> &History { &self.history } @@ -887,6 +906,59 @@ mod tests { } } + fn set_name(d: &mut Document, v: &str, label: &str, key: Option<&str>, now: f64) { + d.history_mut().set_label(label); + d.commit(ops(json!([{"kind":"setField","key":"name","value":v}])), key, now, false).unwrap(); + } + + #[test] + fn schritt_beschriftungen_ueberleben_koaleszenz_gruppen_undo() { + let mut d = doc(); + set_name(&mut d, "A", "Eins", None, 0.0); + // Koaleszenz: der Schritt behält die Beschriftung des ersten Eintrags. + set_name(&mut d, "B", "Zwei", Some("drag"), 10.0); + set_name(&mut d, "C", "Drei", Some("drag"), 20.0); + // Gruppe: erste Beschriftung gilt; ohne Beschriftung bleibt sie leer (= Standard in der UI). + d.history_mut().begin_group(); + set_name(&mut d, "D", "Gruppe", None, 30.0); + set_name(&mut d, "E", "", None, 31.0); + d.history_mut().end_group(); + set_name(&mut d, "F", "", None, 40.0); + assert_eq!(d.history().labels(), (vec!["Eins".to_string(), "Zwei".into(), "Gruppe".into(), "".into()], vec![])); + d.undo().unwrap(); + d.undo().unwrap(); + let (u, r) = d.history().labels(); + assert_eq!(u, vec!["Eins", "Zwei"]); + // Redo: nächster Schritt zuerst. + assert_eq!(r, vec!["Gruppe", ""]); + d.redo().unwrap(); + assert_eq!(d.history().labels().0.last().unwrap(), "Gruppe"); + } + + #[test] + fn sprung_zu_schritt_n() { + let mut d = doc(); + let mut states = vec![d.to_json()]; + for (i, v) in ["A", "B", "C", "D"].iter().enumerate() { + set_name(&mut d, v, "x", None, i as f64 * 1000.0); + states.push(d.to_json()); + } + assert_eq!(d.history().undo_depth(), 4); + let ops1 = d.history_jump(1).unwrap(); + assert_eq!(d.to_json(), states[1]); + assert_eq!((d.history().undo_depth(), d.history().redo_depth()), (1, 3)); + assert_eq!(d.last_hits().len(), ops1.len()); + d.history_jump(4).unwrap(); + assert_eq!(d.to_json(), states[4]); + d.history_jump(0).unwrap(); + assert_eq!(d.to_json(), states[0]); + assert!(d.history_jump(0).is_none(), "schon dort"); + assert!(d.history_jump(9).is_none(), "ausserhalb"); + assert_eq!(d.to_json(), states[0]); + d.history_jump(2).unwrap(); + assert_eq!(d.to_json(), states[2]); + } + #[test] fn coalesce_key_ein_schritt_und_verdichtet() { let mut d = doc(); diff --git a/src-tauri/core/src/ops.rs b/src-tauri/core/src/ops.rs index 4b29948e..b3db664d 100644 --- a/src-tauri/core/src/ops.rs +++ b/src-tauri/core/src/ops.rs @@ -292,13 +292,20 @@ pub fn validate_project(root: &Map) -> Vec { #[derive(Clone, Debug, Default)] pub struct Step { pub ops: Vec, + /// Kurze Beschriftung für die Verlaufsliste (i18n-Schlüssel oder Text; leer = Standard der UI). + pub label: String, bytes: usize, } impl Step { pub fn new(ops: Vec) -> Step { let bytes = ops_bytes(&ops); - Step { ops, bytes } + Step { ops, label: String::new(), bytes } + } + pub fn labeled(mut self, label: String) -> Step { + self.bytes += label.len(); + self.label = label; + self } } @@ -383,6 +390,8 @@ pub struct History { group_at: f64, /// Die offene Gruppe hat etwas aufgezeichnet. group_recorded: bool, + /// Beschriftung für den nächsten neu angelegten Schritt ([`History::set_label`]). + pending_label: String, bytes: usize, pub max_steps: usize, pub max_bytes: usize, @@ -400,6 +409,7 @@ impl Default for History { group_key: None, group_at: 0.0, group_recorded: false, + pending_label: String::new(), bytes: 0, max_steps: 100, max_bytes: 256 << 20, @@ -419,7 +429,23 @@ impl History { self.bytes } + /// Beschriftung des Schritts, den die nächste aufgezeichnete Änderung neu anlegt (Koaleszenz + /// und Gruppen-Folgeänderungen behalten die des ersten). Wird von `record` verbraucht; leer = keine. + pub fn set_label(&mut self, label: &str) { + self.pending_label.clear(); + self.pending_label.extend(label.chars().take(120)); + } + + /// Beschriftungen `(Undo: ältester zuerst, Redo: nächster zuerst)`. + pub fn labels(&self) -> (Vec, Vec) { + ( + self.undo.iter().map(|s| s.label.clone()).collect(), + self.redo.iter().rev().map(|s| s.label.clone()).collect(), + ) + } + pub fn clear(&mut self) { + self.pending_label.clear(); self.undo.clear(); self.redo.clear(); self.bytes = 0; @@ -474,17 +500,18 @@ impl History { if self.group_depth > 0 { self.group_recorded = true; } + let label = std::mem::take(&mut self.pending_label); let merge = if self.group_depth > 0 { std::mem::replace(&mut self.group_started, true) } else { coalesced }; match self.undo.back_mut().filter(|_| merge) { Some(top) => { self.bytes -= top.bytes; let mut inv = inverse; inv.append(&mut top.ops); - *top = Step::new(compact(inv)); + *top = Step::new(compact(inv)).labeled(std::mem::take(&mut top.label)); self.bytes += top.bytes; } None => { - let s = Step::new(inverse); + let s = Step::new(inverse).labeled(label); self.bytes += s.bytes; self.undo.push_back(s); } diff --git a/src-tauri/core/src/web/document.rs b/src-tauri/core/src/web/document.rs index bec26de9..60f866eb 100644 --- a/src-tauri/core/src/web/document.rs +++ b/src-tauri/core/src/web/document.rs @@ -128,6 +128,29 @@ pub fn doc_history_state(h: u32) -> Vec { .unwrap_or_default() } +/// Beschriftung für den nächsten Undo-Schritt (leer = keine); wird beim nächsten Aufzeichnen verbraucht. +#[wasm_bindgen] +pub fn doc_history_label(h: u32, label: &str) { + with_doc(h, |d| d.history_mut().set_label(label)); +} + +/// Verlaufsliste als JSON `{"undo":[…ältester zuerst],"redo":[…nächster zuerst]}` (Beschriftungen). +#[wasm_bindgen] +pub fn doc_history_labels(h: u32) -> String { + with_doc(h, |d| { + let (undo, redo) = d.history().labels(); + serde_json::json!({ "undo": undo, "redo": redo }).to_string() + }) + .unwrap_or_default() +} + +/// Springt auf Undo-Tiefe `target` (mehrere Schritte in einem Aufruf): alle angewendeten Ops als +/// JSON-Array (für die TS-Leseansicht, `doc_last_hits` passend dazu), leer = nichts. +#[wasm_bindgen] +pub fn doc_history_jump(h: u32, target: u32) -> String { + with_doc(h, |d| d.history_jump(target as usize).map(|ops| ops_to_json(&ops))).flatten().unwrap_or_default() +} + /// Verlauf leeren (z. B. nach einer Änderung am Projekt vorbei an den Ops). #[wasm_bindgen] pub fn doc_history_clear(h: u32) { diff --git a/src/App.tsx b/src/App.tsx index bce2f618..b5a9d931 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1678,7 +1678,7 @@ export default function App() { .arrayBuffer() .then((buf) => readIfcFlat(new Uint8Array(buf), elements)) .then((flat) => { - const r = getState().commitImport((doc, base, now) => doc.importIfc(base, flat, { fileName: f.name, elements }, now)); + const r = getState().commitImport((doc, base, now) => doc.importIfc(base, flat, { fileName: f.name, elements }, now), "history.import.ifc"); if (!r) return; const report = r.report; if (elements && r.summary) { @@ -3302,7 +3302,7 @@ export default function App() { notify={notify} onImport={(read, fileName, placement) => { // Der Kern macht die Kontext-Meshes und übernimmt sie als EINEN Undo-Schritt ([K4] S4). - const r = getState().commitImport((doc, base, now) => doc.importMesh(base, read.flat, { fileName, placement }, now)); + const r = getState().commitImport((doc, base, now) => doc.importMesh(base, read.flat, { fileName, placement }, now), "history.import.mesh"); if (!r) return; fitToContextObjects(addedItems(r.ops, "context") as ContextObject[]); notify(formatMeshReport(read.report, t), r.contextObjects === 0 || read.report.truncated ? "warning" : "info"); @@ -3416,6 +3416,7 @@ export default function App() { onToggleResources={() => toggleResources()} onOpenSettings={() => openSettings()} onOpenBcf={() => setLayout((l) => revealPanel(l, "bcf"))} + onOpenHistory={() => setLayout((l) => revealPanel(l, "history"))} /> ) } diff --git a/src/core/document.ts b/src/core/document.ts index c6706361..66a5320b 100644 --- a/src/core/document.ts +++ b/src/core/document.ts @@ -441,6 +441,30 @@ export class ProjectDocument { return project; } + /** Springt im Verlauf auf Undo-Tiefe `target` (mehrere Schritte, ein Kern-Aufruf); `null` = schon dort/ausserhalb. */ + jumpTo(base: Project, target: number): Project | null { + if (base !== this.mirror || !this.handle) { + this.ensure(base); + return null; + } + const json = core().doc_history_jump(this.handle, target); + if (!json) return null; + const project = applyOps(base, JSON.parse(json) as CoreOp[], core().doc_last_hits(this.handle)); + this.mirror = project; + return project; + } + + /** Beschriftung (i18n-Schlüssel oder Text) für den nächsten neu angelegten Undo-Schritt; leer = keine. */ + setHistoryLabel(label: string): void { + if (this.handle) core().doc_history_label(this.handle, label); + } + + /** Beschriftungen der Verlaufsschritte: Undo (ältester zuerst) und Redo (nächster zuerst). */ + historyLabels(): { undo: string[]; redo: string[] } { + const json = this.handle ? core().doc_history_labels(this.handle) : ""; + return json ? (JSON.parse(json) as { undo: string[]; redo: string[] }) : { undo: [], redo: [] }; + } + /** Verlaufsstand: Undo-/Redo-Tiefe und geschätzter Speicher (Bytes). */ historyState(): { undo: number; redo: number; bytes: number } { const s = this.handle ? core().doc_history_state(this.handle) : new Float64Array(0); diff --git a/src/i18n/de.ts b/src/i18n/de.ts index 8a69b6ef..427278b1 100644 --- a/src/i18n/de.ts +++ b/src/i18n/de.ts @@ -2553,6 +2553,102 @@ export const de = { "bcf.addViewpoint": "Ansicht aufnehmen", "bcf.addViewpoint.hint": "Hängt die aktuelle 3D-Kamera mit Bild und der Auswahl als Viewpoint an das Thema.", "bcf.noSnapshot": "Kein Bild aufgenommen (3D-Bild nicht lesbar); die Kamera ist trotzdem gespeichert.", + "nav.history": "Verlauf", + "history.empty": "Noch keine Änderungen.", + "history.current": "Aktueller Stand", + "history.start": "Ausgangsstand", + "history.step.generic": "Änderung", + "history.grip": "Griff ziehen", + "history.import": "Import", + "history.import.ifc": "Import IFC", + "history.import.mesh": "Import 3D-Modell", + "history.import.drawing": "Import Zeichnung", + "history.op.add": "{what} hinzufügen", + "history.op.replace": "{what} ändern", + "history.op.remove": "{what} löschen", + "history.op.reorder": "{what} umordnen", + "history.op.setField": "{what} ändern", + "history.cmd.arc": "Bogen", + "history.cmd.autodim": "Automassketten", + "history.cmd.bezier": "Bézierkurve", + "history.cmd.block": "Block einfügen", + "history.cmd.break": "Auftrennen", + "history.cmd.ceiling": "Decke zeichnen", + "history.cmd.ceilingOpening": "Deckenöffnung", + "history.cmd.chamfer": "Fase", + "history.cmd.circle": "Kreis zeichnen", + "history.cmd.column": "Stütze zeichnen", + "history.cmd.defblock": "Block definieren", + "history.cmd.detailref": "Detailverweis", + "history.cmd.dimension": "Bemassung", + "history.cmd.ellipse": "Ellipse zeichnen", + "history.cmd.explode": "Auflösen", + "history.cmd.extend": "Verlängern", + "history.cmd.extrude": "Extrusion", + "history.cmd.fillet": "Verrundung", + "history.cmd.join": "Verbinden", + "history.cmd.kote": "Höhenkote", + "history.cmd.leader": "Beschriftungspfeil", + "history.cmd.line": "Linie zeichnen", + "history.cmd.multiline": "Mehrfachlinie", + "history.cmd.offset": "Versatz", + "history.cmd.opening": "Öffnung setzen", + "history.cmd.pointmarker": "Punktmarke", + "history.cmd.polygon": "Polygon zeichnen", + "history.cmd.polyline": "Polylinie zeichnen", + "history.cmd.ray": "Strahl", + "history.cmd.rect": "Rechteck zeichnen", + "history.cmd.rect4": "Rechteck zeichnen", + "history.cmd.revcloud": "Revisionswolke", + "history.cmd.roof": "Dach zeichnen", + "history.cmd.roofHole": "Dachöffnung", + "history.cmd.room": "Raum zeichnen", + "history.cmd.roomInside": "Raum aus Umriss", + "history.cmd.scalebar": "Massstabsbalken", + "history.cmd.sectionline": "Schnittlinie", + "history.cmd.solid": "Körper", + "history.cmd.solidOutline": "Körper aus Umriss", + "history.cmd.solidbool": "Körper-Boolesche", + "history.cmd.spline": "Spline zeichnen", + "history.cmd.stair": "Treppe zeichnen", + "history.cmd.terrain": "Gelände", + "history.cmd.text": "Text setzen", + "history.cmd.textbox": "Textfeld", + "history.cmd.textpath": "Text auf Pfad", + "history.cmd.transform": "Transformieren", + "history.cmd.trim": "Stutzen", + "history.cmd.voidbox": "Aussparung", + "history.cmd.wall": "Wand zeichnen", + "history.cmd.wipeout": "Abdeckfläche", + "history.cmd.xline": "Hilfslinie", + "history.cmd.align": "Ausrichten", + "history.cmd.distribute": "Verteilen", + "history.cmd.paste": "Einfügen", + "history.cmd.split": "Teilen", + "history.coll.walls": "Wand", + "history.coll.ceilings": "Decke", + "history.coll.roofs": "Dach", + "history.coll.openings": "Öffnung", + "history.coll.stairs": "Treppe", + "history.coll.rooms": "Raum", + "history.coll.drawings2d": "2D-Element", + "history.coll.columns": "Stütze", + "history.coll.extrudedSolids": "Körper", + "history.coll.groups": "Gruppe", + "history.coll.layers": "Ebene", + "history.coll.drawingLevels": "Geschoss", + "history.coll.pens": "Stift", + "history.coll.hatches": "Schraffur", + "history.coll.lineStyles": "Linienstil", + "history.coll.textStyles": "Textstil", + "history.coll.components": "Bauteilaufbau", + "history.coll.wallTypes": "Wandtyp", + "history.coll.layouts": "Layout", + "history.coll.viewSnapshots": "Ausschnitt", + "history.coll.context": "Kontext", + "history.coll.penSets": "Stiftsatz", + "history.coll.customPalettes": "Palette", + "history.coll.blockDefs": "Blockdefinition", } as const; export type TranslationKey = keyof typeof de; diff --git a/src/i18n/en.ts b/src/i18n/en.ts index d309481b..4229b486 100644 --- a/src/i18n/en.ts +++ b/src/i18n/en.ts @@ -2539,4 +2539,100 @@ export const en: Record = { "bcf.addViewpoint": "Capture view", "bcf.addViewpoint.hint": "Attaches the current 3D camera with image and selection to the topic as a viewpoint.", "bcf.noSnapshot": "No image captured (3D image not readable); the camera is saved anyway.", + "nav.history": "History", + "history.empty": "No changes yet.", + "history.current": "Current state", + "history.start": "Initial state", + "history.step.generic": "Change", + "history.grip": "Drag handle", + "history.import": "Import", + "history.import.ifc": "Import IFC", + "history.import.mesh": "Import 3D model", + "history.import.drawing": "Import drawing", + "history.op.add": "Add {what}", + "history.op.replace": "Change {what}", + "history.op.remove": "Delete {what}", + "history.op.reorder": "Reorder {what}", + "history.op.setField": "Change {what}", + "history.cmd.arc": "Arc", + "history.cmd.autodim": "Auto dimensions", + "history.cmd.bezier": "Bezier curve", + "history.cmd.block": "Insert block", + "history.cmd.break": "Break", + "history.cmd.ceiling": "Draw ceiling", + "history.cmd.ceilingOpening": "Ceiling opening", + "history.cmd.chamfer": "Chamfer", + "history.cmd.circle": "Draw circle", + "history.cmd.column": "Draw column", + "history.cmd.defblock": "Define block", + "history.cmd.detailref": "Detail reference", + "history.cmd.dimension": "Dimension", + "history.cmd.ellipse": "Draw ellipse", + "history.cmd.explode": "Explode", + "history.cmd.extend": "Extend", + "history.cmd.extrude": "Extrude", + "history.cmd.fillet": "Fillet", + "history.cmd.join": "Join", + "history.cmd.kote": "Level mark", + "history.cmd.leader": "Leader", + "history.cmd.line": "Draw line", + "history.cmd.multiline": "Multiline", + "history.cmd.offset": "Offset", + "history.cmd.opening": "Place opening", + "history.cmd.pointmarker": "Point marker", + "history.cmd.polygon": "Draw polygon", + "history.cmd.polyline": "Draw polyline", + "history.cmd.ray": "Ray", + "history.cmd.rect": "Draw rectangle", + "history.cmd.rect4": "Draw rectangle", + "history.cmd.revcloud": "Revision cloud", + "history.cmd.roof": "Draw roof", + "history.cmd.roofHole": "Roof opening", + "history.cmd.room": "Draw room", + "history.cmd.roomInside": "Room from outline", + "history.cmd.scalebar": "Scale bar", + "history.cmd.sectionline": "Section line", + "history.cmd.solid": "Solid", + "history.cmd.solidOutline": "Solid from outline", + "history.cmd.solidbool": "Solid boolean", + "history.cmd.spline": "Draw spline", + "history.cmd.stair": "Draw stair", + "history.cmd.terrain": "Terrain", + "history.cmd.text": "Place text", + "history.cmd.textbox": "Text box", + "history.cmd.textpath": "Text on path", + "history.cmd.transform": "Transform", + "history.cmd.trim": "Trim", + "history.cmd.voidbox": "Void box", + "history.cmd.wall": "Draw wall", + "history.cmd.wipeout": "Wipeout", + "history.cmd.xline": "Construction line", + "history.cmd.align": "Align", + "history.cmd.distribute": "Distribute", + "history.cmd.paste": "Paste", + "history.cmd.split": "Split", + "history.coll.walls": "wall", + "history.coll.ceilings": "ceiling", + "history.coll.roofs": "roof", + "history.coll.openings": "opening", + "history.coll.stairs": "stair", + "history.coll.rooms": "room", + "history.coll.drawings2d": "2D element", + "history.coll.columns": "column", + "history.coll.extrudedSolids": "solid", + "history.coll.groups": "group", + "history.coll.layers": "layer", + "history.coll.drawingLevels": "level", + "history.coll.pens": "pen", + "history.coll.hatches": "hatch", + "history.coll.lineStyles": "line style", + "history.coll.textStyles": "text style", + "history.coll.components": "component", + "history.coll.wallTypes": "wall type", + "history.coll.layouts": "layout", + "history.coll.viewSnapshots": "view snapshot", + "history.coll.context": "context", + "history.coll.penSets": "pen set", + "history.coll.customPalettes": "palette", + "history.coll.blockDefs": "block definition", }; diff --git a/src/panels/HistoryPanel.tsx b/src/panels/HistoryPanel.tsx new file mode 100644 index 00000000..4d25fb06 --- /dev/null +++ b/src/panels/HistoryPanel.tsx @@ -0,0 +1,68 @@ +// Dock-Panel „Verlauf" ([84]): die Undo-Schritte als Liste, jüngster oben, der aktuelle Stand +// markiert, Wiederholen-Schritte (noch nicht gültig) gedimmt darüber. Klick auf einen Eintrag springt +// dorthin (`jumpHistory`: ein Kern-Aufruf über mehrere Schritte). Die Beschriftungen liefert der Kern +// (`historyEntries`), Anzeigetext über `historyLabelText`. +// +// Bezeichner englisch, UI-Text/Kommentare deutsch (CONVENTIONS.md). + +import { useMemo } from "react"; +import { t } from "../i18n"; +import { useStore } from "../state/appStore"; +import { historyLabelText } from "../state/historyLabels"; + +interface Entry { + /** Undo-Tiefe, auf die ein Klick springt (0 = Ausgangsstand). */ + depth: number; + text: string; + future: boolean; +} + +export function HistoryPanel() { + const undoDepth = useStore((s) => s.undoDepth); + const redoDepth = useStore((s) => s.redoDepth); + const project = useStore((s) => s.project); + const historyEntries = useStore((s) => s.historyEntries); + const jumpHistory = useStore((s) => s.jumpHistory); + + const entries = useMemo(() => { + const { undo, redo } = historyEntries(); + const list: Entry[] = [{ depth: 0, text: t("history.start"), future: false }]; + undo.forEach((l, i) => list.push({ depth: i + 1, text: historyLabelText(l), future: false })); + redo.forEach((l, i) => list.push({ depth: undo.length + i + 1, text: historyLabelText(l), future: true })); + return list.reverse(); + // `project` ändert sich mit jedem Schritt; die Tiefen fangen Sprünge ab. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [historyEntries, undoDepth, redoDepth, project]); + + if (undoDepth + redoDepth === 0) { + return ( +
+
{t("history.empty")}
+
+ ); + } + return ( +
+
    + {entries.map((e) => { + const current = e.depth === undoDepth; + return ( +
  • jumpHistory(e.depth)} + > + {e.text} + {current && } +
  • + ); + })} +
+
+ ); +} diff --git a/src/panels/PanelIcons.tsx b/src/panels/PanelIcons.tsx index c0b22d73..93d26a3d 100644 --- a/src/panels/PanelIcons.tsx +++ b/src/panels/PanelIcons.tsx @@ -98,6 +98,17 @@ export function RoomBalanceTabIcon() { ); } +/** Verlauf — Uhr mit Rückwärtspfeil. */ +export function HistoryTabIcon() { + return ( + + + + + + ); +} + /** BCF-Themen — Sprechblase mit Haken (Koordinations-Thema). */ export function BcfTabIcon() { return ( diff --git a/src/panels/builtinPanels.tsx b/src/panels/builtinPanels.tsx index 12b7fa6c..ee6d3218 100644 --- a/src/panels/builtinPanels.tsx +++ b/src/panels/builtinPanels.tsx @@ -26,6 +26,7 @@ import { ElementTreePanel, ElementsTabIcon } from "./ElementTreePanel"; import { ViewSnapshotsPanel, ViewSnapshotsTabIcon } from "./ViewSnapshotsPanel"; import { LayoutsPanel, LayoutsTabIcon } from "./LayoutsPanel"; import { BcfPanel } from "./BcfPanel"; +import { HistoryPanel } from "./HistoryPanel"; import { ToolsTabIcon, AttributesTabIcon, @@ -35,6 +36,7 @@ import { SiteTabIcon, RoomBalanceTabIcon, BcfTabIcon, + HistoryTabIcon, } from "./PanelIcons"; /** IDs der eingebauten Dock-Panels (auch für defaultLayout/Filter nutzbar). */ @@ -50,6 +52,7 @@ export const BUILTIN_PANEL_IDS = { viewSnapshots: "view-snapshots", layouts: "layouts", bcf: "bcf", + history: "history", } as const; // Werkzeug-Palette (Symbol + Name je Werkzeug, ArchiCAD/Vectorworks-Stil). @@ -158,3 +161,13 @@ registerPanel({ hasDisplayMode: false, render: () => , }); + +// Verlauf ([84]) — Undo-Schritte als Liste, Klick springt zum Schritt. Nicht im Standard-Layout, +// erreichbar über „Bearbeiten > Verlauf" bzw. „Fenster > Panels". +registerPanel({ + id: BUILTIN_PANEL_IDS.history, + title: "nav.history", + icon: , + hasDisplayMode: false, + render: () => , +}); diff --git a/src/state/historyLabels.ts b/src/state/historyLabels.ts new file mode 100644 index 00000000..c7297394 --- /dev/null +++ b/src/state/historyLabels.ts @@ -0,0 +1,26 @@ +// Beschriftungen der Undo-Schritte ([84]). Der Kern speichert je Schritt einen kurzen Text: einen +// i18n-Schlüssel (`history.…`, Sprache folgt der Oberfläche), `history.op.:` (aus den Ops +// abgeleitet) oder freien Text; leer = Standard. + +import { t } from "../i18n"; +import type { CoreOp } from "../core/ops"; + +/** Beschriftung aus den Ops (erste Op), wenn der Aufrufer keine setzt: `history.op.:`. */ +export function opsLabel(ops: readonly CoreOp[]): string { + const op = ops[0]; + if (!op) return ""; + return op.kind === "setField" ? `history.op.setField:${op.key}` : `history.op.${op.kind}:${op.collection}`; +} + +/** Anzeigetext eines Schritts in der aktuellen Sprache. */ +export function historyLabelText(label: string): string { + if (!label) return t("history.step.generic"); + if (!label.startsWith("history.")) return label; + const [key, arg] = label.split(":", 2); + if (arg !== undefined) { + const coll = t(`history.coll.${arg}`); + return t(key!, { what: coll === `history.coll.${arg}` ? arg : coll }); + } + const text = t(key!); + return text === key ? t("history.step.generic") : text; +} diff --git a/src/state/historyList.test.ts b/src/state/historyList.test.ts new file mode 100644 index 00000000..0f727afe --- /dev/null +++ b/src/state/historyList.test.ts @@ -0,0 +1,66 @@ +// Verlaufsliste [84]: Beschriftungen der Schritte und Sprung zu einem Schritt über den Store. + +import { describe, it, expect, beforeEach } from "vitest"; +import { getState, setState } from "./appStore"; +import { sampleProject } from "../model/sampleProject"; +import { withHistoryLabel } from "./historySlice"; +import { historyLabelText, opsLabel } from "./historyLabels"; + +beforeEach(() => { + setState({ project: sampleProject, undoDepth: 0, redoDepth: 0, canUndo: false, canRedo: false }); + getState().clearHistory(); +}); + +const egVisible = () => getState().project.drawingLevels.find((l) => l.id === "eg")?.visible; + +describe("Verlaufsliste", () => { + it("Schritte tragen Beschriftungen (explizit, Gruppe)", () => { + getState().toggleLevelVisible("eg"); + withHistoryLabel("Eigenschaft ändern: Dicke", () => getState().toggleLevelVisible("eg")); + getState().groupChanges( + () => { + getState().toggleLevelVisible("eg"); + getState().toggleLevelVisible("eg"); + }, + undefined, + "history.import", + ); + const { undo, redo } = getState().historyEntries(); + expect(undo).toHaveLength(3); + expect(undo[0]).toBe("history.op.replace:drawingLevels"); + expect(undo[1]).toBe("Eigenschaft ändern: Dicke"); + expect(undo[2]).toBe("history.import"); + expect(redo).toEqual([]); + }); + + it("Anzeigetexte: Schlüssel, Ops-Ableitung, freier Text, Standard", () => { + expect(opsLabel([])).toBe(""); + expect(opsLabel([{ kind: "add", collection: "walls", items: [] }])).toBe("history.op.add:walls"); + expect(historyLabelText("Eigenschaft ändern: Dicke")).toBe("Eigenschaft ändern: Dicke"); + expect(historyLabelText("")).toBe("Änderung"); + expect(historyLabelText("history.op.add:walls")).toBe("Wand hinzufügen"); + expect(historyLabelText("history.op.replace:unbekannt")).toBe("unbekannt ändern"); + expect(historyLabelText("history.gibtsnicht")).toBe("Änderung"); + expect(historyLabelText("history.cmd.wall")).toBe("Wand zeichnen"); + }); + + it("jumpHistory springt über mehrere Schritte und zurück", () => { + const start = egVisible(); + for (let i = 0; i < 3; i++) getState().toggleLevelVisible("eg"); + const after3 = egVisible(); + expect(after3).toBe(!start); + getState().jumpHistory(1); + expect(getState().undoDepth).toBe(1); + expect(getState().redoDepth).toBe(2); + expect(egVisible()).toBe(!start); + expect(getState().historyEntries().redo).toHaveLength(2); + getState().jumpHistory(0); + expect(egVisible()).toBe(start); + expect(getState().canUndo).toBe(false); + getState().jumpHistory(3); + expect(egVisible()).toBe(after3); + expect(getState().canRedo).toBe(false); + getState().jumpHistory(99); + expect(getState().undoDepth).toBe(3); + }); +}); diff --git a/src/state/historySlice.ts b/src/state/historySlice.ts index 910d80c1..1f302bda 100644 --- a/src/state/historySlice.ts +++ b/src/state/historySlice.ts @@ -38,7 +38,36 @@ export interface HistorySlice { * Alle Projekt-Änderungen in `fn` werden EIN Undo-Schritt. Mit `coalesceKey` schliessen * aufeinanderfolgende Gruppen mit gleichem Schlüssel (im Zeitfenster) an denselben Schritt an. */ - groupChanges: (fn: () => void, coalesceKey?: string) => void; + groupChanges: (fn: () => void, coalesceKey?: string, label?: string) => void; + /** Beschriftungen der Schritte (Undo: ältester zuerst; Redo: nächster zuerst), für die Verlaufsliste [84]. */ + historyEntries: () => { undo: string[]; redo: string[] }; + /** Springt auf Undo-Tiefe `target` (0 = Anfang), mehrere Schritte in einem Kern-Aufruf. */ + jumpHistory: (target: number) => void; +} + +let activeLabel = ""; + +/** Alle Änderungen in `fn` ohne eigene Beschriftung bekommen `label` (i18n-Schlüssel oder Text) als Schritt-Name. */ +export function withHistoryLabel(label: string, fn: () => T): T { + const prev = activeLabel; + activeLabel = label; + try { + return fn(); + } finally { + activeLabel = prev; + } +} + +/** Führt einen Commit mit Beschriftung aus: die des umgebenden {@link withHistoryLabel}, sonst `fallback`. */ +export function labelCommit(d: ProjectDocument, fallback: string, run: () => T): T { + const label = activeLabel || fallback; + if (!label) return run(); + d.setHistoryLabel(label); + try { + return run(); + } finally { + d.setHistoryLabel(""); + } } let doc: ProjectDocument | null = null; @@ -85,15 +114,23 @@ export function createHistorySlice(api: StoreApi { + groupChanges: (fn, coalesceKey, label) => { const d = storeDocument(get().project); if (coalesceKey) d.beginKeyedGroup(coalesceKey, Date.now()); else d.beginGroup(); try { - fn(); + if (label) withHistoryLabel(label, fn); + else fn(); } finally { d.endGroup(); } }, + historyEntries: () => storeDocument(get().project).historyLabels(), + jumpHistory: (target) => { + const { project } = get(); + const d = storeDocument(project); + const next = d.jumpTo(project, target); + if (next) set({ project: next, ...historyPatch(d) }); + }, }; } diff --git a/src/state/projectSlice.ts b/src/state/projectSlice.ts index 9d011f7c..fd971bc2 100644 --- a/src/state/projectSlice.ts +++ b/src/state/projectSlice.ts @@ -66,8 +66,9 @@ import { DEFAULT_SCALE_DENOMINATOR } from "../model/dimension"; import { DEFAULT_PRESETS, type TextStylePreset } from "../text/richText"; import { t } from "../i18n"; import type { StoreApi } from "./store"; -import { createHistorySlice, historyPatch, storeDocument } from "./historySlice"; +import { createHistorySlice, historyPatch, labelCommit, storeDocument } from "./historySlice"; import type { HistorySlice } from "./historySlice"; +import { opsLabel } from "./historyLabels"; import type { NotifyKind } from "./notifySlice"; /** Felder, die diese Slice in den RootState beisteuert. */ @@ -97,6 +98,7 @@ export interface ProjectSlice { */ commitImport: ( run: (doc: ProjectDocument, base: Project, now: number) => ({ project: Project; ops: CoreOp[] } & R) | { problems: string[] }, + label?: string, ) => ({ ops: CoreOp[] } & R) | null; /** * Ein anderes Projekt übernehmen (Neu, Musterhaus; [K4] S4): lädt es als Ganzes ins Kern-Dokument @@ -485,7 +487,7 @@ export function createProjectSlice( ): Partial => { if (ops.length === 0) return {}; const doc = storeDocument(s.project); - const res = doc.commit(s.project, ops, coalesceKey, Date.now()); + const res = labelCommit(doc, opsLabel(ops), () => doc.commit(s.project, ops, coalesceKey, Date.now())); if ("problems" in res) { const problems = res.problems; console.warn("Projektänderung verworfen:", problems); @@ -509,7 +511,10 @@ export function createProjectSlice( const applyCmd = (req: object, coalesceKey?: string) => set((s) => { const doc = storeDocument(s.project); - const res = doc.commitCmd(s.project, req, coalesceKey, Date.now()); + const cmd = (req as { cmd?: unknown }).cmd; + const res = labelCommit(doc, typeof cmd === "string" ? `history.cmd.${cmd}` : "", () => + doc.commitCmd(s.project, req, coalesceKey, Date.now()), + ); if ("problems" in res) { const problems = res.problems; console.warn("Projektänderung verworfen:", problems); @@ -534,7 +539,7 @@ export function createProjectSlice( let notice: string | undefined; set((s) => { const doc = storeDocument(s.project); - const res = doc.commitGrip(s.project, req, coalesceKey, Date.now()); + const res = labelCommit(doc, "history.grip", () => doc.commitGrip(s.project, req, coalesceKey, Date.now())); if ("problems" in res) { const problems = res.problems; console.warn("Projektänderung verworfen:", problems); @@ -563,11 +568,11 @@ export function createProjectSlice( applyChange, recentOps: () => opLog.slice(), - commitImport: (run) => { + commitImport: (run, label) => { let out: ReturnType | null = null; set((s) => { const doc = storeDocument(s.project); - const res = run(doc, s.project, Date.now()); + const res = labelCommit(doc, label ?? "history.import", () => run(doc, s.project, Date.now())); out = res; if ("problems" in res) { const problems = res.problems; diff --git a/src/state/useProjectFileActions.ts b/src/state/useProjectFileActions.ts index b50ef465..3885a46c 100644 --- a/src/state/useProjectFileActions.ts +++ b/src/state/useProjectFileActions.ts @@ -599,6 +599,7 @@ export function useProjectFileActions( }, now, ), + "history.import.drawing", ); } catch (err) { // Kaputter Puffer o. Ä. (Meldung des Kerns). diff --git a/src/styles.css b/src/styles.css index 00228197..c8a8c32f 100644 --- a/src/styles.css +++ b/src/styles.css @@ -8687,3 +8687,33 @@ body { .rpi-state { font-size: 11px; } + +/* Verlauf-Panel [84]: Zeilen wie .nav-row (eigene Klasse, damit der Element-Baum sie nicht mitzählt). */ +.history-row { + display: flex; + align-items: center; + gap: 6px; + min-height: 26px; + padding: 2px 10px 2px 10px; + border-bottom: 1px solid var(--line); + color: var(--label); + font-size: 12px; + cursor: pointer; + user-select: none; +} +.history-row:hover { + background: var(--panel-2); +} +.history-row.active { + background: var(--active-dim); + border-radius: 999px; + border-bottom-color: transparent; + color: var(--active-light); +} +.history-row.active .nav-label { + font-weight: 600; + color: var(--active-light); +} +.history-row.future { + opacity: 0.45; +} diff --git a/src/ui/AppMenuBar.tsx b/src/ui/AppMenuBar.tsx index 1834b758..329daa3e 100644 --- a/src/ui/AppMenuBar.tsx +++ b/src/ui/AppMenuBar.tsx @@ -51,6 +51,8 @@ export interface AppMenuBarProps { onOpenSettings: () => void; /** BCF-Themen-Panel öffnen (`revealPanel`); ohne diese Funktion entfällt der Menüpunkt. */ onOpenBcf?: () => void; + /** Verlauf-Panel öffnen ([84]). */ + onOpenHistory?: () => void; } /** Menüleiste (Bearbeiten/Ansicht/Fenster) — sitzt in der TopBar neben der Wortmarke. */ @@ -83,6 +85,7 @@ export function AppMenuBar({ onToggleResources, onOpenSettings, onOpenBcf, + onOpenHistory, }: AppMenuBarProps) { const fileItems: DropdownItem[] = [ { label: t("file.new"), onSelect: onNewProject }, @@ -105,6 +108,7 @@ export function AppMenuBar({ const editItems: DropdownItem[] = [ { label: t("menu.edit.undo"), onSelect: onUndo, disabled: !canUndo }, { label: t("menu.edit.redo"), onSelect: onRedo, disabled: !canRedo }, + ...(onOpenHistory ? [{ label: t("nav.history"), onSelect: onOpenHistory }] : []), { divider: true }, { label: t("menu.edit.delete"),