From 9b0f64fc35d2f36fd300c6ba756c1825c23d3871 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 14:25:13 +0000 Subject: [PATCH] =?UTF-8?q?[121]=20Neurendern:=20Panels=20lesen=20Projekt?= =?UTF-8?q?=20und=20Objekt-Info=20selbst=20aus=20dem=20Store=20(useSelecti?= =?UTF-8?q?onInfo,=20inhaltlich=20stabil),=20Panel-Host=20ohne=20project/s?= =?UTF-8?q?election/contextObjects=20und=20mit=20stabiler=20Identit=C3=A4t?= =?UTF-8?q?=20(Handler=20als=20Trampoline),=20usePanelHostBase=20in=20src/?= =?UTF-8?q?state/panelHost/=20zerlegt;=20Docks,=20versteckte=20Datei-Felde?= =?UTF-8?q?r,=20Zeichnungs-Reiter=20und=20Pr=C3=A4sentations-Dialog=20memo?= =?UTF-8?q?isiert;=20Wand-=C3=84nderung=2055=20=E2=86=92=2042=20Renders,?= =?UTF-8?q?=20Schranken=20im=20e2e=20gesenkt;=20Doku=20und=20TODO=20nachge?= =?UTF-8?q?f=C3=BChrt?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TODO.md | 8 +- doc/ARCHITEKTUR.md | 30 +- e2e/renderCount.spec.ts | 9 +- src/App.tsx | 27 +- src/DrawingTabs.tsx | 19 +- src/panels/AreaTableSection.tsx | 4 +- src/panels/AttributesPanel.tsx | 10 +- src/panels/BcfPanel.tsx | 18 +- src/panels/ContextObjectProps.tsx | 5 +- src/panels/Dock.tsx | 6 +- src/panels/DockArea.tsx | 57 +- src/panels/DrawingLevelsPanel.tsx | 6 +- src/panels/ElementScheduleSection.tsx | 4 +- src/panels/ElementTreePanel.tsx | 10 +- src/panels/KennzahlenSection.tsx | 4 +- src/panels/LayersPanel.tsx | 6 +- src/panels/LayoutsPanel.tsx | 8 +- src/panels/ObjectInfoPanel.tsx | 68 +- src/panels/OpeningScheduleSection.tsx | 2 +- src/panels/PointCloudSection.tsx | 6 +- src/panels/ProgramCompareSection.tsx | 2 +- src/panels/PublishSection.tsx | 5 +- src/panels/RoomBalancePanel.tsx | 10 +- src/panels/RoomBookSection.tsx | 3 +- src/panels/SitePanel.tsx | 13 +- src/panels/SiteRulesSection.tsx | 14 +- src/panels/SunStudySection.tsx | 9 +- src/panels/SurfacePatternPlacement.tsx | 3 +- src/panels/ViewSnapshotsPanel.tsx | 12 +- src/panels/host.ts | 17 +- src/state/README.md | 13 +- src/state/panelHost/elementAttributesHost.ts | 332 ++++ src/state/panelHost/layoutsHost.ts | 169 ++ src/state/panelHost/selectionStyleHost.ts | 431 +++++ src/state/panelHost/siteHost.ts | 61 + src/state/panelHost/stableHost.test.ts | 50 + src/state/panelHost/stableHost.ts | 76 + src/state/panelHost/toolsHost.ts | 70 + src/state/panelHost/types.ts | 163 ++ src/state/panelHost/viewSnapshotsHost.ts | 184 ++ src/state/panelHost/viewState.ts | 97 ++ src/state/panelOps.test.ts | 3 +- src/state/usePanelHostBase.ts | 1575 +----------------- src/state/useSectionLineState.ts | 7 +- src/state/useSelectionInfo.ts | 30 + src/ui/HiddenFileInputs.tsx | 9 +- src/ui/PresentationDialog.tsx | 19 +- src/views/viewportContent.tsx | 8 +- 48 files changed, 1981 insertions(+), 1711 deletions(-) create mode 100644 src/state/panelHost/elementAttributesHost.ts create mode 100644 src/state/panelHost/layoutsHost.ts create mode 100644 src/state/panelHost/selectionStyleHost.ts create mode 100644 src/state/panelHost/siteHost.ts create mode 100644 src/state/panelHost/stableHost.test.ts create mode 100644 src/state/panelHost/stableHost.ts create mode 100644 src/state/panelHost/toolsHost.ts create mode 100644 src/state/panelHost/types.ts create mode 100644 src/state/panelHost/viewSnapshotsHost.ts create mode 100644 src/state/panelHost/viewState.ts create mode 100644 src/state/useSelectionInfo.ts diff --git a/TODO.md b/TODO.md index d578edf2..66df2e74 100644 --- a/TODO.md +++ b/TODO.md @@ -229,9 +229,11 @@ Wer zu einer ID mehr wissen will (Entscheide, Tests, Bilder), sucht dort nach `* ## App und UI -- ◐ **[121]** `App.tsx` zerlegen, Neurendern stoppen. App abonniert weiter das ganze Projekt; Panels lesen `usePanelHost`; - `usePanelHostBase` (1565 Z.) gross; Nebenfenster senden ihren ganzen Zustand. Zerlegung selbst erledigt mit [163] - (9.11.: App.tsx 2957 → ~1120 Z., Teile in `src/state/use*.ts`, `src/ui/AppDialogs.tsx` u. a.). · L +- ◐ **[121]** `App.tsx` zerlegen, Neurendern stoppen. 9.11.: Panels lesen Projekt/Objekt-Info selbst aus dem Store + (`useSelectionInfo`), Panel-Host stabil und in `src/state/panelHost/` zerlegt, Docks u. a. memoisiert, Nebenfenster + senden Patches; Wand-Änderung 55 → 42 Renders (Zoom 8, Zeiger 20). Offen: App abonniert weiter das ganze Projekt + (Griffe, Auswahl-Befehle im App-Render; nächster Schritt Griffe nach `Content`); viele Panels noch mit + `s.project` statt schmalem Ausschnitt. Nicht in Tauri geprüft (Nebenfenster-Patches nur per Unit-Test). · L - ◐ **[130]** Kleinkram. PlanView/`useGrip3dEditing` nutzen lokale `selected…Ids`-Namen statt `Selection`. · S - ◐ **[128]** Restlogik nach Rust. Griffe: Zusammenstellen der Griff-/Kanten-Listen (`gripOwners`), Höhen-Griff-Lagen, Vorschau, Zug-Anwendung bleiben in `useGripEditing.ts`; nächster Schritt: Griff-Listen als Dokument-Abfrage. · L diff --git a/doc/ARCHITEKTUR.md b/doc/ARCHITEKTUR.md index 4b1bd01a..e418ff54 100644 --- a/doc/ARCHITEKTUR.md +++ b/doc/ARCHITEKTUR.md @@ -560,9 +560,11 @@ dort steht, was fehlt; was schon versucht wurde, steht im Archiv (`doc/archiv/TO 4. **Formatierung und Clippy in den Check** (`[C6]`, `[22]`). Mit einem kleinen Crate anfangen (`src-tauri/hatchgen`), `cargo fmt` und `cargo clippy` dort sauber machen und in `scripts/check.mjs` aufnehmen. Die übrigen Crates folgen einzeln (sonst ein Riesen-Diff). -5. **Panels schmal abonnieren** (`[121]`). Die meisten Panels lesen noch den ganzen Host - (`usePanelHost`); `src/panels/ToolsPanel.tsx` zeigt das Muster mit `usePanelHostSelect`. - Dateien: `src/panels/host.ts`, `src/state/usePanelHostBase.ts`, Messung `e2e/renderCount.spec.ts`. +5. **Panels noch schmaler abonnieren** (Rest aus `[121]`). Projekt und Objekt-Info lesen die Panels seit + 9.11. selbst aus dem Store (der Panel-Host trägt nur Handler und kleine Ansichts-Werte); viele tun das + aber noch mit `useStore((s) => s.project)` statt mit dem Ausschnitt, den sie zeigen (Muster: + `PresentationDialogHost` mit `s.project.drawingLevels`, `DrawingTabs` mit `s.project.viewSnapshots`). + Dateien: `src/panels/*.tsx`, Messung `e2e/renderCount.spec.ts`. 6. **Abzugskörper in der Ansicht** (Rest aus `[G8]`). Grundriss, Schnitt und 3D sparen Abzugskörper aus, die Ansicht noch nicht. Dateien: `src-tauri/core/src/plan/elevation.rs`, `src-tauri/core/src/voids.rs`; Vorbild `subtract_voids_in_section()` in `plan/section/voids.rs`. @@ -626,7 +628,27 @@ Reihenfolge aufrufen, Gerüst rendern. Herausgelöst, ohne Verhaltensänderung ( | `src/panels/DockArea.tsx` | Docks links/rechts, Andockzonen, schwebende Panels um die Mitte | | `src/ui/AppDialogs.tsx`, `HiddenFileInputs.tsx`, `BootScreen.tsx`, `useTopBarElements.tsx` | Dialoge und Overlays; versteckte Datei-Felder; Splash/Start; Menüleiste und Ansichts-Ribbon | -Offen bleibt aus `[121]`: App abonniert weiter das ganze Projekt; `usePanelHostBase` ist gross. +### Neurendern und Panel-Host ([121], 9.11.2026) + +- Panels lesen Projektdaten selbst aus dem Store (`useStore`), die Objekt-Info der Auswahl über + `src/state/useSelectionInfo.ts` (einmal je Projekt/Auswahl gerechnet, inhaltlich gleiche Info behält + ihre Referenz). `project`, `selection` und `contextObjects` sind keine Felder des Panel-Hosts mehr. +- `src/state/usePanelHostBase.ts` ist nur noch der Zusammenbau; die Teile liegen in `src/state/panelHost/` + (`toolsHost`, `selectionStyleHost`, `elementAttributesHost`, `siteHost`, `viewSnapshotsHost` mit + `viewState`, `layoutsHost`, Typen in `types.ts`). `stableHost.ts` gibt dem Host eine feste Identität: + Handler sind Trampoline auf die neueste Fassung, neu wird er nur bei geänderten Wert-Feldern. +- Docks (`Dock` mit stabilen Rückrufen aus `DockArea`), versteckte Datei-Felder, Zeichnungs-Reiter und + der Präsentations-Dialog sind memoisiert. +- Nebenfenster (`src/native/windowBridge.ts`): nach dem ersten ganzen Zustand nur noch Patches mit den + inhaltlich geänderten Feldern; gleicher Zustand wird nicht gesendet. Das Ressourcen-Fenster schickt + weiter seine Projekt-Differenz (`projectDelta.ts`). +- Gemessen (`e2e/renderCount.spec.ts`, Musterhaus): Wand-Änderung 55 → 42 Renders, Zoom-Schritt 8, + 5 Zeiger-Schritte 20 (unverändert). + +Offen: `App.tsx` abonniert weiter das ganze Projekt. Die Griffe (`useGripEditing`, `useGrip3dEditing`), die +Befehle auf der Auswahl und die Objekt-Info hängen im App-Render am Projekt; solange sie dort gerechnet +werden, rendert App bei jeder Op (die Kinder dank Memo meist nicht mit). Nächster Schritt: Griffe in die +Hauptansicht (`Content`) verlegen, dann App nur noch auf Ebenen/Layer/Name abonnieren. ### Bekannte veraltete Kommentare diff --git a/e2e/renderCount.spec.ts b/e2e/renderCount.spec.ts index 34874a8c..1939e594 100644 --- a/e2e/renderCount.spec.ts +++ b/e2e/renderCount.spec.ts @@ -6,6 +6,9 @@ // Minifizierung: `vite build --minify false`). Gemessen 3.11. (Musterhaus): Wand-Änderung 413 → 290, // Zoom-Schritt 240 → 61. 4.11.: Wand-Änderung 290 → 51 (Plan-Primitive/Schraffur-Muster mit // Strukturvergleich), Zoom-Schritt 61 → 8, 5 Zeiger-Schritte 75 → 20 (Live-Anzeigen abonnieren selbst). +// 9.11.: Wand-Änderung 55 → 42 (Panels lesen Projekt und Objekt-Info selbst aus dem Store, Panel-Host +// mit stabiler Identität, Docks/Datei-Felder/Reiter/Präsentations-Dialog memoisiert). Der Rest ist die +// Objekt-Info der geänderten Wand samt Feldern, die Plan-Ansicht und `App` selbst (Griffe der Auswahl). // Die Schranken unten fangen den Rückfall ab, dass wieder ganze Bäume mitrendern. import type { Page } from "@playwright/test"; import { blurFocus, elementRows, expect, openSample, openTab, startNewProject, test } from "./app"; @@ -128,7 +131,7 @@ test("Neurendern zählen: Wand-Änderung, Zoom- und Zeiger-Schritt", async ({ pa for (let k = 1; k <= 5; k++) await page.mouse.move(box.x + box.width / 2 + k * 7, box.y + box.height / 2 + k * 5); }); - expect(edit, "Renders je Wand-Änderung").toBeLessThan(90); - expect(zoom, "Renders je Zoom-Schritt").toBeLessThan(25); - expect(pointer, "Renders je 5 Zeiger-Schritte").toBeLessThan(40); + expect(edit, "Renders je Wand-Änderung").toBeLessThan(50); + expect(zoom, "Renders je Zoom-Schritt").toBeLessThan(12); + expect(pointer, "Renders je 5 Zeiger-Schritte").toBeLessThan(25); }); diff --git a/src/App.tsx b/src/App.tsx index 93cfe35e..839ae91f 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -832,21 +832,32 @@ export default function App() { onToolClick: toolHandlers.onToolClick, onToolCommit: toolHandlers.onToolCommit, onMeshImport, + // Versteckte Datei-Felder (memoisiert). + openImportForAnyFile, + importStepFile, + importIfcFile, + onImageOrPdfFileChosen, + onProjectFileChosen, + onProjectTemplateFileChosen, }); const contentToolHandlers: ToolHandlers = useMemo( () => ({ onToolMove: ev.onToolMove, onToolClick: ev.onToolClick, onToolCommit: ev.onToolCommit, draft }), [ev, draft], ); const viewTabsState = useViewTabs(); + // `autoName` liest die Zeichnungsebenen (Name, Sichtbarkeit): neue Funktion, wenn sie sich ändern, + // damit die Reiter-Titel nachziehen (die Host-Handler selbst sind stabil, [121]). + const drawingLevels = project.drawingLevels; const viewSnapshotTabs = useMemo( () => ({ tabs: viewTabsState, onActivate: baseHost.onActivateViewTab, onNew: baseHost.onNewViewTab, onClose: baseHost.onCloseViewTab, - autoName: baseHost.viewTabAutoName, + autoName: (levelId?: string) => baseHost.viewTabAutoName(levelId), }), - [baseHost, viewTabsState], + // eslint-disable-next-line react-hooks/exhaustive-deps + [baseHost, viewTabsState, drawingLevels], ); // In-App-Menüleiste (nur ohne natives Menü) und Ansichts-Ribbon als memoisierte Elemente → ui/useTopBarElements.tsx. const { menuBarEl, viewControlsEl } = useTopBarElements({ @@ -896,12 +907,12 @@ export default function App() { imageInputRef={imageInputRef} projectFileInputRef={projectFileInputRef} projectTemplateFileInputRef={projectTemplateFileInputRef} - openImportForAnyFile={openImportForAnyFile} - importStepFile={importStepFile} - importIfcFile={importIfcFile} - onImageOrPdfFileChosen={onImageOrPdfFileChosen} - onProjectFileChosen={onProjectFileChosen} - onProjectTemplateFileChosen={onProjectTemplateFileChosen} + openImportForAnyFile={ev.openImportForAnyFile} + importStepFile={ev.importStepFile} + importIfcFile={ev.importIfcFile} + onImageOrPdfFileChosen={ev.onImageOrPdfFileChosen} + onProjectFileChosen={ev.onProjectFileChosen} + onProjectTemplateFileChosen={ev.onProjectTemplateFileChosen} notify={notify} onMeshImport={ev.onMeshImport} /> diff --git a/src/DrawingTabs.tsx b/src/DrawingTabs.tsx index 48aa84bd..01709a14 100644 --- a/src/DrawingTabs.tsx +++ b/src/DrawingTabs.tsx @@ -9,7 +9,9 @@ // // Bezeichner englisch, UI-Text/Kommentare deutsch (CONVENTIONS.md). -import type { Project } from "./model/types"; +import { memo } from "react"; +import type { ViewSnapshot } from "./model/types"; +import { useStore } from "./state/appStore"; import { tabTitle, type ViewTab, type ViewTabsState } from "./state/viewTabs"; import { t } from "./i18n"; @@ -23,14 +25,11 @@ export interface ViewSnapshotTabsHandlers { autoName: (levelId?: string) => string; } -export function DrawingTabs({ - project, - handlers, -}: { - project: Project; - handlers: ViewSnapshotTabsHandlers; -}) { - const snapshots = project.viewSnapshots ?? []; +const NO_SNAPSHOTS: ViewSnapshot[] = []; + +/** Memoisiert ([121]): rendert nur, wenn sich Ausschnitte oder Reiter-Handler ändern, nicht bei jeder Op. */ +export const DrawingTabs = memo(function DrawingTabs({ handlers }: { handlers: ViewSnapshotTabsHandlers }) { + const snapshots = useStore((s) => s.project.viewSnapshots) ?? NO_SNAPSHOTS; const { tabs, onActivate, onNew, onClose, autoName } = handlers; const title = (tab: ViewTab) => tabTitle(tab, snapshots, (tb) => autoName(tb.id === tabs.activeId ? undefined : tb.state?.activeLevelId)); @@ -78,4 +77,4 @@ export function DrawingTabs({ ); -} +}); diff --git a/src/panels/AreaTableSection.tsx b/src/panels/AreaTableSection.tsx index 792835d6..5683ee3c 100644 --- a/src/panels/AreaTableSection.tsx +++ b/src/panels/AreaTableSection.tsx @@ -8,7 +8,6 @@ import { useMemo, useState } from "react"; import { t } from "../i18n"; -import { usePanelHost } from "./host"; import { areaReportToCsv, buildAreaReport, buildAreaReportPdf } from "../core"; import type { AgfBasis } from "../core"; import { DEFAULT_AREA_INPUTS, ivhbOptionsOf, type AreaInputs } from "./areaInputs"; @@ -18,8 +17,7 @@ import { useStore } from "../state/appStore"; const BASES: AgfBasis[] = ["ngf", "gf", "nf"]; export function AreaTableSection() { - const host = usePanelHost(); - const project = host.project; + const project = useStore((s) => s.project); const [inputs, setInputs] = useState(DEFAULT_AREA_INPUTS); const notify = useStore((s) => s.notify); const report = useMemo( diff --git a/src/panels/AttributesPanel.tsx b/src/panels/AttributesPanel.tsx index b39bf922..57e0fdd9 100644 --- a/src/panels/AttributesPanel.tsx +++ b/src/panels/AttributesPanel.tsx @@ -11,7 +11,7 @@ // Wert"; ein Wechsel auf „Nach Ebene"/„Nach Bauteil" löscht den Wert wieder // (siehe host.ts: onSetSelection{Foreground,Background,StrokeWeight,Hatch}Source). // -// Daten/Handler kommen ausschließlich über usePanelHost (kein Prop-Drilling). +// Handler kommen über usePanelHost, Projekt und Objekt-Info aus dem Store ([121]). // Es werden NUR Eigenschaften angeboten, die der Host-Kontrakt tatsächlich // setzen kann — keine Stubs/Fake-Setter (Konvention wire-dont-stub). Felder ohne // echten Setter (Linienstil) werden read-only/informativ gezeigt; Felder, die @@ -23,6 +23,8 @@ // Alle sichtbaren Texte über t(...). import { Fragment } from "react"; +import { useSelectionInfo } from "../state/useSelectionInfo"; +import { useStore } from "../state/appStore"; import type { ReactNode } from "react"; import { t } from "../i18n"; import { formatM, wallTypeLabel } from "../model/types"; @@ -78,8 +80,8 @@ function uiSourceOf( export function AttributesPanel() { const host = usePanelHost(); - const sel = host.selection; - const { project } = host; + const project = useStore((s) => s.project); + const sel = useSelectionInfo(); // Wandtyp-/Deckentyp-Wahl für das NEUE Bauteil (was gezeichnet wird) — früher // in der Werkzeug-Sidebar (ToolsPanel), seit deren Entfernung hier. Erscheint @@ -127,7 +129,7 @@ export function AttributesPanel() { } const isDrawing = sel.kind === "drawing2d"; - const sheetUnits = unitsForLevel(host.project.drawingLevels.find((z) => z.id === sel.floorId)); + const sheetUnits = unitsForLevel(project.drawingLevels.find((z) => z.id === sel.floorId)); const sizeText = (m: number): string => (sheetUnits.perMeter === 1 ? formatM(m) : `${fmtLength(sheetUnits, m).replace(/mm$/, "")} mm`); // Strichstärke: Wand/Decke/Stütze/Drawing2D tragen einen eigenen Override // (`strokeWeight`/`weightMm`) + Quellen-Dropdown; andere Elementarten erben diff --git a/src/panels/BcfPanel.tsx b/src/panels/BcfPanel.tsx index 50966c4d..350891b0 100644 --- a/src/panels/BcfPanel.tsx +++ b/src/panels/BcfPanel.tsx @@ -14,7 +14,6 @@ import { useMemo, useRef } from "react"; import { t } from "../i18n"; -import { usePanelHost } from "./host"; import { getState, useStore } from "../state/appStore"; import { fromIdLists, toIdLists } from "../state/selection"; import { saveBinaryFile } from "../native/saveFile"; @@ -92,7 +91,7 @@ function cameraText(c: BcfCamera): string { } export function BcfPanel() { - const host = usePanelHost(); + const project = useStore((s) => s.project); const notify = useStore((s) => s.notify); const session = useBcfSession(); const inputRef = useRef(null); @@ -117,7 +116,7 @@ export function BcfPanel() { /** Kamera, Schnittebene und Bauteile eines Viewpoints im Modell zeigen. */ const showViewpoint = (vp: BcfViewpoint | null, topicGuids: string[]) => { - const origin = projectGeoOrigin(host.project); + const origin = projectGeoOrigin(project); if (vp?.camera || (vp && vp.clippingPlanes.length > 0)) { if (!viewportAvailable()) { notify(t("bcf.noViewport"), "warning"); @@ -141,7 +140,7 @@ export function BcfPanel() { if (guids.length === 0) return; // GlobalIds brauchen das Format-Modul (Rust-Hash); nach dem Öffnen ist es geladen. void loadFileio().then(() => { - const { selection } = resolveGuids(host.project, guids); + const { selection } = resolveGuids(project, guids); const found = bcfSelectionSize(selection); applySelection(selection); notify(t("bcf.components", { found, total: guids.length }), found > 0 ? "info" : "warning"); @@ -161,18 +160,18 @@ export function BcfPanel() { const captureViewpoint = async (): Promise => { await loadFileio(); const sel = currentSelection(); - const guids = bcfSelectionSize(sel) > 0 ? selectionToGuids(host.project, sel) : []; + const guids = bcfSelectionSize(sel) > 0 ? selectionToGuids(project, sel) : []; const camera = getCamera(); const png = camera ? await captureSnapshot() : null; if (camera && !png) notify(t("bcf.noSnapshot"), "info"); - return viewpointForTopic({ guid: uuid(), ifcGuids: guids, camera, snapshotPng: png, origin: projectGeoOrigin(host.project) }); + return viewpointForTopic({ guid: uuid(), ifcGuids: guids, camera, snapshotPng: png, origin: projectGeoOrigin(project) }); }; const save = async () => { if (!file) return; try { const bytes = await writeBcf(file, session.version); - const name = session.fileName.replace(/\.(bcf|bcfzip|zip)$/i, "") || host.project.name || "themen"; + const name = session.fileName.replace(/\.(bcf|bcfzip|zip)$/i, "") || project.name || "themen"; if (await saveBinaryFile(bytes, `${name}.bcfzip`, "application/zip")) { setBcfSession({ dirty: false, fileName: `${name}.bcfzip` }); notify(t("bcf.saved"), "info"); @@ -197,7 +196,7 @@ export function BcfPanel() { now: now(), viewpoints: vp.selection.length > 0 || vp.camera ? [vp] : [], }); - const base = file ?? emptyBcf(host.project.id, host.project.name ?? ""); + const base = file ?? emptyBcf(project.id, project.name ?? ""); setBcfSession({ file: addTopic(base, tp), dirty: true, selectedGuid: topicGuid }); }; @@ -233,7 +232,6 @@ export function BcfPanel() { const clipping = topic?.viewpoints.flatMap((v) => v.clippingPlanes) ?? []; const camera = topic?.viewpoints.find((v) => v.camera)?.camera ?? null; const topicGuids = topic ? [...new Set(topic.viewpoints.flatMap(viewpointGuids))] : []; - const project = host.project; const foundCount = useMemo( () => (topicGuids.length > 0 && fileioLoaded() ? bcfSelectionSize(resolveGuids(project, topicGuids).selection) : 0), // eslint-disable-next-line react-hooks/exhaustive-deps @@ -244,7 +242,7 @@ export function BcfPanel() {
- + { const f = e.target.files?.[0]; e.target.value = ""; if (f) void openFile(f); }} />
diff --git a/src/panels/ContextObjectProps.tsx b/src/panels/ContextObjectProps.tsx index 7774bb85..49faa6c0 100644 --- a/src/panels/ContextObjectProps.tsx +++ b/src/panels/ContextObjectProps.tsx @@ -63,6 +63,7 @@ const RESMOOTH_PASSES = [1, 2, 4] as const; /** Felder eines Kontext-Objekts; `null` für Arten ohne eigene Einstellungen (Höhenlinien, Luftbild). */ export function ContextObjectProps({ obj, quantities }: { obj: ContextObject; quantities: readonly ExcavationQuantity[] }) { const host = usePanelHost(); + const project = useStore((s) => s.project); const notify = useStore((s) => s.notify); const regenerateTerrain = useStore((s) => s.regenerateTerrain); const resmoothTerrain = useStore((s) => s.resmoothTerrain); @@ -100,8 +101,8 @@ export function ContextObjectProps({ obj, quantities }: { obj: ContextObject; qu } if (obj.type === "terrainMesh") { - const cat = obj.categoryCode ? flattenCategories(host.project.layers).find((c) => c.code === obj.categoryCode) : undefined; - const hasSource = (host.project.context ?? []).some((o) => o.type === "contourSet"); + const cat = obj.categoryCode ? flattenCategories(project.layers).find((c) => c.code === obj.categoryCode) : undefined; + const hasSource = (project.context ?? []).some((o) => o.type === "contourSet"); return (
- + {/* Firstrichtung (X/Y) — nur bei Formen mit First relevant. */} {roof.shape !== "flach" && roof.shape !== "zelt" && ( @@ -1580,6 +1585,7 @@ export function StairSection({ stair: StairInfo; host: ReturnType; }) { + const project = useStore((s) => s.project); return ( <>
@@ -1593,7 +1599,7 @@ export function StairSection({ onChange={(v) => host.onSetStairType(v)} options={[ { value: "", label: t("objinfo.type.none") }, - ...(host.project.stairTypes ?? []).map((st) => ({ + ...(project.stairTypes ?? []).map((st) => ({ value: st.id, label: st.name, })), @@ -1757,6 +1763,7 @@ export function OpeningSection({ opening: OpeningInfo; host: ReturnType; }) { + const project = useStore((s) => s.project); const isDoor = opening.kind === "door"; if (opening.hostRoofId || opening.hostCeilingId) { return ; @@ -1776,8 +1783,8 @@ export function OpeningSection({ options={[ { value: "", label: t("objinfo.type.none") }, ...(isDoor - ? host.project.doorTypes ?? [] - : host.project.windowTypes ?? [] + ? project.doorTypes ?? [] + : project.windowTypes ?? [] ).map((ty) => ({ value: ty.id, label: ty.name })), ]} title={t("objinfo.opening.type")} @@ -2010,7 +2017,8 @@ function SurfaceOpeningSection({ opening: OpeningInfo; host: ReturnType; }) { - const info = surfaceOpeningInfo(host.project, opening.id); + const project = useStore((s) => s.project); + const info = surfaceOpeningInfo(project, opening.id); const roof = !!opening.hostRoofId; const hp = opening.hostPoint ?? { x: 0, y: 0 }; return ( @@ -2024,7 +2032,7 @@ function SurfaceOpeningSection({ onChange={(v) => host.onSetOpeningType(v)} options={[ { value: "", label: t("objinfo.type.none") }, - ...(host.project.windowTypes ?? []).map((ty) => ({ value: ty.id, label: ty.name })), + ...(project.windowTypes ?? []).map((ty) => ({ value: ty.id, label: ty.name })), ]} title={t("objinfo.opening.type")} width={106} @@ -2105,6 +2113,7 @@ export function CeilingSection({ ceiling: CeilingInfo; host: ReturnType; }) { + const project = useStore((s) => s.project); const isSingle = ceiling.singleLayer; const multiPresets = ceiling.ceilingTypes.filter((ct) => ct.layerCount > 1); @@ -2175,7 +2184,7 @@ export function CeilingSection({ {t("objinfo.ceiling.refFloor")} {ceiling.floorName}
- + {/* Fläche + Volumen (read-only). */}
@@ -2254,6 +2263,7 @@ export function WallSection({ wall: WallInfo; host: ReturnType; }) { + const project = useStore((s) => s.project); // Aufbau-Typ-Segment: einschichtig vs. mehrschichtig. Aus dem Modell // abgeleitet (singleLayer); der Umschalter auf „mehrschichtig" wählt einen // mehrschichtigen Wandtyp-Preset (erster mit >1 Schicht), auf „einschichtig" @@ -2393,7 +2403,7 @@ export function WallSection({ {t("objinfo.wall.refFloor")} {wall.floorName}
- + {/* Länge + Volumen (read-only). Volumen ist NETTO — Fenster/Türen abgezogen; der Titel zeigt zusätzlich das Bruttovolumen. */} @@ -2562,15 +2572,15 @@ const TREE_STATUS: TreeStatus[] = ["existing", "new", "remove"]; const TREE_FOLIAGE: TreeFoliage[] = ["deciduous", "conifer"]; export function TreeSection({ ids }: { ids: readonly string[] }) { - const host = usePanelHost(); + const project = useStore((s) => s.project); const applyChange = useStore((s) => s.applyChange); - const trees = (host.project.trees ?? []).filter((x) => ids.includes(x.id)); + const trees = (project.trees ?? []).filter((x) => ids.includes(x.id)); const tree = trees[0]; if (!tree) return
{t("objinfo.empty")}
; const locked = !!tree.locked; const set = (patch: Partial, all = false) => applyChange((p) => (all ? trees : [tree]).filter((x) => !x.locked).flatMap((x) => patchItem(p, "trees", x.id, patch))); - const level = host.project.drawingLevels.find((l) => l.id === tree.floorId); + const level = project.drawingLevels.find((l) => l.id === tree.floorId); return (
diff --git a/src/panels/OpeningScheduleSection.tsx b/src/panels/OpeningScheduleSection.tsx index 31b1de5b..58ffd6ab 100644 --- a/src/panels/OpeningScheduleSection.tsx +++ b/src/panels/OpeningScheduleSection.tsx @@ -19,7 +19,7 @@ const m2 = (v: number) => v.toFixed(2); export function OpeningScheduleSection() { const host = usePanelHost(); - const project = host.project; + const project = useStore((s) => s.project); const applyChange = useStore((s) => s.applyChange); const notify = useStore((s) => s.notify); const rows = useMemo(() => openingSchedule(project), [project]); diff --git a/src/panels/PointCloudSection.tsx b/src/panels/PointCloudSection.tsx index f47ee426..a4cae232 100644 --- a/src/panels/PointCloudSection.tsx +++ b/src/panels/PointCloudSection.tsx @@ -3,8 +3,8 @@ // (`state/pointCloudStore.ts`), nicht im Projekt — Änderungen hier sind kein Undo-Schritt. import { t } from "../i18n"; +import { useStore } from "../state/appStore"; import type { TranslationKey } from "../i18n"; -import { usePanelHost } from "./host"; import { MAX_POINT_SIZE, MIN_POINT_SIZE, @@ -26,7 +26,7 @@ const MODE_KEY: Record = { }; export function PointCloudSection() { - const host = usePanelHost(); + const project = useStore((s) => s.project); const clouds = usePointClouds(); return (
@@ -91,7 +91,7 @@ export function PointCloudSection() { {t("pointCloud.count", { n: c.data.report.pointsKept.toLocaleString("de-CH") })} {c.data.report.epsg !== null && <> · EPSG {c.data.report.epsg}} {" · "} - {placementHints(placementOf(c.data, host.project)) + {placementHints(placementOf(c.data, project)) .map((k) => t(k)) .join(" ")}
diff --git a/src/panels/ProgramCompareSection.tsx b/src/panels/ProgramCompareSection.tsx index 5ceeefdb..d6918992 100644 --- a/src/panels/ProgramCompareSection.tsx +++ b/src/panels/ProgramCompareSection.tsx @@ -40,7 +40,7 @@ function SumRow({ s, label, total }: { s: CompareSum; label: string; total?: boo export function ProgramCompareSection({ statusLabel }: { statusLabel: (status: CompareRow["status"]) => string }) { const host = usePanelHost(); - const project = host.project; + const project = useStore((s) => s.project); const applyChange = useStore((s) => s.applyChange); const notify = useStore((s) => s.notify); const c = compareRoomProgram(project); diff --git a/src/panels/PublishSection.tsx b/src/panels/PublishSection.tsx index d27ffd78..d23fa119 100644 --- a/src/panels/PublishSection.tsx +++ b/src/panels/PublishSection.tsx @@ -3,6 +3,7 @@ // Reine Verdrahtung über den Host; Logik in `export/publishSet.ts`, `state/publishActions.ts`. import { useState } from "react"; +import { useStore } from "../state/appStore"; import { usePanelHost } from "./host"; import type { LayoutPaperFormat, PublishSet } from "../model/types"; import { PAPER_FORMATS } from "../model/layoutModel"; @@ -27,7 +28,7 @@ export function move(list: readonly string[], i: number, d: number): string[] { function SetEditor({ set }: { set: PublishSet }) { const host = usePanelHost(); - const project = host.project; + const project = useStore((s) => s.project); const patch = (p: Partial>) => host.onPatchPublishSet(set.id, p); const layouts = project.layouts ?? []; const snapshots = project.viewSnapshots ?? []; @@ -149,7 +150,7 @@ function SetEditor({ set }: { set: PublishSet }) { export function PublishSection() { const host = usePanelHost(); - const project = host.project; + const project = useStore((s) => s.project); const sets = project.publishSets ?? []; const log = (project.publishLog ?? []).slice(-LOG_SHOWN).reverse(); const [open, setOpen] = useState(null); diff --git a/src/panels/RoomBalancePanel.tsx b/src/panels/RoomBalancePanel.tsx index 48ef0077..e11b4acc 100644 --- a/src/panels/RoomBalancePanel.tsx +++ b/src/panels/RoomBalancePanel.tsx @@ -4,11 +4,11 @@ // (KennzahlenSection). Fläche/Bilanz werden LIVE aus den Raum-Umrissen abgeleitet // (geometry/roomArea: evaluateRoom/balance/roomsToCsv) — nie gespeichert. // -// Daten kommen über usePanelHost (project.rooms). Bezeichner englisch, UI-Text +// Daten kommen aus dem Store (project.rooms). Bezeichner englisch, UI-Text // deutsch via t() (CONVENTIONS.md). import { t } from "../i18n"; -import { usePanelHost } from "./host"; +import { useStore } from "../state/appStore"; import { balance, evaluateRoom, roomsToCsv, siaLabelFull } from "../core"; import type { Room } from "../model/types"; import { roomDisplayName } from "../model/roomStamp"; @@ -36,9 +36,9 @@ function floorNameOf( } export function RoomBalancePanel() { - const host = usePanelHost(); - const rooms = host.project.rooms ?? []; - const levels = host.project.drawingLevels; + const project = useStore((s) => s.project); + const rooms = project.rooms ?? []; + const levels = project.drawingLevels; if (rooms.length === 0) { return ( diff --git a/src/panels/RoomBookSection.tsx b/src/panels/RoomBookSection.tsx index 5b29ad7c..90d5c77c 100644 --- a/src/panels/RoomBookSection.tsx +++ b/src/panels/RoomBookSection.tsx @@ -5,7 +5,6 @@ import { useMemo } from "react"; import { t } from "../i18n"; -import { usePanelHost } from "./host"; import { areaReportToCsv, buildAreaReportPdf, buildRoomBookReport, roomBook, usageLabel } from "../core"; import { downloadCsv } from "./downloadFile"; import { useStore } from "../state/appStore"; @@ -13,7 +12,7 @@ import { useStore } from "../state/appStore"; const m2 = (v: number) => v.toFixed(2); export function RoomBookSection() { - const project = usePanelHost().project; + const project = useStore((s) => s.project); const notify = useStore((s) => s.notify); const book = useMemo(() => roomBook(project), [project]); const stem = `${project.name || "projekt"}-raumbuch`; diff --git a/src/panels/SitePanel.tsx b/src/panels/SitePanel.tsx index 9b8c1b8e..c17a21f2 100644 --- a/src/panels/SitePanel.tsx +++ b/src/panels/SitePanel.tsx @@ -1,6 +1,6 @@ // Inhalts-Panel „Gelände & Kontext" — verwaltet die Kontext-Schicht -// (importierte Meshes, Höhenlinien-Sätze, abgeleitetes Gelände-TIN). Daten/ -// Handler kommen über usePanelHost (kein Prop-Drilling). +// (importierte Meshes, Höhenlinien-Sätze, abgeleitetes Gelände-TIN). Handler +// kommen über usePanelHost, die Kontext-Objekte aus dem Store (`project.context`, [121]). // // Aufbau: // • Aktions-Zeile: „DXF importieren" (öffnet den in App montierten Datei- @@ -79,12 +79,15 @@ function groupByLayer(objects: ContextObject[]): { layer: string; items: Context return order.map((layer) => ({ layer, items: byLayer.get(layer)! })); } +const NO_CONTEXT: ContextObject[] = []; + export function SitePanel() { const host = usePanelHost(); + const project = useStore((s) => s.project); // Gewählte Kontext-Objekte schmal aus dem Store ([121], [130]). const selectedContextObjectIds = useStore((s) => s.selection.contextObjects); const notify = useStore((s) => s.notify); - const objects = host.contextObjects; + const objects = project.context ?? NO_CONTEXT; const contourSets = objects.filter((o) => o.type === "contourSet"); // Standort-Import-Dialog (geo.admin/OSM) offen? @@ -100,7 +103,7 @@ export function SitePanel() { // [T6] Glätten beim Erzeugen (Bruchkanten werden immer erzwungen). const [smooth, setSmooth] = useState(true); // [68] Mengen der Baugruben (Kern), nur neu, wenn sich das Projekt ändert. - const quantities = useMemo(() => excavationQuantities(host.project), [host.project]); + const quantities = useMemo(() => excavationQuantities(project), [project]); const onGenerate = () => { if (!effectiveSet) return; @@ -147,7 +150,7 @@ export function SitePanel() { host.onAddContextObjects(objs)} onClose={() => setCtxImportOpen(false)} - geoAnchor={host.project.geoAnchor} + geoAnchor={project.geoAnchor} onSetGeoAnchor={host.onSetGeoAnchor} /> )} diff --git a/src/panels/SiteRulesSection.tsx b/src/panels/SiteRulesSection.tsx index cdaf015b..48bbf144 100644 --- a/src/panels/SiteRulesSection.tsx +++ b/src/panels/SiteRulesSection.tsx @@ -3,7 +3,7 @@ // Grundriss entsteht aus `Project.siteRules` (`plan/generatePlan/siteRules.ts`). import { t } from "../i18n"; -import { usePanelHost } from "./host"; +import { useSelectionInfo } from "../state/useSelectionInfo"; import { useStore } from "../state/appStore"; import { checkSiteRules, patchItem, setField } from "../core"; import type { Project, SiteRules } from "../model/types"; @@ -45,15 +45,15 @@ function withProjection(e: T, on: boolea } export function SiteRulesSection() { - const host = usePanelHost(); + const project = useStore((s) => s.project); const applyChange = useStore((s) => s.applyChange); - const rules = host.project.siteRules; - const sel = host.selection; - const selDrawing = sel?.kind === "drawing2d" ? host.project.drawings2d.find((d) => d.id === sel.id) : undefined; + const rules = project.siteRules; + const sel = useSelectionInfo(); + const selDrawing = sel?.kind === "drawing2d" ? project.drawings2d.find((d) => d.id === sel.id) : undefined; const selParcel = parcelFromDrawing(selDrawing); const selLine = lineFromDrawing(selDrawing); // Vorsprung markieren: gewählte Decke (Balkon), freier Körper oder Wand (Erker). - const selProjection = projectionTarget(host.project, sel); + const selProjection = projectionTarget(project, sel); const write = (fn: (r: SiteRules) => SiteRules | undefined, key?: string) => applyChange((p: Project) => { @@ -83,7 +83,7 @@ export function SiteRulesSection() { ); } - const check = checkSiteRules(host.project); + const check = checkSiteRules(project); const n = rules.parcel.length; const ok = check !== null && check.violationArea < 0.01 && !check.heightExceeded && !check.profileExceeded; diff --git a/src/panels/SunStudySection.tsx b/src/panels/SunStudySection.tsx index 2264c150..b5af1454 100644 --- a/src/panels/SunStudySection.tsx +++ b/src/panels/SunStudySection.tsx @@ -3,7 +3,6 @@ // und im 3D (render3d-Shadow-Mapping, `viewport/sun3d.ts`, [64]) aus `Project.sunStudy`; der Regler schreibt mit coalesceKey (ein Undo-Schritt je Ziehen). import { t } from "../i18n"; -import { usePanelHost } from "./host"; import { useStore } from "../state/appStore"; import { projectLatLon, setField, sunPosition } from "../core"; import type { SunStudy } from "../model/types"; @@ -17,9 +16,9 @@ const PRESETS: { key: "sun.equinox" | "sun.summer" | "sun.winter"; md: string }[ ]; export function SunStudySection() { - const host = usePanelHost(); + const project = useStore((s) => s.project); const applyChange = useStore((s) => s.applyChange); - const study: SunStudy = host.project.sunStudy ?? { when: defaultStudyIso(), show: false }; + const study: SunStudy = project.sunStudy ?? { when: defaultStudyIso(), show: false }; const local = isoToLocal(study.when) ?? isoToLocal(defaultStudyIso())!; const write = (next: SunStudy, key?: string) => applyChange([setField("sunStudy", next)], key); @@ -28,7 +27,7 @@ export function SunStudySection() { if (iso) write({ ...study, when: iso }, key); }; - const { lat, lon } = projectLatLon(host.project); + const { lat, lon } = projectLatLon(project); const sun = sunPosition(lat, lon, new Date(study.when)); const year = local.date.slice(0, 4); @@ -91,7 +90,7 @@ export function SunStudySection() { {sun.elevation > 0 ? t("sun.position", { az: sun.azimuth.toFixed(0), el: sun.elevation.toFixed(1) }) : t("sun.belowHorizon")} - {!host.project.geoAnchor && · {t("sun.noAnchor")}} + {!project.geoAnchor && · {t("sun.noAnchor")}}
); diff --git a/src/panels/SurfacePatternPlacement.tsx b/src/panels/SurfacePatternPlacement.tsx index 58c3819e..3d39f1ee 100644 --- a/src/panels/SurfacePatternPlacement.tsx +++ b/src/panels/SurfacePatternPlacement.tsx @@ -4,6 +4,7 @@ import { t } from "../i18n"; import type { usePanelHost } from "./host"; +import { useStore } from "../state/appStore"; export function SurfacePatternPlacement({ kind, @@ -14,7 +15,7 @@ export function SurfacePatternPlacement({ id: string; host: ReturnType; }) { - const p = host.project; + const p = useStore((s) => s.project); const el = kind === "wall" ? p.walls.find((w) => w.id === id) : p.roofs?.find((r) => r.id === id); if (!el || !host.onSetSurfacePatternPlacement) return null; const typeId = kind === "wall" ? (el as { wallTypeId?: string }).wallTypeId : (el as { roofTypeId?: string }).roofTypeId; diff --git a/src/panels/ViewSnapshotsPanel.tsx b/src/panels/ViewSnapshotsPanel.tsx index 9a35b647..9d28ce0a 100644 --- a/src/panels/ViewSnapshotsPanel.tsx +++ b/src/panels/ViewSnapshotsPanel.tsx @@ -27,6 +27,7 @@ // Bezeichner englisch, UI-Text/Kommentare deutsch (CONVENTIONS.md). import { useMemo, useState } from "react"; +import { useStore } from "../state/appStore"; import { usePanelHost } from "./host"; import type { ViewSnapshot } from "../model/types"; import { @@ -148,8 +149,9 @@ interface Renaming { export function ViewSnapshotsPanel() { const host = usePanelHost(); - const snaps = host.project.viewSnapshots ?? []; - const folders = host.project.viewSnapshotFolders ?? []; + const project = useStore((s) => s.project); + const snaps = project.viewSnapshots ?? []; + const folders = project.viewSnapshotFolders ?? []; const tree = useMemo( () => buildViewSnapshotTree(folders, snaps), @@ -202,11 +204,11 @@ export function ViewSnapshotsPanel() { selectedSnap.drawingVisibility, ); const ids = new Set(selectedSnap.enabledOverrideRuleIds ?? []); - const overrideNames = (host.project.overrideRules ?? []) + const overrideNames = (project.overrideRules ?? []) .filter((r) => ids.has(r.id)) .map((r) => r.name); return { layerCombo, drawingCombo, overrideNames }; - }, [selectedSnap, host]); + }, [selectedSnap, host, project.overrideRules]); // ── Auf-/Zuklappen ──────────────────────────────────────────────────────── const isExpanded = (id: string) => !collapsed.has(id); @@ -673,7 +675,7 @@ export function ViewSnapshotsPanel() { }} > - {(host.project.viewTemplates ?? []).map((tpl) => ( + {(project.viewTemplates ?? []).map((tpl) => ( diff --git a/src/panels/host.ts b/src/panels/host.ts index 4706c116..23739697 100644 --- a/src/panels/host.ts +++ b/src/panels/host.ts @@ -30,7 +30,6 @@ import type { LineStyle, MasterLayout, PublishSet, - Project, SiaCategory, SliceTermination, Stair, @@ -42,7 +41,6 @@ import type { } from "../model/types"; import type { MeasurementReadout, SnapSettings, ToolId } from "../tools/types"; import type { TerrainOptions } from "../model/terrain"; -import type { SelectionInfo } from "../state/selectionInfo"; import type { TextStylePreset } from "../text/richText"; import type { ScheduleKind } from "../export/exportSchedule"; import type { DetailLevel } from "../model/viewTypes"; @@ -69,8 +67,9 @@ export interface DisplayModeControl { * Closure über setProject existiert. */ export interface PanelHostValue { - // Projektzustand (Single Source of Truth aus App). - project: Project; + // Projekt und Objekt-Info der Auswahl sind KEINE Host-Felder ([121]): Panels lesen sie selbst + // aus dem Store (`useStore((s) => s.project…)`, `useSelectionInfo()`), damit eine Op nur die + // Panels neu rendert, die die geänderten Daten zeigen. // Aktive Auswahl (Zeichnungsebene) — Arbeitsfokus für „active"/„grey". activeLevelId: string; @@ -173,12 +172,7 @@ export interface PanelHostValue { onImportHatches: (hatches: Omit[]) => void; // ── Selektions-Attribute (Attributes-/Object-Info-Paletten) ───────────── - /** - * Normalisierte, effektiv aufgelöste Sicht auf das ERSTE selektierte Element - * (oder `null`). Die Paletten lesen daraus Farbe/Strichstärke/Füllung/bbox - * und grauen nicht-anwendbare Felder per `selection.kind` aus. - */ - selection: SelectionInfo | null; + // Die Sicht auf das erste gewählte Element liefert `useSelectionInfo()` (state/useSelectionInfo.ts). /** * Live-Messwerte des Mess-Werkzeugs (Länge/Fläche/Winkel), oder `null`, wenn * gerade nicht gemessen wird. Das Objekt-Info-Panel zeigt sie dauerhaft an, @@ -597,8 +591,7 @@ export interface PanelHostValue { onSetColumnRotation: (deg: number) => void; // ── Site-/Kontext-Schicht (SitePanel) ─────────────────────────────────── - /** Aktuelle Kontext-Objekte (Meshes/Konturen/Gelände) aus `project.context`. */ - contextObjects: ContextObject[]; + // Die Kontext-Objekte selbst liest das Panel aus dem Store (`project.context`). /** Fügt mehrere Kontext-Objekte hinzu (z. B. aus einem DXF-Import). */ onAddContextObjects: (objs: ContextObject[]) => void; /** Entfernt ein Kontext-Objekt per ID. */ diff --git a/src/state/README.md b/src/state/README.md index fc0cc38c..4ab00d6d 100644 --- a/src/state/README.md +++ b/src/state/README.md @@ -5,7 +5,9 @@ Zustand der Oberfläche: ein Store mit Slices, Hooks, die `App.tsx` entlasten, u die **Leseansicht** (`project`) und ändert sie ausschliesslich über Ops, die der Kern angenommen hat. Kein Zustand-/Redux-Paket: `store.ts` ist ein kleiner eigener Store auf `useSyncExternalStore`. -Komponenten lesen mit `useStore(selector)` nur ihren Ausschnitt. +Komponenten lesen mit `useStore(selector)` nur ihren Ausschnitt — möglichst schmal +(`s.project.drawingLevels` statt `s.project`), denn jede Op erzeugt ein neues `project`, aber nur die +geänderten Listen sind neu ([121]). ## Store und Slices @@ -40,7 +42,8 @@ Ergebnisse weiter; Komponenten-Teile der App liegen in `src/ui/AppDialogs.tsx`, | `useKeyboardShortcuts.ts`, `keyboardShortcuts.ts`, `commandKeys.ts` | Tastenkürzel, Esc/Enter laufender Befehle | | `useDisplayResolvers.ts` | sichtbar, gedimmt, gesperrt je Ebene und Kategorie | | `useTextTarget.ts`, `useSectionLineState.ts`, `useStatusBarInfo.ts` | Text-Ziel der Formatierleiste; Objekt-Info, Schnittlinie, 3D-Live-Schnitt; Status-Leiste | -| `usePanelHostBase.ts` | Host-Wert für die Panels | +| `usePanelHostBase.ts`, `panelHost/` | Host-Wert für die Panels: Zusammenbau aus Teil-Bauern je Bereich (`toolsHost`, `selectionStyleHost`, `elementAttributesHost`, `siteHost`, `viewSnapshotsHost` + `viewState`, `layoutsHost`); `stableHost.ts` hält die Identität fest (Handler als Trampoline), solange sich kein Wert-Feld ändert | +| `useSelectionInfo.ts` | Objekt-Info der Auswahl für Panels (`useSelectionInfo()`) und App (`selectionInfoFor`), einmal je Projekt/Auswahl gerechnet, inhaltlich stabil | | `useProjectFileActions.ts`, `useImportHandling.ts`, `useModelImport.ts`, `useExportHandlers.ts` | Datei öffnen und speichern, Importe (Bild, Drag & Drop; IFC/STEP/Mesh), Plan-Export | | `useResourceHandlers.ts`, `useSettingsHost.ts` | Ressourcen-Fenster; Einstellungen, Offline, KI-Zugriff, Start-Protokoll | | `useNativeWindowHosts.ts`, `useNativeMenu.ts` | native Nebenfenster und macOS-Menüleiste (ausserhalb von Tauri No-ops) | @@ -51,6 +54,7 @@ Ergebnisse weiter; Komponenten-Teile der App liegen in `src/ui/AppDialogs.tsx`, | Datei | Inhalt | |---|---| | `selectionInfo.ts` | Objekt-Info der Auswahl (Fassade über den Kern, `selection_info.rs`) | +| `dataEqual.ts` | Strukturvergleich reiner Daten (Objekt-Info, Zustand der Nebenfenster) | | `viewTemplates.ts` | Ansichtsvorlagen als Ops | | `viewSnapshots.ts`, `viewSnapshotFolders.ts`, `viewTabs.ts` | Ausschnitte, ihre Ordner, Zeichnungs-Reiter | | `groupActions.ts` | Gruppen erzeugen, auflösen, betreten | @@ -63,5 +67,8 @@ Ergebnisse weiter; Komponenten-Teile der App liegen in `src/ui/AppDialogs.tsx`, - Das Projekt ändert sich nur über Ops: `applyChange(ops | (p) => ops, coalesceKey?)` mit den Helfern aus `src/core/opsBuild.ts`. Kein direktes Setzen von `project`. - Öffnen und Neu über `openProjectFile()` bzw. `loadProject()`; danach ist der Verlauf leer. +- Panels lesen Projektdaten selbst aus dem Store, nicht über den Panel-Host (der trägt nur Handler und + kleine Ansichts-Werte); die Objekt-Info über `useSelectionInfo()`. So rendert eine Op nur die Panels, + deren Daten sich geändert haben ([121], Messung `e2e/renderCount.spec.ts`). - macOS-Nebenfenster (`src/native/*WindowApp.tsx`) haben keinen gemeinsamen Store; ihr Zustand läuft über - die Sync-Brücken in `src/native/`. + die Sync-Brücken in `src/native/` (`windowBridge.ts`: erst ganz, dann nur geänderte Felder als Patch). diff --git a/src/state/panelHost/elementAttributesHost.ts b/src/state/panelHost/elementAttributesHost.ts new file mode 100644 index 00000000..3c9dc57d --- /dev/null +++ b/src/state/panelHost/elementAttributesHost.ts @@ -0,0 +1,332 @@ +// Panel-Host, Teil Bauteil-Attribute der Objekt-Info ([121], aus `usePanelHostBase` herausgelöst): +// Wand, Decke, Öffnung, Dach, Schnitt-/Ansichtslinie, Treppe, Raum, Extrusion und Stütze. Jeder +// Handler wirkt nur bei passender Auswahl (`selection.kind`) und schreibt über die Projekt-Aktionen +// bzw. `applyChange`. + +import { patchItem, removeRoofHole, setRoofEdge } from "../../core"; +import type { FlatHostOpts, HostPart } from "./types"; + +export function buildElementAttributesHost(c: FlatHostOpts) { + const { applyChange, onOpenStampEditor, onToggleSection3dCut, openResources, patchLevel, project, section3dCutId, sectionLine, selection, setCeilingThickness, setOpeningEditorId, setWallThickness, slideOpening, updateCeiling, updateOpening, updateRoof, updateRoom, updateStair, updateWall } = c; + return { + // ── Wand-Attribute (nur bei selektierter Wand) ───────────────────────── + onSetWallReferenceLine: (ref) => { + if (selection?.kind === "wall") + // Benannte Linie gewählt ⇒ freien Fugen-Versatz löschen (er übersteuert sonst). + updateWall(selection.id, { referenceLine: ref, referenceOffset: undefined }); + }, + onSetWallReferenceOffset: (offset) => { + if (selection?.kind === "wall") + updateWall(selection.id, { referenceOffset: offset ?? undefined }); + }, + onSetSurfacePatternPlacement: (patch) => { + if (selection?.kind === "wall") updateWall(selection.id, patch, "surface-pattern"); + else if (selection?.kind === "roof") updateRoof(selection.id, patch, "surface-pattern"); + }, + onSetWallSliceTermination: (termination) => { + if (selection?.kind === "wall") + // "both" ist der Default ⇒ als undefined speichern (Alt-Projekt-Parität). + updateWall(selection.id, { + sliceTermination: termination === "both" ? undefined : termination, + }); + }, + onSetWallRoofAttach: (attach) => { + if (selection?.kind === "wall") + // "auto" ist der Default ⇒ als undefined speichern. + updateWall(selection.id, { roofAttach: attach === "auto" ? undefined : attach === "on" }); + }, + onSetBuildingFlags: (flags) => { + const patch: { isExternal?: boolean; loadBearing?: boolean } = {}; + if (flags.isExternal !== undefined) patch.isExternal = flags.isExternal || undefined; + if (flags.loadBearing !== undefined) patch.loadBearing = flags.loadBearing || undefined; + if (selection?.kind === "wall") updateWall(selection.id, patch); + else if (selection?.kind === "ceiling") updateCeiling(selection.id, patch); + }, + onSetWallType: (wallTypeId) => { + if (selection?.kind === "wall") + updateWall(selection.id, { wallTypeId }); + }, + onSetWallThickness: (thickness) => { + if (selection?.kind === "wall") + setWallThickness(selection.id, thickness); + }, + onSetWallBottom: (anchor) => { + if (selection?.kind === "wall") + updateWall(selection.id, { bottom: anchor ?? undefined }); + }, + onSetWallTop: (anchor) => { + if (selection?.kind === "wall") + updateWall(selection.id, { top: anchor ?? undefined }); + }, + // ── Decken-Attribute (nur bei selektierter Decke) ────────────────────── + onSetCeilingType: (ceilingTypeId) => { + if (selection?.kind === "ceiling") + updateCeiling(selection.id, { ceilingTypeId, thickness: undefined }); + }, + onSetCeilingThickness: (thickness) => { + if (selection?.kind === "ceiling") + setCeilingThickness(selection.id, thickness); + }, + onRemoveCeilingOpening: (index) => { + if (selection?.kind !== "ceiling") return; + const c = (project.ceilings ?? []).find((x) => x.id === selection.id); + if (!c?.openings || index < 0 || index >= c.openings.length) return; + updateCeiling(selection.id, { + openings: c.openings.filter((_, i) => i !== index), + }); + }, + onSetCeilingTop: (anchor) => { + if (selection?.kind === "ceiling") + updateCeiling(selection.id, { top: anchor ?? undefined }); + }, + onSetCeilingBottom: (anchor) => { + if (selection?.kind === "ceiling") + updateCeiling(selection.id, { bottom: anchor ?? undefined }); + }, + // ── Öffnungs-Attribute (nur bei selektierter Öffnung) ────────────────── + onSetOpeningKind: (kind) => { + if (selection?.kind === "opening") + updateOpening( + selection.id, + kind === "door" + ? { kind, sillHeight: 0, hinge: "start", swing: "left", openingDir: "in", swingAngle: 90 } + : { kind }, + ); + }, + onSetOpeningWidth: (width) => { + if (selection?.kind === "opening" && width > 0) + updateOpening(selection.id, { width }); + }, + onSetOpeningHeight: (height) => { + if (selection?.kind === "opening" && height > 0) + updateOpening(selection.id, { height }); + }, + onSetOpeningSill: (sillHeight) => { + if (selection?.kind === "opening" && sillHeight >= 0) + updateOpening(selection.id, { sillHeight }); + }, + onSetOpeningPosition: (position) => { + if (selection?.kind !== "opening" || !Number.isFinite(position)) return; + // [144] Dach-/Deckenöffnung: Feld frei; Wandöffnung: der Kern klemmt auf [0, Wandlänge − Breite] + // (Bogenwand: Bogenlänge) und hält 5 cm vor der Nachbaröffnung an (mit Hinweis). + if (selection.opening?.wallLength == null) updateOpening(selection.id, { position: Math.max(0, position) }); + else slideOpening(selection.id, { position }); + }, + onSetOpeningSwingAngle: (swingAngle) => { + if (selection?.kind === "opening" && swingAngle > 0) + updateOpening(selection.id, { swingAngle }); + }, + onSetOpeningHinge: (hinge) => { + if (selection?.kind === "opening") updateOpening(selection.id, { hinge }); + }, + onSetOpeningSwing: (swing) => { + if (selection?.kind === "opening") updateOpening(selection.id, { swing }); + }, + onSetOpeningDir: (openingDir) => { + if (selection?.kind === "opening") updateOpening(selection.id, { openingDir }); + }, + onSetOpeningWingCount: (wingCount) => { + if (selection?.kind === "opening") + updateOpening(selection.id, { wingCount: Math.max(1, Math.min(4, Math.round(wingCount))) }); + }, + onSetOpeningDoorType: (doorType) => { + if (selection?.kind === "opening") updateOpening(selection.id, { doorType }); + }, + onSetOpeningLintelLines: (lintelLines) => { + if (selection?.kind === "opening") updateOpening(selection.id, { lintelLines }); + }, + onSetOpeningHost: (patch) => { + if (selection?.kind === "opening") updateOpening(selection.id, patch); + }, + onSetOpeningDetailLevel: (detailLevel) => { + if (selection?.kind === "opening") updateOpening(selection.id, { detailLevel }); + }, + onSetOpeningFrameLine: (v) => { + if (selection?.kind === "opening") updateOpening(selection.id, { frameLine: v }); + }, + onSetOpeningFrameViewLine: (v) => { + if (selection?.kind === "opening") updateOpening(selection.id, { frameViewLine: v }); + }, + onSetOpeningSashLine: (v) => { + if (selection?.kind === "opening") updateOpening(selection.id, { sashLine: v }); + }, + onSetOpeningSillLineStyle: (v) => { + if (selection?.kind === "opening") updateOpening(selection.id, { sillLineStyle: v }); + }, + // Typ-Zuweisung (Bibliothek): Tür-/Fenstertyp per typeId; leerer String löst + // die Zuweisung wieder (Inline-Verhalten). + onSetOpeningType: (typeId) => { + if (selection?.kind === "opening") + updateOpening(selection.id, { typeId: typeId || undefined }); + }, + onEditOpeningType: (kind) => { + openResources(kind === "door" ? "doorStyles" : "windowStyles"); + }, + onOpenOpeningEditor: (id) => setOpeningEditorId(id), + // ── Dach-Attribute (nur bei selektiertem Dach) ───────────────────────── + onSetRoofPatch: (patch, coalesceKey) => { + if (selection?.kind === "roof") updateRoof(selection.id, patch, coalesceKey); + }, + onSetRoofEdge: (index, spec) => { + if (selection?.kind !== "roof") return; + const r = (project.roofs ?? []).find((x) => x.id === selection.id); + if (!r) return; + // Zahl tippen: gleicher Schlüssel je Kante ⇒ ein Undo-Schritt; Giebel-Schalter einzeln. + updateRoof(selection.id, setRoofEdge(r, index, spec), spec.kind === "pitch" ? `roof-edge-${selection.id}-${index}` : undefined); + }, + onRemoveRoofHole: (k) => { + if (selection?.kind !== "roof") return; + const r = (project.roofs ?? []).find((x) => x.id === selection.id); + if (r) updateRoof(selection.id, removeRoofHole(r, k)); + }, + // ── Schnitt-/Ansichtslinie (nur bei selektierter Linie) ──────────────── + sectionLine, + onSetSectionLinePatch: (patch) => { + if (sectionLine) patchLevel(sectionLine.id, patch); + }, + onDeleteSectionLine: () => { + if (sectionLine) patchLevel(sectionLine.id, { linePoints: undefined }); + }, + // 3D-Live-Schnitt an die gewählte Schnittlinie binden (Toggle im Objekt-Info). + section3dCutActive: section3dCutId != null && section3dCutId === sectionLine?.id, + onToggleSection3dCut, + // ── Treppen-Attribute (nur bei selektierter Treppe) ──────────────────── + onSetStairShape: (shape) => { + if (selection?.kind === "stair") updateStair(selection.id, { shape }); + }, + onSetStairWidth: (width) => { + if (selection?.kind === "stair" && width > 0) + updateStair(selection.id, { width }); + }, + onSetStairSteps: (stepCount) => { + if (selection?.kind === "stair" && stepCount >= 2) + updateStair(selection.id, { stepCount: Math.round(stepCount) }); + }, + onSetStairRise: (totalRise) => { + if (selection?.kind === "stair" && totalRise > 0) + updateStair(selection.id, { totalRise }); + }, + onSetStairUp: (up) => { + if (selection?.kind === "stair") updateStair(selection.id, { up }); + }, + onSetStairArrowStyle: (arrowStyle) => { + if (selection?.kind === "stair") updateStair(selection.id, { arrowStyle }); + }, + onSetStairColumn: (radius) => { + if (selection?.kind === "stair") + updateStair(selection.id, { centerColumn: radius > 0 ? radius : undefined }); + }, + onSetStairReferenz: (referenz) => { + if (selection?.kind === "stair") updateStair(selection.id, { referenz }); + }, + onSetStairPatch: (patch) => { + if (selection?.kind === "stair") updateStair(selection.id, patch); + }, + // Typ-Zuweisung (Bibliothek): Treppentyp per typeId; leerer String löst die + // Zuweisung (Inline-Verhalten). Treibt u. a. die 3D-Tragart (massiv/offen). + onSetStairType: (typeId) => { + if (selection?.kind === "stair") + updateStair(selection.id, { typeId: typeId || undefined }); + }, + // ── Raum-Attribute (nur bei selektiertem Raum) ───────────────────────── + onSetRoomName: (name) => { + if (selection?.kind === "room") updateRoom(selection.id, { name }); + }, + onSetRoomSia: (category) => { + if (selection?.kind === "room") updateRoom(selection.id, { siaCategory: category }); + }, + onEditRoomStamp: (roomId) => onOpenStampEditor(roomId), + // ── Extrusions-Attribute (truck-Integration; nur bei selektiertem Körper) ── + onSetExtrudedSolidHeight: (height) => { + if (selection?.kind !== "extrudedSolid" || !(height > 0)) return; + const id = selection.id; + applyChange((p) => patchItem(p, "extrudedSolids", id, { height })); + }, + onSetExtrudedSolidTaper: (taper) => { + if (selection?.kind !== "extrudedSolid") return; + const clamped = Math.min(1, Math.max(0, taper)); + const id = selection.id; + applyChange((p) => patchItem(p, "extrudedSolids", id, { taper: clamped })); + }, + onSetExtrudedSolidCornerRadius: (radius) => { + if (selection?.kind !== "extrudedSolid") return; + const r = Math.max(0, radius); + const id = selection.id; + applyChange((p) => patchItem(p, "extrudedSolids", id, { cornerRadius: r > 0 ? r : undefined })); + }, + onSetExtrudedSolidChamfer: (chamfer) => { + if (selection?.kind !== "extrudedSolid") return; + const c = Math.max(0, chamfer); + const id = selection.id; + applyChange((p) => patchItem(p, "extrudedSolids", id, { chamfer: c > 0 ? c : undefined })); + }, + onSetExtrudedSolidSubtract: (subtract) => { + if (selection?.kind !== "extrudedSolid") return; + const id = selection.id; + applyChange((p) => patchItem(p, "extrudedSolids", id, { operation: subtract ? ("subtract" as const) : undefined })); + }, + onSetExtrudedSolidBaseOffset: (offset) => { + if (selection?.kind !== "extrudedSolid" || !Number.isFinite(offset)) return; + const id = selection.id; + applyChange((p) => patchItem(p, "extrudedSolids", id, { baseOffset: Math.abs(offset) > 1e-9 ? offset : undefined })); + }, + // ── Stützen-Attribute (Tragwerk; nur bei selektierter Stütze) ────────── + onSetColumnProfileKind: (kind) => { + if (selection?.kind !== "column") return; + const id = selection.id; + applyChange((p) => + patchItem(p, "columns", id, (c) => { + if (kind === c.profile.kind) return c; + // Profil-Typ wechseln: sinnvolles Mass aus dem bisherigen ableiten. + if (kind === "round") { + const r = + c.profile.kind === "rect" + ? Math.max(c.profile.width, c.profile.depth) / 2 + : c.profile.radius; + return { ...c, profile: { kind: "round" as const, radius: r } }; + } + const side = c.profile.kind === "round" ? c.profile.radius * 2 : 0.3; + return { ...c, profile: { kind: "rect" as const, width: side, depth: side } }; + }), + ); + }, + onSetColumnWidth: (width) => { + if (selection?.kind !== "column" || !(width > 0)) return; + const id = selection.id; + applyChange((p) => + patchItem(p, "columns", id, (c) => + c.profile.kind === "rect" ? { ...c, profile: { ...c.profile, width } } : c, + ), + ); + }, + onSetColumnDepth: (depth) => { + if (selection?.kind !== "column" || !(depth > 0)) return; + const id = selection.id; + applyChange((p) => + patchItem(p, "columns", id, (c) => + c.profile.kind === "rect" ? { ...c, profile: { ...c.profile, depth } } : c, + ), + ); + }, + onSetColumnRadius: (radius) => { + if (selection?.kind !== "column" || !(radius > 0)) return; + const id = selection.id; + applyChange((p) => + patchItem(p, "columns", id, (c) => + c.profile.kind === "round" ? { ...c, profile: { ...c.profile, radius } } : c, + ), + ); + }, + onSetColumnHeight: (height) => { + if (selection?.kind !== "column" || !(height > 0)) return; + const id = selection.id; + applyChange((p) => patchItem(p, "columns", id, { height })); + }, + onSetColumnRotation: (deg) => { + if (selection?.kind !== "column" || !Number.isFinite(deg)) return; + const id = selection.id; + const rotation = (deg * Math.PI) / 180; + applyChange((p) => patchItem(p, "columns", id, { rotation })); + }, + } satisfies HostPart; +} diff --git a/src/state/panelHost/layoutsHost.ts b/src/state/panelHost/layoutsHost.ts new file mode 100644 index 00000000..540456f5 --- /dev/null +++ b/src/state/panelHost/layoutsHost.ts @@ -0,0 +1,169 @@ +// Panel-Host, Teil Layouts und Plansätze ([121], aus `usePanelHostBase` herausgelöst): Blätter und +// Masterlayouts anlegen, umbenennen, löschen, in Ordner legen, Ordner-PDF, Publikations-Sätze. + +import { addItems, fieldOps, patchItem, patchItems, removeItems } from "../../core"; +import { t } from "../../i18n"; +import { createLayout, createLayoutFolder, createMasterLayout, deleteFolder as deleteLayoutFolder, deleteMasterFolder, moveLayoutToFolder, moveFolderToFolder, createSheetLevel } from "../../model/layoutModel"; +import { folderPdfBytes } from "../../export/layoutPdf"; +import { addPublishSetOps, deletePublishSetOps, patchPublishSetOps, publishSet } from "../publishActions"; +import { saveBinaryFile } from "../../native/saveFile"; +import type { FlatHostOpts, HostPart } from "./types"; + +export function buildLayoutsHost(c: FlatHostOpts) { + const { applyChange, project, setActiveLayoutId } = c; + return { + // ── Layouts / Masterlayouts (DOSSIER A3) ────────────────────────────── + // Immutable CRUD über pure Helfer (panels/layoutModel.ts); das Blatt öffnet + // als erstklassige Ansicht IM HAUPT-Viewport (activeLayoutId, Phase 2b). + // Anlegen öffnet es direkt; Löschen schliesst es, falls es das offene trifft. + onAddLayout: (name, paper, orientation) => { + const lay = createLayout(`lay-${Date.now()}`, name, paper, orientation); + // Jedes Blatt trägt seine Blatt-Ebene (2D-Zeichnung auf dem Blatt, s. layoutModel). + applyChange([...addItems("layouts", [lay]), ...addItems("drawingLevels", [createSheetLevel(`sheet-${lay.id}`, lay)])]); + setActiveLayoutId(lay.id); + }, + onRenameLayout: (id, name) => { + applyChange((p) => patchItem(p, "layouts", id, { name })); + }, + onDeleteLayout: (id) => { + // Mit dem Layout gehen seine Blatt-Ebene und deren Zeichnungen (ein Undo-Schritt). + applyChange((p) => { + const levels = p.drawingLevels.filter((l) => l.layoutId === id).map((l) => l.id); + const drawings = p.drawings2d.filter((d) => levels.includes(d.levelId)).map((d) => d.id); + return [ + ...removeItems(p, "drawings2d", drawings), + ...removeItems(p, "drawingLevels", levels), + ...removeItems(p, "layouts", [id]), + ]; + }); + setActiveLayoutId((cur) => (cur === id ? null : cur)); + }, + onOpenLayout: (id) => setActiveLayoutId(id), + onAddMasterLayout: (name) => { + const m = createMasterLayout(`mas-${Date.now()}`, name, "a4", "portrait"); + applyChange(addItems("masterLayouts", [m])); + }, + onRenameMasterLayout: (id, name) => { + applyChange((p) => patchItem(p, "masterLayouts", id, { name })); + }, + onDeleteMasterLayout: (id) => { + // Master löschen UND Bindungen der Layouts lösen (masterId → undefined). + applyChange((p) => [ + ...removeItems(p, "masterLayouts", [id]), + ...patchItems(p, "layouts", (l) => l.masterId === id, (l) => ({ ...l, masterId: undefined })), + ]); + }, + onPatchMasterLayout: (id, patch) => { + applyChange((p) => patchItem(p, "masterLayouts", id, patch)); + }, + + // ── Layouts-Baum (Ordner) + Erstell-Dialoge (DOSSIER A3) ──────────── + onAddLayoutFolder: (parentId) => { + const id = `folder-${Date.now()}`; + const folder = createLayoutFolder(id, t("layouts.folder.defaultName"), parentId); + applyChange(addItems("layoutFolders", [folder])); + return id; + }, + onAddMasterFolder: (parentId) => { + const id = `mfolder-${Date.now()}`; + const folder = createLayoutFolder( + id, + t("layouts.folder.defaultName"), + parentId, + "master", + ); + applyChange(addItems("layoutFolders", [folder])); + return id; + }, + onDeleteMasterFolder: (id) => { + applyChange((p) => { + const { folders, masters } = deleteMasterFolder( + id, + p.layoutFolders ?? [], + p.masterLayouts ?? [], + ); + return [...fieldOps(p, "layoutFolders", folders), ...fieldOps(p, "masterLayouts", masters)]; + }); + }, + onRenameLayoutFolder: (id, name) => { + applyChange((p) => patchItem(p, "layoutFolders", id, { name })); + }, + onDeleteLayoutFolder: (id) => { + applyChange((p) => { + const { folders, layouts } = deleteLayoutFolder( + id, + p.layoutFolders ?? [], + p.layouts ?? [], + ); + return [...fieldOps(p, "layoutFolders", folders), ...fieldOps(p, "layouts", layouts)]; + }); + }, + onCreateLayout: (opts) => { + const id = `lay-${Date.now()}`; + // Bei gebundenem Master erbt das Blatt dessen Papier/Ausrichtung/Grösse. + const master = opts.masterId + ? (project.masterLayouts ?? []).find((m) => m.id === opts.masterId) + : undefined; + const paper = master?.paper ?? opts.paper; + const orientation = master?.orientation ?? opts.orientation; + const customWidthMm = master ? master.customWidthMm : opts.customWidthMm; + const customHeightMm = master ? master.customHeightMm : opts.customHeightMm; + const lay = createLayout(id, t("layouts.defaultName"), paper, orientation); + const full = { + ...lay, + ...(opts.masterId ? { masterId: opts.masterId } : {}), + ...(opts.folderId ? { folderId: opts.folderId } : {}), + ...(customWidthMm !== undefined && customHeightMm !== undefined + ? { customWidthMm, customHeightMm } + : {}), + }; + applyChange([...addItems("layouts", [full]), ...addItems("drawingLevels", [createSheetLevel(`sheet-${id}`, full)])]); + return id; + }, + onCreateMasterLayout: (opts) => { + const id = `mas-${Date.now()}`; + const custom = + opts.customWidthMm !== undefined && opts.customHeightMm !== undefined + ? { widthMm: opts.customWidthMm, heightMm: opts.customHeightMm } + : undefined; + const m = createMasterLayout( + id, + t("layouts.defaultMasterName"), + opts.paper, + opts.orientation, + custom, + ); + const full = opts.folderId ? { ...m, folderId: opts.folderId } : m; + applyChange(addItems("masterLayouts", [full])); + return id; + }, + onExportFolderPdf: (folderId) => { + const folder = (project.layoutFolders ?? []).find((f) => f.id === folderId); + const name = folder?.name?.trim() || "layouts"; + void folderPdfBytes(project, folderId).then((bytes) => { + if (bytes) return saveBinaryFile(bytes, `${name}.pdf`, "application/pdf"); + }); + }, + onMoveLayoutToFolder: (layoutId, folderId) => { + applyChange((p) => fieldOps(p, "layouts", moveLayoutToFolder(p.layouts ?? [], layoutId, folderId))); + }, + onMoveFolderToFolder: (folderId, parentId) => { + applyChange((p) => + fieldOps(p, "layoutFolders", moveFolderToFolder(p.layoutFolders ?? [], folderId, parentId)), + ); + }, + onAddPublishSet: () => { + const id = `pubset-${Date.now()}`; + applyChange((p) => addPublishSetOps(p, id)); + return id; + }, + onPatchPublishSet: (id, patch) => applyChange((p) => patchPublishSetOps(p, id, patch), `pubset-${id}`), + onSetProjectNumber: (value) => applyChange((p) => fieldOps(p, "projectNumber", value.trim() ? value : undefined), "projectNumber"), + onDeletePublishSet: (id) => applyChange((p) => deletePublishSetOps(p, id)), + onPublishSet: (id) => { + void publishSet(project, id).then((ops) => { + if (ops && ops.length > 0) applyChange(ops); + }); + }, + } satisfies HostPart; +} diff --git a/src/state/panelHost/selectionStyleHost.ts b/src/state/panelHost/selectionStyleHost.ts new file mode 100644 index 00000000..c4ea28ef --- /dev/null +++ b/src/state/panelHost/selectionStyleHost.ts @@ -0,0 +1,431 @@ +// Panel-Host, Teil Darstellung der Auswahl ([121], aus `usePanelHostBase` herausgelöst): Farbe, +// Stift-Kopplung, Strichstärke, Füllung/Schraffur, Deckkraft, Vorder-/Hintergrund samt Quellen +// (Nach Ebene/Bauteil), Massketten-/Detail-/Raster-Attribute sowie Grösse, Lage, Ebene und Drehung +// der gewählten Elemente und die Geometrie-Felder freier 2D-Elemente (Linie, Kreis, Bogen, Text). + +import { applyFillMode } from "../fillMode"; +import { cmdMutation, opsMutation, patchItem } from "../../core"; +import { resolvePenColor } from "../../model/penSets"; +import type { TransformSelection } from "../../tools/transform"; +import type { FlatHostOpts, HostPart } from "./types"; + + +/** + * Baut eine TransformSelection für GENAU EIN Element (Object-Info: Verschieben/ + * Drehen per Zahlenfeld, siehe onMoveSelectionBy/onRotateSelectionAround unten). + * Deckt nur die vom Transform-Kern (tools/transform.ts) unterstützten Arten ab + * — Decke/Öffnung/Treppe/Raum kennt er nicht, dort liefert die Funktion `null` + * (Aufrufer macht dann No-op, wie bei onResizeSelection). + */ +function singleTransformSel(kind: string, id: string): TransformSelection | null { + if (kind === "wall") return { wallIds: [id], drawingId: null }; + if (kind === "drawing2d") return { wallIds: [], drawingId: id }; + if (kind === "extrudedSolid") return { wallIds: [], drawingId: null, extrudedSolidId: id }; + if (kind === "column") return { wallIds: [], drawingId: null, columnId: id }; + if (kind === "ceiling") return { wallIds: [], drawingId: null, ceilingIds: [id] }; + // Dach: Move geht (Umriss verschiebt sich), Rotate no-opt bewusst (s. + // TransformSelection.roofIds) — der Host-Aufruf degradiert dafür von + // selbst über `gatherItems`, kein Sonderfall hier nötig. + if (kind === "roof") return { wallIds: [], drawingId: null, roofIds: [id] }; + if (kind === "stair") return { wallIds: [], drawingId: null, stairIds: [id] }; + if (kind === "room") return { wallIds: [], drawingId: null, roomIds: [id] }; + // [144] Öffnung: X/Y im Objekt-Info verschiebt sie entlang (bzw. in eine andere) Wand. + if (kind === "opening") return { wallIds: [], drawingId: null, openingIds: [id] }; + return null; +} + +export function buildSelectionStyleHost(c: FlatHostOpts) { + const { addColorToCustomPalette, applyChange, commitTransformOn, project, resizeElement, selection, setElementBackground, setElementColor, setElementFill, setElementFillColor, setElementForeground, setElementWeight, setProject, updateCeiling, updateDrawing2D, updateOpening, updateRoof, updateRoom, updateStair, updateWall } = c; + return { + onSetSelectionColor: (color) => { + if (!selection) return; + if (selection.kind === "wall" || selection.kind === "drawing2d") + setElementColor(selection.kind, selection.id, color); + else if (selection.kind === "ceiling") + updateCeiling(selection.id, { color }); + else if (selection.kind === "opening") + updateOpening(selection.id, { color }); + else if (selection.kind === "stair") + updateStair(selection.id, { color }); + else if (selection.kind === "room") + updateRoom(selection.id, { color }); + }, + // Stift-Kopplung der Farbe oben (s. `Selection.colorPenId`-Doku) — + // dieselben Selektionsarten wie `onSetSelectionColor`. `penId` gesetzt ⇒ Farbe sofort aus dem aktiven + // Stiftsatz backen; `undefined` ⇒ nur die Kopplung lösen, letzter + // gebackener Wert bleibt als freie Farbe stehen. + onSetSelectionColorPen: (penId) => { + if (!selection) return; + const color = penId ? resolvePenColor(project, penId) : undefined; + const patch = color !== undefined ? { colorPenId: penId, color } : { colorPenId: penId }; + if (selection.kind === "wall") updateWall(selection.id, patch); + else if (selection.kind === "drawing2d") updateDrawing2D(selection.id, patch); + else if (selection.kind === "ceiling") updateCeiling(selection.id, patch); + else if (selection.kind === "opening") updateOpening(selection.id, patch); + else if (selection.kind === "stair") updateStair(selection.id, patch); + else if (selection.kind === "room") updateRoom(selection.id, patch); + }, + onSetSelectionWeight: (weightMm) => { + // Strichstärke-Override: Wand/Decke (`strokeWeight`) oder Drawing2D (`weightMm`). + if (selection?.kind === "wall") updateWall(selection.id, { strokeWeight: weightMm }); + else if (selection?.kind === "ceiling") + updateCeiling(selection.id, { strokeWeight: weightMm }); + else if (selection?.kind === "drawing2d") + setElementWeight(selection.id, weightMm); + }, + onSetSelectionFill: (hatchId) => { + // Schraffur-Override: Wand, Decke oder Drawing2D (geschlossene Formen). + // `null` löscht das Feld (→ „Nach System"/Quelle). + if (selection?.kind === "wall") + updateWall(selection.id, { hatchId: hatchId ?? undefined }); + else if (selection?.kind === "ceiling") + updateCeiling(selection.id, { hatchId: hatchId ?? undefined }); + else if (selection?.kind === "drawing2d") + setElementFill(selection.id, hatchId); + }, + onSetSelectionLineStyle: (lineStyleId) => { + // Nur Drawing2D trägt einen Linienstil (Wand/Decke/etc. nicht). + if (selection?.kind === "drawing2d") + updateDrawing2D(selection.id, { lineStyleId }); + }, + onSetSelectionFillColor: (color) => { + // Vollton-Füllfarbe nur bei Drawing2D (geschlossene Formen). + if (selection?.kind === "drawing2d") + setElementFillColor(selection.id, color); + }, + onSetSelectionFillMode: (mode) => { + if (selection?.kind !== "drawing2d") return; + const id = selection.id; + setProject(opsMutation((p) => patchItem(p, "drawings2d", id, (d) => applyFillMode(d, p.hatches, mode)))); + }, + onSetSelectionFillOpacity: (opacity) => { + if (selection?.kind === "drawing2d") + setProject( + opsMutation((p) => + patchItem(p, "drawings2d", selection.id, (d) => { + const { fillOpacity: _old, ...rest } = d; + return opacity >= 1 ? rest : { ...rest, fillOpacity: Math.max(0, opacity) }; + }), + ), + ); + }, + onSetSelectionOpacity: (opacity) => { + // Deckkraft eines 2D-Elements. Bei BILDERN bleibt es die Deckkraft der + // Bildgeometrie (bestehendes Verhalten, eigenes Feld); bei allen + // übrigen Formen die neue OBJEKT-Transparenz, die auf Striche UND + // Füllungen wirkt (`Drawing2D.opacity`). Nur EIN Bedienfeld — welches + // Feld gesetzt wird, entscheidet die Form. + if (selection?.kind === "drawing2d") + setProject( + opsMutation((p) => + patchItem(p, "drawings2d", selection.id, (d) => + d.geom.shape === "image" ? { ...d, geom: { ...d.geom, opacity } } : { ...d, opacity }, + ), + ), + ); + else if (selection?.kind === "contextObject") + applyChange((p) => + patchItem(p, "context", selection.id, (o) => (o.type === "image" ? { ...o, opacity } : o)), + ); + }, + onSetSelectionImageFilters: (filters) => { + // Nur Kontext-Objekt-Bilder tragen `filters` (s. `ContextImage`) — + // gemergt mit den bestehenden Werten (Teil-Update, ein Slider ändert + // nur SEINEN eigenen Wert). + if (selection?.kind !== "contextObject") return; + applyChange((p) => + patchItem(p, "context", selection.id, (o) => + o.type === "image" ? { ...o, filters: { ...o.filters, ...filters } } : o, + ), + ); + }, + onSetSelectionForeground: (color) => { + // Vordergrund-Override: Wand, Decke oder Drawing2D. + if ( + selection?.kind === "wall" || + selection?.kind === "ceiling" || + selection?.kind === "drawing2d" + ) + setElementForeground(selection.kind, selection.id, color); + }, + onSetSelectionBackground: (color) => { + // Hintergrund-Override: Wand, Decke oder Drawing2D. + if ( + selection?.kind === "wall" || + selection?.kind === "ceiling" || + selection?.kind === "drawing2d" + ) + setElementBackground(selection.kind, selection.id, color); + }, + // Stift-Kopplung von Vordergrund/Hintergrund (s. `Selection. + // foregroundPenId`/`backgroundPenId`-Doku) — dieselben Selektionsarten + // wie `onSetSelectionForeground`/`onSetSelectionBackground` (Wand/Decke/ + // Drawing2D; Stütze trägt zwar dasselbe Feld im Modell, hat aber ebenso + // wie bei `onSetSelectionColorPen` noch KEINEN UI-Schreibpfad — s. + // PENDENZEN.md-Scope-Entscheid). `penId` gesetzt ⇒ sofort aus dem aktiven + // Stiftsatz backen; `undefined` ⇒ nur die Kopplung lösen, letzter + // gebackener Wert bleibt als freier Override stehen. + onSetSelectionForegroundPen: (penId) => { + if (!selection) return; + const foreground = penId ? resolvePenColor(project, penId) : undefined; + const patch = + foreground !== undefined + ? { foregroundPenId: penId, foreground } + : { foregroundPenId: penId }; + if (selection.kind === "wall") updateWall(selection.id, patch); + else if (selection.kind === "ceiling") updateCeiling(selection.id, patch); + else if (selection.kind === "drawing2d") updateDrawing2D(selection.id, patch); + }, + onAddColorToCustomPalette: (paletteId, hex) => addColorToCustomPalette(paletteId, hex), + onSetDashScale: (drawingId, scale) => + setProject(opsMutation((p) => patchItem(p, "drawings2d", drawingId, { dashScale: scale }))), + onDetachDimension: (drawingId) => setProject(cmdMutation({ cmd: "dimdetach", ids: [drawingId] })), + onSetDetailRefLabel: (drawingId, label) => + setProject( + opsMutation((p) => + patchItem(p, "drawings2d", drawingId, (d) => + d.geom.shape === "detailref" ? { ...d, geom: { ...d.geom, label } } : d, + ), + ), + ), + onSetDetailRefSheetLayout: (drawingId, sheetLayoutId) => + setProject( + opsMutation((p) => + patchItem(p, "drawings2d", drawingId, (d) => { + if (d.geom.shape !== "detailref") return d; + const geom = { ...d.geom }; + if (sheetLayoutId) geom.sheetLayoutId = sheetLayoutId; + else delete geom.sheetLayoutId; + return { ...d, geom }; + }), + ), + ), + onSetDetailRefSheetLabel: (drawingId, sheetLabel) => + setProject( + opsMutation((p) => + patchItem(p, "drawings2d", drawingId, (d) => + d.geom.shape === "detailref" ? { ...d, geom: { ...d.geom, sheetLabel } } : d, + ), + ), + ), + onSetHatchPlacement: (drawingId, patch) => + setProject( + opsMutation((p) => + patchItem(p, "drawings2d", drawingId, (d) => { + const next = { ...d }; + // `null` = zurück auf die Ressource (Feld entfernen). + if ("angleDeg" in patch) + patch.angleDeg === null ? delete next.hatchAngleDeg : (next.hatchAngleDeg = patch.angleDeg); + if ("scale" in patch) + patch.scale === null ? delete next.hatchScale : (next.hatchScale = patch.scale); + if ("origin" in patch) + patch.origin === null ? delete next.hatchOrigin : (next.hatchOrigin = patch.origin); + return next; + }), + ), + ), + onSetEndMarks: (drawingId, patch) => + setProject( + opsMutation((p) => + patchItem(p, "drawings2d", drawingId, (d) => ({ ...d, endMarks: { ...d.endMarks, ...patch } })), + ), + ), + onSetGridProps: (drawingId, patch) => + setProject( + opsMutation((p) => + patchItem(p, "drawings2d", drawingId, (d) => { + if (d.geom.shape !== "grid") return d; + const geom = { ...d.geom, ...patch }; + if (patch.levels === undefined && "levels" in patch) delete geom.levels; + return { ...d, geom }; + }), + ), + ), + onSetDimensionStyle: (drawingId, patch) => + setProject( + opsMutation((p) => + patchItem(p, "drawings2d", drawingId, (d) => + d.geom.shape === "dimension" ? { ...d, geom: { ...d.geom, ...patch } } : d, + ), + ), + ), + onSetSelectionBackgroundPen: (penId) => { + if (!selection) return; + const background = penId ? resolvePenColor(project, penId) : undefined; + const patch = + background !== undefined + ? { backgroundPenId: penId, background } + : { backgroundPenId: penId }; + if (selection.kind === "wall") updateWall(selection.id, patch); + else if (selection.kind === "ceiling") updateCeiling(selection.id, patch); + else if (selection.kind === "drawing2d") updateDrawing2D(selection.id, patch); + }, + // ── By-Layer/By-Object-Quellen (Vordergrund/Hintergrund/Strichstärke/ + // Schraffur): "layer" erzwingt die Ebene, "object" erbt vom Bauteil — + // beide löschen dabei den expliziten Wert (siehe Modell-Kommentar + // `AttributeSource`); „eigener Wert" läuft weiterhin über die + // onSetSelection{Foreground,Background,Weight,Fill}-Setter oben. + onSetSelectionForegroundSource: (source) => { + if (!selection) return; + const patch = { + foregroundSource: source === "layer" ? ("layer" as const) : undefined, + foreground: undefined, + }; + if (selection.kind === "wall") updateWall(selection.id, patch); + else if (selection.kind === "ceiling") updateCeiling(selection.id, patch); + else if (selection.kind === "drawing2d") updateDrawing2D(selection.id, patch); + }, + onSetSelectionBackgroundSource: (source) => { + if (!selection) return; + const patch = { + backgroundSource: source === "layer" ? ("layer" as const) : undefined, + background: undefined, + }; + if (selection.kind === "wall") updateWall(selection.id, patch); + else if (selection.kind === "ceiling") updateCeiling(selection.id, patch); + else if (selection.kind === "drawing2d") updateDrawing2D(selection.id, patch); + }, + onSetSelectionStrokeWeightSource: (source) => { + if (!selection) return; + const strokeWeightSource = source === "layer" ? ("layer" as const) : undefined; + if (selection.kind === "wall") + updateWall(selection.id, { strokeWeightSource, strokeWeight: undefined }); + else if (selection.kind === "ceiling") + updateCeiling(selection.id, { strokeWeightSource, strokeWeight: undefined }); + else if (selection.kind === "drawing2d") + updateDrawing2D(selection.id, { strokeWeightSource, weightMm: undefined }); + }, + onSetSelectionHatchSource: (source) => { + if (!selection) return; + const hatchSource = source === "layer" ? ("layer" as const) : undefined; + if (selection.kind === "wall") + updateWall(selection.id, { hatchSource, hatchId: undefined }); + else if (selection.kind === "ceiling") + updateCeiling(selection.id, { hatchSource, hatchId: undefined }); + else if (selection.kind === "drawing2d") + updateDrawing2D(selection.id, { hatchSource, hatchId: undefined }); + }, + onResizeSelection: (w, h, anchor) => { + if (selection?.kind === "wall" || selection?.kind === "drawing2d") + resizeElement(selection.kind, selection.id, w, h, anchor); + }, + onMoveSelectionBy: (dx, dy) => { + if (!selection) return; + if (!isFinite(dx) || !isFinite(dy) || (dx === 0 && dy === 0)) return; + const sel2 = singleTransformSel(selection.kind, selection.id); + if (!sel2) return; + commitTransformOn(sel2, "move", [{ x: 0, y: 0 }, { x: dx, y: dy }], "move", 1); + }, + // Objektinfo-Kopf: Klasse (Grafik-Kategorie) + Zeichnungsebene ändern + // (VW-Muster „Klasse"/„Ebene"). Je Elementart der passende Store-Weg. + onSetSelectionCategory: (code) => { + if (!selection || !code) return; + const id = selection.id; + switch (selection.kind) { + case "wall": updateWall(id, { categoryCode: code }); break; + case "ceiling": updateCeiling(id, { categoryCode: code }); break; + case "roof": updateRoof(id, { categoryCode: code }); break; + case "opening": updateOpening(id, { categoryCode: code }); break; + case "stair": updateStair(id, { categoryCode: code }); break; + case "room": updateRoom(id, { categoryCode: code }); break; + case "drawing2d": updateDrawing2D(id, { categoryCode: code }); break; + case "column": + applyChange((p) => patchItem(p, "columns", id, { categoryCode: code })); + break; + default: break; // extrudedSolid/door: keine Kategorie am Element + } + }, + onSetSelectionLevel: (levelId) => { + if (!selection || !levelId) return; + const id = selection.id; + switch (selection.kind) { + case "wall": updateWall(id, { floorId: levelId }); break; + case "ceiling": updateCeiling(id, { floorId: levelId }); break; + case "roof": updateRoof(id, { floorId: levelId }); break; + case "stair": updateStair(id, { floorId: levelId }); break; + case "room": updateRoom(id, { floorId: levelId }); break; + case "drawing2d": updateDrawing2D(id, { levelId }); break; + case "extrudedSolid": + applyChange((p) => patchItem(p, "extrudedSolids", id, { levelId })); + break; + case "column": + applyChange((p) => patchItem(p, "columns", id, { floorId: levelId })); + break; + default: break; // opening: Ebene kommt aus der Wirts-Wand + } + }, + onRotateSelectionAround: (cx, cy, deg) => { + if (!selection) return; + if (!isFinite(deg) || deg === 0) return; + const sel2 = singleTransformSel(selection.kind, selection.id); + if (!sel2) return; + const rad = (deg * Math.PI) / 180; + commitTransformOn( + sel2, + "rotate", + [ + { x: cx, y: cy }, + { x: cx + 1, y: cy }, + { x: cx + Math.cos(rad), y: cy + Math.sin(rad) }, + ], + "move", + 1, + ); + }, + onSetDrawingLineLength: (length) => { + if (selection?.kind !== "drawing2d" || !isFinite(length) || length <= 0) return; + const d = project.drawings2d.find((x) => x.id === selection.id); + if (!d || d.geom.shape !== "line") return; + const { a, b } = d.geom; + const len = Math.hypot(b.x - a.x, b.y - a.y); + if (len < 1e-9) return; + const ux = (b.x - a.x) / len, uy = (b.y - a.y) / len; + updateDrawing2D(selection.id, { + geom: { ...d.geom, b: { x: a.x + ux * length, y: a.y + uy * length } }, + }); + }, + onSetDrawingLineAngle: (deg) => { + if (selection?.kind !== "drawing2d" || !isFinite(deg)) return; + const d = project.drawings2d.find((x) => x.id === selection.id); + if (!d || d.geom.shape !== "line") return; + const { a, b } = d.geom; + const len = Math.hypot(b.x - a.x, b.y - a.y); + if (len < 1e-9) return; + const rad = (deg * Math.PI) / 180; + updateDrawing2D(selection.id, { + geom: { ...d.geom, b: { x: a.x + Math.cos(rad) * len, y: a.y + Math.sin(rad) * len } }, + }); + }, + onSetDrawingCircleRadius: (radius) => { + if (selection?.kind !== "drawing2d" || !isFinite(radius) || radius <= 0) return; + const d = project.drawings2d.find((x) => x.id === selection.id); + if (!d || d.geom.shape !== "circle") return; + updateDrawing2D(selection.id, { geom: { ...d.geom, r: radius } }); + }, + onSetDrawingTextPaperHeight: (mm) => { + if (selection?.kind !== "drawing2d" || !isFinite(mm) || mm < 0) return; + const d = project.drawings2d.find((x) => x.id === selection.id); + if (!d || d.geom.shape !== "text") return; + const { paperHeight: _old, ...rest } = d.geom; + updateDrawing2D(selection.id, { geom: mm > 0 ? { ...rest, paperHeight: mm } : rest }); + }, + onSetDrawingArcRadius: (radius) => { + if (selection?.kind !== "drawing2d" || !isFinite(radius) || radius <= 0) return; + const d = project.drawings2d.find((x) => x.id === selection.id); + if (!d || d.geom.shape !== "arc") return; + updateDrawing2D(selection.id, { geom: { ...d.geom, r: radius } }); + }, + onSetDrawingArcStartAngle: (deg) => { + if (selection?.kind !== "drawing2d" || !isFinite(deg)) return; + const d = project.drawings2d.find((x) => x.id === selection.id); + if (!d || d.geom.shape !== "arc") return; + updateDrawing2D(selection.id, { geom: { ...d.geom, a0: (deg * Math.PI) / 180 } }); + }, + onSetDrawingArcEndAngle: (deg) => { + if (selection?.kind !== "drawing2d" || !isFinite(deg)) return; + const d = project.drawings2d.find((x) => x.id === selection.id); + if (!d || d.geom.shape !== "arc") return; + updateDrawing2D(selection.id, { geom: { ...d.geom, a1: (deg * Math.PI) / 180 } }); + }, + } satisfies HostPart; +} diff --git a/src/state/panelHost/siteHost.ts b/src/state/panelHost/siteHost.ts new file mode 100644 index 00000000..878f942f --- /dev/null +++ b/src/state/panelHost/siteHost.ts @@ -0,0 +1,61 @@ +// Panel-Host, Teil Lage und Elemente-Baum ([121], aus `usePanelHostBase` herausgelöst): +// Kontext-Objekte (Gelände, Aushub, Georeferenz, DXF-Import) und die Auswahl einer Zeile im +// Elemente-Panel samt Geschosswechsel und Zoom. + +import { setFieldIfChanged } from "../../core"; +import { clearKinds, type SelectionKind } from "../selection"; +import type { ScheduleKind } from "../../export/exportSchedule"; +import type { FlatHostOpts, HostPart } from "./types"; + +export function buildSiteHost(c: FlatHostOpts) { + const { activeLevelId, addContextObjectsAndFit, applyChange, dxfInputRef, generateTerrain, onRunCommand, patchContextObject, planViewRef, removeContextObject, removeContextObjects, setActiveLevelId, setSelection } = c; + return { + // ── Site-/Kontext-Schicht ────────────────────────────────────────────── + onAddContextObjects: addContextObjectsAndFit, + onRemoveContextObject: removeContextObject, + onRemoveContextObjects: removeContextObjects, + onGenerateTerrain: generateTerrain, + onPatchContextObject: patchContextObject, + onStartExcavation: () => onRunCommand("excavation"), + onSetGeoAnchor: (anchor) => { + applyChange((p) => setFieldIfChanged(p, "geoAnchor", anchor)); + }, + onImportDxf: () => dxfInputRef.current?.click(), + onStartGeoref: () => onRunCommand("georef"), + // ── Element-Baum (Elemente-Panel) ──────────────────────────────────── + onSelectScheduleRow: ( + kind: ScheduleKind, + id: string, + floorId: string | undefined, + opts?: { zoom?: boolean }, + ) => { + const applySelection = () => { + const kindOf: Partial> = { + Wand: "walls", + Decke: "ceilings", + Fenster: "openings", + Öffnung: "openings", + Treppe: "stairs", + Extrusion: "solids", + Dach: "roofs", + Stütze: "columns", + }; + const k = kindOf[kind]; + setSelection({ ...clearKinds(), ...(k ? { [k]: [id] } : {}) }); + // z. B. Legacy-„Tür"-Datensätze (project.doors) — kein Auswahl-Kanal. + if (!k) return; + if (opts?.zoom) requestAnimationFrame(() => planViewRef.current?.fit()); + }; + if (floorId && floorId !== activeLevelId) { + // Der Geschosswechsel-Effekt (oben, deps [activeLevelId]) leert die + // Auswahl NACH diesem Render — die neue Auswahl daher einen Tick + // später anwenden, sonst überschreibt der Effekt sie sofort wieder. + setActiveLevelId(floorId); + requestAnimationFrame(applySelection); + } else { + applySelection(); + } + }, + + } satisfies HostPart; +} diff --git a/src/state/panelHost/stableHost.test.ts b/src/state/panelHost/stableHost.test.ts new file mode 100644 index 00000000..82c36ea5 --- /dev/null +++ b/src/state/panelHost/stableHost.test.ts @@ -0,0 +1,50 @@ +// [121] Stabiler Panel-Host: Handler als feste Trampoline, neue Identität nur bei geänderten Wert-Feldern. +import { describe, expect, it } from "vitest"; +import { stabilizeHost, type StableHost } from "./stableHost"; +import { dataEqual } from "../dataEqual"; + +type Host = { activeLevelId: string; onPick: (id: string) => string; snap: { grid: boolean } }; + +describe("stabilizeHost", () => { + it("neuer Bau mit gleichen Wert-Feldern behält die Identität, Handler rufen die neueste Fassung", () => { + const snap = { grid: true }; + const latest = { current: { activeLevelId: "eg", onPick: (id: string) => `alt:${id}`, snap } as Host }; + const s1 = stabilizeHost(null, latest.current, latest); + // Neubau (z. B. nach einer Op): neue Handler-Closures, gleiche Werte. + latest.current = { activeLevelId: "eg", onPick: (id: string) => `neu:${id}`, snap }; + const s2 = stabilizeHost(s1, latest.current, latest); + expect(s2).toBe(s1); + expect(s2.out.onPick("w1")).toBe("neu:w1"); + }); + + it("geändertes Wert-Feld: neue Ausgabe, Trampoline bleiben dieselben", () => { + const latest = { current: { activeLevelId: "eg", onPick: (id: string) => id, snap: { grid: true } } as Host }; + const s1 = stabilizeHost(null, latest.current, latest); + latest.current = { ...latest.current, activeLevelId: "og" }; + const s2: StableHost = stabilizeHost(s1, latest.current, latest); + expect(s2).not.toBe(s1); + expect(s2.out.activeLevelId).toBe("og"); + expect(s2.out.onPick).toBe(s1.out.onPick); + }); + + it("Feld wechselt zwischen Wert und Handler: neue Ausgabe", () => { + type H = { f?: (() => void) | null }; + const latest = { current: { f: null } as H }; + const s1 = stabilizeHost(null, latest.current, latest); + latest.current = { f: () => {} }; + const s2 = stabilizeHost(s1, latest.current, latest); + expect(s2).not.toBe(s1); + expect(typeof s2.out.f).toBe("function"); + }); +}); + +describe("dataEqual", () => { + it("vergleicht Daten strukturell", () => { + expect(dataEqual({ a: [1, { b: "x" }] }, { a: [1, { b: "x" }] })).toBe(true); + expect(dataEqual({ a: [1, { b: "x" }] }, { a: [1, { b: "y" }] })).toBe(false); + expect(dataEqual({ a: 1 }, { a: 1, b: undefined })).toBe(false); + expect(dataEqual([1, 2], { 0: 1, 1: 2 })).toBe(false); + expect(dataEqual(null, {})).toBe(false); + expect(dataEqual(Number.NaN, Number.NaN)).toBe(true); + }); +}); diff --git a/src/state/panelHost/stableHost.ts b/src/state/panelHost/stableHost.ts new file mode 100644 index 00000000..9e46b0ce --- /dev/null +++ b/src/state/panelHost/stableHost.ts @@ -0,0 +1,76 @@ +// Panel-Host mit stabiler Identität ([121]). Der Basis-Host wird in `usePanelHostBase` bei jeder +// Projekt- oder Auswahl-Änderung neu gebaut (seine Handler schliessen über das aktuelle Projekt). +// Panels sollen deshalb aber nicht neu rendern: `useStableHost` gibt ein Objekt zurück, dessen +// Handler feste Trampoline sind (rufen beim Aufruf die Fassung des letzten Renders) und das sich nur +// ändert, wenn sich ein Wert-Feld (aktive Ebene, Werkzeug, Fang, Schnittlinie …) ändert. +// +// Damit gilt: wer Projektdaten anzeigt, abonniert sie selbst im Store (`useStore`, +// `useSelectionInfo`); der Host trägt nur noch Handler und kleine Ansichts-Werte. Handler, deren +// ERGEBNIS im Render gelesen wird (`viewTabAutoName`), braucht der Leser mit eigenem Abo (s. App.tsx). + +import { useRef } from "react"; + +/** Zustand der Stabilisierung: Ausgabe und was zu ihr geführt hat. */ +export interface StableHost { + /** Ausgabe-Objekt (Trampoline + Wert-Felder). */ + out: T; + /** Wert-Felder der Ausgabe (Schlüssel → Wert) zum Vergleich. */ + values: Map; + /** Schlüssel mit Handler (Funktion). */ + fns: Set; +} + +/** Gleiche Schlüssel, gleiche Handler-Schlüssel, gleiche Wert-Felder (Referenz)? */ +function sameShape(prev: StableHost, next: T): boolean { + const keys = Object.keys(next); + if (keys.length !== prev.values.size + prev.fns.size) return false; + for (const k of keys) { + const v = (next as Record)[k]; + if (typeof v === "function") { + if (!prev.fns.has(k)) return false; + } else if (!prev.values.has(k) || !Object.is(prev.values.get(k), v)) { + return false; + } + } + return true; +} + +/** + * Ein Schritt der Stabilisierung (rein, für Tests): liefert `prev` unverändert, wenn `value` dieselbe + * Form und dieselben Wert-Felder hat, sonst eine neue Ausgabe. Trampoline rufen `latest.current[k]`; + * bestehende Trampoline werden weiterverwendet. + */ +export function stabilizeHost( + prev: StableHost | null, + value: T, + latest: { readonly current: T }, +): StableHost { + if (prev !== null && sameShape(prev, value)) return prev; + const prevOut = prev?.out as Record | undefined; + const out: Record = {}; + const values = new Map(); + const fns = new Set(); + for (const [k, v] of Object.entries(value)) { + if (typeof v === "function") { + fns.add(k); + out[k] = + prevOut && prev?.fns.has(k) + ? prevOut[k] + : (...args: unknown[]) => ((latest.current as Record)[k] as (...a: unknown[]) => unknown)(...args); + } else { + values.set(k, v); + out[k] = v; + } + } + return { out: out as T, values, fns }; +} + +/** Stabile Fassung von `value` (s. Kopf). */ +export function useStableHost(value: T): T { + const latest = useRef(value); + // Im Render nachführen: Handler-Aufrufe danach treffen die neue Fassung. + latest.current = value; + const stable = useRef | null>(null); + stable.current = stabilizeHost(stable.current, value, latest); + return stable.current.out; +} diff --git a/src/state/panelHost/toolsHost.ts b/src/state/panelHost/toolsHost.ts new file mode 100644 index 00000000..2cb9fd69 --- /dev/null +++ b/src/state/panelHost/toolsHost.ts @@ -0,0 +1,70 @@ +// Panel-Host, Teil Werkzeuge, Zeichnungsebenen, Ebenen und Ressourcen ([121], aus +// `usePanelHostBase` herausgelöst): Werkzeug-Palette (aktives Werkzeug, Wandtyp, Fang), Zeichnungs- +// ebenen- und Ebenen-Handler sowie das CRUD der Ressourcen (Bauteile, Schraffuren, Linien-/Textstile, +// Wand-/Decken-/Dachtypen). Reine Verdrahtung auf die Projekt-Aktionen. + +import { isTauriRuntime } from "../../native/projectFile"; +import { openDrawingLevelsWindowNative } from "../../native/drawingLevelsWindow"; +import type { FlatHostOpts, HostPart } from "./types"; + +export function buildToolsHost(c: FlatHostOpts) { + const { activeCategoryCode, activeLevel, activeLevelId, activeTool, activeWallTypeId, addCategory, addCeiling, addCeilingType, addComponent, addDrawing, addElevation, addFloor, addHatch, addLineStyle, addRoofType, addSection, addTextStyle, addWallType, deleteCeilingType, deleteComponent, deleteHatch, deleteLineStyle, deleteRoofType, deleteTextStyle, deleteWallType, engineView, importHatches, importLineStyles, onRunCommand, onSelectTool, openLayerSettings, openSettings, patchCeilingType, patchComponent, patchHatch, patchLineStyle, patchRoofType, patchTextStyle, patchWallType, setActiveCategoryCode, setActiveLevelId, setActiveWallTypeId, setMenu, setSnap, snap, toggleCategoryVisible, toggleLevelVisible } = c; + return { + activeLevelId, + activeTool, + onSelectTool, + // Werkzeuge auch in der Perspektive: der Cursor wird per Raycast auf die + // Geschoss-Arbeitsebene (OKFF) projiziert und über onWorkplanePoint in + // dieselbe Engine wie im Grundriss gespeist (Viewport3D). + toolsEnabled: activeLevel.kind === "floor", + activeCommand: engineView.commandName, + onRunCommand, + activeWallTypeId, + onActiveWallTypeId: setActiveWallTypeId, + snap, + onSnapChange: setSnap, + onSelectLevel: setActiveLevelId, + onToggleLevel: toggleLevelVisible, + onAddFloor: addFloor, + onAddDrawing: addDrawing, + onAddSection: addSection, + onAddElevation: addElevation, + onAddCeiling: addCeiling, + onLevelContextMenu: (id, x, y) => + setMenu({ kind: "level", id, x, y }), + activeCategoryCode, + onSelectCategory: setActiveCategoryCode, + onToggleCategory: toggleCategoryVisible, + onAddCategory: addCategory, + onLayerContextMenu: (code, x, y) => + setMenu({ kind: "layer", code, x, y }), + onOpenLayerSettings: (code, x, y) => openLayerSettings(code, x, y), + onOpenDrawingLevelsWindow: () => { + if (isTauriRuntime()) void openDrawingLevelsWindowNative(); + }, + onOpenSettings: () => openSettings(), + onPatchComponent: patchComponent, + onAddComponent: addComponent, + onDeleteComponent: deleteComponent, + onPatchHatch: patchHatch, + onAddHatch: addHatch, + onDeleteHatch: deleteHatch, + onPatchLineStyle: patchLineStyle, + onAddLineStyle: addLineStyle, + onDeleteLineStyle: deleteLineStyle, + onPatchTextStyle: patchTextStyle, + onAddTextStyle: addTextStyle, + onDeleteTextStyle: deleteTextStyle, + onPatchWallType: patchWallType, + onAddWallType: addWallType, + onDeleteWallType: deleteWallType, + onPatchCeilingType: patchCeilingType, + onAddCeilingType: addCeilingType, + onDeleteCeilingType: deleteCeilingType, + onPatchRoofType: patchRoofType, + onAddRoofType: addRoofType, + onDeleteRoofType: deleteRoofType, + onImportLineStyles: importLineStyles, + onImportHatches: importHatches, + } satisfies HostPart; +} diff --git a/src/state/panelHost/types.ts b/src/state/panelHost/types.ts new file mode 100644 index 00000000..9e2dd86f --- /dev/null +++ b/src/state/panelHost/types.ts @@ -0,0 +1,163 @@ +// Panel-Host, gemeinsame Typen ([121]): was `usePanelHostBase` aus der App bekommt (`PanelHostOpts`), +// die flache Sicht darauf für die Teil-Bauer (`FlatHostOpts`, alle Unter-Bündel ausgepackt) und der +// Teil-Typ, den jeder Bauer liefert (`HostPart`). Die Teile zusammen ergeben den Basis-Host +// (`BaseHost` = `PanelHostValue` ohne Darstellungsmodus; den hängt `hostWithMode` je Dock an). + +import type { CoreOp, ProjectMutation } from "../../core"; +import type { RefObject } from "react"; +import type { DrawingLevel, Project } from "../../model/types"; +import type { ToolId } from "../../tools/types"; +import type { ViewType } from "../../model/viewTypes"; +import type { PlanViewHandle } from "../../views/plan/PlanView"; +import type { PanelHostValue } from "../../panels/host"; +import type { SelectionInfo } from "../selectionInfo"; +import type { EngineView } from "../../commands/engine"; +import type { TabId as ResourceTabId } from "../../ui/ResourceManager"; +import type { useProjectActions } from "../useProjectActions"; +import type { useSelectionState } from "../useSelectionState"; +import type { useDrawingToolState } from "../useDrawingToolState"; +import type { useTopBarState } from "../useTopBarState"; +import type { useDialogState } from "../useDialogState"; +import type { useContextMenuState } from "../../menus/useContextMenuState"; + +/** Basis-Host: alles ausser dem Darstellungsmodus je Dock. */ +export type BaseHost = Omit; + +/** Ein Teil des Basis-Hosts (Rückgabe eines Teil-Bauers, mit `satisfies` geprüft). */ +export type HostPart = Partial; + +/** + * Eingaben von `usePanelHostBase` (aus `App.tsx`). `project` und `selection` (Objekt-Info) sind keine + * Host-Felder mehr ([121]): Panels lesen sie selbst aus dem Store (`useStore`, `useSelectionInfo`). + * Die Handler brauchen sie aber weiter (jeweils die Fassung des letzten App-Renders). + */ +export type PanelHostOpts = { + project: Project; + setProject: (updater: ProjectMutation) => void; + /** Änderung direkt als Ops ([K4] S3), s. `ProjectSlice.applyChange`. */ + applyChange: (ops: readonly CoreOp[] | ((p: Project) => readonly CoreOp[]), coalesceKey?: string) => void; + activeLevelId: string; + setActiveLevelId: (id: string) => void; + activeLevel: DrawingLevel; + viewType: ViewType; + setViewType: (v: ViewType) => void; + engineView: EngineView; + onSelectTool: (id: ToolId) => void; + onRunCommand: (name: string) => void; + sectionLine: DrawingLevel | null; + onToggleSection3dCut: (id: string) => void; + openLayerSettings: (code: string, x: number, y: number) => void; + openSettings: () => void; + onOpenStampEditor: (roomId: string) => void; + openResources: (tab?: ResourceTabId) => void; + dxfInputRef: RefObject; + planViewRef: RefObject; + selection: SelectionInfo | null; + projectActions: Pick< + ReturnType, + | "toggleLevelVisible" + | "toggleCategoryVisible" + | "addFloor" + | "addDrawing" + | "addSection" + | "addElevation" + | "addCeiling" + | "addCategory" + | "snapshotLayerVisibility" + | "applyLayerVisibility" + | "snapshotDrawingVisibility" + | "applyDrawingVisibility" + | "patchLevel" + | "patchComponent" + | "addComponent" + | "deleteComponent" + | "patchHatch" + | "addHatch" + | "deleteHatch" + | "patchLineStyle" + | "addLineStyle" + | "deleteLineStyle" + | "patchTextStyle" + | "addTextStyle" + | "deleteTextStyle" + | "patchWallType" + | "addWallType" + | "deleteWallType" + | "patchCeilingType" + | "addCeilingType" + | "deleteCeilingType" + | "patchRoofType" + | "addRoofType" + | "deleteRoofType" + | "importLineStyles" + | "importHatches" + | "addContextObjectsAndFit" + | "removeContextObject" + | "removeContextObjects" + | "generateTerrain" + | "patchContextObject" + | "commitTransformOn" + | "setElementColor" + | "setElementWeight" + | "setElementFill" + | "setElementFillColor" + | "setElementForeground" + | "setElementBackground" + | "updateDrawing2D" + | "resizeElement" + | "updateWall" + | "setWallThickness" + | "updateOpening" + | "slideOpening" + | "updateCeiling" + | "setCeilingThickness" + | "updateStair" + | "updateRoom" + | "addColorToCustomPalette" + >; + selectionState: Pick< + ReturnType, + | "updateRoof" + | "setSelection" + | "selectedSectionLineId" + | "section3dCutId" + >; + toolState: Pick< + ReturnType, + "activeTool" | "activeWallTypeId" | "setActiveWallTypeId" | "activeCategoryCode" | "setActiveCategoryCode" | "snap" | "setSnap" + >; + topBarState: Pick< + ReturnType, + | "detail" + | "setDetail" + | "view3d" + | "setView3d" + | "fov" + | "setFov" + | "scaleDenominator" + | "setScaleDenominator" + | "selectedViewSnapshotId" + | "setSelectedViewSnapshotId" + >; + dialogState: Pick, "setActiveLayoutId" | "setOpeningEditorId">; + contextMenuState: Pick, "setMenu">; +}; + +/** + * Packt die Unter-Bündel aus: ein flaches Objekt mit allen Werten und Handlern. Die Felder der obersten + * Ebene (`selection` = Objekt-Info …) gehen vor gleichnamigen Feldern der Bündel. + */ +export function flatHostOpts(o: PanelHostOpts) { + return { + ...o.projectActions, + ...o.selectionState, + ...o.toolState, + ...o.topBarState, + ...o.dialogState, + ...o.contextMenuState, + ...o, + }; +} + +/** Flache Sicht auf die Eingaben (s. `flatHostOpts`). */ +export type FlatHostOpts = ReturnType; diff --git a/src/state/panelHost/viewSnapshotsHost.ts b/src/state/panelHost/viewSnapshotsHost.ts new file mode 100644 index 00000000..8fae8499 --- /dev/null +++ b/src/state/panelHost/viewSnapshotsHost.ts @@ -0,0 +1,184 @@ +// Panel-Host, Teil Ausschnitte und Zeichnungs-Reiter ([121], aus `usePanelHostBase` herausgelöst): +// Ausschnitte erfassen, anwenden, aktualisieren, umbenennen, löschen, in Ordner legen; Reiter +// öffnen/schliessen (`viewTabs.ts`); Sichtbarkeits-Kombinationen für den Panel-Fuss. Der +// Darstellungszustand selbst (`liveViewState`/`applyViewState`) kommt aus `viewState.ts`. + +import { addItems, fieldOps, patchItem, removeItems } from "../../core"; +import { t } from "../../i18n"; +import { getState } from "../appStore"; +import { captureViewSnapshot, matchingComboName, readViewSnapshot } from "../viewSnapshots"; +import { activateTab, activeTab, closeTab, detachSnapshots, getViewTabs, linkActiveTab, openTab, setViewTabs, storeActiveState, type ViewTabsState } from "../viewTabs"; +import { createViewSnapshotFolder, deleteFolder as deleteViewSnapshotFolder, moveSnapshotToFolder, moveFolder as moveViewSnapshotFolder } from "../viewSnapshotFolders"; +import { listDrawingCombos, listLayerCombos, loadDrawingCombo, loadLayerCombo } from "../visibilitySets"; +import type { FlatHostOpts, HostPart } from "./types"; +import type { ViewStateFns } from "./viewState"; + +/** Letzter Klick auf einen Ausschnitt im Panel (Doppelklick-Erkennung, [136]). */ +let lastPanelClick: { id: string; at: number; tabs: ViewTabsState } | null = null; + +export function buildViewSnapshotsHost(c: FlatHostOpts, view: ViewStateFns) { + const { activeLevelId, applyChange, project, selectedViewSnapshotId, setSelectedViewSnapshotId, snapshotDrawingVisibility } = c; + const { liveViewState, applyViewState } = view; + return { + // ── Ausschnitte / View-Snapshots (DOSSIER A2) und Reiter ([136]) ────── + // Ausschnitte leben im Projekt (Panel „Ausschnitte"), Reiter sind reiner UI-Zustand + // (state/viewTabs.ts). Klick im Panel zeigt den Ausschnitt im aktiven Reiter, Doppelklick/Knopf + // öffnet ihn in einem neuen; Reiter schliessen löscht keinen Ausschnitt; „Aktualisieren" schreibt + // die aktuelle Ansicht ausdrücklich in den Ausschnitt zurück. + onCaptureViewSnapshot: (name: string, folderId?: string): string => { + const trimmed = name.trim(); + if (!trimmed) return ""; + const snap = captureViewSnapshot(`vs-${Date.now()}`, trimmed, liveViewState()); + // Neuer Ausschnitt landet im aktiven Ordner (falls das Panel einen + // mitgibt), sonst auf der Wurzelebene — additiv (folderId optional). + const full = folderId ? { ...snap, folderId } : snap; + applyChange(addItems("viewSnapshots", [full])); + // Der aktive Reiter zeigt jetzt diesen Ausschnitt (Titel), der Ausschnitt ist im Panel gewählt. + setViewTabs(linkActiveTab(getViewTabs(), full.id)); + setSelectedViewSnapshotId(full.id); + return full.id; + }, + + // Titel eines Reiters ohne Ausschnitt: aktive Zeichnungskombination (falls deren + // Sichtbarkeits-Map exakt passt), sonst die Zeichnungsebene des Reiters. + viewTabAutoName: (levelId?: string): string => { + if (!levelId || levelId === activeLevelId) { + const combo = matchingComboName(listDrawingCombos(), loadDrawingCombo, snapshotDrawingVisibility()); + if (combo) return combo; + } + const id = levelId ?? activeLevelId; + return project.drawingLevels.find((l) => l.id === id)?.name ?? id; + }, + + // Klick im Panel: Ausschnitt im AKTIVEN Reiter anzeigen und im Panel wählen. + onApplyViewSnapshot: (id: string) => { + // Aktuellen Stand lesen (direkt nach einer Änderung am Ausschnitt ist `project` hier noch der alte). + const snap = (getState().project.viewSnapshots ?? []).find((s) => s.id === id); + if (!snap) return; + // Für einen folgenden Doppelklick merken, was der aktive Reiter vorher zeigte. + lastPanelClick = { id, at: Date.now(), tabs: storeActiveState(getViewTabs(), liveViewState()) }; + applyViewState(readViewSnapshot(snap)); + setViewTabs(linkActiveTab(getViewTabs(), id)); + setSelectedViewSnapshotId(id); + }, + + // Doppelklick/Knopf im Panel: Ausschnitt in einem NEUEN Reiter öffnen. + onOpenViewSnapshotInNewTab: (id: string) => { + const snap = (getState().project.viewSnapshots ?? []).find((s) => s.id === id); + if (!snap) return; + // Doppelklick: die beiden vorangehenden Klicks haben den Ausschnitt schon im aktiven Reiter gezeigt — + // dieser behält seinen früheren Inhalt, nur der neue Reiter zeigt den Ausschnitt. + const prev = lastPanelClick; + lastPanelClick = null; + const base = prev && prev.id === id && Date.now() - prev.at < 1000 ? prev.tabs : undefined; + const cur = getViewTabs(); + setViewTabs( + base && base.activeId === cur.activeId + ? openTab({ ...cur, tabs: cur.tabs.map((tb) => (tb.id === cur.activeId ? activeTab(base) : tb)) }, { snapshotId: id }) + : openTab(cur, { snapshotId: id }, liveViewState()), + ); + applyViewState(readViewSnapshot(snap)); + setSelectedViewSnapshotId(id); + }, + + // Ausdrücklich: aktuelle Ansicht in den Ausschnitt schreiben (Name, Ordner, Vorlage bleiben). + onUpdateViewSnapshot: (id: string) => { + const live = liveViewState(); + applyChange((p) => + patchItem(p, "viewSnapshots", id, (v) => { + const fresh = captureViewSnapshot(v.id, v.name, live); + const { cameraCenter: _c, cameraPxPerMeter: _m, ...rest } = v; + return { ...rest, ...fresh }; + }), + ); + }, + + // Reiterleiste. + onActivateViewTab: (tabId: string) => { + const { next, apply } = activateTab(getViewTabs(), tabId, liveViewState()); + setViewTabs(next); + if (apply) applyViewState(apply); + const snapId = next.tabs.find((tb) => tb.id === next.activeId)?.snapshotId; + if (snapId) setSelectedViewSnapshotId(snapId); + }, + onNewViewTab: () => { + setViewTabs(openTab(getViewTabs(), {}, liveViewState())); + }, + onCloseViewTab: (tabId: string) => { + const { next, apply } = closeTab(getViewTabs(), tabId); + setViewTabs(next); + if (apply) applyViewState(apply); + }, + + onRenameViewSnapshot: (id: string, name: string) => { + const trimmed = name.trim(); + if (!trimmed) return; + applyChange((p) => patchItem(p, "viewSnapshots", id, { name: trimmed })); + }, + + onDuplicateViewSnapshot: (id: string) => { + // [40] Kopie gleich hinter dem Original, gleicher Ordner, „… Kopie"; danach angewählt. + const list = project.viewSnapshots ?? []; + const i = list.findIndex((v) => v.id === id); + if (i < 0) return; + const copy = { ...list[i], id: `vs-${Date.now()}`, name: t("viewsnap.copyName", { name: list[i].name }) }; + applyChange(() => addItems("viewSnapshots", [copy], i + 1)); + setSelectedViewSnapshotId(copy.id); + }, + + // Löschen nur im Panel. Offene Reiter des Ausschnitts bleiben (eigener Zustand, letzter Name als Titel). + onDeleteViewSnapshot: (id: string) => { + const snap = (getState().project.viewSnapshots ?? []).find((s) => s.id === id); + applyChange((p) => removeItems(p, "viewSnapshots", [id])); + if (snap) setViewTabs(detachSnapshots(getViewTabs(), [{ id, name: snap.name }])); + if (selectedViewSnapshotId === id) setSelectedViewSnapshotId(null); + }, + + // ── Ausschnitte-Baum (Ordner, DOSSIER A2) ───────────────────────────── + // Immutable CRUD über pure Helfer (state/viewSnapshotFolders.ts). Löschen + // zieht Inhalt auf die Elternebene hoch (kein Datenverlust). + onAddViewSnapshotFolder: (parentId) => { + const id = `vsf-${Date.now()}`; + const folder = createViewSnapshotFolder( + id, + t("viewsnap.folder.defaultName"), + parentId, + ); + applyChange(addItems("viewSnapshotFolders", [folder])); + return id; + }, + onRenameViewSnapshotFolder: (id, name) => { + const trimmed = name.trim(); + if (!trimmed) return; + applyChange((p) => patchItem(p, "viewSnapshotFolders", id, { name: trimmed })); + }, + onDeleteViewSnapshotFolder: (id) => { + applyChange((p) => { + const { folders, snapshots } = deleteViewSnapshotFolder( + id, + p.viewSnapshotFolders ?? [], + p.viewSnapshots ?? [], + ); + return [...fieldOps(p, "viewSnapshotFolders", folders), ...fieldOps(p, "viewSnapshots", snapshots)]; + }); + }, + onMoveViewSnapshotToFolder: (snapshotId, folderId) => { + applyChange((p) => fieldOps(p, "viewSnapshots", moveSnapshotToFolder(p.viewSnapshots ?? [], snapshotId, folderId))); + }, + onMoveViewSnapshotFolder: (folderId, parentId) => { + applyChange((p) => + fieldOps(p, "viewSnapshotFolders", moveViewSnapshotFolder(p.viewSnapshotFolders ?? [], folderId, parentId)), + ); + }, + + // Footer-Bar des Ausschnitte-Panels: die aktuell „angewählte" Id plus + // Lesezugriff auf die benannten Sichtbarkeits-Kombinationen (localStorage), + // damit der Footer den Kombi-NAMEN zu den gespeicherten Maps auflösen kann. + selectedViewSnapshotId, + listLayerCombos, + loadLayerCombo, + listDrawingCombos, + loadDrawingCombo, + + } satisfies HostPart; +} diff --git a/src/state/panelHost/viewState.ts b/src/state/panelHost/viewState.ts new file mode 100644 index 00000000..be94679f --- /dev/null +++ b/src/state/panelHost/viewState.ts @@ -0,0 +1,97 @@ +// Panel-Host, Darstellungszustand für Ausschnitte und Reiter ([121], aus `usePanelHostBase` +// herausgelöst): `liveViewState` liest Ansicht, Kamera, Massstab, Detail, Geschoss, Sichtbarkeit und +// aktive Overrides; `applyViewState` stellt einen solchen Zustand wieder her (Projektdaten nur bei +// echter Abweichung, als ein Undo-Schritt). + +import { fieldOps } from "../../core"; +import type { RefObject } from "react"; +import type { ViewType } from "../../model/viewTypes"; +import type { PlanViewHandle } from "../../views/plan/PlanView"; +import { getState } from "../appStore"; +import { applyOverrideRuleEnabled, type ViewSnapshotState } from "../viewSnapshots"; +import type { FlatHostOpts } from "./types"; + +/** + * Grundriss-Kamera für einen View-Snapshot einsammeln (Bildmitte + Zoom) — + * nur möglich, wenn gerade ein Grundriss gemountet ist (`viewType==="grundriss"`, + * `planViewRef.current` also nicht null); sonst leeres Objekt (kein Feld + * gesetzt), damit `{...captureCameraState(...)}` additiv in ein + * `ViewSnapshotState`-Objektliteral eingemischt werden kann, ohne `undefined`- + * Werte explizit zu setzen. + */ +function captureCameraState( + planViewRef: RefObject, + viewType: ViewType, +): Partial> { + if (viewType !== "grundriss") return {}; + const pv = planViewRef.current; + if (!pv) return {}; + const pxPerMeter = pv.pxPerMeter(); + if (!(pxPerMeter > 0)) return {}; + return { cameraCenter: pv.viewCenterModel(), cameraPxPerMeter: pxPerMeter }; +} + +/** Stimmt die Live-Sichtbarkeit mit der gespeicherten überein (nur gespeicherte Schlüssel zählen)? */ +function visibilityMatches(live: Record, stored: Record): boolean { + for (const k of Object.keys(stored)) if (k in live && live[k] !== stored[k]) return false; + return true; +} + +/** Lesen und Wiederherstellen des Darstellungszustands (s. Kopf). */ +export interface ViewStateFns { + liveViewState: () => ViewSnapshotState; + applyViewState: (st: ViewSnapshotState) => void; +} + +export function buildViewStateFns(c: FlatHostOpts): ViewStateFns { + const { activeLevelId, applyChange, applyDrawingVisibility, applyLayerVisibility, detail, fov, planViewRef, scaleDenominator, setActiveLevelId, setDetail, setFov, setScaleDenominator, setView3d, setViewType, snapshotDrawingVisibility, snapshotLayerVisibility, view3d, viewType } = c; + // Aktueller Darstellungszustand (Ansicht/Kamera/Massstab/Detail/Geschoss + Sichtbarkeit + Overrides). + const liveViewState = (): ViewSnapshotState => ({ + viewType, + view3d, + fov, + scaleDenominator, + detail, + activeLevelId, + layerVisibility: snapshotLayerVisibility(), + drawingVisibility: snapshotDrawingVisibility(), + enabledOverrideRuleIds: (getState().project.overrideRules ?? []).filter((r) => r.enabled).map((r) => r.id), + ...captureCameraState(planViewRef, viewType), + }); + // Darstellungszustand wiederherstellen. Reihenfolge: Geschoss ZUERST (setActiveLevelId setzt viewType + // provisorisch aus viewTypeByLevel), danach die Ansicht (überschreibt es synchron), dann Sichtbarkeit + + // Overrides — diese sind Projektdaten: nur bei echter Abweichung und dann als EIN Undo-Schritt. + // Den imperativen Massstab-Zoom (Plan muss für den neuen View gemountet sein) via rAF nachziehen. + const applyViewState = (st: ViewSnapshotState) => { + setActiveLevelId(st.activeLevelId); + setViewType(st.viewType); + setView3d(st.view3d); + setFov(st.fov); + setDetail(st.detail); + setScaleDenominator(st.scaleDenominator); + const layersDiffer = !visibilityMatches(snapshotLayerVisibility(), st.layerVisibility); + const drawingsDiffer = !visibilityMatches(snapshotDrawingVisibility(), st.drawingVisibility); + const wanted = new Set(st.enabledOverrideRuleIds); + const overridesDiffer = (getState().project.overrideRules ?? []).some((r) => !!r.enabled !== wanted.has(r.id)); + if (layersDiffer || drawingsDiffer || overridesDiffer) { + getState().groupChanges(() => { + if (layersDiffer) applyLayerVisibility(st.layerVisibility); + if (drawingsDiffer) applyDrawingVisibility(st.drawingVisibility); + if (overridesDiffer) + applyChange((p) => + fieldOps(p, "overrideRules", applyOverrideRuleEnabled(p.overrideRules ?? [], st.enabledOverrideRuleIds)), + ); + }); + } + requestAnimationFrame(() => { + planViewRef.current?.applyScale(st.scaleDenominator); + // Kamera NACH `applyScale` restaurieren (nicht statt): `applyScale` setzt auch die + // Papier-Massstab-Referenz für Strichbreiten, hält aber die BISHERIGE Bildmitte; `setCamera` + // schwenkt danach im selben Tick auf die erfasste Mitte — nur wenn der Zustand eine Kamera trägt. + if (st.cameraCenter && st.cameraPxPerMeter) { + planViewRef.current?.setCamera(st.cameraCenter, st.cameraPxPerMeter); + } + }); + }; + return { liveViewState, applyViewState }; +} diff --git a/src/state/panelOps.test.ts b/src/state/panelOps.test.ts index d045757f..4eccc1cd 100644 --- a/src/state/panelOps.test.ts +++ b/src/state/panelOps.test.ts @@ -129,7 +129,8 @@ function host(h: ReturnType, selection: any) { projectActions: stubObj({ snapshotLayerVisibility: () => ({}), snapshotDrawingVisibility: () => ({}), applyLayerVisibility: () => {}, applyDrawingVisibility: () => {} }), selectionState: stubObj({ selection: EMPTY_SELECTION }), toolState: stubObj({}), - topBarState: stubObj({}), + // Bündel werden ausgepackt (Spread): Felder, die die Aktionen brauchen, ausdrücklich angeben. + topBarState: stubObj({ setSelectedViewSnapshotId: () => {} }), dialogState: stubObj({ setActiveLayoutId: () => {} }), contextMenuState: stubObj({}), engineView: { commandName: null }, diff --git a/src/state/usePanelHostBase.ts b/src/state/usePanelHostBase.ts index 713f6ed9..e465667d 100644 --- a/src/state/usePanelHostBase.ts +++ b/src/state/usePanelHostBase.ts @@ -1,1551 +1,72 @@ -// Host-Context für die Panels: baut den (dock-unabhängigen) `PanelHostValue`- -// Basisvertrag aus Projekt/Selektion/Snap-/View-State + den Projekt-Mutationen -// zusammen — die eine grosse Adapter-Schicht zwischen App-State und dem -// PanelHostContext, den die Docks/Floating-Panels konsumieren (`hostWithMode` -// hängt je Dock nur noch den Darstellungsmodus an). Reine Verschiebung aus -// App.tsx, keine Verhaltensänderung. +// Host-Context für die Panels: baut den (dock-unabhängigen) Basis-Host aus Snap-/View-State, Auswahl +// und den Projekt-Mutationen zusammen — die Adapter-Schicht zwischen App-Zustand und dem +// PanelHostContext, den Docks und schwebende Panels konsumieren (`hostWithMode` hängt je Dock nur noch +// den Darstellungsmodus an). Aufgerufen von `App.tsx`. // -// Extrahiert aus App.tsx. Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md). +// [121] Zerlegt in Teil-Bauer unter `panelHost/` (je Themenbereich eine Datei, s. dort): Werkzeuge und +// Ressourcen, Darstellung der Auswahl, Bauteil-Attribute, Lage/Elemente, Ausschnitte/Reiter, Layouts. +// Das Projekt und die Objekt-Info sind KEINE Host-Felder mehr — Panels abonnieren sie selbst im Store +// (`useStore`, `useSelectionInfo`). Der Host wird zwar bei jeder Projekt-/Auswahl-Änderung neu gebaut +// (die Handler schliessen über den aktuellen Stand), `useStableHost` hält aber seine Identität, solange +// sich kein Wert-Feld ändert: eine Op am Modell rendert die Panels nicht über den Host neu. -import { applyFillMode } from "./fillMode"; -import { addItems, cmdMutation, fieldOps, opsMutation, patchItem, patchItems, removeItems, removeRoofHole, setFieldIfChanged, setRoofEdge } from "../core"; -import type { CoreOp, ProjectMutation } from "../core"; -import { useMemo, type RefObject } from "react"; -import type { DrawingLevel, Project } from "../model/types"; -import { resolvePenColor } from "../model/penSets"; -import type { ToolId } from "../tools/types"; -import type { ViewType } from "../model/viewTypes"; -import type { TransformSelection } from "../tools/transform"; -import type { PlanViewHandle } from "../views/plan/PlanView"; -import type { PanelHostValue } from "../panels/host"; -import type { SelectionInfo } from "./selectionInfo"; -import { clearKinds } from "./selection"; -import type { SelectionKind } from "./selection"; -import type { EngineView } from "../commands/engine"; -import type { ScheduleKind } from "../export/exportSchedule"; -import type { TabId as ResourceTabId } from "../ui/ResourceManager"; -import { isTauriRuntime } from "../native/projectFile"; -import { openDrawingLevelsWindowNative } from "../native/drawingLevelsWindow"; -import { t } from "../i18n"; -import { getState } from "./appStore"; -import { - applyOverrideRuleEnabled, - captureViewSnapshot, - matchingComboName, - readViewSnapshot, - type ViewSnapshotState, -} from "./viewSnapshots"; -import { - activateTab, - activeTab, - closeTab, - detachSnapshots, - getViewTabs, - linkActiveTab, - openTab, - setViewTabs, - storeActiveState, - type ViewTabsState, -} from "./viewTabs"; +import { useMemo } from "react"; +import { buildElementAttributesHost } from "./panelHost/elementAttributesHost"; +import { buildLayoutsHost } from "./panelHost/layoutsHost"; +import { buildSelectionStyleHost } from "./panelHost/selectionStyleHost"; +import { buildSiteHost } from "./panelHost/siteHost"; +import { useStableHost } from "./panelHost/stableHost"; +import { buildToolsHost } from "./panelHost/toolsHost"; +import { flatHostOpts, type BaseHost, type PanelHostOpts } from "./panelHost/types"; +import { buildViewSnapshotsHost } from "./panelHost/viewSnapshotsHost"; +import { buildViewStateFns } from "./panelHost/viewState"; -/** Letzter Klick auf einen Ausschnitt im Panel (Doppelklick-Erkennung, [136]). */ -let lastPanelClick: { id: string; at: number; tabs: ViewTabsState } | null = null; -import { - createViewSnapshotFolder, - deleteFolder as deleteViewSnapshotFolder, - moveSnapshotToFolder, - moveFolder as moveViewSnapshotFolder, -} from "./viewSnapshotFolders"; -import { - listDrawingCombos, - listLayerCombos, - loadDrawingCombo, - loadLayerCombo, -} from "./visibilitySets"; -import { - createLayout, - createLayoutFolder, - createMasterLayout, - deleteFolder as deleteLayoutFolder, - deleteMasterFolder, - moveLayoutToFolder, - moveFolderToFolder, - createSheetLevel, -} from "../model/layoutModel"; -import { folderPdfBytes } from "../export/layoutPdf"; -import { addPublishSetOps, deletePublishSetOps, patchPublishSetOps, publishSet } from "./publishActions"; -import { saveBinaryFile } from "../native/saveFile"; -import type { useProjectActions } from "./useProjectActions"; -import type { useSelectionState } from "./useSelectionState"; -import type { useDrawingToolState } from "./useDrawingToolState"; -import type { useTopBarState } from "./useTopBarState"; -import type { useDialogState } from "./useDialogState"; -import type { useContextMenuState } from "../menus/useContextMenuState"; +export type { PanelHostOpts } from "./panelHost/types"; -/** - * Baut eine TransformSelection für GENAU EIN Element (Object-Info: Verschieben/ - * Drehen per Zahlenfeld, siehe onMoveSelectionBy/onRotateSelectionAround unten). - * Deckt nur die vom Transform-Kern (tools/transform.ts) unterstützten Arten ab - * — Decke/Öffnung/Treppe/Raum kennt er nicht, dort liefert die Funktion `null` - * (Aufrufer macht dann No-op, wie bei onResizeSelection). - */ -function singleTransformSel(kind: string, id: string): TransformSelection | null { - if (kind === "wall") return { wallIds: [id], drawingId: null }; - if (kind === "drawing2d") return { wallIds: [], drawingId: id }; - if (kind === "extrudedSolid") return { wallIds: [], drawingId: null, extrudedSolidId: id }; - if (kind === "column") return { wallIds: [], drawingId: null, columnId: id }; - if (kind === "ceiling") return { wallIds: [], drawingId: null, ceilingIds: [id] }; - // Dach: Move geht (Umriss verschiebt sich), Rotate no-opt bewusst (s. - // TransformSelection.roofIds) — der Host-Aufruf degradiert dafür von - // selbst über `gatherItems`, kein Sonderfall hier nötig. - if (kind === "roof") return { wallIds: [], drawingId: null, roofIds: [id] }; - if (kind === "stair") return { wallIds: [], drawingId: null, stairIds: [id] }; - if (kind === "room") return { wallIds: [], drawingId: null, roomIds: [id] }; - // [144] Öffnung: X/Y im Objekt-Info verschiebt sie entlang (bzw. in eine andere) Wand. - if (kind === "opening") return { wallIds: [], drawingId: null, openingIds: [id] }; - return null; -} - -/** - * Grundriss-Kamera für einen View-Snapshot einsammeln (Bildmitte + Zoom) — - * nur möglich, wenn gerade ein Grundriss gemountet ist (`viewType==="grundriss"`, - * `planViewRef.current` also nicht null); sonst leeres Objekt (kein Feld - * gesetzt), damit `{...captureCameraState(...)}` additiv in ein - * `ViewSnapshotState`-Objektliteral eingemischt werden kann, ohne `undefined`- - * Werte explizit zu setzen. - */ -/** Stimmt die Live-Sichtbarkeit mit der gespeicherten überein (nur gespeicherte Schlüssel zählen)? */ -function visibilityMatches(live: Record, stored: Record): boolean { - for (const k of Object.keys(stored)) if (k in live && live[k] !== stored[k]) return false; - return true; -} - -function captureCameraState( - planViewRef: RefObject, - viewType: ViewType, -): Partial> { - if (viewType !== "grundriss") return {}; - const pv = planViewRef.current; - if (!pv) return {}; - const pxPerMeter = pv.pxPerMeter(); - if (!(pxPerMeter > 0)) return {}; - return { cameraCenter: pv.viewCenterModel(), cameraPxPerMeter: pxPerMeter }; -} - -export function usePanelHostBase(opts: { - project: Project; - setProject: (updater: ProjectMutation) => void; - /** Änderung direkt als Ops ([K4] S3), s. `ProjectSlice.applyChange`. */ - applyChange: (ops: readonly CoreOp[] | ((p: Project) => readonly CoreOp[]), coalesceKey?: string) => void; - activeLevelId: string; - setActiveLevelId: (id: string) => void; - activeLevel: DrawingLevel; - viewType: ViewType; - setViewType: (v: ViewType) => void; - engineView: EngineView; - onSelectTool: (id: ToolId) => void; - onRunCommand: (name: string) => void; - sectionLine: DrawingLevel | null; - onToggleSection3dCut: (id: string) => void; - openLayerSettings: (code: string, x: number, y: number) => void; - openSettings: () => void; - onOpenStampEditor: (roomId: string) => void; - openResources: (tab?: ResourceTabId) => void; - dxfInputRef: RefObject; - planViewRef: RefObject; - selection: SelectionInfo | null; - projectActions: Pick< - ReturnType, - | "toggleLevelVisible" - | "toggleCategoryVisible" - | "addFloor" - | "addDrawing" - | "addSection" - | "addElevation" - | "addCeiling" - | "addCategory" - | "snapshotLayerVisibility" - | "applyLayerVisibility" - | "snapshotDrawingVisibility" - | "applyDrawingVisibility" - | "patchLevel" - | "patchComponent" - | "addComponent" - | "deleteComponent" - | "patchHatch" - | "addHatch" - | "deleteHatch" - | "patchLineStyle" - | "addLineStyle" - | "deleteLineStyle" - | "patchTextStyle" - | "addTextStyle" - | "deleteTextStyle" - | "patchWallType" - | "addWallType" - | "deleteWallType" - | "patchCeilingType" - | "addCeilingType" - | "deleteCeilingType" - | "patchRoofType" - | "addRoofType" - | "deleteRoofType" - | "importLineStyles" - | "importHatches" - | "addContextObjectsAndFit" - | "removeContextObject" - | "removeContextObjects" - | "generateTerrain" - | "patchContextObject" - | "commitTransformOn" - | "setElementColor" - | "setElementWeight" - | "setElementFill" - | "setElementFillColor" - | "setElementForeground" - | "setElementBackground" - | "updateDrawing2D" - | "resizeElement" - | "updateWall" - | "setWallThickness" - | "updateOpening" - | "slideOpening" - | "updateCeiling" - | "setCeilingThickness" - | "updateStair" - | "updateRoom" - | "addColorToCustomPalette" - >; - selectionState: Pick< - ReturnType, - | "updateRoof" - | "setSelection" - | "selectedSectionLineId" - | "section3dCutId" - >; - toolState: Pick< - ReturnType, - "activeTool" | "activeWallTypeId" | "setActiveWallTypeId" | "activeCategoryCode" | "setActiveCategoryCode" | "snap" | "setSnap" - >; - topBarState: Pick< - ReturnType, - | "detail" - | "setDetail" - | "view3d" - | "setView3d" - | "fov" - | "setFov" - | "scaleDenominator" - | "setScaleDenominator" - | "selectedViewSnapshotId" - | "setSelectedViewSnapshotId" - >; - dialogState: Pick, "setActiveLayoutId" | "setOpeningEditorId">; - contextMenuState: Pick, "setMenu">; -}): Omit { +export function usePanelHostBase(opts: PanelHostOpts): BaseHost { + const c = flatHostOpts(opts); const { project, - setProject, - applyChange, activeLevelId, - setActiveLevelId, - activeLevel, + activeCategoryCode, + activeTool, + activeWallTypeId, + snap, viewType, - setViewType, - engineView, - onSelectTool, - onRunCommand, - sectionLine, - onToggleSection3dCut, - openLayerSettings, - openSettings, - onOpenStampEditor, - openResources, - dxfInputRef, - planViewRef, + view3d, + fov, + detail, + scaleDenominator, selection, - projectActions, - selectionState, - toolState, - topBarState, - dialogState, - contextMenuState, - } = opts; - const { - toggleLevelVisible, - toggleCategoryVisible, - addFloor, - addDrawing, - addSection, - addElevation, - addCeiling, - addCategory, - snapshotLayerVisibility, - applyLayerVisibility, - snapshotDrawingVisibility, - applyDrawingVisibility, - patchLevel, - patchComponent, - addComponent, - deleteComponent, - patchHatch, - addHatch, - deleteHatch, - patchLineStyle, - addLineStyle, - deleteLineStyle, - patchTextStyle, - addTextStyle, - deleteTextStyle, - patchWallType, - addWallType, - deleteWallType, - patchCeilingType, - addCeilingType, - deleteCeilingType, - patchRoofType, - addRoofType, - deleteRoofType, - importLineStyles, - importHatches, - addContextObjectsAndFit, - removeContextObject, - removeContextObjects, - generateTerrain, - patchContextObject, - commitTransformOn, - setElementColor, - setElementWeight, - setElementFill, - setElementFillColor, - setElementForeground, - setElementBackground, - updateDrawing2D, - resizeElement, - updateWall, - setWallThickness, - updateOpening, - slideOpening, - updateCeiling, - setCeilingThickness, - updateStair, - updateRoom, - addColorToCustomPalette, - } = projectActions; - const { - updateRoof, - setSelection, + sectionLine, selectedSectionLineId, section3dCutId, - } = selectionState; - const { activeTool, activeWallTypeId, setActiveWallTypeId, activeCategoryCode, setActiveCategoryCode, snap, setSnap } = - toolState; - const { - detail, - setDetail, - view3d, - setView3d, - fov, - setFov, - scaleDenominator, - setScaleDenominator, + onToggleSection3dCut, selectedViewSnapshotId, - setSelectedViewSnapshotId, - } = topBarState; - const { setActiveLayoutId, setOpeningEditorId } = dialogState; - const { setMenu } = contextMenuState; - - const baseHost = useMemo(() => { - // Aktueller Darstellungszustand (Ansicht/Kamera/Massstab/Detail/Geschoss + Sichtbarkeit + Overrides). - const liveViewState = (): ViewSnapshotState => ({ - viewType, - view3d, - fov, - scaleDenominator, - detail, - activeLevelId, - layerVisibility: snapshotLayerVisibility(), - drawingVisibility: snapshotDrawingVisibility(), - enabledOverrideRuleIds: (getState().project.overrideRules ?? []).filter((r) => r.enabled).map((r) => r.id), - ...captureCameraState(planViewRef, viewType), - }); - // Darstellungszustand wiederherstellen. Reihenfolge: Geschoss ZUERST (setActiveLevelId setzt viewType - // provisorisch aus viewTypeByLevel), danach die Ansicht (überschreibt es synchron), dann Sichtbarkeit + - // Overrides — diese sind Projektdaten: nur bei echter Abweichung und dann als EIN Undo-Schritt. - // Den imperativen Massstab-Zoom (Plan muss für den neuen View gemountet sein) via rAF nachziehen. - const applyViewState = (st: ViewSnapshotState) => { - setActiveLevelId(st.activeLevelId); - setViewType(st.viewType); - setView3d(st.view3d); - setFov(st.fov); - setDetail(st.detail); - setScaleDenominator(st.scaleDenominator); - const layersDiffer = !visibilityMatches(snapshotLayerVisibility(), st.layerVisibility); - const drawingsDiffer = !visibilityMatches(snapshotDrawingVisibility(), st.drawingVisibility); - const wanted = new Set(st.enabledOverrideRuleIds); - const overridesDiffer = (getState().project.overrideRules ?? []).some((r) => !!r.enabled !== wanted.has(r.id)); - if (layersDiffer || drawingsDiffer || overridesDiffer) { - getState().groupChanges(() => { - if (layersDiffer) applyLayerVisibility(st.layerVisibility); - if (drawingsDiffer) applyDrawingVisibility(st.drawingVisibility); - if (overridesDiffer) - applyChange((p) => - fieldOps(p, "overrideRules", applyOverrideRuleEnabled(p.overrideRules ?? [], st.enabledOverrideRuleIds)), - ); - }); - } - requestAnimationFrame(() => { - planViewRef.current?.applyScale(st.scaleDenominator); - // Kamera NACH `applyScale` restaurieren (nicht statt): `applyScale` setzt auch die - // Papier-Massstab-Referenz für Strichbreiten, hält aber die BISHERIGE Bildmitte; `setCamera` - // schwenkt danach im selben Tick auf die erfasste Mitte — nur wenn der Zustand eine Kamera trägt. - if (st.cameraCenter && st.cameraPxPerMeter) { - planViewRef.current?.setCamera(st.cameraCenter, st.cameraPxPerMeter); - } - }); - }; - const value: Omit = { - project, - activeLevelId, - activeTool, - onSelectTool, - // Werkzeuge auch in der Perspektive: der Cursor wird per Raycast auf die - // Geschoss-Arbeitsebene (OKFF) projiziert und über onWorkplanePoint in - // dieselbe Engine wie im Grundriss gespeist (Viewport3D). - toolsEnabled: activeLevel.kind === "floor", - activeCommand: engineView.commandName, - onRunCommand, - activeWallTypeId, - onActiveWallTypeId: setActiveWallTypeId, - snap, - onSnapChange: setSnap, - onSelectLevel: setActiveLevelId, - onToggleLevel: toggleLevelVisible, - onAddFloor: addFloor, - onAddDrawing: addDrawing, - onAddSection: addSection, - onAddElevation: addElevation, - onAddCeiling: addCeiling, - onLevelContextMenu: (id, x, y) => - setMenu({ kind: "level", id, x, y }), - activeCategoryCode, - onSelectCategory: setActiveCategoryCode, - onToggleCategory: toggleCategoryVisible, - onAddCategory: addCategory, - onLayerContextMenu: (code, x, y) => - setMenu({ kind: "layer", code, x, y }), - onOpenLayerSettings: (code, x, y) => openLayerSettings(code, x, y), - onOpenDrawingLevelsWindow: () => { - if (isTauriRuntime()) void openDrawingLevelsWindowNative(); - }, - onOpenSettings: () => openSettings(), - onPatchComponent: patchComponent, - onAddComponent: addComponent, - onDeleteComponent: deleteComponent, - onPatchHatch: patchHatch, - onAddHatch: addHatch, - onDeleteHatch: deleteHatch, - onPatchLineStyle: patchLineStyle, - onAddLineStyle: addLineStyle, - onDeleteLineStyle: deleteLineStyle, - onPatchTextStyle: patchTextStyle, - onAddTextStyle: addTextStyle, - onDeleteTextStyle: deleteTextStyle, - onPatchWallType: patchWallType, - onAddWallType: addWallType, - onDeleteWallType: deleteWallType, - onPatchCeilingType: patchCeilingType, - onAddCeilingType: addCeilingType, - onDeleteCeilingType: deleteCeilingType, - onPatchRoofType: patchRoofType, - onAddRoofType: addRoofType, - onDeleteRoofType: deleteRoofType, - onImportLineStyles: importLineStyles, - onImportHatches: importHatches, - selection, + } = c; + const commandName = opts.engineView.commandName; + const baseHost = useMemo((): BaseHost => { + const view = buildViewStateFns(c); + return { + ...buildToolsHost(c), // Platzhalter — der LIVE-Wert wird in `hostWithMode` je Render injiziert // (nicht hier, weil `draft` bewusst kein Dep dieses Memos ist, s. dort). measurement: null, - onSetSelectionColor: (color) => { - if (!selection) return; - if (selection.kind === "wall" || selection.kind === "drawing2d") - setElementColor(selection.kind, selection.id, color); - else if (selection.kind === "ceiling") - updateCeiling(selection.id, { color }); - else if (selection.kind === "opening") - updateOpening(selection.id, { color }); - else if (selection.kind === "stair") - updateStair(selection.id, { color }); - else if (selection.kind === "room") - updateRoom(selection.id, { color }); - }, - // Stift-Kopplung der Farbe oben (s. `Selection.colorPenId`-Doku) — - // dieselben Selektionsarten wie `onSetSelectionColor`. `penId` gesetzt ⇒ Farbe sofort aus dem aktiven - // Stiftsatz backen; `undefined` ⇒ nur die Kopplung lösen, letzter - // gebackener Wert bleibt als freie Farbe stehen. - onSetSelectionColorPen: (penId) => { - if (!selection) return; - const color = penId ? resolvePenColor(project, penId) : undefined; - const patch = color !== undefined ? { colorPenId: penId, color } : { colorPenId: penId }; - if (selection.kind === "wall") updateWall(selection.id, patch); - else if (selection.kind === "drawing2d") updateDrawing2D(selection.id, patch); - else if (selection.kind === "ceiling") updateCeiling(selection.id, patch); - else if (selection.kind === "opening") updateOpening(selection.id, patch); - else if (selection.kind === "stair") updateStair(selection.id, patch); - else if (selection.kind === "room") updateRoom(selection.id, patch); - }, - onSetSelectionWeight: (weightMm) => { - // Strichstärke-Override: Wand/Decke (`strokeWeight`) oder Drawing2D (`weightMm`). - if (selection?.kind === "wall") updateWall(selection.id, { strokeWeight: weightMm }); - else if (selection?.kind === "ceiling") - updateCeiling(selection.id, { strokeWeight: weightMm }); - else if (selection?.kind === "drawing2d") - setElementWeight(selection.id, weightMm); - }, - onSetSelectionFill: (hatchId) => { - // Schraffur-Override: Wand, Decke oder Drawing2D (geschlossene Formen). - // `null` löscht das Feld (→ „Nach System"/Quelle). - if (selection?.kind === "wall") - updateWall(selection.id, { hatchId: hatchId ?? undefined }); - else if (selection?.kind === "ceiling") - updateCeiling(selection.id, { hatchId: hatchId ?? undefined }); - else if (selection?.kind === "drawing2d") - setElementFill(selection.id, hatchId); - }, - onSetSelectionLineStyle: (lineStyleId) => { - // Nur Drawing2D trägt einen Linienstil (Wand/Decke/etc. nicht). - if (selection?.kind === "drawing2d") - updateDrawing2D(selection.id, { lineStyleId }); - }, - onSetSelectionFillColor: (color) => { - // Vollton-Füllfarbe nur bei Drawing2D (geschlossene Formen). - if (selection?.kind === "drawing2d") - setElementFillColor(selection.id, color); - }, - onSetSelectionFillMode: (mode) => { - if (selection?.kind !== "drawing2d") return; - const id = selection.id; - setProject(opsMutation((p) => patchItem(p, "drawings2d", id, (d) => applyFillMode(d, p.hatches, mode)))); - }, - onSetSelectionFillOpacity: (opacity) => { - if (selection?.kind === "drawing2d") - setProject( - opsMutation((p) => - patchItem(p, "drawings2d", selection.id, (d) => { - const { fillOpacity: _old, ...rest } = d; - return opacity >= 1 ? rest : { ...rest, fillOpacity: Math.max(0, opacity) }; - }), - ), - ); - }, - onSetSelectionOpacity: (opacity) => { - // Deckkraft eines 2D-Elements. Bei BILDERN bleibt es die Deckkraft der - // Bildgeometrie (bestehendes Verhalten, eigenes Feld); bei allen - // übrigen Formen die neue OBJEKT-Transparenz, die auf Striche UND - // Füllungen wirkt (`Drawing2D.opacity`). Nur EIN Bedienfeld — welches - // Feld gesetzt wird, entscheidet die Form. - if (selection?.kind === "drawing2d") - setProject( - opsMutation((p) => - patchItem(p, "drawings2d", selection.id, (d) => - d.geom.shape === "image" ? { ...d, geom: { ...d.geom, opacity } } : { ...d, opacity }, - ), - ), - ); - else if (selection?.kind === "contextObject") - applyChange((p) => - patchItem(p, "context", selection.id, (o) => (o.type === "image" ? { ...o, opacity } : o)), - ); - }, - onSetSelectionImageFilters: (filters) => { - // Nur Kontext-Objekt-Bilder tragen `filters` (s. `ContextImage`) — - // gemergt mit den bestehenden Werten (Teil-Update, ein Slider ändert - // nur SEINEN eigenen Wert). - if (selection?.kind !== "contextObject") return; - applyChange((p) => - patchItem(p, "context", selection.id, (o) => - o.type === "image" ? { ...o, filters: { ...o.filters, ...filters } } : o, - ), - ); - }, - onSetSelectionForeground: (color) => { - // Vordergrund-Override: Wand, Decke oder Drawing2D. - if ( - selection?.kind === "wall" || - selection?.kind === "ceiling" || - selection?.kind === "drawing2d" - ) - setElementForeground(selection.kind, selection.id, color); - }, - onSetSelectionBackground: (color) => { - // Hintergrund-Override: Wand, Decke oder Drawing2D. - if ( - selection?.kind === "wall" || - selection?.kind === "ceiling" || - selection?.kind === "drawing2d" - ) - setElementBackground(selection.kind, selection.id, color); - }, - // Stift-Kopplung von Vordergrund/Hintergrund (s. `Selection. - // foregroundPenId`/`backgroundPenId`-Doku) — dieselben Selektionsarten - // wie `onSetSelectionForeground`/`onSetSelectionBackground` (Wand/Decke/ - // Drawing2D; Stütze trägt zwar dasselbe Feld im Modell, hat aber ebenso - // wie bei `onSetSelectionColorPen` noch KEINEN UI-Schreibpfad — s. - // PENDENZEN.md-Scope-Entscheid). `penId` gesetzt ⇒ sofort aus dem aktiven - // Stiftsatz backen; `undefined` ⇒ nur die Kopplung lösen, letzter - // gebackener Wert bleibt als freier Override stehen. - onSetSelectionForegroundPen: (penId) => { - if (!selection) return; - const foreground = penId ? resolvePenColor(project, penId) : undefined; - const patch = - foreground !== undefined - ? { foregroundPenId: penId, foreground } - : { foregroundPenId: penId }; - if (selection.kind === "wall") updateWall(selection.id, patch); - else if (selection.kind === "ceiling") updateCeiling(selection.id, patch); - else if (selection.kind === "drawing2d") updateDrawing2D(selection.id, patch); - }, - onAddColorToCustomPalette: (paletteId, hex) => addColorToCustomPalette(paletteId, hex), - onSetDashScale: (drawingId, scale) => - setProject(opsMutation((p) => patchItem(p, "drawings2d", drawingId, { dashScale: scale }))), - onDetachDimension: (drawingId) => setProject(cmdMutation({ cmd: "dimdetach", ids: [drawingId] })), - onSetDetailRefLabel: (drawingId, label) => - setProject( - opsMutation((p) => - patchItem(p, "drawings2d", drawingId, (d) => - d.geom.shape === "detailref" ? { ...d, geom: { ...d.geom, label } } : d, - ), - ), - ), - onSetDetailRefSheetLayout: (drawingId, sheetLayoutId) => - setProject( - opsMutation((p) => - patchItem(p, "drawings2d", drawingId, (d) => { - if (d.geom.shape !== "detailref") return d; - const geom = { ...d.geom }; - if (sheetLayoutId) geom.sheetLayoutId = sheetLayoutId; - else delete geom.sheetLayoutId; - return { ...d, geom }; - }), - ), - ), - onSetDetailRefSheetLabel: (drawingId, sheetLabel) => - setProject( - opsMutation((p) => - patchItem(p, "drawings2d", drawingId, (d) => - d.geom.shape === "detailref" ? { ...d, geom: { ...d.geom, sheetLabel } } : d, - ), - ), - ), - onSetHatchPlacement: (drawingId, patch) => - setProject( - opsMutation((p) => - patchItem(p, "drawings2d", drawingId, (d) => { - const next = { ...d }; - // `null` = zurück auf die Ressource (Feld entfernen). - if ("angleDeg" in patch) - patch.angleDeg === null ? delete next.hatchAngleDeg : (next.hatchAngleDeg = patch.angleDeg); - if ("scale" in patch) - patch.scale === null ? delete next.hatchScale : (next.hatchScale = patch.scale); - if ("origin" in patch) - patch.origin === null ? delete next.hatchOrigin : (next.hatchOrigin = patch.origin); - return next; - }), - ), - ), - onSetEndMarks: (drawingId, patch) => - setProject( - opsMutation((p) => - patchItem(p, "drawings2d", drawingId, (d) => ({ ...d, endMarks: { ...d.endMarks, ...patch } })), - ), - ), - onSetGridProps: (drawingId, patch) => - setProject( - opsMutation((p) => - patchItem(p, "drawings2d", drawingId, (d) => { - if (d.geom.shape !== "grid") return d; - const geom = { ...d.geom, ...patch }; - if (patch.levels === undefined && "levels" in patch) delete geom.levels; - return { ...d, geom }; - }), - ), - ), - onSetDimensionStyle: (drawingId, patch) => - setProject( - opsMutation((p) => - patchItem(p, "drawings2d", drawingId, (d) => - d.geom.shape === "dimension" ? { ...d, geom: { ...d.geom, ...patch } } : d, - ), - ), - ), - onSetSelectionBackgroundPen: (penId) => { - if (!selection) return; - const background = penId ? resolvePenColor(project, penId) : undefined; - const patch = - background !== undefined - ? { backgroundPenId: penId, background } - : { backgroundPenId: penId }; - if (selection.kind === "wall") updateWall(selection.id, patch); - else if (selection.kind === "ceiling") updateCeiling(selection.id, patch); - else if (selection.kind === "drawing2d") updateDrawing2D(selection.id, patch); - }, - // ── By-Layer/By-Object-Quellen (Vordergrund/Hintergrund/Strichstärke/ - // Schraffur): "layer" erzwingt die Ebene, "object" erbt vom Bauteil — - // beide löschen dabei den expliziten Wert (siehe Modell-Kommentar - // `AttributeSource`); „eigener Wert" läuft weiterhin über die - // onSetSelection{Foreground,Background,Weight,Fill}-Setter oben. - onSetSelectionForegroundSource: (source) => { - if (!selection) return; - const patch = { - foregroundSource: source === "layer" ? ("layer" as const) : undefined, - foreground: undefined, - }; - if (selection.kind === "wall") updateWall(selection.id, patch); - else if (selection.kind === "ceiling") updateCeiling(selection.id, patch); - else if (selection.kind === "drawing2d") updateDrawing2D(selection.id, patch); - }, - onSetSelectionBackgroundSource: (source) => { - if (!selection) return; - const patch = { - backgroundSource: source === "layer" ? ("layer" as const) : undefined, - background: undefined, - }; - if (selection.kind === "wall") updateWall(selection.id, patch); - else if (selection.kind === "ceiling") updateCeiling(selection.id, patch); - else if (selection.kind === "drawing2d") updateDrawing2D(selection.id, patch); - }, - onSetSelectionStrokeWeightSource: (source) => { - if (!selection) return; - const strokeWeightSource = source === "layer" ? ("layer" as const) : undefined; - if (selection.kind === "wall") - updateWall(selection.id, { strokeWeightSource, strokeWeight: undefined }); - else if (selection.kind === "ceiling") - updateCeiling(selection.id, { strokeWeightSource, strokeWeight: undefined }); - else if (selection.kind === "drawing2d") - updateDrawing2D(selection.id, { strokeWeightSource, weightMm: undefined }); - }, - onSetSelectionHatchSource: (source) => { - if (!selection) return; - const hatchSource = source === "layer" ? ("layer" as const) : undefined; - if (selection.kind === "wall") - updateWall(selection.id, { hatchSource, hatchId: undefined }); - else if (selection.kind === "ceiling") - updateCeiling(selection.id, { hatchSource, hatchId: undefined }); - else if (selection.kind === "drawing2d") - updateDrawing2D(selection.id, { hatchSource, hatchId: undefined }); - }, - onResizeSelection: (w, h, anchor) => { - if (selection?.kind === "wall" || selection?.kind === "drawing2d") - resizeElement(selection.kind, selection.id, w, h, anchor); - }, - onMoveSelectionBy: (dx, dy) => { - if (!selection) return; - if (!isFinite(dx) || !isFinite(dy) || (dx === 0 && dy === 0)) return; - const sel2 = singleTransformSel(selection.kind, selection.id); - if (!sel2) return; - commitTransformOn(sel2, "move", [{ x: 0, y: 0 }, { x: dx, y: dy }], "move", 1); - }, - // Objektinfo-Kopf: Klasse (Grafik-Kategorie) + Zeichnungsebene ändern - // (VW-Muster „Klasse"/„Ebene"). Je Elementart der passende Store-Weg. - onSetSelectionCategory: (code) => { - if (!selection || !code) return; - const id = selection.id; - switch (selection.kind) { - case "wall": updateWall(id, { categoryCode: code }); break; - case "ceiling": updateCeiling(id, { categoryCode: code }); break; - case "roof": updateRoof(id, { categoryCode: code }); break; - case "opening": updateOpening(id, { categoryCode: code }); break; - case "stair": updateStair(id, { categoryCode: code }); break; - case "room": updateRoom(id, { categoryCode: code }); break; - case "drawing2d": updateDrawing2D(id, { categoryCode: code }); break; - case "column": - applyChange((p) => patchItem(p, "columns", id, { categoryCode: code })); - break; - default: break; // extrudedSolid/door: keine Kategorie am Element - } - }, - onSetSelectionLevel: (levelId) => { - if (!selection || !levelId) return; - const id = selection.id; - switch (selection.kind) { - case "wall": updateWall(id, { floorId: levelId }); break; - case "ceiling": updateCeiling(id, { floorId: levelId }); break; - case "roof": updateRoof(id, { floorId: levelId }); break; - case "stair": updateStair(id, { floorId: levelId }); break; - case "room": updateRoom(id, { floorId: levelId }); break; - case "drawing2d": updateDrawing2D(id, { levelId }); break; - case "extrudedSolid": - applyChange((p) => patchItem(p, "extrudedSolids", id, { levelId })); - break; - case "column": - applyChange((p) => patchItem(p, "columns", id, { floorId: levelId })); - break; - default: break; // opening: Ebene kommt aus der Wirts-Wand - } - }, - onRotateSelectionAround: (cx, cy, deg) => { - if (!selection) return; - if (!isFinite(deg) || deg === 0) return; - const sel2 = singleTransformSel(selection.kind, selection.id); - if (!sel2) return; - const rad = (deg * Math.PI) / 180; - commitTransformOn( - sel2, - "rotate", - [ - { x: cx, y: cy }, - { x: cx + 1, y: cy }, - { x: cx + Math.cos(rad), y: cy + Math.sin(rad) }, - ], - "move", - 1, - ); - }, - onSetDrawingLineLength: (length) => { - if (selection?.kind !== "drawing2d" || !isFinite(length) || length <= 0) return; - const d = project.drawings2d.find((x) => x.id === selection.id); - if (!d || d.geom.shape !== "line") return; - const { a, b } = d.geom; - const len = Math.hypot(b.x - a.x, b.y - a.y); - if (len < 1e-9) return; - const ux = (b.x - a.x) / len, uy = (b.y - a.y) / len; - updateDrawing2D(selection.id, { - geom: { ...d.geom, b: { x: a.x + ux * length, y: a.y + uy * length } }, - }); - }, - onSetDrawingLineAngle: (deg) => { - if (selection?.kind !== "drawing2d" || !isFinite(deg)) return; - const d = project.drawings2d.find((x) => x.id === selection.id); - if (!d || d.geom.shape !== "line") return; - const { a, b } = d.geom; - const len = Math.hypot(b.x - a.x, b.y - a.y); - if (len < 1e-9) return; - const rad = (deg * Math.PI) / 180; - updateDrawing2D(selection.id, { - geom: { ...d.geom, b: { x: a.x + Math.cos(rad) * len, y: a.y + Math.sin(rad) * len } }, - }); - }, - onSetDrawingCircleRadius: (radius) => { - if (selection?.kind !== "drawing2d" || !isFinite(radius) || radius <= 0) return; - const d = project.drawings2d.find((x) => x.id === selection.id); - if (!d || d.geom.shape !== "circle") return; - updateDrawing2D(selection.id, { geom: { ...d.geom, r: radius } }); - }, - onSetDrawingTextPaperHeight: (mm) => { - if (selection?.kind !== "drawing2d" || !isFinite(mm) || mm < 0) return; - const d = project.drawings2d.find((x) => x.id === selection.id); - if (!d || d.geom.shape !== "text") return; - const { paperHeight: _old, ...rest } = d.geom; - updateDrawing2D(selection.id, { geom: mm > 0 ? { ...rest, paperHeight: mm } : rest }); - }, - onSetDrawingArcRadius: (radius) => { - if (selection?.kind !== "drawing2d" || !isFinite(radius) || radius <= 0) return; - const d = project.drawings2d.find((x) => x.id === selection.id); - if (!d || d.geom.shape !== "arc") return; - updateDrawing2D(selection.id, { geom: { ...d.geom, r: radius } }); - }, - onSetDrawingArcStartAngle: (deg) => { - if (selection?.kind !== "drawing2d" || !isFinite(deg)) return; - const d = project.drawings2d.find((x) => x.id === selection.id); - if (!d || d.geom.shape !== "arc") return; - updateDrawing2D(selection.id, { geom: { ...d.geom, a0: (deg * Math.PI) / 180 } }); - }, - onSetDrawingArcEndAngle: (deg) => { - if (selection?.kind !== "drawing2d" || !isFinite(deg)) return; - const d = project.drawings2d.find((x) => x.id === selection.id); - if (!d || d.geom.shape !== "arc") return; - updateDrawing2D(selection.id, { geom: { ...d.geom, a1: (deg * Math.PI) / 180 } }); - }, - // ── Wand-Attribute (nur bei selektierter Wand) ───────────────────────── - onSetWallReferenceLine: (ref) => { - if (selection?.kind === "wall") - // Benannte Linie gewählt ⇒ freien Fugen-Versatz löschen (er übersteuert sonst). - updateWall(selection.id, { referenceLine: ref, referenceOffset: undefined }); - }, - onSetWallReferenceOffset: (offset) => { - if (selection?.kind === "wall") - updateWall(selection.id, { referenceOffset: offset ?? undefined }); - }, - onSetSurfacePatternPlacement: (patch) => { - if (selection?.kind === "wall") updateWall(selection.id, patch, "surface-pattern"); - else if (selection?.kind === "roof") updateRoof(selection.id, patch, "surface-pattern"); - }, - onSetWallSliceTermination: (termination) => { - if (selection?.kind === "wall") - // "both" ist der Default ⇒ als undefined speichern (Alt-Projekt-Parität). - updateWall(selection.id, { - sliceTermination: termination === "both" ? undefined : termination, - }); - }, - onSetWallRoofAttach: (attach) => { - if (selection?.kind === "wall") - // "auto" ist der Default ⇒ als undefined speichern. - updateWall(selection.id, { roofAttach: attach === "auto" ? undefined : attach === "on" }); - }, - onSetBuildingFlags: (flags) => { - const patch: { isExternal?: boolean; loadBearing?: boolean } = {}; - if (flags.isExternal !== undefined) patch.isExternal = flags.isExternal || undefined; - if (flags.loadBearing !== undefined) patch.loadBearing = flags.loadBearing || undefined; - if (selection?.kind === "wall") updateWall(selection.id, patch); - else if (selection?.kind === "ceiling") updateCeiling(selection.id, patch); - }, - onSetWallType: (wallTypeId) => { - if (selection?.kind === "wall") - updateWall(selection.id, { wallTypeId }); - }, - onSetWallThickness: (thickness) => { - if (selection?.kind === "wall") - setWallThickness(selection.id, thickness); - }, - onSetWallBottom: (anchor) => { - if (selection?.kind === "wall") - updateWall(selection.id, { bottom: anchor ?? undefined }); - }, - onSetWallTop: (anchor) => { - if (selection?.kind === "wall") - updateWall(selection.id, { top: anchor ?? undefined }); - }, - // ── Decken-Attribute (nur bei selektierter Decke) ────────────────────── - onSetCeilingType: (ceilingTypeId) => { - if (selection?.kind === "ceiling") - updateCeiling(selection.id, { ceilingTypeId, thickness: undefined }); - }, - onSetCeilingThickness: (thickness) => { - if (selection?.kind === "ceiling") - setCeilingThickness(selection.id, thickness); - }, - onRemoveCeilingOpening: (index) => { - if (selection?.kind !== "ceiling") return; - const c = (project.ceilings ?? []).find((x) => x.id === selection.id); - if (!c?.openings || index < 0 || index >= c.openings.length) return; - updateCeiling(selection.id, { - openings: c.openings.filter((_, i) => i !== index), - }); - }, - onSetCeilingTop: (anchor) => { - if (selection?.kind === "ceiling") - updateCeiling(selection.id, { top: anchor ?? undefined }); - }, - onSetCeilingBottom: (anchor) => { - if (selection?.kind === "ceiling") - updateCeiling(selection.id, { bottom: anchor ?? undefined }); - }, - // ── Öffnungs-Attribute (nur bei selektierter Öffnung) ────────────────── - onSetOpeningKind: (kind) => { - if (selection?.kind === "opening") - updateOpening( - selection.id, - kind === "door" - ? { kind, sillHeight: 0, hinge: "start", swing: "left", openingDir: "in", swingAngle: 90 } - : { kind }, - ); - }, - onSetOpeningWidth: (width) => { - if (selection?.kind === "opening" && width > 0) - updateOpening(selection.id, { width }); - }, - onSetOpeningHeight: (height) => { - if (selection?.kind === "opening" && height > 0) - updateOpening(selection.id, { height }); - }, - onSetOpeningSill: (sillHeight) => { - if (selection?.kind === "opening" && sillHeight >= 0) - updateOpening(selection.id, { sillHeight }); - }, - onSetOpeningPosition: (position) => { - if (selection?.kind !== "opening" || !Number.isFinite(position)) return; - // [144] Dach-/Deckenöffnung: Feld frei; Wandöffnung: der Kern klemmt auf [0, Wandlänge − Breite] - // (Bogenwand: Bogenlänge) und hält 5 cm vor der Nachbaröffnung an (mit Hinweis). - if (selection.opening?.wallLength == null) updateOpening(selection.id, { position: Math.max(0, position) }); - else slideOpening(selection.id, { position }); - }, - onSetOpeningSwingAngle: (swingAngle) => { - if (selection?.kind === "opening" && swingAngle > 0) - updateOpening(selection.id, { swingAngle }); - }, - onSetOpeningHinge: (hinge) => { - if (selection?.kind === "opening") updateOpening(selection.id, { hinge }); - }, - onSetOpeningSwing: (swing) => { - if (selection?.kind === "opening") updateOpening(selection.id, { swing }); - }, - onSetOpeningDir: (openingDir) => { - if (selection?.kind === "opening") updateOpening(selection.id, { openingDir }); - }, - onSetOpeningWingCount: (wingCount) => { - if (selection?.kind === "opening") - updateOpening(selection.id, { wingCount: Math.max(1, Math.min(4, Math.round(wingCount))) }); - }, - onSetOpeningDoorType: (doorType) => { - if (selection?.kind === "opening") updateOpening(selection.id, { doorType }); - }, - onSetOpeningLintelLines: (lintelLines) => { - if (selection?.kind === "opening") updateOpening(selection.id, { lintelLines }); - }, - onSetOpeningHost: (patch) => { - if (selection?.kind === "opening") updateOpening(selection.id, patch); - }, - onSetOpeningDetailLevel: (detailLevel) => { - if (selection?.kind === "opening") updateOpening(selection.id, { detailLevel }); - }, - onSetOpeningFrameLine: (v) => { - if (selection?.kind === "opening") updateOpening(selection.id, { frameLine: v }); - }, - onSetOpeningFrameViewLine: (v) => { - if (selection?.kind === "opening") updateOpening(selection.id, { frameViewLine: v }); - }, - onSetOpeningSashLine: (v) => { - if (selection?.kind === "opening") updateOpening(selection.id, { sashLine: v }); - }, - onSetOpeningSillLineStyle: (v) => { - if (selection?.kind === "opening") updateOpening(selection.id, { sillLineStyle: v }); - }, - // Typ-Zuweisung (Bibliothek): Tür-/Fenstertyp per typeId; leerer String löst - // die Zuweisung wieder (Inline-Verhalten). - onSetOpeningType: (typeId) => { - if (selection?.kind === "opening") - updateOpening(selection.id, { typeId: typeId || undefined }); - }, - onEditOpeningType: (kind) => { - openResources(kind === "door" ? "doorStyles" : "windowStyles"); - }, - onOpenOpeningEditor: (id) => setOpeningEditorId(id), - // ── Dach-Attribute (nur bei selektiertem Dach) ───────────────────────── - onSetRoofPatch: (patch, coalesceKey) => { - if (selection?.kind === "roof") updateRoof(selection.id, patch, coalesceKey); - }, - onSetRoofEdge: (index, spec) => { - if (selection?.kind !== "roof") return; - const r = (project.roofs ?? []).find((x) => x.id === selection.id); - if (!r) return; - // Zahl tippen: gleicher Schlüssel je Kante ⇒ ein Undo-Schritt; Giebel-Schalter einzeln. - updateRoof(selection.id, setRoofEdge(r, index, spec), spec.kind === "pitch" ? `roof-edge-${selection.id}-${index}` : undefined); - }, - onRemoveRoofHole: (k) => { - if (selection?.kind !== "roof") return; - const r = (project.roofs ?? []).find((x) => x.id === selection.id); - if (r) updateRoof(selection.id, removeRoofHole(r, k)); - }, - // ── Schnitt-/Ansichtslinie (nur bei selektierter Linie) ──────────────── - sectionLine, - onSetSectionLinePatch: (patch) => { - if (sectionLine) patchLevel(sectionLine.id, patch); - }, - onDeleteSectionLine: () => { - if (sectionLine) patchLevel(sectionLine.id, { linePoints: undefined }); - }, - // 3D-Live-Schnitt an die gewählte Schnittlinie binden (Toggle im Objekt-Info). - section3dCutActive: section3dCutId != null && section3dCutId === sectionLine?.id, - onToggleSection3dCut, - // ── Treppen-Attribute (nur bei selektierter Treppe) ──────────────────── - onSetStairShape: (shape) => { - if (selection?.kind === "stair") updateStair(selection.id, { shape }); - }, - onSetStairWidth: (width) => { - if (selection?.kind === "stair" && width > 0) - updateStair(selection.id, { width }); - }, - onSetStairSteps: (stepCount) => { - if (selection?.kind === "stair" && stepCount >= 2) - updateStair(selection.id, { stepCount: Math.round(stepCount) }); - }, - onSetStairRise: (totalRise) => { - if (selection?.kind === "stair" && totalRise > 0) - updateStair(selection.id, { totalRise }); - }, - onSetStairUp: (up) => { - if (selection?.kind === "stair") updateStair(selection.id, { up }); - }, - onSetStairArrowStyle: (arrowStyle) => { - if (selection?.kind === "stair") updateStair(selection.id, { arrowStyle }); - }, - onSetStairColumn: (radius) => { - if (selection?.kind === "stair") - updateStair(selection.id, { centerColumn: radius > 0 ? radius : undefined }); - }, - onSetStairReferenz: (referenz) => { - if (selection?.kind === "stair") updateStair(selection.id, { referenz }); - }, - onSetStairPatch: (patch) => { - if (selection?.kind === "stair") updateStair(selection.id, patch); - }, - // Typ-Zuweisung (Bibliothek): Treppentyp per typeId; leerer String löst die - // Zuweisung (Inline-Verhalten). Treibt u. a. die 3D-Tragart (massiv/offen). - onSetStairType: (typeId) => { - if (selection?.kind === "stair") - updateStair(selection.id, { typeId: typeId || undefined }); - }, - // ── Raum-Attribute (nur bei selektiertem Raum) ───────────────────────── - onSetRoomName: (name) => { - if (selection?.kind === "room") updateRoom(selection.id, { name }); - }, - onSetRoomSia: (category) => { - if (selection?.kind === "room") updateRoom(selection.id, { siaCategory: category }); - }, - onEditRoomStamp: (roomId) => onOpenStampEditor(roomId), - // ── Extrusions-Attribute (truck-Integration; nur bei selektiertem Körper) ── - onSetExtrudedSolidHeight: (height) => { - if (selection?.kind !== "extrudedSolid" || !(height > 0)) return; - const id = selection.id; - applyChange((p) => patchItem(p, "extrudedSolids", id, { height })); - }, - onSetExtrudedSolidTaper: (taper) => { - if (selection?.kind !== "extrudedSolid") return; - const clamped = Math.min(1, Math.max(0, taper)); - const id = selection.id; - applyChange((p) => patchItem(p, "extrudedSolids", id, { taper: clamped })); - }, - onSetExtrudedSolidCornerRadius: (radius) => { - if (selection?.kind !== "extrudedSolid") return; - const r = Math.max(0, radius); - const id = selection.id; - applyChange((p) => patchItem(p, "extrudedSolids", id, { cornerRadius: r > 0 ? r : undefined })); - }, - onSetExtrudedSolidChamfer: (chamfer) => { - if (selection?.kind !== "extrudedSolid") return; - const c = Math.max(0, chamfer); - const id = selection.id; - applyChange((p) => patchItem(p, "extrudedSolids", id, { chamfer: c > 0 ? c : undefined })); - }, - onSetExtrudedSolidSubtract: (subtract) => { - if (selection?.kind !== "extrudedSolid") return; - const id = selection.id; - applyChange((p) => patchItem(p, "extrudedSolids", id, { operation: subtract ? ("subtract" as const) : undefined })); - }, - onSetExtrudedSolidBaseOffset: (offset) => { - if (selection?.kind !== "extrudedSolid" || !Number.isFinite(offset)) return; - const id = selection.id; - applyChange((p) => patchItem(p, "extrudedSolids", id, { baseOffset: Math.abs(offset) > 1e-9 ? offset : undefined })); - }, - // ── Stützen-Attribute (Tragwerk; nur bei selektierter Stütze) ────────── - onSetColumnProfileKind: (kind) => { - if (selection?.kind !== "column") return; - const id = selection.id; - applyChange((p) => - patchItem(p, "columns", id, (c) => { - if (kind === c.profile.kind) return c; - // Profil-Typ wechseln: sinnvolles Mass aus dem bisherigen ableiten. - if (kind === "round") { - const r = - c.profile.kind === "rect" - ? Math.max(c.profile.width, c.profile.depth) / 2 - : c.profile.radius; - return { ...c, profile: { kind: "round" as const, radius: r } }; - } - const side = c.profile.kind === "round" ? c.profile.radius * 2 : 0.3; - return { ...c, profile: { kind: "rect" as const, width: side, depth: side } }; - }), - ); - }, - onSetColumnWidth: (width) => { - if (selection?.kind !== "column" || !(width > 0)) return; - const id = selection.id; - applyChange((p) => - patchItem(p, "columns", id, (c) => - c.profile.kind === "rect" ? { ...c, profile: { ...c.profile, width } } : c, - ), - ); - }, - onSetColumnDepth: (depth) => { - if (selection?.kind !== "column" || !(depth > 0)) return; - const id = selection.id; - applyChange((p) => - patchItem(p, "columns", id, (c) => - c.profile.kind === "rect" ? { ...c, profile: { ...c.profile, depth } } : c, - ), - ); - }, - onSetColumnRadius: (radius) => { - if (selection?.kind !== "column" || !(radius > 0)) return; - const id = selection.id; - applyChange((p) => - patchItem(p, "columns", id, (c) => - c.profile.kind === "round" ? { ...c, profile: { ...c.profile, radius } } : c, - ), - ); - }, - onSetColumnHeight: (height) => { - if (selection?.kind !== "column" || !(height > 0)) return; - const id = selection.id; - applyChange((p) => patchItem(p, "columns", id, { height })); - }, - onSetColumnRotation: (deg) => { - if (selection?.kind !== "column" || !Number.isFinite(deg)) return; - const id = selection.id; - const rotation = (deg * Math.PI) / 180; - applyChange((p) => patchItem(p, "columns", id, { rotation })); - }, - // ── Site-/Kontext-Schicht ────────────────────────────────────────────── - contextObjects: project.context ?? [], - onAddContextObjects: addContextObjectsAndFit, - onRemoveContextObject: removeContextObject, - onRemoveContextObjects: removeContextObjects, - onGenerateTerrain: generateTerrain, - onPatchContextObject: patchContextObject, - onStartExcavation: () => onRunCommand("excavation"), - onSetGeoAnchor: (anchor) => { - applyChange((p) => setFieldIfChanged(p, "geoAnchor", anchor)); - }, - onImportDxf: () => dxfInputRef.current?.click(), - onStartGeoref: () => onRunCommand("georef"), - // ── Element-Baum (Elemente-Panel) ──────────────────────────────────── - onSelectScheduleRow: ( - kind: ScheduleKind, - id: string, - floorId: string | undefined, - opts?: { zoom?: boolean }, - ) => { - const applySelection = () => { - const kindOf: Partial> = { - Wand: "walls", - Decke: "ceilings", - Fenster: "openings", - Öffnung: "openings", - Treppe: "stairs", - Extrusion: "solids", - Dach: "roofs", - Stütze: "columns", - }; - const k = kindOf[kind]; - setSelection({ ...clearKinds(), ...(k ? { [k]: [id] } : {}) }); - // z. B. Legacy-„Tür"-Datensätze (project.doors) — kein Auswahl-Kanal. - if (!k) return; - if (opts?.zoom) requestAnimationFrame(() => planViewRef.current?.fit()); - }; - if (floorId && floorId !== activeLevelId) { - // Der Geschosswechsel-Effekt (oben, deps [activeLevelId]) leert die - // Auswahl NACH diesem Render — die neue Auswahl daher einen Tick - // später anwenden, sonst überschreibt der Effekt sie sofort wieder. - setActiveLevelId(floorId); - requestAnimationFrame(applySelection); - } else { - applySelection(); - } - }, - - // ── Ausschnitte / View-Snapshots (DOSSIER A2) und Reiter ([136]) ────── - // Ausschnitte leben im Projekt (Panel „Ausschnitte"), Reiter sind reiner UI-Zustand - // (state/viewTabs.ts). Klick im Panel zeigt den Ausschnitt im aktiven Reiter, Doppelklick/Knopf - // öffnet ihn in einem neuen; Reiter schliessen löscht keinen Ausschnitt; „Aktualisieren" schreibt - // die aktuelle Ansicht ausdrücklich in den Ausschnitt zurück. - onCaptureViewSnapshot: (name: string, folderId?: string): string => { - const trimmed = name.trim(); - if (!trimmed) return ""; - const snap = captureViewSnapshot(`vs-${Date.now()}`, trimmed, liveViewState()); - // Neuer Ausschnitt landet im aktiven Ordner (falls das Panel einen - // mitgibt), sonst auf der Wurzelebene — additiv (folderId optional). - const full = folderId ? { ...snap, folderId } : snap; - applyChange(addItems("viewSnapshots", [full])); - // Der aktive Reiter zeigt jetzt diesen Ausschnitt (Titel), der Ausschnitt ist im Panel gewählt. - setViewTabs(linkActiveTab(getViewTabs(), full.id)); - setSelectedViewSnapshotId(full.id); - return full.id; - }, - - // Titel eines Reiters ohne Ausschnitt: aktive Zeichnungskombination (falls deren - // Sichtbarkeits-Map exakt passt), sonst die Zeichnungsebene des Reiters. - viewTabAutoName: (levelId?: string): string => { - if (!levelId || levelId === activeLevelId) { - const combo = matchingComboName(listDrawingCombos(), loadDrawingCombo, snapshotDrawingVisibility()); - if (combo) return combo; - } - const id = levelId ?? activeLevelId; - return project.drawingLevels.find((l) => l.id === id)?.name ?? id; - }, - - // Klick im Panel: Ausschnitt im AKTIVEN Reiter anzeigen und im Panel wählen. - onApplyViewSnapshot: (id: string) => { - // Aktuellen Stand lesen (direkt nach einer Änderung am Ausschnitt ist `project` hier noch der alte). - const snap = (getState().project.viewSnapshots ?? []).find((s) => s.id === id); - if (!snap) return; - // Für einen folgenden Doppelklick merken, was der aktive Reiter vorher zeigte. - lastPanelClick = { id, at: Date.now(), tabs: storeActiveState(getViewTabs(), liveViewState()) }; - applyViewState(readViewSnapshot(snap)); - setViewTabs(linkActiveTab(getViewTabs(), id)); - setSelectedViewSnapshotId(id); - }, - - // Doppelklick/Knopf im Panel: Ausschnitt in einem NEUEN Reiter öffnen. - onOpenViewSnapshotInNewTab: (id: string) => { - const snap = (getState().project.viewSnapshots ?? []).find((s) => s.id === id); - if (!snap) return; - // Doppelklick: die beiden vorangehenden Klicks haben den Ausschnitt schon im aktiven Reiter gezeigt — - // dieser behält seinen früheren Inhalt, nur der neue Reiter zeigt den Ausschnitt. - const prev = lastPanelClick; - lastPanelClick = null; - const base = prev && prev.id === id && Date.now() - prev.at < 1000 ? prev.tabs : undefined; - const cur = getViewTabs(); - setViewTabs( - base && base.activeId === cur.activeId - ? openTab({ ...cur, tabs: cur.tabs.map((tb) => (tb.id === cur.activeId ? activeTab(base) : tb)) }, { snapshotId: id }) - : openTab(cur, { snapshotId: id }, liveViewState()), - ); - applyViewState(readViewSnapshot(snap)); - setSelectedViewSnapshotId(id); - }, - - // Ausdrücklich: aktuelle Ansicht in den Ausschnitt schreiben (Name, Ordner, Vorlage bleiben). - onUpdateViewSnapshot: (id: string) => { - const live = liveViewState(); - applyChange((p) => - patchItem(p, "viewSnapshots", id, (v) => { - const fresh = captureViewSnapshot(v.id, v.name, live); - const { cameraCenter: _c, cameraPxPerMeter: _m, ...rest } = v; - return { ...rest, ...fresh }; - }), - ); - }, - - // Reiterleiste. - onActivateViewTab: (tabId: string) => { - const { next, apply } = activateTab(getViewTabs(), tabId, liveViewState()); - setViewTabs(next); - if (apply) applyViewState(apply); - const snapId = next.tabs.find((tb) => tb.id === next.activeId)?.snapshotId; - if (snapId) setSelectedViewSnapshotId(snapId); - }, - onNewViewTab: () => { - setViewTabs(openTab(getViewTabs(), {}, liveViewState())); - }, - onCloseViewTab: (tabId: string) => { - const { next, apply } = closeTab(getViewTabs(), tabId); - setViewTabs(next); - if (apply) applyViewState(apply); - }, - - onRenameViewSnapshot: (id: string, name: string) => { - const trimmed = name.trim(); - if (!trimmed) return; - applyChange((p) => patchItem(p, "viewSnapshots", id, { name: trimmed })); - }, - - onDuplicateViewSnapshot: (id: string) => { - // [40] Kopie gleich hinter dem Original, gleicher Ordner, „… Kopie"; danach angewählt. - const list = project.viewSnapshots ?? []; - const i = list.findIndex((v) => v.id === id); - if (i < 0) return; - const copy = { ...list[i], id: `vs-${Date.now()}`, name: t("viewsnap.copyName", { name: list[i].name }) }; - applyChange(() => addItems("viewSnapshots", [copy], i + 1)); - setSelectedViewSnapshotId(copy.id); - }, - - // Löschen nur im Panel. Offene Reiter des Ausschnitts bleiben (eigener Zustand, letzter Name als Titel). - onDeleteViewSnapshot: (id: string) => { - const snap = (getState().project.viewSnapshots ?? []).find((s) => s.id === id); - applyChange((p) => removeItems(p, "viewSnapshots", [id])); - if (snap) setViewTabs(detachSnapshots(getViewTabs(), [{ id, name: snap.name }])); - if (selectedViewSnapshotId === id) setSelectedViewSnapshotId(null); - }, - - // ── Ausschnitte-Baum (Ordner, DOSSIER A2) ───────────────────────────── - // Immutable CRUD über pure Helfer (state/viewSnapshotFolders.ts). Löschen - // zieht Inhalt auf die Elternebene hoch (kein Datenverlust). - onAddViewSnapshotFolder: (parentId) => { - const id = `vsf-${Date.now()}`; - const folder = createViewSnapshotFolder( - id, - t("viewsnap.folder.defaultName"), - parentId, - ); - applyChange(addItems("viewSnapshotFolders", [folder])); - return id; - }, - onRenameViewSnapshotFolder: (id, name) => { - const trimmed = name.trim(); - if (!trimmed) return; - applyChange((p) => patchItem(p, "viewSnapshotFolders", id, { name: trimmed })); - }, - onDeleteViewSnapshotFolder: (id) => { - applyChange((p) => { - const { folders, snapshots } = deleteViewSnapshotFolder( - id, - p.viewSnapshotFolders ?? [], - p.viewSnapshots ?? [], - ); - return [...fieldOps(p, "viewSnapshotFolders", folders), ...fieldOps(p, "viewSnapshots", snapshots)]; - }); - }, - onMoveViewSnapshotToFolder: (snapshotId, folderId) => { - applyChange((p) => fieldOps(p, "viewSnapshots", moveSnapshotToFolder(p.viewSnapshots ?? [], snapshotId, folderId))); - }, - onMoveViewSnapshotFolder: (folderId, parentId) => { - applyChange((p) => - fieldOps(p, "viewSnapshotFolders", moveViewSnapshotFolder(p.viewSnapshotFolders ?? [], folderId, parentId)), - ); - }, - - // Footer-Bar des Ausschnitte-Panels: die aktuell „angewählte" Id plus - // Lesezugriff auf die benannten Sichtbarkeits-Kombinationen (localStorage), - // damit der Footer den Kombi-NAMEN zu den gespeicherten Maps auflösen kann. - selectedViewSnapshotId, - listLayerCombos, - loadLayerCombo, - listDrawingCombos, - loadDrawingCombo, - - // ── Layouts / Masterlayouts (DOSSIER A3) ────────────────────────────── - // Immutable CRUD über pure Helfer (panels/layoutModel.ts); das Blatt öffnet - // als erstklassige Ansicht IM HAUPT-Viewport (activeLayoutId, Phase 2b). - // Anlegen öffnet es direkt; Löschen schliesst es, falls es das offene trifft. - onAddLayout: (name, paper, orientation) => { - const lay = createLayout(`lay-${Date.now()}`, name, paper, orientation); - // Jedes Blatt trägt seine Blatt-Ebene (2D-Zeichnung auf dem Blatt, s. layoutModel). - applyChange([...addItems("layouts", [lay]), ...addItems("drawingLevels", [createSheetLevel(`sheet-${lay.id}`, lay)])]); - setActiveLayoutId(lay.id); - }, - onRenameLayout: (id, name) => { - applyChange((p) => patchItem(p, "layouts", id, { name })); - }, - onDeleteLayout: (id) => { - // Mit dem Layout gehen seine Blatt-Ebene und deren Zeichnungen (ein Undo-Schritt). - applyChange((p) => { - const levels = p.drawingLevels.filter((l) => l.layoutId === id).map((l) => l.id); - const drawings = p.drawings2d.filter((d) => levels.includes(d.levelId)).map((d) => d.id); - return [ - ...removeItems(p, "drawings2d", drawings), - ...removeItems(p, "drawingLevels", levels), - ...removeItems(p, "layouts", [id]), - ]; - }); - setActiveLayoutId((cur) => (cur === id ? null : cur)); - }, - onOpenLayout: (id) => setActiveLayoutId(id), - onAddMasterLayout: (name) => { - const m = createMasterLayout(`mas-${Date.now()}`, name, "a4", "portrait"); - applyChange(addItems("masterLayouts", [m])); - }, - onRenameMasterLayout: (id, name) => { - applyChange((p) => patchItem(p, "masterLayouts", id, { name })); - }, - onDeleteMasterLayout: (id) => { - // Master löschen UND Bindungen der Layouts lösen (masterId → undefined). - applyChange((p) => [ - ...removeItems(p, "masterLayouts", [id]), - ...patchItems(p, "layouts", (l) => l.masterId === id, (l) => ({ ...l, masterId: undefined })), - ]); - }, - onPatchMasterLayout: (id, patch) => { - applyChange((p) => patchItem(p, "masterLayouts", id, patch)); - }, - - // ── Layouts-Baum (Ordner) + Erstell-Dialoge (DOSSIER A3) ──────────── - onAddLayoutFolder: (parentId) => { - const id = `folder-${Date.now()}`; - const folder = createLayoutFolder(id, t("layouts.folder.defaultName"), parentId); - applyChange(addItems("layoutFolders", [folder])); - return id; - }, - onAddMasterFolder: (parentId) => { - const id = `mfolder-${Date.now()}`; - const folder = createLayoutFolder( - id, - t("layouts.folder.defaultName"), - parentId, - "master", - ); - applyChange(addItems("layoutFolders", [folder])); - return id; - }, - onDeleteMasterFolder: (id) => { - applyChange((p) => { - const { folders, masters } = deleteMasterFolder( - id, - p.layoutFolders ?? [], - p.masterLayouts ?? [], - ); - return [...fieldOps(p, "layoutFolders", folders), ...fieldOps(p, "masterLayouts", masters)]; - }); - }, - onRenameLayoutFolder: (id, name) => { - applyChange((p) => patchItem(p, "layoutFolders", id, { name })); - }, - onDeleteLayoutFolder: (id) => { - applyChange((p) => { - const { folders, layouts } = deleteLayoutFolder( - id, - p.layoutFolders ?? [], - p.layouts ?? [], - ); - return [...fieldOps(p, "layoutFolders", folders), ...fieldOps(p, "layouts", layouts)]; - }); - }, - onCreateLayout: (opts) => { - const id = `lay-${Date.now()}`; - // Bei gebundenem Master erbt das Blatt dessen Papier/Ausrichtung/Grösse. - const master = opts.masterId - ? (project.masterLayouts ?? []).find((m) => m.id === opts.masterId) - : undefined; - const paper = master?.paper ?? opts.paper; - const orientation = master?.orientation ?? opts.orientation; - const customWidthMm = master ? master.customWidthMm : opts.customWidthMm; - const customHeightMm = master ? master.customHeightMm : opts.customHeightMm; - const lay = createLayout(id, t("layouts.defaultName"), paper, orientation); - const full = { - ...lay, - ...(opts.masterId ? { masterId: opts.masterId } : {}), - ...(opts.folderId ? { folderId: opts.folderId } : {}), - ...(customWidthMm !== undefined && customHeightMm !== undefined - ? { customWidthMm, customHeightMm } - : {}), - }; - applyChange([...addItems("layouts", [full]), ...addItems("drawingLevels", [createSheetLevel(`sheet-${id}`, full)])]); - return id; - }, - onCreateMasterLayout: (opts) => { - const id = `mas-${Date.now()}`; - const custom = - opts.customWidthMm !== undefined && opts.customHeightMm !== undefined - ? { widthMm: opts.customWidthMm, heightMm: opts.customHeightMm } - : undefined; - const m = createMasterLayout( - id, - t("layouts.defaultMasterName"), - opts.paper, - opts.orientation, - custom, - ); - const full = opts.folderId ? { ...m, folderId: opts.folderId } : m; - applyChange(addItems("masterLayouts", [full])); - return id; - }, - onExportFolderPdf: (folderId) => { - const folder = (project.layoutFolders ?? []).find((f) => f.id === folderId); - const name = folder?.name?.trim() || "layouts"; - void folderPdfBytes(project, folderId).then((bytes) => { - if (bytes) return saveBinaryFile(bytes, `${name}.pdf`, "application/pdf"); - }); - }, - onMoveLayoutToFolder: (layoutId, folderId) => { - applyChange((p) => fieldOps(p, "layouts", moveLayoutToFolder(p.layouts ?? [], layoutId, folderId))); - }, - onMoveFolderToFolder: (folderId, parentId) => { - applyChange((p) => - fieldOps(p, "layoutFolders", moveFolderToFolder(p.layoutFolders ?? [], folderId, parentId)), - ); - }, - onAddPublishSet: () => { - const id = `pubset-${Date.now()}`; - applyChange((p) => addPublishSetOps(p, id)); - return id; - }, - onPatchPublishSet: (id, patch) => applyChange((p) => patchPublishSetOps(p, id, patch), `pubset-${id}`), - onSetProjectNumber: (value) => applyChange((p) => fieldOps(p, "projectNumber", value.trim() ? value : undefined), "projectNumber"), - onDeletePublishSet: (id) => applyChange((p) => deletePublishSetOps(p, id)), - onPublishSet: (id) => { - void publishSet(project, id).then((ops) => { - if (ops && ops.length > 0) applyChange(ops); - }); - }, + ...buildSelectionStyleHost(c), + ...buildElementAttributesHost(c), + ...buildSiteHost(c), + ...buildViewSnapshotsHost(c, view), + ...buildLayoutsHost(c), }; - return value; - // setProject-Closures sind stabil genug; Neuberechnung bei project/active. + // Die Handler-Bündel (Projekt-Aktionen, Setter) sind stabil genug; neu gebaut wird bei + // Projekt, Auswahl und den Wert-Feldern. // eslint-disable-next-line react-hooks/exhaustive-deps }, [ project, activeLevelId, activeCategoryCode, activeTool, - engineView.commandName, + commandName, activeWallTypeId, snap, viewType, @@ -1561,5 +82,5 @@ export function usePanelHostBase(opts: { selectedViewSnapshotId, ]); - return baseHost; + return useStableHost(baseHost); } diff --git a/src/state/useSectionLineState.ts b/src/state/useSectionLineState.ts index ac71ec5b..597dbafc 100644 --- a/src/state/useSectionLineState.ts +++ b/src/state/useSectionLineState.ts @@ -6,7 +6,7 @@ import { useCallback, useEffect, useMemo } from "react"; import type { DrawingLevel, Project, ViewType } from "../model/types"; import { sectionPlaneFromLevel } from "../core"; -import { deriveSelection } from "./selectionInfo"; +import { selectionInfoFor } from "./useSelectionInfo"; import type { SelectionInfo } from "./selectionInfo"; import type { useSelectionState } from "./useSelectionState"; @@ -24,9 +24,10 @@ export function useSectionLineState(opts: { const { project, selection, activeLevel, viewType, selectedSectionLineId, section3dCutId, setSection3dCutId } = opts; // ── Selektions-Attribut-Kontrakt (Attributes-/Object-Info-Paletten) ─────── - // Normalisierte, effektiv aufgelöste Sicht auf das erste selektierte Element. + // Normalisierte, effektiv aufgelöste Sicht auf das erste selektierte Element (gemeinsamer Cache mit + // `useSelectionInfo` der Panels, inhaltlich stabil). const selectionInfo = useMemo( - (): SelectionInfo | null => deriveSelection(project, selection), + (): SelectionInfo | null => selectionInfoFor(project, selection), [project, selection], ); diff --git a/src/state/useSelectionInfo.ts b/src/state/useSelectionInfo.ts new file mode 100644 index 00000000..2cffd82f --- /dev/null +++ b/src/state/useSelectionInfo.ts @@ -0,0 +1,30 @@ +// Objekt-Info der Auswahl als feines Store-Abo ([121]). Panels (Objekt-Info, Attribute, Baurecht) +// lesen die abgeleitete `SelectionInfo` hier statt über den Panel-Host: so rendern sie nur, wenn +// sich die Info selbst ändert, nicht bei jeder Op am Projekt. +// +// `selectionInfoFor` merkt sich das letzte Paar (Projekt, Auswahl) und rechnet nur bei neuem Paar +// (eine Kern-Abfrage). Ist das Ergebnis inhaltlich gleich wie das vorige (Strukturvergleich), +// bleibt das alte Objekt — Leser mit Referenzvergleich rendern dann nicht. `App.tsx` +// (`useSectionLineState`) nutzt denselben Cache, die Info wird je Änderung nur einmal gerechnet. + +import type { Project } from "../model/types"; +import { useStore } from "./appStore"; +import { dataEqual } from "./dataEqual"; +import type { Selection } from "./selection"; +import { deriveSelection, type SelectionInfo } from "./selectionInfo"; + +let last: { project: Project; selection: Partial; info: SelectionInfo | null } | null = null; + +/** Objekt-Info für (Projekt, Auswahl), zwischengespeichert und inhaltlich stabil (s. Kopf). */ +export function selectionInfoFor(project: Project, selection: Partial): SelectionInfo | null { + if (last && last.project === project && last.selection === selection) return last.info; + const info = deriveSelection(project, selection); + const kept = last && dataEqual(last.info, info) ? last.info : info; + last = { project, selection, info: kept }; + return kept; +} + +/** Objekt-Info der aktuellen Auswahl; rendert nur neu, wenn sie sich inhaltlich ändert. */ +export function useSelectionInfo(): SelectionInfo | null { + return useStore((s) => selectionInfoFor(s.project, s.selection)); +} diff --git a/src/ui/HiddenFileInputs.tsx b/src/ui/HiddenFileInputs.tsx index c33d20c3..e623e129 100644 --- a/src/ui/HiddenFileInputs.tsx +++ b/src/ui/HiddenFileInputs.tsx @@ -1,16 +1,17 @@ // Versteckte Datei-Felder der App ([163], aus App.tsx herausgelöst): DXF/DWG/IFC/PDF, STEP, IFC, // Bild/PDF, Projektdatei und Vorlage, dazu die Hosts für Punktwolken- und Mesh-Import. Menüs, Befehle // und Werkzeuge öffnen den Dateidialog über die Refs (`ref.current.click()`); die gewählte Datei geht -// an den jeweiligen Handler. Gerendert von `App.tsx` ganz oben im Editor. +// an den jeweiligen Handler. Gerendert von `App.tsx` ganz oben im Editor; memoisiert ([121]), die +// Handler kommen mit stabiler Identität aus dem Handler-Bündel der App. -import type { RefObject } from "react"; +import { memo, type RefObject } from "react"; import { PROJECT_TEMPLATE_EXT } from "../native/projectFile"; import type { MeshPlacement, MeshRead } from "../io/meshImport"; import { MeshImportHost } from "./MeshImportDialog"; import { PointCloudImportHost } from "./PointCloudImportDialog"; import type { NotifyKind } from "../state/notifySlice"; -export function HiddenFileInputs(props: { +export const HiddenFileInputs = memo(function HiddenFileInputs(props: { dxfInputRef: RefObject; stepInputRef: RefObject; ifcInputRef: RefObject; @@ -123,4 +124,4 @@ export function HiddenFileInputs(props: { /> ); -} +}); diff --git a/src/ui/PresentationDialog.tsx b/src/ui/PresentationDialog.tsx index b09a3330..4e929d46 100644 --- a/src/ui/PresentationDialog.tsx +++ b/src/ui/PresentationDialog.tsx @@ -3,7 +3,7 @@ // Layouts-Panel ihn öffnen. Beim Bestätigen entsteht das Blatt in EINEM Undo-Schritt // (`state/presentationSheet.ts`); `onCreated` öffnet es. Overlay wie `LayoutCreateDialogs` (kein window.prompt). -import { useCallback, useEffect, useState } from "react"; +import { memo, useCallback, useEffect, useState } from "react"; import { t } from "../i18n"; import { presentationDefaults, type PresentationOptions } from "../core"; import type { LayoutOrientation, LayoutPaperFormat } from "../model/types"; @@ -12,9 +12,14 @@ import { getState, useStore } from "../state/appStore"; import { setPresentationDialogOpener } from "../state/presentationSheetHook"; import { createPresentationSheet } from "../state/presentationSheet"; -export function PresentationDialogHost({ onCreated }: { onCreated: (layoutId: string) => void }) { +/** Memoisiert und nur auf die Zeichnungsebenen abonniert ([121]): rendert nicht bei jeder Op. */ +export const PresentationDialogHost = memo(function PresentationDialogHost({ + onCreated, +}: { + onCreated: (layoutId: string) => void; +}) { const [opts, setOpts] = useState(null); - const project = useStore((s) => s.project); + const drawingLevels = useStore((s) => s.project.drawingLevels); useEffect(() => { setPresentationDialogOpener(() => setOpts(presentationDefaults(getState().project))); @@ -42,9 +47,9 @@ export function PresentationDialogHost({ onCreated }: { onCreated: (layoutId: st }, [opts, close, confirm]); if (!opts) return null; - const floors = project.drawingLevels.filter((l) => l.kind === "floor" && !l.layoutId); - const sections = project.drawingLevels.filter((l) => l.kind === "section"); - const hasElevations = project.drawingLevels.some((l) => l.kind === "elevation"); + const floors = drawingLevels.filter((l) => l.kind === "floor" && !l.layoutId); + const sections = drawingLevels.filter((l) => l.kind === "section"); + const hasElevations = drawingLevels.some((l) => l.kind === "elevation"); const set = (patch: Partial) => setOpts({ ...opts, ...patch }); const toggleFloor = (id: string, on: boolean) => // Blattreihenfolge = Reihenfolge der Geschosse im Projekt. @@ -162,4 +167,4 @@ export function PresentationDialogHost({ onCreated }: { onCreated: (layoutId: st
); -} +}); diff --git a/src/views/viewportContent.tsx b/src/views/viewportContent.tsx index 5351cc7c..1056c86e 100644 --- a/src/views/viewportContent.tsx +++ b/src/views/viewportContent.tsx @@ -351,7 +351,7 @@ export const Content = memo(function Content({ if ((level.kind === "section" || level.kind === "elevation") && viewType === "perspektive") { return (
- + {view3dPane}
); @@ -360,7 +360,7 @@ export const Content = memo(function Content({ if (level.kind === "section" || level.kind === "elevation") { return (
- + - + {plan()}
); @@ -494,7 +494,7 @@ export const Content = memo(function Content({ // Geschoss im Panel „Zeichnungsebenen"), nicht mehr hier in der Kopfzeile. return (
- + {viewType === "perspektive" ? ( view3dPane ) : (