[272] Variantenkombinationen: benannte Kombinationen wie Archicad (Modell, Rangfolge, Panel, Vergleich je Kombination, Blatt-Tabelle, CLI --combination); set_field kennt renovation/designOptionSets
check / check (push) Has been cancelled
check / licenses (push) Has been cancelled
check / e2e (push) Has been cancelled
macos / native (push) Has been cancelled

This commit is contained in:
Claude committed 2026-11-17 14:10:30 +00:00
1 parent 08891e81fb
commit 78791a347a
42 files changed
+1193 -119

No files matched your search

+1 -1
View File
@@ -688,7 +688,7 @@ Kennwort, anonym) als PDF; Austausch mit Fachplanern über DXF/IFC.
Grünfläche nur per Eingabe, Grenzabstand als Verstossfläche statt kleinster Abstand, Fassadenhöhe nur über ±0.00, Mac/Tauri nicht geprüft. · S
UI-Review 14.11.: Flächenbilanz-Panel: Tabellen brechen Text/Köpfe um (Nachweis- und Grundlagen-Tabelle jetzt in 340 px ganz sichtbar, de/en); die breite Flächentabelle (11 Spalten) scrollt nicht mehr: in der schmalen Dock-Spalte (Container ≤ 460 px) wird jede Zeile zur Karte (Geschoss oben, Kennwerte 5 je Zeile mit Kopf über der Zahl; `.area-table.wide`, de/en bei 340 px vollständig lesbar, CSV/PDF unverändert); Fenster-/Türliste (15–20 Spalten) und Raumbuch (12–16) nutzen dasselbe Muster als gemeinsame Komponente `src/panels/CardTable.tsx` (Köpfe per Effekt als `data-label`, lange Textzellen belegen 2–3 Rasterspalten, leere Zellen entfallen; Container-Query ≤ 460 px, sonst normale Tabelle; 14.11. spät, Chromium de/en, 303 px Dock, kein waagrechtes Scrollen mehr; Kosten- und Bauteil-Tabelle (≤ 6 Spalten) scrollten nicht und blieben). Icon-Schrift „settings“ als Text: Schrift ist lokal gebündelt (npm `material-symbols`, `main.tsx`, NOTICE [117]) — Ursache war nur der verlinkte `node_modules` im Worktree (Vite `/@fs` 403), kein App-Fehler. Blatt-Tabelle Baurecht (14.11. spät, als Primitive in Chromium angesehen, nicht in der Blatt-Ansicht der App): Kopf „Reserve (+) / Überschr. (−)“ und „Zulässig“/„Erfüllt“ wurden mit „…“ gekürzt → kurzer Blatt-Kopf „Reserve“, Spaltenbreiten neu (Köpfe passen ab 100 mm Rahmenbreite, Test `baurecht_tabelle_koepfe_passen`); lange Zeilentexte kürzen bei < 150 mm weiterhin mit „…“ (kein Umbruch im Blatt-Tabellenkern).
- ◐ **[272]** Varianten wie Archicad „Design Options“ (17.11., Wunsch Maintainer, für 1.0). **Stand 17.11.:** Modell (Rust, gen:types, KNOWN_KEYS): `Project.designOptionSets` (Sätze, Varianten, Hauptvariante), `designOption: {set, option}` an Wand, Öffnung, Decke, Dach, Treppe, Stütze, Körper, Raum, 2D-Element (samt Bibliotheksobjekt), Kombination `designOptions` an Ebene/Vorlage/Ausschnitt/Layout-Viewport. Sichtbarkeit im EINEN Kern-Ort `renovation::View` (Kombination neben dem Umbaufilter, `doc/ARCHITEKTUR.md` 3.9): Grundriss, Schnitt, Ansicht, Vektor-Axo, 3D-Fenster (Kombination der aktiven Ebene), Kennzahlen, Kosten, Baurecht, Raumbuch, DXF (über den Plan), IFC/Netz-Exporte (Hauptvarianten bzw. JSON-Text), PDF/Blatt (Viewport-Kombination + Titelzusatz). Kern `design_options.rs`: Übernehmen, Satz/Variante löschen, Zuweisen, In Variante kopieren (je ein Undo-Schritt), Zeichen-Variante neuer Elemente, Vergleich (Kreuzprodukt ≤ 24). Oberfläche: Panel „Varianten“ (Kombination, neue Elemente zeichnen in …, Zuweisen/Kopieren, Sätze verwalten, Übernehmen, Vergleich), Chip „Variante: …“ in der Statusleiste (öffnet das Panel, Überlauf „⋯“), Objekt-Info „Variante“, Ressourcen-Tab „Varianten“, Befehle `variante`/`variantekopieren`, Varianten-Vergleich + CSV in der Flächenbilanz, Viewport-Wahl je Satz im Blatt; Vorlage „Beispiel Varianten“ (CLI `:varianten`); CLI `--options`, `designoptions`. Tests: Kern `design_options_tests.rs` (13), Robustheit, vitest `model/designOptions.test.ts`, `commands/cmds/designOption.test.ts`, e2e `designOptions272.spec.ts` (2× grün, Port 5195); Bilder `doc/review-272/`. **Offen:** Blatt-Tabelle (`sheet_table.rs`) für den Vergleich fehlt (nur Panel + CSV); App-IFC-Export und Cycles-Szene nehmen die Hauptvarianten, nicht die Kombination der Ansicht; Variantensatz-Wahl in Ansichtsvorlagen/Ausschnitten nur im Modell (keine Oberfläche ausser Ebene und Viewport); nicht geprüft, ob Wandanschlüsse im Grundriss Wände anderer Varianten noch berücksichtigen (gleicher Weg wie die Regel „Ausblenden“); 3D-Bild und Tauri/Mac nicht geprüft (Prüfschritt `doc/RELEASE-1.0.md` 13.38). · M–L
- ◐ **[272]** Varianten wie Archicad „Design Options“ (17.11., Wunsch Maintainer, für 1.0). **Stand 17.11.:** Modell (Rust, gen:types, KNOWN_KEYS): `Project.designOptionSets` (Sätze, Varianten, Hauptvariante), `designOption: {set, option}` an Wand, Öffnung, Decke, Dach, Treppe, Stütze, Körper, Raum, 2D-Element (samt Bibliotheksobjekt), Kombination `designOptions` an Ebene/Vorlage/Ausschnitt/Layout-Viewport. Sichtbarkeit im EINEN Kern-Ort `renovation::View` (Kombination neben dem Umbaufilter, `doc/ARCHITEKTUR.md` 3.9): Grundriss, Schnitt, Ansicht, Vektor-Axo, 3D-Fenster (Kombination der aktiven Ebene), Kennzahlen, Kosten, Baurecht, Raumbuch, DXF (über den Plan), IFC/Netz-Exporte (Hauptvarianten bzw. JSON-Text), PDF/Blatt (Viewport-Kombination + Titelzusatz). Kern `design_options.rs`: Übernehmen, Satz/Variante löschen, Zuweisen, In Variante kopieren (je ein Undo-Schritt), Zeichen-Variante neuer Elemente, Vergleich (Kreuzprodukt ≤ 24). Oberfläche: Panel „Varianten“ (Kombination, neue Elemente zeichnen in …, Zuweisen/Kopieren, Sätze verwalten, Übernehmen, Vergleich), Chip „Variante: …“ in der Statusleiste (öffnet das Panel, Überlauf „⋯“), Objekt-Info „Variante“, Ressourcen-Tab „Varianten“, Befehle `variante`/`variantekopieren`, Varianten-Vergleich + CSV in der Flächenbilanz, Viewport-Wahl je Satz im Blatt; Vorlage „Beispiel Varianten“ (CLI `:varianten`); CLI `--options`, `designoptions`. Tests: Kern `design_options_tests.rs` (13), Robustheit, vitest `model/designOptions.test.ts`, `commands/cmds/designOption.test.ts`, e2e `designOptions272.spec.ts` (2× grün, Port 5195); Bilder `doc/review-272/`. **Nachtrag 17.11. (benannte Kombinationen wie Archicad):** `Project.designOptionCombinations` (`{id, name, choices}`), `designOptionCombination` (Id) an Ebene/Vorlage/Ausschnitt/Layout-Viewport; Rangfolge in `design_options::stored_choice` (gültiger Verweis gilt vollständig, fehlende Sätze = Hauptvariante, übergeht die freie Wahl desselben Objekts; sonst freie Wahl; zwischen Objekten Ebene < Vorlage < Ausschnitt < Viewport < Anfrage), Sichtbarkeit weiter nur in `renovation::View`. Löschen von Variante/Satz/Übernehmen bereinigt Kombinationen (ein Undo-Schritt), `designOptionCombinationDeleteOps` löscht eine Kombination samt Verweisen. Panel „Varianten“: Bereich „Kombinationen“ (Aktuell/Eigene, „Als Kombination speichern …“, umbenennen, Wahl je Satz, Zuweisen, Löschen mit Rückfrage), Chip zeigt den Namen; Viewport-Feld „Kombination“ (Titelzusatz = Name); Vergleich je gespeicherte Kombination (Name als Zeilentitel, „Alle Kombinationen“ = Kreuzprodukt, CSV) und **Blatt-Tabelle „Variantenvergleich“** (`sheet_table.rs`, Quelle `designOptionCompare`); CLI `--combination "<Name>"`, `designoptions` (`--all`); Beispiel `:varianten` mit „Studie 1 Flachdach/Lochfenster“ und „Studie 2 Satteldach/Bandfenster“. Nebenbei behoben: `Project::set_field` (generated.rs) kannte `renovation` und `designOptionSets` nicht (typisierte Sicht blieb nach einer Op auf diese Felder alt) — jetzt samt Kombinationen, Test `set_field_kennt_alle_wurzelfelder`. Tests: Kern `design_options_tests.rs` (+8), `sheet_table.rs` (+1), vitest `model/designOptions.test.ts`, e2e `designOptions272.spec.ts` (3 Tests, 2× grün, Port 5194), Bild `doc/review-272/04-kombinationen.png`. **Offen:** Blatt-Tabelle ohne Umbau-Zustand/Kombination der Ansicht (zeigt immer die gespeicherten Kombinationen); Ausschnitt/Vorlage nur im Modell (keine Oberfläche ausser Ebene und Viewport); App-IFC-Export und Cycles-Szene nehmen die Hauptvarianten, nicht die Kombination der Ansicht; Variantensatz-Wahl in Ansichtsvorlagen/Ausschnitten nur im Modell (keine Oberfläche ausser Ebene und Viewport); nicht geprüft, ob Wandanschlüsse im Grundriss Wände anderer Varianten noch berücksichtigen (gleicher Weg wie die Regel „Ausblenden“); 3D-Bild und Tauri/Mac nicht geprüft (Prüfschritt `doc/RELEASE-1.0.md` 13.38). · M–L
### Phase 4 (4.–12.12.): Härten und veröffentlichen
- Nur noch Fehler aus dem Referenz-Ablauf; Leistung mit grossen Kontext-Importen; keine neuen Funktionen.
- Release 1.0.0: Tag, signierte Pakete, Release-Notes (ehrlich: was nicht geht), Download-Seite.
+9
View File
@@ -495,6 +495,15 @@ Raumbuch/IFC/Netz-Exporte (`queries.rs::options_state`: Kombination des JSON-Tex
Vergleich `designOptionCompare` (Kreuzprodukt, höchstens 24 Kombinationen). Oberfläche: Panel „Varianten“ (`panels/DesignOptionsPanel.tsx`),
Chip in der Statusleiste, Objekt-Info `DesignOptionField`, Ressourcen-Tab, Befehle `variante`/`variantekopieren`; CLI `--options`.
**Benannte Kombinationen** (Nachtrag): `Project.designOptionCombinations` (`{id, name, choices: Satz-Id → Varianten-Id}`); Ebene, Vorlage,
Ausschnitt und Viewport tragen zusätzlich `designOptionCombination` (Id). Rangfolge in `design_options::stored_choice`: gültiger Verweis
gilt vollständig (fehlende Sätze ⇒ Hauptvariante) und übergeht die freie Wahl `designOptions` desselben Objekts; sonst die freie Wahl.
Zwischen den Objekten wie vorher (Hauptvarianten < Ebene < Vorlage < Ausschnitt < Viewport < Anfrage). Sichtbarkeit weiter nur in
`renovation::View`. Löschen von Variante/Satz/„Übernehmen“ bereinigt Kombinationen (`clear_choices`), `designOptionCombinationDeleteOps`
löscht eine Kombination samt Verweisen — je ein Undo-Schritt. Vergleich `design_options::compare` (je gespeicherte Kombination, sonst
Kreuzprodukt; `compare_scope(.., all)`), Blatt-Tabelle `sheet_table.rs` Quelle `designOptionCompare`; TS: `model/designOptions.ts`
(`storedChoice`, `assignCombinationOps` …), Panel `DesignOptionsPanel.tsx`; CLI `--combination`.
---
## 4. Schnitt
+12 -2
View File
@@ -393,10 +393,20 @@ Flachdach/Satteldach und Fassade: Lochfenster/Bandfenster).
Oder die Befehle `variante` und `variantekopieren` (Ziel z. B. Dachform=B, Variantenname oder Nummer; H = Hauptmodell).
- **Übernehmen:** „Übernehmen“ bei einer Variante legt ihre Elemente ins Hauptmodell und löscht die übrigen Varianten des Satzes
samt Elementen (ein Undo-Schritt). Der Papierkorb löscht eine Variante bzw. einen Satz samt Elementen.
- **Kombinationen (wie in Archicad):** Eine Kombination hat einen Namen und speichert je Satz genau eine Variante (z. B.
Studie 2 Satteldach/Bandfenster). Im Panel „Varianten“ zeigt „Aktuell“ die Kombination der Ansicht; eine Wahl, die zu keiner
gespeicherten Kombination passt, heisst „Eigene“ und lässt sich mit „Als Kombination speichern …“ unter einem Namen sichern.
Je Kombination lässt sich die Wahl je Satz ändern, „Dieser Ansicht zuweisen“ setzt sie auf die aktive Ansicht, das Kreuz löscht sie
(nach Rückfrage; die Varianten bleiben). Ein Viewport auf dem Blatt wählt eine Kombination im Feld „Kombination“ und trägt
ihren Namen als Titelzusatz. Sätze, die eine Kombination nicht nennt, zeigen die Hauptvariante; wer eine Variante oder einen
Satz löscht, bereinigt die Kombinationen im selben Undo-Schritt. Der Chip in der Statusleiste nennt den Kombinationsnamen.
- **Vergleich:** Panel Flächenbilanz (oder „Vergleich öffnen“ im Panel „Varianten“): der „Varianten-Vergleich“ zeigt GF, HNF,
GV, Fussabdruck, AZ, ÜZ und Kosten je Kombination nebeneinander, mit „Vergleich als CSV“.
GV, Fussabdruck, AZ, ÜZ und Kosten je gespeicherte Kombination nebeneinander (Name als Zeilentitel; „Alle Kombinationen der Sätze
zeigen“ rechnet das ganze Kreuzprodukt), mit „Vergleich als CSV“. Dieselbe Tabelle gibt es als Blatt-Tabelle „Variantenvergleich“
(Layout, Tabelle hinzufügen).
- **Exporte:** DXF, IFC, PDF und Kennzahlen nehmen die Kombination der Ansicht bzw. die Hauptvarianten. Kommandozeile:
--options "Dachform=B,Fassade=A" bei allen Ausgaben, dossier-cli … designoptions für den Vergleich (--format csv).
--options "Dachform=B,Fassade=A" oder --combination "Studie 1 …" (gespeicherte Kombination) bei allen Ausgaben,
dossier-cli … designoptions für den Vergleich der gespeicherten Kombinationen (--format csv, --all für alle).
---
+4 -1
View File
@@ -97,7 +97,10 @@ in `doc/KURZANLEITUNG.md`):
neue Elemente zeichnen in …, Zuweisen, Kopieren in …, Übernehmen), Objekt-Info „Variante“, Befehle `variante`/`variantekopieren`,
Varianten-Vergleich (GF, HNF, GV, AZ, ÜZ, Kosten je Kombination, CSV) in der Flächenbilanz; ein Viewport kann dieselbe Ansicht in
anderer Kombination zeigen (Titelzusatz mit Variantenname). CLI `--options "Dachform=B"`, Vergleich `designoptions`. Beispiel:
*Datei → Neu aus Vorlage: Beispiel Varianten*.
*Datei → Neu aus Vorlage: Beispiel Varianten*. **Benannte Kombinationen (wie Archicad „Design Option Combinations“):** Wahl je Satz
unter einem Namen speichern („Studie 1: Satteldach + Bandfenster“), einer Ansicht oder einem Viewport zuweisen (Zustand „Aktuell“ /
„Eigene“, Name im Chip der Statusleiste und als Titelzusatz im Blatt), Löschen bereinigt Verweise; Varianten-Vergleich je gespeicherter
Kombination (CSV, Blatt-Tabelle „Variantenvergleich“); CLI `--combination "Name"`.
**Erker und Wiederanlauf (15.11.).** Fenster in Bogenwänden (Erker) sitzen in Schnitt und Ansicht wie im 3D und im Grundriss auf der Sehne; die Sehnen-Zonen
gelten über alle Geschosse, der Deckenrand folgt der Sehne ([216]). Raumstempel rücken in Lücken zwischen den Linien, bevor sie schrumpfen; die Baulinie setzt vor
Binary file not shown.

After

Width:  |  Height:  |  Size: 157 KiB

+110 -4
View File
@@ -1,7 +1,8 @@
// [272] Varianten: Beispiel Varianten öffnen, Panel „Varianten“ über den Chip der Statusleiste, Satz anlegen, Auswahl einer
// Variante zuweisen (Undo), Kombination der Ansicht umschalten (Grundriss zeigt das Bandfenster statt des Lochfensters),
// Vergleichstabelle, Variante übernehmen und Undo. Geprüft über die UI und den Plan (Test-Nähte), nicht über Pixel.
import { blurFocus, discardIfAsked, expect, fileMenu, test } from "./app";
import type { Page } from "@playwright/test";
import { blurFocus, discardIfAsked, expect, fileMenu, openTab, test } from "./app";
test("Varianten: Satz, Zuweisen, Kombination, Vergleich, Übernehmen, Undo ([272])", async ({ page }) => {
await page.goto("/?dossierTest");
@@ -18,7 +19,8 @@ test("Varianten: Satz, Zuweisen, Kombination, Vergleich, Übernehmen, Undo ([272
// Chip der Statusleiste öffnet das Panel.
const chip = page.getByTestId("design-option-toggle");
await expect(chip).toContainText("Hauptvarianten");
// Die Hauptvarianten entsprechen der gespeicherten Kombination „Studie 1“: ihr Name steht im Chip.
await expect(chip).toContainText("Studie 1 Flachdach/Lochfenster");
await chip.click();
const panel = page.getByTestId("design-options-panel");
await expect(panel).toBeVisible();
@@ -44,10 +46,13 @@ test("Varianten: Satz, Zuweisen, Kombination, Vergleich, Übernehmen, Undo ([272
expect(await openings()).not.toContain("O2");
await expect(chip).toContainText("Fassade B Bandfenster");
// Vergleich: vier Kombinationen, Hauptkombination zuerst.
// Vergleich: je gespeicherte Kombination eine Zeile (Name als Titel), „alle“ zeigt das Kreuzprodukt (2 × 2 × 2).
await panel.getByTestId("design-option-compare-open").click();
const rows = panel.getByTestId("design-option-compare-row");
await expect(rows).toHaveCount(4);
await expect(rows).toHaveCount(2);
await expect(rows.first()).toContainText("Studie 1 Flachdach/Lochfenster");
await panel.getByTestId("design-option-compare-all").check();
await expect(rows).toHaveCount(8);
await expect(rows.first()).toContainText("Dachform A Flachdach, Fassade A Lochfenster");
await page.screenshot({ path: "test-results/designOptions272-panel.png" });
await rows.last().scrollIntoViewIfNeeded();
@@ -63,3 +68,104 @@ test("Varianten: Satz, Zuweisen, Kombination, Vergleich, Übernehmen, Undo ([272
await expect.poll(async () => (await dopt()).sets).toEqual(["dachform", "fassade", "satz-3"]);
expect((await dopt()).elements.RF1).toBe("dachform/b");
});
test("Variantenkombinationen: speichern, zuweisen, umschalten, Vergleich, Löschen, Undo ([272])", async ({ page }) => {
await page.goto("/?dossierTest");
await page.getByRole("button", { name: /Neues Projekt/ }).first().click();
await expect(page.getByRole("group", { name: "Befehlszeile" })).toBeVisible();
await fileMenu(page, /^Neu aus Vorlage: Beispiel Varianten$/);
await discardIfAsked(page);
await expect(page.locator(".project-name")).toHaveText("Beispiel Varianten");
const dopt = () => page.evaluate(() => window.__dossierTest!.designOptions());
const openings = () => page.evaluate(() => window.__dossierTest!.planOpeningIds());
const chip = page.getByTestId("design-option-toggle");
await chip.click();
const panel = page.getByTestId("design-options-panel");
await expect(panel).toBeVisible();
await expect(panel.getByTestId("design-option-combination")).toHaveCount(2);
await expect(panel.getByTestId("design-option-current-name")).toHaveText("Studie 1 Flachdach/Lochfenster");
// Eine Wahl, die zu keiner Kombination passt, heisst „Eigene“ und wird unter neuem Namen gespeichert.
await panel.getByTestId("design-option-combo-dachform").selectOption("b");
await expect(panel.getByTestId("design-option-current-name")).toHaveText("Eigene");
await expect(chip).toContainText("Eigene");
await panel.getByTestId("design-option-combo-save").click();
const dialog = page.getByRole("dialog", { name: /Als Kombination speichern/ });
await dialog.getByLabel("Name der Kombination").fill("Studie 3 Satteldach/Lochfenster");
await dialog.getByRole("button", { name: "Exportieren" }).click();
await expect.poll(async () => (await dopt()).combinations).toEqual(["Studie 1 Flachdach/Lochfenster", "Studie 2 Satteldach/Bandfenster", "Studie 3 Satteldach/Lochfenster"]);
await expect(panel.getByTestId("design-option-current-name")).toHaveText("Studie 3 Satteldach/Lochfenster");
// Zuweisen: Studie 2 ⇒ Bandfenster; Chip nennt den Namen; Studie 1 ⇒ wieder das Lochfenster.
const comb = (n: number) => panel.getByTestId("design-option-combination").nth(n);
await comb(1).getByTestId("design-option-combination-assign").click();
await expect.poll(async () => (await dopt()).combination).toBe("studie-2");
await expect.poll(openings).toContain("O-band");
expect(await openings()).not.toContain("O2");
await expect(chip).toContainText("Studie 2 Satteldach/Bandfenster");
await comb(0).getByTestId("design-option-combination-assign").click();
await expect.poll(async () => (await dopt()).combination).toBe("studie-1");
await expect.poll(openings).toContain("O2");
// Undo schaltet zurück auf Studie 2.
await blurFocus(page);
await page.keyboard.press("ControlOrMeta+z");
await expect.poll(async () => (await dopt()).combination).toBe("studie-2");
await expect.poll(openings).toContain("O-band");
// Abnahmebild (1280 × 800): Panel mit den Kombinationen, Studie 2 der Ansicht zugewiesen.
const shots = process.env.DOSSIER_SHOTS;
if (shots) {
await page.setViewportSize({ width: 1280, height: 800 });
await panel.getByText("Kombinationen", { exact: true }).scrollIntoViewIfNeeded();
await page.screenshot({ path: `${shots}/04-kombinationen.png` });
}
// Wahl je Satz in einer Kombination ändern: Studie 2 mit Fassade A ⇒ Lochfenster.
await comb(1).getByTestId("design-option-combination-studie-2-fassade").selectOption("a");
await expect.poll(openings).toContain("O2");
// Vergleich je Kombination.
await panel.getByTestId("design-option-compare-open").click();
const rows = panel.getByTestId("design-option-compare-row");
await expect(rows).toHaveCount(3);
await expect(rows.nth(2)).toContainText("Studie 3 Satteldach/Lochfenster");
await panel.screenshot({ path: "test-results/designOptions272-kombinationen.png" });
// Löschen: Overlay-Dialog, danach Undo (ein Schritt, Verweis der Ansicht kommt mit zurück).
await comb(1).getByTestId("design-option-combination-delete").click();
await page.getByTestId("confirm-dialog-ok").click();
await expect.poll(async () => (await dopt()).combinations.length).toBe(2);
await expect.poll(async () => (await dopt()).combination).toBe(null);
await blurFocus(page);
await page.keyboard.press("ControlOrMeta+z");
await expect.poll(async () => (await dopt()).combinations.length).toBe(3);
await expect.poll(async () => (await dopt()).combination).toBe("studie-2");
});
test("Variantenvergleich als Blatt-Tabelle ([272])", async ({ page }) => {
await page.goto("/?dossierTest");
await page.getByRole("button", { name: /Neues Projekt/ }).first().click();
await expect(page.getByRole("group", { name: "Befehlszeile" })).toBeVisible();
await fileMenu(page, /^Neu aus Vorlage: Beispiel Varianten$/);
await discardIfAsked(page);
await openNewLayoutInFolder(page);
await page.locator("[data-table-add]").selectOption({ label: "Variantenvergleich" });
await expect(page.locator("[data-table-id]")).toHaveCount(1);
const texts = await page.locator("[data-table-id] text").allTextContents();
expect(texts).toContain("Studie 1 Flachdach/Lochfenster");
expect(texts).toContain("Studie 2 Satteldach/Bandfenster");
expect(texts).toContain("Kombination");
});
/** Layout in einem neuen Ordner anlegen und öffnen (wie `sheetTable.spec.ts`). */
async function openNewLayoutInFolder(page: Page) {
await openTab(page, "Mappe");
await page.getByRole("button", { name: "Ordner erstellen" }).first().click();
await page.keyboard.press("Enter");
await page.locator(".nav-label", { hasText: "Neuer Ordner" }).click();
await page.getByRole("button", { name: "Layout erstellen" }).first().click();
await page.getByRole("button", { name: "Erstellen", exact: true }).click();
await page.keyboard.press("Enter");
await page.locator(".nav-row", { hasText: "Layout" }).first().dblclick();
await expect(page.locator(".layout-sheet-pane")).toBeVisible();
}
+130 -27
View File
@@ -216,9 +216,41 @@ impl Combination {
}
}
/// Gespeicherte Kombination einer Ebene (über die verknüpfte Vorlage hat sie schon `level_with_template`).
pub fn level_choice<'a>(p: &'a Project, level_id: &str) -> Option<&'a BTreeMap<String, String>> {
p.floor(level_id).and_then(|l| l.design_options.as_ref())
/// Gespeicherte Wahl einer Ebene ([`stored_choice`]; über die verknüpfte Vorlage hat sie schon `level_with_template`).
pub fn level_choice(p: &Project, level_id: &str) -> Option<BTreeMap<String, String>> {
p.floor(level_id).and_then(|l| stored_choice(p, l.design_option_combination.as_deref(), l.design_options.as_ref()))
}
// ── Benannte Kombinationen ([272] Nachtrag, Archicad „Design Option Combinations“) ───────────────────────────────
/// Benannte Variantenkombinationen des Projekts.
pub fn combinations(p: &Project) -> &[DesignOptionCombination] {
p.design_option_combinations.as_deref().unwrap_or(&[])
}
/// Kombination nach Id, sonst nach Name (ohne Gross-/Kleinschreibung).
pub fn find_combination<'a>(p: &'a Project, key: &str) -> Option<&'a DesignOptionCombination> {
let key = key.trim();
let low = key.to_lowercase();
combinations(p).iter().find(|c| c.id == key).or_else(|| combinations(p).iter().find(|c| c.name.trim().to_lowercase() == low))
}
/// Vollständige Wahl einer benannten Kombination: je Satz die gespeicherte Variante, sonst (fehlender Satz, gelöschte
/// Variante) die Hauptvariante.
pub fn combination_choice(p: &Project, c: &DesignOptionCombination) -> Combination {
Combination::resolve(p, &[&c.choices], &[])
}
/// **Rangfolge der gespeicherten Wahl eines Objekts** (Ebene, Vorlage, Ausschnitt, Viewport): Verweist es auf eine
/// vorhandene benannte Kombination (`designOptionCombination`, Id), gilt diese vollständig — fehlende Sätze zeigen die
/// Hauptvariante — und die freie Wahl `designOptions` desselben Objekts wird übergangen. Sonst (kein oder unbekannter
/// Verweis) gilt die freie Wahl je Satz. Zwischen den Objekten bleibt es bei der bisherigen Reihenfolge (Hauptvarianten <
/// Ebene < Vorlage < Ausschnitt < Viewport < Anfrage; spätere gehen vor). `None` = keine Wahl gespeichert.
pub fn stored_choice(p: &Project, combination: Option<&str>, free: Option<&BTreeMap<String, String>>) -> Option<BTreeMap<String, String>> {
if let Some(c) = combination.filter(|s| !s.is_empty()).and_then(|id| combinations(p).iter().find(|c| c.id == id)) {
return Some(combination_choice(p, c).choice);
}
free.cloned()
}
/// Das Projekt in einer Kombination (Elemente anderer Varianten fehlen; ohne Wirkung geliehen).
@@ -239,7 +271,12 @@ pub fn project_in<'a>(p: &'a Project, c: &Combination) -> std::borrow::Cow<'a, P
pub struct CompareRow {
/// Satz-Id → Varianten-Id.
pub choice: BTreeMap<String, String>,
/// Zeilentitel: Name der benannten Kombination, sonst die Wahl als Text („Dachform B“).
pub label: String,
/// Id der benannten Kombination; fehlt bei Zeilen aus dem Kreuzprodukt.
pub combination: Option<String>,
/// Die Wahl je Satz als Text („Dachform B, Fassade A“).
pub detail: String,
pub primary: bool,
pub gf: f64,
pub hnf: f64,
@@ -251,20 +288,45 @@ pub struct CompareRow {
pub cost: f64,
}
/// [272] Kennzahlen und Kosten je Kombination (Hauptkombination zuerst); `filter`/`phase`: Umbau-Zustand.
/// [272] Kennzahlen und Kosten je Kombination; `filter`/`phase`: Umbau-Zustand. Zeilen: die gespeicherten benannten
/// Kombinationen (Name als Zeilentitel, Reihenfolge des Projekts); ohne gespeicherte Kombination alle Kombinationen
/// der Sätze (Hauptkombination zuerst).
pub fn compare(p: &Project, filter: Option<&str>, phase: Option<&str>) -> Vec<CompareRow> {
compare_scope(p, filter, phase, false)
}
/// Wie [`compare`]; `all` = immer alle Kombinationen der Sätze (Kreuzprodukt, höchstens [`MAX_COMPARE`]).
pub fn compare_scope(p: &Project, filter: Option<&str>, phase: Option<&str>, all: bool) -> Vec<CompareRow> {
if sets(p).is_empty() {
return Vec::new();
}
let prim = Combination::primary(p);
Combination::all(p)
.into_iter()
.map(|c| {
let rows: Vec<(Option<&DesignOptionCombination>, Combination)> = if all || combinations(p).is_empty() {
Combination::all(p).into_iter().map(|c| (None, c)).collect()
} else {
combinations(p).iter().take(MAX_COMPARE).map(|c| (Some(c), combination_choice(p, c))).collect()
};
rows.into_iter()
.map(|(named, c)| {
let q = crate::renovation::project_in_view(p, filter, phase, &c);
let k = crate::kennzahlen::compute(&q);
let cost = crate::kosten::estimate(&q);
let num = |x: f64| if x.is_finite() { x } else { 0.0 };
CompareRow { label: c.label(p), primary: c == prim, gf: num(k.gf), hnf: num(k.hnf), gv: num(k.gv), footprint: num(k.footprint), az: k.az.filter(|x| x.is_finite()), uez: k.uez.filter(|x| x.is_finite()), cost: num(cost.gross), choice: c.choice }
let detail = c.label(p);
CompareRow {
label: named.map_or_else(|| detail.clone(), |n| n.name.clone()),
combination: named.map(|n| n.id.clone()),
detail,
primary: c == prim,
gf: num(k.gf),
hnf: num(k.hnf),
gv: num(k.gv),
footprint: num(k.footprint),
az: k.az.filter(|x| x.is_finite()),
uez: k.uez.filter(|x| x.is_finite()),
cost: num(cost.gross),
choice: c.choice,
}
})
.collect()
}
@@ -324,25 +386,8 @@ fn set_list(root: &Map<String, Value>) -> Vec<Value> {
arr(root, "designOptionSets").to_vec()
}
/// Gespeicherte Kombinationen (Ebenen, Vorlagen, Ausschnitte, Layout-Viewports) ohne den Satz `set` bzw. ohne die
/// Variante `option` des Satzes (`None` = alle seine Varianten).
fn clear_choices(root: &Map<String, Value>, set: &str, option: Option<&str>, ops: &mut Vec<Value>) {
let fix = |v: &Value| -> Option<Value> {
let m = v.get("designOptions")?.as_object()?;
let cur = m.get(set)?.as_str();
if option.is_some_and(|o| cur != Some(o)) {
return None;
}
let mut obj = v.as_object()?.clone();
let mut next = m.clone();
next.shift_remove(set);
if next.is_empty() {
obj.shift_remove("designOptions");
} else {
obj.insert("designOptions".into(), Value::Object(next));
}
Some(Value::Object(obj))
};
/// Ops: `fix` auf Ebenen, Vorlagen, Ausschnitte und Layout-Viewports (Träger einer gespeicherten Wahl) anwenden.
fn map_holders(root: &Map<String, Value>, fix: impl Fn(&Value) -> Option<Value>, ops: &mut Vec<Value>) {
for key in ["drawingLevels", "viewTemplates", "viewSnapshots"] {
for v in arr(root, key) {
if let Some(n) = fix(v) {
@@ -362,6 +407,64 @@ fn clear_choices(root: &Map<String, Value>, set: &str, option: Option<&str>, ops
}
}
/// Gespeicherte Wahlen (Ebenen, Vorlagen, Ausschnitte, Layout-Viewports) und benannte Kombinationen ohne den Satz `set`
/// bzw. ohne die Variante `option` des Satzes (`None` = alle seine Varianten). Eine benannte Kombination ohne den Satz
/// zeigt dort die Hauptvariante.
fn clear_choices(root: &Map<String, Value>, set: &str, option: Option<&str>, ops: &mut Vec<Value>) {
let without = |m: &Map<String, Value>| -> Option<Map<String, Value>> {
let cur = m.get(set)?.as_str();
if option.is_some_and(|o| cur != Some(o)) {
return None;
}
let mut next = m.clone();
next.shift_remove(set);
Some(next)
};
map_holders(
root,
|v| {
let next = without(v.get("designOptions")?.as_object()?)?;
let mut obj = v.as_object()?.clone();
if next.is_empty() {
obj.shift_remove("designOptions");
} else {
obj.insert("designOptions".into(), Value::Object(next));
}
Some(Value::Object(obj))
},
ops,
);
for c in arr(root, "designOptionCombinations") {
let Some(next) = c.get("choices").and_then(Value::as_object).and_then(&without) else { continue };
let mut obj = c.as_object().cloned().unwrap_or_default();
obj.insert("choices".into(), Value::Object(next));
ops.push(json!({"kind": "replace", "collection": "designOptionCombinations", "entity": Value::Object(obj)}));
}
}
/// [272] Benannte Kombination löschen: sie verschwindet, Verweise an Ebenen, Vorlagen, Ausschnitten und Viewports fallen weg
/// (dort gilt wieder die freie Wahl bzw. die Hauptvarianten). Ein Undo-Schritt.
pub fn delete_combination_ops(root: &Map<String, Value>, id: &str) -> Vec<Value> {
let mut ops = Vec::new();
if !arr(root, "designOptionCombinations").iter().any(|c| id_of(c) == Some(id)) {
return ops;
}
map_holders(
root,
|v| {
if v.get("designOptionCombination").and_then(Value::as_str) != Some(id) {
return None;
}
let mut obj = v.as_object()?.clone();
obj.shift_remove("designOptionCombination");
Some(Value::Object(obj))
},
&mut ops,
);
ops.push(json!({"kind": "remove", "collection": "designOptionCombinations", "ids": [id]}));
ops
}
/// Elemente des Satzes `set` je Liste: (Liste, Element) für jede Variante, die `keep(option)` nicht behält.
fn elements_where<'a>(root: &'a Map<String, Value>, pred: impl Fn(&str, &str) -> bool) -> Vec<(&'static str, &'a Value)> {
let mut out = Vec::new();
+227 -2
View File
@@ -392,13 +392,13 @@ fn blatt_viewport_mit_eigener_kombination() {
let snap: ViewSnapshot = serde_json::from_value(json!({"id": "s", "name": "EG", "activeLevelId": "eg", "viewType": "grundriss", "scaleDenominator": 100, "detail": "mittel", "layerVisibility": {}, "drawingVisibility": {}})).unwrap_or_default();
let mut vp = LayoutViewport::default();
vp.design_options = Some([("dach".to_string(), "b".to_string())].into());
let s2 = crate::sheet_viewports::viewport_snapshot(&snap, &vp);
let s2 = crate::sheet_viewports::viewport_snapshot(&p, &snap, &vp);
assert_eq!(s2.design_options.as_ref().unwrap()["dach"], "b");
let q = crate::sheet_viewports::snapshot_project(&p, &s2);
let l = q.drawing_levels.iter().find(|l| l.id == "eg").unwrap();
assert_eq!(l.design_options.as_ref().unwrap()["dach"], "b");
// Ohne eigene Wahl unverändert (geliehen).
assert!(matches!(crate::sheet_viewports::viewport_snapshot(&snap, &LayoutViewport::default()), std::borrow::Cow::Borrowed(_)));
assert!(matches!(crate::sheet_viewports::viewport_snapshot(&p, &snap, &LayoutViewport::default()), std::borrow::Cow::Borrowed(_)));
}
#[test]
@@ -436,3 +436,228 @@ fn robust_bei_unsinn() {
let pm = project(&many);
assert!(Combination::all(&pm).len() <= MAX_COMPARE);
}
// ── Benannte Kombinationen ([272] Nachtrag) ─────────────────────────────────────────────────────────
/// Fixture mit zweitem Satz „Fassade“ (X = Haupt, Y: Wand W1) und zwei benannten Kombinationen:
/// „Studie 1“ = Dachform A (Fassade fehlt ⇒ Hauptvariante X), „Studie 2“ = Dachform B + Fassade Y.
fn fixture_k() -> Value {
let mut v = fixture();
v["designOptionSets"].as_array_mut().unwrap().push(json!({"id": "fas", "name": "Fassade", "options": [{"id": "x", "name": "X"}, {"id": "y", "name": "Y"}], "primary": "x"}));
v["walls"][0]["designOption"] = json!({"set": "fas", "option": "y"});
v["designOptionCombinations"] = json!([
{"id": "k1", "name": "Studie 1: Flachdach", "choices": {"dach": "a"}},
{"id": "k2", "name": "Studie 2: Satteldach + Y", "choices": {"dach": "b", "fas": "y"}},
]);
v
}
fn level_with(v: &mut Value, id: &str, f: impl Fn(&mut Value)) {
for l in v["drawingLevels"].as_array_mut().unwrap() {
if l["id"] == id {
f(l);
}
}
}
#[test]
fn kombination_rangfolge_und_fehlende_saetze() {
let p = project(&fixture_k());
let k1 = find_combination(&p, "k1").unwrap();
// Fehlender Satz „fas“ ⇒ Hauptvariante X.
assert_eq!(combination_choice(&p, k1).choice, BTreeMap::from([("dach".to_string(), "a".to_string()), ("fas".to_string(), "x".to_string())]));
assert_eq!(find_combination(&p, "studie 2: satteldach + y").unwrap().id, "k2", "auch nach Name");
// Unbekannte Variante in einer Kombination ⇒ Hauptvariante.
let mut v = fixture_k();
v["designOptionCombinations"][0]["choices"] = json!({"dach": "gibtsnicht"});
let q = project(&v);
assert_eq!(combination_choice(&q, find_combination(&q, "k1").unwrap()).choice["dach"], "a");
// Kombination gilt vollständig und geht der freien Wahl desselben Objekts vor; unbekannter Verweis ⇒ freie Wahl.
let free: BTreeMap<String, String> = [("dach".to_string(), "b".to_string())].into();
assert_eq!(stored_choice(&p, Some("k1"), Some(&free)).unwrap()["dach"], "a");
assert_eq!(stored_choice(&p, Some("weg"), Some(&free)).unwrap()["dach"], "b");
assert_eq!(stored_choice(&p, None, Some(&free)), Some(free.clone()));
assert_eq!(stored_choice(&p, None, None), None);
// Ebene: Kombination k2 ⇒ W9 (Dach B) sichtbar, W2 (A) weg, W1 (Fassade Y) sichtbar.
let mut v = fixture_k();
level_with(&mut v, "eg", |l| {
l["designOptionCombination"] = json!("k2");
l["designOptions"] = json!({"dach": "a"});
});
let q = project(&v);
let pr = plan_with(&q, json!({}));
assert!(has_wall(&pr, "W9") && !has_wall(&pr, "W2") && has_wall(&pr, "W1"), "Kombination vor freier Wahl");
// Die Anfrage geht der Kombination der Ebene vor.
let pr = plan_with(&q, json!({"designOptions": "Dachform=A"}));
assert!(has_wall(&pr, "W2") && !has_wall(&pr, "W9") && has_wall(&pr, "W1"));
// Kombination k1: Fassade fehlt ⇒ Hauptvariante X ⇒ W1 (Y) fehlt.
level_with(&mut v, "eg", |l| l["designOptionCombination"] = json!("k1"));
let pr = plan_with(&project(&v), json!({}));
assert!(has_wall(&pr, "W2") && !has_wall(&pr, "W1"));
// Gelöschte/unbekannte Kombination: freie Wahl der Ebene (A).
level_with(&mut v, "eg", |l| l["designOptionCombination"] = json!("weg"));
let pr = plan_with(&project(&v), json!({}));
assert!(has_wall(&pr, "W2") && !has_wall(&pr, "W9"));
}
#[test]
fn kombination_in_vorlage_ausschnitt_und_viewport() {
let p = project(&fixture_k());
let snap: ViewSnapshot = serde_json::from_value(json!({"id": "s", "name": "EG", "activeLevelId": "eg", "viewType": "grundriss", "scaleDenominator": 100, "detail": "mittel", "layerVisibility": {}, "drawingVisibility": {}, "designOptionCombination": "k1", "designOptions": {"dach": "b"}})).unwrap_or_default();
// Ausschnitt: k1 vor freier Wahl; Viewport k2 darüber.
let mut vp = LayoutViewport::default();
vp.design_option_combination = Some("k2".into());
let s2 = crate::sheet_viewports::viewport_snapshot(&p, &snap, &vp);
assert_eq!(s2.design_options.as_ref().unwrap()["dach"], "b");
assert_eq!(s2.design_options.as_ref().unwrap()["fas"], "y");
assert!(s2.design_option_combination.is_none(), "aufgelöst, kein zweiter Verweis");
let q = crate::sheet_viewports::snapshot_project(&p, &s2);
assert_eq!(level_choice(&q, "eg").unwrap()["dach"], "b");
assert!(q.drawing_levels.iter().find(|l| l.id == "eg").unwrap().design_option_combination.is_none());
// Nur Ausschnitt: k1 (Fassade fehlt ⇒ Hauptvariante X), die freie Wahl des Ausschnitts wird übergangen.
let s3 = crate::sheet_viewports::viewport_snapshot(&p, &snap, &LayoutViewport::default());
let args = crate::sheet_viewports::viewport_args(&p, &s3, 100.0, false);
let c = Combination::resolve(&p, &[], &args.design_options);
assert_eq!((c.choice["dach"].as_str(), c.choice["fas"].as_str()), ("a", "x"));
// Vorlage mit Kombination ersetzt die freie Wahl der Ebene.
let mut v = fixture_k();
level_with(&mut v, "eg", |l| l["designOptions"] = json!({"dach": "b"}));
v["viewTemplates"] = json!([{"id": "vt", "name": "T", "designOptionCombination": "k1"}]);
let q = project(&v);
let t = &q.view_templates.as_ref().unwrap()[0];
let lv = crate::sheet_viewports::level_with_template(q.drawing_levels.iter().find(|l| l.id == "eg").unwrap(), t);
assert_eq!(stored_choice(&q, lv.design_option_combination.as_deref(), lv.design_options.as_ref()).unwrap()["dach"], "a");
// Vorlage ohne eigene Wahl: die der Ebene bleibt.
let t0: ViewTemplate = serde_json::from_value(json!({"id": "t0", "name": "T0"})).unwrap_or_default();
let lv = crate::sheet_viewports::level_with_template(q.drawing_levels.iter().find(|l| l.id == "eg").unwrap(), &t0);
assert_eq!(lv.design_options.as_ref().unwrap()["dach"], "b");
}
#[test]
fn varianten_loeschen_bereinigt_kombinationen() {
// Variante B löschen: „Studie 2“ verliert die Wahl für „dach“ (⇒ Hauptvariante), „fas“ bleibt; ein Undo-Schritt.
let mut d = crate::document::Document::from_json(&fixture_k().to_string()).unwrap();
let before = d.to_json();
let ops = root_ops(&d, "designOptionDeleteOps", json!({"set": "dach", "option": "b"}));
apply(&mut d, &ops);
let p = project(&serde_json::from_str(&d.to_json()).unwrap());
let k2 = find_combination(&p, "k2").unwrap();
assert!(!k2.choices.contains_key("dach") && k2.choices["fas"] == "y", "{:?}", k2.choices);
assert_eq!(find_combination(&p, "k1").unwrap().choices["dach"], "a");
d.undo().unwrap();
assert_eq!(d.to_json(), before, "ein Undo-Schritt");
// Satz „fas“ löschen: beide Kombinationen ohne den Satz.
let ops = root_ops(&d, "designOptionDeleteOps", json!({"set": "fas"}));
apply(&mut d, &ops);
let p = project(&serde_json::from_str(&d.to_json()).unwrap());
assert!(combinations(&p).iter().all(|c| !c.choices.contains_key("fas")));
assert_eq!(combinations(&p).len(), 2, "Kombinationen bleiben");
d.undo().unwrap();
// Übernehmen von „dach“: Satz weg, Kombinationen ohne ihn.
let ops = root_ops(&d, "designOptionAcceptOps", json!({"set": "dach", "option": "a"}));
apply(&mut d, &ops);
assert!(combinations(&project(&serde_json::from_str(&d.to_json()).unwrap())).iter().all(|c| !c.choices.contains_key("dach")));
d.undo().unwrap();
assert_eq!(d.to_json(), before);
}
#[test]
fn kombination_loeschen_raeumt_verweise_auf() {
let mut v = fixture_k();
level_with(&mut v, "eg", |l| {
l["designOptionCombination"] = json!("k2");
l["designOptions"] = json!({"dach": "a"});
});
v["viewSnapshots"] = json!([{"id": "s", "name": "EG", "activeLevelId": "eg", "viewType": "grundriss", "scaleDenominator": 100, "detail": "mittel", "layerVisibility": {}, "drawingVisibility": {}, "designOptionCombination": "k2"}]);
v["layouts"] = json!([{"id": "L", "name": "Blatt", "viewports": [{"id": "vp", "snapshotId": "s", "xMm": 0, "yMm": 0, "widthMm": 100, "heightMm": 100, "designOptionCombination": "k2"}, {"id": "vp2", "snapshotId": "s", "xMm": 0, "yMm": 0, "widthMm": 100, "heightMm": 100, "designOptionCombination": "k1"}]}]);
let mut d = crate::document::Document::from_json(&v.to_string()).unwrap();
let before = d.to_json();
let ops = root_ops(&d, "designOptionCombinationDeleteOps", json!({"id": "k2"}));
apply(&mut d, &ops);
let p = d.project().unwrap().clone();
assert!(find_combination(&p, "k2").is_none());
let l = p.drawing_levels.iter().find(|l| l.id == "eg").unwrap();
assert!(l.design_option_combination.is_none());
assert_eq!(l.design_options.as_ref().unwrap()["dach"], "a", "freie Wahl gilt wieder");
assert!(p.view_snapshots.as_ref().unwrap()[0].design_option_combination.is_none());
let vps = &p.layouts.as_ref().unwrap()[0].viewports;
assert!(vps[0].design_option_combination.is_none() && vps[1].design_option_combination.as_deref() == Some("k1"));
d.undo().unwrap();
assert_eq!(d.to_json(), before);
assert!(root_ops(&d, "designOptionCombinationDeleteOps", json!({"id": "nix"})).is_empty());
}
#[test]
fn vergleich_je_gespeicherter_kombination() {
let p = project(&fixture_k());
let rows = compare(&p, None, None);
assert_eq!(rows.len(), 2, "gespeicherte Kombinationen, nicht das Kreuzprodukt (4)");
assert_eq!(rows[0].label, "Studie 1: Flachdach");
assert_eq!(rows[0].combination.as_deref(), Some("k1"));
assert_eq!(rows[0].detail, "Dachform A, Fassade X");
assert!(rows[0].primary && !rows[1].primary);
assert_eq!(rows[1].label, "Studie 2: Satteldach + Y");
assert_ne!(rows[0].hnf, rows[1].hnf, "R1 zählt nur in A");
// Alle Kombinationen: 4, Zeilentitel = Wahl als Text.
let all = compare_scope(&p, None, None, true);
assert_eq!(all.len(), 4);
assert!(all.iter().all(|r| r.combination.is_none()));
assert_eq!(all[0].label, "Dachform A, Fassade X");
// Abfrage und CSV: Name als Zeilentitel.
let q: Value = serde_json::from_str(&crate::queries::run(&p, "designOptionCompare", &[], "").unwrap()).unwrap();
assert_eq!(q.as_array().unwrap().len(), 2);
let q: Value = serde_json::from_str(&crate::queries::run(&p, "designOptionCompare", &[], r#"{"all": true}"#).unwrap()).unwrap();
assert_eq!(q.as_array().unwrap().len(), 4);
let csv: String = serde_json::from_str(&crate::queries::run(&p, "designOptionCompare", &[], r#"{"head": ["Kombination","GF","HNF","GV","Fussabdruck","AZ","ÜZ","Kosten"]}"#).unwrap()).unwrap();
assert!(csv.lines().nth(1).unwrap().starts_with("Studie 1: Flachdach;"), "{csv}");
assert_eq!(csv.lines().count(), 3);
// Ohne gespeicherte Kombinationen wie bisher.
assert_eq!(compare(&project(&fixture()), None, None).len(), 2);
}
#[test]
fn kennzahlen_je_kombination_ueber_anfrage() {
// Kennzahlen mit der Wahl einer Kombination als Anfrage = Zeile des Vergleichs.
let p = project(&fixture_k());
let k2 = find_combination(&p, "k2").unwrap();
let spec = combination_choice(&p, k2).choice.iter().map(|(a, b)| format!("{a}={b}")).collect::<Vec<_>>().join(",");
let via_req = crate::queries::run(&p, "kennzahlen", &[], &json!({"designOptions": spec}).to_string()).unwrap();
let rows = compare(&p, None, None);
let k: Value = serde_json::from_str(&via_req).unwrap();
assert!((k["hnf"].as_f64().unwrap() - rows[1].hnf).abs() < 1e-9, "{} / {}", k["hnf"], rows[1].hnf);
}
#[test]
fn robust_bei_kombinationen_unsinn() {
let mut v = fixture_k();
v["designOptionCombinations"] = json!([{}, {"id": "k1"}, {"id": "k1", "name": "doppelt", "choices": {"nix": "y", "dach": "gibtsnicht"}}, {"id": "k3"}]);
level_with(&mut v, "eg", |l| l["designOptionCombination"] = json!("k1"));
let p = project(&v);
let _ = plan_with(&p, json!({}));
let _ = compare(&p, None, None);
let _ = compare_scope(&p, None, None, true);
let d = crate::document::Document::from_json(&v.to_string()).unwrap();
for t in ["{}", r#"{"id": 5}"#, r#"{"id": "k1"}"#] {
let _ = crate::queries::run_root(&d.lookup(), "designOptionCombinationDeleteOps", t);
}
assert!(crate::queries::run_root(&d.lookup(), "designOptionCombinationDeleteOps", "kaputt").is_err());
}
/// Die typisierte Sicht des Dokuments folgt jeder Op auf ein Wurzelfeld: `Project::set_field` kennt alle Felder der Fixture
/// (sonst landete z. B. `designOptionCombinations` nach einer Op in `extra` und die Ableitungen sähen die alte Fassung).
#[test]
fn set_field_kennt_alle_wurzelfelder() {
let v = fixture_k();
for (k, val) in v.as_object().unwrap() {
let mut q = Project::default();
q.set_field(k, Some(val)).unwrap();
assert!(!q.extra.0.contains_key(k), "set_field ohne Zweig für „{k}“");
}
// Op auf Kombinationen wirkt auf die typisierte Sicht (auch nach Undo).
let mut d = crate::document::Document::from_json(&v.to_string()).unwrap();
assert_eq!(d.project().unwrap().design_option_combinations.as_ref().unwrap().len(), 2);
apply(&mut d, &[json!({"kind": "setField", "key": "designOptionCombinations", "value": [{"id": "k9", "name": "Neu", "choices": {}}]})]);
assert_eq!(d.project().unwrap().design_option_combinations.as_ref().unwrap()[0].id, "k9");
d.undo().unwrap();
assert_eq!(d.project().unwrap().design_option_combinations.as_ref().unwrap()[0].id, "k1");
}
+59
View File
@@ -1967,6 +1967,11 @@ pub struct DrawingLevel {
#[serde(rename = "designOptions", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub design_options: Option<std::collections::BTreeMap<String, String>>,
/// [272] Benannte Variantenkombination (`Project.designOptionCombinations`, Id). Gesetzt und gültig ⇒ sie gilt vollständig
/// (fehlende Sätze ⇒ Hauptvariante) und die freie Wahl `designOptions` desselben Objekts wird übergangen; sonst die freie Wahl.
#[serde(rename = "designOptionCombination", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub design_option_combination: Option<String>,
#[serde(flatten)]
#[ts(skip)]
pub extra: Extra,
@@ -2066,6 +2071,11 @@ pub struct ViewTemplate {
#[serde(rename = "designOptions", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub design_options: Option<std::collections::BTreeMap<String, String>>,
/// [272] Benannte Variantenkombination (`Project.designOptionCombinations`, Id). Gesetzt und gültig ⇒ sie gilt vollständig
/// (fehlende Sätze ⇒ Hauptvariante) und die freie Wahl `designOptions` desselben Objekts wird übergangen; sonst die freie Wahl.
#[serde(rename = "designOptionCombination", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub design_option_combination: Option<String>,
#[serde(flatten)]
#[ts(skip)]
pub extra: Extra,
@@ -3092,6 +3102,20 @@ pub struct DesignOptionSet {
pub extra: Extra,
}
/// [272] Eine benannte Variantenkombination (z. B. „Studie 1: Satteldach + Bandfenster“): je Satz die gewählte Variante.
/// Sätze, die fehlen (oder deren Variante gelöscht wurde), zeigen ihre Hauptvariante.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, TS)]
#[serde(default)]
pub struct DesignOptionCombination {
pub id: String,
pub name: String,
/// Satz-Id → Varianten-Id.
pub choices: std::collections::BTreeMap<String, String>,
#[serde(flatten)]
#[ts(skip)]
pub extra: Extra,
}
/// [271] Umbau-Einstellungen des Projekts.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, TS)]
#[serde(default)]
@@ -5759,6 +5783,11 @@ pub struct ViewSnapshot {
#[serde(rename = "designOptions", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub design_options: Option<std::collections::BTreeMap<String, String>>,
/// [272] Benannte Variantenkombination (`Project.designOptionCombinations`, Id). Gesetzt und gültig ⇒ sie gilt vollständig
/// (fehlende Sätze ⇒ Hauptvariante) und die freie Wahl `designOptions` desselben Objekts wird übergangen; sonst die freie Wahl.
#[serde(rename = "designOptionCombination", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub design_option_combination: Option<String>,
#[serde(flatten)]
#[ts(skip)]
pub extra: Extra,
@@ -5962,6 +5991,11 @@ pub struct LayoutViewport {
#[serde(rename = "designOptions", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub design_options: Option<std::collections::BTreeMap<String, String>>,
/// [272] Benannte Variantenkombination (`Project.designOptionCombinations`, Id). Gesetzt und gültig ⇒ sie gilt vollständig
/// (fehlende Sätze ⇒ Hauptvariante) und die freie Wahl `designOptions` desselben Objekts wird übergangen; sonst die freie Wahl.
#[serde(rename = "designOptionCombination", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub design_option_combination: Option<String>,
#[serde(flatten)]
#[ts(skip)]
pub extra: Extra,
@@ -5995,6 +6029,9 @@ pub enum LayoutTableSource {
/// [255] Baurecht-Nachweis (AZ/ÜZ/Höhen: zulässig, Projekt, Reserve, erfüllt).
#[serde(rename = "siteProof")]
SiteProof,
/// [272] Variantenvergleich: Kennzahlen und Kosten je gespeicherte Variantenkombination.
#[serde(rename = "designOptionCompare")]
DesignOptionCompare,
#[serde(other)]
#[ts(skip)]
Unknown,
@@ -6862,6 +6899,10 @@ pub struct Project {
#[serde(rename = "designOptionSets", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub design_option_sets: Option<Vec<DesignOptionSet>>,
/// [272] Benannte Variantenkombinationen (Archicad „Design Option Combinations“): je Satz genau eine Variante.
#[serde(rename = "designOptionCombinations", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub design_option_combinations: Option<Vec<DesignOptionCombination>>,
#[serde(flatten)]
#[ts(skip)]
pub extra: Extra,
@@ -7741,6 +7782,24 @@ impl Project {
None => Default::default(),
};
}
"renovation" => {
self.renovation = match v {
Some(v) => <Option<RenovationSettings>>::deserialize(v).map_err(|e| e.to_string())?,
None => Default::default(),
};
}
"designOptionSets" => {
self.design_option_sets = match v {
Some(v) => <Option<Vec<DesignOptionSet>>>::deserialize(v).map_err(|e| e.to_string())?,
None => Default::default(),
};
}
"designOptionCombinations" => {
self.design_option_combinations = match v {
Some(v) => <Option<Vec<DesignOptionCombination>>>::deserialize(v).map_err(|e| e.to_string())?,
None => Default::default(),
};
}
other => match v {
Some(v) => {
self.extra.0.insert(other.to_owned(), v.clone());
+3 -3
View File
@@ -628,7 +628,7 @@ impl AxoArgs {
/// [266] Abfrage-Text (`axoPlan`) eines 3D-Dokuments: Einstellungen des Ausschnitts (`doc3d`, sonst sein Blickwinkel
/// `view3d`) und die Klassen, die er ausblendet (`invisible`, wie beim Schnitt-Viewport).
pub fn snapshot_text(snap: &ViewSnapshot, invisible: &[String]) -> String {
pub fn snapshot_text(p: &Project, snap: &ViewSnapshot, invisible: &[String]) -> String {
let mut v = snap.doc3d.as_ref().and_then(|d| serde_json::to_value(d).ok()).unwrap_or_else(|| serde_json::json!({}));
if let Some(o) = v.as_object_mut() {
if !o.contains_key("view") {
@@ -637,8 +637,8 @@ pub fn snapshot_text(snap: &ViewSnapshot, invisible: &[String]) -> String {
o.insert("hasVis".into(), serde_json::Value::Bool(true));
o.insert("invisible".into(), serde_json::to_value(invisible).unwrap_or_default());
// [272] Variantenkombination des Ausschnitts.
if let Some(m) = snap.design_options.as_ref().filter(|m| !m.is_empty()) {
o.insert("designOptions".into(), serde_json::to_value(m).unwrap_or_default());
if let Some(m) = crate::design_options::stored_choice(p, snap.design_option_combination.as_deref(), snap.design_options.as_ref()).filter(|m| !m.is_empty()) {
o.insert("designOptions".into(), serde_json::to_value(&m).unwrap_or_default());
}
}
v.to_string()
+3
View File
@@ -136,6 +136,8 @@ pub struct LevelSpec {
pub renovation_phase: Option<String>,
/// [272] Variantenkombination der Ebene (`designOptions`: Satz-Id → Varianten-Id).
pub design_options: Option<std::collections::BTreeMap<String, String>>,
/// [272] Benannte Kombination der Ebene (`designOptionCombination`, Id); sie geht `design_options` vor.
pub design_option_combination: Option<String>,
}
impl LevelSpec {
@@ -156,6 +158,7 @@ impl LevelSpec {
model_view: v.get("modelViewOptionId").and_then(|m| m.as_str()).filter(|m| !m.is_empty()).map(String::from),
renovation: v.get("renovationFilter").and_then(|m| m.as_str()).filter(|m| !m.is_empty()).map(String::from),
renovation_phase: v.get("renovationPhase").and_then(|m| m.as_str()).filter(|m| !m.is_empty()).map(String::from),
design_option_combination: v.get("designOptionCombination").and_then(|m| m.as_str()).filter(|m| !m.is_empty()).map(String::from),
design_options: v.get("designOptions").and_then(|m| m.as_object()).map(|m| m.iter().filter_map(|(k, v)| Some((k.clone(), v.as_str()?.to_string()))).collect()),
}
}
+2 -2
View File
@@ -49,8 +49,8 @@ pub fn renovation_view(p: &Project, v: &serde_json::Value, level: &LevelSpec) ->
Some(f) => (Some(f), v.get("renovationPhase").and_then(|m| m.as_str())),
None => (level.renovation.as_deref(), level.renovation_phase.as_deref()),
};
let stored: Vec<&std::collections::BTreeMap<String, String>> = level.design_options.iter().collect();
crate::renovation::View::with(p, f, ph, &stored, &crate::design_options::parse_request(v.get("designOptions")))
let own = crate::design_options::stored_choice(p, level.design_option_combination.as_deref(), level.design_options.as_ref());
crate::renovation::View::with(p, f, ph, &own.iter().collect::<Vec<_>>(), &crate::design_options::parse_request(v.get("designOptions")))
}
/// Abfrage `sectionPlan`: `args` = `[mono, openings, key]` (`key` > 0
+1 -1
View File
@@ -168,7 +168,7 @@ fn tiefe_blendet_ferne_bauteile_aus() {
let mut p = Project::default();
// quer: von der Ebene geschnitten und weit nach hinten; nah: 3 m, fern: 10 m hinter der Ebene (höher).
p.walls = vec![wall("quer", (0.0, -1.0), (0.0, 12.0), 2.5), wall("nah", (2.0, 3.0), (6.0, 3.0), 2.5), wall("fern", (2.0, 10.0), (6.0, 10.0), 4.0)];
let lv = |depth: Option<f64>| LevelSpec { model_view: None, renovation: None, renovation_phase: None, design_options: None, bends: Vec::new(), sketch: false, cut_hatch: false, kind: "section".into(), line: Some([Vec2 { x: -1.0, y: 0.0 }, Vec2 { x: 8.0, y: 0.0 }]), direction_sign: Some(1.0), depth, shadows: false, hidden_lines: false };
let lv = |depth: Option<f64>| LevelSpec { model_view: None, renovation: None, renovation_phase: None, design_options: None, design_option_combination: None, bends: Vec::new(), sketch: false, cut_hatch: false, kind: "section".into(), line: Some([Vec2 { x: -1.0, y: 0.0 }, Vec2 { x: 8.0, y: 0.0 }]), direction_sign: Some(1.0), depth, shadows: false, hidden_lines: false };
let top = |o: &Output| o.visible.iter().map(|e| e.a[1].max(e.b[1])).fold(f64::NEG_INFINITY, f64::max);
let all = compute_section(&p, &lv(None), &[]).unwrap().unwrap();
assert!(top(&all) > 3.9, "ohne Tiefe ist die ferne Wand sichtbar: {}", top(&all));
+2 -1
View File
@@ -15,7 +15,7 @@ const REQUIRED_ARRAYS: [&str; 3] = ["walls", "layers", "drawingLevels"];
const DEFAULT_ARRAYS: [&str; 5] = ["lineStyles", "hatches", "components", "wallTypes", "drawings2d"];
/// Bekannte Felder von `Project` (für die Meldung unbekannter Felder).
const KNOWN_KEYS: [&str; 61] = [
const KNOWN_KEYS: [&str; 62] = [
"formatVersion", "id", "name", "lineStyles", "textStyles", "hatches", "components", "wallTypes",
"ceilingTypes", "roofTypes", "blockDefs", "doorTypes", "windowTypes", "stairTypes", "pens",
"penSets", "activePenSetId", "customPalettes", "builtinPaletteBanks", "drawingLevels", "layers",
@@ -28,6 +28,7 @@ const KNOWN_KEYS: [&str; 61] = [
"costEstimate",
"renovation",
"designOptionSets",
"designOptionCombinations",
];
/// Ergebnis des Einlesens.
+6 -1
View File
@@ -99,7 +99,7 @@ pub fn run(p: &Project, name: &str, args: &[f64], text: &str) -> Result<String,
("designOptionCompare", _) => {
let v: serde_json::Value = serde_json::from_str(text).unwrap_or_default();
let s = |k: &str| v.get(k).and_then(|x| x.as_str()).filter(|x| !x.is_empty());
let rows = crate::design_options::compare(p, s("renovation"), s("renovationPhase"));
let rows = crate::design_options::compare_scope(p, s("renovation"), s("renovationPhase"), v.get("all").and_then(|x| x.as_bool()).unwrap_or(false));
match v.get("head").and_then(|h| h.as_array()) {
Some(h) => json(&crate::design_options::compare_csv(&rows, &h.iter().filter_map(|x| x.as_str().map(String::from)).collect::<Vec<_>>())),
None => json(&rows),
@@ -280,6 +280,11 @@ pub fn run_root(lk: &crate::document::Lookup, name: &str, text: &str) -> Result<
_ => crate::design_options::copy_ops(root, &sel, target, &s("stamp")),
})
}
// [272] Benannte Kombination löschen (`text` = `{"id"}`): samt Verweisen an Ebenen, Vorlagen, Ausschnitten, Viewports.
"designOptionCombinationDeleteOps" => {
let a: serde_json::Value = serde_json::from_str(text).map_err(|e| format!("{name}: {e}"))?;
json(&crate::design_options::delete_combination_ops(root, a.get("id").and_then(|x| x.as_str()).unwrap_or("")))
}
"penDeleteOps" => json(&crate::pens::delete_pen_ops(root, text)),
// Standard-Bibliothek ([100]–[102], `standards.rs`): fehlende Standard-Ressourcen als Ops.
"standardsMergeOps" => json(&crate::standards::merge_ops_in(root, crate::standards::Lang::parse(text))),
+2 -2
View File
@@ -195,8 +195,8 @@ impl View {
let l = p.floor(level_id);
let f = filter.filter(|s| !s.is_empty()).or_else(|| l.and_then(|l| l.renovation_filter.as_deref()));
let ph = if filter.is_some_and(|s| !s.is_empty()) { phase } else { phase.or_else(|| l.and_then(|l| l.renovation_phase.as_deref())) };
let stored: Vec<&std::collections::BTreeMap<String, String>> = l.and_then(|l| l.design_options.as_ref()).into_iter().collect();
Self::with(p, f, ph, &stored, options)
let own = l.and_then(|l| crate::design_options::stored_choice(p, l.design_option_combination.as_deref(), l.design_options.as_ref()));
Self::with(p, f, ph, &own.iter().collect::<Vec<_>>(), options)
}
/// Zustand des Elements in der Etappe des Filters; `None` = es steht dort (noch/schon) nicht.
+53 -1
View File
@@ -146,6 +146,18 @@ const SITE_PROOF: &[Col] = &[
cc("ok", "siteProof.col.ok", 1.35, true),
];
/// [272] Variantenvergleich (je gespeicherte Kombination, sonst je Kombination der Sätze).
const DESIGN_OPTION_COMPARE: &[Col] = &[
c("combination", "designOption.compare.combination", 3.4, false, true),
c("gf", "designOption.compare.col.gf", 1.3, true, true),
c("hnf", "designOption.compare.col.hnf", 1.3, true, true),
c("gv", "designOption.compare.col.gv", 1.3, true, true),
c("footprint", "designOption.compare.footprint", 1.4, true, false),
c("az", "designOption.compare.col.az", 1.0, true, false),
c("uez", "designOption.compare.col.uez", 1.0, true, false),
c("cost", "designOption.compare.cost", 1.9, true, true),
];
/// [158] Raumbuch-Spalten, die nur erscheinen, wenn ein Raum eine Dachschräge hat.
const SLOPE_COLS: &[&str] = &["heightMin", "heightMean", "areaUnder1", "area1To15"];
@@ -220,6 +232,7 @@ pub fn catalog(source: LayoutTableSource) -> &'static [Col] {
LayoutTableSource::RoomBook => ROOM_BOOK,
LayoutTableSource::Costs => COSTS,
LayoutTableSource::SiteProof => SITE_PROOF,
LayoutTableSource::DesignOptionCompare => DESIGN_OPTION_COMPARE,
}
}
@@ -227,7 +240,7 @@ pub fn catalog(source: LayoutTableSource) -> &'static [Col] {
pub fn catalog_json() -> Value {
let one = |s: &[Col]| s.iter().map(|k| json!({"id": k.id, "key": k.key, "numeric": k.numeric, "default": k.default})).collect::<Vec<_>>();
json!({
"sources": {"openings": one(OPENINGS), "areas": one(AREAS), "rooms": one(ROOMS), "elements": one(ELEMENTS), "earthworks": one(EARTHWORKS), "roomBook": one(ROOM_BOOK), "costs": one(COSTS), "siteProof": one(SITE_PROOF)},
"sources": {"openings": one(OPENINGS), "areas": one(AREAS), "rooms": one(ROOMS), "elements": one(ELEMENTS), "earthworks": one(EARTHWORKS), "roomBook": one(ROOM_BOOK), "costs": one(COSTS), "siteProof": one(SITE_PROOF), "designOptionCompare": one(DESIGN_OPTION_COMPARE)},
"valueKeys": VALUE_KEYS,
})
}
@@ -365,6 +378,7 @@ fn data_of(p: &Project, t: &LayoutTable, lb: &Labels) -> Data {
LayoutTableSource::RoomBook => room_book_data(p, lb),
LayoutTableSource::Costs => costs_data(p, lb),
LayoutTableSource::SiteProof => site_proof_data(p, lb),
LayoutTableSource::DesignOptionCompare => design_option_compare_data(p),
}
}
@@ -427,6 +441,19 @@ fn costs_data(p: &Project, lb: &Labels) -> Data {
Data { rows, sloped: false, total_last: true }
}
/// [272] Variantenvergleich: Kennzahlen und Kosten je gespeicherte Kombination (Name als Zeilentitel), ohne gespeicherte
/// Kombination je Kombination der Sätze; ohne Variantensätze leer.
fn design_option_compare_data(p: &Project) -> Data {
let rows = crate::design_options::compare(p, None, None)
.into_iter()
.map(|r| {
let opt = |x: Option<f64>| x.map_or_else(|| txt("–"), |x| num(x, 2));
vec![txt(r.label), num(r.gf, 1), num(r.hnf, 1), num(r.gv, 0), num(r.footprint, 1), opt(r.az), opt(r.uez), Cell::Num { n: Some(r.cost), d: 0, g: true }]
})
.collect();
Data { rows, sloped: false, total_last: false }
}
/// [255] Baurecht-Nachweis: eine Zeile je Prüfgrösse; fehlende Vorgabe/Projektwert als „—“. Ohne Angaben aus dem
/// Dokument (IVHB-Optionen) rechnet der Nachweis mit Parzellenfläche bzw. Parzellengrenze.
fn site_proof_data(p: &Project, lb: &Labels) -> Data {
@@ -887,6 +914,31 @@ mod tests {
assert_eq!(crate::area_report::fmt_num(-999.0, 0, true), "-999");
assert_eq!(crate::area_report::fmt_num(-1000.0, 0, true), "-1'000");
}
/// [272] Variantenvergleich als Blatt-Tabelle: eine Zeile je gespeicherte Kombination (Name als Zeilentitel), sonst je Kombination der Sätze.
#[test]
fn variantenvergleich_tabelle() {
let mut t = table("v", None);
t.source = LayoutTableSource::DesignOptionCompare;
let mut p = project(0, vec![t]);
let opt = |id: &str, name: &str| DesignOption { id: id.into(), name: name.into(), ..Default::default() };
p.design_option_sets = Some(vec![DesignOptionSet { id: "dach".into(), name: "Dachform".into(), options: vec![opt("a", "A"), opt("b", "B")], primary: Some("a".into()), ..Default::default() }]);
p.walls[0].design_option = Some(DesignOptionRef { set: "dach".into(), option: "b".into(), ..Default::default() });
let lb = Labels::parse(&json!({"designOption.compare.combination": "Kombination"}));
let r = render(&p, &p.layouts.as_ref().unwrap()[0], &lb);
assert_eq!(r[0].total, 2, "ohne gespeicherte Kombinationen: alle (A, B)");
let tx = texts(&r[0]);
assert!(tx.contains(&"Kombination".to_string()) && tx.contains(&"Dachform A".to_string()) && tx.contains(&"Dachform B".to_string()), "{tx:?}");
p.design_option_combinations = Some(vec![DesignOptionCombination { id: "k".into(), name: "Studie 1".into(), choices: [("dach".to_string(), "b".to_string())].into(), ..Default::default() }]);
let r = render(&p, &p.layouts.as_ref().unwrap()[0], &lb);
assert_eq!(r[0].total, 1);
assert!(texts(&r[0]).contains(&"Studie 1".to_string()));
// Ohne Variantensätze: leere Tabelle, nie Panic.
p.design_option_sets = None;
assert_eq!(render(&p, &p.layouts.as_ref().unwrap()[0], &lb)[0].total, 0);
assert_eq!(serde_json::to_value(LayoutTableSource::DesignOptionCompare).unwrap(), "designOptionCompare");
assert_eq!(catalog_json()["sources"]["designOptionCompare"].as_array().unwrap().len(), 8);
}
/// [255] Baurecht-Nachweis als Blatt-Tabelle: ohne Vorgaben überall „—“, mit Vorgabe zulässig/Projekt/Reserve/ja-nein.
#[test]
fn baurecht_nachweis_tabelle() {
+27 -15
View File
@@ -102,7 +102,12 @@ pub fn level_with_template(l: &DrawingLevel, t: &ViewTemplate) -> DrawingLevel {
macro_rules! take {
($($f:ident),*) => { $(if t.$f.is_some() { l.$f = t.$f.clone(); })* };
}
take!(cut_height, view_top, view_bottom, view_depth, shadows, hidden_lines, sketch, cut_hatch, floor_finish, show_terrain, model_view_option_id, renovation_filter, renovation_phase, design_options);
take!(cut_height, view_top, view_bottom, view_depth, shadows, hidden_lines, sketch, cut_hatch, floor_finish, show_terrain, model_view_option_id, renovation_filter, renovation_phase);
// [272] Wahl der Vorlage (Kombination oder freie Wahl) ersetzt die der Ebene als Ganzes.
if t.design_options.is_some() || t.design_option_combination.is_some() {
l.design_options = t.design_options.clone();
l.design_option_combination = t.design_option_combination.clone();
}
l
}
@@ -110,20 +115,26 @@ pub fn level_with_template(l: &DrawingLevel, t: &ViewTemplate) -> DrawingLevel {
/// der Vorlage und ihre Strichstärken-Skalierung. Ohne verknüpfte Vorlage unverändert (geliehen).
pub fn snapshot_project<'a>(p: &'a Project, snap: &ViewSnapshot) -> Cow<'a, Project> {
let t = snapshot_template(p, snap);
// [272] Variantenkombination des Ausschnitts (über der der Ebene und der Vorlage).
let opts = snap.design_options.as_ref().filter(|m| !m.is_empty());
// [272] Variantenkombination des Ausschnitts (über der der Ebene und der Vorlage; benannte Kombination vor freier Wahl).
let opts = crate::design_options::stored_choice(p, snap.design_option_combination.as_deref(), snap.design_options.as_ref()).filter(|m| !m.is_empty());
if t.is_none() && opts.is_none() {
return Cow::Borrowed(p);
}
let mut q = p.clone();
for l in q.drawing_levels.iter_mut().filter(|l| l.id == snap.active_level_id) {
if let Some(t) = t {
*l = level_with_template(l, t);
for i in 0..q.drawing_levels.len() {
if q.drawing_levels[i].id != snap.active_level_id {
continue;
}
if let Some(o) = opts {
let mut m = l.design_options.clone().unwrap_or_default();
if let Some(t) = t {
q.drawing_levels[i] = level_with_template(&q.drawing_levels[i], t);
}
if let Some(o) = &opts {
let l = &q.drawing_levels[i];
let mut m = crate::design_options::stored_choice(&q, l.design_option_combination.as_deref(), l.design_options.as_ref()).unwrap_or_default();
m.extend(o.iter().map(|(k, v)| (k.clone(), v.clone())));
let l = &mut q.drawing_levels[i];
l.design_options = Some(m);
l.design_option_combination = None;
}
}
if let Some(t) = t.filter(|t| t.scale_line_weights.is_some()) {
@@ -134,13 +145,14 @@ pub fn snapshot_project<'a>(p: &'a Project, snap: &ViewSnapshot) -> Cow<'a, Proj
/// [272] Der Ausschnitt eines Viewports mit dessen eigener Variantenkombination (über der des Ausschnitts); ohne
/// eigene Wahl unverändert.
pub fn viewport_snapshot<'a>(snap: &'a ViewSnapshot, vp: &LayoutViewport) -> Cow<'a, ViewSnapshot> {
match vp.design_options.as_ref().filter(|m| !m.is_empty()) {
pub fn viewport_snapshot<'a>(p: &Project, snap: &'a ViewSnapshot, vp: &LayoutViewport) -> Cow<'a, ViewSnapshot> {
match crate::design_options::stored_choice(p, vp.design_option_combination.as_deref(), vp.design_options.as_ref()).filter(|m| !m.is_empty()) {
Some(o) => {
let mut s = snap.clone();
let mut m = s.design_options.clone().unwrap_or_default();
m.extend(o.iter().map(|(k, v)| (k.clone(), v.clone())));
let mut m = crate::design_options::stored_choice(p, snap.design_option_combination.as_deref(), snap.design_options.as_ref()).unwrap_or_default();
m.extend(o);
s.design_options = Some(m);
s.design_option_combination = None;
Cow::Owned(s)
}
None => Cow::Borrowed(snap),
@@ -171,7 +183,7 @@ pub fn viewport_args(p: &Project, snap: &ViewSnapshot, scale: f64, mono: bool) -
renovation: snap.renovation_filter.clone().filter(|s| !s.is_empty()),
renovation_phase: snap.renovation_phase.clone().filter(|s| !s.is_empty()),
// [272] Variantenkombination des Ausschnitts (über der der Ebene).
design_options: snap.design_options.iter().flatten().map(|(k, v)| (k.clone(), v.clone())).collect(),
design_options: crate::design_options::stored_choice(p, snap.design_option_combination.as_deref(), snap.design_options.as_ref()).into_iter().flatten().collect(),
};
a.apply_model_view(p);
a
@@ -193,7 +205,7 @@ pub fn viewport_maps(p: &Project, layout: &Layout) -> Vec<VpMap> {
let mut out = Vec::new();
for vp in &layout.viewports {
let Some(snap) = snaps.iter().find(|s| s.id == vp.snapshot_id) else { continue };
let snap = viewport_snapshot(snap, vp);
let snap = viewport_snapshot(p, snap, vp);
let snap = snap.as_ref();
if !(vp.width_mm > 0.0 && vp.height_mm > 0.0 && vp.x_mm.is_finite() && vp.y_mm.is_finite()) {
continue;
@@ -256,7 +268,7 @@ pub fn snapshot_buf(p: &Project, snap: &ViewSnapshot, scale: f64, shadows: Optio
pub fn doc3d_buf(p: &Project, snap: &ViewSnapshot, scale: f64) -> Option<Vec<u8>> {
let show: HashSet<&String> = snap.layer_visibility.iter().filter(|(_, v)| **v).map(|(k, _)| k).collect();
let invisible: Vec<String> = candidate_codes(p).into_iter().filter(|c| !show.contains(c)).collect();
let text = crate::plan::axo::snapshot_text(snap, &invisible);
let text = crate::plan::axo::snapshot_text(p, snap, &invisible);
let buf = crate::plan::axo::axo_plan_buf(p, &[f64::from(u8::from(snapshot_mono(p, snap))), scale], &text).ok()?;
let v = crate::plan::buf::View::parse(&buf)?;
if v.prims()?.is_empty() {
+15 -3
View File
@@ -23,7 +23,9 @@
// mit --phase <Etappe> (Name oder id); auch für axo, model3d und kennzahlen [271]
// --options "Dachform=B,Fassade=A" Variantenkombination (Satz=Variante, Namen oder ids;
// fehlende Sätze: Hauptvariante); für alle Ausgaben (plan, section, elevation, axo,
// model3d, kennzahlen, dxf, ifc, obj …); `designoptions` vergleicht alle Kombinationen [272]
// model3d, kennzahlen, dxf, ifc, obj …); `designoptions` vergleicht die gespeicherten Kombinationen
// (--all: alle Kombinationen der Sätze) [272]
// --combination "Studie 1" gespeicherte benannte Kombination (Name oder id), für alle Ausgaben [272]
// --hide <Code|Name,…> blendet Klassen aus (z. B. --hide "Schatten,Auto-Bemassung") [180]
// --snapshot <Name|id> übernimmt Geschoss, Massstab, Vorlage und Sichtbarkeit eines Ausschnitts [207]
// dossier-cli <projekt.obp> axo [--view southeast|southwest|northeast|northwest|iso|…] [--projection iso|military|military30]
@@ -150,6 +152,8 @@ import {
renovationFilterList,
parseCombination,
designOptionSets,
designOptionCombinations,
combinationChoice,
projectWithCombination,
compareDesignOptions,
compareDesignOptionsCsv,
@@ -1099,6 +1103,14 @@ async function execute(project: Project, file: string, command: string, rest: st
}
project = projectWithCombination(project, combo);
}
// [272] `--combination "Studie 1"`: benannte Kombination (Name oder id) gilt für alle Ausgaben (`designoptions` listet sie nur).
const combSpec = args.flags.get("combination");
if (combSpec && combSpec !== "true" && command !== "designoptions") {
const key = combSpec.trim().toLowerCase();
const found = designOptionCombinations(project).find((c) => c.id.toLowerCase() === key) ?? designOptionCombinations(project).find((c) => c.name.trim().toLowerCase() === key);
if (!found) fail(`Kombination nicht gefunden: ${combSpec} (vorhanden: ${designOptionCombinations(project).map((c) => c.name).join(", ") || "keine"})`);
project = projectWithCombination(project, combinationChoice(project, found));
}
// [257] `bench --context`: vorher synthetische Kontext-Importe (Kataster, Höhenlinien, Gebäudenetze) ins Projekt laden.
const contextRows: Array<[string, number]> = [];
if (command === "bench" && args.flags.has("context")) {
@@ -1367,8 +1379,8 @@ async function execute(project: Project, file: string, command: string, rest: st
const ren = renovationFlags(project, args)?.renovation ?? "";
const stem = `${exportProjectName(project) || "projekt"}-varianten`;
if ((args.flags.get("format") ?? "json") === "csv") {
out(args, compareDesignOptionsCsv(project, ["Kombination", "GF m2", "HNF m2", "GV m3", "Fussabdruck m2", "AZ", "UEZ", "Kosten CHF"], ren), `${stem}.csv`);
} else out(args, JSON.stringify(compareDesignOptions(project, ren), null, 2), `${stem}.json`);
out(args, compareDesignOptionsCsv(project, ["Kombination", "GF m2", "HNF m2", "GV m3", "Fussabdruck m2", "AZ", "UEZ", "Kosten CHF"], ren, args.flags.has("all")), `${stem}.csv`);
} else out(args, JSON.stringify(compareDesignOptions(project, ren, args.flags.has("all")), null, 2), `${stem}.json`);
return 0;
}
case "raumprogramm": {
+1 -1
View File
@@ -174,7 +174,7 @@ export type LoadFileResult =
/** Wurzel-Abfragen des Kerns (`queries.rs::run_root`). */
export type RootQueryName = "penRebakeOps" | "penDeleteOps" | "penSeedOps" | "standardsMergeOps" | "standardsUpdatePlan" | "standardsUpdateOps" | "folderPdfPages" | "layoutTitleBlock" | "translatePatch" | "translateOps" | "selectionFilterPatch"
// [272] Varianten (`design_options.rs`)
| "designOptionAcceptOps" | "designOptionDeleteOps" | "designOptionAssignOps" | "designOptionCopyOps";
| "designOptionAcceptOps" | "designOptionDeleteOps" | "designOptionAssignOps" | "designOptionCopyOps" | "designOptionCombinationDeleteOps";
/** Abfragen des Kerns (`queries.rs`). */
export type QueryName =
+3 -1
View File
@@ -134,6 +134,8 @@ export {
parseCombination, showsInCombination, designOptionLabel, designOptionSelection, designOptionIds, commonDesignOption, parseTarget, designOptionTargets,
assignDesignOptionOps, copyToDesignOptionOps, acceptDesignOptionOps, deleteDesignOptionOps, nextOptionName, addDesignOptionSetOps, addDesignOptionOps,
renameDesignOptionSetOps, renameDesignOptionOps, setPrimaryOptionOps, setLevelCombinationOps, compareDesignOptions, compareDesignOptionsCsv, projectWithCombination,
designOptionCombinations, combinationChoice, storedChoice, levelCombinationState, combinationNameFor, assignCombinationOps, viewportCombinationPatch, nextCombinationName, addCombinationOps,
renameCombinationOps, setCombinationChoiceOps, deleteCombinationOps,
} from "../model/designOptions";
export type { Combination, DesignOptionCompareRow, DesignOptionCollection } from "../model/designOptions";
export type { Combination, CombinationState, DesignOptionCompareRow, DesignOptionCollection } from "../model/designOptions";
export { buildVariantenSampleProject } from "../model/sampleProjectVarianten";
+1 -1
View File
@@ -234,7 +234,7 @@ async function renderPage(
const template = snapshotTemplate(project, snap);
// [266] 3D-Ausschnitt: 3D-Dokument aus dem Kern (`viewportSnapshotPlan`).
// [272] Variantenkombination des Ausschnitts/Viewports.
const dopts = viewportDesignOptions(snap, vp);
const dopts = viewportDesignOptions(project, snap, vp);
const planOf = (visible: Set<string>) => (isDoc3dSnapshot(snap) ? viewportSnapshotPlan(project, snap, visible, scaleN, true, vp) : viewportLevelPlan(project, snap.activeLevelId, visible, snap.detail, scaleN, true, snapshotMono(project, snap), ruleIds, template, snap.modelViewOptionId, dopts));
// [208] Eigene Bildmitte (Plakat): Ausschnitt um die Mitte; was darüber hinausgeht, schneidet der Rahmen ab.
const centered = viewportCenterBounds(vp, scaleN);
+3 -3
View File
@@ -55,10 +55,10 @@ describe("Tabellen auf dem Blatt ([111])", () => {
it("alle Quellen liefern Primitive; Katalog nennt die Spalten", () => {
const cat = tableCatalog(sampleProject);
expect(Object.keys(cat.sources).sort()).toEqual(["areas", "costs", "earthworks", "elements", "openings", "roomBook", "rooms", "siteProof"]);
const p = withTables((["openings", "areas", "rooms", "elements", "earthworks", "roomBook", "costs", "siteProof"] as const).map((source) => table({ id: source, source })));
expect(Object.keys(cat.sources).sort()).toEqual(["areas", "costs", "designOptionCompare", "earthworks", "elements", "openings", "roomBook", "rooms", "siteProof"]);
const p = withTables((["openings", "areas", "rooms", "elements", "earthworks", "roomBook", "costs", "siteProof", "designOptionCompare"] as const).map((source) => table({ id: source, source })));
const out = sheetTables(p, "L1");
expect(out.map((o) => o.id)).toEqual(["openings", "areas", "rooms", "elements", "earthworks", "roomBook", "costs", "siteProof"]);
expect(out.map((o) => o.id)).toEqual(["openings", "areas", "rooms", "elements", "earthworks", "roomBook", "costs", "siteProof", "designOptionCompare"]);
for (const o of out) expect(o.prims.some((x) => x.k === "text")).toBe(true);
});
+1 -1
View File
@@ -39,7 +39,7 @@ interface Catalog {
valueKeys: string[];
}
export const TABLE_SOURCES: readonly LayoutTableSource[] = ["openings", "areas", "rooms", "elements", "earthworks", "roomBook", "costs", "siteProof"];
export const TABLE_SOURCES: readonly LayoutTableSource[] = ["openings", "areas", "rooms", "elements", "earthworks", "roomBook", "costs", "siteProof", "designOptionCompare"];
export function tableSourceLabel(s: LayoutTableSource): string {
return t(`sheetTable.source.${s}`);
+21
View File
@@ -4784,6 +4784,27 @@ export const de = {
"designOption.copy": "Kopieren in …",
"designOption.compare.show": "Vergleich öffnen",
"designOption.compare.hide": "Vergleich schliessen",
"designOption.combinations.title": "Kombinationen",
"designOption.combinations.empty": "Noch keine gespeicherte Kombination. Wähle oben je Satz eine Variante und speichere die Wahl mit „Als Kombination speichern …“.",
"designOption.current": "Aktuell",
"designOption.customName": "Eigene",
"designOption.custom": "Eigene: {combination}",
"designOption.combination": "Kombination",
"designOption.combination.save": "Als Kombination speichern …",
"designOption.combination.name": "Name der Kombination",
"designOption.combination.defaultName": "Studie",
"designOption.combination.assign": "Dieser Ansicht zuweisen",
"designOption.combination.assigned": "Zugewiesen",
"designOption.combination.delete": "Kombination löschen",
"designOption.combination.deleteMessage": "Die Kombination „{name}“ wird gelöscht. Ansichten und Viewports, die sie zeigen, behalten ihre aktuelle Wahl als „Eigene“. Die Varianten selbst bleiben.",
"designOption.combination.deleteConfirm": "Löschen",
"designOption.compare.all": "Alle Kombinationen der Sätze zeigen",
"designOption.compare.col.gf": "GF m²",
"designOption.compare.col.hnf": "HNF m²",
"designOption.compare.col.gv": "GV m³",
"designOption.compare.col.az": "AZ",
"designOption.compare.col.uez": "ÜZ",
"sheetTable.source.designOptionCompare": "Variantenvergleich",
"resources.tab.designOptions": "Varianten",
"cmd.designOption.label": "Variante zuweisen …",
"cmd.designOption.prompt": "Ziel-Variante (z. B. Dachform=B, Variantenname oder Nummer; H = Hauptmodell)",
+21
View File
@@ -4770,6 +4770,27 @@ export const en: Record<TranslationKey, string> = {
"designOption.copy": "Copy to …",
"designOption.compare.show": "Open comparison",
"designOption.compare.hide": "Close comparison",
"designOption.combinations.title": "Combinations",
"designOption.combinations.empty": "No saved combination yet. Pick one option per set above and save the choice with “Save as combination …”.",
"designOption.current": "Current",
"designOption.customName": "Custom",
"designOption.custom": "Custom: {combination}",
"designOption.combination": "Combination",
"designOption.combination.save": "Save as combination …",
"designOption.combination.name": "Combination name",
"designOption.combination.defaultName": "Study",
"designOption.combination.assign": "Assign to this view",
"designOption.combination.assigned": "Assigned",
"designOption.combination.delete": "Delete combination",
"designOption.combination.deleteMessage": "The combination “{name}” will be deleted. Views and viewports that show it keep their current choice as “Custom”. The options themselves stay.",
"designOption.combination.deleteConfirm": "Delete",
"designOption.compare.all": "Show all combinations of the sets",
"designOption.compare.col.gf": "GFA m²",
"designOption.compare.col.hnf": "NUA m²",
"designOption.compare.col.gv": "GV m³",
"designOption.compare.col.az": "AZ",
"designOption.compare.col.uez": "ÜZ",
"sheetTable.source.designOptionCompare": "Design option comparison",
"resources.tab.designOptions": "Design options",
"cmd.designOption.label": "Assign design option …",
"cmd.designOption.prompt": "Target option (e.g. Roof=B, option name or number; H = main model)",
+100 -2
View File
@@ -7,7 +7,11 @@ import {
acceptDesignOptionOps, addDesignOptionOps, addDesignOptionSetOps, assignDesignOptionOps, combinationLabel, combinationSpec, combinationSuffix, commonDesignOption,
compareDesignOptions, compareDesignOptionsCsv, copyToDesignOptionOps, deleteDesignOptionOps, levelCombination, nextOptionName, parseCombination, projectWithCombination,
resolveCombination, setLevelCombinationOps, setPrimaryOptionOps, showsInCombination,
addCombinationOps, assignCombinationOps, combinationChoice, deleteCombinationOps, designOptionCombinations, levelCombinationState, renameCombinationOps, setCombinationChoiceOps,
storedChoice,
} from "./designOptions";
import { viewportDesignOptions } from "../plan/viewportPlan";
import { viewportVariantSuffix } from "./posterTemplates";
import { buildVariantenSampleProject } from "./sampleProjectVarianten";
import { sampleProject } from "./sampleProject";
import { generatePlan } from "../plan/generatePlan";
@@ -89,13 +93,13 @@ describe("[272] Varianten", () => {
it("Vergleich: alle Kombinationen, Hauptkombination zuerst, CSV mit Kopf", () => {
const p = buildVariantenSampleProject();
const rows = withDocument(p, () => compareDesignOptions(p));
const rows = withDocument(p, () => compareDesignOptions(p, "", true));
expect(rows).toHaveLength(4);
expect(rows[0].primary).toBe(true);
expect(rows[0].label).toBe("Dachform A Flachdach, Fassade A Lochfenster");
expect(new Set(rows.map((r) => r.gv)).size).toBeGreaterThan(1);
expect(rows.every((r) => Number.isFinite(r.cost) && r.cost > 0)).toBe(true);
const csv = withDocument(p, () => compareDesignOptionsCsv(p, ["Kombination", "GF", "HNF", "GV", "Fussabdruck", "AZ", "ÜZ", "Kosten"]));
const csv = withDocument(p, () => compareDesignOptionsCsv(p, ["Kombination", "GF", "HNF", "GV", "Fussabdruck", "AZ", "ÜZ", "Kosten"], "", true));
expect(csv.split("\n")[0]).toBe("Kombination;GF;HNF;GV;Fussabdruck;AZ;ÜZ;Kosten");
expect(csv.trim().split("\n")).toHaveLength(5);
expect(compareDesignOptions(sampleProject)).toEqual([]);
@@ -135,3 +139,97 @@ describe("[272] Varianten", () => {
expect(projectWithCombination(p, {})).toBe(p);
});
});
describe("[272] Benannte Variantenkombinationen", () => {
it("Beispiel hat zwei Kombinationen; Vergleich je Kombination (Name als Zeilentitel), alle über `all`", () => {
const p = buildVariantenSampleProject();
expect(designOptionCombinations(p).map((c) => c.name)).toEqual(["Studie 1 Flachdach/Lochfenster", "Studie 2 Satteldach/Bandfenster"]);
const rows = withDocument(p, () => compareDesignOptions(p));
expect(rows.map((r) => r.label)).toEqual(["Studie 1 Flachdach/Lochfenster", "Studie 2 Satteldach/Bandfenster"]);
expect(rows[0].primary).toBe(true);
expect(rows[1].detail).toBe("Dachform B Satteldach, Fassade B Bandfenster");
expect(rows[0].gv).not.toBeCloseTo(rows[1].gv, 3);
const csv = withDocument(p, () => compareDesignOptionsCsv(p, ["Kombination", "GF", "HNF", "GV", "Fussabdruck", "AZ", "ÜZ", "Kosten"]));
expect(csv.split("\n")[1].startsWith("Studie 1 Flachdach/Lochfenster;")).toBe(true);
expect(withDocument(p, () => compareDesignOptions(p, "", true))).toHaveLength(4);
});
it("Speichern, umbenennen, Wahl ändern, löschen (ein Undo-Schritt im Kern); fehlende Sätze zeigen die Hauptvariante", () => {
const p0 = buildVariantenSampleProject();
const base = { ...p0, designOptionCombinations: undefined } as typeof p0;
delete (base as { designOptionCombinations?: unknown }).designOptionCombinations;
const { ops, id } = addCombinationOps(base, "Studie A", { dachform: "b" });
let p = applyOps(base, ops);
expect(p.designOptionCombinations?.[0]).toMatchObject({ id, name: "Studie A", choices: { dachform: "b", fassade: "a" } });
p = applyOps(p, renameCombinationOps(p, id, "Satteldach"));
p = applyOps(p, setCombinationChoiceOps(p, id, "fassade", "b"));
expect(combinationChoice(p, p.designOptionCombinations![0])).toEqual({ dachform: "b", fassade: "b" });
expect(setCombinationChoiceOps(p, id, "fassade", "zz")).toHaveLength(0);
// Eine Kombination mit fehlendem Satz zeigt dort die Hauptvariante.
const miss = { ...p, designOptionCombinations: [{ id: "m", name: "M", choices: { dachform: "b" } }] };
expect(combinationChoice(miss, miss.designOptionCombinations[0])).toEqual({ dachform: "b", fassade: "a" });
// Zuweisen an eine Ebene, danach Löschen räumt den Verweis auf.
p = applyOps(p, assignCombinationOps(p, "eg", id));
const eg = () => p.drawingLevels.find((l) => l.id === "eg")!;
expect(eg().designOptionCombination).toBe(id);
expect(levelCombinationState(p, eg())).toMatchObject({ kind: "named", name: "Satteldach", assigned: true });
p = withDocument(p, () => applyOps(p, deleteCombinationOps(p, id)));
expect(p.designOptionCombinations).toEqual([]);
expect(eg()).not.toHaveProperty("designOptionCombination");
});
it("Rangfolge: Kombination vor freier Wahl; „Eigene“ nach Änderung; gleiche Wahl erkennt den Namen", () => {
const p0 = buildVariantenSampleProject();
// Studie 2 zugewiesen ⇒ Dach B und Fassade B im Grundriss/Wahl.
let p = applyOps(p0, assignCombinationOps(p0, "eg", "studie-2"));
expect(storedChoice(p, p.drawingLevels.find((l) => l.id === "eg"))).toEqual({ dachform: "b", fassade: "b" });
expect(levelCombination(p, p.drawingLevels.find((l) => l.id === "eg"))).toEqual({ dachform: "b", fassade: "b" });
const ids = planIds(p, "eg");
expect(ids.has("O-band")).toBe(true);
expect(ids.has("O2")).toBe(false);
// Wahl der zugewiesenen Kombination ändern: der Grundriss folgt sofort (kein Cache-Rest).
const edited = applyOps(p, setCombinationChoiceOps(p, "studie-2", "fassade", "a"));
expect(planIds(edited, "eg").has("O2")).toBe(true);
expect(planIds(edited, "eg").has("O-band")).toBe(false);
// Eine Wahländerung löst den Verweis: „Eigene“ (Fassade A + Dach B passt zu keiner gespeicherten Kombination).
p = applyOps(p, setLevelCombinationOps(p, "eg", "fassade", "a"));
const l = p.drawingLevels.find((x) => x.id === "eg")!;
expect(l).not.toHaveProperty("designOptionCombination");
expect(l.designOptions).toEqual({ dachform: "b" });
expect(levelCombinationState(p, l).kind).toBe("custom");
// Zurück zur Wahl von Studie 2 ohne Verweis: gleicher Name (nicht zugewiesen).
p = applyOps(p, setLevelCombinationOps(p, "eg", "fassade", "b"));
expect(levelCombinationState(p, p.drawingLevels.find((x) => x.id === "eg")!)).toMatchObject({ kind: "named", name: "Studie 2 Satteldach/Bandfenster", assigned: false });
// Verweis lösen behält die Wahl als freie Wahl.
const q = applyOps(p0, [...assignCombinationOps(p0, "eg", "studie-2"), ...[]]);
const r = applyOps(q, assignCombinationOps(q, "eg", null));
expect(r.drawingLevels.find((x) => x.id === "eg")?.designOptions).toEqual({ dachform: "b", fassade: "b" });
// Unbekannte Kombination: keine Ops.
expect(assignCombinationOps(p0, "eg", "weg")).toHaveLength(0);
});
it("Viewport/Ausschnitt: Kombination, Titelzusatz = Kombinationsname", () => {
const p = buildVariantenSampleProject();
const snap = { id: "s", name: "EG", activeLevelId: "eg" } as never;
expect(viewportDesignOptions(p, snap, { designOptionCombination: "studie-2" })).toEqual({ dachform: "b", fassade: "b" });
// Viewport vor Ausschnitt; freie Wahl des Viewports wird bei Kombination übergangen.
expect(viewportDesignOptions(p, { designOptionCombination: "studie-1" }, { designOptions: { dachform: "b" }, designOptionCombination: "studie-1" })).toEqual({ dachform: "a", fassade: "a" });
const q = { ...p, viewSnapshots: [{ id: "s", name: "EG", activeLevelId: "eg", designOptionCombination: "studie-1" }] } as never as typeof p;
const vp = { id: "v", snapshotId: "s", designOptionCombination: "studie-2" } as never;
expect(viewportVariantSuffix(q, vp)).toBe("Studie 2 Satteldach/Bandfenster");
expect(viewportVariantSuffix(q, { id: "v2", snapshotId: "s" } as never)).toBe("Studie 1 Flachdach/Lochfenster");
expect(viewportVariantSuffix({ ...q, viewSnapshots: [{ id: "s", name: "EG", activeLevelId: "eg" }] } as never, { id: "v2", snapshotId: "s" } as never)).toBe("");
expect(viewportVariantSuffix(q, { id: "v3", snapshotId: "s", designOptions: { dachform: "b", fassade: "b" } } as never)).toBe("Studie 2 Satteldach/Bandfenster");
});
it("CLI-Kombination: benannte Kombination wird Hauptkombination, Verweise lösen sich auf", () => {
const p0 = buildVariantenSampleProject();
const p = applyOps(p0, assignCombinationOps(p0, "eg", "studie-2"));
const q = projectWithCombination(p, combinationChoice(p, p.designOptionCombinations![0]));
expect(q.designOptionSets?.map((s) => s.primary)).toEqual(["a", "a"]);
expect(q.drawingLevels.find((l) => l.id === "eg")).not.toHaveProperty("designOptionCombination");
expect(q.drawingLevels.find((l) => l.id === "eg")).not.toHaveProperty("designOptions");
const q2 = projectWithCombination(p, { dachform: "a" });
expect(q2.drawingLevels.find((l) => l.id === "eg")?.designOptions).toEqual({ fassade: "b" });
});
});
+143 -18
View File
@@ -5,7 +5,7 @@
import type { CoreOp } from "../core/ops";
import { documentFor } from "../core/document";
import { patchItem, setField } from "../core/opsBuild";
import type { DesignOption, DesignOptionRef, DesignOptionSet, DrawingLevel, Project } from "./types";
import type { DesignOption, DesignOptionCombination, DesignOptionRef, DesignOptionSet, DrawingLevel, Project } from "./types";
/** Listen, deren Elemente einer Variante angehören können (gleich wie `design_options::COLLECTIONS`). */
export const DESIGN_OPTION_COLLECTIONS = ["walls", "openings", "ceilings", "roofs", "stairs", "columns", "extrudedSolids", "rooms", "drawings2d"] as const;
@@ -40,9 +40,43 @@ export function resolveCombination(project: Project, ...stored: (Combination | u
return out;
}
/** Kombination einer Ebene (`DrawingLevel.designOptions` über den Hauptvarianten). */
/** Benannte Kombinationen des Projekts ([272] Nachtrag, wie Archicads „Design Option Combinations“). */
export function designOptionCombinations(project: Project): readonly DesignOptionCombination[] {
return project.designOptionCombinations ?? [];
}
/** Vollständige Wahl einer benannten Kombination: je Satz die gespeicherte Variante, sonst (fehlender Satz, gelöschte Variante) die Hauptvariante. */
export function combinationChoice(project: Project, c: DesignOptionCombination): Combination {
return resolveCombination(project, c.choices);
}
/**
* Rangfolge der gespeicherten Wahl eines Objekts (Ebene, Vorlage, Ausschnitt, Viewport; Kern `design_options::stored_choice`):
* verweist es auf eine vorhandene benannte Kombination, gilt diese vollständig (fehlende Sätze ⇒ Hauptvariante) und die freie
* Wahl `designOptions` desselben Objekts wird übergangen; sonst (kein oder unbekannter Verweis) die freie Wahl; `undefined` ohne Wahl.
*/
export function storedChoice(project: Project, holder: { designOptionCombination?: string | null; designOptions?: Combination | null } | null | undefined): Combination | undefined {
const c = holder?.designOptionCombination ? designOptionCombinations(project).find((x) => x.id === holder.designOptionCombination) : undefined;
if (c) return combinationChoice(project, c);
return holder?.designOptions ?? undefined;
}
/** Kombination einer Ebene (`DrawingLevel`: benannte Kombination bzw. freie Wahl über den Hauptvarianten). */
export function levelCombination(project: Project, level: DrawingLevel | undefined): Combination {
return resolveCombination(project, level?.designOptions);
return resolveCombination(project, storedChoice(project, level));
}
/** Zustand der Kombination einer Ansicht wie in Archicad: benannte Kombination (`named`; auch bei gleicher Wahl wie eine gespeicherte) oder „Eigene“. */
export type CombinationState = { kind: "named"; id: string; name: string; assigned: boolean } | { kind: "custom" };
export function levelCombinationState(project: Project, level: DrawingLevel | undefined): CombinationState {
const ref = level?.designOptionCombination ? designOptionCombinations(project).find((x) => x.id === level.designOptionCombination) : undefined;
if (ref) return { kind: "named", id: ref.id, name: ref.name, assigned: true };
const cur = levelCombination(project, level);
const same = (a: Combination, b: Combination) => Object.keys({ ...a, ...b }).every((k) => a[k] === b[k]);
const hit = designOptionCombinations(project).find((c) => same(combinationChoice(project, c), cur));
if (hit) return { kind: "named", id: hit.id, name: hit.name, assigned: false };
return { kind: "custom" };
}
/** Lesbarer Name „Dachform B, Fassade A“ (nur Sätze mit Varianten). */
@@ -55,6 +89,12 @@ export function combinationLabel(project: Project, c: Combination): string {
return parts.join(", ");
}
/** Name einer benannten Kombination mit genau dieser Wahl (erste in der Liste); sonst `undefined`. */
export function combinationNameFor(project: Project, c: Combination): string | undefined {
const full = resolveCombination(project, c);
return designOptionCombinations(project).find((x) => Object.entries(combinationChoice(project, x)).every(([k, v]) => full[k] === v))?.name;
}
/** Kurzname nur der Varianten, die von der Hauptvariante abweichen (Titelzusatz im Blatt); leer = Hauptkombination. */
export function combinationSuffix(project: Project, c: Combination | undefined | null): string {
if (!c) return "";
@@ -233,26 +273,103 @@ export function setPrimaryOptionOps(project: Project, setId: string, optionId: s
return [setField("designOptionSets", sets.map((s) => (s.id === setId ? { ...s, primary: optionId } : s)))];
}
/** Ops: Kombination der Ebene setzen (eine Variante je Satz; die Hauptvariante wird nicht gespeichert). */
/** Ops: Wahl der Ebene setzen (eine Variante je Satz; die Hauptvariante wird nicht gespeichert). Verweist die Ebene auf eine benannte
* Kombination, wird deren Wahl zur freien Wahl der Ebene (Verweis weg, Zustand „Eigene“) und dann der Satz geändert. */
export function setLevelCombinationOps(project: Project, levelId: string, setId: string, optionId: string): CoreOp[] {
const s = designOptionSets(project).find((x) => x.id === setId);
if (!s || !s.options.some((o) => o.id === optionId)) return [];
return patchItem(project, "drawingLevels", levelId, (l) => {
const m: Combination = { ...(l.designOptions ?? {}) };
const m: Combination = { ...freeOf(project, l) };
if (primaryOption(s) === optionId) delete m[setId];
else m[setId] = optionId;
const next = { ...l, designOptions: m };
if (!Object.keys(m).length) delete (next as { designOptions?: Combination }).designOptions;
return withFree(l, m);
});
}
/** Freie Wahl ohne Hauptvarianten, die die Ebene wirksam zeigt (benannte Kombination aufgelöst). */
function freeOf(project: Project, l: DrawingLevel): Combination {
const eff = storedChoice(project, l) ?? {};
const prim = resolveCombination(project);
const out: Combination = {};
for (const [k, v] of Object.entries(eff)) if (prim[k] !== v) out[k] = v;
return out;
}
/** Die Ebene mit freier Wahl `m` und ohne Verweis auf eine benannte Kombination. */
function withFree(l: DrawingLevel, m: Combination): DrawingLevel {
const next = { ...l } as DrawingLevel;
delete next.designOptionCombination;
if (Object.keys(m).length) next.designOptions = m;
else delete next.designOptions;
return next;
}
// ── Benannte Kombinationen ──────────────────────────────────────────────────
/** Ops: Ebene `levelId` zeigt die benannte Kombination `combinationId` (`null` = Verweis lösen: die Wahl bleibt als freie Wahl, „Eigene“). */
export function assignCombinationOps(project: Project, levelId: string, combinationId: string | null): CoreOp[] {
if (combinationId !== null && !designOptionCombinations(project).some((c) => c.id === combinationId)) return [];
return patchItem(project, "drawingLevels", levelId, (l) => {
if (combinationId === null) return withFree(l, freeOf(project, l));
const next = { ...l, designOptionCombination: combinationId } as DrawingLevel;
delete next.designOptions;
return next;
});
}
/** Ops: Layout-Viewport-Felder für die Wahl einer Kombination (`""` = wie Ausschnitt): Verweis setzen, freie Wahl des Viewports entfällt. */
export function viewportCombinationPatch(combinationId: string): { designOptionCombination?: string; designOptions?: undefined } {
return combinationId ? { designOptionCombination: combinationId, designOptions: undefined } : { designOptionCombination: undefined };
}
/** Nächster freier Name „Kombination n“ nach Muster `base`. */
export function nextCombinationName(project: Project, base: string): string {
const used = new Set(designOptionCombinations(project).map((c) => c.name.trim().toLowerCase()));
for (let n = designOptionCombinations(project).length + 1; ; n++) {
const name = `${base} ${n}`;
if (!used.has(name.toLowerCase())) return name;
}
}
/** Ops: neue benannte Kombination `name` mit der Wahl `choices` (ganz aufgelöst gespeichert, je Satz eine Variante). Gibt die neue Id zurück. */
export function addCombinationOps(project: Project, name: string, choices: Combination): { ops: CoreOp[]; id: string } {
const list = designOptionCombinations(project);
const id = freeId(list.map((c) => c.id), "komb-");
const full = resolveCombination(project, choices);
return { ops: [setField("designOptionCombinations", [...list, { id, name: name.trim() || id, choices: full }])], id };
}
/** Ops: Kombination umbenennen. */
export function renameCombinationOps(project: Project, id: string, name: string): CoreOp[] {
const list = designOptionCombinations(project);
if (!list.some((c) => c.id === id)) return [];
return [setField("designOptionCombinations", list.map((c) => (c.id === id ? { ...c, name } : c)))];
}
/** Ops: Wahl eines Satzes in einer benannten Kombination ändern. */
export function setCombinationChoiceOps(project: Project, id: string, setId: string, optionId: string): CoreOp[] {
const list = designOptionCombinations(project);
const s = designOptionSets(project).find((x) => x.id === setId);
if (!list.some((c) => c.id === id) || !s || !s.options.some((o) => o.id === optionId)) return [];
return [setField("designOptionCombinations", list.map((c) => (c.id === id ? { ...c, choices: { ...c.choices, [setId]: optionId } } : c)))];
}
/** Ops: Kombination löschen samt Verweisen an Ebenen, Vorlagen, Ausschnitten und Viewports (Kern; ein Undo-Schritt). */
export function deleteCombinationOps(project: Project, id: string): CoreOp[] {
return documentFor(project).queryRoot<CoreOp[]>("designOptionCombinationDeleteOps", JSON.stringify({ id }));
}
// ── Vergleich ───────────────────────────────────────────────────────────────
/** Zeile der Vergleichstabelle (Kern `design_options::CompareRow`). */
export interface DesignOptionCompareRow {
choice: Combination;
/** Zeilentitel: Name der benannten Kombination, sonst die Wahl als Text. */
label: string;
/** Id der benannten Kombination (fehlt in Zeilen aus dem Kreuzprodukt). */
combination?: string | null;
/** Wahl je Satz als Text („Dachform B, Fassade A“). */
detail: string;
primary: boolean;
gf: number;
hnf: number;
@@ -263,16 +380,20 @@ export interface DesignOptionCompareRow {
cost: number;
}
/** Kennzahlen und Kosten je Kombination (Hauptkombination zuerst); `renovation`: Umbau-Zustand (Filter-Id). */
export function compareDesignOptions(project: Project, renovation = ""): DesignOptionCompareRow[] {
/**
* Kennzahlen und Kosten je gespeicherte benannte Kombination (Name als Zeilentitel); ohne gespeicherte Kombination, oder mit
* `all`, je Kombination der Sätze (Hauptkombination zuerst). `renovation`: Umbau-Zustand (Filter-Id).
*/
export function compareDesignOptions(project: Project, renovation = "", all = false): DesignOptionCompareRow[] {
if (!designOptionSets(project).length) return [];
return documentFor(project).query<DesignOptionCompareRow[]>("designOptionCompare", [], renovation ? JSON.stringify({ renovation }) : "");
const a = { ...(renovation ? { renovation } : {}), ...(all ? { all } : {}) };
return documentFor(project).query<DesignOptionCompareRow[]>("designOptionCompare", [], Object.keys(a).length ? JSON.stringify(a) : "");
}
/** Vergleich als CSV (Semikolon) mit den Spaltenköpfen `head` (übersetzt). */
export function compareDesignOptionsCsv(project: Project, head: readonly string[], renovation = ""): string {
export function compareDesignOptionsCsv(project: Project, head: readonly string[], renovation = "", all = false): string {
if (!designOptionSets(project).length) return "";
return documentFor(project).query<string>("designOptionCompare", [], JSON.stringify(renovation ? { renovation, head } : { head }));
return documentFor(project).query<string>("designOptionCompare", [], JSON.stringify({ head, ...(renovation ? { renovation } : {}), ...(all ? { all } : {}) }));
}
/**
@@ -282,12 +403,16 @@ export function compareDesignOptionsCsv(project: Project, head: readonly string[
export function projectWithCombination(project: Project, c: Combination): Project {
const keys = Object.keys(c);
if (!keys.length) return project;
const strip = <T extends { designOptions?: Combination | null }>(x: T): T => {
if (!x.designOptions || !keys.some((k) => k in x.designOptions!)) return x;
const m = { ...x.designOptions };
for (const k of keys) delete m[k];
const next = { ...x, designOptions: m };
if (!Object.keys(m).length) delete (next as { designOptions?: Combination | null }).designOptions;
// Benannte Kombinationen der Objekte werden zuerst zur freien Wahl aufgelöst, dann fallen die Sätze von `c` heraus.
const strip = <T extends { designOptions?: Combination | null; designOptionCombination?: string | null }>(x: T): T => {
if (!x.designOptions && !x.designOptionCombination) return x;
const eff = storedChoice(project, x) ?? {};
const m: Combination = {};
for (const [k, v] of Object.entries(eff)) if (!keys.includes(k)) m[k] = v;
const next = { ...x };
delete next.designOptionCombination;
if (Object.keys(m).length) next.designOptions = m;
else delete next.designOptions;
return next;
};
return {
+9 -2
View File
@@ -9,7 +9,7 @@ import type { Layout, LayoutOrientation, LayoutPaperFormat, MasterLayout, Projec
import { core } from "../engine/coreWasm";
import { t } from "../i18n/translate";
import { findSnapshot, resolveTitleBlock, resolveViewportScale, sheetSizeMm } from "./layoutModel";
import { combinationSuffix } from "./designOptions";
import { combinationNameFor, combinationSuffix, designOptionCombinations, resolveCombination, storedChoice } from "./designOptions";
export interface PosterTemplate {
/** Schlüssel in `MasterLayout.template`. */
@@ -123,7 +123,14 @@ export function viewportScaleLabel(
export function viewportVariantSuffix(project: Project, vp: Layout["viewports"][number]): string {
if (!project.designOptionSets?.length) return "";
const snap = findSnapshot(project, vp.snapshotId);
return combinationSuffix(project, { ...(snap?.designOptions ?? {}), ...(vp.designOptions ?? {}) });
// Verweist der Viewport (sonst der Ausschnitt) auf eine benannte Kombination, ist ihr Name der Titelzusatz (Hauptkombination: leer).
const ref = vp.designOptionCombination ?? (vp.designOptions && Object.keys(vp.designOptions).length ? undefined : snap?.designOptionCombination);
const named = ref ? designOptionCombinations(project).find((c) => c.id === ref) : undefined;
if (named) return named.name;
const m = { ...(snap ? storedChoice(project, snap) : {}), ...(storedChoice(project, vp) ?? {}) };
const sfx = combinationSuffix(project, m);
// Gleiche Wahl wie eine gespeicherte Kombination: deren Name statt der Aufzählung.
return sfx ? (combinationNameFor(project, resolveCombination(project, m)) ?? sfx) : "";
}
/** [272] Titelzusatz unter einem Viewport ohne Massstabsangaben des Masters: nur die Varianten; `null` ohne Abweichung. */
+8 -1
View File
@@ -5,7 +5,7 @@
// Satz „Fassade": A Lochfenster (Nordfenster O2 des Demo-Hauses, Hauptvariante), B Bandfenster (O-band, 3.6 m breit).
// Alles Übrige gehört zum Hauptmodell. Ein eigenes Beispiel, damit die bestehenden Goldens unverändert bleiben.
import type { DesignOptionSet, Opening, Project, Roof } from "./types";
import type { DesignOptionCombination, DesignOptionSet, Opening, Project, Roof } from "./types";
import { sampleProject } from "./sampleProject";
export const VARIANTEN_SETS: DesignOptionSet[] = [
@@ -13,6 +13,12 @@ export const VARIANTEN_SETS: DesignOptionSet[] = [
{ id: "fassade", name: "Fassade", options: [{ id: "a", name: "A Lochfenster" }, { id: "b", name: "B Bandfenster" }], primary: "a" },
];
/** Zwei benannte Kombinationen (wie Archicads „Design Option Combinations“): Studie 1 = Hauptvarianten, Studie 2 = B + B. */
export const VARIANTEN_COMBINATIONS: DesignOptionCombination[] = [
{ id: "studie-1", name: "Studie 1 Flachdach/Lochfenster", choices: { dachform: "a", fassade: "a" } },
{ id: "studie-2", name: "Studie 2 Satteldach/Bandfenster", choices: { dachform: "b", fassade: "b" } },
];
/** Das Varianten-Beispiel (frische Kopie bei jedem Aufruf). */
export function buildVariantenSampleProject(): Project {
const base = structuredClone(sampleProject);
@@ -31,5 +37,6 @@ export function buildVariantenSampleProject(): Project {
roofs,
openings,
designOptionSets: structuredClone(VARIANTEN_SETS),
designOptionCombinations: structuredClone(VARIANTEN_COMBINATIONS),
};
}
+37 -1
View File
@@ -678,6 +678,17 @@ export type CustomPalette = {
/** [272] Eine Variante eines Satzes (z. B. „A Flachdach“). */
export type DesignOption = { id: string; name: string };
/**
* [272] Eine benannte Variantenkombination (z. B. „Studie 1: Satteldach + Bandfenster“): je Satz die gewählte Variante.
* Sätze, die fehlen (oder deren Variante gelöscht wurde), zeigen ihre Hauptvariante.
*/
export type DesignOptionCombination = {
id: string;
name: string;
/** Satz-Id → Varianten-Id. */
choices: { [key in string]: string };
};
/** [272] Zugehörigkeit eines Elements zu einer Variante (Archicad „Design Options“). */
export type DesignOptionRef = {
/** Id des Variantensatzes (`DesignOptionSet.id`). */
@@ -1444,6 +1455,11 @@ export type DrawingLevel = {
renovationPhase?: string;
/** [272] Variantenkombination: Satz-Id → Varianten-Id (fehlende Sätze ⇒ Hauptvariante). */
designOptions?: { [key in string]: string };
/**
* [272] Benannte Variantenkombination (`Project.designOptionCombinations`, Id). Gesetzt und gültig ⇒ sie gilt vollständig
* (fehlende Sätze ⇒ Hauptvariante) und die freie Wahl `designOptions` desselben Objekts wird übergangen; sonst die freie Wahl.
*/
designOptionCombination?: string;
};
/**
@@ -2168,7 +2184,8 @@ export type LayoutTableSource =
| "earthworks"
| "roomBook"
| "costs"
| "siteProof";
| "siteProof"
| "designOptionCompare";
/**
* Einfache Textfelder des Titelblocks (Master). Alle optional — leere Felder
@@ -2206,6 +2223,11 @@ export type LayoutViewport = {
* [272] Variantenkombination des Viewports (über der des Ausschnitts): Satz-Id → Varianten-Id (fehlende Sätze ⇒ Hauptvariante).
*/
designOptions?: { [key in string]: string };
/**
* [272] Benannte Variantenkombination (`Project.designOptionCombinations`, Id). Gesetzt und gültig ⇒ sie gilt vollständig
* (fehlende Sätze ⇒ Hauptvariante) und die freie Wahl `designOptions` desselben Objekts wird übergangen; sonst die freie Wahl.
*/
designOptionCombination?: string;
};
/** Linienenden aller Striche im Plan/Schnitt/Ansicht und in den Exporten ([146]); fehlt = flach. */
@@ -3309,6 +3331,10 @@ export type Project = {
* Kombination ihrer Variante.
*/
designOptionSets?: Array<DesignOptionSet>;
/**
* [272] Benannte Variantenkombinationen (Archicad „Design Option Combinations“): je Satz genau eine Variante.
*/
designOptionCombinations?: Array<DesignOptionCombination>;
};
/** Protokolleintrag einer Publikation ([79]): Datum, Blätter mit Revision, erzeugte Dateien. */
@@ -4463,6 +4489,11 @@ export type ViewSnapshot = {
renovationPhase?: string;
/** [272] Variantenkombination: Satz-Id → Varianten-Id (fehlende Sätze ⇒ Hauptvariante). */
designOptions?: { [key in string]: string };
/**
* [272] Benannte Variantenkombination (`Project.designOptionCombinations`, Id). Gesetzt und gültig ⇒ sie gilt vollständig
* (fehlende Sätze ⇒ Hauptvariante) und die freie Wahl `designOptions` desselben Objekts wird übergangen; sonst die freie Wahl.
*/
designOptionCombination?: string;
};
/**
@@ -4536,6 +4567,11 @@ export type ViewTemplate = {
renovationPhase?: string;
/** [272] Variantenkombination: Satz-Id → Varianten-Id (fehlende Sätze ⇒ Hauptvariante). */
designOptions?: { [key in string]: string };
/**
* [272] Benannte Variantenkombination (`Project.designOptionCombinations`, Id). Gesetzt und gültig ⇒ sie gilt vollständig
* (fehlende Sätze ⇒ Hauptvariante) und die freie Wahl `designOptions` desselben Objekts wird übergangen; sonst die freie Wahl.
*/
designOptionCombination?: string;
};
/** Ansichtstyp eines Geschosses (wie in App). */
+14 -5
View File
@@ -2,8 +2,9 @@
// inkl. MwSt.) je Kombination der Variantensätze nebeneinander, Hauptkombination zuerst (Kern `design_options::compare`);
// mit CSV-Export. Nur mit Variantensätzen im Projekt; `renovation`: Umbau-Zustand wie die Kennzahlenleiste.
import { useState } from "react";
import { t } from "../i18n";
import { compareDesignOptions, compareDesignOptionsCsv, designOptionSets, exportProjectName, formatChf } from "../core";
import { compareDesignOptions, compareDesignOptionsCsv, designOptionCombinations, designOptionSets, exportProjectName, formatChf } from "../core";
import type { Project } from "../model/types";
import { downloadCsv } from "./downloadFile";
import { runWithAnonymityGate } from "../state/anonymityGate";
@@ -16,17 +17,25 @@ export function designOptionCompareHead(): string[] {
}
export function DesignOptionCompareSection({ project, renovation = "" }: { project: Project; renovation?: string }) {
const [all, setAll] = useState(false);
if (!designOptionSets(project).length) return null;
const rows = compareDesignOptions(project, renovation);
const saved = designOptionCombinations(project).length > 0;
const rows = compareDesignOptions(project, renovation, all);
if (!rows.length) return null;
const head = designOptionCompareHead();
const stem = `${exportProjectName(project) || "projekt"}-varianten`;
const exportCsv = () => runWithAnonymityGate(project, [`${stem}.csv`], () => downloadCsv(`${stem}.csv`, compareDesignOptionsCsv(project, head, renovation)));
const exportCsv = () => runWithAnonymityGate(project, [`${stem}.csv`], () => downloadCsv(`${stem}.csv`, compareDesignOptionsCsv(project, head, renovation, all)));
const base = rows[0];
const delta = (v: number, b: number, d: number) => (v === b ? "" : ` (${v > b ? "+" : "−"}${fmt(Math.abs(v - b), d)})`);
return (
<div className="kz-variants" data-testid="design-option-compare">
<div className="balance-section-label">{t("designOption.compare.title")}</div>
{saved && (
<label className="kz-parcel">
<input type="checkbox" checked={all} data-testid="design-option-compare-all" onChange={(e) => setAll(e.target.checked)} />
<span>{t("designOption.compare.all")}</span>
</label>
)}
<div className="kz-variants-scroll">
<table className="kz-variants-table">
<thead>
@@ -38,8 +47,8 @@ export function DesignOptionCompareSection({ project, renovation = "" }: { proje
</thead>
<tbody>
{rows.map((r) => (
<tr key={r.label} className={r.primary ? "kz-variants-primary" : undefined} data-testid="design-option-compare-row">
<td title={r.label}>{r.label}</td>
<tr key={r.combination ?? r.label} className={r.primary ? "kz-variants-primary" : undefined} data-testid="design-option-compare-row">
<td title={r.detail}>{r.label}</td>
<td className="num">{fmt(r.gf) + delta(r.gf, base.gf, 1)}</td>
<td className="num">{fmt(r.hnf) + delta(r.hnf, base.hnf, 1)}</td>
<td className="num">{fmt(r.gv, 0) + delta(r.gv, base.gv, 0)}</td>
+81 -1
View File
@@ -7,9 +7,12 @@ import { useMemo, useState } from "react";
import { t } from "../i18n";
import { useStore } from "../state/appStore";
import {
addCombinationOps, assignCombinationOps, combinationChoice, deleteCombinationOps, designOptionCombinations, levelCombinationState, nextCombinationName, renameCombinationOps, setCombinationChoiceOps,
acceptDesignOptionOps, addDesignOptionOps, addDesignOptionSetOps, assignDesignOptionOps, copyToDesignOptionOps, deleteDesignOptionOps, designOptionIds,
designOptionSets, designOptionTargets, levelCombination, parseTarget, renameDesignOptionOps, renameDesignOptionSetOps, setLevelCombinationOps, setPrimaryOptionOps,
} from "../core";
import { ConfirmDialog } from "../ui/ConfirmDialog";
import { PromptDialog } from "../ui/PromptDialog";
import { DesignOptionsTab, type DesignOptionHandlers } from "../ui/resourceManager/DesignOptionsTab";
import { DesignOptionCompareSection } from "./DesignOptionCompareSection";
import { selectionDesignOptionIds } from "./objectInfo/DesignOptionField";
@@ -23,11 +26,16 @@ export function DesignOptionsPanel() {
const applyChange = useStore((s) => s.applyChange);
const [target, setTarget] = useState("");
const [showCompare, setShowCompare] = useState(false);
const [saving, setSaving] = useState(false);
const [deleting, setDeleting] = useState<string | null>(null);
const sets = designOptionSets(project);
const level = project.drawingLevels.find((l) => l.id === activeLevelId);
const combo = levelCombination(project, level);
const levelEditable = !!level && (level.kind === "floor" || level.kind === "section" || level.kind === "elevation" || level.kind === "ceiling");
const targets = designOptionTargets(project);
const combos = designOptionCombinations(project);
const state = levelCombinationState(project, level);
const deleteCombo = combos.find((c) => c.id === deleting);
const selIds = useMemo(() => designOptionIds(project, selectionDesignOptionIds(selection)), [project, selection]);
const handlers: DesignOptionHandlers = {
onAddDesignOptionSet: (name) => applyChange((p) => addDesignOptionSetOps(p, name).ops),
@@ -74,6 +82,53 @@ export function DesignOptionsPanel() {
))}
</select>
</label>
<div className="balance-section-label">{t("designOption.combinations.title")}</div>
<div className="kz-parcel" data-testid="design-option-current">
<span>{t("designOption.current")}</span>
<strong className="design-option-current-name" data-testid="design-option-current-name">
{state.kind === "named" ? state.name : t("designOption.customName")}
</strong>
</div>
<button type="button" className="balance-export" data-testid="design-option-combo-save" onClick={() => setSaving(true)}>
{t("designOption.combination.save")}
</button>
{combos.length === 0 && <div className="rm-hint">{t("designOption.combinations.empty")}</div>}
{combos.map((c) => {
const full = combinationChoice(project, c);
const assigned = state.kind === "named" && state.id === c.id;
return (
<div key={c.id} className="design-option-combination" data-testid="design-option-combination">
<div className="kz-parcel">
<input
className="kz-input"
type="text"
value={c.name}
aria-label={t("designOption.combination.name")}
data-testid="design-option-combination-name"
onChange={(e) => applyChange((p) => renameCombinationOps(p, c.id, e.target.value), `dopt-comb-${c.id}`)}
/>
<button type="button" className="kz-add" disabled={!levelEditable || (assigned && state.kind === "named" && state.assigned)} data-testid="design-option-combination-assign" onClick={() => level && applyChange((p) => assignCombinationOps(p, level.id, c.id))}>
{assigned && state.kind === "named" && state.assigned ? t("designOption.combination.assigned") : t("designOption.combination.assign")}
</button>
<button type="button" className="kz-add" aria-label={t("designOption.combination.delete")} title={t("designOption.combination.delete")} data-testid="design-option-combination-delete" onClick={() => setDeleting(c.id)}>
×
</button>
</div>
{sets.map((s) => (
<label key={s.id} className="kz-parcel design-option-combination-set">
<span>{s.name}</span>
<select className="kz-input" value={full[s.id] ?? ""} aria-label={`${c.name}: ${s.name}`} data-testid={`design-option-combination-${c.id}-${s.id}`} onChange={(e) => applyChange((p) => setCombinationChoiceOps(p, c.id, s.id, e.target.value))}>
{s.options.map((o) => (
<option key={o.id} value={o.id}>
{o.name}
</option>
))}
</select>
</label>
))}
</div>
);
})}
<div className="balance-section-label">{t("designOption.selection", { n: selIds.length })}</div>
<div className="kz-parcel">
<select className="kz-input" value={target} aria-label={t("designOption.label")} data-testid="design-option-target" onChange={(e) => setTarget(e.target.value)}>
@@ -102,6 +157,31 @@ export function DesignOptionsPanel() {
{showCompare && <DesignOptionCompareSection project={project} />}
</>
)}
{saving && (
<PromptDialog
title={t("designOption.combination.save")}
label={t("designOption.combination.name")}
defaultValue={nextCombinationName(project, t("designOption.combination.defaultName"))}
onClose={() => setSaving(false)}
onConfirm={(name) => {
setSaving(false);
applyChange((p) => addCombinationOps(p, name, combo).ops);
}}
/>
)}
{deleteCombo && (
<ConfirmDialog
title={t("designOption.combination.delete")}
message={t("designOption.combination.deleteMessage", { name: deleteCombo.name })}
confirmLabel={t("designOption.combination.deleteConfirm")}
danger
onClose={() => setDeleting(null)}
onConfirm={() => {
setDeleting(null);
applyChange((p) => deleteCombinationOps(p, deleteCombo.id));
}}
/>
)}
</div>
);
}
}
+2 -1
View File
@@ -5,6 +5,7 @@
import type { Doc3d, Project, ViewSnapshot } from "../model/types";
import { documentFor } from "../core/document";
import { lineEndsCode } from "../model/lineEnds";
import { storedChoice } from "../model/designOptions";
import { decodePlanBuf } from "./planBuf";
import { lazyPlan } from "./planLazy";
import { visibilityArgs } from "./toSection";
@@ -55,6 +56,6 @@ export function isDoc3dSnapshot(snap: Pick<ViewSnapshot, "viewType">): boolean {
/** 3D-Dokument eines Ausschnitts (Kern: `sheet_viewports::doc3d_buf`): `doc3d`, sonst sein Blickwinkel `view3d`. */
export function snapshotAxoPlan(project: Project, snap: ViewSnapshot, visibleCodes: Set<string>, scaleDenominator: number, mono = true, designOptions?: Record<string, string> | null): Plan | null {
// [272] Variantenkombination des Ausschnitts bzw. Viewports.
const opts = designOptions ?? snap.designOptions;
const opts = designOptions ?? storedChoice(project, snap);
return generateAxoPlan(project, { view: snap.view3d, ...(snap.doc3d ?? {}), visibleCodes, scaleDenominator, mono, ...(opts && Object.keys(opts).length ? { designOptions: opts } : {}) });
}
+1
View File
@@ -89,6 +89,7 @@ export function levelArg(level: DrawingLevel) {
renovationPhase: level.renovationPhase,
// [272] Variantenkombination der Ebene (Kern `design_options.rs`, Sichtbarkeit `renovation.rs`).
designOptions: level.designOptions,
designOptionCombination: level.designOptionCombination,
};
}
+5
View File
@@ -13,6 +13,11 @@ export const TEMPLATE_LEVEL_KEYS = ["cutHeight", "viewTop", "viewBottom", "viewD
export function templateLevelPatch(t: ViewTemplate): Partial<DrawingLevel> {
const out: Record<string, unknown> = {};
for (const k of TEMPLATE_LEVEL_KEYS) if (t[k] !== undefined) out[k] = t[k];
// [272] Variantenwahl der Vorlage (benannte Kombination oder freie Wahl) ersetzt die der Ebene als Ganzes (Kern `level_with_template`).
if (t.designOptions !== undefined || t.designOptionCombination !== undefined) {
out.designOptions = t.designOptions;
out.designOptionCombination = t.designOptionCombination;
}
return out as Partial<DrawingLevel>;
}
+19 -6
View File
@@ -7,6 +7,7 @@
import type { DetailLevel } from "../model/viewTypes";
import type { Project, ViewTemplate } from "../model/types";
import { withDocument } from "../core/document";
import { storedChoice } from "../model/designOptions";
import { linkedViewTemplate, projectWithTemplate } from "./viewTemplate";
import { generatePlan, type Plan, type Primitive } from "./generatePlan";
import { computeSection, generateSectionPlan } from "./toSection";
@@ -82,9 +83,9 @@ export async function viewportLevelPlan(
* Inhalt eines Ausschnitts auf dem Blatt bzw. im PDF: [266] 3D-Ausschnitte (Ansichtstyp „perspektive“) als 3D-Dokument aus dem
* Kern (Vektor-Axonometrie/-Perspektive mit verdeckten Kanten, Kern: `sheet_viewports::doc3d_buf`), sonst {@link viewportLevelPlan}.
*/
export async function viewportSnapshotPlan(project: Project, snap: ViewSnapshot, visibleCodes: Set<string>, scaleDenominator: number, forPrint = false, viewport?: { designOptions?: Record<string, string> | null } | null): Promise<Plan> {
export async function viewportSnapshotPlan(project: Project, snap: ViewSnapshot, visibleCodes: Set<string>, scaleDenominator: number, forPrint = false, viewport?: { designOptions?: Record<string, string> | null; designOptionCombination?: string | null } | null): Promise<Plan> {
// [272] Variantenkombination: Ausschnitt, darüber die des Viewports (dieselbe Ansicht in anderer Kombination).
const opts = viewportDesignOptions(snap, viewport);
const opts = viewportDesignOptions(project, snap, viewport);
if (isDoc3dSnapshot(snap)) return snapshotAxoPlan(project, snap, visibleCodes, scaleDenominator, snapshotMono(project, snap), opts) ?? EMPTY;
if (opts) {
const dp = projectWithDesignOptions(project, snap.activeLevelId, opts);
@@ -99,15 +100,27 @@ export async function viewportSnapshotPlan(project: Project, snap: ViewSnapshot,
return viewportLevelPlan(project, snap.activeLevelId, visibleCodes, snap.detail, scaleDenominator, forPrint, snapshotMono(project, snap), snapshotOverrideRuleIds(project, snap), snapshotTemplate(project, snap), snap.modelViewOptionId);
}
/** [272] Kombination eines Ausschnitts samt Viewport (Viewport geht vor); `null` ohne eigene Wahl. */
export function viewportDesignOptions(snap: { designOptions?: Record<string, string> | null }, viewport?: { designOptions?: Record<string, string> | null } | null): Record<string, string> | null {
const m = { ...(snap.designOptions ?? {}), ...(viewport?.designOptions ?? {}) };
/** [272] Wahl eines Ausschnitts samt Viewport (Viewport geht vor; benannte Kombination vor freier Wahl, Kern `design_options::stored_choice`); `null` ohne eigene Wahl. */
export function viewportDesignOptions(
project: Project,
snap: { designOptions?: Record<string, string> | null; designOptionCombination?: string | null },
viewport?: { designOptions?: Record<string, string> | null; designOptionCombination?: string | null } | null,
): Record<string, string> | null {
const m = { ...(storedChoice(project, snap) ?? {}), ...(storedChoice(project, viewport) ?? {}) };
return Object.keys(m).length ? m : null;
}
/** [272] Das Projekt mit der Variantenkombination `opts` an der Ebene `levelId` (über deren eigener Wahl). */
export function projectWithDesignOptions(project: Project, levelId: string, opts: Record<string, string>): Project {
return { ...project, drawingLevels: project.drawingLevels.map((l) => (l.id === levelId ? { ...l, designOptions: { ...(l.designOptions ?? {}), ...opts } } : l)) };
return {
...project,
drawingLevels: project.drawingLevels.map((l) => {
if (l.id !== levelId) return l;
const next = { ...l, designOptions: { ...(storedChoice(project, l) ?? {}), ...opts } };
delete next.designOptionCombination;
return next;
}),
};
}
/** [271] Das Projekt mit Umbaufilter `filter` (und Etappe) an der Ebene `levelId`. */
+2 -2
View File
@@ -67,7 +67,7 @@ declare global {
/** [271] Umbau: Filter und Etappe der aktiven Ebene, Zeichen-Status, Status je Wand. */
renovation: () => { filter: string | null; phase: string | null; draw: string; walls: Record<string, string> };
/** [272] Varianten: Kombination der aktiven Ebene, Zeichen-Variante, Variante je Element (`set/option`, leer = Hauptmodell), Sätze. */
designOptions: () => { level: Record<string, string>; draw: string | null; elements: Record<string, string>; sets: string[] };
designOptions: () => { level: Record<string, string>; combination: string | null; combinations: string[]; draw: string | null; elements: Record<string, string>; sets: string[] };
/** [193] Gefüllte Flächen (Füllfarbe gesetzt) im Grundriss der aktiven Ebene (alle Kategorien, 1:100); bei 0 ist nichts Gefülltes mehr zu sehen. */
planFills: () => number;
/** [193] Höhe (z) des ersten Gelände-Netz-Punkts. */
@@ -202,7 +202,7 @@ export function installTestHooks(): void {
for (const list of [s.project.walls, s.project.openings, s.project.roofs, s.project.ceilings, s.project.rooms]) {
for (const e of (list ?? []) as { id: string; designOption?: { set: string; option: string } }[]) elements[e.id] = e.designOption ? `${e.designOption.set}/${e.designOption.option}` : "";
}
return { level: l?.designOptions ?? {}, draw: s.drawDesignOption ? `${s.drawDesignOption.set}/${s.drawDesignOption.option}` : null, elements, sets: (s.project.designOptionSets ?? []).map((x) => x.id) };
return { level: l?.designOptions ?? {}, combination: l?.designOptionCombination ?? null, combinations: (s.project.designOptionCombinations ?? []).map((x) => x.name), draw: s.drawDesignOption ? `${s.drawDesignOption.set}/${s.drawDesignOption.option}` : null, elements, sets: (s.project.designOptionSets ?? []).map((x) => x.id) };
},
renovation: () => {
const s = getState();
+25
View File
@@ -9972,3 +9972,28 @@ body {
.design-options-panel .kz-parcel select {
max-width: 170px;
}
/* [272] Benannte Variantenkombinationen im Panel „Varianten“ */
.design-option-combination {
border-top: 1px solid var(--border, rgba(128, 128, 128, 0.25));
padding: 4px 0;
}
.design-option-combination .kz-input[type="text"] {
flex: 1;
min-width: 0;
max-width: none;
}
.design-option-combination-set {
padding-left: 8px;
font-size: 11px;
}
.design-options-panel .rm-hint {
font-size: 11px;
opacity: 0.75;
}
.design-option-current-name {
font-size: 12px;
font-weight: 600;
text-align: right;
min-width: 0;
overflow-wrap: anywhere;
}
+5 -2
View File
@@ -4,7 +4,7 @@
import { t } from "../i18n";
import { useStore } from "../state/appStore";
import { combinationSuffix, designOptionTargets } from "../core";
import { combinationSuffix, designOptionTargets, levelCombination, levelCombinationState } from "../core";
export function DesignOptionControl() {
const project = useStore((s) => s.project);
@@ -12,7 +12,10 @@ export function DesignOptionControl() {
const draw = useStore((s) => s.drawDesignOption);
if (!project.designOptionSets?.length) return null;
const level = project.drawingLevels.find((l) => l.id === activeLevelId);
const suffix = combinationSuffix(project, level?.designOptions);
// Name der benannten Kombination (zugewiesen oder gleiche Wahl), sonst „Eigene: Abweichungen“ bzw. die Hauptvarianten.
const state = levelCombinationState(project, level);
const diff = combinationSuffix(project, levelCombination(project, level));
const suffix = state.kind === "named" ? state.name : diff ? t("designOption.custom", { combination: diff }) : "";
const drawKey = draw ? `${draw.set}/${draw.option}` : "";
const drawLabel = designOptionTargets(project).find((x) => x.key === drawKey)?.label ?? t("designOption.main");
const shown = suffix || t("designOption.primaryCombination");
+22 -3
View File
@@ -27,7 +27,7 @@ import type {
Project,
Vec2,
} from "../model/types";
import { createTable, PX_PER_M, sheetTables, TABLE_SOURCES, tableSourceLabel, viewportSnapshotPlan } from "../core";
import { createTable, PX_PER_M, sheetTables, storedChoice, TABLE_SOURCES, tableSourceLabel, viewportCombinationPatch, viewportSnapshotPlan } from "../core";
import type { TableOut } from "../core";
import { SheetTableHud } from "./SheetTableHud";
import { isInModalDialog } from "../state/modalScope";
@@ -131,7 +131,7 @@ export function ViewportPlanSvg({
return () => {
disposed = true;
};
}, [project, viewport.snapshotId, viewport.widthMm, viewport.heightMm, viewport.scaleDenominator, viewport.center?.x, viewport.center?.y, viewport.designOptions]);
}, [project, viewport.snapshotId, viewport.widthMm, viewport.heightMm, viewport.scaleDenominator, viewport.center?.x, viewport.center?.y, viewport.designOptions, viewport.designOptionCombination]);
// Lage/Grösse über die Attribute des inneren SVG (folgt auch dem Ghost beim Ziehen).
useEffect(() => {
if (ref.current) placeInner(ref.current, rect);
@@ -1219,13 +1219,32 @@ export function LayoutSheetPane({
</span>
</label>
{/* [272] Eigene Variantenkombination des Viewports: dieselbe Ansicht in anderer Kombination (Titelzusatz). */}
{(project.designOptionCombinations ?? []).length > 0 && (
<label className="layout-sheet-hud-row">
<span>{t("designOption.combination")}</span>
<select
className="res-input"
data-testid="vp-design-option-combination"
value={selectedVp.designOptionCombination ?? ""}
onChange={(e) => handlers.onPatchViewport(selectedVp.id, viewportCombinationPatch(e.target.value))}
>
<option value="">{t("designOption.fromSnapshot")}</option>
{(project.designOptionCombinations ?? []).map((c) => (
<option key={c.id} value={c.id}>
{c.name}
</option>
))}
</select>
</label>
)}
{(project.designOptionSets ?? []).map((s) => (
<label key={s.id} className="layout-sheet-hud-row">
<span>{s.name}</span>
<select
className="res-input"
data-testid={`vp-design-option-${s.id}`}
value={selectedVp.designOptions?.[s.id] ?? ""}
value={(storedChoice(project, selectedVp) ?? {})[s.id] ?? ""}
disabled={!!selectedVp.designOptionCombination}
onChange={(e) => {
const next = { ...(selectedVp.designOptions ?? {}) };
if (e.target.value) next[s.id] = e.target.value;
+3 -2
View File
@@ -70,7 +70,7 @@ import { pointCloudSyncItems } from "./pointCloudSync";
import { usePointClouds } from "../state/pointCloudStore";
import { sun3dFor, sun3dKey } from "./sun3d";
import { useStore } from "../state/appStore";
import { projectGeoOrigin } from "../core";
import { projectGeoOrigin, storedChoice } from "../core";
import {
FOV_Y,
PITCH_LIMIT,
@@ -629,7 +629,8 @@ export function Wasm3DViewport({
// [272] Variantenkombination der aktiven Ebene (wie im Grundriss); ohne Wahl die Hauptvarianten (Kern).
const optKey = useStore((s) => {
const l = s.project.drawingLevels.find((x) => x.id === s.activeLevelId);
return l?.designOptions ? JSON.stringify(l.designOptions) : "";
const c = l ? storedChoice(s.project, l) : undefined;
return c ? JSON.stringify(c) : "";
});
const hide = useMemo<Hide3d>(() => {
const split = (k: string) => (k ? k.split("\u0001") : []);