[163] App.tsx zerlegt (2957 → 1121 Zeilen), ohne Verhaltensänderung: Werkzeug-Eingabe, Auswahl-Befehle, Griff-Eingaben, Befehlszeile/HUD, Modell-Importe, Text-Ziel, Schnittlinien, Status-Leiste, Ressourcen, Einstellungen, native Fenster und Menü als Hooks in src/state/; Kontextmenü, Dock-Bereich, Dialoge, versteckte Datei-Felder, Boot-Bildschirm und Kopfzeilen-Elemente als eigene Dateien; Doku (ARCHITEKTUR.md, READMEs) und TODO [121] nachgeführt

This commit is contained in:
Claude committed 2026-11-09 13:25:34 +00:00
1 parent c7705b1c58
commit d8b06bfb79
24 files changed
+3288 -2313

No files matched your search

+13 -1
View File
@@ -23,15 +23,27 @@ Komponenten lesen mit `useStore(selector)` nur ihren Ausschnitt.
## Verdrahtung (aus `App.tsx` herausgelöst)
`App.tsx` ruft diese Hooks in fester Reihenfolge auf (Effekte laufen in dieser Reihenfolge) und reicht die
Ergebnisse weiter; Komponenten-Teile der App liegen in `src/ui/AppDialogs.tsx`, `HiddenFileInputs.tsx`,
`BootScreen.tsx`, `useTopBarElements.tsx`, `src/menus/AppContextMenu.tsx` und `src/panels/DockArea.tsx`.
| Datei | Inhalt |
|---|---|
| `useProjectActions.ts` | Projekt-Aktionen als Store-Actions (früh aufgerufen, nur Selektoren) |
| `useCommandEngineHost.ts` | Host der Befehls-Engine: Kontext, Fang, Vorschau, Commit in den Store |
| `useToolInput.ts` | Plan-Handler (`toolHandlers`), Werkzeugwahl, Ribbon-Befehle, 3D-Arbeitsebene → Engine |
| `useGripInputs.ts` | einzeln gewähltes Element je Art, Schnitt-/Ansichts-Blatt, Fang für Griffe |
| `useSelectionCommands.ts` | Befehle auf der Auswahl (Löschen, Split, Booleans, Stil, Sperren, Ebenen, Gruppen) samt Kürzeln |
| `useGripEditing.ts`, `useGrip3dEditing.ts` | Griffe in 2D und 3D; die Rechnung je Mausschritt liegt im Kern (`grips.rs`, `grip_drag.rs`) |
| `useCommandLineBinding.ts` | Befehlszeile und Cursor-HUD: Feld-Controller eines Griff-Drags oder die Engine |
| `useMouseSelectionHandlers.ts` | Auswahl und Kontextmenü aus Grundriss und 3D |
| `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 |
| `useProjectFileActions.ts`, `useImportHandling.ts`, `useExportHandlers.ts` | Datei öffnen und speichern, Importe, Plan-Export |
| `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) |
| `useSheetPane.ts` | offenes Layout-Blatt |
## Reine Logik
+166
View File
@@ -0,0 +1,166 @@
// Befehlszeile und Cursor-HUD ([163], aus App.tsx herausgelöst): entscheidet, wer Befehlsfeld und HUD
// belegt — ein laufender Griff-Drag (2D-Punkt, 2D-Kante, 3D) als Feld-Controller oder sonst die
// Befehls-Engine — und leitet Eingabe, Tab und Esc dorthin. Getippte Längen werden aus Anzeige-
// Einheiten (Blatt: Papier-mm) in Meter umgerechnet. Aufgerufen von `App.tsx`; die Werte gehen an
// `CommandLine` und die Hauptansicht (`hudFields`).
import type { RefObject } from "react";
import { NON_LENGTH_FIELDS } from "../commands/parseInput";
import type { EngineView } from "../commands/engine";
import { lengthFromDisplay, type DisplayUnits } from "../tools/displayUnits";
import { grip3dEditFields } from "../viewport/grip3dHud";
import type { PlanViewHandle } from "../views/plan/PlanView";
import type { useCommandEngineHost } from "./useCommandEngineHost";
import type { useGrip3dEditing } from "./useGrip3dEditing";
import type { useGripEditing } from "./useGripEditing";
/** Keine Inline-Optionen (stabile Identität für die memoisierte Befehlszeile, [121]). */
const NO_OPTIONS: EngineView["options"] = [];
export function useCommandLineBinding(opts: {
engine: ReturnType<typeof useCommandEngineHost>["engine"];
engineView: EngineView;
commandActive: boolean;
cmdTyped: string;
displayUnits: DisplayUnits;
planViewRef: RefObject<PlanViewHandle>;
grip2d: ReturnType<typeof useGripEditing>;
grip3d: ReturnType<typeof useGrip3dEditing>;
}) {
const { engine, engineView, commandActive, cmdTyped, displayUnits, planViewRef } = opts;
const {
gripEdit,
gripEditFields,
submitGripEditValue,
cycleGripEditField,
closeGripEditField,
edgeEdit,
edgeEditFields,
submitEdgeEditValue,
cycleEdgeEditField,
closeEdgeEditField,
} = opts.grip2d;
const { grip3dEdit, setGrip3dEdit, last3dDragRef, cycleGrip3dEditField, submitGrip3dEditValue } = opts.grip3d;
// Feld-Zustand fürs Cursor-HUD (neben der Maus, VW-Stil): läuft ein Punkt-
// ODER Kanten-Griff-Drag, hat er Vorrang (dieselben Felder wie unten in der
// Befehlszeile — Länge/Winkel- bzw. Abstand-Tab-Zyklus), sonst die Befehls-
// Engine-Felder (Zeichnen; Winkel beim Drehen bzw. Distanz beim Bewegen). Vorher zeigte das Cursor-HUD beim Griff-Ziehen
// GAR KEINE Länge/Winkel-Werte an (nur die Befehlszeile unten) — Nutzer-
// Wunsch: „du kannst [Länge/Winkel] gleich bei der Maus anzeigen wie beim
// Erstellen".
const hudFields =
gripEdit
? { fields: gripEditFields(), typed: cmdTyped }
: edgeEdit
? { fields: edgeEditFields(), typed: cmdTyped }
: grip3dEdit
? {
fields: grip3dEditFields(grip3dEdit, last3dDragRef.current?.raw ?? grip3dEdit.anchor),
typed: cmdTyped,
}
: commandActive && engineView.fields.length > 0
? {
fields: engineView.fields.map((f) => ({
id: f.id,
value: f.value,
locked: f.locked,
active: f.active,
})),
typed: cmdTyped,
}
: null;
// Befehlszeile (Rhino-artig): Während eines Vertex- ODER Kanten-Griff-Drags belegt der Feld-
// Controller das Befehlsfeld (Länge/Winkel bzw. Abstand). Läuft eine Auswahl-Transformation
// (Drehen etc.), belegt sie Prompt + U/I/O/P + Winkel-/Distanzfeld. Sonst gilt die Engine
// (Zeichnen/Ruhe). Griff-/Kanten-Drag haben Vorrang (schließen sich sonst aus).
const fieldController = !!(gripEdit || edgeEdit || grip3dEdit);
const cmdLineActive = fieldController ? true : engineView.active;
const cmdLinePromptKey = gripEdit
? "cmd.edit.point"
: edgeEdit
? "cmd.edit.edge"
: grip3dEdit
? "cmd.edit.point"
: engineView.promptKey;
const cmdLineOptions = fieldController ? NO_OPTIONS : engineView.options;
const cmdLineFields = gripEdit
? gripEditFields()
: edgeEdit
? edgeEditFields()
: grip3dEdit
? grip3dEditFields(grip3dEdit, last3dDragRef.current?.raw ?? grip3dEdit.anchor)
: engineView.fields;
const cmdLineSteps = fieldController ? 0 : engineView.steps;
const onCmdSubmit = (text: string) => {
// Feld-Controller (Griff, Kante): getippte Länge in Anzeige-Einheiten
// (Blatt: Papier-mm) → Meter; Winkel/Anzahl bleiben.
const ctlFields = gripEdit
? gripEditFields()
: edgeEdit
? edgeEditFields()
: [];
const ctlActive = ctlFields.find((f) => f.active)?.id;
const typed = (raw: string): number => {
const n = parseFloat(raw.replace(",", "."));
return ctlActive && !NON_LENGTH_FIELDS.has(ctlActive) ? lengthFromDisplay(displayUnits, n) : n;
};
if (gripEdit) {
const v = typed(text);
if (isFinite(v)) submitGripEditValue(v);
// Leere Eingabe: kein neuer Wert zu locken — Enter bestätigt
// stattdessen die aktuelle Position (Maus- oder bereits
// gelockte Werte) und schließt die Griff-Bearbeitung ab. Vorher
// ein Totdruck (Nutzer-Report: Enter tat nichts).
else planViewRef.current?.confirmGripEdit();
return;
}
if (edgeEdit) {
const v = typed(text);
if (isFinite(v)) submitEdgeEditValue(v);
else planViewRef.current?.confirmEdgeEdit();
return;
}
if (grip3dEdit) {
const v = parseFloat(text.replace(",", "."));
if (isFinite(v)) submitGrip3dEditValue(v);
// Leere Eingabe: Feld-Controller schliessen, Maus steuert den
// laufenden Griff-Drag wieder normal weiter (kein 3D-Äquivalent
// zu `confirmGripEdit` — die Maustaste bleibt physisch gedrückt).
else setGrip3dEdit(null);
return;
}
engine.submitText(text);
};
const onCmdCycleField = () =>
gripEdit
? cycleGripEditField()
: edgeEdit
? cycleEdgeEditField()
: grip3dEdit
? cycleGrip3dEditField()
: engine.cycleField();
const onCmdCancel = () =>
gripEdit
? closeGripEditField()
: edgeEdit
? closeEdgeEditField()
: grip3dEdit
? setGrip3dEdit(null)
: engine.escape();
return {
hudFields,
cmdLineActive,
cmdLinePromptKey,
cmdLineOptions,
cmdLineFields,
cmdLineSteps,
onCmdSubmit,
onCmdCycleField,
onCmdCancel,
};
}
+33 -2
View File
@@ -1,10 +1,12 @@
// Bündelt die PDF-/DXF-Plan-Export-Handler (Papier-/Modell-Space-Export der
// aktuellen Grundriss-Ansicht) — die Schnellexporte (CSV/IFC/OBJ/STL) liegen
// bereits in useProjectFileActions(). Nur aus App.tsx herausgezogen, um die
// Funktion zu entlasten — reine Verlagerung, keine Verhaltensänderung.
// Funktion zu entlasten — reine Verlagerung, keine Verhaltensänderung. Dazu das Inhaltsmass
// des Plans für die „passt aufs Blatt?"-Warnung im PDF-Dialog ([163]).
//
// Extrahiert aus App.tsx. Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md).
import { useMemo } from "react";
import { generatePlan, withDocument } from "../core";
import type { CategoryDisplayResolver } from "../core";
import type { DetailLevel } from "../model/viewTypes";
@@ -22,6 +24,8 @@ import { getState } from "./appStore";
import { t } from "../i18n";
export function useExportHandlers(opts: {
/** PDF-Export-Dialog offen? Nur dann wird das Inhaltsmass gerechnet. */
exportOpen: boolean;
project: Project;
activeLevelId: string;
activeLevelName: string;
@@ -35,11 +39,13 @@ export function useExportHandlers(opts: {
setExportOpen: (open: boolean) => void;
setExportDxfOpen: (open: boolean) => void;
}): {
exportContentMeters: { w: number; h: number } | undefined;
onExportPdf: (decision: ExportPdfDecision) => Promise<void>;
onExportSvg: (decision: ExportPdfDecision) => void;
onExportDxf: (decision: ExportDxfDecision) => Promise<void>;
} {
const {
exportOpen,
project,
activeLevelId,
activeLevelName,
@@ -53,6 +59,31 @@ export function useExportHandlers(opts: {
setExportDxfOpen,
} = opts;
// Massstäbliche Inhalts-Maße (Meter) des aktuellen Plans — nur berechnet, wenn
// der Export-Dialog offen ist (für die „passt aufs Blatt?"-Warnung).
const exportContentMeters = useMemo(() => {
if (!exportOpen) return undefined;
const b = generatePlan(
project,
activeLevelId,
visibleCodes,
categoryDisplay,
detail,
referenceLines,
planColorMode === "mono",
).bounds;
return { w: b.maxX - b.minX, h: b.maxY - b.minY };
}, [
exportOpen,
project,
activeLevelId,
visibleCodes,
categoryDisplay,
detail,
referenceLines,
planColorMode,
]);
const scopedProject = (selectionOnly: boolean): Project =>
selectionOnly ? filterProjectToSelection(project, selectionMembers) : project;
@@ -152,5 +183,5 @@ export function useExportHandlers(opts: {
setExportDxfOpen(false);
};
return { onExportPdf, onExportSvg, onExportDxf };
return { exportContentMeters, onExportPdf, onExportSvg, onExportDxf };
}
+93
View File
@@ -0,0 +1,93 @@
// Eingaben der Editier-Griffe ([163], aus App.tsx herausgelöst): das einzeln gewählte Element je Art
// (2D-Element, Decke, Baugrube, Raum samt Stempel-Anker), das Schnitt-/Ansichts-Blatt für waagrechtes
// Ziehen und der Fang ohne Entwurfspunkte (`snapFor`). Aufgerufen von `App.tsx`; die Werte gehen an
// `useGripEditing` und an die Hauptansicht (`roomStamp`).
import { useMemo } from "react";
import type { DrawingLevel, Project, Vec2 } from "../model/types";
import { roomLabelPoint, sectionPlaneFromLevel, sectionUAxisModel } from "../core";
import { computeSnap } from "../tools/snapping";
import type { SnapSettings, ToolMods } from "../tools/types";
import type { useSelectionState } from "./useSelectionState";
type Sel = ReturnType<typeof useSelectionState>;
export function useGripInputs(opts: {
project: Project;
activeLevel: DrawingLevel;
selection: Sel["selection"];
selectedDrawingId: string | null;
selectedCeilingId: string | null;
selectedRoomId: string | null;
visibleCodes: Set<string>;
snap: SnapSettings;
/** Massstab der Arbeitsebene (Blatt: 1:1). */
planScale: number;
}) {
const { project, activeLevel, selection, selectedDrawingId, selectedCeilingId, selectedRoomId, visibleCodes, snap, planScale } =
opts;
// ── Editier-Griffe (Grips) des einzeln selektierten Elements ──────────────
// Genau eine Wand ODER ein 2D-Element → dessen Eckpunkte als ziehbare Griffe.
const selectedDrawing = useMemo(
() => project.drawings2d.find((d) => d.id === selectedDrawingId) ?? null,
[project.drawings2d, selectedDrawingId],
);
const selectedCeiling = useMemo(
() => (project.ceilings ?? []).find((c) => c.id === selectedCeilingId) ?? null,
[project.ceilings, selectedCeilingId],
);
// [68] Genau eine gewählte Baugrube (Griffe für Umriss und Sohle).
const selectedExcavation = useMemo(() => {
if (selection.contextObjects.length !== 1) return null;
const o = (project.context ?? []).find((c) => c.id === selection.contextObjects[0]);
return o && o.type === "excavation" ? o : null;
}, [project.context, selection.contextObjects]);
const selectedRoom = useMemo(
() => (project.rooms ?? []).find((r) => r.id === selectedRoomId) ?? null,
[project.rooms, selectedRoomId],
);
// Stempel-Griff des (einzeln) gewählten Raums: sein fixer Anker (Meter) + ID.
const roomStamp = useMemo(
() =>
selectedRoom
? {
roomId: selectedRoom.id,
anchor: selectedRoom.stampAnchor ?? roomLabelPoint(selectedRoom.boundary),
}
: null,
[selectedRoom],
);
// Schnitt-/Ansichts-Blatt: geschnittene (bzw. in der Ansicht sichtbare)
// Wände/Decken lassen sich dort waagrecht entlang der Linie ziehen (s.
// useGripEditing `sheet`).
const sectionSheet = useMemo(() => {
if (activeLevel.kind !== "section" && activeLevel.kind !== "elevation") return null;
const plane = sectionPlaneFromLevel(activeLevel);
if (!plane) return null;
const u = sectionUAxisModel(plane);
const len = Math.hypot(u.x, u.y) || 1;
return { levelId: activeLevel.id, uAxis: { x: u.x / len, y: u.y / len } };
}, [activeLevel]);
// Snap ohne Entwurfspunkte (Griff-Ziehen, s. useGripEditing).
const snapFor = (raw: Vec2, pxPerMeter: number, mods: ToolMods) => {
const pts: Vec2[] = [];
return computeSnap({
raw,
project,
levelId: activeLevel.id,
visibleCodes,
settings: snap,
draftPoints: pts,
lastPoint: pts.length ? pts[pts.length - 1] : null,
scale: planScale,
pxPerMeter,
shift: mods.shift,
ctrl: mods.ctrl,
});
};
return { selectedDrawing, selectedCeiling, selectedExcavation, selectedRoom, roomStamp, sectionSheet, snapFor };
}
+105
View File
@@ -0,0 +1,105 @@
// Modell-Importe mit eigenem Ablauf ([163], aus App.tsx herausgelöst): IFC (erst Wahl Mesh/Bauteile,
// dann Bericht), STEP und 3D-Meshes (OBJ/STL/glTF/PLY) werden im Kern als EIN Undo-Schritt übernommen
// (`commitImport`). `openImportForAnyFile` verteilt eine Datei aus Dialog oder Drag & Drop auf den
// passenden Import. Aufgerufen von `App.tsx` nach `useProjectFileActions` (braucht `openImportForFile`).
import { useState, type RefObject } from "react";
import type { ContextObject, Wall } from "../model/types";
import { addedItems } from "../core";
import { readStepFlat } from "../engine/truckSolid";
import { formatIfcElementsSummary, formatIfcReport, readIfcFlat, type IfcElementsSummary } from "../io/ifcImport";
import { formatMeshReport, isMeshFile, type MeshPlacement, type MeshRead } from "../io/meshImport";
import { isPointCloudFile } from "../io/pointCloud";
import type { IfcImportMode } from "../ui/IfcImportDialog";
import type { PlanViewHandle } from "../views/plan/PlanView";
import { t } from "../i18n";
import { getState, type RootState } from "./appStore";
import { requestMeshImport } from "./meshImportStore";
import { requestPointCloudImport } from "./pointCloudStore";
import type { useProjectActions } from "./useProjectActions";
export function useModelImport(opts: {
notify: RootState["notify"];
planViewRef: RefObject<PlanViewHandle | null>;
fitToContextObjects: ReturnType<typeof useProjectActions>["fitToContextObjects"];
/** DXF/DWG/PDF-Import-Dialog (aus `useProjectFileActions`). */
openImportForFile: (f: File) => void;
}) {
const { notify, planViewRef, fitToContextObjects, openImportForFile } = opts;
// IFC-Import: erst die Wahl Mesh/Bauteile (`IfcImportDialog`), dann liest das Format-Modul (Web-Worker) und der
// Kern übernimmt [B3] Kontext-Meshes oder [B4] echte Bauteile als EINEN Undo-Schritt ([K4] S4, `importIfc`).
const [pendingIfc, setPendingIfc] = useState<File | null>(null);
// Bericht nach dem Bauteil-Import ([B4]): erkannt je Bauteilart, als Mesh geblieben mit Grund.
const [ifcReport, setIfcReport] = useState<{ fileName: string; summary: IfcElementsSummary } | null>(null);
const importIfcFile = (f: File) => setPendingIfc(f);
const runIfcImport = (f: File, mode: IfcImportMode) => {
const elements = mode === "elements";
void f
.arrayBuffer()
.then((buf) => readIfcFlat(new Uint8Array(buf), elements))
.then((flat) => {
const r = getState().commitImport((doc, base, now) => doc.importIfc(base, flat, { fileName: f.name, elements }, now), "history.import.ifc");
if (!r) return;
const report = r.report;
if (elements && r.summary) {
const bounds = addedItems(r.ops, "walls").flatMap((w) => [(w as Wall).start, (w as Wall).end]);
if (bounds.length) planViewRef.current?.fitBounds(bounds);
const s = r.summary;
const empty = s.walls + s.ceilings + s.columns + s.rooms + s.meshes === 0;
notify(formatIfcElementsSummary(s, report, t), empty || report.truncated ? "warning" : "info");
setIfcReport({ fileName: f.name, summary: s });
return;
}
fitToContextObjects(addedItems(r.ops, "context") as ContextObject[]);
const warn = r.contextObjects === 0 || report.truncated || report.productsWithoutGeometry > 0;
notify(formatIfcReport(report, t), warn ? "warning" : "info");
})
.catch((err) =>
notify(`${t("ifc.import.failed")}: ${err instanceof Error ? err.message : String(err)}`, "error"),
);
};
/** Datei aus Import-Dialog oder Drag & Drop: IFC direkt, sonst DXF/DWG-Dialog. */
const openImportForAnyFile = (f: File) => {
if (isMeshFile(f.name)) return requestMeshImport(f);
if (isPointCloudFile(f.name)) return requestPointCloudImport(f);
if (/\.ifc$/i.test(f.name)) importIfcFile(f);
else openImportForFile(f);
};
// STEP-Import (Menü Datei, STEP importieren).
const importStepFile = (f: File) => {
void f
.text()
.then((text) => readStepFlat(text))
.then((flat) => {
// Der Kern macht je Körper ein Kontext-Mesh und übernimmt sie als EINEN Undo-Schritt ([K4] S4).
const r = getState().commitImport((doc, base, now) => doc.importStep(base, flat, { fileName: f.name }, now));
if (r) fitToContextObjects(addedItems(r.ops, "context") as ContextObject[]);
})
.catch((err) =>
notify(`${t("step.import.failed")}: ${err instanceof Error ? err.message : String(err)}`, "error"),
);
};
// 3D-Modell-Import (OBJ/STL/glTF/GLB/PLY) aus dem MeshImportHost.
const onMeshImport = (read: MeshRead, fileName: string, placement: MeshPlacement) => {
// Der Kern macht die Kontext-Meshes und übernimmt sie als EINEN Undo-Schritt ([K4] S4).
const r = getState().commitImport((doc, base, now) => doc.importMesh(base, read.flat, { fileName, placement }, now), "history.import.mesh");
if (!r) return;
fitToContextObjects(addedItems(r.ops, "context") as ContextObject[]);
notify(formatMeshReport(read.report, t), r.contextObjects === 0 || read.report.truncated ? "warning" : "info");
};
return {
pendingIfc,
setPendingIfc,
ifcReport,
setIfcReport,
importIfcFile,
runIfcImport,
openImportForAnyFile,
importStepFile,
onMeshImport,
};
}
+178
View File
@@ -0,0 +1,178 @@
// Native macOS-Menüleiste der App ([163], aus App.tsx herausgelöst): verdrahtet `useNativeAppMenu`
// (src/native/appMenu.ts) mit Datei-, Import-/Export-, Bearbeiten-, Ansichts- und Fenster-Aktionen,
// dazu die Kennzahlen-Kurzmeldung. Ausserhalb von Tauri ein No-op (im Browser übernimmt `AppMenuBar`).
// Aufgerufen von `App.tsx`, nachdem Einstellungen, Ressourcen und Nebenfenster verdrahtet sind.
import { useMemo, type RefObject } from "react";
import type { Project, ViewType } from "../model/types";
import { computeKennzahlen, checkRoomProgram } from "../core";
import { useNativeAppMenu } from "../native/appMenu";
import { openContextImportWindowNative } from "../native/contextImportWindow";
import { openDrawingLevelsWindowNative } from "../native/drawingLevelsWindow";
import { runClashAndStore } from "../panels/clashSession";
import { programStatusLabel } from "../panels/KennzahlenSection";
import { revealPanel } from "../panels/layout";
import { listPanels } from "../panels/registry";
import { t } from "../i18n";
import type { RootState } from "./appStore";
import { openMeshFileDialog } from "./meshImportStore";
import { openPointCloudFileDialog } from "./pointCloudStore";
import type { useDialogState } from "./useDialogState";
import type { useProjectFileActions } from "./useProjectFileActions";
import type { useTopBarState } from "./useTopBarState";
type TopBar = ReturnType<typeof useTopBarState>;
type Dialogs = ReturnType<typeof useDialogState>;
export function useNativeMenu(opts: {
project: Project;
files: ReturnType<typeof useProjectFileActions>;
notify: RootState["notify"];
undo: () => void;
redo: () => void;
canUndo: boolean;
canRedo: boolean;
setLayout: RootState["setLayout"];
viewType: ViewType;
setViewType: (v: ViewType) => void;
view3d: TopBar["view3d"];
setView3d: TopBar["setView3d"];
referenceLines: TopBar["referenceLines"];
setReferenceLines: TopBar["setReferenceLines"];
resourcesOpen: boolean;
setExportOpen: Dialogs["setExportOpen"];
setExportDxfOpen: Dialogs["setExportDxfOpen"];
dxfInputRef: RefObject<HTMLInputElement>;
stepInputRef: RefObject<HTMLInputElement>;
ifcInputRef: RefObject<HTMLInputElement>;
hasSelectionToDelete: () => boolean;
deleteSelection: () => void;
onRunCommand: (name: string) => void;
toggleResources: () => void;
openSettings: () => void;
openLayerSettings: (code: string, x: number, y: number) => void;
activeCategoryCode: string;
}) {
const {
project,
notify,
undo,
redo,
canUndo,
canRedo,
setLayout,
viewType,
setViewType,
view3d,
setView3d,
referenceLines,
setReferenceLines,
resourcesOpen,
setExportOpen,
setExportDxfOpen,
dxfInputRef,
stepInputRef,
ifcInputRef,
hasSelectionToDelete,
deleteSelection,
onRunCommand,
toggleResources,
openSettings,
openLayerSettings,
activeCategoryCode,
} = opts;
const {
onNewProject,
onNewProjectFromSample,
onNewProjectFromComplexSample,
onNewProjectFromTemplate,
onOpenProject,
onSaveProject,
onSaveProjectAs,
onExportSchedule,
onExportIfc,
onExportObj,
onExportStl,
onExportGlb,
onExportStep,
} = opts.files;
// Panel-Liste für „Fenster > Panels" (native Menüleiste) — die Registry ist
// statisch (Panels tragen sich beim Modul-Import ein), daher einmalig.
const nativeMenuPanels = useMemo(
() => listPanels().map((p) => ({ id: p.id, label: t(p.title) })),
[],
);
// Native macOS-Systemmenüleiste (oben am Bildschirm) — dieselben Aktionen
// wie AppMenuBar/QuickAccess, nur als echter App-Menü-Baum. No-op ausserhalb
// von Tauri (isTauriRuntime-Guard steckt im Hook selbst).
useNativeAppMenu(
{
onNewProject,
onNewProjectFromSample,
onNewProjectFromComplexSample,
onNewProjectFromTemplate,
onOpenProject,
onSaveProject,
onSaveProjectAs,
onImport: () => dxfInputRef.current?.click(),
onExportPdf: () => setExportOpen(true),
onExportDxf: () => setExportDxfOpen(true),
onExportSchedule,
onExportIfc,
onExportObj,
onExportStl,
onExportGlb,
onExportStep,
onImportStep: () => stepInputRef.current?.click(),
onImportIfc: () => ifcInputRef.current?.click(),
onImportPointCloud: () => openPointCloudFileDialog(),
onImportMesh: () => openMeshFileDialog(),
onClashCheck: () => {
setLayout((l) => revealPanel(l, "clash"));
void runClashAndStore();
},
onKennzahlen: () => {
const k = computeKennzahlen(project);
const prog = checkRoomProgram(project);
const f = (n: number, d = 1) => n.toFixed(d);
const lines = [
t("kennzahlen.summary", { gf: f(k.gf), agf: f(k.agf), gv: f(k.gv) }),
k.az !== null && k.uez !== null ? t("kennzahlen.ziffern", { az: f(k.az, 2), uez: f(k.uez, 2) }) : t("kennzahlen.noParcel"),
];
if (prog.rows.length > 0) {
const bad = prog.rows.filter((r) => r.status !== "ok");
lines.push(t("kennzahlen.program", { ok: prog.rows.length - bad.length, n: prog.rows.length }));
for (const r of bad.slice(0, 4)) lines.push(t("kennzahlen.programIssue", { name: r.name, status: programStatusLabel(r.status) }));
}
notify(lines.join(" — "), "info");
},
onUndo: undo,
onRedo: redo,
onDeleteSelection: deleteSelection,
onMove: () => onRunCommand("move"),
onMirror: () => onRunCommand("mirror"),
onRotate: () => onRunCommand("rotate"),
onViewType: setViewType,
onView3d: setView3d,
onReferenceLines: setReferenceLines,
onToggleResources: () => toggleResources(),
onOpenSettings: () => openSettings(),
onOpenPanel: (panelId) => setLayout((l) => revealPanel(l, panelId)),
onOpenDrawingLevelsWindow: () => void openDrawingLevelsWindowNative(),
onOpenLayerSettingsWindow: () => openLayerSettings(activeCategoryCode, 0, 0),
onOpenContextImportWindow: () => void openContextImportWindowNative(),
},
{
canUndo,
canRedo,
hasSelection: hasSelectionToDelete(),
viewType,
view3d,
referenceLines,
resourcesOpen,
},
nativeMenuPanels,
);
}
+95
View File
@@ -0,0 +1,95 @@
// Native Nebenfenster der App ([163], aus App.tsx herausgelöst): Ebeneneinstellungen,
// Standort-Import und Zeichnungsebenen-Manager als eigene Tauri-Fenster, je über ihre Sync-Brücke
// (`src/native/*Window.ts`). Ausserhalb von Tauri sind die Hosts No-ops; `openLayerSettings` öffnet
// dann den Inline-Editor. Aufgerufen von `App.tsx`.
import type { ContextObject, Project } from "../model/types";
import { setFieldIfChanged } from "../core";
import { isTauriRuntime } from "../native/projectFile";
import { useContextImportWindowHost } from "../native/contextImportWindow";
import { useDrawingLevelsWindowHost } from "../native/drawingLevelsWindow";
import { openLayerSettingsWindowNative, useLayerSettingsWindowHost } from "../native/layerSettingsWindow";
import { BUILTIN_PANEL_IDS } from "../panels/builtinPanels";
import type { useContextMenuState } from "../menus/useContextMenuState";
import type { RootState } from "./appStore";
import type { useDisplayResolvers } from "./useDisplayResolvers";
import type { useProjectActions } from "./useProjectActions";
type Menu = ReturnType<typeof useContextMenuState>;
export function useNativeWindowHosts(opts: {
project: Project;
applyChange: RootState["applyChange"];
activeLevelId: string;
setActiveLevelId: RootState["setActiveLevelId"];
setModeFor: RootState["setModeFor"];
drawingLevelsMode: ReturnType<typeof useDisplayResolvers>["drawingLevelsMode"];
nativeLayerSettingsCode: Menu["nativeLayerSettingsCode"];
setNativeLayerSettingsCode: Menu["setNativeLayerSettingsCode"];
setEditor: Menu["setEditor"];
pa: ReturnType<typeof useProjectActions>;
}) {
const {
project,
applyChange,
activeLevelId,
setActiveLevelId,
setModeFor,
drawingLevelsMode,
nativeLayerSettingsCode,
setNativeLayerSettingsCode,
setEditor,
} = opts;
const {
patchCategory,
addContextObjectsAndFit,
toggleLevelVisible,
addFloor,
addSection,
addElevation,
addCeiling,
addDrawing,
} = opts.pa;
// Ebeneneinstellungen als eigenes natives Fenster (DOSSIER-Rhino-Referenz)
// — ersetzt unter Tauri den InlineEditor-Popover, s. native/layerSettingsWindow.ts.
useLayerSettingsWindowHost(project, nativeLayerSettingsCode, patchCategory);
const openLayerSettings = (code: string, x: number, y: number) => {
if (isTauriRuntime()) {
setNativeLayerSettingsCode(code);
void openLayerSettingsWindowNative(code);
} else {
setEditor({ kind: "layer", code, x, y });
}
};
// Standort-Import als eigenes natives Fenster — s. native/contextImportWindow.ts.
useContextImportWindowHost(project.geoAnchor, {
onImport: (objs) => addContextObjectsAndFit(objs as ContextObject[]),
onSetGeoAnchor: (anchor) => applyChange((p) => setFieldIfChanged(p, "geoAnchor", anchor)),
});
// Zeichnungsebenen-Manager als eigenes natives Fenster (DOSSIER-Rhino-
// Referenz) — additiv NEBEN dem bestehenden Dock-Panel, siehe
// native/drawingLevelsWindow.ts Kopfkommentar (Rechtsklick-Kontextmenü
// bewusst nicht mitgenommen).
useDrawingLevelsWindowHost(
{
drawingLevels: project.drawingLevels.filter((z) => !z.layoutId),
activeLevelId,
displayMode: drawingLevelsMode,
},
{
onSelectLevel: setActiveLevelId,
onToggleLevel: toggleLevelVisible,
onAddFloor: addFloor,
onAddSection: addSection,
onAddElevation: addElevation,
onAddCeiling: addCeiling,
onAddDrawing: addDrawing,
onSetDisplayMode: (mode) => setModeFor(BUILTIN_PANEL_IDS.drawingLevels, mode),
},
);
return { openLayerSettings };
}
+214
View File
@@ -0,0 +1,214 @@
// Ressourcen-Fenster der App ([163], aus App.tsx herausgelöst): Handler-Bündel für den
// `ResourceManager` (Typen, Bauteile, Schraffuren, Linien-/Textstile, Stifte, Paletten,
// Ansichtsvorlagen), der Abgleich mit dem nativen Ressourcen-Fenster (Tauri) und das Öffnen bzw.
// Umschalten. Aufgerufen von `App.tsx`; `openResources` geht an die Panels, `toggleResources` an Menüs.
import type { RefObject } from "react";
import type { DrawingLevel, Project } from "../model/types";
import { isTauriRuntime } from "../native/projectFile";
import { openResourceWindowNative, useResourceWindowHost } from "../native/resourceWindow";
import { BUILTIN_PANEL_IDS } from "../panels/builtinPanels";
import type { ResourceManagerHandlers, TabId as ResourceTabId } from "../ui/ResourceManager";
import type { PlanViewHandle } from "../views/plan/PlanView";
import type { RootState } from "./appStore";
import type { useDialogState } from "./useDialogState";
import type { useProjectActions } from "./useProjectActions";
import type { useTopBarState } from "./useTopBarState";
import { useViewTemplateHandlers } from "./useViewTemplateHandlers";
type TopBar = ReturnType<typeof useTopBarState>;
type Dialogs = ReturnType<typeof useDialogState>;
export function useResourceHandlers(opts: {
project: Project;
applyChange: RootState["applyChange"];
groupChanges: RootState["groupChanges"];
activeLevel: DrawingLevel;
detail: TopBar["detail"];
setDetail: TopBar["setDetail"];
scaleDenominator: TopBar["scaleDenominator"];
setScaleDenominator: TopBar["setScaleDenominator"];
planColorMode: TopBar["planColorMode"];
setPlanColorMode: TopBar["setPlanColorMode"];
modeFor: RootState["modeFor"];
setModeFor: RootState["setModeFor"];
planViewRef: RefObject<PlanViewHandle>;
pa: ReturnType<typeof useProjectActions>;
setResourcesTab: Dialogs["setResourcesTab"];
setResourcesOpen: Dialogs["setResourcesOpen"];
}) {
const {
project,
applyChange,
groupChanges,
activeLevel,
detail,
setDetail,
scaleDenominator,
setScaleDenominator,
planColorMode,
setPlanColorMode,
modeFor,
setModeFor,
planViewRef,
setResourcesTab,
setResourcesOpen,
} = opts;
const {
addCeilingType,
addColorToCustomPalette,
addComponent,
addCustomPalette,
addDoorType,
addHatch,
addLineStyle,
addPen,
addPenSet,
addRoofType,
addStairType,
addTextStyle,
addWallType,
addWindowType,
deleteCeilingType,
deleteComponent,
deleteCustomPalette,
deleteDoorType,
deleteHatch,
deleteLineStyle,
deletePen,
deletePenSet,
deleteRoofType,
deleteStairType,
deleteTextStyle,
deleteWallType,
deleteWindowType,
importHatches,
importLineStyles,
loadStandards,
patchCeilingType,
patchComponent,
patchDoorType,
patchHatch,
patchLineStyle,
patchPenSetColor,
patchPenSetWeight,
patchRoofType,
patchStairType,
patchTextStyle,
patchWallType,
patchWindowType,
removeColorFromCustomPalette,
renameCustomPalette,
renamePen,
renamePenSet,
seedStandardPenSet,
setActivePenSet,
setBuiltinPaletteVisible,
setCustomPaletteVisible,
setOverrideRules,
updateStandards,
snapshotLayerVisibility,
applyLayerVisibility,
} = opts.pa;
// Ansichtsvorlagen ([34]): Ressourcen-Handler + Abgleich der verknüpften Vorlage der aktiven Ansicht.
const viewTemplateHandlers = useViewTemplateHandlers({
project,
applyChange,
groupChanges,
activeLevel,
detail,
setDetail,
scaleDenominator,
setScaleDenominator,
snapshotLayerVisibility,
applyLayerVisibility,
mono: planColorMode === "mono",
setMono: (m) => setPlanColorMode(m ? "mono" : "color"),
displayMode: modeFor(BUILTIN_PANEL_IDS.drawingLevels),
setDisplayMode: (m) => setModeFor(BUILTIN_PANEL_IDS.drawingLevels, m),
planViewRef,
});
// Handler-Bündel für das schwebende Ressourcen-Fenster (ResourceManager).
const resourceHandlers: ResourceManagerHandlers = {
...viewTemplateHandlers,
onPatchComponent: patchComponent,
onPatchWallType: patchWallType,
onAddWallType: addWallType,
onDeleteWallType: deleteWallType,
onPatchCeilingType: patchCeilingType,
onAddCeilingType: addCeilingType,
onDeleteCeilingType: deleteCeilingType,
onPatchRoofType: patchRoofType,
onAddRoofType: addRoofType,
onDeleteRoofType: deleteRoofType,
onAddDoorType: addDoorType,
onPatchDoorType: patchDoorType,
onDeleteDoorType: deleteDoorType,
onAddWindowType: addWindowType,
onPatchWindowType: patchWindowType,
onDeleteWindowType: deleteWindowType,
onAddStairType: addStairType,
onPatchStairType: patchStairType,
onDeleteStairType: deleteStairType,
onAddComponent: addComponent,
onDeleteComponent: deleteComponent,
onPatchHatch: patchHatch,
onAddHatch: addHatch,
onDeleteHatch: deleteHatch,
onPatchLineStyle: patchLineStyle,
onAddLineStyle: addLineStyle,
onDeleteLineStyle: deleteLineStyle,
onImportLineStyles: importLineStyles,
onImportHatches: importHatches,
onPatchTextStyle: patchTextStyle,
onAddTextStyle: addTextStyle,
onDeleteTextStyle: deleteTextStyle,
onSetOverrideRules: setOverrideRules,
onAddPen: addPen,
onRenamePen: renamePen,
onDeletePen: deletePen,
onAddPenSet: addPenSet,
onRenamePenSet: renamePenSet,
onDeletePenSet: deletePenSet,
onSetActivePenSet: setActivePenSet,
onPatchPenSetColor: patchPenSetColor,
onPatchPenSetWeight: patchPenSetWeight,
onSeedStandardPenSet: seedStandardPenSet,
onLoadStandards: loadStandards,
onUpdateStandards: updateStandards,
onAddCustomPalette: addCustomPalette,
onRenameCustomPalette: renameCustomPalette,
onDeleteCustomPalette: deleteCustomPalette,
onRemoveColorFromCustomPalette: removeColorFromCustomPalette,
onSetCustomPaletteVisible: setCustomPaletteVisible,
onSetBuiltinPaletteVisible: setBuiltinPaletteVisible,
onAddColorToCustomPalette: addColorToCustomPalette,
};
// Ressourcen-Manager als eigenes natives Fenster (Tauri) statt Overlay im
// Hauptfenster — hält es (falls offen) synchron zum Projekt, wendet dessen
// Befehle auf die ECHTEN Handler oben an (siehe native/resourceWindow.ts).
// No-op ausserhalb von Tauri.
useResourceWindowHost(project, resourceHandlers);
// Öffnet die Ressourcen: unter Tauri das native Zweitfenster, sonst (reiner
// Browser, kein OS-Fenster-Konzept) das bisherige schwebende Overlay.
const openResources = (tab?: ResourceTabId) => {
if (isTauriRuntime()) {
void openResourceWindowNative(tab);
} else {
if (tab) setResourcesTab(tab);
setResourcesOpen(true);
}
};
const toggleResources = () => {
if (isTauriRuntime()) {
void openResourceWindowNative();
} else {
setResourcesOpen((v) => !v);
}
};
return { resourceHandlers, openResources, toggleResources };
}
+81
View File
@@ -0,0 +1,81 @@
// Auswahl-Sicht und Schnittlinien ([163], aus App.tsx herausgelöst): die Objekt-Info der Auswahl
// (`deriveSelection`), die gewählte bzw. aktive Schnitt-/Ansichtslinie für das Objekt-Info-Panel und
// die 3D-Schnittebene des Live-Schnitts samt Umschalter. Aufgerufen von `App.tsx`; die Werte gehen an
// die Panels (`usePanelHostBase`) und die Hauptansicht.
import { useCallback, useEffect, useMemo } from "react";
import type { DrawingLevel, Project, ViewType } from "../model/types";
import { sectionPlaneFromLevel } from "../core";
import { deriveSelection } from "./selectionInfo";
import type { SelectionInfo } from "./selectionInfo";
import type { useSelectionState } from "./useSelectionState";
type Sel = ReturnType<typeof useSelectionState>;
export function useSectionLineState(opts: {
project: Project;
selection: Sel["selection"];
activeLevel: DrawingLevel;
viewType: ViewType;
selectedSectionLineId: string | null;
section3dCutId: Sel["section3dCutId"];
setSection3dCutId: Sel["setSection3dCutId"];
}) {
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.
const selectionInfo = useMemo(
(): SelectionInfo | null => deriveSelection(project, selection),
[project, selection],
);
// Gewählte Schnitt-/Ansichtslinie (DrawingLevel) — separat von `selection`, da
// eine Schnittlinie KEIN Projekt-Bauteil ist. Speist die Schnittlinien-Sektion
// des Object-Info-Panels.
// Ohne gewählte Linie, aber mit aktivem Schnitt/aktiver Ansicht: deren
// Einstellungen (Tiefe, verdeckte Kanten, Grundriss-Unterlage …) direkt im
// Leerzustand zeigen — man arbeitet ja gerade IN diesem Schnitt.
const sectionLineId =
selectedSectionLineId ??
(activeLevel.kind === "section" || activeLevel.kind === "elevation" ? activeLevel.id : null);
const sectionLine = useMemo(
() =>
sectionLineId
? project.drawingLevels.find(
(z) =>
z.id === sectionLineId &&
(z.kind === "section" || z.kind === "elevation"),
) ?? null
: null,
[project.drawingLevels, sectionLineId],
);
// Abgeleitete 3D-Schnittebene der gebundenen Schnittlinie (world point+normal
// via sectionPlaneFromLevel) — speist Viewport3D/Wasm3DViewport. Fehlt die
// Linie (gelöscht/ohne linePoints), liefert der Helfer null → kein Schnitt.
const section3dPlane = useMemo(() => {
if (!section3dCutId) return null;
const lvl = project.drawingLevels.find(
(z) =>
z.id === section3dCutId &&
(z.kind === "section" || z.kind === "elevation"),
);
return lvl ? sectionPlaneFromLevel(lvl) : null;
}, [project.drawingLevels, section3dCutId]);
// Aus einem Schnitt ins 3D ([115]): der Live-Schnitt folgt der Schnittlinie dieses Schnitts (einmal
// beim Wechsel; im 3D lässt er sich wie sonst aufheben).
const sectionLevelIn3d = activeLevel.kind === "section" && viewType === "perspektive" ? activeLevel.id : null;
useEffect(() => {
if (sectionLevelIn3d) setSection3dCutId(sectionLevelIn3d);
}, [sectionLevelIn3d, setSection3dCutId]);
// Bindet den 3D-Live-Schnitt an eine Schnittlinie (Toggle im Objekt-Info).
const onToggleSection3dCut = useCallback(
(id: string) => setSection3dCutId((cur) => (cur === id ? null : id)),
[],
);
return { selectionInfo, sectionLine, section3dPlane, onToggleSection3dCut };
}
+366
View File
@@ -0,0 +1,366 @@
// Befehle auf der aktuellen Auswahl ([163], aus App.tsx herausgelöst): Löschen, Split, 2D-Booleans,
// Stil übertragen, Sperren, Ebenen ausblenden/isolieren, „Nicht drucken", Bemassung lösen, Gruppen
// betreten/verlassen, Segment schneiden — samt der zugehörigen Tastenkürzel (gleiche Reihenfolge wie
// zuvor in App). Aufgerufen von `App.tsx`; die Rückgaben speisen Kontextmenü (`AppContextMenu`),
// Menüleisten, Export-Dialoge und die Hauptansicht.
import { useMemo } from "react";
import type { Drawing2D, DrawingLevel, Project, Vec2 } from "../model/types";
import { addItems, cmdMutation, fieldOps, opsMutation, patchItems, removeItems } from "../core";
import type { ToolId } from "../tools/types";
import type { MenuState } from "../menus/contextMenu";
import type { DrawingStyle } from "../editors/matchProps";
import { applyDrawingStyleOps, readDrawingStyle } from "../editors/matchProps";
import { cutSegmentOps, splitOps } from "../editors/splitJoin";
import type { BooleanResult } from "../editors/booleanOps";
import type { EngineView } from "../commands/engine";
import { clearKinds, fromIdLists, hasTransformable, isEmpty, toMembership } from "./selection";
import { containingGroupId, EMPTY_MEMBERSHIP } from "./groupActions";
import type { GroupMembership, MemberKind } from "./groupActions";
import { isLocked, lockMembersOps } from "./objectLock";
import { isolateCategories, selectionCategoryCodes, setCategoriesVisible } from "./selectionLayers";
import type { ShortcutOverrides } from "./keyboardShortcuts";
import {
useBooleanOpsShortcut,
useGroupShortcut,
useSelectAllAndDeleteShortcut,
useSplitJoinShortcut,
useTransformShortcuts,
} from "./useKeyboardShortcuts";
import { TRANSFORM_COMMANDS } from "./useToolInput";
import type { RootState } from "./appStore";
import type { useSelectionState } from "./useSelectionState";
import type { useProjectActions } from "./useProjectActions";
import type { useCommandEngineHost } from "./useCommandEngineHost";
type Sel = ReturnType<typeof useSelectionState>;
export function useSelectionCommands(opts: {
project: Project;
setProject: RootState["setProject"];
applyChange: RootState["applyChange"];
groupChanges: RootState["groupChanges"];
selection: Sel["selection"];
setSelection: Sel["setSelection"];
groupPath: Sel["groupPath"];
setGroupPath: Sel["setGroupPath"];
patchLevel: ReturnType<typeof useProjectActions>["patchLevel"];
activeTool: ToolId;
activeLevel: DrawingLevel;
engine: ReturnType<typeof useCommandEngineHost>["engine"];
engineView: EngineView;
shortcutOverrides: ShortcutOverrides;
menu: MenuState;
drawingStyleClipboard: DrawingStyle | null;
setDrawingStyleClipboard: (s: DrawingStyle | null) => void;
onCommandOption: (id: string) => void;
onRunCommand: (name: string) => void;
}) {
const {
project,
setProject,
applyChange,
groupChanges,
selection,
setSelection,
groupPath,
setGroupPath,
patchLevel,
activeTool,
activeLevel,
engine,
engineView,
shortcutOverrides,
menu,
drawingStyleClipboard,
setDrawingStyleClipboard,
onCommandOption,
onRunCommand,
} = opts;
// Ob irgendeine löschbare Auswahl ansteht — geteilt zwischen dem Entf-
// Tastatur-Handler unten und dem Menüpunkt „Bearbeiten > Löschen" (AppMenuBar).
const hasSelectionToDelete = () => !isEmpty(selection, { withGroups: false });
// Löscht die AKTUELLE Auswahl (alle Kanäle) — geteilte Logik zwischen dem
// Entf-Tastatur-Handler und dem Menüpunkt „Bearbeiten > Löschen".
const deleteSelection = () => {
// Ein Undo-Schritt für alles (Schnittlinien + Elemente), [K4] S3.
groupChanges(() => deleteSelectionChanges());
setSelection(clearKinds());
};
const deleteSelectionChanges = () => {
// Schnittlinie(n): Entf löscht NUR ihre Linie (linePoints), die Ebene
// bleibt — ADDITIV zu den übrigen Kanälen unten (nicht mehr exklusiv:
// seit Cmd/Ctrl+A Schnittlinien zusammen mit Wänden/etc. mitselektiert,
// würde ein frühes `return` hier die übrigen Kanäle stumm überspringen).
if (selection.sectionLines.length) {
for (const id of selection.sectionLines) patchLevel(id, { linePoints: undefined });
}
// Objekt-Sperre: gesperrte Elemente aus der Löschung ausnehmen (s.
// `moveGrip`/`moveElementBy` im Kern, `grips.rs`, für dieselbe Prüfung
// beim Ziehen). ExtrudedSolid/Kontext-Objekte haben kein `locked`-Feld
// (s. deren Typdefinitionen) — bleiben ungefiltert.
const notLocked = (kind: MemberKind, ids: string[]) =>
ids.filter((id) => !isLocked(project, kind, id));
const dids = new Set(notLocked("drawingIds", selection.drawings));
const wids = new Set(notLocked("wallIds", selection.walls));
const cids = new Set(notLocked("ceilingIds", selection.ceilings));
const oids = new Set(notLocked("openingIds", selection.openings));
const stids = new Set(notLocked("stairIds", selection.stairs));
const rmids = new Set(notLocked("roomIds", selection.rooms));
const exids = new Set(selection.solids);
const colids = new Set(notLocked("columnIds", selection.columns));
const rfids = new Set(notLocked("roofIds", selection.roofs));
const ctxids = new Set(selection.contextObjects);
// [149] Bäume (gesperrte bleiben).
const treeids = new Set(selection.trees.filter((id) => !(project.trees ?? []).find((t) => t.id === id)?.locked));
setProject(
opsMutation((p) => [
...removeItems(p, "drawings2d", dids),
...removeItems(p, "walls", wids),
...removeItems(p, "ceilings", cids),
...removeItems(p, "roofs", rfids),
...removeItems(p, "stairs", stids),
...removeItems(p, "rooms", rmids),
...removeItems(p, "extrudedSolids", exids),
...removeItems(p, "columns", colids),
// Öffnungen: eigene Auswahl löschen UND alle, deren Wirt (Wand, Dach, Decke [103]) entfällt.
...removeItems(p, "openings", (o) => oids.has(o.id) || wids.has(o.hostWallId) || (!!o.hostRoofId && rfids.has(o.hostRoofId)) || (!!o.hostCeilingId && cids.has(o.hostCeilingId))),
...removeItems(p, "context", ctxids),
...removeItems(p, "trees", treeids),
]),
);
};
// Tastatur im Auswahl-Werkzeug: Ctrl/Cmd+A = alles wählen, Entf/Backspace =
// Auswahl löschen — siehe state/useKeyboardShortcuts.ts.
useSelectAllAndDeleteShortcut({
activeTool,
transformActive: TRANSFORM_COMMANDS.has(engineView.commandName ?? ""),
project,
activeLevelId: activeLevel.id,
shortcutOverrides,
selection,
setSelection,
hasSelectionToDelete,
deleteSelection,
});
// Split der gewählten 2D-Elemente an einem Punkt in mehrere Stücke (shared von
// Ctrl+S und einem etwaigen Menü-Eintrag). Ersetzt jedes Quell-Drawing durch ≥1
// Ergebnis; neue Elemente werden ausgewählt. Wände sind ausgenommen (no-op).
const runSplit = (ids: string[]) => {
if (ids.length === 0) return;
let newIds: string[] = [];
applyChange((p) => {
const r = splitOps(p, ids);
newIds = r.selectIds;
return r.ops;
});
setSelection({ drawings: newIds, walls: [] });
};
// Ctrl/Cmd+S = Split, Ctrl/Cmd+J = Join der selektierten Drawing2D-Elemente —
// siehe state/useKeyboardShortcuts.ts.
useSplitJoinShortcut(selection.drawings, engine, runSplit, setSelection, shortcutOverrides);
// Ctrl/Cmd+Shift+U/D/I = Boolean Vereinigung/Subtraktion/Schnitt — siehe
// state/useKeyboardShortcuts.ts. (Ctrl/Cmd+C/V-Kopieren/Einfügen folgt weiter
// unten, nach `importDrawings`.)
// 2D-Boolean-Operation (Union / Subtract / Intersect) auf die gewählten
// geschlossenen Drawing2D anwenden. Reihenfolge der Auswahl = Reihenfolge in
// `selection.drawings` (für Differenz: erstes Element = Basis). Ersetzt die
// beteiligten Quellen durch das Ergebnis und selektiert die neuen Elemente.
// Braucht ≥2 geschlossene Flächen; sonst No-op.
const applyBoolean = (
op: (srcs: Drawing2D[]) => BooleanResult,
) => {
const order = selection.drawings;
if (order.length < 2) return;
const byId = new Map(project.drawings2d.map((d) => [d.id, d]));
// In Auswahl-Reihenfolge (Basis zuerst) auflösen.
const srcs = order
.map((id) => byId.get(id))
.filter((d): d is Drawing2D => d !== undefined);
const result = op(srcs);
if (result.replacedIds.length === 0) return; // <2 geschlossene → No-op
const replaced = new Set(result.replacedIds);
applyChange((p) => [...removeItems(p, "drawings2d", replaced), ...addItems("drawings2d", result.created)]);
setSelection({ drawings: result.created.map((d) => d.id), walls: [] });
};
useBooleanOpsShortcut(selection.drawings, project.drawings2d, applyBoolean, shortcutOverrides);
// „Eigenschaften übertragen" (2D-Kontextmenü) — dasselbe Zwischenablage-
// Muster wie beim Ebenen-Menü (`layerClipboard`), nur für den vollen
// Aussehen-Stil eines 2D-Elements (s. `editors/matchProps.ts`).
const copyDrawingStyle = () => {
const d = project.drawings2d.find((x) => x.id === selection.drawings[0]);
if (d) setDrawingStyleClipboard(readDrawingStyle(d));
};
const pasteDrawingStyle = () => {
if (!drawingStyleClipboard || selection.drawings.length === 0) return;
applyChange((p) => applyDrawingStyleOps(p, selection.drawings, drawingStyleClipboard));
};
// Objekt sperren/entsperren (Kontextmenü) — wirkt auf die GANZE aktuelle
// Auswahl (alle Elementarten, nicht nur 2D-Zeichnungen), ein Undo-Schritt.
// Anders als der Ebenen-/Geschoss-Sperrmodus (`DisplayMode`, session-lokal)
// ist `locked` hier ein persistiertes Feld am Element selbst, s.
// `state/objectLock.ts`.
const groupMembers = useMemo(() => toMembership(selection), [selection]);
const selectionLockMembers: Partial<Record<MemberKind, string[]>> = groupMembers;
const selectionLockIds = (
Object.entries(selectionLockMembers) as [MemberKind, string[]][]
).flatMap(([kind, ids]) => ids.map((id) => [kind, id] as const));
const selectionAllLocked =
selectionLockIds.length > 0 &&
selectionLockIds.every(([kind, id]) => isLocked(project, kind, id));
const toggleSelectionLock = () => {
if (selectionLockIds.length === 0) return;
applyChange((p) => lockMembersOps(p, selectionLockMembers, !selectionAllLocked));
};
// Ebene(n) der Auswahl ausblenden / isolieren (Kontextmenü). Nur bei geöffnetem
// Menü berechnet — bei Kataster-Importen (~10^5 Zeichnungen) nicht bei jedem Render.
const selectionLayerCodes = menu
? selectionCategoryCodes(project, groupMembers)
: [];
const hideSelectionLayers = () => {
if (selectionLayerCodes.length === 0) return;
const codes = new Set(selectionLayerCodes);
applyChange((p) => fieldOps(p, "layers", setCategoriesVisible(p.layers, codes, false)));
};
const isolateSelectionLayers = () => {
if (selectionLayerCodes.length === 0) return;
const codes = new Set(selectionLayerCodes);
applyChange((p) => fieldOps(p, "layers", isolateCategories(p.layers, codes)));
};
// „Nicht drucken"/„Drucken" (Kontextmenü) — nur `Drawing2D` kennt
// `noPrint` (Nutzer-Wunsch „Kein 'nicht druckend'-Flag im Modell"), daher
// simpler als die Sperre oben: direkt über `selection.drawings`.
const selectionAllNoPrint =
selection.drawings.length > 0 &&
selection.drawings.every((id) => project.drawings2d.find((d) => d.id === id)?.noPrint);
const toggleSelectionNoPrint = () => {
if (selection.drawings.length === 0) return;
const next = !selectionAllNoPrint;
applyChange((p) => patchItems(p, "drawings2d", selection.drawings, (d) => ({ ...d, noPrint: next })));
};
// „Bemassung lösen" ([38]): gewählte Bemassungen mit Bezügen auf Modell-Elemente.
const attachedDimensionIds = selection.drawings.filter((id) => {
const g = project.drawings2d.find((d) => d.id === id)?.geom;
return g?.shape === "dimension" && !!g.refs?.some(Boolean);
});
const detachDimensions = () => {
if (attachedDimensionIds.length) applyChange((p) => cmdMutation({ cmd: "dimdetach", ids: attachedDimensionIds }).toOps(p));
};
// Ctrl/Cmd+G / Ctrl/Cmd+Shift+G = Gruppieren/Auflösen (Vectorworks-artig,
// s. state/groupActions.ts). `applyGroupSelection` setzt nach dem Gruppieren/
// Auflösen alle betroffenen Auswahl-Kanäle auf einen Schlag.
const applyGroupSelection = (mem: GroupMembership, groupIds: string[]) =>
setSelection({ ...fromIdLists(mem), groups: groupIds });
useGroupShortcut(
project,
applyChange,
groupMembers,
selection.groups,
applyGroupSelection,
shortcutOverrides,
);
// Doppelklick auf ein gruppiertes Element → Gruppe betreten (Isolation):
// alles ausserhalb wird gedimmt/gesperrt gerendert (s. viewportContent.tsx/
// PlanView „greyed"-Pass) und lässt sich nicht mehr anwählen (s.
// useMouseSelectionHandlers.ts). Auswahl wird geleert, damit man sauber
// "in" der Gruppe startet.
const onEnterGroup = (hit: {
wallId?: string;
drawingId?: string;
ceilingId?: string;
roomId?: string;
stairId?: string;
columnId?: string;
roofId?: string;
}): boolean => {
const kind = hit.wallId
? "wallIds"
: hit.drawingId
? "drawingIds"
: hit.ceilingId
? "ceilingIds"
: hit.roomId
? "roomIds"
: hit.stairId
? "stairIds"
: hit.columnId
? "columnIds"
: hit.roofId
? "roofIds"
: null;
const id = hit.wallId ?? hit.drawingId ?? hit.ceilingId ?? hit.roomId ?? hit.stairId ?? hit.columnId ?? hit.roofId;
if (!kind || !id) return false;
const gid = containingGroupId(project, kind, id, groupPath);
if (!gid) return false;
setGroupPath([...groupPath, gid]);
applyGroupSelection({ ...EMPTY_MEMBERSHIP }, []);
return true;
};
// "Gruppe verlassen"-Knopf (oben links im Grundriss): verlässt genau EIN
// Isolations-Level (Vectorworks-Verhalten bei verschachtelten Gruppen).
const onLeaveGroup = () => {
setGroupPath(groupPath.slice(0, -1));
applyGroupSelection({ ...EMPTY_MEMBERSHIP }, []);
};
// Alt+Klick im Grundriss = Segment löschen (Schere): PlanView meldet das
// getroffene Drawing2D + den Modellpunkt; App ermittelt daraus die nächst-
// gelegene Kante (Kern `cmd_split.rs`) und entfernt sie. Geschlossene Form →
// offene Polylinie; bleiben <2 Punkte übrig, wird das Element gelöscht.
const onSegmentCut = (drawingId: string, model: Vec2) => {
let removed = false;
applyChange((p) => {
const r = cutSegmentOps(p, drawingId, model);
removed = r.removed;
return r.ops;
});
if (removed) setSelection({ drawings: [] });
};
// Transformations-Shortcuts (m/s/d, U/I/O/P-Modusleiste, „q" Messen) — siehe
// state/useKeyboardShortcuts.ts.
useTransformShortcuts(
activeTool,
hasTransformable(selection),
engine,
(id) => onCommandOption(id),
onRunCommand,
shortcutOverrides,
);
return {
hasSelectionToDelete,
deleteSelection,
applyBoolean,
copyDrawingStyle,
pasteDrawingStyle,
selectionLockMembers,
selectionLockIds,
selectionAllLocked,
toggleSelectionLock,
selectionLayerCodes,
hideSelectionLayers,
isolateSelectionLayers,
selectionAllNoPrint,
toggleSelectionNoPrint,
attachedDimensionIds,
detachDimensions,
onEnterGroup,
onLeaveGroup,
onSegmentCut,
};
}
+129
View File
@@ -0,0 +1,129 @@
// Einstellungen der App ([163], aus App.tsx herausgelöst): Start-Protokoll (Hinweis nach unsauberem
// Ende), Offline-Modus, KI-Zugriff, Hell/Dunkel, projektweite Linien-Einstellungen und der Abgleich mit
// dem nativen Einstellungsfenster (Tauri). Aufgerufen von `App.tsx`; die Rückgaben speisen den
// `SettingsDialog` (Browser) und `openSettings` die Menüs und Panels.
import { useEffect, useState, type RefObject } from "react";
import type { Project } from "../model/types";
import { lineEndsOf, setFieldIfChanged, type LineEnds } from "../core";
import { isOffline, setOffline } from "../net/net";
import { isTauriRuntime } from "../native/projectFile";
import { openSettingsWindowNative, useSettingsWindowHost } from "../native/settingsWindow";
import { useThemeModeState } from "../theme/useThemeMode";
import type { PlanViewHandle } from "../views/plan/PlanView";
import { t } from "../i18n";
import type { RootState } from "./appStore";
import { setAiAccessEnabled, setAiView, useAiAccess } from "./aiAccess";
import { reconcileLayout } from "./layoutSlice";
import { markSessionClean, markSessionStart } from "./startupGuard";
import type { useDialogState } from "./useDialogState";
import type { useTopBarState } from "./useTopBarState";
type TopBar = ReturnType<typeof useTopBarState>;
export function useSettingsHost(opts: {
project: Project;
applyChange: RootState["applyChange"];
groupChanges: RootState["groupChanges"];
notify: RootState["notify"];
layout: RootState["layout"];
setLayout: RootState["setLayout"];
marqueeColor: TopBar["marqueeColor"];
setMarqueeColor: TopBar["setMarqueeColor"];
snapColor: TopBar["snapColor"];
setSnapColor: TopBar["setSnapColor"];
planViewRef: RefObject<PlanViewHandle>;
setSettingsOpen: ReturnType<typeof useDialogState>["setSettingsOpen"];
}) {
const {
project,
applyChange,
groupChanges,
notify,
layout,
setLayout,
marqueeColor,
setMarqueeColor,
snapColor,
setSnapColor,
planViewRef,
setSettingsOpen,
} = opts;
// Start-Protokoll: war der letzte Lauf unsauber beendet, kurz darauf hinweisen (Autosave sichert
// die Daten); beim Schliessen die Sitzung als sauber markieren.
useEffect(() => {
const r = markSessionStart();
if (r.previousCrashed) notify(t("startup.previousCrashed"), "warning");
const clean = () => markSessionClean();
window.addEventListener("pagehide", clean);
return () => window.removeEventListener("pagehide", clean);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
// Offline-Modus (Einstellungen → Allgemein): sperrt alle entfernten Abrufe (src/net/net.ts).
const [offline, setOfflineState] = useState<boolean>(() => isOffline());
const onOfflineChange = (v: boolean) => {
setOffline(v);
setOfflineState(v);
};
// [9] KI-Zugriff (MCP-Brücke, Einstellungen → Allgemein): Stand für die Einstellungen; die
// Planansicht für `zoom_to` anmelden.
const aiAccessState = useAiAccess();
const aiAccess = { enabled: aiAccessState.enabled, token: aiAccessState.token, port: aiAccessState.port, status: aiAccessState.status };
useEffect(() => {
setAiView({ fitBounds: (pts) => planViewRef.current?.fitBounds(pts) });
return () => setAiView(null);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
// Hell/Dunkel (Einstellungen → Darstellung). Standard Hell (styles.css);
// Dunkel ist Opt-in und persistiert in localStorage.
const { themeMode, setThemeMode } = useThemeModeState();
// Einstellungen als eigenes natives Fenster (Tauri) statt Overlay-Dialog —
// hält es (falls offen) synchron zu den betroffenen Feldern, wendet dessen
// Befehle auf die echten Setter an (siehe native/settingsWindow.ts).
const setScaleLineWeights = (on: boolean) =>
applyChange((p) => setFieldIfChanged(p, "scaleLineWeights", on ? true : undefined));
// [146] Linienenden/-ecken: Standard (flach, Gehrung) = Feld weglassen; beide Felder ein Undo-Schritt.
const setLineEnds = (e: LineEnds) =>
groupChanges(() => {
applyChange((p) => setFieldIfChanged(p, "lineCap", e.cap === "butt" ? undefined : e.cap));
applyChange((p) => setFieldIfChanged(p, "lineJoin", e.join === "miter" ? undefined : e.join));
});
useSettingsWindowHost(
{
themeMode,
marqueeColor,
snapColor,
referenceElevationMasl: project.referenceElevationMasl,
scaleLineWeights: project.scaleLineWeights === true,
lineEnds: lineEndsOf(project),
offline,
aiAccess,
layout,
},
{
onThemeModeChange: setThemeMode,
onMarqueeColorChange: setMarqueeColor,
onSnapColorChange: setSnapColor,
onReferenceElevationChange: (n) => applyChange((p) => setFieldIfChanged(p, "referenceElevationMasl", n)),
onScaleLineWeightsChange: setScaleLineWeights,
onLineEndsChange: setLineEnds,
onOfflineChange,
onAiAccessChange: setAiAccessEnabled,
onApplyLayout: (l) => setLayout(reconcileLayout(l)),
},
);
const openSettings = () => {
if (isTauriRuntime()) {
void openSettingsWindowNative();
} else {
setSettingsOpen(true);
}
};
return { themeMode, setThemeMode, offline, onOfflineChange, aiAccess, setScaleLineWeights, setLineEnds, openSettings };
}
+45
View File
@@ -0,0 +1,45 @@
// Status-Leiste der App ([163], aus App.tsx herausgelöst): Werkzeug-Hinweis („Auswahl: n Wände")
// und aktive Ebene (Kategorie der einzeln gewählten Wand, sonst die aktive Kategorie). Gewählte Wände,
// die es nicht mehr gibt, fallen heraus. Aufgerufen von `App.tsx`; die Werte gehen an `StatusBar`.
import { useMemo } from "react";
import type { Project } from "../model/types";
import { categoryLabel } from "../model/layers";
import { t } from "../i18n";
import type { useSelectionState } from "./useSelectionState";
export function useStatusBarInfo(opts: {
project: Project;
selection: ReturnType<typeof useSelectionState>["selection"];
activeCategoryCode: string;
}) {
const { project, selection, activeCategoryCode } = opts;
// Tatsächlich (noch) existierende gewählte Wände — IDs, die es nicht mehr gibt
// (z. B. nach Löschen/Geschosswechsel), fallen heraus.
const selectedWalls = useMemo(() => {
const ids = new Set(selection.walls);
return project.walls.filter((w) => ids.has(w.id));
}, [project.walls, selection.walls]);
const selectionCount = selectedWalls.length;
// Erste gewählte Wand (für Status-Leiste / Kontextmenü-Aktionen mit Einzelbezug).
const selectedWall = selectedWalls[0] ?? null;
// Aktive Ebene (Kategorie) der Status-Leiste: die Kategorie der (ersten)
// gewählten Wand, sonst „—" (es gibt keine eigenständige Kategorie-Selektion).
const activeLayerName =
selectionCount === 1 && selectedWall
? categoryLabel(project.layers, selectedWall.categoryCode)
: categoryLabel(project.layers, activeCategoryCode);
// Kontextueller Werkzeug-Hinweis (links). Zeigt die Anzahl gewählter Wände:
// 0 → „Auswahl", 1 → „Auswahl: 1 Wand", n → „Auswahl: n Wände".
const toolHint =
selectionCount === 0
? t("status.selection")
: t("status.selectionN", {
n: selectionCount,
noun: selectionCount === 1 ? t("status.wall") : t("status.walls"),
});
return { toolHint, activeLayerName };
}
+68
View File
@@ -0,0 +1,68 @@
// Text-Ziel der Oberleisten-Formatierung ([163], aus App.tsx herausgelöst): der Stempel-Text des
// einzeln gewählten Raums oder ein gewählter freier Text, mit einem Setter, der live ins Projekt
// schreibt. Ohne passendes Element `null` (die Leiste setzt dann nur Vorgaben). Aufgerufen von
// `App.tsx`; das Ergebnis geht an `ViewRibbonTab`.
import { useMemo } from "react";
import type { Project, Room } from "../model/types";
import { docFromText, plainText } from "../text/richText";
import type { RichTextDoc } from "../text/richText";
import { useEventBundle } from "./useEvent";
import type { useProjectActions } from "./useProjectActions";
type ProjectActions = ReturnType<typeof useProjectActions>;
export function useTextTarget(opts: {
project: Project;
selectedRoom: Room | null;
selectedDrawingId: string | null;
setRoomStampDoc: ProjectActions["setRoomStampDoc"];
updateDrawing2D: ProjectActions["updateDrawing2D"];
}) {
const { project, selectedRoom, selectedDrawingId, setRoomStampDoc, updateDrawing2D } = opts;
// Text-Ziel der Oberleisten-Text-Gruppe: der Stempel-Text des (einzeln)
// gewählten Raums. Ohne aktive Editor-Auswahl wirkt Formatierung auf das ganze
// Doc (range: null). Ist kein Raum gewählt → null (Controls setzen nur
// Defaults). Der Setter schreibt live in den Store.
// Store-Aktionen mit stabiler Identität ([121]): sonst wäre `textTarget` je Render neu.
const textActions = useEventBundle({ setRoomStampDoc, updateDrawing2D });
const textTarget = useMemo(() => {
if (selectedRoom) {
return {
doc: selectedRoom.stampDoc ?? docFromText(selectedRoom.name),
range: null,
apply: (doc: RichTextDoc) => textActions.setRoomStampDoc(selectedRoom.id, doc),
};
}
// Selektierter freier Text/Textspalte: die Oberleisten-Formatier-Gruppe wirkt
// auf Schriftfamilie/fett/kursiv/Farbe des ganzen Texts. Die GRÖSSE bleibt
// bewusst über die Modell-Höhe (Meter, height) geführt — nicht über sizePt,
// damit der Text im Massstab bleibt (Punkt-Grössen wären massstabslos).
if (selectedDrawingId) {
const d = project.drawings2d.find((x) => x.id === selectedDrawingId);
if (d && d.geom.shape === "text") {
const g = d.geom;
// Trägt das Element bereits ein reiches Doc (Doppelklick-Editor), wirkt
// die Oberleiste per Bereichs-Operation (toggleMark/applyMark) DARAUF —
// Mischformatierung anderer Runs bleibt erhalten. Ohne Doc (Alt-Element)
// bleibt das bisherige Uniform-Verhalten (ein `marks`-Objekt fürs Ganze).
const doc = g.doc ?? docFromText(g.text, g.marks ?? {});
return {
doc,
range: null,
apply: (newDoc: RichTextDoc) => {
const runMarks = newDoc.paragraphs.flatMap((p) => p.runs)[0]?.marks ?? {};
const marks = { ...runMarks };
delete marks.sizePt; // Grösse folgt der Modell-Höhe, nicht dem pt-Wert.
const patch = g.doc
? { doc: newDoc, text: plainText(newDoc), marks }
: { text: plainText(newDoc), marks };
textActions.updateDrawing2D(d.id, { geom: { ...g, ...patch } });
},
};
}
}
return null;
}, [selectedRoom, textActions, selectedDrawingId, project.drawings2d]);
return textTarget;
}
+132
View File
@@ -0,0 +1,132 @@
// Werkzeug-Eingabe → Befehls-Engine ([163], aus App.tsx herausgelöst): die Plan-Handler
// (`toolHandlers`: Bewegen, Klick, Rechtsklick), die Werkzeugwahl der Palette (`onSelectTool`),
// Ribbon-Befehle (`onRunCommand`) und die 3D-Arbeitsebene (`onWorkplanePoint`). Alles mündet in
// dieselbe `CommandEngine` aus `useCommandEngineHost`. Aufgerufen von `App.tsx` direkt nach dem
// Engine-Host; `TRANSFORM_COMMANDS` nutzen auch `useSelectionCommands` und die Effekte in App.
import type { RefObject } from "react";
import type { Vec2 } from "../model/types";
import { toolInfo } from "../tools/tools";
import type { ToolDraft, ToolHandlers, ToolId } from "../tools/types";
import type { EngineMods } from "../commands/engine";
import type { useCommandEngineHost } from "./useCommandEngineHost";
type EngineHost = ReturnType<typeof useCommandEngineHost>;
/**
* Befehlsname für ein gekoppeltes Werkzeug (oder null). Die Zeichen-Werkzeuge der Palette sind
* Engine-Befehle: ein Klick auf das Werkzeug startet diesen Befehl (`tools/tools.ts`, [123]).
*/
function coupledCommandFor(id: ToolId): string | null {
return toolInfo(id).command ?? null;
}
/** Transformations-Befehle der Auswahl: Rechtsklick bricht ab, Geschoss-/Ansichtswechsel auch. */
export const TRANSFORM_COMMANDS = new Set(["move", "rotate", "mirror"]);
export function useToolInput(opts: {
engineRef: EngineHost["engineRef"];
engine: EngineHost["engine"];
commandLineRef: EngineHost["commandLineRef"];
activeTool: ToolId;
setActiveTool: (id: ToolId) => void;
draft: ToolDraft | null;
imageInputRef: RefObject<HTMLInputElement | null>;
}) {
const { engineRef, engine, commandLineRef, activeTool, setActiveTool, draft, imageInputRef } = opts;
const toolHandlers: ToolHandlers = {
onToolMove: (raw, _pxPerMeter, mods) => {
// Läuft ein Befehl, übernimmt die Engine die Plan-Eingabe (ein Eingabepfad).
// Modifikatoren (Shift=Ortho, Ctrl=Snap aus) mitgeben, damit auch der ERSTE
// Punkt sauber snappt bzw. unterdrückt werden kann. Ohne Befehl: nur Hover.
engineRef.current?.move(raw, { shift: mods.shift, ctrl: mods.ctrl });
},
onToolClick: (raw, _pxPerMeter, mods) => {
const em = { shift: mods.shift, ctrl: mods.ctrl };
if (engineRef.current?.isActive()) {
engineRef.current.pick(raw, em);
return;
}
// Gekoppeltes Werkzeug, aber der Befehl ist (nach Commit) beendet: denselben
// Befehl neu starten und den Klick als ersten Punkt durchreichen — so bleibt
// das Werkzeug wie in einem CAD armiert. Der erste Punkt snappt ebenfalls.
const cmd = coupledCommandFor(activeTool);
if (cmd) {
engineRef.current?.start(cmd);
engineRef.current?.pick(raw, em);
}
},
onToolCommit: () => {
// Rechtsklick im Viewport = Enter an die Engine (§2.3); in einer Transformation = abbrechen.
const eng = engineRef.current;
if (!eng?.isActive()) return;
if (TRANSFORM_COMMANDS.has(eng.activeCommandName() ?? "")) eng.cancel();
else eng.confirm();
},
draft,
};
// ── GUI-Werkzeug ↔ Befehls-Engine (ein Eingabe-Hub) ───────────────────────
// Ein Klick auf ein gekoppeltes Zeichen-Werkzeug (Wand/Linie/Rechteck/Polylinie)
// STARTET den passenden Befehl in der Engine und fokussiert das Befehlsfeld
// („Dialog drin"). „Auswahl" beendet einen laufenden Befehl (Auswahl-Modus).
const onSelectTool = (id: ToolId) => {
// Erneuter Klick auf das bereits AKTIVE Werkzeug schaltet zurück auf
// „Auswahl" (Nutzer-Wunsch) — statt das Werkzeug einfach neu zu starten.
if (id !== "select" && id === activeTool) id = "select";
if (id === "image") {
// Datei-Auswahl ist async (Dateidialog) — kein Klick-Platzieren wie bei
// den übrigen Zeichen-Werkzeugen, daher hier abgefangen statt über die
// Befehls-Engine/`activeTool` zu laufen (s. tools/tools.ts).
imageInputRef.current?.click();
return;
}
const cmd = coupledCommandFor(id);
if (cmd) {
// Den gekoppelten Befehl in DERSELBEN Engine starten wie das Tippen von
// „line" — Klick und Tippen münden in denselben Befehl. Das aktive-Tool-
// Highlight spiegelt den laufenden Befehl (activeTool = id); toolHandlers
// leiten Move/Pick/Confirm an die Engine (siehe oben).
engine.start(cmd);
setActiveTool(id);
// Befehlsfeld fokussieren: getippte Präzisionseingabe steht sofort bereit.
// Nach dem Render des aktiven Prompts fokussieren (nächster Tick).
requestAnimationFrame(() => commandLineRef.current?.focus());
return;
}
// „Auswahl": laufenden Befehl beenden.
if (engine.isActive()) engine.cancel();
setActiveTool(id);
};
// Ribbon-Befehl (Ändern-Gruppe u. a.): startet einen Engine-Befehl OHNE
// eigenes Werkzeug (kein ToolId). Läuft über DIESELBE Engine wie das Tippen des
// Befehls; das Werkzeug-Highlight fällt auf „Auswahl" zurück, das Aktiv-
// Highlight des Ribbon-Befehls spiegelt der laufende Befehl (engineView).
// Bewegen/Drehen/Spiegeln sind gewöhnliche Befehle ([123]); ohne Auswahl starten sie nicht
// (Hinweis über den Engine-Host) und das Werkzeug bleibt, wie es ist.
const onRunCommand = (name: string) => {
if (!engine.start(name) && TRANSFORM_COMMANDS.has(name)) return;
setActiveTool("select");
requestAnimationFrame(() => commandLineRef.current?.focus());
};
// 3D-Viewport als Erstellungs-Fläche: der Viewport projiziert den Cursor auf
// die Geschoss-Arbeitsebene und liefert einen rohen Modell-`Vec2`; wir füttern
// ihn in DIESELBE ansichts-agnostische CommandEngine wie PlanView (move/pick).
// Snapping/Tab-Felder/Commit laufen unverändert über den EngineHost; die neuen
// Elemente landen auf dem aktiven Geschoss (host.context().level).
const onWorkplanePoint = (kind: "move" | "pick", model: Vec2, mods?: EngineMods) => {
const eng = engineRef.current;
if (!eng?.isActive()) return;
if (kind === "move") eng.move(model, mods);
else eng.pick(model, mods);
};
const onWorkplaneConfirm = () => {
// Rechtsklick-ohne-Drag/Doppelklick im 3D — dasselbe Verhalten wie `onToolCommit` im 2D-Plan.
toolHandlers.onToolCommit();
};
return { toolHandlers, onSelectTool, onRunCommand, onWorkplanePoint, onWorkplaneConfirm };
}