9 Commits
Author SHA1 Message Date
Claude b3325a98e7 [333] Blätter-Leiste: Blätter per Ziehen umsortieren, Duplizieren und Löschen mit Rückfrage (Kontextmenü, „…“) 2026-11-27 08:20:54 +00:00
Claude 516eaf16be [333] 3D-Griffe: Treppe, Öffnung, Stütze; Plan: nächster Griff gewinnt
check / check (push) Canceled after 0s
check / licenses (push) Canceled after 0s
check / e2e (push) Canceled after 0s
macos / native (push) Canceled after 0s
Treppe (Bewegpunkt + Parameter-Griffe), Wandöffnung (Gleit-Griff auf Brüstungshöhe) und Stütze (Mitte, Ecken) haben 3D-Griffe mit denselben Kern-Anfragen wie im Plan. Plan-Treffer: nächster Griff statt erster im Radius (kleine Stütze: Ecke statt Mitte).
2026-11-27 05:47:54 +00:00
Claude 228921a193 [333] Grundriss: Griffe für Stützen, freie Körper und Bibliotheks-Objekte
check / check (push) Canceled after 0s
check / licenses (push) Canceled after 0s
check / e2e (push) Canceled after 0s
macos / native (push) Canceled after 0s
Stütze: Mitte verschiebt, Eck-Griffe setzen Breite/Tiefe symmetrisch um die Mitte (auch gedreht), Rundprofil Radius-Griff, Dreh-Griff (Kern grips.rs columnGrip). Freier Körper: Profil-Ecken + Verschiebe-Griff, Kreis/B-Rep nur verschieben (solidGrip). Bibliotheks-Objekt: Dreh-Griff neben dem Einfügepunkt. Rust-Tests + e2e grips333.
2026-11-27 04:45:44 +00:00
Claude c3bfe2cf59 [333] Schnitt: waagrechte Griffe für Decke und Wand (Ende entlang der Schnittlinie ziehen, Kern sheet_height::end_ops)
check / check (push) Canceled after 0s
check / licenses (push) Canceled after 0s
check / e2e (push) Canceled after 0s
macos / native (push) Canceled after 0s
2026-11-27 02:41:25 +00:00
Claude 880d7751f9 [333] Layout: Blätter-Leiste mit Vorschau (wie die Seitenpalette in InDesign) 2026-11-27 00:54:44 +00:00
Claude 58ce7ebabb [333] Blatt: Inhalts-Griff verschiebt den Plan im Rahmen (wie InDesign) 2026-11-27 00:49:58 +00:00
Claude 69507b10db [333] Layout-Oberfläche: Blatt-Leiste in einer Zeile mit Symbolen, Blatt-Werkzeuge, Blatt in der Objekt-Info 2026-11-27 00:48:24 +00:00
Claude e788ebb990 [333] Gerade Treppe: Griffe an allen vier Ecken (Breite, Lauflänge)
check / check (push) Canceled after 0s
check / licenses (push) Canceled after 0s
check / e2e (push) Canceled after 0s
macos / native (push) Canceled after 0s
2026-11-26 23:51:04 +00:00
Claude 003271953d [333] Blatt: Viewport vergrössern lässt den Inhalt liegen (wie InDesign) 2026-11-26 23:28:19 +00:00
46 changed files with 2225 additions and 142 deletions

No files matched your search

+1 -1
View File
@@ -60,7 +60,7 @@ Kennwort, anonym) als PDF; Austausch mit Fachplanern über DXF/IFC.
- ◐ **[308]** 3D-Dokument: Gelände als Modellsockel (20.11., Bild `doc/review-308/axo.png`; `plan/axo_terrain.rs`). Zuschnitt auf Parzelle (`siteRules.parcel`, Bounding-Box ∪ Gebäude) + 2 m, ohne Parzelle Gebäude + 5 m; an allen Randkanten senkrechte Seitenflächen bis tiefster Geländepunkt (inkl. Baugrube) − 1 m, dunkler getönt, senkrechte Kanten nur an Ecken. Bildgrösse folgt Haus + Sockel. Option `terrainClip` (`parcel` Vorgabe | `building` | `none` = wie bisher ohne Sockel), CLI `--terrain-clip`. Offen: Rechteck-Hülle und Keller siehe [309]; keine UI-Einstellung für `terrainClip` (nur Doc3d-Extra/CLI); Mac/Tauri nicht geprüft. · S
- ◐ **[309]** 3D-Dokument: Sockelrand gerade, Zuschnitt auf Parzellenumriss, Keller (20.11., Bild `doc/review-309/axo.png`; `plan/axo_terrain.rs`). Zuschnittfläche = Parzellenumriss + 2 m (Gehrung über `kernel2d`, Ecken ≤ 4·d, Selbstschnitte per Vereinigung geheilt, konkave Parzellen) ∪ Gebäude + 2 m, ohne Parzelle Gebäude + 5 m; Dreiecke werden an die Fläche geschnitten (i_overlay), Randkanten nur auf der Zuschnittkante und echtem Netzrand. Deckt das Netz die Fläche nicht oder ist es zu dicht, Raster über der Fläche mit am Netzrand ergänztem (konstant fortgesetztem) Gelände statt gezacktem Rand. Sockel-Unterkante ≤ tiefstes Bauteil − 0.5 m (zusätzlich zu tiefster Geländepunkt − 1 m). Offen: ergänztes Gelände ausserhalb des Netzes ist eine Annahme (nächste Höhe), im Bild nicht gekennzeichnet; keine UI-Einstellung für `terrainClip`; Mac/Tauri nicht geprüft (Haarlinien auf den Sockelseiten: [310]). · S
- ◐ **[319]** Ansichtsschatten ([316]) schneller (20.11.; `plan/elevation/sun.rs`): Werfer-Stücke vorab aufs Hüllrechteck des Empfängers beschnitten, Stücke neben einem konvexen Empfänger (Dachdreieck) entfallen, ganz deckendes Stück allein, EIN Boolean je Empfänger (Vereinigung + Schnitt in einem). Nicht an schrägen Kanten beschneiden: fast gleiche Kanten bringen i_overlay auf Sekunden. Musterhaus komplex, alle 4 Ansichten nativ: Schatten 863 → 109 ms, Wettbewerb 46 → 14 ms; Abweichung zur alten Rechnung ≤ 3e-7 m² (`bench319`, ignored), Golden komplex Süd +3 Polygone (Rundungssplitter). e2e Präsentationsblatt 1.7 min / Pick 1.5 min (Grenze 2 min). Offen: Mac nicht geprüft (Ansicht Ost Komplex → [320]). · S
- ◐ **[333]** Leistung der Anzeige-Engines (25.11., Wunsch Maintainer). Gemessen im Browser (Chromium + SwiftShader-WebGPU: `--use-gl=angle --use-angle=swiftshader --enable-unsafe-webgpu --use-webgpu-adapter=swiftshader`; ohne die ANGLE-Flags verliert headless Chromium das Gerät beim ersten Bild — darum fiel der e2e-Plan bisher immer auf SVG zurück) und nativ (`render2d/examples/scene_stats.rs`). render2d (WebGPU-Pfad: Browser, Linux/Electron): Batch-Werte statisch beim Hochladen, Zeichenfolge als Render-Bundle, je Bild nur 96 Byte Bild-Uniform + `execute_bundles` (Szenen-Varianten der Shader `shaders::scene_variant`, Vorlagen für den nativen Chunk-Renderer unverändert). Grossgebäude (1456 Draws, 1275 Pipeline-Wechsel je Bild) beim Zoomen/Schwenken: p90 283 → 17 ms, p99 416 → 17 ms, längstes Bild 1.4 s → 67 ms; Bild pixelgleich (Musterhaus komplex, eingepasst und gezoomt, Abweichung 0). 3D beim Orbiten schon flüssig (193 Draws, ein 320-Byte-Upload je Bild). render3d Szenen-Aufbau (Öffnen der 3D-Ansicht, Teil-Updates; `examples/scene_bench.rs`, callgrind): Kanten nicht mehr nach Schlüssel nachsortiert (Gruppierungs-Reihenfolge ist deterministisch), Radix-Sortierung grosser Teile, Kanten-Entscheid ohne Heap (`edges::crease_of`, Test gegen den alten Weg), Teil-Nummern-Tabelle statt Hash-Tabelle, Kanten-Index vorab reserviert, Schlüssel je Eckpunkt einmal, Ausdehnung in einem Durchgang — Grossgebäude ganzes Modell −47 %, Teil-Update (3519 Teile, wie im Browser) −30 % Instruktionen. Kern-Wandkörper (`model3d::wall_body`, Giebel-/Bogenwände): Löcher und Formöffnungs-Schneidkörper per Sammel-Vereinigung (`Solid::union_many`, Manifold `CsgNode::op_n`, Exact), Leibungsstücke erst unter sich, dann je EINE Operation mit dem verfeinerten Bandkörper — 3D-Ableitung Grossgebäude 781 → ~560 ms nativ, im Browser Kern 1.6 → 1.1 s, erstes 3D-Bild 4.4 → 3.9 s; Bild bis auf 22 Pixel gleich (Schattierung an Giebelkanten), Golden `komplex-model3d` (Dreieckszahlen) nachgeführt. render3d Kanten-Index kompakt (`scene::EdgeIndex`: Einträge dicht im Vec, `hashbrown::HashTable` nur mit Nummern, Teile merken Nummern statt 48-Byte-Schlüssel), Beiträge linear über eine Hash-Tabelle gruppiert statt sortiert, Rundung der Schlüssel ohne `roundf`-Aufruf (Test gegen `round`), Ausdehnung ohne Verzweigung: Szenen-Aufbau Grossgebäude Teile 1025 → ~640 ms, ganzes Modell 1558 → ~870 ms, Spitzenspeicher 696 → 428 MB (nativ); im Browser render3d-CPU 2.1 → 1.1 s, erstes 3D-Bild ~4.2 → ~3.2 s, Bild pixelgleich; Teil-Update unverändert ~18 ms. Material-Texturen beim Öffnen: alle Bilder zugleich laden, schon beim Dekodieren auf 256×256 (`createImageBitmap` mit `resizeWidth`) — Hauptthread 306 → 196 ms (SwiftShader; Rest ist das Auslesen über den Canvas), Bild „Texturiert“ gleich (mittlere Abweichung 0.004). Dekodieren und Auslesen seither im Worker (`materialTextures.worker.ts`, OffscreenCanvas; Rückfall im Hauptthread): Grossgebäude Hauptthread −0.25 s beim Öffnen der 3D-Ansicht. Sammel-Vereinigung NICHT für Stücke, die verschmelzen sollen (sie setzt sich nur berührende Körper bloss zusammen: Fugen, Test `toWalls3d.giebel`). Offen: Mac-nativer Chunk-Renderer (Metal) nicht gemessen; Öffnen der 3D-Ansicht (Grossgebäude ~3.2 s im Browser) hängt noch an Kern-Booleans (~0.6 s) und am JSON-Weg Kern → JS-Objekte → `JSON.stringify` (`Model3dPartsSync.diff`) → render3d-Parser (~1 s zusammen) — Kern sollte die `set_parts`-Nutzlast je Teil als Text liefern; Text-Rasterung beim Zoomen (klein); e2e mit WebGPU: erledigt 26.11. als eigenes Playwright-Projekt `webgpu` (ANGLE/SwiftShader-Flags, `e2e/webgpu333.spec.ts`: render2d zeichnet den Plan ohne SVG-Rückfall, Zoom zeichnet neu, render3d zeichnet die 3D-Ansicht; Prüfbilder aus dem Canvas); die übrige Suite bleibt auf dem SVG-Rückfall. · M Optik 3D (26.11.): Bodengitter als eine Fläche mit Linien im Shader (`grid.rs`, `GROUND_GRID_WGSL`): geglättet, Meterlinien blenden aus, wo sie zu dicht stehen (kein Moiré/Grauschleier zum Horizont), weicher Rand, nur im leeren Hintergrund (verdeckt kein Gelände/Untergeschoss mehr). Licht: ohne Sonnenstudie folgt das Hauptlicht der Kamera (von links oben hinter dem Betrachter, `gpu::camera_light`), das Aufhelllicht immer (`camera_fill`, flach, mit Sonne von links, sonst von rechts) — zuvor feste Weltrichtung bzw. Gegenrichtung der Sonne: von der Gegenseite beide Fassaden gleich grau; Grundlicht angehoben (Boden 0.30 → 0.42), Weissmodell hell. Umgebungsverdeckung (`ssao.rs`, beleuchtete Stile, Standard an, `set_ambient_occlusion`): Durchgang A Flächen → AO in halber Auflösung aus der Tiefe (Kameraraum, 12 Proben, Radius nach Kamera-Abstand) → Durchgang B multipliziert die Farbe (Weichzeichner nach Tiefe) und zeichnet dann Kanten/Linien/Gitter; unter GL (Tests im Container) aus. Kosten auf dem Mac nicht gemessen; folgt der Klasse „08 Schatten“ (ausgeblendet = keine AO).Line truncated
- ◐ **[333]** Leistung der Anzeige-Engines (25.11., Wunsch Maintainer). Gemessen im Browser (Chromium + SwiftShader-WebGPU: `--use-gl=angle --use-angle=swiftshader --enable-unsafe-webgpu --use-webgpu-adapter=swiftshader`; ohne die ANGLE-Flags verliert headless Chromium das Gerät beim ersten Bild — darum fiel der e2e-Plan bisher immer auf SVG zurück) und nativ (`render2d/examples/scene_stats.rs`). render2d (WebGPU-Pfad: Browser, Linux/Electron): Batch-Werte statisch beim Hochladen, Zeichenfolge als Render-Bundle, je Bild nur 96 Byte Bild-Uniform + `execute_bundles` (Szenen-Varianten der Shader `shaders::scene_variant`, Vorlagen für den nativen Chunk-Renderer unverändert). Grossgebäude (1456 Draws, 1275 Pipeline-Wechsel je Bild) beim Zoomen/Schwenken: p90 283 → 17 ms, p99 416 → 17 ms, längstes Bild 1.4 s → 67 ms; Bild pixelgleich (Musterhaus komplex, eingepasst und gezoomt, Abweichung 0). 3D beim Orbiten schon flüssig (193 Draws, ein 320-Byte-Upload je Bild). render3d Szenen-Aufbau (Öffnen der 3D-Ansicht, Teil-Updates; `examples/scene_bench.rs`, callgrind): Kanten nicht mehr nach Schlüssel nachsortiert (Gruppierungs-Reihenfolge ist deterministisch), Radix-Sortierung grosser Teile, Kanten-Entscheid ohne Heap (`edges::crease_of`, Test gegen den alten Weg), Teil-Nummern-Tabelle statt Hash-Tabelle, Kanten-Index vorab reserviert, Schlüssel je Eckpunkt einmal, Ausdehnung in einem Durchgang — Grossgebäude ganzes Modell −47 %, Teil-Update (3519 Teile, wie im Browser) −30 % Instruktionen. Kern-Wandkörper (`model3d::wall_body`, Giebel-/Bogenwände): Löcher und Formöffnungs-Schneidkörper per Sammel-Vereinigung (`Solid::union_many`, Manifold `CsgNode::op_n`, Exact), Leibungsstücke erst unter sich, dann je EINE Operation mit dem verfeinerten Bandkörper — 3D-Ableitung Grossgebäude 781 → ~560 ms nativ, im Browser Kern 1.6 → 1.1 s, erstes 3D-Bild 4.4 → 3.9 s; Bild bis auf 22 Pixel gleich (Schattierung an Giebelkanten), Golden `komplex-model3d` (Dreieckszahlen) nachgeführt. render3d Kanten-Index kompakt (`scene::EdgeIndex`: Einträge dicht im Vec, `hashbrown::HashTable` nur mit Nummern, Teile merken Nummern statt 48-Byte-Schlüssel), Beiträge linear über eine Hash-Tabelle gruppiert statt sortiert, Rundung der Schlüssel ohne `roundf`-Aufruf (Test gegen `round`), Ausdehnung ohne Verzweigung: Szenen-Aufbau Grossgebäude Teile 1025 → ~640 ms, ganzes Modell 1558 → ~870 ms, Spitzenspeicher 696 → 428 MB (nativ); im Browser render3d-CPU 2.1 → 1.1 s, erstes 3D-Bild ~4.2 → ~3.2 s, Bild pixelgleich; Teil-Update unverändert ~18 ms. Material-Texturen beim Öffnen: alle Bilder zugleich laden, schon beim Dekodieren auf 256×256 (`createImageBitmap` mit `resizeWidth`) — Hauptthread 306 → 196 ms (SwiftShader; Rest ist das Auslesen über den Canvas), Bild „Texturiert“ gleich (mittlere Abweichung 0.004). Dekodieren und Auslesen seither im Worker (`materialTextures.worker.ts`, OffscreenCanvas; Rückfall im Hauptthread): Grossgebäude Hauptthread −0.25 s beim Öffnen der 3D-Ansicht. Sammel-Vereinigung NICHT für Stücke, die verschmelzen sollen (sie setzt sich nur berührende Körper bloss zusammen: Fugen, Test `toWalls3d.giebel`). Offen: Mac-nativer Chunk-Renderer (Metal) nicht gemessen; Öffnen der 3D-Ansicht (Grossgebäude ~3.2 s im Browser) hängt noch an Kern-Booleans (~0.6 s) und am JSON-Weg Kern → JS-Objekte → `JSON.stringify` (`Model3dPartsSync.diff`) → render3d-Parser (~1 s zusammen) — Kern sollte die `set_parts`-Nutzlast je Teil als Text liefern; Text-Rasterung beim Zoomen (klein); e2e mit WebGPU: erledigt 26.11. als eigenes Playwright-Projekt `webgpu` (ANGLE/SwiftShader-Flags, `e2e/webgpu333.spec.ts`: render2d zeichnet den Plan ohne SVG-Rückfall, Zoom zeichnet neu, render3d zeichnet die 3D-Ansicht; Prüfbilder aus dem Canvas); die übrige Suite bleibt auf dem SVG-Rückfall. · M Optik 3D (26.11.): Bodengitter als eine Fläche mit Linien im Shader (`grid.rs`, `GROUND_GRID_WGSL`): geglättet, Meterlinien blenden aus, wo sie zu dicht stehen (kein Moiré/Grauschleier zum Horizont), weicher Rand, nur im leeren Hintergrund (verdeckt kein Gelände/Untergeschoss mehr). Licht: ohne Sonnenstudie folgt das Hauptlicht der Kamera (von links oben hinter dem Betrachter, `gpu::camera_light`), das Aufhelllicht immer (`camera_fill`, flach, mit Sonne von links, sonst von rechts) — zuvor feste Weltrichtung bzw. Gegenrichtung der Sonne: von der Gegenseite beide Fassaden gleich grau; Grundlicht angehoben (Boden 0.30 → 0.42), Weissmodell hell. Umgebungsverdeckung (`ssao.rs`, beleuchtete Stile, Standard an, `set_ambient_occlusion`): Durchgang A Flächen → AO in halber Auflösung aus der Tiefe (Kameraraum, 12 Proben, Radius nach Kamera-Abstand) → Durchgang B multipliziert die Farbe (Weichzeichner nach Tiefe) und zeichnet dann Kanten/Linien/Gitter; unter GL (Tests im Container) aus. Kosten auf dem Mac nicht gemessen; folgt der Klasse „08 Schatten“ (ausgeblendet = keine AO).Line truncated
- ◐ **[332]** Eigenes Gelände aus gezeichneten Höhenlinien (25.11., Wunsch Maintainer): Befehl „Höhenlinie“ (`hl`, Knopf „Höhenlinien zeichnen“ im Panel Gelände) — Linie, Polylinie (mit Bögen), Spline, Bezier, Bogen, Kreis, Ellipse oder Rechteck anklicken, Höhe tippen (Enter: letzte Höhe + Äquidistanz; vorgewählte Linie: Zahl sofort tippen); die Linie wird Höhenlinie im ersten Höhenlinien-Satz (sonst neuer Satz, Klasse 14), danach „Gelände erzeugen“. Kern `contour_draw.rs`, Befehl `commands/cmds/contourLine.ts`, e2e `contourLine332.spec.ts`. Höhenpunkte (25.11.): Höhenkote anklicken übernimmt ihren Wert sofort, Punktmarker mit getippter Höhe; Ein-Punkt-Einträge sind beim Gelände Stützpunkte (zählen nicht für die Äquidistanz, `cmd_solid::terrain_from_contours_with`). Offen: mehrere vorgewählte Linien auf einmal mit Äquidistanz; Höhenpunkte im Plan nicht als Zeichen sichtbar (nur im Gelände); nicht auf dem Mac. · S
- ◐ **[331]** Schraffuren Erdreich und Kies (25.11., Vorlage Maintainer): Erdreich als SIA-Flechtmuster (quadratische Felder 0.25 m, je vier Striche, von Feld zu Feld um 90° gewechselt, 45° gedreht; `hatchgen/src/hatch.rs` `earth_runs`), Kies als Kiesel (Ellipsen verschiedener Grösse/Drehung, dazwischen Punkte; `gravel_runs`). Im Schnitt über 1:50 papierkonstant vergrössert (sonst bei 1:100 zu dicht, `plan/section/primitives.rs`). Geprüft: Schnitt A 1:50/1:100 (CLI `--hatch`, Linux). Offen: gestalterische Varianten (ausfransender Unterrand des Erdbands), nicht auf dem Mac. · S
- ◐ **[330]** SIA-400-Prüfung der Darstellung (24.11., Musterhaus komplex: EG 1:100/1:50, Schnitt A-A, Ansicht Süd, Bilder nur lokal). In Ordnung: Wände 1:100 schwarz, 1:50 nach Baustoff schraffiert; Türen mit Flügel und Viertelkreis, Schiebetüren mit Pfeil; Fenster mit Glas-/Leibungslinien; Treppe mit Bruchlinie, über der Schnittebene gestrichelt; Schnitt mit Höhenkoten (fertig, ▽), Erdreich, Achsen; Ansicht mit Strichstärken-Hierarchie Gelände 0.5 / Umriss 0.25 / Kanten 0.13 / Feines 0.09 mm, Flügelsymbole gestrichelt, Materialfuge, Schatten 45°. Geändert: Lauflinie mit Antrittspunkt als Vorgabe (SIA 400 / DIN 1356: Punkt am Antritt, Pfeil am Austritt; vorher aus, `plan/model_view.rs`); Goldens nachgeführt. Hinweis: der CLI-Plan zeigt alle Klassen (Kamera-Blickkegel quer durch den Plan) — die Vorlage „Grundriss 1:100“ blendet sie aus. Offen: Dämmung im 1:100 nicht vom Mauerwerk abgesetzt (alles schwarz; Bürowahl), Rohbau-/Fertigkoten nicht unterschieden; Grundriss 1:200 (UG, 25.11.) in Ordnung: Wände schwarz, Rundstütze, Türen/Fenster, Wendeltreppe lesbar; Erker-Sehnen über den Fenstern gewollt ([216]). Das automatische Radiusmass am Erker steht mittig über der Wendeltreppe (Zahl am Griff verschiebbar; „bündig am Bogen“ versucht und verworfen, weil es bis zur Aussenkante misst und die Zahl dann auf der Wand liegt). Blatt 501 „Detail und Situation“ (25.11.): Situation nach SIA 400 in Ordnung (Neubau schwarz, Bestand grau, Höhenlinien, Nordpfeil, Massstabsbalken); das Detail fehlte auf dem Blatt (die Nachbarhäuser, Klasse 12, waren im Detail-Ausschnitt sichtbar, der Viewport rechnete mit ihnen und das Detail fiel aus dem Rahmen) → Klasse 12 im Ausschnitt aus, Beschriftungen näher ans Bauteil, Viewport 265 mm hoch (Beispielprojekt). Plankopf mit mehreren Massstäben zeigt jetzt alle („1:10 / 1:500“, Kern `layout_model.rs`). Blätter 101–103 (25.11.): 101 zeigte den Sonnenschatten trotz Vorlage „Grundriss 1:100“ (Klassen-Schalter der verknüpften Vorlage fehlten im Ausschnitt; Test), Nachbarhäuser im Grundriss, Titel links ausserhalb, Zahlen des Massstabsbalkens abgeschnitten (Kern: Ausmass des Balkens ohne Zahlen, `acc_bounds`) → behoben; Ansichtslinien West/Ost näher ans Haus (−11/22 m). Run-Schriftgrösse `sizePt` in Plantexten jetzt überall Papier-pt (Entscheid Maintainer 25.11.: 14 pt sind gedruckt 14 pt; vorher rechneten Druck/PDF `print_svg.rs` und SVG-Planansicht in Modell-pt, render2d und DXF schon in Papier-pt). Offen: Blatt 401 (Listen) nicht geprüft; nicht auf dem Mac. · M
+102
View File
@@ -0,0 +1,102 @@
// [333] Grundriss-Griffe für Stützen und freie Körper (Musterhaus komplex): Stütze `st-carport-1` (EG, 12×12 cm) lässt
// sich an der Ecke aufziehen (Querschnitt wächst symmetrisch um die Mitte) und an der Mitte verschieben; ein Körper
// (`void-durchreiche`) an einer Profil-Ecke ziehen.
import type { Page } from "@playwright/test";
import { blurFocus, discardIfAsked, expect, fileMenu, openTab, test } from "./app";
import type {} from "../src/state/testHooks"; // Typ von window.__dossierTest
async function screenOf(page: Page, x: number, y: number): Promise<{ x: number; y: number }> {
return page.locator("svg.plan-svg").first().evaluate(
(el, [x, y]) => {
const [vx, vy, vw, vh] = el.getAttribute("viewBox")!.split(/\s+/).map(Number);
const ox = Number(el.getAttribute("data-origin-x") ?? 0);
const oy = Number(el.getAttribute("data-origin-y") ?? 0);
const r = el.getBoundingClientRect();
const s = Math.min(r.width / vw, r.height / vh);
return { x: r.left + (r.width - vw * s) / 2 + (x * 90 - ox - vx) * s, y: r.top + (r.height - vh * s) / 2 + (-y * 90 - oy - vy) * s };
},
[x, y],
);
}
async function openComplex(page: Page) {
await page.goto("/?dossierTest");
await page.getByRole("button", { name: /Neues Projekt/ }).first().click();
await expect(page.getByRole("group", { name: "Befehlszeile" })).toBeVisible();
await fileMenu(page, /Musterhaus \(komplex\)/);
await discardIfAsked(page);
await expect(page.locator(".project-name")).toHaveText("Musterhaus komplex", { timeout: 30_000 });
await expect(page.locator("svg.plan-svg").first()).toBeVisible({ timeout: 30_000 });
}
const nav = (page: Page, name: string) => page.locator(".nav-row").filter({ hasText: name }).first();
const geom = (page: Page) => page.evaluate(() => window.__dossierTest!.gripGeom());
const column = async (page: Page) => (await geom(page)).columns.find((c) => c.id === "st-carport-1")!;
async function drag(page: Page, from: { x: number; y: number }, to: { x: number; y: number }) {
await page.mouse.move(from.x, from.y);
await page.mouse.down();
await page.mouse.move((from.x + to.x) / 2, (from.y + to.y) / 2, { steps: 4 });
await page.mouse.move(to.x, to.y, { steps: 4 });
await page.mouse.up();
}
async function openEg(page: Page) {
await openComplex(page);
await openTab(page, "Zeichnungsebenen");
await nav(page, "Erdgeschoss").click();
await page.waitForTimeout(800);
await blurFocus(page);
}
test("Stütze: Ecken-Griff vergrössert den Querschnitt um die Mitte", async ({ page }) => {
test.setTimeout(150_000);
await openEg(page);
await page.evaluate(() => window.__dossierTest!.select({ columns: ["st-carport-1"] }));
await page.waitForTimeout(500);
const before = await column(page);
expect(before.width).toBeCloseTo(0.12, 6);
// Eine 12-cm-Stütze ist im Plan nur wenige Pixel gross (Ecken- und Mitte-Griff liegen übereinander): erst per Kern-Griff auf
// 1 × 1 m aufziehen (Ecke 3 = +x/+y), dann die Ecke mit der Maus weiterziehen.
const [cx, cy] = [before.position.x, before.position.y];
await page.evaluate(([x, y]) => window.__dossierTest!.columnGrip("st-carport-1", 3, x + 0.5, y + 0.5), [cx, cy]);
await expect.poll(async () => (await column(page)).width).toBeCloseTo(1.0, 6);
expect((await column(page)).depth).toBeCloseTo(1.0, 6);
await page.waitForTimeout(500);
const a = await screenOf(page, cx + 0.5, cy + 0.5);
const b = await screenOf(page, cx + 0.9, cy + 0.8);
await drag(page, a, b);
// Der Fang kann den Zielpunkt verziehen: nur prüfen, dass beide Masse wachsen und die Mitte bleibt.
await expect.poll(async () => (await column(page)).width, { timeout: 10_000 }).toBeGreaterThan(1.2);
const after = await column(page);
expect(after.depth).toBeGreaterThan(1.2);
expect(Math.abs(after.position.x - before.position.x) + Math.abs(after.position.y - before.position.y)).toBeLessThan(1e-9);
});
test("Stütze: Mitte-Griff verschiebt die Stütze", async ({ page }) => {
test.setTimeout(150_000);
await openEg(page);
await page.evaluate(() => window.__dossierTest!.select({ columns: ["st-carport-1"] }));
await page.waitForTimeout(500);
const before = await column(page);
const a = await screenOf(page, before.position.x, before.position.y);
const b = await screenOf(page, before.position.x + 0.8, before.position.y);
await drag(page, a, b);
await expect.poll(async () => (await column(page)).position.x, { timeout: 10_000 }).toBeGreaterThan(before.position.x + 0.3);
expect((await column(page)).width).toBeCloseTo(0.12, 6);
});
test("Freier Körper: Eck-Griff verschiebt die Profil-Ecke", async ({ page }) => {
test.setTimeout(150_000);
await openEg(page);
await page.evaluate(() => window.__dossierTest!.select({ solids: ["void-durchreiche"] }));
await page.waitForTimeout(500);
const solid = async () => (await geom(page)).solids.find((s) => s.id === "void-durchreiche")!;
const before = await solid();
const c = before.points[2];
const a = await screenOf(page, c.x, c.y);
const b = await screenOf(page, c.x + 0.5, c.y + 0.6);
await drag(page, a, b);
await expect.poll(async () => (await solid()).points[2].x, { timeout: 10_000 }).toBeGreaterThan(c.x + 0.2);
expect((await solid()).points[0]).toEqual(before.points[0]);
});
+69
View File
@@ -0,0 +1,69 @@
// [333] 3D-Griffe für Stützen und Wandöffnungen (Projekt „webgpu“, echtes WebGPU über SwiftShader, s. webgpu333.spec.ts):
// gewähltes Element → DOM-Griff über dem 3D-Canvas → Klick bewaffnet, Mausbewegung zieht, zweiter Klick setzt.
// Geprüft wird, dass sich das Modell ändert (Kern-Zug wie im Plan: `columnGrip`, `openingSlide`).
// Lauf: E2E_PORT=5186 npx playwright test e2e/grips3d333.spec.ts --project=webgpu --trace off
import type { Page } from "@playwright/test";
import { expect, fileMenu, discardIfAsked, test } from "./app";
type Hooks = {
select: (s: Record<string, string[]>) => void;
gripGeom: () => { columns: { id: string; position: { x: number; y: number } }[] };
openings: () => { id: string; position: number }[];
};
const hooks = (page: Page) => page.evaluate(() => (window as unknown as { __dossierTest: unknown }).__dossierTest !== undefined);
async function open3d(page: Page) {
await page.goto("/?dossierTest");
await page.getByRole("button", { name: /Neues Projekt/ }).first().click();
await expect(page.getByRole("group", { name: "Befehlszeile" })).toBeVisible();
await fileMenu(page, /Musterhaus \(komplex\)/);
await discardIfAsked(page);
await page.getByRole("button", { name: "Ansicht", exact: true }).click();
await page.getByRole("option", { name: "3D-Ansicht", exact: true }).click();
await page.locator("canvas[data-engine=render3d]").waitFor({ timeout: 60_000 });
await page.waitForTimeout(2000);
expect(await hooks(page)).toBe(true);
}
/** Griff anklicken (bewaffnet ihn), `dx`/`dy` Pixel weiterfahren, zweiter Klick setzt ihn. */
async function dragGrip(page: Page, title: string, dx: number, dy: number) {
const grip = page.locator(`div[title="${title}"][style*="width: 16px"]`).first();
await grip.waitFor({ timeout: 20_000 });
const b = (await grip.boundingBox())!;
const [x, y] = [b.x + b.width / 2, b.y + b.height / 2];
await page.mouse.move(x, y);
await page.mouse.down();
await page.mouse.up();
await page.mouse.move(x + dx, y + dy, { steps: 12 });
await page.waitForTimeout(300);
await page.mouse.down();
await page.mouse.up();
await page.waitForTimeout(300);
}
test("3D-Griffe: Stütze verschieben, Fenster in der Wand gleiten", async ({ page }) => {
test.setTimeout(180_000);
await open3d(page);
// Stütze: Mitte-Griff („Verschieben") ziehen.
await page.evaluate(() => (window as unknown as { __dossierTest: Hooks }).__dossierTest.select({ columns: ["st-carport-1"] }));
// 12 cm sind im ganzen Modell nur wenige Pixel: Stütze erst aufziehen (Kern-Griff 3), damit die Griffe getrennt liegen.
await page.evaluate(() => {
const h = (window as unknown as { __dossierTest: { columnGrip: (id: string, i: number, x: number, y: number) => void; gripGeom: Hooks["gripGeom"] } }).__dossierTest;
const c = h.gripGeom().columns.find((x) => x.id === "st-carport-1")!;
h.columnGrip("st-carport-1", 3, c.position.x + 5, c.position.y + 5);
});
await page.waitForTimeout(800);
const before = await page.evaluate(() => (window as unknown as { __dossierTest: Hooks }).__dossierTest.gripGeom().columns.find((c) => c.id === "st-carport-1")!.position);
await dragGrip(page, "Verschieben", 70, 30);
const after = await page.evaluate(() => (window as unknown as { __dossierTest: Hooks }).__dossierTest.gripGeom().columns.find((c) => c.id === "st-carport-1")!.position);
expect(Math.hypot(after.x - before.x, after.y - before.y), "Stütze verschoben").toBeGreaterThan(0.05);
// Fenster: Gleit-Griff entlang der Wirtswand.
const id = "eg-f1";
await page.evaluate((i) => (window as unknown as { __dossierTest: Hooks }).__dossierTest.select({ openings: [i] }), id);
const p0 = await page.evaluate((i) => (window as unknown as { __dossierTest: Hooks }).__dossierTest.openings().find((o) => o.id === i)!.position, id);
await dragGrip(page, "Öffnung in der Wand verschieben", 90, 0);
const p1 = await page.evaluate((i) => (window as unknown as { __dossierTest: Hooks }).__dossierTest.openings().find((o) => o.id === i)!.position, id);
expect(Math.abs(p1 - p0), "Fenster gleitet").toBeGreaterThan(0.05);
});
+148 -1
View File
@@ -4,7 +4,7 @@
// Griffen und einem Undo-Schritt je Element. Bildschirm-Punkte aus der viewBox-Abbildung des
// SVG-Overlays (x·90, −y·90 minus lokalem Ursprung, s. `planView/overlayOrigin.ts`).
import type { Page } from "@playwright/test";
import { blurFocus, expect, openSample, openTab, startNewProject, test, typeCommand } from "./app";
import { blurFocus, discardIfAsked, expect, fileMenu, openSample, openTab, startNewProject, test, typeCommand } from "./app";
type Pt = { x: number; y: number };
@@ -303,3 +303,150 @@ test("Blatt: Fang auf Viewport-Inhalt", async ({ page }) => {
expect([...kinds].some((k) => ["endpoint", "onEdge", "midpoint", "intersection", "perpendicular"].includes(k))).toBe(true);
await page.screenshot({ path: "test-results/layout-sheet-viewport-snap.png" });
});
test("[333] Blatt: Viewport vergrössern lässt den Inhalt liegen (wie InDesign)", async ({ page }) => {
await startNewProject(page);
await openSample(page);
await openTab(page, "Ausschnitte");
await page.getByTitle("Ausschnitt speichern").first().click();
await page.getByPlaceholder("Ausschnitt speichern als:").fill("EG");
await page.keyboard.press("Enter");
await openNewLayout(page);
const paper = await paperBox(page);
await page.getByRole("button", { name: /Viewport aufziehen/ }).click();
const a = { x: paper.x + paper.width * 0.1, y: paper.y + paper.height * 0.1 };
const b = { x: paper.x + paper.width * 0.7, y: paper.y + paper.height * 0.4 };
await page.mouse.move(a.x, a.y);
await page.mouse.down();
await page.mouse.move(b.x, b.y, { steps: 6 });
await page.mouse.up();
const bind = page.locator(".layout-sheet-bind select");
if (await bind.isVisible().catch(() => false)) await bind.selectOption({ label: "EG" });
await expect(page.locator("[data-viewport-id] svg").first()).toBeAttached();
await page.keyboard.press("Escape");
await page.waitForTimeout(800);
// Lage einer Raumbeschriftung im Viewport vorher und nachher (Bildschirm-Pixel).
const label = page.locator("[data-viewport-id] text", { hasText: "Wohnen" }).first();
const before = (await label.boundingBox())!;
await page.mouse.click((a.x + b.x) / 2, (a.y + b.y) / 2);
const bottom = { x: (a.x + b.x) / 2, y: b.y };
await page.mouse.move(bottom.x, bottom.y);
await page.mouse.down();
await page.mouse.move(bottom.x, bottom.y + 120, { steps: 6 });
await page.mouse.up();
await page.keyboard.press("Escape");
await page.mouse.click(paper.x + paper.width * 0.95, paper.y + paper.height * 0.95);
await page.waitForTimeout(1200);
const frame = (await page.locator("[data-viewport-id]").first().boundingBox())!;
expect(frame.height, "Rahmen höher").toBeGreaterThan(b.y - a.y + 80);
const after = (await label.boundingBox())!;
expect(Math.abs(after.x - before.x), "Inhalt bleibt waagrecht").toBeLessThan(1.5);
expect(Math.abs(after.y - before.y), "Inhalt bleibt liegen (nicht neu zentriert)").toBeLessThan(1.5);
});
test("[333] Blatt: Inhalts-Griff verschiebt den Plan im Rahmen, der Rahmen bleibt", async ({ page }) => {
await startNewProject(page);
await openSample(page);
await openTab(page, "Ausschnitte");
await page.getByTitle("Ausschnitt speichern").first().click();
await page.getByPlaceholder("Ausschnitt speichern als:").fill("EG");
await page.keyboard.press("Enter");
await openNewLayout(page);
const paper = await paperBox(page);
await page.getByRole("button", { name: /Viewport aufziehen/ }).click();
const a = { x: paper.x + paper.width * 0.1, y: paper.y + paper.height * 0.1 };
const b = { x: paper.x + paper.width * 0.8, y: paper.y + paper.height * 0.5 };
await page.mouse.move(a.x, a.y);
await page.mouse.down();
await page.mouse.move(b.x, b.y, { steps: 6 });
await page.mouse.up();
const bind = page.locator(".layout-sheet-bind select");
if (await bind.isVisible().catch(() => false)) await bind.selectOption({ label: "EG" });
await expect(page.locator("[data-viewport-id] svg").first()).toBeAttached();
await page.keyboard.press("Escape");
await page.waitForTimeout(800);
const label = page.locator("[data-viewport-id] text", { hasText: "Wohnen" }).first();
const before = (await label.boundingBox())!;
const frame0 = (await page.locator("[data-viewport-id]").first().boundingBox())!;
await page.mouse.click((a.x + b.x) / 2 + 40, (a.y + b.y) / 2 + 30);
const grip = page.locator("[data-viewport-content-grip]");
await expect(grip).toBeVisible();
const g = (await grip.boundingBox())!;
const c = { x: g.x + g.width / 2, y: g.y + g.height / 2 };
await page.mouse.move(c.x, c.y);
await page.mouse.down();
await page.mouse.move(c.x + 30, c.y + 20, { steps: 5 });
await page.mouse.move(c.x + 60, c.y + 40, { steps: 5 });
await page.mouse.up();
await page.keyboard.press("Escape");
await page.mouse.click(paper.x + paper.width * 0.95, paper.y + paper.height * 0.95);
await page.waitForTimeout(1200);
const after = (await label.boundingBox())!;
expect(after.x - before.x, "Inhalt nach rechts").toBeGreaterThan(50);
expect(after.y - before.y, "Inhalt nach unten").toBeGreaterThan(30);
const frame1 = (await page.locator("[data-viewport-id]").first().boundingBox())!;
expect(Math.abs(frame1.x - frame0.x) + Math.abs(frame1.width - frame0.width), "Rahmen unverändert").toBeLessThan(2);
});
test("[333] Blätter-Leiste: Vorschau aller Blätter, Klick öffnet ein anderes Blatt", async ({ page }) => {
await startNewProject(page);
await fileMenu(page, /^Neu aus Vorlage: Wettbewerb$/);
await discardIfAsked(page);
await page.getByRole("tab", { name: "Mappe", exact: true }).click();
await page.getByText("Präsentationsplan", { exact: true }).first().click();
const strip = page.locator("[data-sheet-strip]");
await expect(strip).toBeVisible();
await expect(strip.locator(".sheet-strip-item")).toHaveCount(3);
await expect(strip.locator(".sheet-strip-item.active")).toContainText("Präsentationsplan");
await strip.locator(".sheet-strip-item", { hasText: "Situation" }).click();
await expect(page.locator(".layout-sheet-name")).toHaveText("Situation 1:500");
await expect(strip.locator(".sheet-strip-item.active")).toContainText("Situation");
// Ausblenden bleibt (Knopf in der Leiste).
await page.locator("[data-sheet-strip-toggle]").click();
await expect(strip).toHaveCount(0);
await page.locator("[data-sheet-strip-toggle]").click();
await expect(page.locator("[data-sheet-strip]")).toBeVisible();
});
test("[333] Blätter-Leiste: Ziehen ordnet um (ein Undo-Schritt), Duplizieren, Löschen mit Rückfrage", async ({ page }) => {
await startNewProject(page);
await fileMenu(page, /^Neu aus Vorlage: Wettbewerb$/);
await discardIfAsked(page);
await page.getByRole("tab", { name: "Mappe", exact: true }).click();
await page.getByText("Präsentationsplan", { exact: true }).first().click();
const strip = page.locator("[data-sheet-strip]");
const items = strip.locator(".sheet-strip-item");
const names = () => strip.locator(".sheet-strip-name").allTextContents();
await expect(items).toHaveCount(3);
const before = await names();
// Dritte Vorschau über die erste ziehen (Zeigerereignisse, Einfügelinie sichtbar).
const first = (await items.nth(0).boundingBox())!;
const third = (await items.nth(2).boundingBox())!;
await page.mouse.move(third.x + third.width / 2, third.y + third.height / 2);
await page.mouse.down();
await page.mouse.move(first.x + first.width / 2, first.y + first.height / 2, { steps: 8 });
await page.mouse.move(first.x + first.width / 2, first.y + 4, { steps: 3 });
await expect(strip.locator(".sheet-strip-item.drop-before")).toHaveCount(1);
await page.mouse.up();
await expect.poll(names).toEqual([before[2], before[0], before[1]]);
// Das Ziehen öffnet kein anderes Blatt.
await expect(strip.locator(".sheet-strip-item.active")).toContainText("Präsentationsplan");
// Ein Undo-Schritt stellt die alte Reihenfolge wieder her.
await blurFocus(page);
await page.keyboard.press("ControlOrMeta+z");
await expect.poll(names).toEqual(before);
// Duplizieren über das Kontextmenü.
await items.nth(1).click({ button: "right" });
await page.getByText("Duplizieren", { exact: true }).click();
await expect(items).toHaveCount(4);
// Löschen verlangt eine Rückfrage; Abbrechen lässt alles.
await items.nth(2).click({ button: "right" });
await page.getByText("Löschen", { exact: true }).click();
await expect(page.getByTestId("confirm-dialog")).toBeVisible();
await page.keyboard.press("Escape");
await expect(items).toHaveCount(4);
await items.nth(2).click({ button: "right" });
await page.getByText("Löschen", { exact: true }).click();
await page.getByTestId("confirm-dialog-ok").click();
await expect(items).toHaveCount(3);
});
+36 -5
View File
@@ -14,10 +14,10 @@ const wall = async (page: Page, id: string) => (await heights(page)).walls.find(
const r3 = (x: number) => Math.round(x * 1000) / 1000;
/** Griffe lesen, sobald sie ruhen: nach Undo rechnet der Schnitt asynchron neu, bis dahin stehen sie an alter Stelle. */
async function gripCentres(page: Page): Promise<{ x: number; y: number }[]> {
async function gripCentres(page: Page, sel = ".plan-grip:not(.plan-grip-horizontal)"): Promise<{ x: number; y: number }[]> {
const read = async () =>
(
await page.locator(".plan-grip").evaluateAll((els) =>
await page.locator(sel).evaluateAll((els) =>
els.map((e) => {
const r = e.getBoundingClientRect();
return { x: Math.round(r.x + r.width / 2), y: Math.round(r.y + r.height / 2) };
@@ -72,7 +72,7 @@ test("Schnitt A-A: Decke, Fenster und Wand haben Höhen-Griffe, Zug = ein Undo-S
// Decke EG: zwei Griffe nebeneinander (OK links, UK rechts).
const c0 = await ceiling(page, "c-eg");
await select(page, { ceilings: ["c-eg"] });
await expect(page.locator(".plan-grip")).toHaveCount(2);
await expect(page.locator(".plan-grip:not(.plan-grip-horizontal)")).toHaveCount(2);
const [ok, uk] = await gripCentres(page);
expect(ok.x).toBeLessThan(uk.x);
@@ -86,7 +86,7 @@ test("Schnitt A-A: Decke, Fenster und Wand haben Höhen-Griffe, Zug = ein Undo-S
// UK nach unten: die Decke wird dicker, die OK bleibt; ein Undo-Schritt stellt alles her.
await select(page, { ceilings: ["c-eg"] });
await expect(page.locator(".plan-grip")).toHaveCount(2);
await expect(page.locator(".plan-grip:not(.plan-grip-horizontal)")).toHaveCount(2);
const [, uk2] = await gripCentres(page);
await dragGrip(page, uk2, 25);
const c2 = await ceiling(page, "c-eg");
@@ -151,7 +151,7 @@ test("Schnitt A-A: Tab tippt die Kote der Decken-Oberkante", async ({ page }) =>
const c0 = await ceiling(page, "c-eg");
await select(page, { ceilings: ["c-eg"] });
await expect(page.locator(".plan-grip")).toHaveCount(2);
await expect(page.locator(".plan-grip:not(.plan-grip-horizontal)")).toHaveCount(2);
const [ok] = await gripCentres(page);
await page.mouse.move(ok.x, ok.y);
await page.mouse.down();
@@ -253,3 +253,34 @@ test("Schnitt A-A: Sohle der Baugrube ziehen", async ({ page }) => {
await undo(page);
await expect.poll(async () => (await pit()).bottom).toBe(b0.bottom);
});
// [333] Waagrechte End-Griffe: die Decke im Schnitt am Ende anfassen und entlang der Schnittlinie verlängern (das rechte Ende
// liegt im Viewport am Rand der Ansicht und ist dort nicht greifbar; das rechte Ende deckt der Kern-Test `decke_rechtes_ende…` ab).
test("Schnitt A-A: Decke am linken Ende waagrecht verlängern, Zug = ein Undo-Schritt", async ({ page }) => {
test.setTimeout(180_000);
await openSheet(page, "Schnitt A-A");
const extent = async () => {
const o = await page.evaluate(() => window.__dossierTest!.ceilingOutline("c-eg"));
const ys = o.map((p) => p.y);
return { y0: Math.min(...ys), y1: Math.max(...ys), n: o.length };
};
const e0 = await extent();
await select(page, { ceilings: ["c-eg"] });
await expect(page.locator(".plan-grip-horizontal")).toHaveCount(2);
const [left, right] = await gripCentres(page, ".plan-grip-horizontal");
expect(left.x).toBeLessThan(right.x);
const len = (e: { y0: number; y1: number }) => e.y1 - e.y0; // die Schnittlinie läuft entlang y
const drag = async (g: { x: number; y: number }, dx: number) => {
await page.mouse.move(g.x, g.y);
await page.mouse.down();
await page.mouse.move(g.x + dx, g.y, { steps: 8 });
await page.mouse.up();
await page.mouse.click(g.x + dx, g.y);
};
// Linkes Ende nach links ziehen: die Decke wird länger.
await drag(left, -40);
await expect.poll(async () => len(await extent()) - len(e0)).toBeGreaterThan(0.05);
expect((await extent()).n).toBe(e0.n);
await undo(page);
await expect.poll(async () => JSON.stringify(await extent())).toBe(JSON.stringify(e0));
});
+24
View File
@@ -78,3 +78,27 @@ test("Wendeltreppe ziehen: Deckenloch wandert mit, im EG weiterhin sichtbar", as
const end = await info(page);
expect(Math.abs(end.hole0!.x - before.hole0!.x) + Math.abs(end.hole0!.y - before.hole0!.y)).toBeLessThan(1e-9);
});
// [333] Gerade Treppe: Griffe an allen vier Ecken (Wunsch Maintainer); hintere Ecke ziehen ändert Breite und Lauflänge.
test("Gerade Treppe: Ecken-Griff ändert Breite und Lauflänge", async ({ page }) => {
test.setTimeout(150_000);
await openComplex(page);
await openTab(page, "Zeichnungsebenen");
await nav(page, "Obergeschoss").click();
await page.waitForTimeout(800);
await blurFocus(page);
await page.evaluate(() => window.__dossierTest!.select({ stairs: ["tr-dg"] }));
await page.waitForTimeout(500);
// tr-dg: Start (10.6125, 9.6), Richtung −y, Lauf 3.9, Breite 1 → Austritt-Ecke (11.1125, 5.7).
const a = await screenOf(page, 11.1125, 5.7);
const b = await screenOf(page, 11.3125, 5.2);
await page.mouse.move(a.x, a.y);
await page.mouse.down();
await page.mouse.move((a.x + b.x) / 2, (a.y + b.y) / 2, { steps: 4 });
await page.mouse.move(b.x, b.y, { steps: 4 });
await page.mouse.up();
const st = () => page.evaluate(() => window.__dossierTest!.heights().stairs.find((s) => s.id === "tr-dg")!);
// Der Fang kann den Zielpunkt an einen nahen Endpunkt ziehen: nur prüfen, dass beide Masse wachsen.
await expect.poll(async () => (await st()).width, { timeout: 10_000 }).toBeGreaterThan(1.02);
expect((await st()).runLength).toBeGreaterThan(3.95);
});
+3 -1
View File
@@ -108,8 +108,10 @@ test("Layout-Werkzeugleiste: Tabellen-Auswahl lesbar, „Einpassen“ im Fenster
await page.getByText("Präsentationsplan", { exact: true }).first().click();
const bar = page.locator(".layout-sheet-toolbar");
await expect(bar).toBeVisible();
// [333] Eine Zeile ohne Umbruch; schmal nur Symbole: die Tabellen-Auswahl bleibt ein ganzer Knopf.
const select = bar.locator("select[data-table-add]");
expect((await select.boundingBox())!.width, "Tabellen-Auswahl nicht auf den Pfeil geschrumpft").toBeGreaterThan(80);
expect((await select.boundingBox())!.width, "Tabellen-Auswahl als ganzer Knopf").toBeGreaterThan(28);
expect((await bar.boundingBox())!.height, "eine Zeile").toBeLessThan(44);
const fit = bar.getByRole("button", { name: "Einpassen" });
const box = (await fit.boundingBox())!;
expect(box.x + box.width, "Einpassen liegt im Fenster").toBeLessThanOrEqual(1280);
+2 -2
View File
@@ -49,10 +49,10 @@ export default defineConfig({
// über den SVG-Rückfall) und `webgpu` mit SwiftShader über ANGLE/Vulkan — dort zeichnen render2d/render3d wirklich
// (`e2e/webgpu*.spec.ts`).
projects: [
{ name: "chromium", testIgnore: /webgpu\d*\.spec\.ts$/ },
{ name: "chromium", testIgnore: /(webgpu|grips3d)\d*\.spec\.ts$/ },
{
name: "webgpu",
testMatch: /webgpu\d*\.spec\.ts$/,
testMatch: /(webgpu|grips3d)\d*\.spec\.ts$/,
use: {
launchOptions: {
executablePath: chromiumPath(),
+51 -3
View File
@@ -429,9 +429,32 @@ fn flight_frame(params: &[f64]) -> Option<(P, P, P, kernel2d::StairGeometry, usi
Some((b, u, (-u.1, u.0), g, last_run, sp.shape))
}
/// [333] Gerade Treppe: Antritt-Mitte, Laufrichtung, linke Normale und die vier Ecken (Antritt links/rechts, Austritt
/// links/rechts, aus der Treppengeometrie).
fn straight_frame(params: &[f64]) -> Option<(P, P, P, [P; 4])> {
let sp = crate::stair::decode_params(params)?;
if sp.shape != "straight" {
return None;
}
let g = kernel2d::stair_geometry(&sp, 1.0);
let (first, last) = (g.treads.first()?, g.treads.last()?);
if first.pts.len() < 4 || last.pts.len() < 4 {
return None;
}
let p = |v: kernel2d::Vec2| (v.x, v.y);
let f = &first.pts;
let b = scale(add(p(f[0]), p(f[3])), 0.5);
let u = normalize(sub(p(f[1]), p(f[0])));
let corners = [p(f[0]), p(f[3]), p(last.pts[1]), p(last.pts[2])];
corners.iter().all(|c| c.0.is_finite() && c.1.is_finite()).then_some((b, u, (-u.1, u.0), corners))
}
/// [151] Parameter-Griffe einer Podesttreppe: Ende des ersten Laufs, Ende des letzten Laufs, bei U und
/// gerade mit Podest der Podestrand (Mitte). Andere Formen: keine.
pub fn stair_param_points(params: &[f64]) -> Vec<P> {
if let Some((_, _, _, corners)) = straight_frame(params) {
return corners.to_vec();
}
let Some((b, u, n, g, last_run, shape)) = flight_frame(params) else { return Vec::new() };
let p = |v: kernel2d::Vec2| (v.x, v.y);
let tr = &g.treads;
@@ -451,10 +474,25 @@ pub fn stair_param_points(params: &[f64]) -> Vec<P> {
/// `runLength`; Ende letzter Lauf → `run2Length` (U: zusätzlich quer `gap` und `turn`); Podestrand →
/// `landingLength`. Längen mindestens 0.3 m.
pub fn stair_param_drag(params: &[f64], index: usize, pt: P) -> Vec<(&'static str, f64)> {
let Some((b, u, n, g, last_run, shape)) = flight_frame(params) else { return Vec::new() };
if !(pt.0.is_finite() && pt.1.is_finite()) {
return Vec::new();
}
if let Some((b, u, n, _)) = straight_frame(params) {
if index > 3 {
return Vec::new();
}
// Breite: Achse in der Mitte → beidseitig (2·Abstand zur Achse); Bezug links/rechts → ab der Bezugskante (Start).
let v = match params.get(15).copied().unwrap_or(0.0) as i64 {
1 | 2 => dot(sub(pt, (params[1], params[2])), n).abs(),
_ => 2.0 * dot(sub(pt, b), n).abs(),
};
let mut out = vec![("width", jsnum::max(0.3, v))];
if index >= 2 {
out.push(("runLength", jsnum::max(0.3, dot(sub(pt, b), u))));
}
return out;
}
let Some((b, u, n, g, last_run, shape)) = flight_frame(params) else { return Vec::new() };
let p = |v: kernel2d::Vec2| (v.x, v.y);
let tr = &g.treads;
let run1 = params.get(5).copied().unwrap_or(0.0);
@@ -538,10 +576,20 @@ mod tests {
let d = stair_param_drag(&u, 1, (0.5, -1.5));
assert!((d[0].1 - 2.5).abs() < 1e-9 && d[1] == ("turn", -1.0) && (d[2].1 - 0.5).abs() < 1e-9, "{d:?}");
assert_eq!(stair_param_drag(&u, 2, (4.5, 0.0)), vec![("landingLength", 1.5)]);
// Gerade Treppe: keine Parameter-Griffe; Unsinn: nichts
// [333] Gerade Treppe (Lauf 3 m, Breite 1, Achse Mitte): vier Ecken; vorne nur Breite, hinten Breite + Lauflänge.
let mut s = u;
s[0] = 0.0;
assert!(stair_param_points(&s).is_empty() && stair_param_drag(&s, 0, (1.0, 1.0)).is_empty());
let c = stair_param_points(&s);
assert_eq!(c.len(), 4, "{c:?}");
let has = |x: f64, y: f64| c.iter().any(|q| (q.0 - x).abs() < 1e-9 && (q.1 - y).abs() < 1e-9);
assert!(has(0.0, 0.5) && has(0.0, -0.5) && has(3.0, 0.5) && has(3.0, -0.5), "{c:?}");
assert_eq!(stair_param_drag(&s, 0, (0.0, 0.8)), vec![("width", 1.6)]);
assert_eq!(stair_param_drag(&s, 3, (3.5, -0.6)), vec![("width", 1.2), ("runLength", 3.5)]);
assert!(stair_param_drag(&s, 4, (1.0, 1.0)).is_empty());
// Bezug links: Breite ab der Startkante
let mut sl = s;
sl[15] = 1.0;
assert_eq!(stair_param_drag(&sl, 1, (0.0, -1.2)), vec![("width", 1.2)]);
assert!(stair_param_drag(&u, 0, (nan, 0.0)).is_empty() && stair_param_drag(&u, 7, (1.0, 1.0)).is_empty());
assert!(stair_param_points(&[1.0]).is_empty());
// L: zwei Griffe (kein Podestrand)
+171 -2
View File
@@ -85,6 +85,74 @@ fn with_geom(d: &Value, g: Value) -> Value {
with(d, "geom", g)
}
/// [333] Abstand des Dreh-Griffs eines Bibliotheks-Objekts vom Einfügepunkt (m).
const LIBOBJ_ROT_ARM: f64 = 0.6;
/// Kleinste Stützenkante/-radius beim Ziehen (m).
const COLUMN_MIN: f64 = 0.05;
/// [333] Stützen-Griff `index` nach (x, y) ziehen (s. `columnGrip`); `None` = nichts ändern.
fn column_grip(e: &Value, index: f64, x: f64, y: f64) -> Option<Value> {
if truthy(field(e, "locked")) || !(x.is_finite() && y.is_finite()) {
return None;
}
let (px, py) = xy(field(e, "position")?);
if index == 0.0 {
return Some(with(e, "position", pt(x, y)));
}
let prof = field(e, "profile")?;
let (dx, dy) = (x - px, y - py);
match prof.get("kind").and_then(Value::as_str)? {
"round" if index == 1.0 => {
let rad = jsnum::max(COLUMN_MIN / 2.0, hypot2(dx, dy));
Some(with(e, "profile", with(prof, "radius", js_num(rad))))
}
"rect" if (1.0..=4.0).contains(&index) => {
let rot = num_of(field(e, "rotation"));
let (c, s) = (jsnum::cos(rot), jsnum::sin(rot));
let (lx, ly) = (dx * c + dy * s, -dx * s + dy * c);
let w = jsnum::max(COLUMN_MIN, 2.0 * lx.abs());
let d = jsnum::max(COLUMN_MIN, 2.0 * ly.abs());
Some(with(e, "profile", with_all(prof, vec![("width", js_num(w)), ("depth", js_num(d))])))
}
"rect" if index == 5.0 => {
if hypot2(dx, dy) < 1e-9 {
return None;
}
Some(with(e, "rotation", js_num(jsnum::atan2(dy, dx))))
}
_ => None,
}
}
/// [333] Griff eines freien Körpers (s. `solidGrip`).
fn solid_grip(e: &Value, index: f64, x: f64, y: f64) -> Option<Value> {
if truthy(field(e, "locked")) || !(x.is_finite() && y.is_finite()) {
return None;
}
let ring = field(e, "points")?.as_array()?;
let derived = field(e, "circle").is_some_and(|c| !c.is_null()) || field(e, "brep").is_some_and(|c| !c.is_null());
if let Some(i) = index_in(index, ring.len()) {
if derived {
return None;
}
return Some(with(e, "points", replace_at(ring, i as f64, &pt(x, y))));
}
if index != ring.len() as f64 {
return None;
}
let c = ring_centroid(ring);
let (dx, dy) = (x - c.0, y - c.1);
let moved_e = with(e, "points", moved_all(ring, dx, dy));
match field(e, "circle") {
Some(circ) if !circ.is_null() => {
let (cx, cy) = xy(field(circ, "center")?);
Some(with(&moved_e, "circle", with(circ, "center", pt(cx + dx, cy + dy))))
}
_ => Some(moved_e),
}
}
// ── Anfrage ──────────────────────────────────────────────────────────────────
/// Eine Änderung aus den Griff-Aktionen des Stores (`GripRequest` in `geometry/grips.ts`); Zahlen dürfen
@@ -282,6 +350,19 @@ pub fn run(lk: &Lookup, req: &Request) -> Result<GripResult, String> {
.into()
}
}
// [333] Stütze im Grundriss: Griff 0 = Mitte (verschiebt), Rechteck: 1..4 = Ecken (Querschnitt symmetrisch um die Mitte,
// im gedrehten Profil-Rahmen: Breite = 2·|lx|, Tiefe = 2·|ly|), 5 = Dreh-Griff auf der lokalen +x-Achse;
// Rundprofil: 1 = Radius-Griff.
"columnGrip" => {
let (index, (x, y)) = (r.n("index"), r.p("pt"));
patch("columns", r.s("id"), &|e| column_grip(e, index, x, y)).into()
}
// [333] Freier Körper im Grundriss: Index < Eckenzahl = Profil-Ecke; Index = Eckenzahl = Verschiebe-Griff (Ziel = neue
// Lage des Profil-Mittelpunkts). Kreis- und B-Rep-Körper nur verschieben (ihr Profil ist abgeleitet).
"solidGrip" => {
let (index, (x, y)) = (r.n("index"), r.p("pt"));
patch("extrudedSolids", r.s("id"), &|e| solid_grip(e, index, x, y)).into()
}
// [213] Kamera: Griff 0 Standpunkt, 1 Ziel, 2 Bildwinkel/Sichtbreite; `cameraBy` verschiebt Standpunkt und Ziel.
"cameraGrip" | "cameraBy" => {
let (index, (x, y), (dx, dy)) = (r.n("index"), r.p("pt"), r.p("delta"));
@@ -491,7 +572,7 @@ pub fn run(lk: &Lookup, req: &Request) -> Result<GripResult, String> {
let (index, (x, y)) = (r.n("index"), r.p("pt"));
patch("stairs", r.s("id"), &|s| {
let st: crate::model::Stair = serde_json::from_value(s.clone()).ok()?;
let i = index_in(index, 3)?;
let i = index_in(index, 4)?;
let changes = crate::grip_drag::stair_param_drag(&st.encode(), i, (x, y));
if changes.is_empty() {
return None;
@@ -570,6 +651,12 @@ pub fn run(lk: &Lookup, req: &Request) -> Result<GripResult, String> {
// [187] Höhen-Griff im Schnitt/in der Ansicht: `kind` = wallTop | wallBottom | openingTop | openingBottom |
// ceilingTop | ceilingBottom | roofEave | roofTop | parapetTop | stairTop | contextTop | contourLine, `a` = Blatt-Höhe (absolutes Z), `free` ohne 1-cm-Raster (`sheet_height.rs`).
"sheetHeight" => crate::sheet_height::ops(lk, r.s("kind").unwrap_or(""), r.s("id").unwrap_or(""), r.n("a"), r.free, r.s("newId").unwrap_or(""), &req.new_name, r.n("b"), r.n("index")).into(),
// [333] Waagrechte End-Griffe im Schnitt: `kind` = ceilingEdge | wallEnd, `index` = Ende (0 links, 1 rechts), `a` = Zug in u (m),
// `pt` = Punkt der Schnittlinie (u = 0), `delta` = u-Achse im Grundriss (`sheet_height::end_ops`).
"sheetEnd" => {
let (base, ua) = (r.p("pt"), r.p("delta"));
crate::sheet_height::end_ops(lk, r.s("kind").unwrap_or(""), r.s("id").unwrap_or(""), u8::from(r.n("index") == 1.0), r.n("a"), [base.0, base.1], [ua.0, ua.1]).into()
}
"wallThickness" => wall_thickness(root, r.s("id").unwrap_or(""), r.n("thickness"), r.s("newId").unwrap_or(""), req.new_name.clone()).into(),
"ceilingThickness" => ceiling_thickness(root, r.s("id").unwrap_or(""), r.n("thickness"), r.s("newId").unwrap_or(""), req.new_name.clone()).into(),
// [144] Wandöffnung gleiten lassen: Griff-Zug nach `pt` bzw. Objekt-Info-Position `a` (ab
@@ -1012,6 +1099,14 @@ fn drawing_grip(d: &Value, index: f64, x: f64, y: f64, scale: f64, free: bool) -
}
set("at", p)
}
// [333] Bibliotheks-Objekt: Griff 0 = Einfügepunkt (verschiebt), 1 = Dreh-Griff (Richtung Mitte → Griff = Drehung).
"libobj" if index == 1.0 => {
let (ax, ay) = xy(field(g, "at").unwrap_or(&Value::Null));
if hypot2(x - ax, y - ay) < 1e-9 {
return None;
}
set("rotation", js_num(jsnum::atan2(y - ay, x - ax)))
}
"kote" | "detailref" | "scalebar" | "pointmarker" | "block" | "libobj" => set("at", p),
"grid" => {
// Griff 0 = Ursprung, danach je Achse (a, dann b) das Achsende: zieht die Achse auf die neue Lage.
@@ -1971,7 +2066,12 @@ pub fn drawing_vertices(g: &Value, scale: f64) -> Option<Vec<(f64, f64)>> {
}
out
}
"kote" | "detailref" | "scalebar" | "pointmarker" | "block" | "libobj" => vec![p("at")],
"libobj" => {
let a = p("at");
let rot = num_of(field(g, "rotation"));
vec![a, (a.0 + LIBOBJ_ROT_ARM * jsnum::cos(rot), a.1 + LIBOBJ_ROT_ARM * jsnum::sin(rot))]
}
"kote" | "detailref" | "scalebar" | "pointmarker" | "block" => vec![p("at")],
"grid" => {
let geom: crate::model::Drawing2DGeom = serde_json::from_value(g.clone()).ok()?;
let spec = crate::grid::Spec::of(&geom)?;
@@ -2074,6 +2174,61 @@ mod tests {
}
}
/// [333] Stützen-Griffe: Mitte verschiebt, Ecke setzt Querschnitt symmetrisch (auch gedreht), Rund = Radius, Dreh-Griff.
#[test]
fn stuetzen_griffe() {
let r = root(json!({"columns": [
{"id": "c", "position": {"x": 1, "y": 2}, "rotation": 0, "profile": {"kind": "rect", "width": 0.3, "depth": 0.3}, "height": 3},
{"id": "k", "position": {"x": 0, "y": 0}, "rotation": 0, "profile": {"kind": "round", "radius": 0.2}, "height": 3},
{"id": "g", "position": {"x": 0, "y": 0}, "rotation": 1.5707963267948966, "profile": {"kind": "rect", "width": 0.3, "depth": 0.3}, "height": 3},
{"id": "l", "locked": true, "position": {"x": 0, "y": 0}, "rotation": 0, "profile": {"kind": "round", "radius": 0.2}, "height": 3}
]}));
let ent = |req: Value| run(&Lookup::plain(&r), &rq(req)).unwrap();
let near = |a: f64, b: f64| (a - b).abs() < 1e-9;
let e = ent(json!({"op": "columnGrip", "id": "c", "index": 0, "pt": [3, 3]}));
assert_eq!(entity(&e)["position"]["x"].as_f64(), Some(3.0));
// Ecke nach (+0.25, +0.2) vom Mittelpunkt: 0.5 × 0.4, Mitte bleibt.
let e = ent(json!({"op": "columnGrip", "id": "c", "index": 3, "pt": [1.25, 2.2]}));
let pr = &entity(&e)["profile"];
assert!(near(pr["width"].as_f64().unwrap(), 0.5) && near(pr["depth"].as_f64().unwrap(), 0.4));
assert_eq!(entity(&e)["position"]["x"].as_f64(), Some(1.0));
// Rund: Radius = Abstand zur Mitte.
let e = ent(json!({"op": "columnGrip", "id": "k", "index": 1, "pt": [0.3, 0.4]}));
assert!(near(entity(&e)["profile"]["radius"].as_f64().unwrap(), 0.5));
// Gedrehtes Profil (90°): lokale x = globale y.
let e = ent(json!({"op": "columnGrip", "id": "g", "index": 1, "pt": [0.1, 0.5]}));
let pr = &entity(&e)["profile"];
assert!(near(pr["width"].as_f64().unwrap(), 1.0) && near(pr["depth"].as_f64().unwrap(), 0.2));
// Drehen: Ziel auf +y → 90°.
let e = ent(json!({"op": "columnGrip", "id": "c", "index": 5, "pt": [1, 5]}));
assert!(near(entity(&e)["rotation"].as_f64().unwrap(), std::f64::consts::FRAC_PI_2));
// Nicht vorhandene Griffe, gesperrt, unbekannt.
assert!(ent(json!({"op": "columnGrip", "id": "k", "index": 5, "pt": [1, 1]})).ops.is_empty());
assert!(ent(json!({"op": "columnGrip", "id": "l", "index": 0, "pt": [1, 1]})).ops.is_empty());
assert!(ent(json!({"op": "columnGrip", "id": "x", "index": 0, "pt": [1, 1]})).ops.is_empty());
}
/// [333] Körper-Griffe: Ecke ziehen, Verschiebe-Griff (Schwerpunkt), Kreis nur verschieben.
#[test]
fn koerper_griffe() {
let r = root(json!({"extrudedSolids": [
{"id": "s", "points": [{"x": 0, "y": 0}, {"x": 2, "y": 0}, {"x": 2, "y": 2}, {"x": 0, "y": 2}], "height": 1},
{"id": "c", "points": [{"x": 0, "y": 0}, {"x": 2, "y": 0}, {"x": 2, "y": 2}, {"x": 0, "y": 2}], "circle": {"center": {"x": 1, "y": 1}, "r": 1}, "height": 1}
]}));
let ent = |req: Value| run(&Lookup::plain(&r), &rq(req)).unwrap();
let e = ent(json!({"op": "solidGrip", "id": "s", "index": 2, "pt": [3, 3]}));
assert_eq!(entity(&e)["points"][2]["x"].as_f64(), Some(3.0));
assert_eq!(entity(&e)["points"][0]["x"].as_f64(), Some(0.0));
let e = ent(json!({"op": "solidGrip", "id": "s", "index": 4, "pt": [11, 11]}));
assert_eq!(entity(&e)["points"][0]["x"].as_f64(), Some(10.0));
assert_eq!(entity(&e)["points"][2]["y"].as_f64(), Some(12.0));
assert!(ent(json!({"op": "solidGrip", "id": "s", "index": 5, "pt": [1, 1]})).ops.is_empty());
assert!(ent(json!({"op": "solidGrip", "id": "c", "index": 1, "pt": [1, 1]})).ops.is_empty());
let e = ent(json!({"op": "solidGrip", "id": "c", "index": 4, "pt": [6, 1]}));
assert_eq!(entity(&e)["circle"]["center"]["x"].as_f64(), Some(6.0));
assert_eq!(entity(&e)["points"][1]["x"].as_f64(), Some(7.0));
}
/// [280] Träger: Griff 0 Anfang, 1 Ende, 2 Mitte verschiebt; gesperrt/unbekannt/Index daneben ändern nichts.
#[test]
fn traeger_griffe() {
@@ -2249,6 +2404,20 @@ mod tests {
assert!(entity(&res)["geom"]["textOffsetsMm"][0].is_object());
}
/// [333] Bibliotheks-Objekt: Griff 0 verschiebt, Griff 1 (0.6 m in Blickrichtung) dreht.
#[test]
fn libobj_griffe() {
let d = json!({"id": "d", "level": "L", "geom": {"shape": "libobj", "libId": "lib:x", "at": {"x": 1, "y": 1}, "rotation": 0}});
let v = drawing_vertices(d.get("geom").unwrap(), 100.0).unwrap();
assert_eq!(v.len(), 2);
assert!((v[1].0 - 1.6).abs() < 1e-9 && (v[1].1 - 1.0).abs() < 1e-9, "{v:?}");
let r = root(json!({"drawings2d": [d]}));
let res = run(&Lookup::plain(&r), &rq(json!({"op": "moveGrip", "drawingId": "d", "index": 1, "pt": [1, 5], "scale": 100}))).unwrap();
assert!((res.ops[0].to_json()["entity"]["geom"]["rotation"].as_f64().unwrap() - std::f64::consts::FRAC_PI_2).abs() < 1e-9);
let res = run(&Lookup::plain(&r), &rq(json!({"op": "moveGrip", "drawingId": "d", "index": 0, "pt": [3, 4], "scale": 100}))).unwrap();
assert_eq!(res.ops[0].to_json()["entity"]["geom"]["at"]["x"].as_f64(), Some(3.0));
}
/// [T2] Bogenlängen-/Radiusmass: Randpunkte-Griffe bleiben auf dem Kreis um den Mittelpunkt.
#[test]
fn bogenmass_griff_auf_dem_kreis() {
+173
View File
@@ -263,6 +263,91 @@ pub fn ops(lk: &Lookup, kind: &str, id: &str, y: f64, free: bool, new_id: &str,
}
}
/// [333] Waagrechte End-Griffe im Schnitt: das Ende `end` (0 = links, 1 = rechts im Blatt) von Decke (`ceilingEdge`) bzw.
/// Wand (`wallEnd`) um `du` Meter entlang der u-Achse ziehen. `base` = Punkt der Schnittlinie im Grundriss (u = 0), `u_axis` =
/// Vektor, in dessen Richtung u im Blatt wächst (bei Blick von der anderen Seite gespiegelt — die Hülle liefert die echte
/// Achse, der Kern rechnet nur damit). Decke: die vom Schnitt gekreuzte Umrisskante an diesem Ende wandert mit beiden Ecken
/// um `du · u_axis` (Aussparungen ignoriert); keine kreuzende Kante → nichts. Wand: nur wenn die Achse höchstens 30° von der
/// Schnittlinie abweicht; der Endpunkt, der im Blatt an diesem Ende liegt, wandert entlang der Achse, sodass seine
/// u-Projektion um `du` wächst (Verbindungen bleiben unberührt). Bogenwand, gesperrt, Unsinn oder Restlänge < 0.1 m → nichts.
#[allow(clippy::too_many_arguments)]
pub fn end_ops(lk: &Lookup, kind: &str, id: &str, end: u8, du: f64, base: [f64; 2], u_axis: [f64; 2]) -> Vec<Op> {
let len = u_axis[0].hypot(u_axis[1]);
if !du.is_finite() || du == 0.0 || base.iter().any(|v| !v.is_finite()) || !len.is_finite() || len < 1e-9 || end > 1 {
return vec![];
}
let u = [u_axis[0] / len, u_axis[1] / len];
let n = [-u[1], u[0]];
let u_of = |p: (f64, f64)| (p.0 - base[0]) * u[0] + (p.1 - base[1]) * u[1];
let side_of = |p: (f64, f64)| (p.0 - base[0]) * n[0] + (p.1 - base[1]) * n[1];
let locked = |e: &Value| truthy(field(e, "locked"));
match kind {
"ceilingEdge" => {
let Some(c) = lk.find("ceilings", id).filter(|c| !locked(c)) else { return vec![] };
let raw = arr(field(c, "outline"));
let ring: Vec<(f64, f64)> = raw.iter().map(crate::json_util::xy).collect();
let n_pts = ring.len();
if n_pts < 3 || ring.iter().any(|p| !p.0.is_finite() || !p.1.is_finite()) {
return vec![];
}
// Kante mit dem kleinsten (links) bzw. grössten (rechts) u-Wert der Kreuzung mit der Schnittlinie.
let mut best: Option<(usize, f64)> = None;
for i in 0..n_pts {
let (a, b) = (ring[i], ring[(i + 1) % n_pts]);
let (sa, sb) = (side_of(a), side_of(b));
if (sa <= 0.0) == (sb <= 0.0) {
continue;
}
let t = sa / (sa - sb);
let ux = u_of(a) + (u_of(b) - u_of(a)) * t;
if best.map_or(true, |(_, bu)| if end == 0 { ux < bu } else { ux > bu }) {
best = Some((i, ux));
}
}
let Some((i, _)) = best else { return vec![] };
let j = (i + 1) % n_pts;
// Nur die zwei Ecken der Kante wandern; die übrigen bleiben unverändert.
let outline: Vec<Value> = raw
.iter()
.enumerate()
.map(|(k, v)| if k == i || k == j { crate::json_util::pt(mm(ring[k].0 + du * u[0]), mm(ring[k].1 + du * u[1])) } else { v.clone() })
.collect();
vec![replace("ceilings", with(c, "outline", Value::Array(outline)))]
}
"wallEnd" => {
let Some(w) = lk.find("walls", id).filter(|w| !locked(w)) else { return vec![] };
let bulge = num_of(field(w, "bulge"));
if bulge.is_finite() && bulge != 0.0 {
return vec![];
}
let (Some(s), Some(e)) = (field(w, "start").map(crate::json_util::xy), field(w, "end").map(crate::json_util::xy)) else { return vec![] };
let axis = (e.0 - s.0, e.1 - s.1);
let l = axis.0.hypot(axis.1);
if !l.is_finite() || l < 1e-9 {
return vec![];
}
let d = (axis.0 / l, axis.1 / l);
let cos = d.0 * u[0] + d.1 * u[1];
if cos.abs() < 30f64.to_radians().cos() {
return vec![];
}
// Welcher Endpunkt liegt im Blatt am gewünschten Ende?
let start_is_left = u_of(s) <= u_of(e);
let move_start = (end == 0) == start_is_left;
// Entlang der Achse um `step`: die u-Projektion wächst um step · cos.
let step = du / cos;
let (new_s, new_e) = if move_start { ((s.0 + d.0 * step, s.1 + d.1 * step), e) } else { (s, (e.0 + d.0 * step, e.1 + d.1 * step)) };
let (nl, along) = ((new_e.0 - new_s.0).hypot(new_e.1 - new_s.1), (new_e.0 - new_s.0) * d.0 + (new_e.1 - new_s.1) * d.1);
if nl < 0.1 || along <= 0.0 {
return vec![];
}
let (key, p) = if move_start { ("start", new_s) } else { ("end", new_e) };
vec![replace("walls", with(w, key, crate::json_util::pt(mm(p.0), mm(p.1))))]
}
_ => vec![],
}
}
/// Bezugshöhe, die der Schnitt von den Höhen eines Höhenlinien-Satzes abzieht (`terrain::datum` über alle Höhenlinien).
pub(crate) fn contour_datum(root: &Map<String, Value>, set: &Value) -> f64 {
let zs: Vec<f64> = arr(field(set, "contours")).iter().map(|c| num_of(field(c, "z"))).collect();
@@ -627,4 +712,92 @@ mod tests {
assert_eq!(e["height"], json!(3.8));
assert_eq!(entity(&run("wallBottom", "w1", 4.0))["height"], json!(0.3));
}
// ── [333] waagrechte End-Griffe ────────────────────────────────────────────────────────────────
fn end_root() -> Map<String, Value> {
json!({
"walls": [
{"id": "wp", "start": {"x": 1.0, "y": 0.0}, "end": {"x": 5.0, "y": 0.0}},
{"id": "wq", "start": {"x": 0.0, "y": 1.0}, "end": {"x": 0.0, "y": 5.0}},
{"id": "wl", "start": {"x": 1.0, "y": 0.0}, "end": {"x": 5.0, "y": 0.0}, "locked": true},
{"id": "wr", "start": {"x": 5.0, "y": 0.0}, "end": {"x": 1.0, "y": 0.0}}
],
"ceilings": [
{"id": "c1", "outline": [{"x": 0.0, "y": -2.0}, {"x": 4.0, "y": -2.0}, {"x": 4.0, "y": 2.0}, {"x": 0.0, "y": 2.0}]}
]
})
.as_object()
.unwrap()
.clone()
}
fn end_run(kind: &str, id: &str, end: u8, du: f64, u_axis: [f64; 2]) -> Vec<Op> {
let r = end_root();
end_ops(&Lookup::plain(&r), kind, id, end, du, [0.0, 0.0], u_axis)
}
fn pts(e: &Value, key: &str) -> Vec<(f64, f64)> {
e[key].as_array().unwrap().iter().map(|p| (p["x"].as_f64().unwrap(), p["y"].as_f64().unwrap())).collect()
}
#[test]
fn decke_rechtes_ende_waechst_entlang_des_schnitts() {
// Schnittlinie = x-Achse (y = 0), u wächst mit x: die Kante x = 4 wandert um +1.
let e = entity(&end_run("ceilingEdge", "c1", 1, 1.0, [1.0, 0.0]));
assert_eq!(pts(&e, "outline"), vec![(0.0, -2.0), (5.0, -2.0), (5.0, 2.0), (0.0, 2.0)]);
// linkes Ende schrumpft (+0.5)
let e = entity(&end_run("ceilingEdge", "c1", 0, 0.5, [1.0, 0.0]));
assert_eq!(pts(&e, "outline"), vec![(0.5, -2.0), (4.0, -2.0), (4.0, 2.0), (0.5, 2.0)]);
}
#[test]
fn decke_gespiegelter_schnitt() {
// Blick von der anderen Seite: u wächst mit −x. Das Blatt-rechte Ende ist die Kante x = 0.
let e = entity(&end_run("ceilingEdge", "c1", 1, 1.0, [-1.0, 0.0]));
assert_eq!(pts(&e, "outline"), vec![(-1.0, -2.0), (4.0, -2.0), (4.0, 2.0), (-1.0, 2.0)]);
let e = entity(&end_run("ceilingEdge", "c1", 0, 1.0, [-1.0, 0.0]));
assert_eq!(pts(&e, "outline"), vec![(0.0, -2.0), (3.0, -2.0), (3.0, 2.0), (0.0, 2.0)]);
}
#[test]
fn decke_ohne_kreuzende_kante_nichts() {
let r = end_root();
let ops_ = end_ops(&Lookup::plain(&r), "ceilingEdge", "c1", 1, 1.0, [0.0, 9.0], [1.0, 0.0]);
assert!(ops_.is_empty());
assert!(end_run("ceilingEdge", "c1", 1, 0.0, [1.0, 0.0]).is_empty());
assert!(end_run("ceilingEdge", "nix", 1, 1.0, [1.0, 0.0]).is_empty());
}
#[test]
fn wand_ende_parallel() {
// Rechtes Ende (x = 5) +1 m; u = x.
let e = entity(&end_run("wallEnd", "wp", 1, 1.0, [1.0, 0.0]));
assert_eq!((e["start"]["x"].as_f64(), e["end"]["x"].as_f64()), (Some(1.0), Some(6.0)));
// linkes Ende −0.5 m
let e = entity(&end_run("wallEnd", "wp", 0, -0.5, [1.0, 0.0]));
assert_eq!((e["start"]["x"].as_f64(), e["end"]["x"].as_f64()), (Some(0.5), Some(5.0)));
// Wand läuft gegen u (start rechts): Blatt-rechtes Ende ist `start`.
let e = entity(&end_run("wallEnd", "wr", 1, 1.0, [1.0, 0.0]));
assert_eq!((e["start"]["x"].as_f64(), e["end"]["x"].as_f64()), (Some(6.0), Some(1.0)));
// gespiegelt: u = −x, Blatt-rechtes Ende = kleineres x
let e = entity(&end_run("wallEnd", "wp", 1, 1.0, [-1.0, 0.0]));
assert_eq!((e["start"]["x"].as_f64(), e["end"]["x"].as_f64()), (Some(0.0), Some(5.0)));
}
#[test]
fn wand_quer_gesperrt_oder_zu_kurz_nichts() {
assert!(end_run("wallEnd", "wq", 1, 1.0, [1.0, 0.0]).is_empty(), "Wand quer zum Schnitt");
assert!(end_run("wallEnd", "wl", 1, 1.0, [1.0, 0.0]).is_empty(), "gesperrt");
assert!(end_run("wallEnd", "wp", 1, -3.95, [1.0, 0.0]).is_empty(), "würde fast verschwinden");
}
#[test]
fn wand_schraeg() {
let mut r = end_root();
r.insert("walls".into(), json!([{"id": "ws", "start": {"x": 0.0, "y": 0.0}, "end": {"x": 4.0, "y": 2.0}}]));
// Achse 26.6° zur u-Achse: die u-Projektion wächst um du = 1 → Punkt wandert 1/cos entlang der Achse.
let e = entity(&end_ops(&Lookup::plain(&r), "wallEnd", "ws", 1, 1.0, [0.0, 0.0], [1.0, 0.0]));
assert!((e["end"]["x"].as_f64().unwrap() - 5.0).abs() < 1e-9);
assert!((e["end"]["y"].as_f64().unwrap() - 2.5).abs() < 1e-9);
}
}
+4
View File
@@ -885,6 +885,10 @@ export default function App() {
| "edit3dDrawings"
| "edit3dCeilings"
| "edit3dRoofs"
| "edit3dStairs"
| "edit3dOpenings"
| "edit3dColumns"
| "onEdit3dElement"
| "onEdit3dVertex"
| "onEdit3dBody"
| "onEdit3dEdge"
+2 -2
View File
@@ -86,12 +86,12 @@ export { EMPTY_MEMBERSHIP, containingGroupId, expandToGroups, isInsideActiveGrou
export type { GroupMembership, MemberKind } from "../model/groups";
export { arcApex, drawingVertices, gripPt, openEdges, polylineEdgeGrips, ringEdges } from "../geometry/grips";
export { verticalExtents } from "../geometry/grips";
export { cameraGripPoints, beamGripPoints } from "../geometry/grips";
export { cameraGripPoints, beamGripPoints, columnGripPoints, solidGripPoints } from "../geometry/grips";
export type { VerticalExtent } from "../geometry/grips";
export type { GripRequest, RingKind } from "../geometry/grips";
export { edgeArcToggle, type ArcRingKind } from "../geometry/grips";
export { clampInside, coincidentGripPoints, excavationGripPoints, gripArcWallRadius, gripArcWallResize, gripArcWallTarget, gripAxisLock, gripEdgeTarget, gripPolar, gripPolarPoint, openingGripPoint, openingSheetSlide, openingTypedPosition, contourMarks, sheetHeightDrag, snapSheetHeight, stairMoveHandle, stairParamPoints, wallGripPoints } from "../geometry/gripDrag";
export type { EdgeDrive, GripLocks, SheetHeightKind } from "../geometry/gripDrag";
export type { EdgeDrive, GripLocks, SheetEndKind, SheetHeightKind } from "../geometry/gripDrag";
export { openingPreviewProject, openingPreviewSvgs } from "../plan/openingPreview";
export type { OpeningPreviewSvgs } from "../plan/openingPreview";
export { surfaceOpeningInfo, surfaceOpeningGrips, surfaceOpeningGripPatch } from "../plan/surfaceOpening";
+4 -1
View File
@@ -114,6 +114,9 @@ export type SheetHeightKind =
// Dach: Traufe, First (bzw. Neigung), Attika; Treppe: Austritt; Gelände: Oberkante (Netz) bzw. Sohle (Baugrube).
| "roofEave" | "roofTop" | "parapetTop" | "stairTop" | "stairBottom" | "contextTop" | "contextBottom" | "contourLine";
/** [333] Art eines waagrechten End-Griffs im Schnitt: Decken-Kante bzw. Wand-Ende (Kern `sheet_height::end_ops`). */
export type SheetEndKind = "ceilingEdge" | "wallEnd";
const SHEET_KIND = { wallTop: 0, openingTop: 1, openingBottom: 2, wallBottom: 3, ceilingTop: 4, ceilingBottom: 6,
roofEave: 7, roofTop: 8, parapetTop: 9, stairTop: 10, stairBottom: 11, contextTop: 4, contextBottom: 7, contourLine: 4 } as const;
@@ -212,7 +215,7 @@ export function stairMoveHandle(st: Stair): Vec2 {
/**
* [151] Parameter-Griffe einer Podesttreppe (L, U, gerade mit Podest): Ende Lauf 1, Ende letzter Lauf, bei
* U / gerade mit Podest der Podestrand. Andere Formen: keine. Den Zug rechnet der Kern (Griff `stairParam`).
* U / gerade mit Podest der Podestrand; [333] gerade Treppe die vier Ecken. Wendeltreppe: keine. Den Zug rechnet der Kern (Griff `stairParam`).
*/
export function stairParamPoints(st: Stair): Vec2[] {
return points(core().grip_stair_param_points(encodeStair(st)));
+30 -1
View File
@@ -13,7 +13,7 @@ import { core } from "../engine/coreWasm";
import { toMarkedJson } from "../core/ops";
import { DEFAULT_SCALE_DENOMINATOR } from "../model/dimension";
import { textFrameCorners } from "../text/textFrame";
import type { SheetHeightKind } from "./gripDrag";
import type { SheetEndKind, SheetHeightKind } from "./gripDrag";
/** Punkt als `[x, y]` (Anfragen an den Kern). */
type P = [number, number];
@@ -49,6 +49,8 @@ export type GripRequest =
// [213] Kamera: 0 = Standpunkt, 1 = Ziel, 2 = Bildwinkel bzw. Sichtbreite (Kern `camera::grip_edit`); `cameraBy` verschiebt Standpunkt und Ziel.
| { op: "cameraGrip"; id: string; index: number; pt: P }
| { op: "beamGrip"; id: string; index: number; pt: P }
// [333] Stütze: 0 = Mitte, Rechteck 1..4 Ecken + 5 Drehen, Rund 1 = Radius; freier Körper: Ecke bzw. (Index = Eckenzahl) Verschieben.
| { op: "columnGrip" | "solidGrip"; id: string; index: number; pt: P }
| { op: "ceilingSlopeGrip"; id: string; index: number; pt: P }
| { op: "cameraBy"; id: string; delta: P }
| { op: "sectionBendDelete"; id: string; index: number }
@@ -67,6 +69,9 @@ export type GripRequest =
| { op: "vertexType"; id: string; index: number; vertexType: "corner" | "arc" | "spline" }
// [187] Höhen-Griff im Schnitt/in der Ansicht: Kante `kind` auf die Blatt-Höhe `a` (absolutes Z) ziehen (Kern `sheet_height.rs`).
| { op: "sheetHeight"; kind: SheetHeightKind; id: string; a: number; b?: number; index?: number; free?: boolean; newId: string; newName: string }
// [333] Waagrechter End-Griff im Schnitt: Ende `index` (0 links, 1 rechts im Blatt) von Decke/Wand um `a` m in u ziehen;
// `pt` = Punkt der Schnittlinie (u = 0), `delta` = u-Achse im Grundriss (Kern `sheet_height::end_ops`).
| { op: "sheetEnd"; kind: SheetEndKind; id: string; index: number; a: number; pt: P; delta: P }
| { op: "wallThickness" | "ceilingThickness"; id: string; thickness: number; newId: string; newName: string }
// [144] Wandöffnung gleiten lassen (Kern `opening_slide`): Griff-Zug nach `pt` bzw. Position `a` ab Wandanfang.
| { op: "openingSlide"; id: string; pt: P }
@@ -118,6 +123,30 @@ export function beamGripPoints(b: { start: Vec2; end: Vec2 }): Vec2[] {
return [b.start, b.end, { x: (b.start.x + b.end.x) / 2, y: (b.start.y + b.end.y) / 2 }];
}
/**
* [333] Griffe einer Stütze im Grundriss (Kern `grips.rs`, `columnGrip`): 0 = Mitte; Rechteck 1..4 = Ecken (Querschnitt
* symmetrisch um die Mitte, im gedrehten Profil-Rahmen) und 5 = Dreh-Griff ausserhalb der +x-Seite; Rund 1 = Radius-Griff.
*/
export function columnGripPoints(c: { position: Vec2; rotation?: number; profile: { kind: "rect"; width: number; depth: number } | { kind: "round"; radius: number } }): Vec2[] {
const rot = c.rotation ?? 0;
const [cos, sin] = [Math.cos(rot), Math.sin(rot)];
const at = (lx: number, ly: number): Vec2 => ({ x: c.position.x + lx * cos - ly * sin, y: c.position.y + lx * sin + ly * cos });
if (c.profile.kind === "round") return [c.position, at(c.profile.radius, 0)];
const [hw, hd] = [c.profile.width / 2, c.profile.depth / 2];
return [c.position, at(-hw, -hd), at(hw, -hd), at(hw, hd), at(-hw, hd), at(hw + 0.3, 0)];
}
/**
* [333] Griffe eines freien Körpers im Grundriss (`solidGrip`): die Profil-Ecken, dahinter der Verschiebe-Griff im
* Schwerpunkt. Kreis- und B-Rep-Körper: nur der Verschiebe-Griff (Index = Eckenzahl, so zählt auch der Kern).
*/
export function solidGripPoints(s: { points: readonly Vec2[]; circle?: unknown; brep?: unknown }): { pts: Vec2[]; first: number } {
const n = s.points.length;
const c = n ? { x: s.points.reduce((a, p) => a + p.x, 0) / n, y: s.points.reduce((a, p) => a + p.y, 0) / n } : { x: 0, y: 0 };
const derived = !!s.circle || !!s.brep;
return { pts: derived ? [c] : [...s.points, c], first: derived ? n : 0 };
}
type Owner = { drawingId?: string; wallId?: string };
function flat(verts: readonly Vec2[]): Float64Array {
+26
View File
@@ -281,6 +281,7 @@ export const de = {
"group.leave.hint": "Isolation verlassen — zurück zur normalen Ansicht (ein Level)",
"tools.view.icons": "Symbole",
"tools.cat.2d": "2D",
"tools.cat.sheet": "Blatt",
"tools.cat.3d": "3D",
"tools.cat.edit": "Bearbeiten",
"ribbon.custom.add": "+ Hinzufügen",
@@ -513,6 +514,15 @@ export const de = {
// Objekt-Info-Palette (ObjectInfoPanel)
"objinfo.title": "Objekt-Info",
"objinfo.empty": "Kein Objekt gewählt",
"objinfo.sheet.kind": "Blatt",
"objinfo.sheet.name": "Name",
"objinfo.sheet.number": "Plan-Nr.",
"objinfo.sheet.revision": "Revision",
"objinfo.sheet.paper": "Papier",
"objinfo.sheet.size": "Grösse",
"objinfo.sheet.content": "Inhalt",
"objinfo.sheet.contentCount": "{views} Ansichten, {tables} Tabellen",
"objinfo.sheet.hint": "Ansicht auf dem Blatt anklicken: Massstab, Ausschnitt und Rahmen.",
"objinfo.category": "Klasse",
"objinfo.level": "Ebene",
"objinfo.refpoint": "Bezugspunkt",
@@ -2760,6 +2770,7 @@ export const de = {
"cmd.field.length": "Länge",
"cmd.field.level": "Kote",
"grip.sheetHeight": "Kote {z} m · Höhe {d} m",
"grip.sheetEnd": "Ende {d} m entlang des Schnitts",
"grip.sheetWallBottomClamped": "Unterkante über Oberkante: Mindesthöhe 0.30 m",
"cmd.field.angle": "Winkel",
"cmd.field.width": "Breite",
@@ -3770,6 +3781,9 @@ export const de = {
"viewport3d.grip.move": "Verschieben",
"viewport3d.grip.edge": "Kante ziehen",
"viewport3d.grip.roofpitch": "Dachneigung ziehen",
"viewport3d.grip.slide": "Öffnung in der Wand verschieben",
"viewport3d.grip.stairParam": "Treppenmass ziehen",
"viewport3d.grip.columnSize": "Stützengrösse ziehen",
// ── Element-Baum (Elemente-Panel, ROADMAP §11) ──────────────────────────────
"elements.title": "Elemente",
@@ -3852,6 +3866,18 @@ export const de = {
// Editor
"layouts.editorTitle": "Layout-Editor",
"layouts.fit": "Einpassen",
"layouts.strip": "Blätter",
"layouts.copyName": "{name} Kopie",
"layouts.duplicate": "Duplizieren",
"layouts.stripMore": "Blattmenü",
"layouts.deleteSheetMessage": "Blatt «{name}» samt Zeichnungen auf dem Blatt löschen? Rückgängig ist möglich.",
"layouts.moveContent": "Inhalt im Rahmen verschieben",
"layouts.insert": "Einfügen",
"layouts.viewportShort": "Ansicht",
"layouts.legendShort": "Legende",
"layouts.tableShort": "Tabelle",
"layouts.imageShort": "Bild",
"layouts.textShort": "Text",
"sheetTable.add": "Tabelle",
"sheetTable.title": "Tabelle",
"sheetTable.source": "Quelle",
+26
View File
@@ -279,6 +279,7 @@ export const en: Record<TranslationKey, string> = {
"group.leave.hint": "Leave isolation — back to normal view (one level)",
"tools.view.icons": "Icons",
"tools.cat.2d": "2D",
"tools.cat.sheet": "Sheet",
"tools.cat.3d": "3D",
"tools.cat.edit": "Modify",
"ribbon.custom.add": "+ Add",
@@ -511,6 +512,15 @@ export const en: Record<TranslationKey, string> = {
// Objekt-Info-Palette (ObjectInfoPanel)
"objinfo.title": "Object Info",
"objinfo.empty": "No object selected",
"objinfo.sheet.kind": "Sheet",
"objinfo.sheet.name": "Name",
"objinfo.sheet.number": "Sheet no.",
"objinfo.sheet.revision": "Revision",
"objinfo.sheet.paper": "Paper",
"objinfo.sheet.size": "Size",
"objinfo.sheet.content": "Content",
"objinfo.sheet.contentCount": "{views} views, {tables} tables",
"objinfo.sheet.hint": "Click a view on the sheet: scale, snapshot and frame.",
"objinfo.category": "Class",
"objinfo.level": "Layer",
"objinfo.refpoint": "Reference point",
@@ -2748,6 +2758,7 @@ export const en: Record<TranslationKey, string> = {
"cmd.field.length": "Length",
"cmd.field.level": "Level",
"grip.sheetHeight": "Level {z} m · height {d} m",
"grip.sheetEnd": "End {d} m along the section",
"grip.sheetWallBottomClamped": "Bottom above top: minimum height 0.30 m",
"cmd.field.angle": "Angle",
"cmd.field.width": "Width",
@@ -3757,6 +3768,9 @@ export const en: Record<TranslationKey, string> = {
"viewport3d.grip.height": "Drag height",
"viewport3d.grip.move": "Move",
"viewport3d.grip.roofpitch": "Drag roof pitch",
"viewport3d.grip.slide": "Slide opening along wall",
"viewport3d.grip.stairParam": "Drag stair dimension",
"viewport3d.grip.columnSize": "Drag column size",
// ── Element tree (Elements panel, ROADMAP §11) ──────────────────────────────
"elements.title": "Elements",
@@ -3839,6 +3853,18 @@ export const en: Record<TranslationKey, string> = {
// Editor
"layouts.editorTitle": "Layout editor",
"layouts.fit": "Fit",
"layouts.strip": "Sheets",
"layouts.copyName": "{name} copy",
"layouts.duplicate": "Duplicate",
"layouts.stripMore": "Sheet menu",
"layouts.deleteSheetMessage": "Delete sheet “{name}” including the drawings on it? You can undo this.",
"layouts.moveContent": "Move content within the frame",
"layouts.insert": "Insert",
"layouts.viewportShort": "View",
"layouts.legendShort": "Legend",
"layouts.tableShort": "Table",
"layouts.imageShort": "Image",
"layouts.textShort": "Text",
"sheetTable.add": "Table",
"sheetTable.title": "Table",
"sheetTable.source": "Source",
+2 -1
View File
@@ -37,7 +37,8 @@ function scan(): Record<string, string[]> {
for (const m of text.matchAll(JSX_TEXT)) {
const s = m[1].trim();
// Generics/Typ-Ausdrücke wie `Array<string>` und reine Platzhalter ausnehmen
if (/^[a-z]+(\.[a-z]+)*$/.test(s) && !s.includes(" ")) continue;
// … und Symbol-Namen (Material Symbols, z. B. `fit_screen`): keine UI-Texte.
if (/^[a-z]+([._][a-z]+)*$/.test(s) && !s.includes(" ")) continue;
if (/=>|=|;|\(|\)/.test(s)) continue;
if (!/[a-zäöüß]{3,}/i.test(s)) continue;
hits.push(s);
+4
View File
@@ -34,6 +34,7 @@ import { SiteRulesSection } from "./SiteRulesSection";
import { TreeSection } from "./objectInfo/TreeSection";
import { RailingSection } from "./objectInfo/RailingSection";
import { CameraSection } from "./objectInfo/CameraSection";
import { SheetSection } from "./objectInfo/SheetSection";
import { ViewShadowsInfo, MeasurementSection } from "./objectInfo/InfoBlocks";
import { DimensionField, RotateField } from "./objectInfo/fields";
import { LibObjectSection } from "./objectInfo/LibObjectSection";
@@ -123,6 +124,9 @@ export function ObjectInfoPanel({ showPlacement = true }: { showPlacement?: bool
</div>
);
}
// [333] Offenes Layout-Blatt ohne Auswahl: die Eigenschaften des Blatts (wie InDesign das Dokument).
const sheetLayoutId = sel === null && !m ? storeProject.drawingLevels.find((l) => l.id === host.activeLevelId)?.layoutId : undefined;
if (sheetLayoutId) return <SheetSection layoutId={sheetLayoutId} />;
if (sel === null) {
const groups = hasInfoGroups(null, undefined, host);
return (
+23 -11
View File
@@ -381,6 +381,8 @@ const TOOLS_2D: ToolId[] = [
];
const TOOLS_3D: ToolId[] = ["wall", "ceiling", "window", "door", "stair", "room"];
const COMMANDS_3D = ["column", "traeger", "gelaender", "tree", "circlestotrees", "ceilingopening", "ramp", "roof", "roofhole", "roofwindow", "dormer", "extrude", "revolve", "loft", "solid", "solidbool", "solidtoparts", "sectionline", "viewline", "ansichten", "autodim", "excavation"];
/** [333] Auf einem Layout-Blatt: nur Zeichnen, Beschriften und Bild — keine Bauteile, keine Konstruktionslinien. */
const TOOLS_SHEET: ToolId[] = ["line", "polyline", "rect", "circle", "arc", "ellipse", "polygon", "spline", "dimension", "scalebar", "revcloud", "wipeout", "block", "text", "leader", "textbox", "image"];
const COMMANDS_EDIT = ["move", "copy", "array", "rotate", "mirror", "offset", "multiline", "trim", "break", "split", "extend", "fillet", "chamfer", "join", "defblock", "measure", "erkennen"];
type ToolsView = "list" | "icons";
@@ -401,6 +403,7 @@ export const ToolsPanel = memo(function ToolsPanel() {
const host = usePanelHostSelect((h) => ({
activeTool: h.activeTool,
toolsEnabled: h.toolsEnabled,
sheetActive: h.sheetActive,
activeCommand: h.activeCommand,
}));
const onSelectTool = usePanelHostAction("onSelectTool");
@@ -491,18 +494,27 @@ export const ToolsPanel = memo(function ToolsPanel() {
{/* Auswahl-Werkzeug: immer als volle Zeile zuoberst (meistgenutzt). */}
<div className="tp-select">{toolButton("select")}</div>
<section className="tp-section">
<div className="tp-section-title">{t("tools.cat.2d")}</div>
<div className={bodyClass}>{TOOLS_2D.map(toolButton)}</div>
</section>
{host.sheetActive ? (
<section className="tp-section">
<div className="tp-section-title">{t("tools.cat.sheet")}</div>
<div className={bodyClass}>{TOOLS_SHEET.map(toolButton)}</div>
</section>
) : (
<>
<section className="tp-section">
<div className="tp-section-title">{t("tools.cat.2d")}</div>
<div className={bodyClass}>{TOOLS_2D.map(toolButton)}</div>
</section>
<section className="tp-section">
<div className="tp-section-title">{t("tools.cat.3d")}</div>
<div className={bodyClass}>
{TOOLS_3D.map(toolButton)}
{COMMANDS_3D.map(commandButton)}
</div>
</section>
<section className="tp-section">
<div className="tp-section-title">{t("tools.cat.3d")}</div>
<div className={bodyClass}>
{TOOLS_3D.map(toolButton)}
{COMMANDS_3D.map(commandButton)}
</div>
</section>
</>
)}
<section className="tp-section">
<div className="tp-section-title">{t("tools.cat.edit")}</div>
+2
View File
@@ -85,6 +85,8 @@ export interface PanelHostValue {
onSelectTool: (id: ToolId) => void;
/** Werkzeuge nur im Grundriss eines Geschosses sinnvoll. */
toolsEnabled: boolean;
/** [333] Ein Layout-Blatt ist offen: die Palette zeigt nur, was auf dem Blatt Sinn ergibt (keine Bauteile). */
sheetActive: boolean;
/** Laufender Engine-Befehl (Highlight der Befehls-Knöpfe im ToolsPanel). */
activeCommand: string | null;
/** Engine-Befehl starten (Ändern-/BIM-Befehle im ToolsPanel — gleicher Pfad
+104
View File
@@ -0,0 +1,104 @@
// [333] Objekt-Info eines offenen Layout-Blatts ohne Auswahl (wie InDesign: ohne Auswahl die Eigenschaften des Dokuments):
// Name, Plannummer, Revision, Format und Ausrichtung (nur ohne Master — sonst gibt der Master die Grösse), Masterlayout,
// dazu Blattgrösse und Inhalt (Ansichten, Tabellen). Jede Änderung ein Undo-Schritt.
import type { Layout, LayoutOrientation, LayoutPaperFormat } from "../../model/types";
import { useStore } from "../../state/appStore";
import { t } from "../../i18n";
import { patchItem } from "../../core";
import { Dropdown } from "../../ui/Dropdown";
import { effectiveSheetSizeMm, findMaster } from "../../model/layoutModel";
const PAPERS: LayoutPaperFormat[] = ["a0", "a1", "a2", "a3", "a4", "a5", "a6", "b0", "b1", "b2", "b3", "b4", "b5", "b6"];
function TextField({ label, value, onCommit, testId }: { label: string; value: string; onCommit: (v: string) => void; testId?: string }) {
return (
<label className="objinfo-field">
<span className="objinfo-flabel">{label}</span>
<input
className="objinfo-text"
type="text"
defaultValue={value}
key={value}
data-testid={testId}
onBlur={(e) => {
const v = e.target.value.trim();
if (v !== value) onCommit(v);
}}
onKeyDown={(e) => {
if (e.key === "Enter") (e.target as HTMLInputElement).blur();
}}
/>
</label>
);
}
export function SheetSection({ layoutId }: { layoutId: string }) {
const project = useStore((s) => s.project);
const applyChange = useStore((s) => s.applyChange);
const layout = (project.layouts ?? []).find((l) => l.id === layoutId);
if (!layout) return null;
const set = (patch: Partial<Layout>) => applyChange((p) => patchItem(p, "layouts", layout.id, patch));
const master = findMaster(project, layout);
const size = effectiveSheetSizeMm(master ?? layout);
const masters = project.masterLayouts ?? [];
return (
<div className="objinfo-panel" data-testid="sheet-section">
<div className="objinfo-head">
<span className="objinfo-kind">{t("objinfo.sheet.kind")}</span>
</div>
<TextField label={t("objinfo.sheet.name")} value={layout.name} testId="sheet-name" onCommit={(v) => v && set({ name: v })} />
<TextField label={t("objinfo.sheet.number")} value={layout.planNumber ?? ""} onCommit={(v) => set({ planNumber: v || undefined })} />
<TextField label={t("objinfo.sheet.revision")} value={layout.revision ?? ""} onCommit={(v) => set({ revision: v || undefined })} />
<div className="objinfo-section-label">{t("objinfo.sheet.paper")}</div>
<div className="objinfo-field">
<span className="objinfo-flabel">{t("layouts.master")}</span>
<Dropdown
value={layout.masterId ?? ""}
onChange={(v) => set({ masterId: v || undefined })}
options={[{ value: "", label: t("layouts.noMaster") }, ...masters.map((m) => ({ value: m.id, label: m.name }))]}
title={t("layouts.master")}
width={150}
/>
</div>
{!master && (
<>
<div className="objinfo-field">
<span className="objinfo-flabel">{t("layouts.paper")}</span>
<Dropdown
value={layout.paper}
onChange={(v) => set({ paper: v as LayoutPaperFormat, customWidthMm: undefined, customHeightMm: undefined })}
options={PAPERS.map((v) => ({ value: v, label: v.toUpperCase() }))}
title={t("layouts.paper")}
width={150}
/>
</div>
<div className="objinfo-field">
<span className="objinfo-flabel">{t("layouts.orientation")}</span>
<Dropdown
value={layout.orientation}
onChange={(v) => set({ orientation: v as LayoutOrientation })}
options={[
{ value: "portrait", label: t("layouts.portrait") },
{ value: "landscape", label: t("layouts.landscape") },
]}
title={t("layouts.orientation")}
width={150}
/>
</div>
</>
)}
<div className="objinfo-field">
<span className="objinfo-flabel">{t("objinfo.sheet.size")}</span>
<span className="objinfo-fval">{`${Math.round(size.w)} × ${Math.round(size.h)} mm`}</span>
</div>
<div className="objinfo-field">
<span className="objinfo-flabel">{t("objinfo.sheet.content")}</span>
<span className="objinfo-fval">
{t("objinfo.sheet.contentCount", { views: layout.viewports.length, tables: (layout.tables ?? []).length })}
</span>
</div>
<div className="objinfo-muted">{t("objinfo.sheet.hint")}</div>
</div>
);
}
+2 -9
View File
@@ -6,6 +6,7 @@ import { t } from "../../i18n";
import { createLayout, createLayoutFolder, createMasterLayout, deleteFolder as deleteLayoutFolder, deleteMasterFolder, moveLayoutToFolder, moveFolderToFolder, createSheetLevel } from "../../model/layoutModel";
import { folderPdfBytes } from "../../export/layoutPdf";
import { addPublishSetOps, addWbwSetOps, deletePublishSetOps, patchPublishSetOps, publishSet, setCompetitionOps } from "../publishActions";
import { deleteSheetOps } from "../sheetOrder";
import { openLayoutTab } from "../tabNavigation";
import { saveBinaryFile } from "../../native/saveFile";
import { runWithAnonymityGate } from "../anonymityGate";
@@ -31,15 +32,7 @@ export function buildLayoutsHost(c: FlatHostOpts) {
},
onDeleteLayout: (id) => {
// Mit dem Layout gehen seine Blatt-Ebene und deren Zeichnungen (ein Undo-Schritt).
applyChange((p) => {
const levels = p.drawingLevels.filter((l) => l.layoutId === id).map((l) => l.id);
const drawings = p.drawings2d.filter((d) => levels.includes(d.levelId)).map((d) => d.id);
return [
...removeItems(p, "drawings2d", drawings),
...removeItems(p, "drawingLevels", levels),
...removeItems(p, "layouts", [id]),
];
});
applyChange((p) => deleteSheetOps(p, id));
setActiveLayoutId((cur) => (cur === id ? null : cur));
},
onOpenLayout: (id) => {
+1
View File
@@ -18,6 +18,7 @@ export function buildToolsHost(c: FlatHostOpts) {
// Geschoss-Arbeitsebene (OKFF) projiziert und über onWorkplanePoint in
// dieselbe Engine wie im Grundriss gespeist (Viewport3D).
toolsEnabled: activeLevel.kind === "floor",
sheetActive: !!activeLevel.layoutId,
activeCommand: engineView.commandName,
onRunCommand,
activeWallTypeId,
+11 -1
View File
@@ -64,7 +64,7 @@ import { reorderByIds } from "../model/reorder";
import { transformMutation } from "../tools/transform";
import type { CopyMode, TransformOp, TransformSelection } from "../tools/transform";
import { uniqueId } from "../tools/types";
import { gripPt, type GripRequest, type RingKind, type SheetHeightKind } from "../core";
import { gripPt, type GripRequest, type RingKind, type SheetEndKind, type SheetHeightKind } from "../core";
import { DEFAULT_SCALE_DENOMINATOR } from "../model/dimension";
import { DEFAULT_PRESETS, type TextStylePreset } from "../text/richText";
import { t } from "../i18n";
@@ -396,6 +396,9 @@ export interface ProjectSlice {
moveCameraGrip: (id: string, index: number, pt: Vec2) => void;
/** [280] Träger: Griff 0 Anfang, 1 Ende, 2 Mitte (verschiebt den Träger), Kern `grips.rs`. */
moveBeamGrip: (id: string, index: number, pt: Vec2) => void;
/** [333] Stütze (Mitte, Ecken, Drehen/Radius) bzw. freier Körper (Ecke, Verschieben); Kern `grips.rs`. */
moveColumnGrip: (id: string, index: number, pt: Vec2) => void;
moveSolidGrip: (id: string, index: number, pt: Vec2) => void;
/** [176] Knick in Segment `seg` (Mittel-Griff) einfügen; `coalesceKey` fasst den anschliessenden Zug zusammen. */
insertSectionBend: (id: string, seg: number, pt: Vec2, coalesceKey?: string) => void;
/** [176] Knick löschen (`index` wie bei {@link moveSectionLineGrip}; Anfang/Ende lassen sich nicht löschen). */
@@ -433,6 +436,8 @@ export interface ProjectSlice {
setCeilingThickness: (ceilingId: string, thickness: number) => void;
/** [187] Höhen-Griff im Schnitt/in der Ansicht: Kante `kind` des Bauteils `id` auf die Blatt-Höhe `y` (absolutes Z) ziehen. */
sheetHeightGrip: (kind: SheetHeightKind, id: string, y: number, free?: boolean, from?: number, index?: number) => void;
/** [333] Waagrechter End-Griff im Schnitt: Ende `end` (0 links, 1 rechts) von Decke/Wand um `du` m in u ziehen. */
sheetEndGrip: (kind: SheetEndKind, id: string, end: 0 | 1, du: number, base: Vec2, uAxis: Vec2) => void;
// ── Öffnungs-Editieren (Object-Info-Panel) ────────────────────────────────
/** Generischer immutabler Patch auf eine Öffnung (per ID). */
@@ -1325,6 +1330,8 @@ export function createProjectSlice(
moveSectionLineGrip: (id, index, pt, coalesceKey) =>
applyGrip({ op: "sectionLineGrip", id, index, pt: gripPt(pt) }, coalesceKey ?? `moveSectionLineGrip:${id}:${index}`),
moveCameraGrip: (id, index, pt) => applyGrip({ op: "cameraGrip", id, index, pt: gripPt(pt) }, `moveCameraGrip:${id}:${index}`),
moveColumnGrip: (id, index, pt) => applyGrip({ op: "columnGrip", id, index, pt: gripPt(pt) }, `moveColumnGrip:${id}:${index}`),
moveSolidGrip: (id, index, pt) => applyGrip({ op: "solidGrip", id, index, pt: gripPt(pt) }, `moveSolidGrip:${id}:${index}`),
moveBeamGrip: (id, index, pt) => applyGrip({ op: "beamGrip", id, index, pt: gripPt(pt) }, `moveBeamGrip:${id}:${index}`),
insertSectionBend: (id, seg, pt, coalesceKey) => applyGrip({ op: "sectionBendInsert", id, seg, pt: gripPt(pt) }, coalesceKey),
deleteSectionBend: (id, index) => applyGrip({ op: "sectionBendDelete", id, index }),
@@ -1387,6 +1394,9 @@ export function createProjectSlice(
newName: t("default.ceilingTypeSingle", { thickness: "{t}" }), // {t} setzt der Kern ein
}),
sheetEndGrip: (kind, id, end, du, base, uAxis) =>
applyGrip({ op: "sheetEnd", kind, id, index: end, a: du, pt: gripPt(base), delta: gripPt(uAxis) }),
// ── Öffnungs-Editieren ────────────────────────────────────────────────
updateOpening: (id, patch) => applyChange((p) => patchItem(p, "openings", id, patch)),
slideOpening: (id, to, coalesceKey) =>
+18
View File
@@ -0,0 +1,18 @@
import { describe, expect, it } from "vitest";
import { moveSheetIds } from "./sheetOrder";
describe("moveSheetIds", () => {
const ids = ["a", "b", "c"];
it("dritte vor die erste", () => expect(moveSheetIds(ids, "c", 0)).toEqual(["c", "a", "b"]));
it("erste ans Ende", () => expect(moveSheetIds(ids, "a", 3)).toEqual(["b", "c", "a"]));
it("erste hinter die zweite (Stelle zählt in der alten Liste)", () => expect(moveSheetIds(ids, "a", 2)).toEqual(["b", "a", "c"]));
it("Stelle direkt vor/nach sich selbst: unverändert (gleiche Liste)", () => {
expect(moveSheetIds(ids, "b", 1)).toBe(ids);
expect(moveSheetIds(ids, "b", 2)).toBe(ids);
});
it("unbekannte id und Stelle ausserhalb", () => {
expect(moveSheetIds(ids, "x", 0)).toBe(ids);
expect(moveSheetIds(ids, "c", -5)).toEqual(["c", "a", "b"]);
expect(moveSheetIds(ids, "a", 99)).toEqual(["b", "c", "a"]);
});
});
+64
View File
@@ -0,0 +1,64 @@
// [333] Blätter-Leiste: reine Logik für Umsortieren, Duplizieren und Löschen eines Blatts (Op-Bauer, ohne UI).
import { addItems, fieldOps, removeItems } from "../core";
import type { CoreOp } from "../core";
import type { Layout, Project } from "../model/types";
import { createSheetLevel } from "../model/layoutModel";
/**
* Verschiebt `fromId` an die Einfüge-Stelle `slot` (0…n, gezählt in der ALTEN Liste: „vor dem Blatt mit diesem Index“).
* Ohne Änderung (unbekannte id, Stelle direkt vor/nach dem Blatt) kommt dieselbe Liste zurück.
*/
export function moveSheetIds(ids: readonly string[], fromId: string, slot: number): readonly string[] {
const from = ids.indexOf(fromId);
if (from < 0) return ids;
const s = Math.max(0, Math.min(ids.length, Math.round(slot)));
if (s === from || s === from + 1) return ids;
const rest = ids.filter((id) => id !== fromId);
rest.splice(s > from ? s - 1 : s, 0, fromId);
return rest;
}
/** Ops, die das Blatt `fromId` an die Stelle `slot` setzen (ein Undo-Schritt); leer, wenn sich nichts ändert. */
export function reorderSheetsOps(p: Project, fromId: string, slot: number): CoreOp[] {
const layouts = p.layouts ?? [];
const ids = layouts.map((l) => l.id);
const next = moveSheetIds(ids, fromId, slot);
if (next === ids) return [];
const byId = new Map(layouts.map((l) => [l.id, l]));
return fieldOps(p, "layouts", next.map((id) => byId.get(id)!));
}
/** Ops, die ein Blatt samt Blatt-Ebene und deren Zeichnungen entfernen. */
export function deleteSheetOps(p: Project, id: string): CoreOp[] {
const levels = p.drawingLevels.filter((l) => l.layoutId === id).map((l) => l.id);
const drawings = p.drawings2d.filter((d) => levels.includes(d.levelId)).map((d) => d.id);
return [
...removeItems(p, "drawings2d", drawings),
...removeItems(p, "drawingLevels", levels),
...removeItems(p, "layouts", [id]),
];
}
/**
* Ops, die ein Blatt direkt hinter dem Original kopieren: eigene Blatt-Ebene samt Zeichnungen (neue ids),
* ohne eigene Plannummer (sonst doppelt). Leer, wenn das Blatt fehlt.
*/
export function duplicateSheetOps(p: Project, id: string, newId: string, copyName: string): CoreOp[] {
const layouts = p.layouts ?? [];
const at = layouts.findIndex((l) => l.id === id);
if (at < 0) return [];
const copy: Layout = { ...layouts[at], id: newId, name: copyName, planNumber: undefined };
const levelIds = new Map<string, string>();
const newLevels = p.drawingLevels
.filter((l) => l.layoutId === id)
.map((l) => {
const nid = `sheet-${newId}${levelIds.size ? `-${levelIds.size}` : ""}`;
levelIds.set(l.id, nid);
return { ...createSheetLevel(nid, copy), ...l, id: nid, name: copyName, layoutId: newId };
});
const newDrawings = p.drawings2d
.filter((d) => levelIds.has(d.levelId))
.map((d, i) => ({ ...d, id: `${d.id}-${newId}-${i}`, levelId: levelIds.get(d.levelId)! }));
return [...addItems("layouts", [copy], at + 1), ...addItems("drawingLevels", newLevels), ...addItems("drawings2d", newDrawings)];
}
+24 -2
View File
@@ -40,6 +40,8 @@ declare global {
selected: () => { drawings: string[]; groups: string[]; all: string };
/** [144] Öffnungen (id, Wirtswand, Lage ab Wandanfang). */
openings: () => { id: string; hostWallId: string; position: number }[];
/** [333] Umriss einer Decke (Modell-Meter). */
ceilingOutline: (id: string) => { x: number; y: number }[];
/** [187] Höhen von Decken (UK/OK/Dicke), Wänden (UK/OK) und Fenstern (Brüstung/Höhe) aus dem Kern, in Metern (absolutes Z). */
heights: () => {
ceilings: { id: string; zBottom: number; zTop: number; thickness: number }[];
@@ -47,7 +49,7 @@ declare global {
openings: { id: string; sillHeight: number; height: number }[];
/** [187] Teil 2: Traufe (absolutes Z), Neigung, Attika-Höhe; Steighöhe der Treppen; Sohle der Baugruben. */
roofs: { id: string; eave: number; pitchDeg: number; parapetHeight: number }[];
stairs: { id: string; totalRise: number; baseOffset: number }[];
stairs: { id: string; totalRise: number; baseOffset: number; runLength: number; width: number }[];
/** [187] Höhe je Höhenlinie der Höhenlinien-Sätze. */
contours: { id: string; zs: number[] }[];
excavations: { id: string; bottom: number }[];
@@ -109,6 +111,13 @@ declare global {
/** [253] Objekte der Bibliothek im Projekt (Id, Lage, Drehung, Parameter, Seed, Klasse) mit Ausmass ihrer Plan-Linien (1:50) im aktiven Geschoss; dazu die Klassen-Codes des Projekts. */
libobjs: () => { items: { id: string; libId: string; at: { x: number; y: number }; rotation: number; params: Record<string, number | boolean | string>; seed: number | undefined; categoryCode: string; lines: number; w: number; h: number }[]; layers: string[] };
/** [202] Treppe (Antritt, Zentrum), erster Punkt des ersten Lochs der Decke `ceilingId` und Zahl der Plan-Linien der Treppe im aktiven Geschoss. */
/** [333] Lage/Querschnitt der Stützen und Profil-Ecken der freien Körper (Griff-Test). */
/** [333] Stützen-Griff ohne Maus auslösen (Testvorbereitung: Stütze aufziehen, damit die Griffe trennbar sind). */
columnGrip: (id: string, index: number, x: number, y: number) => void;
gripGeom: () => {
columns: { id: string; position: { x: number; y: number }; rotation: number; width: number; depth: number; radius: number }[];
solids: { id: string; points: { x: number; y: number }[] }[];
};
stairHole: (stairId: string, ceilingId: string) => { start: { x: number; y: number }; center: { x: number; y: number } | null; hole0: { x: number; y: number } | null; lines: number };
/** [203] Grundriss der aktiven Ebene wie in der Ansicht (Geschoss-Überlagerung nach Zeichnungsebenen-Modus): Raumstempel je Geschoss (gesamt/gedimmt) und Zahl der Achs-Beschriftungen `axis`. */
planStamps: (axis: string) => { floors: Record<string, { n: number; greyed: number }>; axis: number };
@@ -219,6 +228,7 @@ export function installTestHooks(): void {
polylines: (prefix) =>
getState().project.drawings2d.flatMap((d) => (d.id.startsWith(prefix) && d.geom.shape === "polyline" ? [{ id: d.id, pts: d.geom.pts }] : [])),
openings: () => (getState().project.openings ?? []).map((o) => ({ id: o.id, hostWallId: o.hostWallId, position: o.position })),
ceilingOutline: (id) => (getState().project.ceilings ?? []).find((c) => c.id === id)?.outline.map((q) => ({ x: q.x, y: q.y })) ?? [],
heights: () => {
const p = getState().project;
const ceilings = p.ceilings ?? [];
@@ -231,7 +241,7 @@ export function installTestHooks(): void {
const f = p.drawingLevels.find((l) => l.id === r.floorId);
return { id: r.id, eave: r.baseElevation ?? (f ? (f.baseElevation ?? 0) + (f.floorHeight ?? 0) : 0), pitchDeg: r.pitchDeg, parapetHeight: r.parapetHeight ?? 0 };
}),
stairs: (p.stairs ?? []).map((st) => ({ id: st.id, totalRise: st.totalRise ?? NaN, baseOffset: st.baseOffset ?? 0 })),
stairs: (p.stairs ?? []).map((st) => ({ id: st.id, totalRise: st.totalRise ?? NaN, baseOffset: st.baseOffset ?? 0, runLength: st.runLength, width: st.width })),
contours: (p.context ?? []).flatMap((c) => (c.type === "contourSet" ? [{ id: c.id, zs: c.contours.map((k) => k.z) }] : [])),
excavations: (p.context ?? []).flatMap((c) => (c.type === "excavation" ? [{ id: c.id, bottom: c.bottom }] : [])),
};
@@ -541,6 +551,18 @@ export function installTestHooks(): void {
return { wallId: s.project.walls.find((w) => w.floorId === s.activeLevelId)?.id ?? s.project.walls[0]?.id ?? "", visible: vis.sort(), prims: prims.length, wallPrims: prims.filter((q) => !!(q as { wallId?: string }).wallId).length };
},
selected: () => ({ drawings: [...getState().selection.drawings], groups: [...getState().selection.groups], all: JSON.stringify(getState().selection) }),
columnGrip: (id, index, x, y) => getState().moveColumnGrip(id, index, { x, y }),
gripGeom: () => {
const p = getState().project;
return {
columns: (p.columns ?? []).map((c) => ({
id: c.id, position: c.position, rotation: c.rotation,
width: c.profile.kind === "rect" ? c.profile.width : NaN, depth: c.profile.kind === "rect" ? c.profile.depth : NaN,
radius: c.profile.kind === "round" ? c.profile.radius : NaN,
})),
solids: (p.extrudedSolids ?? []).map((x) => ({ id: x.id, points: x.points })),
};
},
stairHole: (stairId, ceilingId) => {
const s = getState();
const st = (s.project.stairs ?? []).find((x) => x.id === stairId)!;
+48 -2
View File
@@ -6,10 +6,11 @@
// 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 { Ceiling, Column, Drawing2D, Opening, Project, Roof, Stair, Vec2, Wall } from "../model/types";
import type { SnapResult, SnapSettings, ToolDraft } from "../tools/types";
import { computeSnap } from "../tools/snapping";
import { roofBaseElevation, roofGeometry } from "../core";
import { roofBaseElevation, roofGeometry, stairMoveHandle } from "../core";
import type { ElemGripTarget } from "../viewport/elementGrips3d";
import {
neighbor3dVertex,
bodyMoveAnchor,
@@ -48,6 +49,10 @@ export function useGrip3dEditing(opts: {
moveGripOf: Actions["moveGripOf"];
moveElementByOf: Actions["moveElementByOf"];
updateWall: Actions["updateWall"];
moveStairBy: Actions["moveStairBy"];
dragStairParam: Actions["dragStairParam"];
slideOpening: Actions["slideOpening"];
moveColumnGrip: Actions["moveColumnGrip"];
}) {
const {
project,
@@ -67,8 +72,13 @@ export function useGrip3dEditing(opts: {
moveGripOf,
moveElementByOf,
updateWall,
moveStairBy,
dragStairParam,
slideOpening,
moveColumnGrip,
} = opts;
const { walls: selectedWallIds, drawings: selectedDrawingIds, ceilings: selectedCeilingIds, roofs: selectedRoofIds } = selection;
const { stairs: selectedStairIds, openings: selectedOpeningIds, columns: selectedColumnIds } = selection;
// ── 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
@@ -121,6 +131,38 @@ export function useGrip3dEditing(opts: {
: [],
[selectedWallIds, selectedDrawingIds, selectedCeilingIds, selectedRoofIds, project.roofs],
);
// [333] Treppen, Wandöffnungen und Stützen: Griffe nur, wenn sonst nichts mit eigenen 3D-Griffen gewählt ist
// (eindeutiger Editierfokus). Gesperrte Elemente zeigt `elementGrips3d` nicht.
const noOtherGrips =
selectedWallIds.length === 0 && selectedDrawingIds.length === 0 && selectedCeilingIds.length === 0 && selectedRoofIds.length === 0;
const edit3dStairs = useMemo(
() => (noOtherGrips ? selectedStairIds.map((id) => (project.stairs ?? []).find((s) => s.id === id)).filter((s): s is Stair => !!s) : []),
[noOtherGrips, selectedStairIds, project.stairs],
);
const edit3dOpenings = useMemo(
() => (noOtherGrips ? selectedOpeningIds.map((id) => (project.openings ?? []).find((o) => o.id === id)).filter((o): o is Opening => !!o) : []),
[noOtherGrips, selectedOpeningIds, project.openings],
);
const edit3dColumns = useMemo(
() => (noOtherGrips ? selectedColumnIds.map((id) => (project.columns ?? []).find((c) => c.id === id)).filter((c): c is Column => !!c) : []),
[noOtherGrips, selectedColumnIds, project.columns],
);
// Griff von Treppe/Öffnung/Stütze ziehen: derselbe Kern-Zug wie im Plan (`stairBy`/`stairParam`/`openingSlide`/`columnGrip`),
// `pt` = Strahl-Treffpunkt auf der Griff-Ebene in Modell-Metern. Ein Undo-Schritt je Zug über den coalesceKey der Aktion.
const onEdit3dElement = (target: ElemGripTarget, index: number, pt: Vec2) => {
if (target.stairId) {
const st = (project.stairs ?? []).find((s) => s.id === target.stairId);
if (!st || st.locked) return;
if (index > 0) dragStairParam(st.id, index - 1, pt);
else moveStairBy(st.id, { x: pt.x - stairMoveHandle(st).x, y: pt.y - stairMoveHandle(st).y });
} else if (target.openingId) {
const op = (project.openings ?? []).find((o) => o.id === target.openingId);
if (op && !op.locked) slideOpening(op.id, { pt }, `slideOpening:${op.id}`);
} else if (target.columnId) {
const c = (project.columns ?? []).find((x) => x.id === target.columnId);
if (c && !c.locked) moveColumnGrip(c.id, index, pt);
}
};
// 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`
@@ -415,6 +457,10 @@ export function useGrip3dEditing(opts: {
edit3dDrawings,
edit3dCeilings,
edit3dRoofs,
edit3dStairs,
edit3dOpenings,
edit3dColumns,
onEdit3dElement: useEvent(onEdit3dElement),
grip3dEdit,
setGrip3dEdit,
last3dDragRef,
+103 -5
View File
@@ -35,6 +35,7 @@ import {
stairParamPoints,
wallGripPoints,
type GripLocks,
type SheetEndKind,
} from "../core";
import { areaMovePreview, drawingMovePreview, transformPreview } from "../tools/transform";
import { contextAnchor } from "./contextDrag";
@@ -52,7 +53,7 @@ import { growRect, meshGripIndices } from "../core";
import { patchItem, verticalExtents } from "../core";
import { treeGripPatch, treeGripPoints } from "./treeGrips";
import { railingGripPatch, railingGripPoints } from "./railingGrips";
import { beamGripPoints, cameraGripPoints } from "../core";
import { beamGripPoints, cameraGripPoints, columnGripPoints, solidGripPoints } from "../core";
import type { Selection } from "./selection";
export interface GripEditFieldsState {
@@ -115,6 +116,8 @@ export function useGripEditing(opts: {
slideOpening: (id: string, to: { position: number } | { pt: Vec2 }, coalesceKey?: string) => void;
/** [187] Höhen-Griff im Schnitt/in der Ansicht anwenden (Kern `sheet_height.rs`); EIN Aufruf je Zug. */
sheetHeightGrip: (kind: SheetHeightKind, id: string, y: number, free?: boolean, from?: number, index?: number) => void;
/** [333] Waagrechter End-Griff im Schnitt (Kern `sheet_height::end_ops`); EIN Aufruf je Zug. */
sheetEndGrip: (kind: SheetEndKind, id: string, end: 0 | 1, du: number, base: Vec2, uAxis: Vec2) => void;
moveStairBy: (id: string, delta: Vec2) => void;
/** [151] Parameter-Griff einer Podesttreppe ziehen (Index ohne den Bewegpunkt). */
dragStairParam?: (id: string, index: number, pt: Vec2) => void;
@@ -173,6 +176,7 @@ export function useGripEditing(opts: {
updateOpening,
slideOpening,
sheetHeightGrip,
sheetEndGrip,
moveStairBy,
moveRoomGrip,
moveCeilingGrip,
@@ -222,6 +226,10 @@ export function useGripEditing(opts: {
// [280] Träger liegen im Auswahlkanal der Stützen: ein gewählter einzelner Träger zeigt Anfang-, Ende- und Mitte-Griff.
const selectedColumnId = single(selection, "columns");
const selectedBeam = selectedColumnId ? (project.beams ?? []).find((x) => x.id === selectedColumnId && x.floorId === levelId) : undefined;
// [333] Stütze und freier Körper: eigene Griffe im Grundriss (Mitte/Ecken/Drehen bzw. Ecken/Verschieben).
const selectedColumn = selectedColumnId && !selectedBeam ? (project.columns ?? []).find((x) => x.id === selectedColumnId && x.floorId === levelId) : undefined;
const selectedSolidId = single(selection, "solids");
const selectedSolid = selectedSolidId ? (project.extrudedSolids ?? []).find((x) => x.id === selectedSolidId && x.levelId === levelId) : undefined;
const selectedCamera = selectedCameraId ? (project.cameras ?? []).find((x) => x.id === selectedCameraId && x.floorId === levelId) : undefined;
// [176] Schnitt-/Ansichtslinie im Grundriss: Griffe an Anfang, Knickpunkten (`bendPoints`) und Ende.
const selectedSectionLineId = single(selection, "sectionLines");
@@ -447,6 +455,43 @@ export function useGripEditing(opts: {
return [];
})();
// [333] Waagrechte End-Griffe im Schnitt (wie in Archicad): Decke an den Enden ihres Schnitts (Mitte der Dicke) bzw. Wand,
// deren Achse höchstens 30° von der Schnittlinie abweicht (Mitte der Höhe). Ziehen verlängert/verkürzt das Bauteil entlang
// der Schnittlinie; der Kern (`end_ops`) rechnet beim Loslassen. Nur gerade Schnittlinien (bei Knicken ist u nicht eindeutig).
type SheetEndGrip = { kind: SheetEndKind; id: string; end: 0 | 1; pt: Vec2; horizontal: true };
const sheetEndGrips: SheetEndGrip[] = (() => {
if (modelEditable || !sheet?.base) return [];
const lvl = project.drawingLevels.find((l) => l.id === sheet.levelId);
if (!lvl || lvl.kind !== "section" || (lvl.bendPoints?.length ?? 0) > 0) return [];
const ends = (kind: SheetEndKind, id: string, owner: "wall" | "ceiling", zMid: number): SheetEndGrip[] => {
const polys = sheetOwnerOutlines(sheet.levelId, owner, id);
let u0 = Infinity, u1 = -Infinity;
for (const poly of polys) for (const q of poly) { u0 = Math.min(u0, q.x); u1 = Math.max(u1, q.x); }
if (!(u1 > u0)) return [];
return [
{ kind, id, end: 0, pt: { x: u0, y: zMid }, horizontal: true },
{ kind, id, end: 1, pt: { x: u1, y: zMid }, horizontal: true },
];
};
if (selectedWallId && selectedWallIds.length <= 1 && !selectedOpeningId) {
const w = project.walls.find((x) => x.id === selectedWallId);
if (!w || w.locked || w.bulge) return [];
const len = Math.hypot(w.end.x - w.start.x, w.end.y - w.start.y);
if (len < 1e-6) return [];
const cos = Math.abs(((w.end.x - w.start.x) * sheet.uAxis.x + (w.end.y - w.start.y) * sheet.uAxis.y) / len);
if (cos < Math.cos((30 * Math.PI) / 180)) return [];
const { zBottom, zTop } = verticalExtents(project, [w]).walls[0];
return ends("wallEnd", w.id, "wall", (zBottom + zTop) / 2);
}
if (selectedCeilingId && !selectedOpeningId) {
const c = (project.ceilings ?? []).find((x) => x.id === selectedCeilingId);
if (!c || c.locked) return [];
const { zBottom, zTop } = verticalExtents(project, [], [c]).ceilings[0];
return ends("ceilingEdge", c.id, "ceiling", (zBottom + zTop) / 2);
}
return [];
})();
const MAX_INSERT_GRIP_POINTS = 100; // Kataster-Umrisse mit tausenden Punkten: keine Rauten
const MAX_CONTOUR_GRIPS = 600; // Höhenlinien-Sätze mit tausenden Punkten: gar keine Punkt-Griffe
/** Anteil entlang der Kante, an dem der Einfüge-Griff sitzt (neben dem Kanten-Anfasser in der Mitte). */
@@ -494,8 +539,9 @@ export function useGripEditing(opts: {
// verschiebt die Öffnung entlang der Wirts-Wand (siehe applyGrip →
// `position`). Nur bei genau einer selektierten Öffnung (Auswahl exklusiv).
if (!modelEditable && effectiveDrawingIds.length === 0) {
sheetHeightGrips.forEach((_, i) => { gripOwners.push({ localIndex: i }); gripOwnerRange.push([0, sheetHeightGrips.length - 1]); });
return sheetHeightGrips.map((g) => g.pt);
const all: (Vec2 & { horizontal?: boolean })[] = [...sheetHeightGrips.map((g) => g.pt), ...sheetEndGrips.map((g) => ({ ...g.pt, horizontal: true }))];
all.forEach((_, i) => { gripOwners.push({ localIndex: i }); gripOwnerRange.push([0, all.length - 1]); });
return all;
}
if (selectedOpeningId && modelEditable) {
const op = (project.openings ?? []).find((o) => o.id === selectedOpeningId);
@@ -521,7 +567,8 @@ export function useGripEditing(opts: {
if (selectedStairId && modelEditable) {
const st = (project.stairs ?? []).find((s) => s.id === selectedStairId);
if (!st) return [];
// [151] Podesttreppen: dazu die Parameter-Griffe (Lauf-Enden, Podestrand).
// [151] Podesttreppen: dazu die Parameter-Griffe (Lauf-Enden, Podestrand); [333] gerade Treppe: die vier Ecken
// (vorne Breite, hinten Breite + Lauflänge).
const pts = [stairMoveHandle(st), ...stairParamPoints(st)];
pts.forEach((_, i) => { gripOwners.push({ localIndex: i }); gripOwnerRange.push([0, pts.length - 1]); });
return pts;
@@ -531,6 +578,16 @@ export function useGripEditing(opts: {
pts.forEach((_, i) => { gripOwners.push({ localIndex: i }); gripOwnerRange.push([0, pts.length - 1]); });
return pts;
}
if (selectedColumn && modelEditable && !selectedColumn.locked) {
const pts = columnGripPoints(selectedColumn);
pts.forEach((_, i) => { gripOwners.push({ localIndex: i }); gripOwnerRange.push([0, pts.length - 1]); });
return pts;
}
if (selectedSolid && modelEditable) {
const { pts, first } = solidGripPoints(selectedSolid);
pts.forEach((_, i) => { gripOwners.push({ localIndex: first + i }); gripOwnerRange.push([first, first + pts.length - 1]); });
return pts;
}
if (selectedCamera && modelEditable && !selectedCamera.locked) {
const pts = cameraGripPoints(selectedCamera, scaleDenominator);
pts.forEach((_, i) => { gripOwners.push({ localIndex: i }); gripOwnerRange.push([0, pts.length - 1]); });
@@ -901,6 +958,8 @@ export function useGripEditing(opts: {
const pendingOpeningMoveRef = useRef<{ id: string; position: number } | null>(null);
/** Aufgeschobene Höhen-Änderung im Schnitt (Kante `kind` auf die Höhe `y`, Kern `sheetHeight`). */
const pendingSheetHeightRef = useRef<{ kind: SheetHeightKind; id: string; y: number; free: boolean; from: number; index?: number } | null>(null);
/** [333] Aufgeschobener End-Zug im Schnitt (Ende von Decke/Wand um `du` in u, Kern `sheetEnd`). */
const pendingSheetEndRef = useRef<{ kind: SheetEndKind; id: string; end: 0 | 1; du: number } | null>(null);
/** [187] Kote der gezogenen Kante im laufenden Höhen-Zug (Tab-Feld „Kote“). */
const sheetDragRef = useRef<{ z: number } | null>(null);
/** Laufendes Blatt-Delta (u, Meter) eines Zugs im Schnitt (s. moveInSheet). */
@@ -1292,6 +1351,15 @@ export function useGripEditing(opts: {
if (!selectedBeam.locked) storeState().moveBeamGrip(selectedBeam.id, index, pt);
return;
}
// [333] Stütze / freier Körper: Griff live über den Kern, ein Undo-Schritt je Zug.
if (selectedColumn) {
if (!selectedColumn.locked) storeState().moveColumnGrip(selectedColumn.id, index, pt);
return;
}
if (selectedSolid) {
storeState().moveSolidGrip(selectedSolid.id, index, pt);
return;
}
// [213] Kamera: Standpunkt, Ziel bzw. Sichtkegel-Rand live (Kern `camera::grip_edit`), ein Undo-Schritt je Zug.
if (selectedCamera) {
if (!selectedCamera.locked) storeState().moveCameraGrip(selectedCamera.id, index, pt);
@@ -1460,6 +1528,9 @@ export function useGripEditing(opts: {
const ph = pendingSheetHeightRef.current;
pendingSheetHeightRef.current = null;
if (ph) sheetHeightGrip(ph.kind, ph.id, ph.y, ph.free, ph.from, ph.index);
const pe = pendingSheetEndRef.current;
pendingSheetEndRef.current = null;
if (pe && sheet?.base) sheetEndGrip(pe.kind, pe.id, pe.end, pe.du, sheet.base, sheet.uAxis);
const pc = pendingContourRef.current;
pendingContourRef.current = null;
if (pc?.mesh) storeState().moveMeshPoint(pc.id, pc.index, pc.pt);
@@ -1649,6 +1720,7 @@ export function useGripEditing(opts: {
pendingWallMoveRef.current = null;
pendingOpeningMoveRef.current = null;
pendingSheetHeightRef.current = null;
pendingSheetEndRef.current = null;
sheetDragRef.current = null;
sheetDuRef.current = null;
pendingBodyRef.current = null;
@@ -1733,6 +1805,29 @@ export function useGripEditing(opts: {
setDraft({ preview, vertices: [], snap: null });
};
/**
* [333] End-Zug anwenden: Blatt-Delta `du` (u, Meter, 1-cm-Raster ausser `free`). Nur Vorschau und HUD — die Umrisse der
* Bauteil-Schnittfläche werden am gezogenen Ende um `du` verschoben; das Projekt ändert sich beim Loslassen (Kern `sheetEnd`).
*/
const applySheetEnd = (g: SheetEndGrip, rawU: number, free: boolean) => {
const du0 = rawU - g.pt.x;
const du = free ? du0 : Math.round(du0 * 100) / 100;
pendingSheetEndRef.current = { kind: g.kind, id: g.id, end: g.end, du };
const edgeU = g.pt.x;
const preview: DraftShape[] = sheetOwnerOutlines(sheet!.levelId, g.kind === "wallEnd" ? "wall" : "ceiling", g.id).map((pts) => ({
kind: "poly" as const,
// Die Ecken am gezogenen Ende (äusserste u) wandern mit.
pts: pts.map((q) => (Math.abs(q.x - edgeU) < 1e-6 ? { x: q.x + du, y: q.y } : q)),
closed: true,
}));
setDraft({
preview,
vertices: [],
snap: null,
hud: { at: { x: g.pt.x + du, y: g.pt.y }, text: t("grip.sheetEnd", { d: (du >= 0 ? "+" : "") + du.toFixed(2) }) },
});
};
/**
* [187] Höhen-Zug anwenden: nur Vorschau und HUD (das Projekt ändert sich beim Loslassen, EIN Undo-Schritt).
* `y` = Blatt-Höhe (absolutes Z); `free` ohne 1-cm-Raster.
@@ -1772,6 +1867,8 @@ export function useGripEditing(opts: {
// Schnitt/Ansicht ([187]): Höhen-Griff (Wand, Öffnung, Decke).
if (!modelEditable && sheet) {
gripDragInfoRef.current = { index, raw };
const endGrip = sheetEndGrips[index - sheetHeightGrips.length];
if (endGrip) return applySheetEnd(endGrip, raw.x, !!mods.ctrl);
const typed = gripEditRef.current?.locks.length; // Tab: getippte Kote
if (typed != null) return applySheetHeight(index, typed, true);
if (mods.ctrl) return applySheetHeight(index, raw.y, true);
@@ -2056,8 +2153,9 @@ export function useGripEditing(opts: {
// danach wie onGripEnd aufräumen.
onGripCancel: (index: number, origin: Vec2) => {
// Ausstehender Zug: einfach verwerfen (das Projekt wurde nie verändert).
if (pendingSheetHeightRef.current) {
if (pendingSheetHeightRef.current || pendingSheetEndRef.current) {
pendingSheetHeightRef.current = null;
pendingSheetEndRef.current = null;
} else if (pendingGripRef.current || pendingWallGripRef.current || pendingAreaGripRef.current || pendingContourRef.current) {
pendingContourRef.current = null;
pendingGripRef.current = null;
+4
View File
@@ -389,8 +389,10 @@ export function useProjectActions(
const updateCeiling = useStore((s) => s.updateCeiling);
const setCeilingThickness = useStore((s) => s.setCeilingThickness);
const sheetHeightGrip = useStore((s) => s.sheetHeightGrip);
const sheetEndGrip = useStore((s) => s.sheetEndGrip);
const updateStair = useStore((s) => s.updateStair);
const moveStairBy = useStore((s) => s.moveStairBy);
const moveColumnGrip = useStore((s) => s.moveColumnGrip);
const dragStairParam = useStore((s) => s.dragStairParam);
const updateRoom = useStore((s) => s.updateRoom);
const moveRoomBy = useStore((s) => s.moveRoomBy);
@@ -513,8 +515,10 @@ export function useProjectActions(
updateCeiling,
setCeilingThickness,
sheetHeightGrip,
sheetEndGrip,
updateStair,
moveStairBy,
moveColumnGrip,
dragStairParam,
updateRoom,
moveRoomBy,
+19
View File
@@ -25,6 +25,8 @@ import { addImage, patchImage, removeImage } from "../model/layoutImages";
import { addLegend, patchLegend, removeLegend } from "../analysis/legend";
import { useEventBundle } from "./useEvent";
import { setSheetGuidesOps } from "./sheetGuides";
import { deleteSheetOps, duplicateSheetOps, reorderSheetsOps } from "./sheetOrder";
import { t } from "../i18n";
export function useSheetPane(opts: {
activeLayoutId: string | null;
@@ -91,6 +93,23 @@ export function useSheetPane(opts: {
const openId = () => activeLayout?.id ?? "";
const handlers = useEventBundle({
onBack: () => setActiveLayoutId(null),
// [333] Blätter-Leiste: anderes Blatt öffnen.
onOpenLayout: (id: string) => setActiveLayoutId(id),
// [333] Blatt an die Einfüge-Stelle `slot` ziehen (ein Undo-Schritt).
onMoveLayout: (id: string, slot: number) => applyChange((p) => reorderSheetsOps(p, id, slot)),
// [333] Blatt direkt hinter dem Original kopieren (Blatt-Ebene und Zeichnungen mit).
onDuplicateLayout: (id: string) => {
const name = (layouts ?? []).find((l) => l.id === id)?.name ?? "";
applyChange((p) => duplicateSheetOps(p, id, `lay-${Date.now()}`, t("layouts.copyName", { name })));
},
// [333] Blatt löschen; ist es das offene, öffnet das Nachbarblatt (sonst zurück zur Modell-Ansicht).
onDeleteLayout: (id: string) => {
const list = layouts ?? [];
const i = list.findIndex((l) => l.id === id);
const next = list[i + 1] ?? list[i - 1];
applyChange((p) => deleteSheetOps(p, id));
if (activeLayoutId === id) setActiveLayoutId(next?.id ?? null);
},
// [208] Freier Text: Textspalte-Befehl auf der Blatt-Ebene (Rahmen aufziehen, dann tippen).
onAddText: () => runCommand?.("textbox"),
onPatchViewport: (viewportId: string, patch: Partial<Omit<LayoutViewport, "id" | "snapshotId">>) =>
+178 -10
View File
@@ -8069,11 +8069,13 @@ body {
display: flex;
align-items: center;
gap: 8px;
/* [263] Umbrechen statt abschneiden: bei 1280 px Fensterbreite ist die Mitte nur 640 px breit, die
Tabellen-Auswahl schrumpfte auf den Pfeil und „Einpassen“ lag ausserhalb. */
flex-wrap: wrap;
row-gap: 4px;
/* [333] Eine Zeile: unter ~820 px Breite nur Symbole (Container-Abfrage unten) statt Umbruch ([263]). */
flex-wrap: nowrap;
gap: 6px;
padding: 5px 10px;
min-width: 0;
container-type: inline-size;
container-name: sheetbar;
border-bottom: 1px solid var(--line, #2b2b2b);
background: var(--panel, #1d1d1d);
flex: 0 0 auto;
@@ -8095,21 +8097,187 @@ body {
.layout-sheet-toolbar .nav-add .material-symbols-outlined {
font-size: 16px;
}
.layout-sheet-toolbar .res-select {
width: auto;
min-width: 0;
.layout-sheet-toolbar .nav-add:disabled,
.layout-sheet-toolbar .nav-add.disabled {
opacity: 0.45;
}
/* [333] Gruppen und Trenner der Blatt-Leiste. */
.layout-sheet-group {
display: inline-flex;
align-items: center;
gap: 2px;
padding: 1px 2px 1px 6px;
border-radius: 6px;
background: color-mix(in srgb, var(--ink, #ddd) 5%, transparent);
flex: 0 0 auto;
}
.layout-sheet-group-label {
font-size: 10px;
font-weight: 600;
letter-spacing: 0.04em;
text-transform: uppercase;
color: var(--muted, #888);
margin-right: 4px;
}
.layout-sheet-sep {
width: 1px;
height: 18px;
background: var(--line, #2b2b2b);
flex: 0 0 auto;
}
/* Tabelle einfügen: Knopf-Optik, die echte Auswahl liegt unsichtbar darüber (Tastatur/Screenreader bleiben). */
.layout-sheet-select {
position: relative;
cursor: pointer;
}
.layout-sheet-select select {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
opacity: 0;
cursor: pointer;
}
.layout-sheet-caret {
font-size: 14px !important;
margin-left: -2px;
}
@container sheetbar (max-width: 820px) {
.layout-sheet-toolbar .tb-label {
display: none;
}
.layout-sheet-toolbar .nav-add {
padding: 0 5px;
}
.layout-sheet-group {
padding-left: 2px;
}
}
.layout-sheet-name {
font-size: 11px;
font-size: 12px;
font-weight: 600;
color: var(--ink);
margin-left: 4px;
margin-left: 2px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 40%;
min-width: 40px;
max-width: 28%;
flex: 0 1 auto;
}
/* [333] Blätter-Leiste links neben dem Blatt (wie die Seitenpalette in InDesign). */
.layout-sheet-body {
display: flex;
flex: 1;
min-height: 0;
min-width: 0;
}
.sheet-strip {
flex: 0 0 124px;
overflow-y: auto;
padding: 10px 8px 16px;
display: flex;
flex-direction: column;
gap: 12px;
border-right: 1px solid var(--line, #2b2b2b);
background: var(--panel, #1d1d1d);
}
.sheet-strip-item {
display: flex;
flex-direction: column;
align-items: center;
gap: 4px;
padding: 6px 4px;
border: 1px solid transparent;
border-radius: 6px;
background: transparent;
color: var(--ink);
cursor: pointer;
}
.sheet-strip-item {
position: relative;
touch-action: none;
user-select: none;
}
.sheet-strip-item.dragging {
opacity: 0.45;
}
/* Einfügelinie beim Ziehen (zwischen den Blättern). */
.sheet-strip-item.drop-before::before,
.sheet-strip-item.drop-after::after {
content: "";
position: absolute;
left: 0;
right: 0;
height: 3px;
border-radius: 2px;
background: var(--accent, #3b82f6);
pointer-events: none;
}
.sheet-strip-item.drop-before::before {
top: -8px;
}
.sheet-strip-item.drop-after::after {
bottom: -8px;
}
.sheet-strip-more {
position: absolute;
top: 2px;
right: 2px;
padding: 0 4px;
line-height: 14px;
border: 0;
border-radius: 4px;
background: transparent;
color: var(--ink);
cursor: pointer;
opacity: 0;
}
.sheet-strip-item:hover .sheet-strip-more,
.sheet-strip-item:focus-within .sheet-strip-more {
opacity: 1;
background: color-mix(in srgb, var(--panel, #1d1d1d) 80%, transparent);
}
.sheet-strip-item:hover {
background: color-mix(in srgb, var(--ink, #ddd) 6%, transparent);
}
.sheet-strip-item.active {
border-color: var(--accent, #3b82f6);
background: color-mix(in srgb, var(--accent, #3b82f6) 10%, transparent);
}
.sheet-strip-item svg {
display: block;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.25);
}
.sheet-strip-vp {
fill: #e6e6e3;
stroke: #9a9a96;
stroke-width: 1px;
vector-effect: non-scaling-stroke;
}
.sheet-strip-tb {
fill: #f1f1ee;
stroke: #b5b5b0;
stroke-width: 1px;
vector-effect: non-scaling-stroke;
}
.sheet-strip-label {
display: flex;
gap: 4px;
max-width: 104px;
font-size: 11px;
line-height: 1.2;
}
.sheet-strip-no {
font-weight: 600;
flex: 0 0 auto;
}
.sheet-strip-name {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.layout-sheet-stage {
+227 -63
View File
@@ -30,6 +30,7 @@ import type {
import { createTable, PX_PER_M, sheetTables, storedChoice, TABLE_SOURCES, tableSourceLabel, viewportCombinationPatch, viewportSnapshotPlan } from "../core";
import type { TableOut } from "../core";
import { SheetTableHud } from "./SheetTableHud";
import { SheetStrip } from "./SheetStrip";
import { isInModalDialog } from "../state/modalScope";
import { SheetImageHud } from "./SheetImageHud";
import { SheetGuidesHud } from "./SheetGuidesHud";
@@ -68,6 +69,8 @@ import {
handleCursor,
normalizeRect,
pickViewport,
resizedCenter,
viewportViewBox,
vpRect,
type Handle,
type RectMm,
@@ -90,15 +93,37 @@ export function ViewportPlanSvg({
project,
viewport,
rect,
contentFixed = false,
panMm = null,
}: {
project: Project;
viewport: LayoutViewport;
rect: RectMm;
/** [333] Rahmen wird gerade in der Grösse geändert: Inhalt bleibt auf dem Papier liegen (Vorschau wie InDesign). */
contentFixed?: boolean;
/** [333] Inhalt im Rahmen wird gerade verschoben (Papier-mm, Vorschau des Inhalts-Griffs). */
panMm?: { x: number; y: number } | null;
}) {
const ref = useRef<SVGGElement>(null);
// Aktuelle Lage für das asynchron eintreffende SVG (Schnitt) — sonst sässe es bis zum nächsten Render falsch.
const place = (): void => {
const el = ref.current;
const r = renderedViewports.get(viewport.id);
if (!el) return;
if (!r) return placeInner(el, rectRef.current);
// Bildmitte jetzt: eigene (`center`), sonst die beim Erzeugen; beim Grössen-Ziehen mitwandernd (Inhalt fest).
const own = viewport.center && Number.isFinite(viewport.center.x) && Number.isFinite(viewport.center.y) ? viewport.center : r.center;
const fixed = contentFixedRef.current ? resizedCenter(own, vpRect(viewport), rectRef.current, r.scale) : own;
const pan = panRef.current;
const c = pan ? pannedCenter(fixed, pan, r.scale) : fixed;
placeInner(el, rectRef.current, viewportViewBox(rectRef.current, c, r.rect, r.center, r.scale));
};
const rectRef = useRef(rect);
rectRef.current = rect;
const contentFixedRef = useRef(contentFixed);
contentFixedRef.current = contentFixed;
const panRef = useRef(panMm);
panRef.current = panMm;
useEffect(() => {
const el = ref.current;
if (!el) return;
@@ -124,7 +149,14 @@ export function ViewportPlanSvg({
bounds: viewportCenterBounds(viewport, scaleN),
});
el.replaceChildren(print.svg);
placeInner(el, rectRef.current);
// [333] Wofür das Bild erzeugt wurde (Rahmen, Bildmitte, Massstab): Grundlage der `viewBox` beim Ziehen.
const b = viewportCenterBounds(viewport, scaleN) ?? plan.bounds;
renderedViewports.set(viewport.id, {
rect: vpRect(viewport),
center: { x: (b.minX + b.maxX) / 2, y: (b.minY + b.maxY) / 2 },
scale: scaleN,
});
place();
})
.catch(() => {
if (!disposed) el.replaceChildren();
@@ -135,19 +167,32 @@ export function ViewportPlanSvg({
}, [project, viewport.snapshotId, viewport.widthMm, viewport.heightMm, viewport.scaleDenominator, viewport.center?.x, viewport.center?.y, viewport.designOptions, viewport.designOptionCombination]);
// Lage/Grösse über die Attribute des inneren SVG (folgt auch dem Ghost beim Ziehen).
useEffect(() => {
if (ref.current) placeInner(ref.current, rect);
place();
});
return <g ref={ref} pointerEvents="none" />;
}
/** Lage/Grösse des inneren Viewport-SVG in Blatt-mm setzen. */
function placeInner(el: SVGGElement, rect: RectMm): void {
/** [333] Bildmitte, wenn der Inhalt um `pan` (Papier-mm, y nach unten) im Rahmen verschoben wird: die Mitte wandert gegenläufig. */
function pannedCenter(c: { x: number; y: number }, pan: { x: number; y: number }, scale: number): { x: number; y: number } {
const m = scale / 1000;
return { x: c.x - pan.x * m, y: c.y + pan.y * m };
}
/**
* [333] Je Viewport das zuletzt erzeugte Bild: Rahmen, Bildmitte (Modell-Meter, auch ohne eigene `center` — dann die
* Mitte des Planausmasses) und Massstab. Für die `viewBox` beim Ziehen und für die mitwandernde Bildmitte beim Loslassen.
*/
const renderedViewports = new Map<string, { rect: RectMm; center: { x: number; y: number }; scale: number }>();
/** Lage/Grösse des inneren Viewport-SVG in Blatt-mm setzen; `viewBox` beschneidet/erweitert statt zu strecken ([333]). */
function placeInner(el: SVGGElement, rect: RectMm, viewBox?: [number, number, number, number]): void {
const svg = el.firstElementChild;
if (!svg) return;
svg.setAttribute("x", String(rect.xMm));
svg.setAttribute("y", String(rect.yMm));
svg.setAttribute("width", String(rect.widthMm));
svg.setAttribute("height", String(rect.heightMm));
if (viewBox && viewBox.every(Number.isFinite)) svg.setAttribute("viewBox", viewBox.join(" "));
svg.setAttribute("preserveAspectRatio", "none");
}
@@ -243,6 +288,14 @@ function clip(s: string, max: number): string {
export interface LayoutSheetHandlers {
/** Zurück zur Modell-Ansicht (Grundriss/3D). */
onBack: () => void;
/** [333] Anderes Blatt der Mappe öffnen (Blätter-Leiste). */
onOpenLayout?: (layoutId: string) => void;
/** [333] Blatt per Ziehen umsortieren: an die Einfüge-Stelle `slot` (0…n, gezählt in der alten Liste). */
onMoveLayout?: (layoutId: string, slot: number) => void;
/** [333] Blatt duplizieren. */
onDuplicateLayout?: (layoutId: string) => void;
/** [333] Blatt löschen (die Rückfrage stellt die Leiste). */
onDeleteLayout?: (layoutId: string) => void;
/** Freier Text ([208]): startet die Textspalte (Rahmen aufziehen, Text tippen) auf der Blatt-Ebene. */
onAddText?: () => void;
/** Ändert Position/Grösse/Massstab eines Viewports (mm). */
@@ -514,6 +567,56 @@ export function LayoutSheetPane({
window.addEventListener("pointercancel", up);
};
// [333] Blätter-Leiste (Vorschau aller Blätter), Zustand je Rechner gemerkt.
const [stripOpen, setStripOpen] = useState<boolean>(() => {
try {
return localStorage.getItem("dossier.sheetStrip") !== "0";
} catch {
return true;
}
});
const toggleStrip = () =>
setStripOpen((v) => {
try {
localStorage.setItem("dossier.sheetStrip", v ? "0" : "1");
} catch {
/* nur Komfort */
}
return !v;
});
// [333] Inhalts-Griff (wie InDesign): Inhalt im Rahmen verschieben, der Rahmen bleibt. Beim Loslassen wandert die Bildmitte.
const [contentPan, setContentPan] = useState<{ id: string; x: number; y: number } | null>(null);
const startContentPan = (e: ReactPointerEvent<SVGElement>, vp: LayoutViewport) => {
if (e.button !== 0) return;
e.stopPropagation();
e.preventDefault();
const grab = toMm(e.clientX, e.clientY);
if (!grab) return;
let last = { x: 0, y: 0 };
const move = (ev: PointerEvent) => {
const mm = toMm(ev.clientX, ev.clientY);
if (!mm) return;
last = { x: mm.xMm - grab.xMm, y: mm.yMm - grab.yMm };
setContentPan({ id: vp.id, ...last });
};
const up = () => {
window.removeEventListener("pointermove", move);
window.removeEventListener("pointerup", up);
window.removeEventListener("pointercancel", up);
setContentPan(null);
const shown = renderedViewports.get(vp.id);
const cur = layout.viewports.find((v) => v.id === vp.id) ?? vp;
const own = cur.center && Number.isFinite(cur.center.x) && Number.isFinite(cur.center.y) ? cur.center : shown?.center;
if (!own || !shown || (Math.abs(last.x) < 0.05 && Math.abs(last.y) < 0.05)) return;
const c = pannedCenter(own, last, shown.scale);
handlers.onPatchViewport(vp.id, { center: { x: Math.round(c.x * 1000) / 1000, y: Math.round(c.y * 1000) / 1000 } });
};
window.addEventListener("pointermove", move);
window.addEventListener("pointerup", up);
window.addEventListener("pointercancel", up);
};
const startDrag = (e: ReactPointerEvent<SVGElement>, drag: Drag) => {
if (e.button !== 0) return; // Mitte = Schwenken der Plan-Ansicht
e.stopPropagation();
@@ -554,12 +657,19 @@ export function LayoutSheetPane({
const s = drag.start;
if (last.xMm === s.xMm && last.yMm === s.yMm && last.widthMm === s.widthMm && last.heightMm === s.heightMm) return;
const r = clampRectToSheet(last, sheet.w, sheet.h);
handlers.onPatchViewport(drag.id, {
const next = {
xMm: round1(r.xMm),
yMm: round1(r.yMm),
widthMm: round1(Math.max(MIN_VP_MM, r.widthMm)),
heightMm: round1(Math.max(MIN_VP_MM, r.heightMm)),
});
};
// [333] Grösse ändern wie InDesign: der Inhalt bleibt auf dem Papier liegen, die Bildmitte wandert mit (ohne eigene
// Mitte ab der des gezeigten Bildes). Verschieben nimmt den Inhalt mit (Mitte bleibt).
const vp = layout.viewports.find((v) => v.id === drag.id);
const shown = renderedViewports.get(drag.id);
const own = vp?.center && Number.isFinite(vp.center.x) && Number.isFinite(vp.center.y) ? vp.center : shown?.center;
const center = drag.handle !== "body" && own && shown ? resizedCenter(own, s, next, shown.scale) : undefined;
handlers.onPatchViewport(drag.id, center ? { ...next, center } : next);
};
window.addEventListener("pointermove", move);
window.addEventListener("pointerup", up);
@@ -751,7 +861,13 @@ export function LayoutSheetPane({
return (
<g key={vp.id} data-viewport-id={vp.id}>
{snap ? (
<ViewportPlanSvg project={project} viewport={vp} rect={r} />
<ViewportPlanSvg
project={project}
viewport={vp}
rect={r}
contentFixed={!!preview && preview.drag.mode === "edit" && preview.drag.id === vp.id && preview.drag.handle !== "body"}
panMm={contentPan && contentPan.id === vp.id ? contentPan : null}
/>
) : (
<g pointerEvents="none">
<rect x={r.xMm} y={r.yMm} width={r.widthMm} height={r.heightMm} fill="#fff6f6" />
@@ -904,6 +1020,19 @@ export function LayoutSheetPane({
}}
/>
))}
{(() => {
// [333] Inhalts-Griff in der Rahmenmitte (Ring wie InDesign): zieht den Plan im Rahmen, der Rahmen bleibt.
const r = displayRect(selectedVp);
const cx = r.xMm + r.widthMm / 2;
const cy = r.yMm + r.heightMm / 2;
return (
<g style={{ cursor: "grab" }} data-viewport-content-grip onPointerDown={(e) => startContentPan(e, selectedVp)}>
<title>{t("layouts.moveContent")}</title>
<circle cx={cx} cy={cy} r={grip * 1.3} fill="rgba(255,255,255,0.85)" stroke={ACCENT} strokeWidth={hair * 1.5} />
<circle cx={cx} cy={cy} r={grip * 0.45} fill={ACCENT} />
</g>
);
})()}
</g>
)}
{/* Gewähltes Bild: Körper verschieben, Ecke unten rechts skalieren; im Zuschnitt-Modus Griffe am Ausschnitt. */}
@@ -1078,62 +1207,90 @@ export function LayoutSheetPane({
return (
<section className="pane layout-sheet-pane">
<div className="layout-sheet-toolbar" data-sheet-ui>
{/* [333] Eine Zeile, gruppiert: Zurück · Blattname | Einfügen | Hilfslinien · Einpassen. Unter ~820 px nur Symbole
(Container-Abfrage in styles.css), die Namen stehen dann im Tooltip. */}
<button className="nav-add" onClick={handlers.onBack} title={t("layouts.backToModel")}>
<span className="material-symbols-outlined" aria-hidden="true">chevron_left</span>
{t("layouts.backToModel")}
</button>
<span className="layout-sheet-name">{layout.name}</span>
<button
className={`nav-add${placing ? " active" : ""}`}
onClick={() => {
setPlacing((v) => !v);
setPendingRect(null);
setSelectedId(null);
}}
disabled={snapshots.length === 0 || toolInputActive}
title={snapshots.length === 0 ? t("layouts.noSnapshots") : t("layouts.placeViewport")}
>
+ {t("layouts.placeViewport")}
</button>
<button
className="nav-add"
data-add-legend
disabled={toolInputActive}
title={t("legend.add")}
onClick={() => {
const id = handlers.onAddLegend({ xMm: 10, yMm: 10 });
setSelectedId(null);
setSelectedLegendId(id);
}}
>
+ {t("legend.add")}
</button>
<select
className="res-select"
value=""
disabled={toolInputActive}
title={t("sheetTable.add")}
data-table-add
onChange={(e) => {
const source = e.target.value as LayoutTableSource;
if (!source) return;
const tb = createTable(`tb-${Date.now()}`, source, sheet.w, sheet.h, layoutTables);
handlers.onAddTable(tb);
setSelectedTableId(tb.id);
setSelectedId(null);
}}
>
<option value="">+ {t("sheetTable.add")}</option>
{TABLE_SOURCES.map((src) => (
<option key={src} value={src}>{tableSourceLabel(src)}</option>
))}
</select>
<button className="nav-add" data-add-image disabled={toolInputActive} title={t("sheetImage.add")} onClick={() => fileRef.current?.click()}>
+ {t("sheetImage.add")}
</button>
<button className="nav-add" data-add-text disabled={toolInputActive || !handlers.onAddText} title={t("sheetText.add.hint")} onClick={() => handlers.onAddText?.()}>
+ {t("sheetText.add")}
<span className="tb-label">{t("layouts.backToModel")}</span>
</button>
{handlers.onOpenLayout && (
<button
className={`nav-add${stripOpen ? " active" : ""}`}
onClick={toggleStrip}
title={t("layouts.strip")}
aria-label={t("layouts.strip")}
aria-pressed={stripOpen}
data-sheet-strip-toggle
>
<span className="material-symbols-outlined" aria-hidden="true">view_sidebar</span>
</button>
)}
<span className="layout-sheet-name" title={layout.name}>{layout.name}</span>
<span className="layout-sheet-sep" aria-hidden="true" />
<span className="layout-sheet-group" role="group" aria-label={t("layouts.insert")}>
<span className="layout-sheet-group-label tb-label">{t("layouts.insert")}</span>
<button
className={`nav-add${placing ? " active" : ""}`}
onClick={() => {
setPlacing((v) => !v);
setPendingRect(null);
setSelectedId(null);
}}
disabled={snapshots.length === 0 || toolInputActive}
title={snapshots.length === 0 ? t("layouts.noSnapshots") : t("layouts.placeViewport")}
aria-label={t("layouts.placeViewport")}
>
<span className="material-symbols-outlined" aria-hidden="true">crop_free</span>
<span className="tb-label">{t("layouts.viewportShort")}</span>
</button>
<button
className="nav-add"
data-add-legend
disabled={toolInputActive}
title={t("legend.add")}
aria-label={t("legend.add")}
onClick={() => {
const id = handlers.onAddLegend({ xMm: 10, yMm: 10 });
setSelectedId(null);
setSelectedLegendId(id);
}}
>
<span className="material-symbols-outlined" aria-hidden="true">format_list_bulleted</span>
<span className="tb-label">{t("layouts.legendShort")}</span>
</button>
<label className={`nav-add layout-sheet-select${toolInputActive ? " disabled" : ""}`} title={t("sheetTable.add")}>
<span className="material-symbols-outlined" aria-hidden="true">table</span>
<span className="tb-label">{t("layouts.tableShort")}</span>
<span className="material-symbols-outlined layout-sheet-caret" aria-hidden="true">expand_more</span>
<select
value=""
disabled={toolInputActive}
aria-label={t("sheetTable.add")}
data-table-add
onChange={(e) => {
const source = e.target.value as LayoutTableSource;
if (!source) return;
const tb = createTable(`tb-${Date.now()}`, source, sheet.w, sheet.h, layoutTables);
handlers.onAddTable(tb);
setSelectedTableId(tb.id);
setSelectedId(null);
}}
>
<option value="">+ {t("sheetTable.add")}</option>
{TABLE_SOURCES.map((src) => (
<option key={src} value={src}>{tableSourceLabel(src)}</option>
))}
</select>
</label>
<button className="nav-add" data-add-image disabled={toolInputActive} title={t("sheetImage.add")} aria-label={t("sheetImage.add")} onClick={() => fileRef.current?.click()}>
<span className="material-symbols-outlined" aria-hidden="true">image</span>
<span className="tb-label">{t("layouts.imageShort")}</span>
</button>
<button className="nav-add" data-add-text disabled={toolInputActive || !handlers.onAddText} title={t("sheetText.add.hint")} aria-label={t("sheetText.add")} onClick={() => handlers.onAddText?.()}>
<span className="material-symbols-outlined" aria-hidden="true">title</span>
<span className="tb-label">{t("layouts.textShort")}</span>
</button>
</span>
<input
ref={fileRef}
type="file"
@@ -1146,22 +1303,28 @@ export function LayoutSheetPane({
if (f) void addImageFile(f);
}}
/>
<span className="layout-sheet-sep" aria-hidden="true" />
<button
ref={guidesToggleRef}
className={`nav-add${guidesOpen ? " active" : ""}`}
data-guides-toggle
disabled={!canGuides}
title={canGuides ? t("sheetGuides.title") : t("sheetGuides.needMaster")}
aria-label={t("sheetGuides.title")}
onClick={() => setGuidesOpen((v) => !v)}
>
{t("sheetGuides.title")}
<span className="material-symbols-outlined" aria-hidden="true">grid_guides</span>
<span className="tb-label">{t("sheetGuides.title")}</span>
</button>
<span style={{ flex: 1 }} />
<button className="nav-add" onClick={() => planViewRef.current?.fit()} title={t("layouts.fit")}>
{t("layouts.fit")}
<button className="nav-add" onClick={() => planViewRef.current?.fit()} title={t("layouts.fit")} aria-label={t("layouts.fit")}>
<span className="material-symbols-outlined" aria-hidden="true">fit_screen</span>
<span className="tb-label">{t("layouts.fit")}</span>
</button>
</div>
<div className={`layout-sheet-body${stripOpen && handlers.onOpenLayout ? " with-strip" : ""}`}>
{stripOpen && handlers.onOpenLayout && <SheetStrip project={project} activeId={layout.id} onOpen={handlers.onOpenLayout} onMove={handlers.onMoveLayout} onDuplicate={handlers.onDuplicateLayout} onDelete={handlers.onDeleteLayout} />}
<div className="layout-sheet-stage">
{children({ backdrop, fitBounds, onPlanSelect: onSheetSelect })}
@@ -1398,6 +1561,7 @@ export function LayoutSheetPane({
</div>
)}
</div>
</div>
</section>
);
}
+171
View File
@@ -0,0 +1,171 @@
// [333] Blätter-Leiste im Layout (wie die Seitenpalette in InDesign): alle Blätter der Mappe als kleine Vorschau — Papier im
// richtigen Seitenverhältnis, darauf die Rahmen der Ansichten und Tabellen —, Name und Plannummer darunter. Klick öffnet
// das Blatt, Ziehen ordnet um (Zeigerereignisse statt HTML5-Drag&Drop: läuft auch im WKWebView), Rechtsklick/„…“ bietet
// Duplizieren und Löschen (mit Rückfrage). Die Vorschau ist schematisch (keine Plan-Erzeugung je Blatt: bleibt bei 30
// Blättern sofort).
import { useRef, useState } from "react";
import type { Project } from "../model/types";
import { effectiveSheetSizeMm, findMaster } from "../model/layoutModel";
import { t } from "../i18n";
import { ContextMenu } from "./ContextMenu";
import { ConfirmDialog } from "./ConfirmDialog";
const THUMB_W = 96;
/** Ab so vielen Pixeln Bewegung gilt ein Klick als Ziehen. */
const DRAG_THRESHOLD = 5;
interface Props {
project: Project;
activeId: string;
onOpen: (id: string) => void;
onMove?: (id: string, slot: number) => void;
onDuplicate?: (id: string) => void;
onDelete?: (id: string) => void;
}
export function SheetStrip({ project, activeId, onOpen, onMove, onDuplicate, onDelete }: Props) {
const layouts = project.layouts ?? [];
const navRef = useRef<HTMLElement>(null);
const press = useRef<{ id: string; x: number; y: number; dragging: boolean } | null>(null);
const suppressClick = useRef(false);
const [drag, setDrag] = useState<{ id: string; slot: number } | null>(null);
const [menu, setMenu] = useState<{ id: string; x: number; y: number } | null>(null);
const [deleting, setDeleting] = useState<string | null>(null);
// Einfüge-Stelle (0…n) aus der Zeigerhöhe: vor dem ersten Blatt, dessen Mitte unter dem Zeiger liegt.
const slotAt = (clientY: number): number => {
const items = Array.from(navRef.current?.querySelectorAll<HTMLElement>(".sheet-strip-item") ?? []);
for (let i = 0; i < items.length; i++) {
const r = items[i].getBoundingClientRect();
if (clientY < r.top + r.height / 2) return i;
}
return items.length;
};
const canMove = !!onMove && layouts.length > 1;
const canMenu = !!onDuplicate || !!onDelete;
const deletingLayout = layouts.find((l) => l.id === deleting);
return (
<nav className="sheet-strip" aria-label={t("layouts.strip")} data-sheet-strip ref={navRef}>
{layouts.map((l, i) => {
const size = effectiveSheetSizeMm(findMaster(project, l) ?? l);
const h = (THUMB_W * size.h) / Math.max(size.w, 1);
const label = l.planNumber || String(i + 1);
const dropBefore = drag?.slot === i && drag.id !== l.id;
const dropAfter = drag?.slot === layouts.length && i === layouts.length - 1;
const open = () => l.id !== activeId && onOpen(l.id);
return (
<div
key={l.id}
role="button"
tabIndex={0}
data-sheet-id={l.id}
className={`sheet-strip-item${l.id === activeId ? " active" : ""}${drag?.id === l.id ? " dragging" : ""}${dropBefore ? " drop-before" : ""}${dropAfter ? " drop-after" : ""}`}
title={l.name}
aria-current={l.id === activeId ? "page" : undefined}
onClick={() => {
if (suppressClick.current) {
suppressClick.current = false;
return;
}
open();
}}
onKeyDown={(e) => {
if (e.target === e.currentTarget && (e.key === "Enter" || e.key === " ")) {
e.preventDefault();
open();
}
}}
onContextMenu={(e) => {
if (!canMenu) return;
e.preventDefault();
setMenu({ id: l.id, x: e.clientX, y: e.clientY });
}}
onPointerDown={(e) => {
if (!canMove || e.button !== 0 || (e.target as HTMLElement).closest(".sheet-strip-more")) return;
press.current = { id: l.id, x: e.clientX, y: e.clientY, dragging: false };
e.currentTarget.setPointerCapture?.(e.pointerId);
}}
onPointerMove={(e) => {
const pr = press.current;
if (!pr || pr.id !== l.id) return;
if (!pr.dragging && Math.hypot(e.clientX - pr.x, e.clientY - pr.y) < DRAG_THRESHOLD) return;
pr.dragging = true;
setDrag({ id: l.id, slot: slotAt(e.clientY) });
}}
onPointerUp={(e) => {
const pr = press.current;
press.current = null;
e.currentTarget.releasePointerCapture?.(e.pointerId);
if (!pr || pr.id !== l.id || !pr.dragging) return;
// Das Click-Ereignis nach dem Loslassen nicht als „Blatt öffnen“ werten.
suppressClick.current = true;
setTimeout(() => (suppressClick.current = false), 0);
const slot = slotAt(e.clientY);
setDrag(null);
onMove?.(l.id, slot);
}}
onPointerCancel={() => {
press.current = null;
setDrag(null);
}}
>
<svg width={THUMB_W} height={h} viewBox={`0 0 ${size.w} ${size.h}`} aria-hidden="true">
<rect x={0} y={0} width={size.w} height={size.h} fill="#ffffff" />
{l.viewports.map((v) => (
<rect key={v.id} x={v.xMm} y={v.yMm} width={v.widthMm} height={v.heightMm} className="sheet-strip-vp" />
))}
{(l.tables ?? []).map((tb) => (
<rect key={tb.id} x={tb.xMm} y={tb.yMm} width={tb.widthMm} height={tb.heightMm ?? 20} className="sheet-strip-tb" />
))}
</svg>
<span className="sheet-strip-label">
<span className="sheet-strip-no">{label}</span>
<span className="sheet-strip-name">{l.name}</span>
</span>
{canMenu && (
<button
type="button"
className="sheet-strip-more"
aria-label={t("layouts.stripMore")}
title={t("layouts.stripMore")}
onClick={(e) => {
e.stopPropagation();
const r = e.currentTarget.getBoundingClientRect();
setMenu({ id: l.id, x: r.left, y: r.bottom });
}}
>
…
</button>
)}
</div>
);
})}
{menu && (
<ContextMenu
x={menu.x}
y={menu.y}
onClose={() => setMenu(null)}
items={[
...(onDuplicate ? [{ label: t("layouts.duplicate"), onClick: () => onDuplicate(menu.id) }] : []),
...(onDelete ? [{ label: t("layouts.delete"), danger: true, onClick: () => setDeleting(menu.id) }] : []),
]}
/>
)}
{deletingLayout && onDelete && (
<ConfirmDialog
title={t("layouts.delete")}
message={t("layouts.deleteSheetMessage", { name: deletingLayout.name })}
confirmLabel={t("layouts.delete")}
danger
onClose={() => setDeleting(null)}
onConfirm={() => {
setDeleting(null);
onDelete(deletingLayout.id);
}}
/>
)}
</nav>
);
}
+24
View File
@@ -1,6 +1,8 @@
import { describe, expect, it } from "vitest";
import type { LayoutViewport } from "../model/types";
import {
resizedCenter,
viewportViewBox,
applyHandleDrag,
clampRectToSheet,
handleAt,
@@ -131,3 +133,25 @@ describe("vpRect", () => {
});
});
});
describe("[333] Inhalt bleibt beim Vergrössern liegen (resizedCenter, viewportViewBox)", () => {
const start = { xMm: 10, yMm: 20, widthMm: 100, heightMm: 60 };
it("Unterkante 40 mm nach unten: Mitte 20 mm tiefer, bei 1:100 also 2 m Richtung −y", () => {
const next = { ...start, heightMm: 100 };
expect(resizedCenter({ x: 5, y: 7 }, start, next, 100)).toEqual({ x: 5, y: 5 });
});
it("linke Kante nach links: Mitte nach links", () => {
const c = resizedCenter({ x: 0, y: 0 }, start, { ...start, xMm: 0, widthMm: 110 }, 50);
expect(c.x).toBeCloseTo(-0.25);
expect(c.y).toBeCloseTo(0);
});
it("viewBox: gleicher Rahmen = 0 0 w h; Vergrössern mit mitwandernder Mitte = Inhalt fest; Verschieben = Inhalt wandert mit", () => {
const c0 = { x: 3, y: 4 };
expect(viewportViewBox(start, c0, start, c0, 100)).toEqual([0, 0, 100, 60]);
const bigger = { ...start, yMm: 10, heightMm: 100 };
const vb = viewportViewBox(bigger, resizedCenter(c0, start, bigger, 100), start, c0, 100);
vb.forEach((v, i) => expect(v).toBeCloseTo([0, -10, 100, 100][i]));
const moved = { ...start, xMm: 50 };
viewportViewBox(moved, c0, start, c0, 100).forEach((v, i) => expect(v).toBeCloseTo([0, 0, 100, 60][i]));
});
});
+30
View File
@@ -247,3 +247,33 @@ export function handleAnchors(r: RectMm): { handle: Handle; xMm: number; yMm: nu
{ handle: "w", xMm: x, yMm: cy },
];
}
/**
* [333] Bildmitte (Modell-Meter) nach dem Ändern der Rahmengrösse, sodass der Inhalt auf dem Papier liegen bleibt (wie
* InDesign: Rahmen nach unten ziehen zeigt mehr von unterhalb). Die Rahmenmitte wandert auf dem Papier um (Δx, Δy) mm;
* die Bildmitte um dasselbe im Modell (1:`scale`, Papier-y nach unten = Modell-y nach oben).
*/
export function resizedCenter(center: { x: number; y: number }, start: RectMm, next: RectMm, scale: number): { x: number; y: number } {
const m = scale / 1000;
const dx = next.xMm + next.widthMm / 2 - (start.xMm + start.widthMm / 2);
const dy = next.yMm + next.heightMm / 2 - (start.yMm + start.heightMm / 2);
return { x: center.x + dx * m, y: center.y - dy * m };
}
/**
* [333] `viewBox` des inneren Viewport-SVG, damit ein für den Rahmen `rendered` (Bildmitte `renderedCenter`) erzeugtes
* Bild im Rahmen `rect` mit Bildmitte `center` richtig liegt — beschnitten bzw. erweitert, nie gestreckt (Vorschau beim
* Ziehen, und bis das neue Bild nach dem Loslassen da ist). Gleiche Mitte, gleiche Lage: `0 0 w h`.
*/
export function viewportViewBox(
rect: RectMm,
center: { x: number; y: number },
rendered: RectMm,
renderedCenter: { x: number; y: number },
scale: number,
): [number, number, number, number] {
const k = 1000 / scale;
const shiftX = rect.xMm + rect.widthMm / 2 - (rendered.xMm + rendered.widthMm / 2) - (center.x - renderedCenter.x) * k;
const shiftY = rect.yMm + rect.heightMm / 2 - (rendered.yMm + rendered.heightMm / 2) + (center.y - renderedCenter.y) * k;
return [rect.xMm - rendered.xMm - shiftX, rect.yMm - rendered.yMm - shiftY, rect.widthMm, rect.heightMm];
}
+57 -7
View File
@@ -43,7 +43,7 @@
// Pixel an der Viewport-Höhe normiert), damit sich beide Pfade gleich anfühlen.
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import type { Project, Wall, Drawing2D, Ceiling, Roof, Vec2 } from "../model/types";
import type { Project, Wall, Drawing2D, Ceiling, Roof, Vec2, Stair, Opening, Column } from "../model/types";
import { roofBaseElevation, roofGeometry, verticalExtents } from "../core";
import { projectToModel3d, pickGeometry, draftWorldLines, explodeFloorOffsets, hiddenClassCodes, filter3d } from "../core";
import type { Hide3d } from "../core";
@@ -66,6 +66,7 @@ import { useWasm3dRenderer } from "./useWasm3dRenderer";
import { cameraRay, pickNearest, rayPlaneY, rayPlane, worldToScreen } from "./raycast3d";
import type { Vec3 } from "../core";
import { drawingGripVertices, drawingMoveAnchor } from "./drawingGrips";
import { elemExplodeDz, elementGrips3d, type ElemGripTarget } from "./elementGrips3d";
import { pointCloudSyncItems } from "./pointCloudSync";
import { usePointClouds } from "../state/pointCloudStore";
import { sun3dFor, sun3dKey } from "./sun3d";
@@ -133,7 +134,9 @@ type GripKind = "vertex" | "height" | "move" | "edge" | "roofpitch";
interface Grip {
kind: GripKind;
/** Element, dessen Griff das ist (Wand-/Drawing-/Decken-/Dach-ID). */
target: { wallId?: string; drawingId?: string; ceilingId?: string; roofId?: string };
target: { wallId?: string; drawingId?: string; ceilingId?: string; roofId?: string } & ElemGripTarget;
/** [333] Arbeitsebene (Welt-y) bei Treppen-/Öffnungs-/Stützen-Griffen; sonst aus dem Ziel abgeleitet. */
planeY?: number;
/** Vertex-Index (`vertex`) bzw. erster Kanten-Index (`edge`); -1 sonst. */
index: number;
/** Zweiter Kanten-Index (nur `kind==="edge"`). */
@@ -151,6 +154,7 @@ function sameGripScreens(a: readonly { grip: Grip; x: number; y: number }[], b:
const u = q.grip.target;
if (p.x !== q.x || p.y !== q.y || p.grip.kind !== q.grip.kind || p.grip.index !== q.grip.index || p.grip.index2 !== q.grip.index2) return false;
if (t.wallId !== u.wallId || t.drawingId !== u.drawingId || t.ceilingId !== u.ceilingId || t.roofId !== u.roofId) return false;
if (t.stairId !== u.stairId || t.openingId !== u.openingId || t.columnId !== u.columnId) return false;
const [x, y, z] = p.grip.pos;
if (x !== q.grip.pos[0] || y !== q.grip.pos[1] || z !== q.grip.pos[2]) return false;
}
@@ -211,12 +215,19 @@ function computeGrips(
drawingElevation: number,
/** Explosionsaxonometrie ([65]): Versatz je Geschoss-id; Griffe sitzen auf den gehobenen Bauteilen. */
floorOffsets: Readonly<Record<string, number>> = {},
/** [333] Gewählte Treppen/Öffnungen/Stützen. */
elems: { stairs: readonly Stair[]; openings: readonly Opening[]; columns: readonly Column[] } = { stairs: [], openings: [], columns: [] },
): Grip[] {
const out = computeGripsAt(project, walls, drawings, ceilings, roofs, drawingElevation);
for (const g of out) {
const dz = explodeGripDz(project, floorOffsets, g.target);
if (dz !== 0) g.pos = [g.pos[0], g.pos[1] + dz, g.pos[2]];
}
// [333] Treppe/Öffnung/Stütze: Lage und Ebene mit Explosionsversatz (Ebene = Höhe, auf der gezogen wird).
for (const e of elementGrips3d(project, elems.stairs, elems.openings, elems.columns)) {
const dz = elemExplodeDz(project, floorOffsets, e.target);
out.push({ kind: e.kind, target: e.target, index: e.index, pos: [e.pos[0], e.pos[1] + dz, e.pos[2]], planeY: e.planeY + dz });
}
return out;
}
@@ -408,6 +419,10 @@ export function Wasm3DViewport({
editDrawings = [],
editCeilings = [],
editRoofs = [],
editStairs = [],
editOpenings = [],
editColumns = [],
onEditElement,
onEditVertex,
onEditBody,
onEditEdge,
@@ -470,6 +485,12 @@ export function Wasm3DViewport({
editCeilings?: Ceiling[];
/** Gewählte Dächer — Quelle der 3D-Eckpunkt-/Verschiebe-/First-Griffe. */
editRoofs?: Roof[];
/** [333] Gewählte Treppen/Wandöffnungen/Stützen — Quelle ihrer 3D-Griffe. */
editStairs?: Stair[];
editOpenings?: Opening[];
editColumns?: Column[];
/** [333] Griff von Treppe/Öffnung/Stütze gezogen: Griff-Index und Punkt (Modell-m) auf der Griff-Ebene. */
onEditElement?: (target: ElemGripTarget, index: number, pt: Vec2) => void;
/**
* Endpunkt-Griff gezogen: neuer XY-Modellpunkt für den Vertex `index` des
* Elements. Optionale `excludeWallIds`/`excludeDrawingIds` = Koinzidenz-
@@ -576,6 +597,14 @@ export function Wasm3DViewport({
editCeilingsRef.current = editCeilings;
const editRoofsRef = useRef(editRoofs);
editRoofsRef.current = editRoofs;
const editStairsRef = useRef(editStairs);
editStairsRef.current = editStairs;
const editOpeningsRef = useRef(editOpenings);
editOpeningsRef.current = editOpenings;
const editColumnsRef = useRef(editColumns);
editColumnsRef.current = editColumns;
const onEditElementRef = useRef(onEditElement);
onEditElementRef.current = onEditElement;
const onEditVertexRef = useRef(onEditVertex);
onEditVertexRef.current = onEditVertex;
const onEditBodyRef = useRef(onEditBody);
@@ -1003,7 +1032,10 @@ export function Wasm3DViewport({
(editWalls.length === 0 &&
editDrawings.length === 0 &&
editCeilings.length === 0 &&
editRoofs.length === 0)
editRoofs.length === 0 &&
editStairs.length === 0 &&
editOpenings.length === 0 &&
editColumns.length === 0)
) {
setGripScreens([]);
return;
@@ -1024,6 +1056,7 @@ export function Wasm3DViewport({
editRoofsRef.current,
groundElevationRef.current,
floorOffsetsRef.current,
{ stairs: editStairsRef.current, openings: editOpeningsRef.current, columns: editColumnsRef.current },
);
const next: { grip: Grip; x: number; y: number }[] = [];
for (const g of grips) {
@@ -1038,7 +1071,7 @@ export function Wasm3DViewport({
};
raf = requestAnimationFrame(tick);
return () => cancelAnimationFrame(raf);
}, [ready, editWalls, editDrawings, editCeilings, editRoofs]);
}, [ready, editWalls, editDrawings, editCeilings, editRoofs, editStairs, editOpenings, editColumns]);
// Cursor-HUD-Bildschirmposition (Länge/Winkel beim Zeichnen ODER Δx/Δy/
// Länge-Winkel während eines Griff-Drags, s. `hudFields`-Doc): derselbe
@@ -1160,6 +1193,7 @@ export function Wasm3DViewport({
moveCoincident: MoveCoincidentVertex[];
}
| { kind: "edge"; ceilingId: string; a: number; b: number; planeY: number; lastModel: Vec2 | null }
| { kind: "elem"; target: ElemGripTarget; index: number; planeY: number }
| { kind: "height"; wallId: string }
| { kind: "roofpitch"; roofId: string; apexXZ: readonly [number, number] };
const gripDragRef = useRef<GripDrag | null>(null);
@@ -1204,7 +1238,11 @@ export function Wasm3DViewport({
endGripDrag();
return;
}
if (grip.kind === "height") {
if (grip.target.stairId || grip.target.openingId || grip.target.columnId) {
// [333] Treppe/Öffnung/Stütze: Strahl auf die waagrechte Griff-Ebene, der Kern rechnet den Zug (wie im Plan).
if (grip.planeY == null) return;
gripDragRef.current = { kind: "elem", target: grip.target, index: grip.index, planeY: grip.planeY };
} else if (grip.kind === "height") {
if (!grip.target.wallId) return;
gripDragRef.current = { kind: "height", wallId: grip.target.wallId };
} else if (grip.kind === "roofpitch") {
@@ -1321,6 +1359,12 @@ export function Wasm3DViewport({
const hit = rayPlaneY(ray, drag.planeY);
if (!hit) return;
const model: Vec2 = { x: hit[0], y: hit[2] };
if (drag.kind === "elem") {
const et = drag.target;
// Ein Undo-Schritt je Zug: gleicher Schlüssel (Aktionen coalescen zusätzlich über ihren eigenen).
editGroup(`grip3dElem:${et.stairId ?? et.openingId ?? et.columnId}:${drag.index}`, () => onEditElementRef.current?.(et, drag.index, model));
return;
}
if (drag.kind === "vertex") {
// Pfeiltasten-Achsen-Lock (s. Datei-Kommentar an `axisLockRef`) hat
// Vorrang vor Shift — ein bewusst per Taste gewählter Anker/Achse soll
@@ -2139,10 +2183,16 @@ export function Wasm3DViewport({
const glyphStrokeWidth = grip.kind === "edge" ? 1.5 : 1.75;
return (
<div
key={`${grip.kind}:${grip.target.wallId ?? grip.target.drawingId ?? grip.target.ceilingId ?? grip.target.roofId}:${grip.index}`}
key={`${grip.kind}:${grip.target.wallId ?? grip.target.drawingId ?? grip.target.ceilingId ?? grip.target.roofId ?? grip.target.stairId ?? grip.target.openingId ?? grip.target.columnId}:${grip.index}`}
onPointerDown={startGripDrag(grip)}
title={t(
grip.kind === "height"
grip.target.openingId
? "viewport3d.grip.slide"
: grip.target.stairId && grip.kind === "vertex"
? "viewport3d.grip.stairParam"
: grip.target.columnId && grip.kind === "vertex"
? "viewport3d.grip.columnSize"
: grip.kind === "height"
? "viewport3d.grip.height"
: grip.kind === "roofpitch"
? "viewport3d.grip.roofpitch"
+45
View File
@@ -0,0 +1,45 @@
import { describe, expect, it } from "vitest";
import { buildComplexSampleProject } from "../model/sampleProjectComplex";
import { columnTopZ, openingSillZ, elemExplodeDz, elementGrips3d } from "./elementGrips3d";
const p = buildComplexSampleProject();
describe("elementGrips3d", () => {
it("Stütze: Mitte als Verschiebe-Griff, dazu Ecken (Index wie columnGrip)", () => {
const c = p.columns!.find((x) => x.id === "st-carport-1")!;
const gs = elementGrips3d(p, [], [], [c]);
expect(gs.length).toBe(6);
expect(gs[0]).toMatchObject({ kind: "move", index: 0, target: { columnId: c.id } });
expect(gs[0].pos[0]).toBeCloseTo(c.position.x);
expect(gs[0].pos[2]).toBeCloseTo(c.position.y);
expect(gs[0].pos[1]).toBeGreaterThan(columnTopZ(p, c));
expect(gs.slice(1).every((g) => g.kind === "vertex")).toBe(true);
});
it("gesperrte Stütze hat keine Griffe", () => {
const c = { ...p.columns![0], locked: true };
expect(elementGrips3d(p, [], [], [c])).toEqual([]);
});
it("Öffnung: ein Gleit-Griff auf Brüstungshöhe", () => {
const win = p.openings!.find((o) => o.sillHeight > 0 && !o.hostRoofId && !o.hostCeilingId)!;
const gs = elementGrips3d(p, [], [win], []);
expect(gs).toHaveLength(1);
expect(gs[0].kind).toBe("move");
const w = p.walls.find((x) => x.id === win.hostWallId)!;
expect(gs[0].planeY).toBeCloseTo(openingSillZ(p, win, w) + 0.05);
});
it("Treppe: Bewegpunkt zuerst, Parameter-Griffe ab Index 1", () => {
const st = p.stairs![0];
const gs = elementGrips3d(p, [st], [], []);
expect(gs[0]).toMatchObject({ kind: "move", index: 0 });
gs.slice(1).forEach((g, i) => expect(g.index).toBe(i + 1));
});
it("Explosion: Versatz des Geschosses", () => {
const c = p.columns!.find((x) => x.id === "st-carport-1")!;
expect(elemExplodeDz(p, { [c.floorId]: 3 }, { columnId: c.id })).toBe(3);
expect(elemExplodeDz(p, {}, { columnId: c.id })).toBe(0);
});
});
+99
View File
@@ -0,0 +1,99 @@
// 3D-Griffe für Treppen, Wandöffnungen und Stützen ([333]): reine Lagen-Berechnung (Welt-Koordinaten
// x, Höhe, y) und Arbeitsebene je Griff. Die Griff-Punkte selbst und die Änderungen rechnet der Kern
// (`stairParamPoints`/`stairMoveHandle`, `columnGripPoints`, `openingGripPoint`; Anfragen `stairBy`,
// `stairParam`, `columnGrip`, `openingSlide`) — hier nur die Höhe, auf der der Griff sitzt.
import type { Column, Opening, Project, Stair, Vec2, Wall } from "../model/types";
import { columnGripPoints, openingGripPoint, stairMoveHandle, stairParamPoints, verticalExtents } from "../core";
import type { Vec3 } from "../core";
/** Ziel eines Element-Griffs (genau eines gesetzt). */
export interface ElemGripTarget {
stairId?: string;
openingId?: string;
columnId?: string;
}
/** Ein Element-Griff: `index` = Griff-Index der Anfrage (Treppe: 0 = Bewegpunkt, n = Parameter n−1). */
export interface ElemGrip {
kind: "move" | "vertex";
target: ElemGripTarget;
index: number;
pos: Vec3;
/** Arbeitsebene (Höhe, Welt-y), auf der der Griff gezogen wird. */
planeY: number;
}
/** Geschoss-OK (m), 0 ohne Angabe. */
function floorBaseZ(project: Project, floorId: string): number {
const z = project.drawingLevels.find((l) => l.id === floorId)?.baseElevation;
return typeof z === "number" && Number.isFinite(z) ? z : 0;
}
/** Höhe einer vertikalen Bindung; ohne Bindung `fallback`. */
function anchorZ(project: Project, a: Column["bottom"], fallback: number): number {
if (!a) return fallback;
return a.mode === "custom" ? a.z : floorBaseZ(project, a.floorId) + (a.offset ?? 0);
}
/** Unterkante (absolutes Z) einer Stütze. */
export function columnBottomZ(project: Project, c: Column): number {
return anchorZ(project, c.bottom, floorBaseZ(project, c.floorId));
}
/** Oberkante (absolutes Z) einer Stütze. */
export function columnTopZ(project: Project, c: Column): number {
return anchorZ(project, c.top, columnBottomZ(project, c) + c.height);
}
/** Brüstungshöhe (absolutes Z) einer Wandöffnung: Wand-UK + `sillHeight`. */
export function openingSillZ(project: Project, op: Opening, wall: Wall): number {
return verticalExtents(project, [wall]).walls[0].zBottom + (op.sillHeight ?? 0);
}
const world = (p: Vec2, y: number): Vec3 => [p.x, y, p.y];
/**
* Griffe der gewählten Treppen, Wandöffnungen und Stützen. Gesperrte Elemente (`locked`) haben keine.
* Treppe: Bewegpunkt + Parameter-Griffe auf der Antrittsebene; Öffnung: ein Gleit-Griff auf Brüstungshöhe;
* Stütze: Mitte (verschieben) knapp über der Oberkante, Ecken/Radius/Dreh-Griff auf der Oberkante.
*/
export function elementGrips3d(project: Project, stairs: readonly Stair[], openings: readonly Opening[], columns: readonly Column[]): ElemGrip[] {
const out: ElemGrip[] = [];
for (const st of stairs) {
if (st.locked) continue;
const y = floorBaseZ(project, st.floorId) + 0.05;
const target = { stairId: st.id };
out.push({ kind: "move", target, index: 0, pos: world(stairMoveHandle(st), y), planeY: y });
stairParamPoints(st).forEach((p, i) => out.push({ kind: "vertex", target, index: i + 1, pos: world(p, y), planeY: y }));
}
for (const op of openings) {
if (op.locked || op.hostRoofId || op.hostCeilingId) continue;
const w = project.walls.find((x) => x.id === op.hostWallId);
if (!w) continue;
const y = openingSillZ(project, op, w) + 0.05;
out.push({ kind: "move", target: { openingId: op.id }, index: 0, pos: world(openingGripPoint(w, op), y), planeY: y });
}
for (const c of columns) {
if (c.locked) continue;
const top = columnTopZ(project, c);
const target = { columnId: c.id };
columnGripPoints(c).forEach((p, i) => {
const y = top + (i === 0 ? 0.25 : 0.02);
out.push({ kind: i === 0 ? "move" : "vertex", target, index: i, pos: world(p, y), planeY: y });
});
}
return out;
}
/** Höhenversatz der Explosionsaxonometrie ([65]) eines Element-Griffs (Geschoss des Elements). */
export function elemExplodeDz(project: Project, offsets: Readonly<Record<string, number>>, target: ElemGripTarget): number {
let floorId: string | undefined;
if (target.stairId) floorId = project.stairs?.find((s) => s.id === target.stairId)?.floorId;
else if (target.columnId) floorId = project.columns?.find((c) => c.id === target.columnId)?.floorId;
else if (target.openingId) {
const op = project.openings?.find((o) => o.id === target.openingId);
floorId = project.walls.find((w) => w.id === op?.hostWallId)?.floorId;
}
return (floorId && offsets[floorId]) || 0;
}
+14 -1
View File
@@ -44,6 +44,10 @@ type DerivedContentProps =
| "edit3dDrawings"
| "edit3dCeilings"
| "edit3dRoofs"
| "edit3dStairs"
| "edit3dOpenings"
| "edit3dColumns"
| "onEdit3dElement"
| "onEdit3dVertex"
| "onEdit3dBody"
| "onEdit3dEdge"
@@ -137,6 +141,7 @@ export function ViewportCenter(props: {
updateOpening: pa.updateOpening,
slideOpening: pa.slideOpening,
sheetHeightGrip: pa.sheetHeightGrip,
sheetEndGrip: pa.sheetEndGrip,
moveStairBy: pa.moveStairBy,
dragStairParam: pa.dragStairParam,
moveRoomGrip: pa.moveRoomGrip,
@@ -190,9 +195,13 @@ export function ViewportCenter(props: {
moveGripOf: pa.moveGripOf,
moveElementByOf: pa.moveElementByOf,
updateWall: pa.updateWall,
moveStairBy: pa.moveStairBy,
dragStairParam: pa.dragStairParam,
slideOpening: pa.slideOpening,
moveColumnGrip: pa.moveColumnGrip,
});
const {
edit3dWalls, edit3dDrawings, edit3dCeilings, edit3dRoofs, onEdit3dVertex, onEdit3dBody, onEdit3dEdge,
edit3dWalls, edit3dDrawings, edit3dCeilings, edit3dRoofs, edit3dStairs, edit3dOpenings, edit3dColumns, onEdit3dElement, onEdit3dVertex, onEdit3dBody, onEdit3dEdge,
onEdit3dRoofPitch, onEdit3dWallTop, onEdit3dEnd, cycleGrip3dEditField, cancelGrip3dEdit,
} = grip3d;
@@ -231,6 +240,10 @@ export function ViewportCenter(props: {
edit3dDrawings={edit3dDrawings}
edit3dCeilings={edit3dCeilings}
edit3dRoofs={edit3dRoofs}
edit3dStairs={edit3dStairs}
edit3dOpenings={edit3dOpenings}
edit3dColumns={edit3dColumns}
onEdit3dElement={onEdit3dElement}
onEdit3dVertex={onEdit3dVertex}
onEdit3dBody={onEdit3dBody}
onEdit3dEdge={onEdit3dEdge}
+9 -5
View File
@@ -1189,16 +1189,20 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
return idx.map((i) => {
const s = toLocal(grips![i]);
const insert = !!(grips![i] as { insert?: boolean }).insert;
// [333] Waagrechter End-Griff im Schnitt: breites flaches Rechteck (links-rechts ziehen), nicht das Quadrat der Höhen-Griffe.
const horizontal = !!(grips![i] as { horizontal?: boolean }).horizontal;
const hover = hoverGrip === i;
const half = (gripSquareHalfPx(insert, hover) * k * (hover ? 1 : crowd)) / meet;
const halfW = horizontal ? half * 1.9 : half;
const halfH = horizontal ? half * 0.8 : half;
return (
<rect
key={`grip-${i}`}
className={"plan-grip" + (insert ? " plan-grip-insert" : "") + (hover ? " plan-grip-hover" : "")}
x={s.x - half}
y={s.y - half}
width={half * 2}
height={half * 2}
className={"plan-grip" + (insert ? " plan-grip-insert" : "") + (horizontal ? " plan-grip-horizontal" : "") + (hover ? " plan-grip-hover" : "")}
x={s.x - halfW}
y={s.y - halfH}
width={halfW * 2}
height={halfH * 2}
pointerEvents="none"
/>
);
+22
View File
@@ -0,0 +1,22 @@
import { describe, expect, it } from "vitest";
import { pickGripIndex } from "./gripPick";
// Stütze 12 cm: Mitte (Index 0) und Ecke (Index 1) nur 7 px auseinander.
const col = [{ x: 100, y: 100 }, { x: 107, y: 100 }, { x: 93, y: 100 }];
describe("pickGripIndex", () => {
it("Klick auf die Ecke trifft die Ecke, nicht die Mitte", () => {
expect(pickGripIndex(col, 107, 100, 9)).toBe(1);
expect(pickGripIndex(col, 93, 101, 9)).toBe(2);
});
it("Klick auf die Mitte trifft die Mitte", () => {
expect(pickGripIndex(col, 100, 100, 9)).toBe(0);
});
it("praktisch gleich nah: Ecke (höherer Index) vor Mitte", () => {
expect(pickGripIndex(col, 103.5, 100, 9)).toBe(1);
});
it("ausserhalb des Radius: null", () => {
expect(pickGripIndex(col, 140, 100, 9)).toBeNull();
expect(pickGripIndex([], 0, 0, 9)).toBeNull();
});
});
+21
View File
@@ -0,0 +1,21 @@
// Griff-Treffer im Plan ([333]): der NÄCHSTE Griff gewinnt, nicht der erste im Radius. Bei einer kleinen Stütze
// (12 cm) liegen die Eck-Griffe nur etwa 7 px vom Mittelgriff; die Liste führt den Mittel-/Verschiebe-Griff an
// Index 0, die Ecken folgen — der alte „erster Treffer"-Test nahm deshalb auch beim Klick auf eine Ecke die Mitte.
/** Abstand (px), innerhalb dessen zwei Griffe als gleich nah gelten (dann gewinnt der spätere: Ecke statt Mitte). */
export const GRIP_TIE_PX = 2;
/**
* Index des Griffs, dessen Mittelpunkt dem Zeiger am nächsten liegt und höchstens `hitPx` entfernt ist; sonst null.
* Liegen mehrere Griffe praktisch gleich nah (Unterschied ≤ {@link GRIP_TIE_PX}), gilt der mit dem höheren Index —
* die Listen der Bauteile führen den Verschiebe-Griff (Mitte) vorn, Ecken/Eckpunkte dahinter.
*/
export function pickGripIndex(centers: readonly { x: number; y: number }[], px: number, py: number, hitPx: number): number | null {
const d = centers.map((c) => Math.hypot(c.x - px, c.y - py));
let minD = Infinity;
for (const x of d) if (x <= hitPx && x < minD) minD = x;
if (!Number.isFinite(minD)) return null;
let best: number | null = null;
for (let i = 0; i < d.length; i++) if (d[i] <= hitPx && d[i] <= minD + GRIP_TIE_PX) best = i;
return best;
}
+11 -6
View File
@@ -8,6 +8,7 @@ import type { ViewBox__plan_planView_geometry as ViewBox, ClientMap } from "../.
import type { Vec2, EdgeGrip } from "../../../model/types";
import type { BodyTarget } from "./types";
import { GRIP_HIT_PX } from "./constants";
import { pickGripIndex } from "./gripPick";
import { createCursorStore } from "../../../state/cursorStore";
import type { GripHandlers } from "./types";
import type { PlanViewHandle } from "./types";
@@ -302,12 +303,16 @@ export function usePlanCoords(inp: UsePlanCoordsArgs) {
// Index des Griffs unter dem Cursor (Bildschirm-Pixel) oder null.
const gripAt = (clientX: number, clientY: number): number | null => {
if (!grips) return null;
for (let i = 0; i < grips.length; i++) {
const vb = toScreen(grips[i]);
const c = vbToClient(vb.x, vb.y);
if (Math.hypot(c.x - clientX, c.y - clientY) <= GRIP_HIT_PX) return i;
}
return null;
// [333] Nächster Griff gewinnt (kleine Stütze: Ecke statt Mitte), s. `gripPick.ts`.
return pickGripIndex(
grips.map((g) => {
const vb = toScreen(g);
return vbToClient(vb.x, vb.y);
}),
clientX,
clientY,
GRIP_HIT_PX,
);
};
// Bildschirm-Versatz (viewBox-Einheiten) eines Kanten-Anfassers entlang seiner
// Normale: das Dreieck sitzt etwas AUSSERHALB der Kante. Y wird gespiegelt
+16
View File
@@ -20,6 +20,9 @@ import type {
Layout,
Project,
Roof,
Stair,
Opening,
Column,
Vec2,
Wall,
} from "../model/types";
@@ -139,6 +142,10 @@ export const Content = memo(function Content({
edit3dDrawings,
edit3dCeilings,
edit3dRoofs,
edit3dStairs,
edit3dOpenings,
edit3dColumns,
onEdit3dElement,
onEdit3dVertex,
onEdit3dBody,
onEdit3dEdge,
@@ -247,6 +254,11 @@ export const Content = memo(function Content({
/** Alle gewählten Decken — 3D-Eckpunkt-/Kanten-/Verschiebe-Griffe. */
edit3dCeilings: Ceiling[];
edit3dRoofs: Roof[];
/** [333] Gewählte Treppen/Wandöffnungen/Stützen — 3D-Griffe (Kern-Anfragen wie im Plan). */
edit3dStairs: Stair[];
edit3dOpenings: Opening[];
edit3dColumns: Column[];
onEdit3dElement: (target: { stairId?: string; openingId?: string; columnId?: string }, index: number, pt: Vec2) => void;
onEdit3dVertex: (
target: { wallId?: string; drawingId?: string; ceilingId?: string; roofId?: string },
index: number,
@@ -358,6 +370,10 @@ export const Content = memo(function Content({
editDrawings={edit3dDrawings}
editCeilings={edit3dCeilings}
editRoofs={edit3dRoofs}
editStairs={edit3dStairs}
editOpenings={edit3dOpenings}
editColumns={edit3dColumns}
onEditElement={onEdit3dElement}
onEditVertex={onEdit3dVertex}
onEditBody={onEdit3dBody}
onEditEdge={onEdit3dEdge}