[121] App.tsx zerlegt, Oberleiste/Statusleiste/Befehlszeile/Werkzeuge memoisiert

Herausgelöst: Befehls-Engine (state/useCommandEngineHost), 3D-Griffe (state/useGrip3dEditing),
Layout-Blatt (state/useSheetPane), Darstellungs-Resolver (state/useDisplayResolvers).
Stabile Handler über useEvent/useEventBundle; memo für TopBar (nur noch projectName),
AppMenuBar, ViewRibbonTab, StatusBar, CommandLine, Werkzeug-/Befehls-Icons, Overlays.
Panels: PanelHostProvider mit Store, usePanelHostSelect/usePanelHostAction — die
Werkzeug-Palette abonniert nur ihre Felder. Wand-Änderung: 413 → 291 Renders.
This commit is contained in:
Claude committed 2026-11-03 20:50:00 +00:00
1 parent 0775339b40
commit 3ec5f42609
21 files changed
+1566 -1072

No files matched your search

+372 -974
View File
File diff suppressed because it is too large. Load diff
+11 -3
View File
@@ -115,6 +115,15 @@ function sameStep(a: CommandState, b: CommandState): boolean {
}
}
/** Ansicht ohne laufenden Befehl — unveränderlich geteilt. */
const IDLE_VIEW: EngineView = Object.freeze({
active: false,
promptKey: null,
options: Object.freeze([]) as unknown as EngineView["options"],
commandName: null,
fields: Object.freeze([]) as unknown as EngineView["fields"],
}) as EngineView;
export class CommandEngine {
private host: EngineHost;
private command: Command | null = null;
@@ -165,9 +174,8 @@ export class CommandEngine {
/** Lesender Schnappschuss für die Command-Line. */
view(): EngineView {
if (!this.command || !this.state) {
return { active: false, promptKey: null, options: [], commandName: null, fields: [] };
}
// Ruhe: immer dasselbe Objekt (stabile Identität für memoisierte Befehlszeile, [121]).
if (!this.command || !this.state) return IDLE_VIEW;
this.syncFields();
const defs = this.currentFields();
// Live-Werte (Maus-Vorschau) für ungelockte Felder, falls der Befehl sie
+4 -4
View File
@@ -23,7 +23,7 @@ import type { CSSProperties, PointerEvent as ReactPointerEvent } from "react";
import { PanelFrame } from "./PanelFrame";
import { TabStrip } from "./TabStrip";
import { getPanel } from "./registry";
import { PanelHostContext } from "./types";
import { PanelHostProvider } from "./host";
import type {
DisplayMode,
DockId,
@@ -57,7 +57,7 @@ export interface DockProps {
/**
* Baut den Host-Context-Wert für eine Gruppe (passend zu ihrem aktiven Tab).
* App reicht hier `hostWithMode(...)` herein; das Dock wickelt jede Gruppe in
* einen eigenen <PanelHostContext.Provider>.
* einen eigenen <PanelHostProvider>.
*/
buildHost: (activeTab: string | null) => PanelHost;
/** Generischer Kontext, den der PanelFrame an `def.render` weiterreicht. */
@@ -223,7 +223,7 @@ export function Dock({
onStartDrag={onStartTabDrag}
/>
{def ? (
<PanelHostContext.Provider value={buildHost(group.activeTab)}>
<PanelHostProvider value={buildHost(group.activeTab)}>
<PanelFrame
def={def}
ctx={ctx}
@@ -232,7 +232,7 @@ export function Dock({
onDisplayModeChange(group.activeTab, m)
}
/>
</PanelHostContext.Provider>
</PanelHostProvider>
) : (
<div className="panel-frame panel-frame-empty" />
)}
+16 -9
View File
@@ -11,9 +11,9 @@
// Bezeichner englisch, UI-Text/Kommentare deutsch (CONVENTIONS.md). Alle sichtbaren
// Texte über t(...).
import { useState } from "react";
import { useState, memo } from "react";
import { t } from "../i18n";
import { usePanelHost } from "./host";
import { usePanelHostAction, usePanelHostSelect } from "./host";
import type { ToolId } from "./host";
import { toolInfo } from "../tools/tools";
import { getCommand } from "../commands/registry";
@@ -23,7 +23,7 @@ import { CommandIcon } from "../ui/ribbon/CommandIcon";
// Keine echten Asset-Icons vorhanden: schlichte Inline-SVG-Glyphen je Werkzeug
// (~16×16, stroke=currentColor, fill=none), damit das Icon die Textfarbe der
// Zeile übernimmt.
export function ToolIcon({ id }: { id: ToolId }) {
export const ToolIcon = memo(function ToolIcon({ id }: { id: ToolId }) {
const common = {
width: 16,
height: 16,
@@ -333,7 +333,7 @@ export function ToolIcon({ id }: { id: ToolId }) {
default:
return null;
}
}
});
// ── Kategorien ───────────────────────────────────────────────────────────────
// Werkzeuge/Befehle in drei Rubriken sortiert (Nutzerwunsch: „sortiere nach 2D
@@ -383,8 +383,15 @@ function loadView(): ToolsView {
// ── Panel ────────────────────────────────────────────────────────────────────
export function ToolsPanel() {
const host = usePanelHost();
export const ToolsPanel = memo(function ToolsPanel() {
// Nur die eigenen Felder abonnieren ([121]): eine Op am Projekt rendert die Palette nicht neu.
const host = usePanelHostSelect((h) => ({
activeTool: h.activeTool,
toolsEnabled: h.toolsEnabled,
activeCommand: h.activeCommand,
}));
const onSelectTool = usePanelHostAction("onSelectTool");
const onRunCommand = usePanelHostAction("onRunCommand");
const [view, setView] = useState<ToolsView>(loadView);
const chooseView = (v: ToolsView) => {
@@ -411,7 +418,7 @@ export function ToolsPanel() {
className={"tp-item" + (active ? " active" : "") + (disabled ? " disabled" : "")}
title={view === "icons" ? label : title}
disabled={disabled}
onClick={() => host.onSelectTool(id)}
onClick={() => onSelectTool(id)}
>
<ToolIcon id={id} />
<span className="tp-label">{label}</span>
@@ -431,7 +438,7 @@ export function ToolsPanel() {
type="button"
className={"tp-item" + (active ? " active" : "")}
title={label}
onClick={() => host.onRunCommand(name)}
onClick={() => onRunCommand(name)}
>
<CommandIcon name={name} />
<span className="tp-label">{label}</span>
@@ -487,4 +494,4 @@ export function ToolsPanel() {
</section>
</div>
);
}
});
+95 -1
View File
@@ -11,7 +11,7 @@
// (siehe Report am Ende der Aufgabe). Bezeichner englisch, Kommentare deutsch
// (CONVENTIONS.md).
import { useContext } from "react";
import { createContext, createElement, useContext, useLayoutEffect, useRef, useSyncExternalStore, type ReactNode } from "react";
import { PanelHostContext } from "./types";
import type { DisplayMode, PanelHost } from "./types";
import type {
@@ -858,3 +858,97 @@ export function hostWithMode(
};
return value as unknown as PanelHost;
}
// ── Host-Store: selektives Abonnieren ([121]) ─────────────────────────────────
//
// Der Host-Wert ist bei jedem App-Render ein neues Objekt (Projekt, Handler …); wer
// `usePanelHost()` liest, rendert darum bei JEDER Op neu. Panels, die nur wenige Felder
// brauchen (Werkzeug-Palette), lesen stattdessen über `usePanelHostSelect` (Wert-Felder,
// flach verglichen) und `usePanelHostAction` (Handler mit stabiler Identität, ruft beim
// Aufruf die aktuelle Fassung) — zusammen mit `memo` rendern sie dann nur, wenn sich ihre
// Felder ändern. `PanelHostProvider` stellt beides bereit (Context wie bisher + Store).
interface PanelHostStore {
get: () => PanelHostValue;
subscribe: (cb: () => void) => () => void;
}
const PanelHostStoreContext = createContext<PanelHostStore | null>(null);
/** Ersetzt `<PanelHostContext.Provider>`: gleicher Context, dazu der Store fürs selektive Lesen. */
export function PanelHostProvider({ value, children }: { value: PanelHost; children?: ReactNode }) {
const current = useRef(value);
// Im Render nachführen: Kinder, die im selben Durchgang rendern, lesen schon den neuen Wert.
current.current = value;
const listeners = useRef(new Set<() => void>());
const store = useRef<PanelHostStore | null>(null);
if (store.current === null) {
store.current = {
get: () => current.current as unknown as PanelHostValue,
subscribe: (cb) => {
listeners.current.add(cb);
return () => listeners.current.delete(cb);
},
};
}
// Nach dem Commit memoisierte Leser benachrichtigen (die prüfen selbst, ob ihre Auswahl sich änderte).
useLayoutEffect(() => {
for (const cb of listeners.current) cb();
}, [value]);
return createElement(
PanelHostContext.Provider,
{ value },
createElement(PanelHostStoreContext.Provider, { value: store.current }, children),
);
}
function useHostStore(): PanelHostStore {
const store = useContext(PanelHostStoreContext);
if (store === null) {
throw new Error("usePanelHostSelect: außerhalb von <PanelHostProvider> verwendet.");
}
return store;
}
function shallowEqual(a: unknown, b: unknown): boolean {
if (Object.is(a, b)) return true;
if (typeof a !== "object" || typeof b !== "object" || a === null || b === null) return false;
const ka = Object.keys(a);
const kb = Object.keys(b);
if (ka.length !== kb.length) return false;
for (const k of ka) {
if (!Object.is((a as Record<string, unknown>)[k], (b as Record<string, unknown>)[k])) return false;
}
return true;
}
/**
* Liest eine Auswahl aus dem Host; rendert nur neu, wenn sie sich (flach verglichen) ändert.
* Für Wert-Felder — Handler über {@link usePanelHostAction}.
*/
export function usePanelHostSelect<T>(select: (host: PanelHostValue) => T): T {
const store = useHostStore();
const selectRef = useRef(select);
selectRef.current = select;
const cache = useRef<{ value: T } | null>(null);
const snapshot = () => {
const next = selectRef.current(store.get());
if (cache.current && shallowEqual(cache.current.value, next)) return cache.current.value;
cache.current = { value: next };
return next;
};
return useSyncExternalStore(store.subscribe, snapshot, snapshot);
}
type HostFn<K extends keyof PanelHostValue> = Extract<PanelHostValue[K], (...args: never[]) => unknown>;
/** Handler des Hosts mit stabiler Identität (ruft beim Aufruf die aktuelle Fassung). */
export function usePanelHostAction<K extends keyof PanelHostValue>(name: K): HostFn<K> {
const store = useHostStore();
const fn = useRef<HostFn<K> | null>(null);
if (fn.current === null) {
fn.current = ((...args: unknown[]) =>
(store.get()[name] as unknown as (...a: unknown[]) => unknown)(...args)) as HostFn<K>;
}
return fn.current;
}
+3 -3
View File
@@ -25,7 +25,7 @@
//
// Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md).
import { useCallback, useRef, useState } from "react";
import { useCallback, useRef, useState, memo } from "react";
import type { DockId } from "./types";
import { getPanel } from "./registry";
import { t } from "../i18n";
@@ -253,7 +253,7 @@ export function usePanelDrag(cb: PanelDragCallbacks) {
* reagiert nicht auf Zeiger (pointer-events: none), damit die Trefferprüfung
* weiter die darunterliegenden Tab-Leisten/Zonen erreicht.
*/
export function DragOverlay({ drag }: { drag: ReturnType<typeof usePanelDrag>["drag"] }) {
export const DragOverlay = memo(function DragOverlay({ drag }: { drag: ReturnType<typeof usePanelDrag>["drag"] }) {
if (!drag) return null;
const def = getPanel(drag.panelId);
const label = def ? t(def.title) : drag.panelId;
@@ -295,4 +295,4 @@ export function DragOverlay({ drag }: { drag: ReturnType<typeof usePanelDrag>["d
</div>
</div>
);
}
});
+355
View File
@@ -0,0 +1,355 @@
// Befehls-Engine der App ([121] aus App.tsx herausgelöst): EINE stabile `CommandEngine`-Instanz
// mit Host (Kontext, Fang, Commit, Text-Fokus), die Nutzer-Übersteuerungen der Befehls-Kürzel und
// Tastatur-Shortcuts (localStorage, Abgleich mit dem nativen Einstellungs-Fenster), das Neurendern
// bei Engine-Änderungen und das Freigeben des Befehlsfelds nach Befehlsende.
//
// Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md).
import { useEffect, useRef, useState, type RefObject } from "react";
import type { DrawingLevel, Project } from "../model/types";
import type { SnapSettings, ToolDraft } from "../tools/types";
import type { TransformSelection } from "../tools/transform";
import { computeSnap } from "../tools/snapping";
import { unitsForLevel } from "../tools/displayUnits";
import { cmdMutation, type ProjectMutation } from "../core";
import { CommandEngine } from "../commands/engine";
import type { EngineHost } from "../commands/engine";
import type { CommandContext } from "../commands/types";
import type { CommandLineHandle } from "../ui/CommandLine";
import type { PlanViewHandle } from "../views/plan/PlanView";
import { loadAliasOverrides, saveAliasOverrides } from "./commandAliasOverrides";
import { loadShortcutOverrides, saveShortcutOverrides, type ShortcutOverrides } from "./keyboardShortcuts";
import { useCommandKeys } from "./commandKeys";
import { t } from "../i18n";
import type { useSelectionState } from "./useSelectionState";
import type { useContextMenuState } from "../menus/useContextMenuState";
/**
* Auswahl für Transformationen/Befehle: im Schnitt/in der Ansicht nur die
* 2D-Elemente der Ebene. Bauteile (Wand/Decke/…) sind dort zwar anwählbar
* (Objekt-Info, Löschen), leben aber im Grundriss-Raum — ein im Schnitt-Blatt
* gemessenes Delta/Drehzentrum würde sie an eine falsche Stelle setzen.
*/
function sheetOnlySelection(level: DrawingLevel, sel: TransformSelection): TransformSelection {
if (level.kind !== "section" && level.kind !== "elevation") return sel;
return {
wallIds: [],
drawingId: sel.drawingId,
drawingIds: sel.drawingIds,
extrudedSolidId: null,
columnId: null,
ceilingIds: [],
roofIds: [],
stairIds: [],
roomIds: [],
};
}
type Sel = ReturnType<typeof useSelectionState>;
type Menu = ReturnType<typeof useContextMenuState>;
export function useCommandEngineHost(opts: {
project: Project;
activeLevel: DrawingLevel;
activeCategoryCode: string;
activeLineStyleId: string;
activeWallTypeId: string;
visibleCodes: Set<string>;
snap: SnapSettings;
sel: Pick<
Sel,
| "selectedWallIds"
| "selectedDrawingId"
| "selectedDrawingIds"
| "selectedExtrudedSolidId"
| "selectedColumnId"
| "selectedCeilingIds"
| "selectedRoofIds"
| "selectedStairIds"
| "selectedRoomIds"
| "groupPath"
| "setSelectedWallIds"
| "setSelectedCeilingIds"
| "setSelectedOpeningIds"
| "setSelectedStairIds"
| "setSelectedRoomIds"
| "setSelectedExtrudedSolidIds"
| "setSelectedColumnIds"
| "setSelectedRoofIds"
| "setSelectedContextObjectIds"
| "setSelectedSectionLineIds"
| "setSelectedDrawingId"
>;
setProject: (m: ProjectMutation) => void;
setDraft: (d: ToolDraft | null) => void;
notify: (msg: string, kind: "info" | "warning" | "error") => void;
planViewRef: RefObject<PlanViewHandle>;
setEditTextId: Menu["setEditTextId"];
setEditTextMinHeightM: Menu["setEditTextMinHeightM"];
}) {
const {
project,
activeLevel,
activeCategoryCode,
activeLineStyleId,
activeWallTypeId,
visibleCodes,
snap,
setProject,
setDraft,
notify,
planViewRef,
setEditTextId,
setEditTextMinHeightM,
} = opts;
const {
selectedWallIds,
selectedDrawingId,
selectedDrawingIds,
selectedExtrudedSolidId,
selectedColumnId,
selectedCeilingIds,
selectedRoofIds,
selectedStairIds,
selectedRoomIds,
groupPath,
setSelectedWallIds,
setSelectedCeilingIds,
setSelectedOpeningIds,
setSelectedStairIds,
setSelectedRoomIds,
setSelectedExtrudedSolidIds,
setSelectedColumnIds,
setSelectedRoofIds,
setSelectedContextObjectIds,
setSelectedSectionLineIds,
setSelectedDrawingId,
} = opts.sel;
// ── Command-Engine (Rhino-artiges Befehlssystem) ──────────────────────────
// Eine stabile Engine-Instanz; alle Live-Werte (Kontext/Snap/visibleCodes)
// liest der Host über einen jeweils aktualisierten `latest`-Ref, damit die
// Instanz nicht je Render neu gebaut werden muss. Die Engine speist Picks +
// getippte Eingabe in DENSELBEN Schritt (ein Eingabepfad). Koexistenz: läuft
// ein Befehl, übernimmt er die linke Maustaste der Plan-Ansicht über denselben
// toolHandlers-Pfad wie die Alt-Tools (siehe unten).
const cmdLatest = useRef({
project,
activeLevel,
activeCategoryCode,
activeLineStyleId,
activeWallTypeId,
visibleCodes,
snap,
selectedWallIds,
selectedDrawingId,
selectedDrawingIds,
selectedExtrudedSolidId,
selectedColumnId,
selectedCeilingIds,
selectedRoofIds,
selectedStairIds,
selectedRoomIds,
groupPath,
setProject,
setDraft,
});
cmdLatest.current = {
project,
activeLevel,
activeCategoryCode,
activeLineStyleId,
activeWallTypeId,
visibleCodes,
snap,
selectedWallIds,
selectedDrawingId,
selectedDrawingIds,
selectedExtrudedSolidId,
selectedColumnId,
selectedCeilingIds,
selectedRoofIds,
selectedStairIds,
selectedRoomIds,
groupPath,
setProject,
setDraft,
};
const commandLineRef = useRef<CommandLineHandle>(null);
const engineRef = useRef<CommandEngine | null>(null);
if (engineRef.current === null) {
const host: EngineHost = {
context: (lastPoint): CommandContext => {
const c = cmdLatest.current;
return {
project: c.project,
level: c.activeLevel,
defaultCategoryCode: c.activeCategoryCode,
activeLineStyleId: c.activeLineStyleId,
activeWallTypeId: c.activeWallTypeId,
lastPoint,
// Vorab gesetzte Auswahl aus dem Store (Rhino: erst selektieren, dann
// Befehl). Move/Copy/Offset operieren darauf.
// Im Schnitt/in der Ansicht nur die 2D-Elemente der Ebene: Bauteile
// leben im Grundriss-Raum, ein Schnitt-Delta wäre dort falsch.
selection: sheetOnlySelection(c.activeLevel, {
wallIds: c.selectedWallIds,
drawingId: c.selectedDrawingId,
drawingIds: c.selectedDrawingIds,
extrudedSolidId: c.selectedExtrudedSolidId,
columnId: c.selectedColumnId,
ceilingIds: c.selectedCeilingIds,
roofIds: c.selectedRoofIds,
stairIds: c.selectedStairIds,
roomIds: c.selectedRoomIds,
}),
};
},
snap: (raw, draftPoints, mods) => {
const c = cmdLatest.current;
return computeSnap({
raw,
project: c.project,
levelId: c.activeLevel.id,
visibleCodes: c.visibleCodes,
settings: c.snap,
draftPoints,
lastPoint: draftPoints.length ? draftPoints[draftPoints.length - 1] : null,
pxPerMeter: planViewRef.current?.pxPerMeter() ?? 90,
// Shift = Ortho, Ctrl = Snap aus — auch für den ERSTEN Punkt (ohne
// Draft): so fängt der Startpunkt einer neuen Linie/Polylinie/Wand an
// vorhandene Endpunkte/Mitten, statt erst ab dem zweiten Punkt.
shift: mods?.shift ?? false,
ctrl: mods?.ctrl ?? false,
});
},
pxPerMeter: () => planViewRef.current?.pxPerMeter() ?? 90,
setDraft: (d) => cmdLatest.current.setDraft(d),
// Zeichnet man WÄHREND man eine Gruppe betreten hat (Isolation), wird
// das neue Element automatisch Mitglied dieser Gruppe (Nutzer-Wunsch:
// „wenn man etwas neu zeichnet ... zeichnet man in der Gruppe"). [K4] S3:
// Befehle tragen ihre Kern-Anfrage mit (`cmdMutation`); die Gruppen-Zuordnung
// rechnet der Kern im selben Commit (`group`, `cmd_create::group_ops`).
commit: (mutate) => {
const groupPath = cmdLatest.current.groupPath;
const group = groupPath[groupPath.length - 1];
// Befehle ohne Kern-Anfrage (Georeferenz, Ausrichten) legen keine Elemente an.
cmdLatest.current.setProject(group && mutate.coreReq ? cmdMutation({ ...mutate.coreReq, group }) : mutate);
},
isFloor: () => cmdLatest.current.activeLevel.kind === "floor",
// Befehl braucht eine Auswahl (Bewegen/Drehen/Spiegeln), es ist keine da.
notify: (key) => notify(t(key as Parameters<typeof t>[0]), "info"),
// Getippte Werte auf einem Layout-Blatt in Papier-mm, y nach unten ([93]).
inputUnits: () => unitsForLevel(cmdLatest.current.activeLevel),
// Frisch über `text`/`textbox` erzeugtes Element sofort inline editieren
// (kein Lookup nötig — der Commit hat es bereits angehängt, s. engine.ts
// applyResult-Reihenfolge commit→focusDrawing). Auswahl-Löschen wie
// onEditDrawingText (useMouseSelectionHandlers.ts), damit kein anderes
// Element gleichzeitig markiert bleibt.
focusDrawing: (id, minHeightM) => {
setSelectedWallIds([]);
setSelectedCeilingIds([]);
setSelectedOpeningIds([]);
setSelectedStairIds([]);
setSelectedRoomIds([]);
setSelectedExtrudedSolidIds([]);
setSelectedColumnIds([]);
setSelectedRoofIds([]);
setSelectedContextObjectIds([]);
setSelectedSectionLineIds([]);
setSelectedDrawingId(id);
setEditTextMinHeightM(minHeightM ?? null);
setEditTextId(id);
},
};
engineRef.current = new CommandEngine(host);
}
const engine = engineRef.current;
// [99] Esc/Enter eines laufenden Befehls unabhängig vom Fokus (ein Verteiler, s. commandKeys.ts).
useCommandKeys(engineRef);
// Nutzer-Kürzel-Übersteuerungen (Einstellungen → Remap) — aus localStorage
// geladen, bei jeder Änderung sofort an die Engine gereicht (s. `commands/
// engine.ts::setAliasOverrides`, `state/commandAliasOverrides.ts`).
const [aliasOverrides, setAliasOverridesState] = useState<Record<string, string>>(() =>
loadAliasOverrides(),
);
useEffect(() => engine.setAliasOverrides(aliasOverrides), [engine, aliasOverrides]);
const setAliasOverrides = (next: Record<string, string>) => {
setAliasOverridesState(next);
saveAliasOverrides(next);
};
// Ändert das native Einstellungs-Fenster (separates Tauri-Fenster) die
// Kürzel, landen sie zwar in localStorage, aber das `storage`-Event feuert
// NIE im Fenster, das selbst geschrieben hat — nur in den ANDEREN Fenstern
// (Web-Storage-API-Standardverhalten). Genau der Fall hier: dieses
// (Haupt-)Fenster empfängt die Änderung darüber und zieht sie nach.
useEffect(() => {
const onStorage = (e: StorageEvent) => {
if (e.key === "cad.commandAliasOverrides") setAliasOverridesState(loadAliasOverrides());
};
window.addEventListener("storage", onStorage);
return () => window.removeEventListener("storage", onStorage);
}, []);
// Nutzer-Übersteuerungen der echten Tastatur-Shortcuts (Einstellungen →
// Tastenkürzel) — analoges Muster zu `aliasOverrides` oben, aber für
// `state/keyboardShortcuts.ts` (Ctrl/Cmd+Z usw.) statt der Befehlszeilen-
// Kürzel. Direkt an alle betroffenen Hooks unten durchgereicht.
const [shortcutOverrides, setShortcutOverridesState] = useState<ShortcutOverrides>(() =>
loadShortcutOverrides(),
);
const setShortcutOverrides = (next: ShortcutOverrides) => {
setShortcutOverridesState(next);
saveShortcutOverrides(next);
};
useEffect(() => {
const onStorage = (e: StorageEvent) => {
if (e.key === "dossier.keyboardShortcutOverrides") {
setShortcutOverridesState(loadShortcutOverrides());
}
};
window.addEventListener("storage", onStorage);
return () => window.removeEventListener("storage", onStorage);
}, []);
// Auf Engine-Zustandsänderungen re-rendern (Prompt/Optionen aktualisieren).
const [engineTick, setEngineTick] = useState(0);
useEffect(
() => engine.subscribe(() => setEngineTick((n) => n + 1)),
[engine],
);
// engineTick wird nur als Re-Render-Trigger gelesen (kein direkter Konsum).
void engineTick;
const engineView = engine.view();
const commandActive = engineView.active;
// Fokus wieder freigeben, sobald ein Befehl fertig ist (Commit ODER Abbruch):
// beim Start wird das Befehlsfeld fokussiert (onSelectTool), bliebe es das
// auch danach, würde die nächste Zifferntaste im (inaktiven) Feld landen
// statt beim globalen Werkzeug-Kürzel anzukommen — Esc wäre nötig. Mit dem
// Blur bei aktiv→inaktiv wählt man wie in Vectorworks sofort das nächste
// Werkzeug per Zifferntaste, ohne dazwischen Esc zu drücken.
const prevCommandActiveRef = useRef(commandActive);
useEffect(() => {
if (prevCommandActiveRef.current && !commandActive) {
commandLineRef.current?.blur();
}
prevCommandActiveRef.current = commandActive;
}, [commandActive]);
// Live-Echo des Befehlszeilen-Texts fürs Cursor-HUD: der getippte Wert
// erscheint sofort im aktiven Tab-Feld am Cursor (VW-Verhalten).
const [cmdTyped, setCmdTyped] = useState("");
return {
engineRef,
engine,
engineView,
commandActive,
commandLineRef,
aliasOverrides,
setAliasOverrides,
shortcutOverrides,
setShortcutOverrides,
cmdTyped,
setCmdTyped,
};
}
+69
View File
@@ -0,0 +1,69 @@
// Effektive Darstellung der Hauptansicht ([121] aus App.tsx herausgelöst): Resolver je Geschoss
// und je Kategorie-Code aus den Darstellungsmodi der Zeichnungsebenen-/Ebenen-Panels plus ein
// stabiler Schlüssel für den 3D-Neuaufbau.
//
// Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md).
import { useMemo } from "react";
import { flattenCategories, type Project } from "../model/types";
import { isSheetLevel } from "../model/layoutModel";
import type { CategoryDisplayResolver } from "../core";
import type { DisplayResolver } from "../viewport/Viewport3D";
import { itemDisplay } from "../panels/displayMode";
import type { DisplayMode } from "../panels/types";
import { BUILTIN_PANEL_IDS } from "../panels/builtinPanels";
import { useStore } from "./appStore";
export function useDisplayResolvers(opts: {
project: Project;
activeLevelId: string;
activeCategoryCode: string;
}) {
const { project, activeLevelId, activeCategoryCode } = opts;
const displayModes = useStore((s) => s.displayModes) as Record<string, DisplayMode | undefined>;
// ── Effektive Darstellung für die Hauptansicht ────────────────────────────
// 3D: Geschosse nach dem Modus des Zeichnungsebenen-Panels, Kategorien nach
// dem Modus des Ebenen-Panels. Grundriss: Kategorien nach dem Ebenen-Panel.
// Aus der abonnierten Map lesen (nicht über modeFor), damit ein Moduswechsel
// garantiert ein Re-Render auslöst und die Resolver neu rechnen.
const drawingLevelsMode =
displayModes[BUILTIN_PANEL_IDS.drawingLevels] ?? "all";
const layersMode = displayModes[BUILTIN_PANEL_IDS.layers] ?? "all";
// Sichtbarkeit je Kategorie-Code (für categoryDisplay), Baum berücksichtigt.
const codeVisible = useMemo(() => {
const map = new Map<string, boolean>();
for (const c of flattenCategories(project.layers)) map.set(c.code, c.visible);
return map;
}, [project.layers]);
// Resolver: je Geschoss-ID die Render-Entscheidung (aktiv = Arbeitsfokus).
// Memoisiert, damit Plan/3D nicht bei jedem Render neu rechnen.
const floorDisplay: CategoryDisplayResolver & DisplayResolver = useMemo(() => {
const visible = new Map(
project.drawingLevels.map((z) => [z.id, z.visible]),
);
// Blatt-Ebenen stehen für sich: nur sichtbar, wenn ihr Blatt offen ist, und dann allein.
const sheets = new Set(project.drawingLevels.filter(isSheetLevel).map((z) => z.id));
const onSheet = sheets.has(activeLevelId);
return (id) =>
onSheet || sheets.has(id)
? { render: id === activeLevelId, greyed: false, locked: false }
: itemDisplay(drawingLevelsMode, id === activeLevelId, visible.get(id) ?? false);
}, [project.drawingLevels, drawingLevelsMode, activeLevelId]);
// Resolver: je Kategorie-Code die Render-Entscheidung. „Aktiv" = die per
// Klick im Ebenen-Panel gewählte Kategorie (activeCategoryCode, wie schon
// in LayersPanel.tsx für die Zeilen-Hervorhebung genutzt). Wirkt in
// Grundriss UND 3D.
const categoryDisplay: CategoryDisplayResolver & DisplayResolver = useMemo(
() => (code) =>
itemDisplay(layersMode, code === activeCategoryCode, codeVisible.get(code) ?? false),
[layersMode, codeVisible, activeCategoryCode],
);
// Stabiler Schlüssel der 3D-Display-Entscheidungen (Resolver sind nicht
// referenzstabil → triggert sonst keinen Neuaufbau).
const displayKey = `${drawingLevelsMode}|${layersMode}|${activeLevelId}|${activeCategoryCode}`;
return { floorDisplay, categoryDisplay, displayKey, drawingLevelsMode };
}
+46
View File
@@ -0,0 +1,46 @@
// Stabile Rückruf-Identität mit immer aktuellem Inhalt ([121], Muster „useEvent").
//
// App.tsx baut viele Handler als Closures über den aktuellen Render (Projekt, Auswahl …). Gibt man
// sie direkt an `memo`-Kinder weiter, ist jede Identität je Render neu und `memo` wirkungslos.
// `useEvent(fn)` liefert eine Funktion, deren Identität über die ganze Lebensdauer gleich bleibt und
// die beim Aufruf die Fassung des LETZTEN Renders ausführt. Nur für Ereignis-Handler (Klick, Ziehen,
// Befehl) — nie für Funktionen, deren Ergebnis während des Renders gelesen wird (die würden ein
// `memo`-Kind sonst nicht mehr neu zeichnen, obwohl sich ihr Ergebnis ändert).
//
// Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md).
import { useRef } from "react";
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function useEvent<F extends (...args: any[]) => any>(fn: F): F {
const latest = useRef(fn);
// Im Render nachführen (nicht erst im Effekt): Kinder rufen manche Handler schon in ihren eigenen
// Layout-Effekten auf, die VOR denen des Elternteils laufen — sie sollen die neue Fassung sehen.
// Die App rendert ohne Transitions, ein verworfener Render kommt nicht vor.
latest.current = fn;
const stable = useRef<F | null>(null);
if (stable.current === null) {
stable.current = ((...args: Parameters<F>) => latest.current(...args)) as F;
}
return stable.current;
}
/**
* Wie `useEvent`, aber für ein ganzes Bündel von Handlern (Objekt aus Funktionen): liefert ein
* stabiles Objekt mit stabilen Weiterleitungen je Schlüssel. Die Schlüsselmenge muss gleich bleiben.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function useEventBundle<T extends Record<string, (...args: any[]) => any>>(handlers: T): T {
const latest = useRef(handlers);
latest.current = handlers;
const stable = useRef<T | null>(null);
if (stable.current === null) {
const out: Record<string, unknown> = {};
for (const key of Object.keys(handlers)) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
out[key] = (...args: any[]) => latest.current[key](...args);
}
stable.current = out as T;
}
return stable.current;
}
+435
View File
@@ -0,0 +1,435 @@
// 3D-Editier-Griffe direkt im Viewport3D ([121] aus App.tsx herausgelöst): Quellen der Griffe
// (gewählte Wände/2D-Elemente/Decken/Dächer), Fang beim Ziehen, Cursor-HUD und der Feld-Controller
// (Tab/getippte Werte) eines laufenden 3D-Griff-Drags. Die zurückgegebenen Handler sind
// referenzstabil (`useEvent`), damit der memoisierte Viewport nicht bei jedem App-Render neu zeichnet.
//
// Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md).
import { useMemo, useRef, useState, type RefObject } from "react";
import type { Ceiling, Drawing2D, Project, Roof, Vec2, Wall } from "../model/types";
import type { SnapResult, SnapSettings, ToolDraft } from "../tools/types";
import { computeSnap } from "../tools/snapping";
import { roofBaseElevation, roofGeometry } from "../core";
import {
neighbor3dVertex,
bodyMoveAnchor,
hudFromAnchor,
grip3dTargetKey,
grip3dEditPoint,
cycleGrip3dEditState,
nextGrip3dEditState,
type Grip3dTarget,
type Grip3dEditState,
} from "../viewport/grip3dHud";
import type { CommandLineHandle } from "../ui/CommandLine";
import { useEvent } from "./useEvent";
import type { useSelectionState } from "./useSelectionState";
import type { useProjectActions } from "./useProjectActions";
type Sel = ReturnType<typeof useSelectionState>;
type Actions = ReturnType<typeof useProjectActions>;
export function useGrip3dEditing(opts: {
project: Project;
levelId: string;
visibleCodes: Set<string>;
snap: SnapSettings;
setDraft: (d: ToolDraft | null) => void;
undo: () => void;
commandLineRef: RefObject<CommandLineHandle>;
selectedWallIds: string[];
selectedDrawingIds: string[];
selectedCeilingIds: string[];
selectedRoofIds: string[];
updateRoof: Sel["updateRoof"];
moveRoofGrip: Sel["moveRoofGrip"];
moveRoofBy: Sel["moveRoofBy"];
moveCeilingGrip: Actions["moveCeilingGrip"];
moveCeilingBy: Actions["moveCeilingBy"];
moveCeilingEdge: Actions["moveCeilingEdge"];
moveGripOf: Actions["moveGripOf"];
moveElementByOf: Actions["moveElementByOf"];
updateWall: Actions["updateWall"];
}) {
const {
project,
levelId,
visibleCodes,
snap,
setDraft,
undo,
commandLineRef,
selectedWallIds,
selectedDrawingIds,
selectedCeilingIds,
selectedRoofIds,
updateRoof,
moveRoofGrip,
moveRoofBy,
moveCeilingGrip,
moveCeilingBy,
moveCeilingEdge,
moveGripOf,
moveElementByOf,
updateWall,
} = opts;
// ── 3D-Editier-Griffe (direkt im Viewport3D) ──────────────────────────────
// Genau EINE gewählte Wand (kein 2D-Element) bzw. genau EIN 2D-Element liefert
// die Quelle der 3D-Griffe. Dieselben Store-Actions wie bei den Plan-Griffen
// (moveGripOf/moveElementByOf), damit Plan + 3D identisch mutieren. Der Höhen-
// Griff bindet die OK absolut (top=custom z) — gleicher Pfad wie das Attribut-
// Panel (updateWall top).
// Alle gewählten Wände/2D-Elemente als Quelle der 3D-Griffe. Wände UND 2D-
// Elemente schließen sich gegenseitig aus (entweder-oder), damit der einzelne
// Element-Editierpfad (moveGripOf je ID) eindeutig bleibt. Bei Mehrfachauswahl
// erscheinen Griffe für ALLE — Basis für das gemeinsame Ziehen koinzidenter Ecken.
const edit3dWalls = useMemo(
() =>
selectedDrawingIds.length === 0
? selectedWallIds
.map((id) => project.walls.find((w) => w.id === id))
.filter((w): w is Wall => !!w)
: [],
[selectedWallIds, selectedDrawingIds, project.walls],
);
const edit3dDrawings = useMemo(
() =>
selectedWallIds.length === 0
? selectedDrawingIds
.map((id) => project.drawings2d.find((d) => d.id === id))
.filter((d): d is Drawing2D => !!d)
: [],
[selectedWallIds, selectedDrawingIds, project.drawings2d],
);
// Gewählte Decken → 3D-Eckpunkt-/Kanten-/Verschiebe-Griffe. Nur wenn keine
// Wände/2D-Elemente mitselektiert sind (eindeutiger Editierfokus).
const edit3dCeilings = useMemo(
() =>
selectedWallIds.length === 0 && selectedDrawingIds.length === 0
? selectedCeilingIds
.map((id) => (project.ceilings ?? []).find((c) => c.id === id))
.filter((c): c is Ceiling => !!c)
: [],
[selectedWallIds, selectedDrawingIds, selectedCeilingIds, project.ceilings],
);
// Dächer mit 3D-Griffen: nur wenn ausschliesslich Dächer gewählt sind
// (Eck-Griffe zum Resizen, Move-Griff, First-Griff für die Neigung).
const edit3dRoofs = useMemo(
() =>
selectedWallIds.length === 0 &&
selectedDrawingIds.length === 0 &&
selectedCeilingIds.length === 0
? selectedRoofIds
.map((id) => (project.roofs ?? []).find((r) => r.id === id))
.filter((r): r is Roof => !!r)
: [],
[selectedWallIds, selectedDrawingIds, selectedCeilingIds, selectedRoofIds, project.roofs],
);
// Snap beim 3D-Vertex-Drag: dieselbe computeSnap-Logik wie die Plan-Griffe.
// Das/die gerade GEZOGENEN Element(e) werden aus den Snap-Quellen genommen
// (sonst fängt der Punkt an sich selbst). `excludeWallIds`/`excludeDrawingIds`
// sind die Mitglieder der Koinzidenz-Gruppe (alle, die mitgeführt werden).
const snapFor3dVertex = (
raw: Vec2,
excludeWallIds: Set<string>,
excludeDrawingIds: Set<string>,
): SnapResult | null => {
return computeSnap({
raw,
project,
excludeIds: [...excludeWallIds, ...excludeDrawingIds],
levelId,
visibleCodes,
settings: snap,
draftPoints: [],
lastPoint: null,
// 3D hat kein echtes pxPerMeter; ein vernünftiger Fallback hält die
// Snap-Toleranz (tolerancePx/pxPerMeter) in einem brauchbaren Meter-Bereich.
pxPerMeter: 90,
shift: false,
ctrl: false,
});
};
// Cursor-HUD (Länge/Winkel bzw. Δx/Δy) für einen 3D-Griff-Drag — Nutzer-
// Report „beim Verschieben von Elementen zeigt es die Werte nicht an": die
// 3D-Griffe (`onEdit3dVertex`/`onEdit3dBody`) mutierten das Modell bisher
// OHNE je `setDraft(...)` mit einem `hud` zu füllen (anders als die 2D-
// Griff-Bearbeitung, `state/useGripEditing.ts::hudFor`/`edgeHudFor`, die das
// von Anfang an tat) — der Cursor-HUD blieb daher leer, obwohl der Kanal
// (`hudFields`/`draft.hud`, s. `Wasm3DViewport.tsx`) längst bis in den 3D-
// Viewport durchgereicht ist. Die reine Geometrie (Nachbar-/Anker-Auflösung)
// lebt in `viewport/grip3dHud.ts` (eigenständig testbar).
//
// Läuft während eines „move"-Griff-Drags (ganzes Element verschieben): sammelt
// die seit Drag-Beginn angewandten Deltas je Ziel-Element, damit das HUD die
// GESAMTE Verschiebung zeigt statt des winzigen Pro-Event-Deltas. `rawTotal`
// = reine Maus-Summe (auch bei aktivem Feld-Controller weitergeführt, damit
// ein entsperrtes Feld sofort wieder der Maus folgt); `appliedTotal` = was
// TATSÄCHLICH aufs Modell angewandt wurde (kann bei Locks abweichen). Reset
// bei Ziel-Wechsel (neuer Drag) UND in `onEdit3dEnd` (Drag-Ende).
const bodyDragRef = useRef<{ key: string; anchor: Vec2; rawTotal: Vec2; appliedTotal: Vec2 } | null>(
null,
);
// Feld-Controller (Tab-Zyklus, getippte Werte) für einen laufenden 3D-Griff-
// Drag — Nutzer-Report „man sieht Länge/Winkel, aber man kann nichts
// eingeben". Eigenständiges 3D-Äquivalent zu `useGripEditing.ts`s `gripEdit`
// (s. `viewport/grip3dHud.ts`-Dateikommentar für das „warum eigenständig").
const [grip3dEdit, setGrip3dEdit] = useState<Grip3dEditState | null>(null);
// Letzter bekannter roh (maus-getriebener, UN-gelockter) Zustand des
// laufenden 3D-Griff-Drags — Grundlage fürs ÖFFNEN des Feld-Controllers
// (Tab friert die AKTUELLE Position ein, s. `cycleGrip3dEditState`).
const last3dDragRef = useRef<
{ target: Grip3dTarget; index: number; kind: "vertex" | "move"; anchor: Vec2; raw: Vec2 } | null
>(null);
// Ein 3D-Vertex-Griff wurde gezogen. `target` benennt das konkrete Element
// (Wand-ID ODER Drawing-ID), `index` den Vertex. Liefert den effektiv
// angewandten (gesnappten) Punkt zurück — der 3D-Viewport nutzt ihn, um
// koinzidente Endpunkte anderer gewählter Elemente mitzuführen und den
// Snap-Marker zu zeigen. `snapped=false` (für mitgeführte Geschwister) wendet
// den Punkt direkt an, ohne erneut zu snappen.
// Reine Mutations-Anwender OHNE Lock-/Snap-/HUD-Logik — von `onEdit3dVertex`/
// `onEdit3dBody` (Maus-Pfad) UND `submitGrip3dEditValue` (Tastatur-Pfad)
// gemeinsam genutzt, damit Letzterer NICHT `onEdit3dVertex`/`onEdit3dBody`
// rekursiv aufruft — das würde `grip3dEdit`/`bodyDragRef` über einen VERALTETEN
// Closure-Wert lesen (React-State ist innerhalb desselben Funktionsaufrufs
// noch nicht aktualisiert) und den gerade getippten Wert wieder verwerfen.
const applyVertexPoint = (target: Grip3dTarget, index: number, pt: Vec2) => {
if (target.roofId) moveRoofGrip(target.roofId, index, pt);
else if (target.ceilingId) moveCeilingGrip(target.ceilingId, index, pt);
else moveGripOf(target.drawingId ?? null, target.wallId ?? null, index, pt);
};
const applyBodyDelta = (target: Grip3dTarget, delta: Vec2) => {
if (target.roofId) moveRoofBy(target.roofId, delta);
else if (target.ceilingId) moveCeilingBy(target.ceilingId, delta);
else moveElementByOf(target.drawingId ?? null, target.wallId ?? null, delta);
};
const onEdit3dVertex = (
target: { wallId?: string; drawingId?: string; ceilingId?: string; roofId?: string },
index: number,
model: Vec2,
excludeWallIds?: Set<string>,
excludeDrawingIds?: Set<string>,
): Vec2 => {
// Nachbarpunkt VOR der Mutation auflösen (Wand/Zeichnung/Decke/Dach ändern
// sich hier nur am gezogenen `index`, der Nachbar bleibt stabil).
const neighbor = neighbor3dVertex(project, target, index);
let pt = model;
let snapHit: SnapResult | null = null;
const ge = grip3dEdit;
if (
ge &&
ge.kind === "vertex" &&
ge.index === index &&
grip3dTargetKey(ge.target) === grip3dTargetKey(target) &&
(ge.locks.length != null || ge.locks.angle != null)
) {
// Feld-Controller aktiv: getippte/eingefrorene Werte übersteuern die
// Maus — kein Snap währenddessen (deckungsgleich mit 2D `onGripMove`).
pt = grip3dEditPoint(ge.anchor, ge.locks, model);
} else if (excludeWallIds || excludeDrawingIds) {
const snapResult = snapFor3dVertex(
model,
excludeWallIds ?? new Set(),
excludeDrawingIds ?? new Set(),
);
pt = snapResult?.point ?? model;
snapHit = snapResult;
}
applyVertexPoint(target, index, pt);
if (neighbor) last3dDragRef.current = { target, index, kind: "vertex", anchor: neighbor, raw: model };
setDraft({
preview: [],
vertices: [],
snap: snapHit,
hud: neighbor ? hudFromAnchor(neighbor, pt) : undefined,
});
return pt;
};
const onEdit3dBody = (
target: { wallId?: string; drawingId?: string; ceilingId?: string; roofId?: string },
delta: Vec2,
locked = false,
) => {
const key = grip3dTargetKey(target);
if (!bodyDragRef.current || bodyDragRef.current.key !== key) {
bodyDragRef.current = {
key,
anchor: bodyMoveAnchor(project, target) ?? { x: 0, y: 0 },
rawTotal: { x: 0, y: 0 },
appliedTotal: { x: 0, y: 0 },
};
}
const st = bodyDragRef.current;
st.rawTotal = { x: st.rawTotal.x + delta.x, y: st.rawTotal.y + delta.y };
const rawPoint: Vec2 = { x: st.anchor.x + st.rawTotal.x, y: st.anchor.y + st.rawTotal.y };
const ge = grip3dEdit;
let bodySnap: SnapResult | null = null;
let desiredPoint: Vec2;
if (ge && ge.kind === "move" && grip3dTargetKey(ge.target) === key && (ge.locks.length != null || ge.locks.angle != null)) {
desiredPoint = grip3dEditPoint(ge.anchor, ge.locks, rawPoint);
} else if (locked) {
desiredPoint = rawPoint; // Shift/Achs-Sperre hat Vorrang vor dem Einrasten
} else {
// Referenzpunkt des Körpers rastet auf andere Punkte ein
bodySnap = snapFor3dVertex(
rawPoint,
new Set(target.wallId ? [target.wallId] : []),
new Set(target.drawingId ? [target.drawingId] : []),
);
desiredPoint = bodySnap?.point ?? rawPoint;
}
const desiredTotal: Vec2 = { x: desiredPoint.x - st.anchor.x, y: desiredPoint.y - st.anchor.y };
const appliedDelta: Vec2 = {
x: desiredTotal.x - st.appliedTotal.x,
y: desiredTotal.y - st.appliedTotal.y,
};
applyBodyDelta(target, appliedDelta);
st.appliedTotal = desiredTotal;
last3dDragRef.current = { target, index: -1, kind: "move", anchor: st.anchor, raw: rawPoint };
setDraft({
preview: [],
vertices: [],
snap: bodySnap,
hud: { at: desiredPoint, dx: desiredTotal.x, dy: desiredTotal.y },
});
};
// Tab während eines laufenden 3D-Griff-Drags (Endpunkt ODER Verschieben):
// Feld-Controller öffnen/zykeln — analog `useGripEditing.ts::
// cycleGripEditField`, aber auf `last3dDragRef` als Zustandsquelle statt
// der 2D-Grips-Liste. `Wasm3DViewport.tsx` ruft dies auf einem eigenen
// Tastatur-Listener auf (nur solange EIN 3D-Griff-Drag läuft — s. dort).
const cycleGrip3dEditField = () => {
const info = last3dDragRef.current;
if (!info) return;
setGrip3dEdit((prev) => cycleGrip3dEditState(prev, info));
requestAnimationFrame(() => commandLineRef.current?.focus());
};
// Escape während eines laufenden 3D-Griff-Drags: abbrechen. ALLE fünf
// Griff-Mutationen coalescen ihre Schritte zu GENAU einem Undo-Eintrag pro
// Drag (s. `state/projectSlice.ts::moveGripOf`/`updateWall`/… -Doc), ein
// einzelner `undo()` reicht also, um den GESAMTEN Drag zu verwerfen statt
// nur den letzten Mikro-Schritt. `Wasm3DViewport.tsx` räumt seinen eigenen
// (lokalen) Drag-Zustand danach selbst auf (`endGripDrag`); hier nur der
// Modell-Zustand + der App-seitige Aufräum-Teil (`onEdit3dEnd`).
const cancelGrip3dEdit = () => {
undo();
onEdit3dEnd();
};
// Getippter Zahlenwert im 3D-Feld-Controller — analog `submitGripEditValue`.
// Nutzt `applyVertexPoint`/`applyBodyDelta` (NICHT `onEdit3dVertex`/
// `onEdit3dBody` selbst, s. deren Dateikommentar oben).
const submitGrip3dEditValue = (value: number) => {
const ge = grip3dEdit;
if (!ge) return;
const next = nextGrip3dEditState(ge, value);
setGrip3dEdit(next);
const raw = last3dDragRef.current?.raw ?? next.anchor;
const pt = grip3dEditPoint(next.anchor, next.locks, raw);
if (next.kind === "vertex") {
applyVertexPoint(next.target, next.index, pt);
last3dDragRef.current = { target: next.target, index: next.index, kind: "vertex", anchor: next.anchor, raw };
setDraft({ preview: [], vertices: [], snap: null, hud: hudFromAnchor(next.anchor, pt) });
return;
}
const st = bodyDragRef.current;
if (!st) return;
const desiredTotal: Vec2 = { x: pt.x - st.anchor.x, y: pt.y - st.anchor.y };
const appliedDelta: Vec2 = {
x: desiredTotal.x - st.appliedTotal.x,
y: desiredTotal.y - st.appliedTotal.y,
};
applyBodyDelta(next.target, appliedDelta);
st.appliedTotal = desiredTotal;
last3dDragRef.current = { target: next.target, index: -1, kind: "move", anchor: next.anchor, raw };
setDraft({ preview: [], vertices: [], snap: null, hud: { at: pt, dx: desiredTotal.x, dy: desiredTotal.y } });
};
// First-Griff: neue First-Höhe (world-Y = Modell-Höhe) → Dachneigung. Aus der
// aktuellen Neigung die halbe Spannweite ableiten und daraus den neuen Winkel
// rechnen (behält die Firstlage, ändert nur die Steilheit).
const onEdit3dRoofPitch = (roofId: string, apexHeight: number) => {
const roof = (project.roofs ?? []).find((r) => r.id === roofId);
if (!roof) return;
const baseZ = roofBaseElevation(project, roof);
const geom = roofGeometry(roof, baseZ);
const currentRidge = geom.ridgeHeight; // Höhe First über Traufe
const newRidge = Math.max(0.05, apexHeight - baseZ);
const curPitch = ((roof.pitchDeg ?? 30) * Math.PI) / 180;
// Halbe Spannweite aus aktueller Geometrie (First/tan(Neigung)).
const halfSpan = currentRidge > 1e-4 ? currentRidge / Math.tan(curPitch || 1e-3) : 1;
const newPitch = (Math.atan(newRidge / Math.max(0.05, halfSpan)) * 180) / Math.PI;
// coalesceKey: EIN First-Drag (viele Maus-Move-Schritte) soll EINEN Undo-
// Schritt erzeugen, s. `state/projectSlice.ts::updateRoof`-Doc.
updateRoof(roofId, { pitchDeg: Math.max(1, Math.min(85, newPitch)) }, `onEdit3dRoofPitch:${roofId}`);
// Cursor-HUD (First-Höhe) — bislang zeigten Höhen-/Kanten-/First-Griff als
// einzige 3D-Griffe GAR KEINEN Wert (Nutzer-Wunsch „generell weiter
// optimieren"). Anker = Dach-Schwerpunkt (`bodyMoveAnchor`, dieselbe
// Formel wie der Verschiebe-Griff).
const at = bodyMoveAnchor(project, { roofId });
if (at) setDraft({ preview: [], vertices: [], snap: null, hud: { at, text: `First: ${apexHeight.toFixed(3)}m` } });
};
// Läuft während eines Kanten-Griff-Drags (Decke): sammelt die seit Drag-
// Beginn angewandte Verschiebung fürs Δ-HUD — analog `bodyDragRef`, aber
// ohne Lock-Unterstützung (kein Feld-Controller für Kanten, s. PENDENZEN).
const edgeDragRef = useRef<{ key: string; start: Vec2; raw: Vec2; applied: Vec2; total?: Vec2 } | null>(null);
const onEdit3dEdge = (ceilingId: string, aIndex: number, bIndex: number, delta: Vec2) => {
const key = `${ceilingId}:${aIndex}:${bIndex}`;
if (!edgeDragRef.current || edgeDragRef.current.key !== key) {
const c0 = (project.ceilings ?? []).find((x) => x.id === ceilingId);
const a0 = c0?.outline[aIndex] ?? { x: 0, y: 0 };
edgeDragRef.current = { key, start: { x: a0.x, y: a0.y }, raw: { x: 0, y: 0 }, applied: { x: 0, y: 0 } };
}
const st = edgeDragRef.current;
st.raw = { x: st.raw.x + delta.x, y: st.raw.y + delta.y };
// Der Kanten-Startpunkt rastet auf andere Wand-/Zeichnungspunkte ein; die Kante
// folgt um dasselbe Delta (inkrementell, damit der Store-Aufruf gleich bleibt).
const rawPoint: Vec2 = { x: st.start.x + st.raw.x, y: st.start.y + st.raw.y };
const edgeSnap = snapFor3dVertex(rawPoint, new Set(), new Set());
const snapped = edgeSnap?.point ?? rawPoint;
const total: Vec2 = { x: snapped.x - st.start.x, y: snapped.y - st.start.y };
const step: Vec2 = { x: total.x - st.applied.x, y: total.y - st.applied.y };
if (step.x !== 0 || step.y !== 0) moveCeilingEdge(ceilingId, aIndex, bIndex, step);
st.applied = total;
st.total = total;
const c = (project.ceilings ?? []).find((x) => x.id === ceilingId);
const a = c?.outline[aIndex];
const b = c?.outline[bIndex];
if (a && b) {
const mid = { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 };
const dist = Math.hypot(st.total.x, st.total.y);
setDraft({ preview: [], vertices: [], snap: edgeSnap, hud: { at: mid, text: `Δ: ${dist.toFixed(3)}m` } });
}
};
const onEdit3dWallTop = (wallId: string, topZ: number) => {
// coalesceKey: EIN Höhen-Drag soll EINEN Undo-Schritt erzeugen, s.
// `state/projectSlice.ts::updateWall`-Doc.
updateWall(wallId, { top: { mode: "custom", z: topZ } }, `onEdit3dWallTop:${wallId}`);
const at = bodyMoveAnchor(project, { wallId });
if (at) setDraft({ preview: [], vertices: [], snap: null, hud: { at, text: `OK: ${topZ.toFixed(3)}m` } });
};
const onEdit3dEnd = () => {
bodyDragRef.current = null;
edgeDragRef.current = null;
last3dDragRef.current = null;
setGrip3dEdit(null);
setDraft(null);
};
return {
edit3dWalls,
edit3dDrawings,
edit3dCeilings,
edit3dRoofs,
grip3dEdit,
setGrip3dEdit,
last3dDragRef,
onEdit3dVertex: useEvent(onEdit3dVertex),
onEdit3dBody: useEvent(onEdit3dBody),
onEdit3dEdge: useEvent(onEdit3dEdge),
onEdit3dRoofPitch: useEvent(onEdit3dRoofPitch),
onEdit3dWallTop: useEvent(onEdit3dWallTop),
onEdit3dEnd: useEvent(onEdit3dEnd),
cycleGrip3dEditField: useEvent(cycleGrip3dEditField),
cancelGrip3dEdit: useEvent(cancelGrip3dEdit),
submitGrip3dEditValue: useEvent(submitGrip3dEditValue),
};
}
+113
View File
@@ -0,0 +1,113 @@
// Offenes Layout-Blatt ([121] aus App.tsx herausgelöst; DOSSIER A3, Phase 2b): Blatt-Ebene als
// aktive Ebene, Rückkehr zur vorigen Ebene beim Schliessen und die Viewport-/Tabellen-/Legenden-
// Handler des Blatts. Die Handler sind referenzstabil, `sheetPane` ändert sich nur mit Blatt/Ebene.
//
// Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md).
import { useEffect, useMemo, useRef } from "react";
import type { Layout, LayoutLegend, LayoutTable, LayoutViewport, Project } from "../model/types";
import { addItems, patchItem } from "../core";
import type { ProjectSlice } from "./projectSlice";
import {
createViewport,
createSheetLevel,
isSheetLevel,
sheetLevelOf,
addViewport as addViewportToLayout,
removeViewport as removeViewportFromLayout,
patchViewport as patchViewportInLayout,
addTable as addTableToLayout,
patchTable as patchTableInLayout,
removeTable as removeTableFromLayout,
} from "../model/layoutModel";
import { addLegend, patchLegend, removeLegend } from "../analysis/legend";
import { useEventBundle } from "./useEvent";
export function useSheetPane(opts: {
project: Project;
activeLayoutId: string | null;
setActiveLayoutId: (id: string | null) => void;
activeLevelId: string;
setActiveLevelId: (id: string) => void;
applyChange: ProjectSlice["applyChange"];
}) {
const { project, activeLayoutId, setActiveLayoutId, activeLevelId, setActiveLevelId, applyChange } = opts;
// ── Layout-Blatt (DOSSIER A3, Phase 2b): das offene Blatt + Viewport-Handler ─
// Das offene Layout wird live aus dem Projekt gelesen (Single Source of Truth);
// wurde es zwischenzeitlich gelöscht, ist es undefined → der Haupt-Viewport
// zeigt wieder die Modell-Ansicht. Die Handler mutieren immutabel über die
// pure CRUD-Ebene (panels/layoutModel.ts).
const activeLayout =
activeLayoutId !== null
? (project.layouts ?? []).find((l) => l.id === activeLayoutId)
: undefined;
const patchOpenLayout = (id: string, fn: (l: Layout) => Layout, coalesceKey?: string) =>
applyChange((p) => patchItem(p, "layouts", id, fn), coalesceKey);
// Ein offenes Blatt IST eine Zeichnungsebene: seine Blatt-Ebene (`layoutId`) wird die aktive Ebene,
// damit Werkzeuge, Befehle, Fang, Griffe, Auswahl und Undo genau wie im Grundriss wirken. Beim
// Schliessen kehrt die vorige Ebene zurück; wählt man im Navigator eine andere Ebene, schliesst
// das Blatt.
const sheetLevel = activeLayout ? sheetLevelOf(project, activeLayout.id) : undefined;
const levelBeforeSheetRef = useRef<string | null>(null);
const enteredSheetRef = useRef<string | null>(null);
useEffect(() => {
const current = project.drawingLevels.find((l) => l.id === activeLevelId);
if (activeLayout) {
if (!sheetLevel) {
// Layout ohne Blatt-Ebene (z. B. per CLI angelegt): einmal nachtragen.
applyChange(addItems("drawingLevels", [createSheetLevel(`sheet-${activeLayout.id}`, activeLayout)]));
return;
}
if (activeLevelId === sheetLevel.id) {
enteredSheetRef.current = activeLayout.id;
return;
}
if (enteredSheetRef.current === activeLayout.id) {
enteredSheetRef.current = null;
setActiveLayoutId(null);
return;
}
if (current && !isSheetLevel(current)) levelBeforeSheetRef.current = current.id;
setActiveLevelId(sheetLevel.id);
return;
}
enteredSheetRef.current = null;
if (current && !isSheetLevel(current)) return;
const back =
project.drawingLevels.find((l) => l.id === levelBeforeSheetRef.current && !isSheetLevel(l)) ??
project.drawingLevels.find((l) => !isSheetLevel(l));
if (back && back.id !== activeLevelId) setActiveLevelId(back.id);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [activeLayout?.id, sheetLevel?.id, activeLevelId]);
// Handler wirken auf das jeweils OFFENE Blatt (stabile Identität, aktueller Stand beim Aufruf).
const openId = () => activeLayout?.id ?? "";
const handlers = useEventBundle({
onBack: () => setActiveLayoutId(null),
onPatchViewport: (viewportId: string, patch: Partial<Omit<LayoutViewport, "id" | "snapshotId">>) =>
patchOpenLayout(openId(), (l) => patchViewportInLayout(l, viewportId, patch)),
onRemoveViewport: (viewportId: string) =>
patchOpenLayout(openId(), (l) => removeViewportFromLayout(l, viewportId)),
onAddTable: (table: LayoutTable) => patchOpenLayout(openId(), (l) => addTableToLayout(l, table)),
onPatchTable: (tableId: string, patch: Partial<Omit<LayoutTable, "id">>, coalesceKey?: string) =>
patchOpenLayout(openId(), (l) => patchTableInLayout(l, tableId, patch), coalesceKey),
onRemoveTable: (tableId: string) => patchOpenLayout(openId(), (l) => removeTableFromLayout(l, tableId)),
onAddViewport: (snapshotId: string, init: Partial<Omit<LayoutViewport, "id" | "snapshotId">>) =>
patchOpenLayout(openId(), (l) =>
addViewportToLayout(l, createViewport(`vp-${Date.now()}`, snapshotId, init)),
),
onAddLegend: (init: Omit<LayoutLegend, "id">) => {
const id = `legend-${Date.now()}`;
patchOpenLayout(openId(), (l) => addLegend(l, { ...init, id }));
return id;
},
onPatchLegend: (legendId: string, patch: Partial<Omit<LayoutLegend, "id">>) =>
patchOpenLayout(openId(), (l) => patchLegend(l, legendId, patch), `legend-${legendId}`),
onRemoveLegend: (legendId: string) => patchOpenLayout(openId(), (l) => removeLegend(l, legendId)),
});
const open = !!activeLayout && !!sheetLevel && activeLevelId === sheetLevel.id;
return useMemo(
() => (open && activeLayout ? { layout: activeLayout, handlers } : null),
[open, activeLayout, handlers],
);
}
+3 -3
View File
@@ -1,13 +1,13 @@
// [9] Kleines Protokoll der KI-Aufrufe (unten links, nur solange „KI-Zugriff erlauben“ an ist):
// Verbindungsstand, Schalter „KI pausieren“, die letzten Aufrufe (Änderungen hervorgehoben).
import { useState } from "react";
import { useState, memo } from "react";
import { t } from "../i18n";
import { clearAiLog, setAiPaused, useAiAccess } from "../state/aiAccess";
const time = (ms: number) => new Date(ms).toLocaleTimeString(undefined, { hour: "2-digit", minute: "2-digit", second: "2-digit" });
export function AiActivityPanel() {
export const AiActivityPanel = memo(function AiActivityPanel() {
const ai = useAiAccess();
const [open, setOpen] = useState(true);
if (!ai.enabled) return null;
@@ -49,4 +49,4 @@ export function AiActivityPanel() {
)}
</div>
);
}
});
+3 -2
View File
@@ -1,3 +1,4 @@
import { memo } from "react";
// Klassische Menüleiste (Bearbeiten/Ansicht/Fenster) neben der Wortmarke in
// der TopBar — ergänzt die bestehende Quick-Access-Icon-Leiste um textuelle
// Menüs im Rhino-/Desktop-Stil. Reine Darstellung + Callbacks (voll gesteuert,
@@ -57,7 +58,7 @@ export interface AppMenuBarProps {
}
/** Menüleiste (Bearbeiten/Ansicht/Fenster) — sitzt in der TopBar neben der Wortmarke. */
export function AppMenuBar({
export const AppMenuBar = memo(function AppMenuBar({
onNewProject,
onNewProjectFromSample,
onNewProjectFromComplexSample,
@@ -195,4 +196,4 @@ export function AppMenuBar({
/>
</div>
);
}
});
+3 -2
View File
@@ -1,7 +1,8 @@
import { memo } from "react";
import { useBusy } from "../state/busyStore";
/** Vollflächiger "Bitte warten"-Hinweis, solange `busyStore` ein Label hält. */
export function BusyOverlay() {
export const BusyOverlay = memo(function BusyOverlay() {
const label = useBusy();
if (!label) return null;
return (
@@ -12,4 +13,4 @@ export function BusyOverlay() {
</div>
</div>
);
}
});
+4 -3
View File
@@ -5,7 +5,7 @@
// Rein gesteuert: alle Aktionen laufen über Callbacks an die Engine. Tab (global
// in App) fokussiert das Eingabefeld. Bezeichner englisch, sichtbarer Text via t().
import { forwardRef, useImperativeHandle, useRef, useState } from "react";
import { forwardRef, memo, useImperativeHandle, useRef, useState } from "react";
import { t } from "../i18n";
import type { TranslationKey } from "../i18n";
import { NON_LENGTH_FIELDS } from "../commands/parseInput";
@@ -86,7 +86,8 @@ export interface CommandLineHandle {
blur: () => void;
}
export const CommandLine = forwardRef<CommandLineHandle, CommandLineProps>(
// memo ([121]): App reicht stabile Handler; ohne Änderung an Prompt/Feldern kein Neurendern.
export const CommandLine = memo(forwardRef<CommandLineHandle, CommandLineProps>(
function CommandLine(
{ active, promptKey, options, fields, onSubmit, onOption, onCycleField, onCancel, stillActive, steps, suggest, onTextChange, units = MODEL_UNITS },
ref,
@@ -258,4 +259,4 @@ export const CommandLine = forwardRef<CommandLineHandle, CommandLineProps>(
</div>
);
},
);
));
+3 -3
View File
@@ -6,7 +6,7 @@
//
// Muster: PointCloudImportDialog (abgedunkeltes Overlay, Esc/Hintergrund schliessen).
import { useEffect, useRef, useState } from "react";
import { useEffect, useRef, useState, memo } from "react";
import { t } from "../i18n";
import { Dropdown } from "./Dropdown";
import {
@@ -195,7 +195,7 @@ function MeshImportDialog({ req, onImport, notify }: { req: MeshImportRequest }
}
/** Verstecktes Datei-Feld (mehrere Dateien: Modell + `.mtl`/`.bin`) + Dialog; einmal in der App einhängen. */
export function MeshImportHost(props: MeshImportHostProps) {
export const MeshImportHost = memo(function MeshImportHost(props: MeshImportHostProps) {
const req = useMeshImportRequest();
return (
<>
@@ -216,4 +216,4 @@ export function MeshImportHost(props: MeshImportHostProps) {
{req && <MeshImportDialog key={req.file.name + req.file.size + req.file.lastModified} req={req} {...props} />}
</>
);
}
});
+12 -5
View File
@@ -6,7 +6,8 @@
//
// Muster: ExportDxfDialog (abgedunkeltes Overlay, Esc/Hintergrund schliessen).
import { useEffect, useState } from "react";
import { memo, useEffect, useState } from "react";
import { useStore } from "../state/appStore";
import { t } from "../i18n";
import type { TranslationKey } from "../i18n";
import { Dropdown } from "./Dropdown";
@@ -211,8 +212,14 @@ function PointCloudImportDialog({ file, project }: { file: File; project: Projec
);
}
/** Verstecktes Datei-Feld + Dialog; einmal in der App einhängen. */
export function PointCloudImportHost({ project }: { project: Project }) {
/** Dialog mit dem aktuellen Projekt aus dem Store (nur solange er offen ist abonniert, [121]). */
function ConnectedPointCloudImportDialog({ file }: { file: File }) {
const project = useStore((s) => s.project);
return <PointCloudImportDialog file={file} project={project} />;
}
/** Verstecktes Datei-Feld + Dialog; einmal in der App einhängen. Liest das Projekt selbst. */
export const PointCloudImportHost = memo(function PointCloudImportHost() {
const file = usePointCloudImportRequest();
return (
<>
@@ -228,7 +235,7 @@ export function PointCloudImportHost({ project }: { project: Project }) {
if (f) requestPointCloudImport(f);
}}
/>
{file && <PointCloudImportDialog key={file.name + file.size + file.lastModified} file={file} project={project} />}
{file && <ConnectedPointCloudImportDialog key={file.name + file.size + file.lastModified} file={file} />}
</>
);
}
});
+3 -3
View File
@@ -10,7 +10,7 @@
import { MODEL_UNITS, fmtDisplay, xToDisplay, yToDisplay, type DisplayUnits } from "../tools/displayUnits";
import { useCursor } from "../state/cursorStore";
import { useEffect, useRef, useState } from "react";
import { useEffect, useRef, useState, memo } from "react";
import type { SnapSettings } from "../tools/types";
import { t } from "../i18n";
@@ -357,7 +357,7 @@ function Sep() {
/** Eine Meterzahl für die Statusleiste (3 Nachkommastellen, ohne Einheit). */
const fmt = (n: number): string => n.toFixed(3);
export function StatusBar({
export const StatusBar = memo(function StatusBar({
hint,
showCursor,
unit,
@@ -423,4 +423,4 @@ export function StatusBar({
</div>
</footer>
);
}
});
+3 -3
View File
@@ -10,7 +10,7 @@
//
// Bezeichner englisch, UI-Text/Kommentare deutsch (CONVENTIONS.md).
import { useEffect } from "react";
import { useEffect, memo } from "react";
import { useStore } from "../state/appStore";
import { t } from "../i18n";
import type { NotifyKind } from "../state/notifySlice";
@@ -18,7 +18,7 @@ import type { NotifyKind } from "../state/notifySlice";
const AUTO_DISMISS_MS = 4000;
/** Top-level Toast-Stack — einmal in App.tsx gerendert. */
export function Toast() {
export const Toast = memo(function Toast() {
const notifications = useStore((s) => s.notifications);
const dismissNotify = useStore((s) => s.dismissNotify);
@@ -37,7 +37,7 @@ export function Toast() {
))}
</div>
);
}
});
function ToastItem({
id,
+9 -52
View File
@@ -8,11 +8,10 @@
// aus App, Aktionen melden sich über Callbacks zurück. Bezeichner englisch,
// UI-Text/Kommentare deutsch (CONVENTIONS.md).
import type { Project } from "../model/types";
import { t } from "../i18n";
import { checkForUpdate } from "../update/checkForUpdate";
import { getRunningVersion } from "../update/version";
import { useEffect, useRef, useState } from "react";
import { memo, useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { Dropdown } from "./Dropdown";
import type { DropdownItem, DropdownOption } from "./Dropdown";
@@ -56,7 +55,8 @@ export const SCALE_PRESETS: number[] = [1, 5, 10, 20, 50, 100, 200, 500, 1000];
const ZOOM_CLUSTER_WIDTH = 140;
export interface TopBarProps {
project: Project;
/** Projektname rechts in der Leiste (nur dieser, nicht das ganze Projekt: [121]). */
projectName: string;
// Kein Ribbon-Tab-Reiter mehr (Werkzeuge leben im ToolsPanel, siehe
// ribbonItems.ts/layout.ts v12) — die TopBar ist nur noch die schmale
@@ -64,49 +64,6 @@ export interface TopBarProps {
// Darstellungs-Steuerung folgt direkt darunter (siehe ViewRibbonTab, von
// App unconditional gerendert statt über Tab-Umschaltung).
/** Ob Zoom/Plan aktiv ist — steuert nur noch, ob Export im Datei-Menü geht. */
zoomEnabled: boolean;
/** Öffnet den PDF-Export-Dialog (nur im Grundriss sinnvoll). */
onExportPdf: () => void;
/** Öffnet den DXF-Export-Dialog (nur im Grundriss sinnvoll). */
onExportDxf: () => void;
/** Lädt die Bauteilliste des Projekts als CSV herunter. */
onExportSchedule: () => void;
/** Lädt das Projekt als IFC4-STEP-Datei herunter. */
onExportIfc: () => void;
onExportObj: () => void;
onExportStl: () => void;
onExportGlb?: () => void;
onExportStep?: () => void;
// Kamera-Settings (FOV), ZUSÄTZLICH zur bestehenden im „Ansichten"-Ribbon-
// Tab (ViewRibbonTab) und im 3D-Ribbon-Tab (Ribbon3dTab) — hier direkt neben
// dem CSV-Export in der schmalen Chrome-Zeile, damit sie immer erreichbar
// ist (Nutzer-Wunsch). Dieselben Felder/Handler wie dort.
viewType: ViewType;
fov: number;
onFov: (n: number) => void;
/** Presets nur sinnvoll, solange ein Geschoss aktiv ist (wie `viewToggleEnabled`
* in {@link ViewRibbonTabProps}). */
cameraEnabled: boolean;
// Ressourcen-Fenster.
resourcesOpen: boolean;
onToggleResources: () => void;
/** Öffnet das Einstellungs-Fenster (Darstellungsfarben, Projekt-Felder). */
onOpenSettings: () => void;
/** Layout-Menü (von App geliefert, damit dessen Logik dort bleibt). */
// ── Datei-Menü (Burger, ganz rechts) ───────────────────────────────────────
/** Öffnet den DXF/DWG-Import-Datei-Dialog. */
onImport: () => void;
/** Projekt als Datei speichern (JSON-Export des gesamten Projekts). */
onSaveProject: () => void;
/** Projekt aus einer Datei laden. */
onOpenProject: () => void;
/** Menüleiste (Bearbeiten/Ansicht/Fenster, {@link AppMenuBar}) — von App
* zusammengesetzt (dort leben Undo/Redo/Auswahl/View-State), hier nur
* platziert. `undefined` blendet sie aus (z. B. für künftige eingebettete
@@ -1104,7 +1061,7 @@ export interface ViewRibbonTabProps {
* Massstab/Zoom-Cluster und Darstellungsart. EIN Ribbon für alles; Handler/Setter
* kommen unverändert von App (gleiche Props wie zuvor an die TopBar).
*/
export function ViewRibbonTab({
export const ViewRibbonTab = memo(function ViewRibbonTab({
viewToggleEnabled,
viewType,
onViewType,
@@ -1389,10 +1346,10 @@ export function ViewRibbonTab({
)}
</div>
);
}
});
export function TopBar({
project,
export const TopBar = memo(function TopBar({
projectName,
menuBar,
viewControls,
}: TopBarProps) {
@@ -1465,11 +1422,11 @@ export function TopBar({
Projektname ganz rechts). Die Fensterknöpfe sitzen ganz links
(macOS-Titelleisten-Konvention). */}
<div className="topbar-right">
<span className="project-name">{project.name}</span>
<span className="project-name">{projectName}</span>
</div>
</header>
);
}
});
// Hinweis: Die früheren Helfer SNAP_TOGGLES + SnapMenu (Fang-Optionen) und die
// Zeichenwerkzeug-Buttons wurden aus der Oberleiste entfernt; sie leben jetzt
+4 -2
View File
@@ -14,7 +14,9 @@ const common = {
strokeLinejoin: "round" as const,
};
export function CommandIcon({ name }: { name: string }) {
import { memo } from "react";
export const CommandIcon = memo(function CommandIcon({ name }: { name: string }) {
switch (name) {
case "move":
// Vier-Wege-Verschiebepfeil.
@@ -307,4 +309,4 @@ export function CommandIcon({ name }: { name: string }) {
default:
return null;
}
}
});