[121] Merge: weniger Neurendern (Zoom 240→61, Wand-Änderung 413→290 Renders), App.tsx 4003→3232 Zeilen, Ressourcenfenster bekommt nur Änderungen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67
This commit is contained in:
33 files changed
+2299
-1353
No files matched your search
@@ -1077,8 +1077,20 @@ Prüfung des ganzen Programms (Rust-Kern, TS-Hülle, Build/Sicherheit), nur Code
|
||||
Plan: gleiche Szene (`demo_scene` bzw. `scene_v1.bin`) einmal per `render2d::headless` auf Metal, einmal im
|
||||
Chromium (Playwright, WebGPU) rendern und mit der Pixeltoleranz aus `tests/golden.rs` vergleichen; Chromium-WebGPU auf
|
||||
macOS-Runnern zuerst prüfen. · M
|
||||
- ○ **[121] App.tsx zerlegen, Neurendern stoppen.** `App.tsx:365` abonniert ganzes Projekt, 0× `memo`;
|
||||
Abschnitte in Hooks/Komponenten, Panels lesen den Store selbst; Nebenfenster bekommen Ops statt Projekt. · L
|
||||
- ◐ **[121] App.tsx zerlegen, Neurendern stoppen.** (3.11.) App.tsx 4003 → 3232 Zeilen: Befehls-Engine
|
||||
(`state/useCommandEngineHost`), 3D-Griffe (`state/useGrip3dEditing`), Layout-Blatt (`state/useSheetPane`),
|
||||
Darstellungs-Resolver (`state/useDisplayResolvers`), Inline-Editoren (`menus/InlineEditors`), Stempel-Editor
|
||||
(`ui/RoomStampEditorHost`). `memo` + stabile Handler (`state/useEvent`: `useEvent`/`useEventBundle`/`useSameData`)
|
||||
für Oberleiste (nur `projectName`), Menü-/Ansichtsleiste, Statusleiste, Befehlszeile (Ruhe-Ansicht der Engine
|
||||
geteilt), Hauptansicht `Content` (Plan/3D), Overlays, Icons. Panels: `hostWithMode` liefert bei gleichen Eingaben
|
||||
denselben Host; `PanelHostProvider` mit Store + `usePanelHostSelect`/`usePanelHostAction` (Werkzeug-Palette
|
||||
abonniert nur ihre Felder). Live-Massstab in `state/liveScaleStore` (Zoom rendert App nicht mehr).
|
||||
Ressourcen-Fenster bekommt nach dem ersten vollen Stand nur die geänderten Felder (`native/projectDelta`).
|
||||
Gemessen (`e2e/renderCount.spec.ts`, Musterhaus, unminifiziert): Wand-Änderung 413 → 290 Renders (Rest: ~200
|
||||
Plan-Primitive, Objekt-Info, Elemente-Baum), Zoom-Schritt 240 → 61. Nicht in der Tauri-App geprüft (Ressourcen-
|
||||
Fenster nur Unit-Test). Offen: App abonniert weiter das ganze Projekt (rendert je Op 1×, Kinder nicht); übrige
|
||||
Panels lesen noch den ganzen Host (`usePanelHost`); `usePanelHostBase` (1515 Z.) und Kontextmenü-Verdrahtung
|
||||
noch in App; andere Nebenfenster (Zeichnungsebenen, Ebenen) senden weiter ihren ganzen Zustand ([130]). · L
|
||||
- ✅ **[122] Zweites Kern-Dokument (`documentFor` → `shared`, Differenz-Abgleich) abschaffen.** (3.11.) `sync`/
|
||||
Differenz-Abgleich gestrichen; `documentFor` findet nur offene Dokumente über die Leseansicht (Store, CLI,
|
||||
`withDocument`). Abgewandelte Projekte: Fang beim Ziehen (`App.tsx` 3D-Griff, `useGripEditing`) über
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
// [121] Neurendern messen: wie viele React-Komponenten rendern bei EINER Wand-Änderung (Objekt-Info,
|
||||
// Musterhaus) bzw. bei einem Zoom-Schritt im Grundriss? Gezählt über einen schlanken DevTools-Haken
|
||||
// (`__REACT_DEVTOOLS_GLOBAL_HOOK__`, den React auch im Produktions-Build bedient) — ohne Produktcode.
|
||||
// Eine Komponente zählt, wenn sich ihre Props oder ihr Hook-Zustand seit dem letzten Commit
|
||||
// geändert haben (= sie hat gerendert). Die Zahlen stehen in der Ausgabe (Namen nur lesbar ohne
|
||||
// Minifizierung: `vite build --minify false`). Gemessen 3.11. (Musterhaus): Wand-Änderung 413 → 290,
|
||||
// Zoom-Schritt 240 → 61 (davon ~200 bzw. ~45 im Grundriss selbst). Die Schranken unten fangen den
|
||||
// Rückfall ab, dass wieder die ganze App mitrendert.
|
||||
import type { Page } from "@playwright/test";
|
||||
import { blurFocus, elementRows, expect, openSample, openTab, startNewProject, test } from "./app";
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
__renderCounts?: { on: boolean; total: number; byName: Record<string, number> };
|
||||
}
|
||||
}
|
||||
|
||||
async function installCounter(page: Page): Promise<void> {
|
||||
await page.addInitScript(() => {
|
||||
const stats = { on: false, total: 0, byName: {} as Record<string, number> };
|
||||
window.__renderCounts = stats;
|
||||
const seen = new WeakMap<object, { p: unknown; s: unknown }>();
|
||||
// Funktions-, Klassen-, forwardRef-, memo-Komponenten (React-18-Fiber-Tags).
|
||||
const COMPOSITE = new Set([0, 1, 11, 14, 15]);
|
||||
type Fiber = {
|
||||
tag: number;
|
||||
type: { displayName?: string; name?: string; render?: { name?: string }; type?: { name?: string } } | null;
|
||||
memoizedProps: unknown;
|
||||
memoizedState: unknown;
|
||||
alternate: Fiber | null;
|
||||
child: Fiber | null;
|
||||
sibling: Fiber | null;
|
||||
};
|
||||
const nameOf = (f: Fiber): string => {
|
||||
const t = f.type;
|
||||
if (!t) return "?";
|
||||
return t.displayName || t.name || t.render?.name || t.type?.name || "anon";
|
||||
};
|
||||
const walk = (root: Fiber | null) => {
|
||||
const stack: Fiber[] = root ? [root] : [];
|
||||
while (stack.length) {
|
||||
const f = stack.pop()!;
|
||||
if (COMPOSITE.has(f.tag)) {
|
||||
const key = (seen.has(f) ? f : f.alternate && seen.has(f.alternate) ? f.alternate : f) as object;
|
||||
const prev = seen.get(key);
|
||||
if (!prev || prev.p !== f.memoizedProps || prev.s !== f.memoizedState) {
|
||||
if (stats.on) {
|
||||
stats.total++;
|
||||
const n = nameOf(f);
|
||||
stats.byName[n] = (stats.byName[n] ?? 0) + 1;
|
||||
}
|
||||
}
|
||||
seen.set(key, { p: f.memoizedProps, s: f.memoizedState });
|
||||
}
|
||||
if (f.sibling) stack.push(f.sibling);
|
||||
if (f.child) stack.push(f.child);
|
||||
}
|
||||
};
|
||||
(window as unknown as { __REACT_DEVTOOLS_GLOBAL_HOOK__: unknown }).__REACT_DEVTOOLS_GLOBAL_HOOK__ = {
|
||||
supportsFiber: true,
|
||||
renderers: new Map(),
|
||||
inject: () => 1,
|
||||
onScheduleFiberRoot: () => {},
|
||||
onCommitFiberRoot: (_id: number, root: { current: Fiber }) => walk(root.current),
|
||||
onPostCommitFiberRoot: () => {},
|
||||
onCommitFiberUnmount: () => {},
|
||||
checkDCE: () => {},
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/** Zählt die Renders während `action` (plus Ausklingen) und gibt sie aus. */
|
||||
async function measure(page: Page, label: string, action: () => Promise<void>): Promise<number> {
|
||||
await page.evaluate(() => {
|
||||
const s = window.__renderCounts!;
|
||||
s.on = true;
|
||||
s.total = 0;
|
||||
s.byName = {};
|
||||
});
|
||||
await action();
|
||||
await page.waitForTimeout(800);
|
||||
const stats = await page.evaluate(() => {
|
||||
const s = window.__renderCounts!;
|
||||
s.on = false;
|
||||
return { total: s.total, byName: s.byName };
|
||||
});
|
||||
const byName = Object.entries(stats.byName)
|
||||
.sort((a, b) => b[1] - a[1])
|
||||
.map(([n, c]) => `${n}:${c}`)
|
||||
.join(" ");
|
||||
console.log(`[121] Renders ${label}: ${stats.total} — ${byName}`);
|
||||
return stats.total;
|
||||
}
|
||||
|
||||
test("Neurendern zählen: Wand-Änderung und Zoom-Schritt", async ({ page }) => {
|
||||
await installCounter(page);
|
||||
await startNewProject(page);
|
||||
await openSample(page);
|
||||
await openTab(page, "Elemente");
|
||||
await elementRows(page).filter({ hasText: "W1" }).click();
|
||||
await expect(page.getByText("Auswahl: 1 Wand")).toBeVisible();
|
||||
const top = page.locator(".objinfo-wall-anchor").first();
|
||||
await top.getByRole("button", { name: "Eigene" }).click();
|
||||
const field = top.getByLabel("Eigene Höhe");
|
||||
await field.fill("3.2");
|
||||
await page.waitForTimeout(500);
|
||||
|
||||
// Genau eine Op (Wand-Oberkante).
|
||||
const edit = await measure(page, "je Wand-Änderung", async () => {
|
||||
await field.press("Enter");
|
||||
await expect(page.getByText("Höhe").locator("..").filter({ hasText: "3.20 m" })).toBeVisible();
|
||||
});
|
||||
await blurFocus(page);
|
||||
|
||||
// Ein Mausrad-Schritt im Grundriss (ändert nur den Live-Massstab).
|
||||
const box = (await page.locator("svg.plan-svg").boundingBox())!;
|
||||
await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2);
|
||||
await page.waitForTimeout(300);
|
||||
const zoom = await measure(page, "je Zoom-Schritt", async () => {
|
||||
await page.mouse.wheel(0, -120);
|
||||
});
|
||||
|
||||
expect(edit, "Renders je Wand-Änderung").toBeLessThan(340);
|
||||
expect(zoom, "Renders je Zoom-Schritt").toBeLessThan(110);
|
||||
});
|
||||
+444
-1215
File diff suppressed because it is too large.
Load diff
+11
-3
@@ -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
|
||||
|
||||
@@ -0,0 +1,207 @@
|
||||
// Inline-Editoren aus dem Kontextmenü ([121] aus App.tsx herausgelöst): Ebene (Name, Farbe/Stift,
|
||||
// Strichstärke, Schraffur) und Zeichnungsebene (Name, Höhen, Ansichtsbereich). Wirken live auf den
|
||||
// Store; das Projekt lesen sie selbst (nur solange offen abonniert).
|
||||
//
|
||||
// Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md).
|
||||
|
||||
import type { ComponentProps } from "react";
|
||||
import { t } from "../i18n";
|
||||
import { activePenSet, resolvePenColor, resolvePenWeight } from "../model/penSets";
|
||||
import { findCategory } from "../model/layers";
|
||||
import type { DrawingLevel, LayerCategory } from "../model/types";
|
||||
import { useStore } from "../state/appStore";
|
||||
import { EditorField } from "../ui/EditorField";
|
||||
import { HatchSwatch } from "../ui/hatchPreview";
|
||||
import { PenColorField } from "../ui/PenColorField";
|
||||
import { InlineEditor } from "../views/InlineEditor";
|
||||
|
||||
export function LayerInlineEditor({
|
||||
editor,
|
||||
onClose,
|
||||
patchCategory,
|
||||
onSaveColor,
|
||||
}: {
|
||||
editor: { code: string; x: number; y: number };
|
||||
onClose: () => void;
|
||||
patchCategory: (code: string, patch: Partial<LayerCategory>) => void;
|
||||
onSaveColor: ComponentProps<typeof PenColorField>["onSaveColor"];
|
||||
}) {
|
||||
const project = useStore((s) => s.project);
|
||||
const cat = findCategory(project.layers, editor.code);
|
||||
if (!cat) return null;
|
||||
return (
|
||||
<InlineEditor
|
||||
x={editor.x}
|
||||
y={editor.y}
|
||||
title={t("editor.layerTitle", { code: cat.code })}
|
||||
onClose={onClose}
|
||||
>
|
||||
<EditorField label={t("editor.name")}>
|
||||
<input
|
||||
type="text"
|
||||
value={cat.name}
|
||||
autoFocus
|
||||
onChange={(e) =>
|
||||
patchCategory(cat.code, { name: e.target.value })
|
||||
}
|
||||
/>
|
||||
</EditorField>
|
||||
<EditorField label={t("editor.color")}>
|
||||
<PenColorField
|
||||
color={cat.colorPenId ? resolvePenColor(project, cat.colorPenId) : cat.color}
|
||||
penId={cat.colorPenId}
|
||||
pens={project.pens ?? []}
|
||||
activeStyles={activePenSet(project)?.pens}
|
||||
customPalettes={project.customPalettes}
|
||||
builtinBanks={project.builtinPaletteBanks}
|
||||
onSaveColor={onSaveColor}
|
||||
showWeight
|
||||
onColorChange={(color) => patchCategory(cat.code, { color, colorPenId: undefined })}
|
||||
onPenChange={(colorPenId) =>
|
||||
patchCategory(cat.code, {
|
||||
colorPenId,
|
||||
...(colorPenId
|
||||
? { color: resolvePenColor(project, colorPenId), lw: resolvePenWeight(project, colorPenId) }
|
||||
: {}),
|
||||
})
|
||||
}
|
||||
/>
|
||||
</EditorField>
|
||||
<EditorField label={t("editor.lineWeight")}>
|
||||
<span className="editor-num">
|
||||
<input
|
||||
type="number"
|
||||
step={0.01}
|
||||
min={0.01}
|
||||
value={cat.lw}
|
||||
disabled={!!cat.colorPenId}
|
||||
onChange={(e) =>
|
||||
patchCategory(cat.code, { lw: Number(e.target.value) })
|
||||
}
|
||||
/>
|
||||
<span className="editor-unit">{t("editor.unit.mm")}</span>
|
||||
</span>
|
||||
</EditorField>
|
||||
<EditorField label={t("editor.hatch")}>
|
||||
<span className="editor-hatch">
|
||||
<select
|
||||
value={cat.hatch ?? ""}
|
||||
onChange={(e) =>
|
||||
patchCategory(cat.code, {
|
||||
hatch: e.target.value || undefined,
|
||||
})
|
||||
}
|
||||
>
|
||||
<option value="">{t("resources.viewHatch.none")}</option>
|
||||
{project.hatches.map((h) => (
|
||||
<option key={h.id} value={h.id}>
|
||||
{h.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{cat.hatch &&
|
||||
(() => {
|
||||
const h = project.hatches.find((ht) => ht.id === cat.hatch);
|
||||
return h ? <HatchSwatch hatch={h} size={26} /> : null;
|
||||
})()}
|
||||
</span>
|
||||
</EditorField>
|
||||
</InlineEditor>
|
||||
);
|
||||
}
|
||||
|
||||
export function LevelInlineEditor({
|
||||
editor,
|
||||
onClose,
|
||||
patchLevel,
|
||||
}: {
|
||||
editor: { id: string; x: number; y: number };
|
||||
onClose: () => void;
|
||||
patchLevel: (id: string, patch: Partial<DrawingLevel>) => void;
|
||||
}) {
|
||||
const project = useStore((s) => s.project);
|
||||
const level = project.drawingLevels.find((z) => z.id === editor.id);
|
||||
if (!level) return null;
|
||||
const isFloor = level.kind === "floor";
|
||||
return (
|
||||
<InlineEditor
|
||||
x={editor.x}
|
||||
y={editor.y}
|
||||
title={level.name}
|
||||
onClose={onClose}
|
||||
>
|
||||
<EditorField label={t("editor.name")}>
|
||||
<input
|
||||
type="text"
|
||||
value={level.name}
|
||||
autoFocus
|
||||
onChange={(e) => patchLevel(level.id, { name: e.target.value })}
|
||||
/>
|
||||
</EditorField>
|
||||
{isFloor && (
|
||||
<>
|
||||
<EditorField label={t("editor.floorHeight")}>
|
||||
<span className="editor-num">
|
||||
<input
|
||||
type="number"
|
||||
step={0.05}
|
||||
min={0}
|
||||
value={level.floorHeight ?? 0}
|
||||
onChange={(e) =>
|
||||
patchLevel(level.id, {
|
||||
floorHeight: Number(e.target.value),
|
||||
})
|
||||
}
|
||||
/>
|
||||
<span className="editor-unit">{t("editor.unit.m")}</span>
|
||||
</span>
|
||||
</EditorField>
|
||||
<EditorField label={t("editor.cutHeight")}>
|
||||
<span className="editor-num">
|
||||
<input
|
||||
type="number"
|
||||
step={0.05}
|
||||
min={0}
|
||||
value={level.cutHeight ?? 0}
|
||||
onChange={(e) =>
|
||||
patchLevel(level.id, {
|
||||
cutHeight: Number(e.target.value),
|
||||
})
|
||||
}
|
||||
/>
|
||||
<span className="editor-unit">{t("editor.unit.m")}</span>
|
||||
</span>
|
||||
</EditorField>
|
||||
{/* Ansichtsbereich ([36]): leer = unbegrenzt (Darstellung wie bisher). */}
|
||||
{(["viewTop", "viewBottom", "viewDepth"] as const).map((k) => (
|
||||
<EditorField key={k} label={t(`editor.${k}`)}>
|
||||
<span className="editor-num">
|
||||
<input
|
||||
type="number"
|
||||
step={0.1}
|
||||
min={k === "viewDepth" ? 0 : undefined}
|
||||
data-testid={`level-${k}`}
|
||||
value={level[k] ?? ""}
|
||||
placeholder="∞"
|
||||
onChange={(e) =>
|
||||
patchLevel(level.id, {
|
||||
[k]: e.target.value === "" ? undefined : Number(e.target.value),
|
||||
})
|
||||
}
|
||||
/>
|
||||
<span className="editor-unit">{t("editor.unit.m")}</span>
|
||||
</span>
|
||||
</EditorField>
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
{!isFloor && (
|
||||
<div className="editor-note">
|
||||
{level.kind === "drawing"
|
||||
? t("editor.noHeightDrawing")
|
||||
: t("editor.noHeightSection")}
|
||||
</div>
|
||||
)}
|
||||
</InlineEditor>
|
||||
);
|
||||
}
|
||||
@@ -16,6 +16,7 @@ import { useEffect, useMemo, useState } from "react";
|
||||
import { ResourceManager } from "../ui/ResourceManager";
|
||||
import type { ResourceManagerHandlers, TabId } from "../ui/ResourceManager";
|
||||
import type { Project } from "../model/types";
|
||||
import { applyProjectDelta, type ProjectDelta } from "./projectDelta";
|
||||
import { t } from "../i18n";
|
||||
|
||||
/** Alle Felder von ResourceManagerHandlers sind Funktionen — für den Proxy unten. */
|
||||
@@ -44,6 +45,13 @@ export function ResourceWindowApp() {
|
||||
unlisten.push(
|
||||
await listen<Project>("resource-sync-project", (e) => setProject(e.payload)),
|
||||
);
|
||||
// Danach nur noch die geänderten Felder ([121]); ohne vollen Stand verworfen (der kommt
|
||||
// mit der „ready"-Antwort).
|
||||
unlisten.push(
|
||||
await listen<ProjectDelta>("resource-sync-delta", (e) =>
|
||||
setProject((p) => (p ? applyProjectDelta(p, e.payload) : p)),
|
||||
),
|
||||
);
|
||||
unlisten.push(await listen<TabId>("resource-set-tab", (e) => setTab(e.payload)));
|
||||
// Hauptfenster um den aktuellen Stand bitten — deckt den Fall ab, dass
|
||||
// dieses Fenster NACH dem letzten Projekt-Push gestartet ist.
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { Project } from "../model/types";
|
||||
import { applyProjectDelta, projectDelta } from "./projectDelta";
|
||||
|
||||
const base = {
|
||||
id: "p",
|
||||
name: "Demo",
|
||||
walls: [{ id: "w1" }],
|
||||
hatches: [{ id: "h1" }],
|
||||
rooms: [],
|
||||
} as unknown as Project;
|
||||
|
||||
describe("projectDelta", () => {
|
||||
it("ohne Änderung: null", () => {
|
||||
expect(projectDelta(base, { ...base })).toBeNull();
|
||||
});
|
||||
|
||||
it("nur geänderte Felder (Referenz), zusammengesetzt gleich dem neuen Stand", () => {
|
||||
const next = { ...base, walls: [{ id: "w1" }, { id: "w2" }] } as unknown as Project;
|
||||
const d = projectDelta(base, next)!;
|
||||
expect(Object.keys(d.set)).toEqual(["walls"]);
|
||||
expect(d.unset).toEqual([]);
|
||||
expect(applyProjectDelta(base, d)).toEqual(next);
|
||||
});
|
||||
|
||||
it("neue und entfernte Felder", () => {
|
||||
const next = { ...base, projectNumber: "42" } as Record<string, unknown>;
|
||||
delete next.rooms;
|
||||
const d = projectDelta(base, next as unknown as Project)!;
|
||||
expect(d.set).toEqual({ projectNumber: "42" });
|
||||
expect(d.unset).toEqual(["rooms"]);
|
||||
const out = applyProjectDelta(base, d) as unknown as Record<string, unknown>;
|
||||
expect(out).toEqual(next);
|
||||
expect("rooms" in out).toBe(false);
|
||||
// Die Basis bleibt unverändert.
|
||||
expect((base as unknown as Record<string, unknown>).rooms).toEqual([]);
|
||||
});
|
||||
|
||||
it("überlebt die JSON-Serialisierung der Brücke (undefined-Feld → entfernt)", () => {
|
||||
const next = { ...base, name: "Neu", projectNumber: undefined } as unknown as Project;
|
||||
const d = projectDelta(base, next)!;
|
||||
const wire = JSON.parse(JSON.stringify(d));
|
||||
expect(applyProjectDelta(base, wire)).toEqual(JSON.parse(JSON.stringify(next)));
|
||||
});
|
||||
|
||||
it("auf undefined gesetztes Feld wird entfernt", () => {
|
||||
const withNumber = { ...base, projectNumber: "1" } as unknown as Project;
|
||||
const next = { ...withNumber, projectNumber: undefined } as unknown as Project;
|
||||
const d = projectDelta(withNumber, next)!;
|
||||
expect(d.unset).toEqual(["projectNumber"]);
|
||||
const wire = JSON.parse(JSON.stringify(d));
|
||||
expect("projectNumber" in applyProjectDelta(withNumber, wire)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,46 @@
|
||||
// Differenz zweier Projekt-Stände auf oberster Ebene ([121]) — für die Sync-Brücke der
|
||||
// Nebenfenster. Die Leseansicht teilt unveränderte Listen (`applyOps` legt nur geänderte neu an),
|
||||
// ein Referenzvergleich je Feld findet also genau die geänderten Teile. Statt des ganzen Projekts
|
||||
// geht nur `{ set, unset }` über IPC; das Fenster setzt das Projekt daraus wieder zusammen.
|
||||
//
|
||||
// Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md).
|
||||
|
||||
import type { Project } from "../model/types";
|
||||
|
||||
export interface ProjectDelta {
|
||||
/** Geänderte oder neue Felder (ganze Werte). */
|
||||
set: Partial<Project>;
|
||||
/** Entfernte Felder. */
|
||||
unset: string[];
|
||||
}
|
||||
|
||||
/** Felder von `next`, deren Referenz sich gegenüber `prev` geändert hat; `null` = keine Änderung. */
|
||||
export function projectDelta(prev: Project, next: Project): ProjectDelta | null {
|
||||
const a = prev as unknown as Record<string, unknown>;
|
||||
const b = next as unknown as Record<string, unknown>;
|
||||
const set: Record<string, unknown> = {};
|
||||
const unset: string[] = [];
|
||||
let changed = false;
|
||||
// `undefined` übersteht die JSON-Serialisierung der Brücke nicht: solche Felder gelten als entfernt.
|
||||
const has = (o: Record<string, unknown>, k: string) => o[k] !== undefined;
|
||||
for (const k of Object.keys(b)) {
|
||||
if (has(b, k) && a[k] !== b[k]) {
|
||||
set[k] = b[k];
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
for (const k of Object.keys(a)) {
|
||||
if (has(a, k) && !has(b, k)) {
|
||||
unset.push(k);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
return changed ? { set: set as Partial<Project>, unset } : null;
|
||||
}
|
||||
|
||||
/** Wendet eine Differenz an (neues Objekt; `base` bleibt unverändert). */
|
||||
export function applyProjectDelta(base: Project, delta: ProjectDelta): Project {
|
||||
const out = { ...(base as unknown as Record<string, unknown>), ...(delta.set as Record<string, unknown>) };
|
||||
for (const k of delta.unset) delete out[k];
|
||||
return out as unknown as Project;
|
||||
}
|
||||
@@ -5,9 +5,12 @@
|
||||
// gemeinsamer JS-Speicher, also kein direkter Store-Zugriff. Die Brücke
|
||||
// synchronisiert daher explizit über Tauri-Events (@tauri-apps/api/event):
|
||||
// • Hauptfenster → Ressourcen-Fenster: „resource-sync-project" mit dem
|
||||
// kompletten (JSON-serialisierbaren) Project bei jeder Änderung + einmal
|
||||
// sofort, sobald das Ressourcen-Fenster „resource-window-ready" meldet
|
||||
// (Race-Schutz: das Fenster könnte später starten als der erste Push).
|
||||
// kompletten (JSON-serialisierbaren) Project einmal sofort, sobald das
|
||||
// Ressourcen-Fenster „resource-window-ready" meldet (Race-Schutz: das
|
||||
// Fenster könnte später starten als der erste Push); danach bei jeder
|
||||
// Änderung nur „resource-sync-delta" mit den geänderten Feldern der obersten
|
||||
// Ebene ([121], `projectDelta.ts`) — eine Wand-Änderung schickt `walls`,
|
||||
// nicht das ganze Projekt.
|
||||
// • Ressourcen-Fenster → Hauptfenster: „resource-command" mit
|
||||
// `{ name, args }` — der Name eines ResourceManagerHandlers-Feldes plus
|
||||
// seine Argumente. Das Hauptfenster ruft den ECHTEN Handler auf (der
|
||||
@@ -21,6 +24,7 @@
|
||||
import { useEffect, useRef } from "react";
|
||||
import { isTauriRuntime } from "./projectFile";
|
||||
import type { Project } from "../model/types";
|
||||
import { projectDelta } from "./projectDelta";
|
||||
import type { ResourceManagerHandlers, TabId } from "../ui/ResourceManager";
|
||||
import { BORDERLESS_WINDOW_CHROME } from "./windowChrome";
|
||||
|
||||
@@ -71,6 +75,9 @@ export function useResourceWindowHost(
|
||||
handlersRef.current = handlers;
|
||||
const projectRef = useRef(project);
|
||||
projectRef.current = project;
|
||||
// Stand, den das Fenster zuletzt bekommen hat (Basis der nächsten Differenz); null = beim
|
||||
// nächsten Mal das ganze Projekt senden.
|
||||
const sentRef = useRef<Project | null>(null);
|
||||
|
||||
// Befehle vom Ressourcen-Fenster entgegennehmen + auf die echten Handler
|
||||
// anwenden, UND bei „ready" (Fenster gerade erst gestartet) sofort das
|
||||
@@ -94,9 +101,11 @@ export function useResourceWindowHost(
|
||||
);
|
||||
unlisten.push(
|
||||
await listen("resource-window-ready", () => {
|
||||
void emitTo(RESOURCE_WINDOW_LABEL, "resource-sync-project", projectRef.current).catch(
|
||||
() => {},
|
||||
);
|
||||
const full = projectRef.current;
|
||||
sentRef.current = full;
|
||||
void emitTo(RESOURCE_WINDOW_LABEL, "resource-sync-project", full).catch(() => {
|
||||
sentRef.current = null;
|
||||
});
|
||||
}),
|
||||
);
|
||||
})();
|
||||
@@ -119,9 +128,24 @@ export function useResourceWindowHost(
|
||||
const timer = setTimeout(() => {
|
||||
void (async () => {
|
||||
const { WebviewWindow } = await import("@tauri-apps/api/webviewWindow");
|
||||
if (cancelled || !(await WebviewWindow.getByLabel(RESOURCE_WINDOW_LABEL))) return;
|
||||
if (cancelled) return;
|
||||
if (!(await WebviewWindow.getByLabel(RESOURCE_WINDOW_LABEL))) {
|
||||
// Fenster zu: beim nächsten Öffnen meldet es „ready" und bekommt das ganze Projekt.
|
||||
sentRef.current = null;
|
||||
return;
|
||||
}
|
||||
const { emitTo } = await import("@tauri-apps/api/event");
|
||||
await emitTo(RESOURCE_WINDOW_LABEL, "resource-sync-project", project).catch(() => {});
|
||||
const prev = sentRef.current;
|
||||
sentRef.current = project;
|
||||
const onFail = () => {
|
||||
sentRef.current = null;
|
||||
};
|
||||
if (!prev) {
|
||||
await emitTo(RESOURCE_WINDOW_LABEL, "resource-sync-project", project).catch(onFail);
|
||||
return;
|
||||
}
|
||||
const delta = projectDelta(prev, project);
|
||||
if (delta) await emitTo(RESOURCE_WINDOW_LABEL, "resource-sync-delta", delta).catch(onFail);
|
||||
})();
|
||||
}, 150);
|
||||
return () => {
|
||||
|
||||
+4
-4
@@ -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" />
|
||||
)}
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
});
|
||||
+126
-4
@@ -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 {
|
||||
@@ -845,6 +845,18 @@ export function hostWithMode(
|
||||
setModeFor: (id: string | null, mode: DisplayMode) => void,
|
||||
measurement: MeasurementReadout | null = null,
|
||||
): PanelHost {
|
||||
const mode = modeFor(activeTab);
|
||||
// Gleiche Eingaben → derselbe Wert ([121]): sonst wäre der Host bei JEDEM App-Render neu und
|
||||
// alle Panels würden mitrendern, auch wenn sich weder Projekt noch Auswahl geändert haben.
|
||||
let perBase = HOST_CACHE.get(base);
|
||||
if (!perBase) {
|
||||
perBase = new Map();
|
||||
HOST_CACHE.set(base, perBase);
|
||||
}
|
||||
const hit = perBase.get(activeTab);
|
||||
if (hit && hit.mode === mode && hit.measurement === measurement && hit.setModeFor === setModeFor) {
|
||||
return hit.value;
|
||||
}
|
||||
const value: PanelHostValue = {
|
||||
...base,
|
||||
// Live-Messwerte NICHT aus dem memoisierten `base` (dort wären sie eingefroren,
|
||||
@@ -852,9 +864,119 @@ export function hostWithMode(
|
||||
// Mausbewegung neu gebaut). Hier bei jedem Render frisch injiziert.
|
||||
measurement,
|
||||
displayMode: {
|
||||
mode: modeFor(activeTab),
|
||||
setMode: (mode) => setModeFor(activeTab, mode),
|
||||
mode,
|
||||
setMode: (m) => setModeFor(activeTab, m),
|
||||
},
|
||||
};
|
||||
return value as unknown as PanelHost;
|
||||
const host = value as unknown as PanelHost;
|
||||
perBase.set(activeTab, { mode, measurement, setModeFor, value: host });
|
||||
return host;
|
||||
}
|
||||
|
||||
/** Zuletzt gebauter Host je Basis-Wert und Tab (s. `hostWithMode`). */
|
||||
const HOST_CACHE = new WeakMap<
|
||||
object,
|
||||
Map<
|
||||
string | null,
|
||||
{
|
||||
mode: DisplayMode;
|
||||
measurement: MeasurementReadout | null;
|
||||
setModeFor: (id: string | null, mode: DisplayMode) => void;
|
||||
value: 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;
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
// LIVE Papier-Massstab-Nenner der Plan-Ansicht AUSSERHALB von React-State ([121]). PlanView meldet
|
||||
// ihn bei jedem Zoom-Schritt; als State in App.tsx hat jeder Mausrad-Schritt die ganze App neu
|
||||
// gerendert. Hier rendert nur, wer ihn abonniert (die Zoom-Anzeige der Oberleiste).
|
||||
// null = keine Plan-Ansicht aktiv.
|
||||
|
||||
import { useSyncExternalStore } from "react";
|
||||
|
||||
let current: number | null = null;
|
||||
const listeners = new Set<() => void>();
|
||||
|
||||
export function setLiveScale(next: number | null): void {
|
||||
if (next === current) return;
|
||||
current = next;
|
||||
for (const l of listeners) l();
|
||||
}
|
||||
|
||||
export function getLiveScale(): number | null {
|
||||
return current;
|
||||
}
|
||||
|
||||
function subscribe(listener: () => void): () => void {
|
||||
listeners.add(listener);
|
||||
return () => listeners.delete(listener);
|
||||
}
|
||||
|
||||
export function useLiveScale(): number | null {
|
||||
return useSyncExternalStore(subscribe, getLiveScale, getLiveScale);
|
||||
}
|
||||
|
||||
/**
|
||||
* Live-Zoom in Prozent RELATIV zum angewandten Papier-Massstab: 100 % = Live-Ansicht steht exakt
|
||||
* im angewandten Massstab (liveScale == scaleDenominator). Reinzoomen > 100 %, Rauszoomen < 100 %.
|
||||
* Ohne Live-Massstab (keine Plan-Ansicht) Fallback 100 %.
|
||||
*/
|
||||
export function zoomPercentOf(scaleDenominator: number, liveScale: number | null): number {
|
||||
return liveScale != null && liveScale > 0 ? (scaleDenominator / liveScale) * 100 : 100;
|
||||
}
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
// 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;
|
||||
}
|
||||
|
||||
/** Strukturgleichheit für reine Daten (Zahlen, Strings, Arrays, flache Objekte). */
|
||||
function sameData(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;
|
||||
if (Array.isArray(a) !== Array.isArray(b)) 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 (!sameData((a as Record<string, unknown>)[k], (b as Record<string, unknown>)[k])) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Behält die vorige Referenz, solange der neue Wert strukturell gleich ist — für je Render neu
|
||||
* berechnete, kleine Daten (Griff-Listen), die an `memo`-Kinder gehen. Nicht für grosse Listen.
|
||||
*/
|
||||
export function useSameData<T>(value: T): T {
|
||||
const ref = useRef(value);
|
||||
if (!sameData(ref.current, value)) ref.current = value;
|
||||
return ref.current;
|
||||
}
|
||||
@@ -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),
|
||||
};
|
||||
}
|
||||
@@ -6,6 +6,7 @@
|
||||
// Extrahiert aus App.tsx. Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md).
|
||||
|
||||
import { useRef, useState, type RefObject } from "react";
|
||||
import { useEventBundle, useSameData } from "./useEvent";
|
||||
import { add, dot, leftNormal, normalize, scale, sub, wallCorners } from "../model/geometry";
|
||||
import type { Ceiling, Drawing2D, EdgeGrip, Excavation, Project, Room, Stair, Vec2 } from "../model/types";
|
||||
import { wallTypeThickness } from "../model/types";
|
||||
@@ -1571,11 +1572,17 @@ export function useGripEditing(opts: {
|
||||
const pendingNow = pendingGripRef.current ?? pendingWallGripRef.current ?? pendingAreaGripRef.current;
|
||||
const displayGrips = pendingNow ? grips.map((g, i) => (i === pendingNow.flat ? pendingNow.pt : g)) : grips;
|
||||
|
||||
// Referenzstabil für die memoisierte Hauptansicht ([121]): gleiche Griffe → gleiche Referenz,
|
||||
// Handler mit fester Identität (rufen die Fassung des letzten Renders).
|
||||
const stableGrips = useSameData(displayGrips);
|
||||
const stableHandleLines = useSameData(gripHandleLines);
|
||||
const stableEdgeGrips = useSameData(edgeGrips);
|
||||
const stableGripHandlers = useEventBundle(gripHandlers);
|
||||
return {
|
||||
grips: displayGrips,
|
||||
gripHandleLines,
|
||||
edgeGrips,
|
||||
gripHandlers,
|
||||
grips: stableGrips,
|
||||
gripHandleLines: stableHandleLines,
|
||||
edgeGrips: stableEdgeGrips,
|
||||
gripHandlers: stableGripHandlers,
|
||||
gripEdit,
|
||||
setGripEdit,
|
||||
gripEditFields,
|
||||
|
||||
@@ -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],
|
||||
);
|
||||
}
|
||||
@@ -36,24 +36,14 @@ export function useTopBarState() {
|
||||
const setSnapColor = useStore((s) => s.setSnapColor);
|
||||
const scaleDenominator = useStore((s) => s.scaleDenominator);
|
||||
const setScaleDenominator = useStore((s) => s.setScaleDenominator);
|
||||
// LIVE Papier-Massstab-Nenner aus der View-Transform (PlanView meldet ihn);
|
||||
// null = keine Plan-Ansicht aktiv. Transienter UI-State, bleibt lokal.
|
||||
const [liveScale, setLiveScale] = useState<number | null>(null);
|
||||
// Der LIVE Papier-Massstab (PlanView meldet ihn) lebt in `liveScaleStore` ([121]): sonst
|
||||
// rendert jeder Zoom-Schritt die ganze App neu.
|
||||
// „Angewählter" Ausschnitt (View-Snapshot): bleibt gesetzt, solange der
|
||||
// Live-Zustand EXAKT dem Ausschnitt entspricht (siehe Effekt weiter unten).
|
||||
// Steuert die Footer-Bar + die Aktiv-Markierung im Ausschnitte-Panel.
|
||||
const [selectedViewSnapshotId, setSelectedViewSnapshotId] = useState<
|
||||
string | null
|
||||
>(null);
|
||||
// Live-Zoom in Prozent RELATIV zum angewandten Papier-Massstab: 100 % =
|
||||
// Live-Ansicht steht exakt im angewandten Massstab (liveScale == scaleDenominator).
|
||||
// Reinzoomen > 100 %, Rauszoomen < 100 %. Einzige Quelle: angewandter Nenner
|
||||
// (scaleDenominator) / Live-Nenner (liveScale). Ohne Live-Massstab (keine
|
||||
// Plan-Ansicht) Fallback 100 %.
|
||||
const zoomPercent =
|
||||
liveScale != null && liveScale > 0
|
||||
? (scaleDenominator / liveScale) * 100
|
||||
: 100;
|
||||
|
||||
return {
|
||||
detail,
|
||||
@@ -78,10 +68,7 @@ export function useTopBarState() {
|
||||
setSnapColor,
|
||||
scaleDenominator,
|
||||
setScaleDenominator,
|
||||
liveScale,
|
||||
setLiveScale,
|
||||
selectedViewSnapshotId,
|
||||
setSelectedViewSnapshotId,
|
||||
zoomPercent,
|
||||
};
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -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>
|
||||
);
|
||||
},
|
||||
);
|
||||
));
|
||||
@@ -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} />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -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} />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,57 @@
|
||||
// Stempel-Editor eines Raums als schwebendes Fenster ([121] aus App.tsx herausgelöst): Doppelklick
|
||||
// auf einen Raumstempel bzw. Button in der Objekt-Info öffnet ihn. Strukturierter Stempel für neue
|
||||
// Räume, freier Rich-Text nur noch als Fallback für Alt-Räume. Liest die Räume selbst aus dem Store.
|
||||
//
|
||||
// Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md).
|
||||
|
||||
import { defaultRoomStamp } from "../model/roomStamp";
|
||||
import type { Room } from "../model/types";
|
||||
import { RoomStampEditor } from "../panels/RoomStampEditor";
|
||||
import { useStore } from "../state/appStore";
|
||||
import { docFromText, type RichTextDoc } from "../text/richText";
|
||||
import { TextEditorDialog } from "./TextEditorDialog";
|
||||
|
||||
const NO_ROOMS: Room[] = [];
|
||||
|
||||
export function RoomStampEditorHost({
|
||||
roomId,
|
||||
onClose,
|
||||
setRoomStamp,
|
||||
setRoomStampDoc,
|
||||
}: {
|
||||
roomId: string;
|
||||
onClose: () => void;
|
||||
setRoomStamp: (id: string, stamp: NonNullable<Room["stamp"]>) => void;
|
||||
setRoomStampDoc: (id: string, doc: RichTextDoc) => void;
|
||||
}) {
|
||||
const rooms = useStore((s) => s.project.rooms) ?? NO_ROOMS;
|
||||
const room = rooms.find((r) => r.id === roomId);
|
||||
if (!room) return null;
|
||||
// Strukturierter Stempel für neue Räume (kein Alt-Rich-Text) bzw. sobald
|
||||
// einer gesetzt ist; freier Text nur noch als Fallback für Alt-Räume,
|
||||
// die einen stampDoc, aber keinen strukturierten Stempel tragen.
|
||||
const useStructured = Boolean(room.stamp) || !room.stampDoc;
|
||||
if (useStructured) {
|
||||
return (
|
||||
<RoomStampEditor
|
||||
value={room.stamp ?? defaultRoomStamp(room)}
|
||||
onApply={(edited) => {
|
||||
setRoomStamp(room.id, edited);
|
||||
onClose();
|
||||
}}
|
||||
onCancel={() => onClose()}
|
||||
/>
|
||||
);
|
||||
}
|
||||
const doc = room.stampDoc ?? docFromText(room.name);
|
||||
return (
|
||||
<TextEditorDialog
|
||||
value={doc}
|
||||
onApply={(edited) => {
|
||||
setRoomStampDoc(room.id, edited);
|
||||
onClose();
|
||||
}}
|
||||
onCancel={() => onClose()}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -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
@@ -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,
|
||||
|
||||
+15
-56
@@ -8,11 +8,11 @@
|
||||
// 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 { useLiveScale, zoomPercentOf } from "../state/liveScaleStore";
|
||||
import { createPortal } from "react-dom";
|
||||
import { Dropdown } from "./Dropdown";
|
||||
import type { DropdownItem, DropdownOption } from "./Dropdown";
|
||||
@@ -56,7 +56,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 +65,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
|
||||
@@ -1073,8 +1031,7 @@ export interface ViewRibbonTabProps {
|
||||
detailEnabled: boolean;
|
||||
scaleDenominator: number;
|
||||
onApplyScale: (n: number) => void;
|
||||
liveScale: number | null;
|
||||
zoomPercent: number;
|
||||
/** Plan-Zoom aktiv; der Live-Massstab kommt aus `state/liveScaleStore` (nicht als Prop, [121]). */
|
||||
zoomEnabled: boolean;
|
||||
onFit: () => void;
|
||||
onFitSelection: () => void;
|
||||
@@ -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,
|
||||
@@ -1115,8 +1072,6 @@ export function ViewRibbonTab({
|
||||
detailEnabled,
|
||||
scaleDenominator,
|
||||
onApplyScale,
|
||||
liveScale,
|
||||
zoomPercent,
|
||||
zoomEnabled,
|
||||
onFit,
|
||||
onFitSelection,
|
||||
@@ -1133,6 +1088,10 @@ export function ViewRibbonTab({
|
||||
textTarget,
|
||||
textStyles,
|
||||
}: ViewRibbonTabProps) {
|
||||
// Live-Massstab direkt abonnieren: ein Zoom-Schritt rendert nur diese Leiste neu ([121]).
|
||||
const liveScaleRaw = useLiveScale();
|
||||
const liveScale = zoomEnabled ? liveScaleRaw : null;
|
||||
const zoomPercent = zoomPercentOf(scaleDenominator, liveScaleRaw);
|
||||
// „frei" wird über einen In-App-Dialog erfasst (window.prompt ist im Tauri-
|
||||
// WKWebView deaktiviert); akzeptiert „1:35" ODER „35".
|
||||
const [scalePromptOpen, setScalePromptOpen] = useState(false);
|
||||
@@ -1389,10 +1348,10 @@ export function ViewRibbonTab({
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
export function TopBar({
|
||||
project,
|
||||
export const TopBar = memo(function TopBar({
|
||||
projectName,
|
||||
menuBar,
|
||||
viewControls,
|
||||
}: TopBarProps) {
|
||||
@@ -1465,11 +1424,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
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -6,7 +6,7 @@
|
||||
// Extrahiert aus App.tsx (top-level, alles über Props — keine App-Closure).
|
||||
// Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md).
|
||||
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, memo } from "react";
|
||||
|
||||
import { t } from "../i18n";
|
||||
import { LayoutSheetPane, type LayoutSheetHandlers, type SheetPlanProps } from "../ui/LayoutSheet";
|
||||
@@ -66,8 +66,11 @@ const HIGHLIGHT_RGB: [number, number, number] = [1.0, 0.5, 0.1];
|
||||
/** Rot der Kollisions-Hüllquader im 3D ([T8]). */
|
||||
const CLASH_RGB: [number, number, number] = [0.88, 0.14, 0.16];
|
||||
|
||||
/** Hauptinhalt — abhängig von der aktiven Zeichnungsebene und dem Ansichtstyp. */
|
||||
export function Content({
|
||||
/**
|
||||
* Hauptinhalt — abhängig von der aktiven Zeichnungsebene und dem Ansichtstyp. `memo` ([121]): App
|
||||
* reicht stabile Handler, ein App-Render ohne geänderte Eingaben zeichnet Plan/3D nicht neu.
|
||||
*/
|
||||
export const Content = memo(function Content({
|
||||
project,
|
||||
level,
|
||||
viewType,
|
||||
@@ -603,7 +606,7 @@ export function Content({
|
||||
)}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
// Auswahl-Felder (wallId/ceilingId/…) aus einer Referenz-Überlagerung entfernen:
|
||||
// die Geometrie stammt aus einer FREMDEN Projektion (z. B. Schnitt-Koordinaten
|
||||
|
||||
Reference in new issue
Block a user