From 3ff123773a14007d1dd9e4716396e6b0cfc1c634 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 29 Oct 2026 20:29:55 +0000 Subject: [PATCH] [89] Layout-Blatt: Zeichnen wie im Grundriss (Blatt-Ebene statt eigener Annotationen) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Jedes Layout hat eine Blatt-Ebene (DrawingLevel.layoutId, Papier 1:1 in Metern); ein offenes Blatt macht sie zur aktiven Ebene in derselben PlanView: gleiche Befehle, Fang, Griffe, Vorschau/HUD, Auswahl, Undo und dasselbe Rendering. Das Blatt liefert nur den Hintergrund (PlanView.backdrop) und das Platzieren der Viewports. Format 3 migriert Layout.annotations zu drawings2d. Layout-PDF legt die Blatt-Ebene über planToPrintSvg aufs Papier. Alter Annotations-Pfad gelöscht. e2e layoutSheet.spec.ts. --- TODO.md | 19 + e2e/layoutSheet.spec.ts | 210 +++ src-tauri/core/src/cmd_create.rs | 18 +- src-tauri/core/src/cmd_draw.rs | 47 +- src-tauri/core/src/document.rs | 2 +- src-tauri/core/src/model/generated.rs | 16 +- src-tauri/core/src/model/manual.rs | 82 -- src-tauri/core/src/plan/extras.rs | 18 +- src-tauri/core/src/project_format.rs | 190 ++- src/App.tsx | 218 ++-- src/cli/main.ts | 2 +- src/commands/createCore.ts | 6 +- src/export/layoutPdf.ts | 151 +-- src/export/planToPrintSvg.sheet.test.ts | 99 ++ src/export/planToPrintSvg.ts | 11 +- src/i18n/de.ts | 17 - src/i18n/en.ts | 17 - src/io/imageAsset.ts | 14 +- src/io/pdfImport.ts | 2 +- src/io/projectFormat.ts | 2 +- src/model/layoutModel.test.ts | 106 +- src/model/layoutModel.ts | 119 +- src/model/richProject.testing.ts | 15 +- src/model/types.generated.ts | 66 +- src/model/types.ts | 24 - src/panels/AttributesPanel.tsx | 44 +- src/panels/DrawingLevelsPanel.tsx | 3 +- src/panels/ObjectInfoPanel.tsx | 11 +- src/plan/generatePlan.ts | 3 + src/state/selectionInfo.ts | 9 +- src/state/setProjectOps.test.ts | 6 +- src/state/useImportHandling.ts | 13 +- src/state/usePanelHostBase.ts | 43 +- src/styles.css | 129 +- src/text/fontMetrics.ts | 7 +- src/text/renderHtml.test.ts | 12 +- src/text/renderHtml.ts | 21 - src/ui/ImportDialog.tsx | 2 +- src/ui/LayoutSheet.tsx | 1586 +++++------------------ src/ui/layoutSheetMath.test.ts | 260 +--- src/ui/layoutSheetMath.ts | 299 +---- src/views/plan/PlanView.tsx | 32 +- src/views/viewportContent.tsx | 50 +- 43 files changed, 1245 insertions(+), 2756 deletions(-) create mode 100644 e2e/layoutSheet.spec.ts create mode 100644 src/export/planToPrintSvg.sheet.test.ts diff --git a/TODO.md b/TODO.md index fd4657d2..cf8efddd 100644 --- a/TODO.md +++ b/TODO.md @@ -1298,6 +1298,25 @@ Reihenfolge = Abhängigkeiten. Neue Geometrie entsteht in Rust ([K]). - ✅ **[78] Autotext im Plankopf.** Titelblock löst Projekt/Blatt/Massstab/Datum auf; Plannummer laufend oder `Layout.planNumber` (27.10.). - ○ **[79] Publikationssätze.** · M +- ✅ **[89] Zeichnen auf dem Layout-Blatt = Zeichnen im Grundriss.** (29.10., Wartungs-Feedback „soll sich genau + gleich anfühlen") Vorher eigener Pfad: `Layout.annotations` (Linie/Rechteck/Text/Bild in Papier-mm) mit eigenen + Werkzeug-Zuständen, Klick-Logik, Griffen, Inline-Editor und DOM-Rendering in `LayoutSheet.tsx`, ohne Fang, + Befehlszeile/HUD, Tab-Felder, Bearbeiten-Befehle, Polylinie/Kreis/Bemassung …; eigene Auswahlart + `layoutAnnotation`, eigenes Pan/Zoom, eigener PDF-Zweig. Jetzt: jedes Layout hat seine Blatt-Ebene + (`DrawingLevel.layoutId`, Art „drawing", Papier 1:1 in Metern, Ursprung oben links, Papier-y = −y); ein offenes + Blatt macht sie zur aktiven Ebene und zeigt sie in derselben PlanView — gleiche Befehle, Fang, Griffe, Vorschau/HUD, + Auswahl, Undo (ein Schritt je Element) und dasselbe Rendering; das Blatt liefert nur den Hintergrund + (`PlanView.backdrop`: Papier, Master, Viewports) und Platzieren/Verschieben/Skalieren der Viewports. Format 3: + Migration `annotations` → `drawings2d` auf der Blatt-Ebene (jedes Layout bekommt seine Ebene); Blatt-Ebenen + ohne Strichstärken-Faktor und ohne projektglobale Zutaten, Schrifthöhe neuer Texte 3.5 mm (`textHeight` im + Befehls-Kontext), Bild einfügen 60 mm mitten aufs Blatt; Layout-PDF legt die Blatt-Ebene über `planToPrintSvg` + (fester Bereich, ohne Blatt) aufs Papier. Gelöscht: Annotations-Typen/-CRUD/-Mathe/-Rendering/-CSS, `annotationTextLines`. + e2e `layoutSheet.spec.ts` (Linie, Polylinie, Rechteck, Fang auf Endpunkt, Griff ziehen + Undo, ein Undo-Schritt je + Element — identisch im Grundriss und auf dem Blatt). Offen: Blatt rendert über den SVG-Pfad der PlanView (wegen des + Hintergrunds, wie bei Luftbildern), nicht über render2d; Lineale/Objekt-Info zeigen Meter (y negativ) statt + Papier-mm; feste Modellgrössen anderer Befehle (Kote, Detailverweis, Punktmarke) nicht ans Papier angepasst; kein + Fang auf Viewport-Inhalt; Layout-DXF (`--layout`) ohne Blatt-Zeichnung; PDF-Export der Blatt-Zeichnung nicht + angesehen; nicht in der Tauri-App/macOS geprüft. · M - ○ **[80] PDF mit Ebenen.** · M - ◐ **[81] Automatische Aussenbemassung.** (27.10.) Befehl `autodim` (Kürzel `ab`): je Seite Öffnungs-, Vor-/Rücksprung- und Gesamtkette. Offen: schiefe Wände, Massstab aus der Ansicht statt fest 1:100. diff --git a/e2e/layoutSheet.spec.ts b/e2e/layoutSheet.spec.ts new file mode 100644 index 00000000..1a7262df --- /dev/null +++ b/e2e/layoutSheet.spec.ts @@ -0,0 +1,210 @@ +// Zeichnen auf dem Layout-Blatt = Zeichnen im Grundriss (Wartungs-Feedback 29.10.: „es sollte sich +// genau gleich wie im normalen Ausschnitt anfühlen/sein"). Das Blatt ist die Blatt-Ebene des Layouts +// in derselben Plan-Ansicht: dieselbe Maus-/Tastenfolge erzeugt dort dieselben Elemente, mit Fang, +// 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, openTab, startNewProject, test } from "./app"; + +type Pt = { x: number; y: number }; + +/** Bisherige Rückgängig-Schritte (Panel „Verlauf", ohne Ausgangsstand und wiederholbare). */ +function doneSteps(page: Page) { + return page.locator("[data-testid=history-panel] .history-row:not(.future)").filter({ hasNotText: "Ausgangsstand" }); +} + +async function openHistory(page: Page): Promise { + await page.getByRole("button", { name: "Bearbeiten", exact: true }).click(); + await page.getByRole("option", { name: "Verlauf" }).click(); + await expect(page.locator("[data-testid=history-panel]")).toBeVisible(); + // Schwebendes Fenster aus dem Weg (über das rechte Dock) ziehen. + const title = page.locator("section[aria-label=Verlauf] .floating-title"); + const tb = await title.boundingBox(); + if (tb && tb.x < 1250) { + await page.mouse.move(tb.x + 10, tb.y + tb.height / 2); + await page.mouse.down(); + await page.mouse.move(1300, 760, { steps: 5 }); + await page.mouse.up(); + } +} + +/** Sichtbarer Bereich der Plan-Ansicht (Client-Pixel). */ +async function planBox(page: Page) { + return (await page.locator("svg.plan-svg").boundingBox())!; +} + +/** Client-Pixel → Modellpunkt (m) über die viewBox der Plan-Ansicht. */ +async function modelOf(page: Page, p: Pt): Promise { + return page.locator("svg.plan-svg").evaluate( + (el, [cx, cy]) => { + 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); + const lx = (cx - r.left - (r.width - vw * s) / 2) / s + vx + ox; + const ly = (cy - r.top - (r.height - vh * s) / 2) / s + vy + oy; + return { x: lx / 90, y: -ly / 90 }; + }, + [p.x, p.y], + ); +} + +/** Mittelpunkte der gezeichneten Griffe (Client-Pixel). */ +async function gripCenters(page: Page): Promise { + return page.locator(".plan-grip").evaluateAll((els) => + els.map((e) => { + const r = e.getBoundingClientRect(); + return { x: r.x + r.width / 2, y: r.y + r.height / 2 }; + }), + ); +} + +async function pickTool(page: Page, name: string, prompt: string | RegExp): Promise { + await page.getByRole("button", { name, exact: true }).click(); + await expect(page.locator(".cmdline-prompt")).toHaveText(prompt); +} + +async function clickAt(page: Page, p: Pt): Promise { + await page.mouse.move(p.x - 6, p.y - 6); + await page.mouse.move(p.x, p.y, { steps: 3 }); + await page.mouse.click(p.x, p.y); +} + +/** Zeichenzug beenden wie im Grundriss: leeres Enter in der Befehlszeile. */ +async function finish(page: Page): Promise { + await page.locator(".cmdline-input").press("Enter"); + await expect(page.locator(".cmdline-prompt")).toHaveText("Befehl:"); +} + +/** + * Dieselbe Folge wie im Grundriss: Linie (2 Klicks), Polylinie (3 Klicks + Enter), Rechteck + * (2 Klicks), alles relativ zum Rahmen `f` (Client-Pixel). Danach: zweite Linie, deren Start 4 px + * neben dem Ende der ersten Linie liegt — der Fang muss auf den Endpunkt ziehen. + */ +async function drawSequence(page: Page, f: { x: number; y: number; w: number; h: number }, base: number) { + const steps = (n: number) => expect(doneSteps(page)).toHaveCount(base + n); + const at = (u: number, v: number): Pt => ({ x: f.x + u * f.w, y: f.y + v * f.h }); + await pickTool(page, "Linie", /Startpunkt/); + await clickAt(page, at(0.1, 0.15)); + await clickAt(page, at(0.45, 0.15)); + await finish(page); + await steps(1); + await pickTool(page, "Polylinie", /Startpunkt|Erster Punkt/); + await clickAt(page, at(0.1, 0.35)); + await clickAt(page, at(0.3, 0.5)); + await clickAt(page, at(0.45, 0.35)); + await finish(page); + await steps(2); + await pickTool(page, "Rechteck", /Ecke|Startpunkt/); + await clickAt(page, at(0.55, 0.15)); + await clickAt(page, at(0.9, 0.5)); + if ((await page.locator(".cmdline-prompt").textContent()) !== "Befehl:") await finish(page); + await steps(3); + + // Fang: 4 px neben dem Endpunkt der ersten Linie → die Marke sitzt genau auf dem Endpunkt. + const end = at(0.45, 0.15); + await pickTool(page, "Linie", /Startpunkt/); + await page.mouse.move(end.x + 4, end.y + 3, { steps: 4 }); + const marker = page.locator(".snap-marker .snap-glyph").first(); + await expect(marker).toBeVisible(); + const mb = (await marker.boundingBox())!; + expect(Math.hypot(mb.x + mb.width / 2 - end.x, mb.y + mb.height / 2 - end.y)).toBeLessThan(1.5); + await page.mouse.click(end.x + 4, end.y + 3); + await clickAt(page, at(0.45, 0.3)); + await finish(page); + await steps(4); + return { at, end }; +} + +/** Elemente nacheinander rückgängig machen und wiederholen: je Element genau ein Schritt. */ +async function undoEach(page: Page, base: number, n: number) { + await blurFocus(page); + for (let i = n; i > 0; i--) { + await expect(doneSteps(page)).toHaveCount(base + i); + await page.keyboard.press("ControlOrMeta+z"); + } + await expect(doneSteps(page)).toHaveCount(base); + for (let i = 1; i <= n; i++) { + await page.keyboard.press("ControlOrMeta+Shift+z"); + await expect(doneSteps(page)).toHaveCount(base + i); + } +} + +/** Neues A4-Layout anlegen und öffnen. */ +async function openNewLayout(page: Page) { + await openTab(page, "Mappe"); + await page.getByRole("button", { name: "Layout erstellen" }).first().click(); + await page.getByRole("button", { name: "Erstellen", exact: true }).click(); + await page.keyboard.press("Enter"); + await page.locator(".nav-row", { hasText: "Layout" }).first().dblclick(); + await expect(page.locator(".layout-sheet-pane")).toBeVisible(); +} + +/** Bildschirm-Rahmen des Papiers (aus der Blatt-Gruppe im Hintergrund der Plan-Ansicht). */ +async function paperBox(page: Page) { + return (await page.locator("[data-sheet-backdrop] > rect").nth(1).boundingBox())!; +} + +for (const where of ["Grundriss", "Layout-Blatt"] as const) { + test(`Linie, Polylinie, Rechteck, Fang, Griff, Undo — ${where}`, async ({ page }) => { + await startNewProject(page); + let frame; + if (where === "Layout-Blatt") { + await openNewLayout(page); + frame = await paperBox(page); + // Das ganze Blatt ist eingepasst und sichtbar. + const pb = await planBox(page); + expect(frame.width).toBeGreaterThan(200); + expect(frame.x).toBeGreaterThan(pb.x); + expect(frame.y + frame.height).toBeLessThan(pb.y + pb.height); + } else { + const pb = await planBox(page); + frame = { x: pb.x + pb.width * 0.3, y: pb.y + pb.height * 0.15, width: pb.width * 0.4, height: pb.height * 0.6 }; + } + await openHistory(page); + const base = await doneSteps(page).count(); + const f = { x: frame.x, y: frame.y, w: frame.width, h: frame.height }; + const { at, end } = await drawSequence(page, f, base); + + // Die zweite Linie beginnt exakt im Endpunkt der ersten: ihr Griff liegt auf dem Endpunkt. + // Zurück zur Auswahl wie im Grundriss (Werkzeug „Auswahl"). + await page.getByRole("button", { name: "Auswahl", exact: true }).click(); + await blurFocus(page); + const mid2 = at(0.45, 0.225); + await page.mouse.click(mid2.x, mid2.y); + await expect(page.locator(".plan-grip")).toHaveCount(2); + const g = await gripCenters(page); + expect(Math.min(...g.map((p) => Math.hypot(p.x - end.x, p.y - end.y)))).toBeLessThan(1); + const m = await modelOf(page, end); + // Sheet: Papier 1:1 in Metern (Ursprung oben links → y negativ), Grundriss: beliebig. + if (where === "Layout-Blatt") expect(m.y).toBeLessThan(0); + + await page.screenshot({ path: `test-results/layout-sheet-${where === "Grundriss" ? "plan" : "sheet"}.png` }); + + // Griff: Rechteck wählen, Ecke ziehen (Klick-Ziehen-Klick wie im Grundriss) → breiter; Undo. + const rectEdge = at(0.9, 0.3); + await page.mouse.click(rectEdge.x, rectEdge.y); + await expect(page.locator(".plan-grip").first()).toBeVisible(); + const width = page.locator(".objinfo-field").filter({ hasText: "Breite" }).locator("input"); + await openTab(page, "Objekt-Info"); + const w0 = Number(await width.inputValue()); + const corner = at(0.9, 0.5); + const to = at(0.97, 0.5); + await page.mouse.move(corner.x, corner.y); + await page.mouse.down(); + await page.mouse.move((corner.x + to.x) / 2, corner.y, { steps: 4 }); + await page.mouse.move(to.x, to.y, { steps: 4 }); + await page.mouse.up(); + await page.mouse.click(to.x, to.y); + await expect.poll(async () => Number(await width.inputValue())).toBeGreaterThan(w0 * 1.1); + await blurFocus(page); + await page.keyboard.press("ControlOrMeta+z"); + await expect.poll(async () => Number(await width.inputValue())).toBeCloseTo(w0, 6); + + // Undo je Element ein Schritt (4 Elemente). + await page.keyboard.press("Escape"); + await openHistory(page); + await undoEach(page, base, 4); + }); +} diff --git a/src-tauri/core/src/cmd_create.rs b/src-tauri/core/src/cmd_create.rs index 0514ec8f..69005f12 100644 --- a/src-tauri/core/src/cmd_create.rs +++ b/src-tauri/core/src/cmd_create.rs @@ -92,12 +92,22 @@ pub struct Ctx<'a> { pub floor_height: Option, pub cat: &'a str, pub wall_type: &'a str, + /// Schrifthöhe neuer Texte (Modell-Meter, `textHeight` im Kontext): im Grundriss die Vorgabe + /// [`DEFAULT_TEXT_HEIGHT`], auf einem Layout-Blatt (Papier 1:1) die Papierhöhe. + pub text_height: f64, +} + +/// Schrifthöhe neuer Texte im Grundriss (Modell-Meter, 2.5 mm bei 1:100). +pub const DEFAULT_TEXT_HEIGHT: f64 = 0.25; + +fn text_height_of(c: &Value) -> f64 { + opt_n(c, "textHeight").filter(|h| *h > 0.0 && h.is_finite()).unwrap_or(DEFAULT_TEXT_HEIGHT) } pub(crate) fn ctx_of(v: &Value) -> Ctx<'_> { let c = v.get("ctx").unwrap_or(&Value::Null); let fh = opt_n(c, "floorHeight").filter(|h| *h > 0.0); - Ctx { level: s_of(c, "level"), floor_height: fh, cat: s_of(c, "cat"), wall_type: s_of(c, "wallType") } + Ctx { level: s_of(c, "level"), floor_height: fh, cat: s_of(c, "cat"), wall_type: s_of(c, "wallType"), text_height: text_height_of(c) } } // ── Werte bauen ────────────────────────────────────────────────────────────── @@ -912,20 +922,22 @@ pub struct Req { floor_height: Option, cat: String, wall_type: String, + text_height: f64, } impl Req { pub fn new(v: Value) -> Req { let c = ctx_of(&v); let (level, floor_height, cat, wall_type) = (c.level.to_string(), c.floor_height, c.cat.to_string(), c.wall_type.to_string()); - Req { cmd: s_of(&v, "cmd").to_string(), v, level, floor_height, cat, wall_type } + let text_height = c.text_height; + Req { cmd: s_of(&v, "cmd").to_string(), v, level, floor_height, cat, wall_type, text_height } } } /// Wie [`preview`] mit gelesener Anfrage (Mausschritt: dieselbe Anfrage, neue Punkte). pub fn preview_req(root: &Map, req: &Req, pts: &[f64]) -> Preview { let v = &req.v; - let ctx = Ctx { level: &req.level, floor_height: req.floor_height, cat: &req.cat, wall_type: &req.wall_type }; + let ctx = Ctx { level: &req.level, floor_height: req.floor_height, cat: &req.cat, wall_type: &req.wall_type, text_height: req.text_height }; let pts = flat_pts(pts); let mut p = Preview { ok: true, ..Default::default() }; let out = &mut p.shapes; diff --git a/src-tauri/core/src/cmd_draw.rs b/src-tauri/core/src/cmd_draw.rs index f8804cba..2e48b9ff 100644 --- a/src-tauri/core/src/cmd_draw.rs +++ b/src-tauri/core/src/cmd_draw.rs @@ -823,21 +823,22 @@ fn multiline_preview(v: &Value, pts: &[V], p: &mut Preview) { } } -const TEXT_HEIGHT: f64 = 0.25; -const TEXTBOX_MIN: f64 = 0.2; +/// Mindestgrösse eines Textrahmens als Vielfaches der Schrifthöhe (0.2 m bei 0.25 m Schrift). +const TEXTBOX_MIN_PER_HEIGHT: f64 = 0.8; -fn text_geom(at: Value, extra: Vec<(&str, Value)>) -> Value { - let mut f = vec![("shape", s("text")), ("at", at), ("text", s("")), ("height", js_num(TEXT_HEIGHT)), ("angle", js_num(0.0))]; +fn text_geom(ctx: &Ctx, at: Value, extra: Vec<(&str, Value)>) -> Value { + let mut f = vec![("shape", s("text")), ("at", at), ("text", s("")), ("height", js_num(ctx.text_height)), ("angle", js_num(0.0))]; f.extend(extra); obj(f) } /// Textrahmen aus zwei Ecken: Anker oben links (eine Zeile tief), Breite, Mindesthöhe. -fn textbox_frame(a: V, b: V) -> (V, f64, f64) { +fn textbox_frame(a: V, b: V, text_height: f64) -> (V, f64, f64) { let (mn, mx) = rect_geom(a, b); - let width = jsnum::max(TEXTBOX_MIN, mx.0 - mn.0); - let height = jsnum::max(TEXTBOX_MIN, mx.1 - mn.1); - ((mn.0, mx.1 - TEXT_HEIGHT), width, height) + let min = TEXTBOX_MIN_PER_HEIGHT * text_height; + let width = jsnum::max(min, mx.0 - mn.0); + let height = jsnum::max(min, mx.1 - mn.1); + ((mn.0, mx.1 - text_height), width, height) } fn kote_tri(at: V, kind: &str) -> [V; 3] { @@ -1091,15 +1092,15 @@ pub fn ops(root: &Map, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> add_op("drawings2d", vec![d]) } "multiline" => multiline_ops(v, ctx, ids), - "text" => add_drawing(v, ctx, ids, text_geom(pt_val(v, "at"), vec![])), + "text" => add_drawing(v, ctx, ids, text_geom(ctx, pt_val(v, "at"), vec![])), "textbox" => { - let (at, width, _) = textbox_frame(p_of(v, "a"), p_of(v, "b")); - add_drawing(v, ctx, ids, text_geom(pv(at), vec![("width", js_num(width))])) + let (at, width, _) = textbox_frame(p_of(v, "a"), p_of(v, "b"), ctx.text_height); + add_drawing(v, ctx, ids, text_geom(ctx, pv(at), vec![("width", js_num(width))])) } "textpath" => { let pts = pts_val(v, "pts"); let at = pts.get(0).cloned().unwrap_or(Value::Null); - add_drawing(v, ctx, ids, text_geom(at, vec![("pathPts", pts)])) + add_drawing(v, ctx, ids, text_geom(ctx, at, vec![("pathPts", pts)])) } "leader" => { let mut extra = vec![("leaderTarget", pt_val(v, "target"))]; @@ -1107,7 +1108,7 @@ pub fn ops(root: &Map, v: &Value, ctx: &Ctx, ids: &mut IdGen) -> if bends.as_array().is_some_and(|b| !b.is_empty()) { extra.push(("leaderBendPoints", bends)); } - add_drawing(v, ctx, ids, text_geom(pt_val(v, "at"), extra)) + add_drawing(v, ctx, ids, text_geom(ctx, pt_val(v, "at"), extra)) } "kote" => add_drawing( v, @@ -1160,7 +1161,7 @@ pub fn preview(root: &Map, v: &Value, ctx: &Ctx, pts: &[V], p: &m "textbox" => { if let [a, b] = pts { let (mn, mx) = rect_geom(*a, *b); - let (_, w, h) = textbox_frame(*a, *b); + let (_, w, h) = textbox_frame(*a, *b, ctx.text_height); p.info.extend([w, h]); p.shapes.poly(&corners_of(mn, mx)); } @@ -1232,7 +1233,23 @@ mod tests { use super::*; fn ctx() -> Ctx<'static> { - Ctx { level: "L", floor_height: None, cat: "20", wall_type: "" } + Ctx { level: "L", floor_height: None, cat: "20", wall_type: "", text_height: crate::cmd_create::DEFAULT_TEXT_HEIGHT } + } + + #[test] + fn schrifthoehe_aus_dem_kontext() { + // Grundriss: Vorgabe 0.25 m; Layout-Blatt (Papier 1:1): die Papierhöhe aus `textHeight`. + let v = json!({"cmd": "text", "at": {"x": 0.1, "y": -0.1}, "ctx": {"level": "blatt", "cat": "20", "textHeight": 0.0035}}); + let c = crate::cmd_create::ctx_of(&v); + assert_eq!(c.text_height, 0.0035); + let o = ops(&Map::new(), &v, &c, &mut IdGen::new("s")).unwrap(); + assert_eq!(o[0].to_json()["items"][0]["geom"]["height"], 0.0035); + let plain = json!({"ctx": {"level": "eg", "textHeight": -1}}); + assert_eq!(crate::cmd_create::ctx_of(&plain).text_height, crate::cmd_create::DEFAULT_TEXT_HEIGHT); + // Textrahmen: Mindestgrösse folgt der Schrifthöhe, Anker eine Zeile unter der Oberkante. + let (at, w, h) = textbox_frame((0.0, 0.0), (0.0001, -0.0001), 0.0035); + assert!((w - 0.0028).abs() < 1e-12 && (h - 0.0028).abs() < 1e-12); + assert!((at.1 - (0.0 - 0.0035)).abs() < 1e-12); } #[test] diff --git a/src-tauri/core/src/document.rs b/src-tauri/core/src/document.rs index fd06147d..f8cf91c3 100644 --- a/src-tauri/core/src/document.rs +++ b/src-tauri/core/src/document.rs @@ -767,7 +767,7 @@ mod tests { assert_eq!(d.project().unwrap().walls.len(), 0); assert_eq!(d.field("openings").unwrap()[0]["kind"], "door"); assert!(d.undo().is_none()); - assert!(d.serialize().starts_with("{\n \"formatVersion\": 2,\n \"id\": \"q\"")); + assert!(d.serialize().starts_with("{\n \"formatVersion\": 3,\n \"id\": \"q\"")); } #[test] diff --git a/src-tauri/core/src/model/generated.rs b/src-tauri/core/src/model/generated.rs index 78056656..83a6ab41 100644 --- a/src-tauri/core/src/model/generated.rs +++ b/src-tauri/core/src/model/generated.rs @@ -1309,6 +1309,14 @@ pub struct DrawingLevel { #[serde(rename = "levelMarks", default, skip_serializing_if = "Option::is_none")] #[ts(optional)] pub level_marks: Option, + /// Blatt-Ebene (nur kind "drawing"): gehört zum Layout mit dieser ID und trägt dessen + /// 2D-Zeichnung (Linien, Texte, Bilder …) als gewöhnliche `drawings2d`. Koordinaten = Papier + /// im Massstab 1:1 in Metern, Ursprung oben links am Blatt, Papier-y nach unten = −y + /// (Papier-mm (x, y) ↔ Modell (x/1000, −y/1000)). Nicht im Navigator; nur sichtbar, wenn das + /// Blatt offen ist. Fehlt ⇒ gewöhnliche Ebene. + #[serde(rename = "layoutId", default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub layout_id: Option, #[serde(flatten)] #[ts(skip)] pub extra: Extra, @@ -3367,13 +3375,9 @@ pub struct Layout { #[serde(rename = "customHeightMm", default, skip_serializing_if = "Option::is_none")] #[ts(optional)] pub custom_height_mm: Option, + /// Die 2D-Zeichnung auf dem Blatt liegt auf der Blatt-Ebene ({@link DrawingLevel.layoutId}), + /// nicht im Layout (bis Format 2: `annotations`, s. `project_format::migrate_layout_annotations`). pub viewports: Vec, - /// 2D-Markups direkt auf dem Blatt (Linie/Rechteck/Text), siehe - /// {@link LayoutAnnotation}. Additiv — Alt-Layouts ohne dieses Feld laden - /// unverändert (Editor/CRUD behandeln ein fehlendes Array wie ein leeres). - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - pub annotations: Option>, #[serde(flatten)] #[ts(skip)] pub extra: Extra, diff --git a/src-tauri/core/src/model/manual.rs b/src-tauri/core/src/model/manual.rs index 45e3f14b..fae59f5d 100644 --- a/src-tauri/core/src/model/manual.rs +++ b/src-tauri/core/src/model/manual.rs @@ -439,88 +439,6 @@ pub enum Drawing2DGeom { }, } -/// Layout-Beschriftung (Tag `kind`). -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)] -#[serde(tag = "kind")] -pub enum LayoutAnnotation { - #[serde(rename = "line")] - Line { - id: String, - #[serde(rename = "x1Mm")] - x1_mm: f64, - #[serde(rename = "y1Mm")] - y1_mm: f64, - #[serde(rename = "x2Mm")] - x2_mm: f64, - #[serde(rename = "y2Mm")] - y2_mm: f64, - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - color: Option, - #[serde(rename = "weightMm", default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - weight_mm: Option, - }, - #[serde(rename = "rect")] - Rect { - id: String, - #[serde(rename = "xMm")] - x_mm: f64, - #[serde(rename = "yMm")] - y_mm: f64, - #[serde(rename = "widthMm")] - width_mm: f64, - #[serde(rename = "heightMm")] - height_mm: f64, - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - color: Option, - #[serde(rename = "weightMm", default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - weight_mm: Option, - }, - #[serde(rename = "text")] - Text { - id: String, - #[serde(rename = "xMm")] - x_mm: f64, - #[serde(rename = "yMm")] - y_mm: f64, - text: String, - #[serde(rename = "heightMm")] - height_mm: f64, - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - color: Option, - /// Reiches Textfeld (mehrere Absätze, gemischte Formatierung) — Vorrang vor - /// `text`, s. gleichnamiges Feld bei `Drawing2DGeom["text"]`. - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - doc: Option, - /// Optionale Rahmenbreite (mm) — bricht `doc` wortweise um; fehlt sie: einzeilig. - #[serde(rename = "widthMm", default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - width_mm: Option, - }, - #[serde(rename = "image")] - Image { - id: String, - #[serde(rename = "xMm")] - x_mm: f64, - #[serde(rename = "yMm")] - y_mm: f64, - #[serde(rename = "widthMm")] - width_mm: f64, - #[serde(rename = "heightMm")] - height_mm: f64, - /// Bildquelle als Data-URL (PNG/JPEG) — eingebettet, keine externe Datei. - src: String, - #[serde(default, skip_serializing_if = "Option::is_none")] - #[ts(optional)] - opacity: Option, - }, -} - /// Parametrische Wandregel (Tag `type`). #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)] #[serde(tag = "type")] diff --git a/src-tauri/core/src/plan/extras.rs b/src-tauri/core/src/plan/extras.rs index 63cb6887..a2cd6c53 100644 --- a/src-tauri/core/src/plan/extras.rs +++ b/src-tauri/core/src/plan/extras.rs @@ -394,8 +394,10 @@ impl Post { } /// Nachbearbeitung eines Plans: Schwarz-Weiss und Strichstärken-Faktor; `None`, wenn sie nichts tut. +/// Auf einer Blatt-Ebene (`layoutId`) gelten die Strichstärken unverändert (Papier 1:1). pub fn post_for(p: &Project, a: &super::domains::PlanArgs) -> Option { - Some(Post { mono: a.mono, lw: line_weight_factor(p, a.scale) }).filter(Post::active) + let sheet = p.floor(&a.floor).is_some_and(|l| l.layout_id.is_some()); + Some(Post { mono: a.mono, lw: if sheet { 1.0 } else { line_weight_factor(p, a.scale) } }).filter(Post::active) } // ── Ausmass ───────────────────────────────────────────────────────────────────────────────────── @@ -479,6 +481,20 @@ mod tests { assert_eq!(line_weight_factor(&on, f64::NAN), 1.0); } + #[test] + fn blatt_ebene_ohne_strichstaerken_faktor() { + let mut p = sample(); + p.scale_line_weights = Some(true); + let mut sheet = p.drawing_levels[0].clone(); + sheet.id = "blatt".into(); + sheet.kind = crate::model::DrawingLevelKind::Drawing; + sheet.layout_id = Some("L1".into()); + p.drawing_levels.push(sheet); + let args = |floor: &str| super::super::domains::PlanArgs::parse(1.0, &serde_json::json!({"floor": floor, "scale": 1}).to_string()).unwrap(); + assert_eq!(post_for(&p, &args("blatt")), None, "Papier 1:1: Stärken unverändert"); + assert!(post_for(&p, &args("eg")).is_some_and(|q| q.lw > 1.0)); + } + #[test] fn abzugskoerper_spart_wand_aus() { let mut v: serde_json::Value = serde_json::from_str(include_str!("../../tests/fixtures/sample_project.json")).unwrap(); diff --git a/src-tauri/core/src/project_format.rs b/src-tauri/core/src/project_format.rs index 1672c4f5..c375c80e 100644 --- a/src-tauri/core/src/project_format.rs +++ b/src-tauri/core/src/project_format.rs @@ -9,7 +9,7 @@ use serde_json::{Map, Value}; /// Aktuelle Version des Dateiformats. Bei jeder Formatänderung erhöhen + Migration anhängen. -pub const PROJECT_FORMAT_VERSION: u64 = 2; +pub const PROJECT_FORMAT_VERSION: u64 = 3; const REQUIRED_ARRAYS: [&str; 3] = ["walls", "layers", "drawingLevels"]; const DEFAULT_ARRAYS: [&str; 5] = ["lineStyles", "hatches", "components", "wallTypes", "drawings2d"]; @@ -86,6 +86,144 @@ fn migrate_doors(mut raw: Map) -> Map { raw } +/// Kategorie für Blatt-Zeichnungen aus der Migration: „50" (Text), sonst die erste Kategorie. +fn sheet_category(raw: &Map) -> String { + fn walk(v: &Value, out: &mut Vec) { + for c in v.as_array().into_iter().flatten() { + if let Some(code) = c.get("code").and_then(Value::as_str) { + out.push(code.to_string()); + } + if let Some(ch) = c.get("children") { + walk(ch, out); + } + } + } + let mut codes = Vec::new(); + if let Some(l) = raw.get("layers") { + walk(l, &mut codes); + } + if codes.iter().any(|c| c == "50") { + return "50".into(); + } + codes.into_iter().next().unwrap_or_else(|| "50".into()) +} + +/// Papier-mm (x, y nach unten) → Blatt-Ebene (Meter, y nach oben), s. `DrawingLevel.layoutId`. +fn sheet_pt(x_mm: f64, y_mm: f64) -> Value { + serde_json::json!({"x": x_mm / 1000.0, "y": -y_mm / 1000.0}) +} + +/// Eine Alt-Annotation (Papier-mm) als `geom` + Zusatzfelder einer 2D-Zeichnung; `None` = unlesbar. +fn annotation_geom(a: &Value) -> Option<(Value, Vec<(&'static str, Value)>)> { + let n = |k: &str| a.get(k).and_then(Value::as_f64).filter(|v| v.is_finite()); + let mut extra: Vec<(&'static str, Value)> = Vec::new(); + let color = a.get("color").and_then(Value::as_str).unwrap_or("#111111").to_string(); + let kind = a.get("kind").and_then(Value::as_str)?; + let geom = match kind { + "line" => { + extra.push(("color", Value::String(color))); + extra.push(("weightMm", n("weightMm").unwrap_or(0.25).into())); + serde_json::json!({"shape": "line", "a": sheet_pt(n("x1Mm")?, n("y1Mm")?), "b": sheet_pt(n("x2Mm")?, n("y2Mm")?)}) + } + "rect" | "image" => { + let (x, y, w, h) = (n("xMm")?, n("yMm")?, n("widthMm")?, n("heightMm")?); + let (x0, x1) = (x.min(x + w), x.max(x + w)); + let (y0, y1) = (y.min(y + h), y.max(y + h)); + let (min, max) = (sheet_pt(x0, y1), sheet_pt(x1, y0)); + if kind == "rect" { + extra.push(("color", Value::String(color))); + extra.push(("weightMm", n("weightMm").unwrap_or(0.25).into())); + serde_json::json!({"shape": "rect", "min": min, "max": max}) + } else { + let mut g = serde_json::json!({"shape": "image", "min": min, "max": max, "src": a.get("src").and_then(Value::as_str)?}); + if let Some(o) = n("opacity") { + g["opacity"] = o.into(); + } + g + } + } + "text" => { + extra.push(("color", Value::String(color))); + let mut g = serde_json::json!({ + "shape": "text", + "at": sheet_pt(n("xMm")?, n("yMm")?), + "text": a.get("text").and_then(Value::as_str).unwrap_or_default(), + "height": n("heightMm")? / 1000.0, + "angle": 0, + }); + if let Some(w) = n("widthMm").filter(|w| *w > 0.0) { + g["width"] = (w / 1000.0).into(); + } + if let Some(d) = a.get("doc").filter(|d| d.is_object()) { + g["doc"] = d.clone(); + } + g + } + _ => return None, + }; + Some((geom, extra)) +} + +/// 2 → 3: Blatt-Zeichnungen sind gewöhnliche 2D-Zeichnungen auf einer Blatt-Ebene +/// (`DrawingLevel.layoutId`) statt eigener `Layout.annotations` in Papier-mm. Jedes Layout bekommt +/// seine Blatt-Ebene; Linie/Rechteck/Text/Bild werden zu `line`/`rect`/`text`/`image`. +fn migrate_layout_annotations(mut raw: Map) -> Map { + let Some(Value::Array(mut layouts)) = raw.get("layouts").cloned() else { return raw }; + let mut levels: Vec = raw.get("drawingLevels").and_then(Value::as_array).cloned().unwrap_or_default(); + let mut drawings: Vec = raw.get("drawings2d").and_then(Value::as_array).cloned().unwrap_or_default(); + let mut level_ids: std::collections::HashSet = + levels.iter().filter_map(|l| l.get("id").and_then(Value::as_str).map(str::to_owned)).collect(); + let mut drawing_ids: std::collections::HashSet = + drawings.iter().filter_map(|d| d.get("id").and_then(Value::as_str).map(str::to_owned)).collect(); + let cat = sheet_category(&raw); + for lay in layouts.iter_mut() { + let Some(lay) = lay.as_object_mut() else { continue }; + let annotations = lay.shift_remove("annotations"); + let Some(layout_id) = lay.get("id").and_then(Value::as_str).map(str::to_owned) else { continue }; + let existing = levels + .iter() + .find(|l| l.get("layoutId").and_then(Value::as_str) == Some(layout_id.as_str())) + .and_then(|l| l.get("id")) + .and_then(Value::as_str) + .map(str::to_owned); + let level_id = match existing { + Some(id) => id, + None => { + let mut id = format!("sheet-{layout_id}"); + while level_ids.contains(&id) { + id.push_str("-s"); + } + level_ids.insert(id.clone()); + let name = lay.get("name").and_then(Value::as_str).unwrap_or_default(); + levels.push(serde_json::json!({"id": id, "name": name, "kind": "drawing", "visible": true, "locked": false, "layoutId": layout_id})); + id + } + }; + for a in annotations.as_ref().and_then(Value::as_array).into_iter().flatten() { + let Some((geom, extra)) = annotation_geom(a) else { continue }; + let mut id = a.get("id").and_then(Value::as_str).filter(|s| !s.is_empty()).unwrap_or("ann").to_string(); + while drawing_ids.contains(&id) { + id.push_str("-a"); + } + drawing_ids.insert(id.clone()); + let mut d = Map::new(); + d.insert("id".into(), Value::String(id)); + d.insert("type".into(), "drawing2d".into()); + d.insert("levelId".into(), Value::String(level_id.clone())); + d.insert("categoryCode".into(), Value::String(cat.clone())); + d.insert("geom".into(), geom); + for (k, v) in extra { + d.insert(k.into(), v); + } + drawings.push(Value::Object(d)); + } + } + raw.insert("layouts".into(), Value::Array(layouts)); + raw.insert("drawingLevels".into(), Value::Array(levels)); + raw.insert("drawings2d".into(), Value::Array(drawings)); + raw +} + /// Liest eine Projektdatei (Text) tolerant ein, migriert und prüft sie. `now_ms`: Zeitpunkt für /// eine Ersatz-ID, falls die Datei keine trägt. pub fn parse_project_file(text: &str, now_ms: f64) -> Parsed { @@ -128,6 +266,7 @@ pub fn parse_project_object(raw: Value, now_ms: f64) -> Parsed { for i in version..PROJECT_FORMAT_VERSION { obj = match i { 1 => migrate_doors(obj), + 2 => migrate_layout_annotations(obj), _ => obj, // 0 → 1: Einführung von `formatVersion`; Inhalt unverändert. }; } @@ -321,7 +460,7 @@ mod tests { fn alte_datei_wird_migriert_und_ergaenzt() { let Parsed::Ok { project, warnings, migrated_from } = parse_project_object(minimal(), 0.0) else { panic!() }; assert_eq!(migrated_from, Some(0)); - assert_eq!(project["formatVersion"], 2); + assert_eq!(project["formatVersion"], 3); assert_eq!(project["lineStyles"], json!([])); assert!(warnings.is_empty()); } @@ -362,6 +501,51 @@ mod tests { assert_eq!(o[2]["id"], "O1-t"); } + #[test] + fn layout_annotationen_werden_blatt_zeichnungen() { + let mut v = minimal(); + v["formatVersion"] = json!(2); + v["layers"] = json!([{"code": "20", "children": [{"code": "50"}]}]); + v["drawings2d"] = json!([{"id": "a1", "levelId": "eg"}]); + v["layouts"] = json!([ + {"id": "L1", "name": "Blatt 1", "paper": "a3", "orientation": "landscape", "viewports": [], "annotations": [ + {"kind": "line", "id": "a1", "x1Mm": 10, "y1Mm": 20, "x2Mm": 110, "y2Mm": 20, "weightMm": 0.5}, + {"kind": "rect", "id": "a2", "xMm": 10, "yMm": 20, "widthMm": 50, "heightMm": 30, "color": "#ff0000"}, + {"kind": "text", "id": "a3", "xMm": 5, "yMm": 7, "text": "Hallo", "heightMm": 3.5, "widthMm": 40}, + {"kind": "image", "id": "a4", "xMm": 0, "yMm": 0, "widthMm": 20, "heightMm": 10, "src": "data:image/png;base64,AA", "opacity": 0.5}, + {"kind": "line", "id": "kaputt", "x1Mm": "x"} + ]}, + {"id": "L2", "name": "Blatt 2", "paper": "a4", "orientation": "portrait", "viewports": []} + ]); + let Parsed::Ok { project, migrated_from, .. } = parse_project_object(v, 0.0) else { panic!() }; + assert_eq!(migrated_from, Some(2)); + assert!(project["layouts"][0].get("annotations").is_none()); + let levels = project["drawingLevels"].as_array().unwrap(); + assert_eq!(levels.len(), 2, "jedes Layout bekommt seine Blatt-Ebene"); + assert_eq!(levels[0], json!({"id": "sheet-L1", "name": "Blatt 1", "kind": "drawing", "visible": true, "locked": false, "layoutId": "L1"})); + assert_eq!(levels[1]["layoutId"], "L2"); + let d = project["drawings2d"].as_array().unwrap(); + assert_eq!(d.len(), 5, "kaputte Annotation fällt weg"); + assert_eq!(d[1]["id"], "a1-a", "ID-Kollision mit bestehender Zeichnung"); + assert_eq!(d[1]["levelId"], "sheet-L1"); + assert_eq!(d[1]["categoryCode"], "50"); + assert_eq!(d[1]["geom"], json!({"shape": "line", "a": {"x": 0.01, "y": -0.02}, "b": {"x": 0.11, "y": -0.02}})); + assert_eq!(d[1]["weightMm"], 0.5); + assert_eq!(d[2]["geom"], json!({"shape": "rect", "min": {"x": 0.01, "y": -0.05}, "max": {"x": 0.06, "y": -0.02}})); + assert_eq!(d[2]["color"], "#ff0000"); + assert_eq!(d[3]["geom"]["at"], json!({"x": 0.005, "y": -0.007})); + assert_eq!(d[3]["geom"]["height"], 0.0035); + assert_eq!(d[3]["geom"]["width"], 0.04); + assert_eq!(d[4]["geom"]["src"], "data:image/png;base64,AA"); + assert_eq!(d[4]["geom"]["max"]["x"], 0.02); + assert_eq!(d[4]["geom"]["min"]["y"], -0.01); + // Schon migriert: ein zweiter Lauf ändert nichts mehr. + let mut again = project.clone(); + again.insert("formatVersion".into(), json!(2)); + let Parsed::Ok { project: p2, .. } = parse_project_object(Value::Object(again), 0.0) else { panic!() }; + assert_eq!(p2, project); + } + #[test] fn unbekannte_felder_bleiben_und_werden_gemeldet() { let mut v = minimal(); @@ -420,6 +604,6 @@ mod tests { fn serialisierung_setzt_version_nach_vorn() { let Value::Object(m) = minimal() else { panic!() }; let s = serialize_project(&m); - assert!(s.starts_with("{\n \"formatVersion\": 2,\n \"id\": \"p\"")); + assert!(s.starts_with("{\n \"formatVersion\": 3,\n \"id\": \"p\"")); } } diff --git a/src/App.tsx b/src/App.tsx index b5a9d931..77a5829d 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -27,6 +27,7 @@ import type { Drawing2D, DrawingLevel, Layout, + LayoutViewport, Project, Roof, Vec2, @@ -78,16 +79,18 @@ import { } from "./viewport/grip3dHud"; import { ResourceManager } from "./ui/ResourceManager"; import type { ResourceManagerHandlers, TabId as ResourceTabId } from "./ui/ResourceManager"; -import { LayoutSheetView } from "./ui/LayoutSheet"; import { createViewport, - createAnnotation, + createSheetLevel, + effectiveSheetSizeMm, + findMaster, + isSheetLevel, + sheetMmToModel, + sheetLevelOf, + SHEET_SCALE_DENOMINATOR, addViewport as addViewportToLayout, removeViewport as removeViewportFromLayout, patchViewport as patchViewportInLayout, - addAnnotation as addAnnotationToLayout, - removeAnnotation as removeAnnotationFromLayout, - patchAnnotation as patchAnnotationInLayout, } from "./model/layoutModel"; import { HatchSwatch } from "./ui/hatchPreview"; import { TopBar, ViewRibbonTab } from "./ui/TopBar"; @@ -511,13 +514,6 @@ export default function App() { setEditTextMinHeightM, } = useContextMenuState(); - // Gewählte Annotation auf einem offenen Layout-Blatt (Linie/Rechteck/Text/ - // Bild) — gehoben aus LayoutSheetView, damit die Attribute-Palette (rechtes - // Panel) dieselbe Auswahl sieht wie ein Drawing2D im Grundriss. - const [selectedLayoutAnnotationId, setSelectedLayoutAnnotationId] = useState( - null, - ); - // Beim Geschosswechsel die Wand-Auswahl + offene Overlays zurücksetzen (die // Wände eines anderen Geschosses sind eine andere Menge). Der Ansichtswechsel // (Grundriss ↔ 3D) lässt die Auswahl bestehen — dieselbe wallId gilt in @@ -602,6 +598,8 @@ export default function App() { const activeLevel = project.drawingLevels.find((z) => z.id === activeLevelId) ?? project.drawingLevels[0]; + // Massstab der Arbeitsebene: auf einem Blatt Papier 1:1, sonst der gewählte Plan-Massstab. + const planScale = isSheetLevel(activeLevel) ? SHEET_SCALE_DENOMINATOR : scaleDenominator; // Sichtbare Kategorie-Codes — Basisfilter für Grundriss & 3D. const visibleCodes = useMemo( @@ -1041,24 +1039,10 @@ export default function App() { // Ein Klick auf ein gekoppeltes Zeichen-Werkzeug (Wand/Linie/Rechteck/Polylinie) // STARTET den passenden Befehl in der Engine und fokussiert das Befehlsfeld // („Dialog drin"). „Auswahl" beendet einen laufenden Befehl (Auswahl-Modus). - // Zeichenwerkzeuge, die auf einem offenen Layout-Blatt sinnvoll sind (Markups - // in Papier-mm, s. LayoutSheet.tsx `annotToolFromGlobal`) — dieselben Tool-IDs - // wie im Grundriss, KEIN eigenes Werkzeug nur fürs Layout (Nutzer-Feedback). - const LAYOUT_ANNOT_TOOLS: ToolId[] = ["line", "rect", "text", "textbox", "image"]; - const onSelectTool = (id: ToolId) => { // Erneuter Klick auf das bereits AKTIVE Werkzeug schaltet zurück auf // „Auswahl" (Nutzer-Wunsch) — statt das Werkzeug einfach neu zu starten. if (id !== "select" && id === activeTool) id = "select"; - if (activeLayout) { - // Ein Layout-Blatt ist offen: PlanView/die Befehls-Engine haben keinen - // sichtbaren Canvas (LayoutSheetView ersetzt die Mitte) — Zeichenwerkzeuge - // wertet dort `activeTool` direkt aus (Klick + ggf. Datei-Dialog fürs - // Bild), alles andere (Wand/Raum/… — auf dem Blatt ohne Bedeutung) fällt - // auf „Auswahl" zurück statt eine Befehls-Engine ohne Canvas zu starten. - setActiveTool(LAYOUT_ANNOT_TOOLS.includes(id) ? id : "select"); - return; - } if (id === "image") { // Datei-Auswahl ist async (Dateidialog) — kein Klick-Platzieren wie bei // den übrigen Zeichen-Werkzeugen, daher hier abgefangen statt über die @@ -1753,7 +1737,7 @@ export default function App() { modelEditable: activeLevel.kind !== "section" && activeLevel.kind !== "elevation", sheet: sectionSheet, visibleCodes, - scaleDenominator, + scaleDenominator: planScale, snap, setDraft, snapFor, @@ -1864,16 +1848,6 @@ export default function App() { planViewRef, ); - // Gewählte Layout-Annotation als echtes Objekt (statt nur ihrer Id) — liegt - // in `Layout.annotations` (Papier-mm), NICHT im Modell, daher separat von - // `deriveSelection` (die nur Projekt-Bauteile kennt) aufgelöst. Muss VOR - // `textTarget`/`selection` stehen (beide lesen sie synchron im selben Render). - const selectedLayoutAnnotation = useMemo(() => { - if (activeLayoutId === null || !selectedLayoutAnnotationId) return null; - const layout = (project.layouts ?? []).find((l) => l.id === activeLayoutId); - return layout?.annotations?.find((a) => a.id === selectedLayoutAnnotationId) ?? null; - }, [project.layouts, activeLayoutId, selectedLayoutAnnotationId]); - // Text-Ziel der Oberleisten-Text-Gruppe: der Stempel-Text des (einzeln) // gewählten Raums. Ohne aktive Editor-Auswahl wirkt Formatierung auf das ganze // Doc (range: null). Ist kein Raum gewählt → null (Controls setzen nur @@ -1914,21 +1888,6 @@ export default function App() { }; } } - // Ausgewähltes Text-Markup auf einem offenen Layout-Blatt: wie Raum-Stempel - // OHNE Grössen-Kopplung ans Modell (Papier-mm-Kontext, `heightMm` ist bereits - // der Basiswert für Runs ohne eigene `sizePt`) — die Oberleisten-Grösse - // wirkt hier also normal, anders als bei freiem Grundriss-Text oben. - if (selectedLayoutAnnotation && selectedLayoutAnnotation.kind === "text" && activeLayoutId !== null) { - const ann = selectedLayoutAnnotation; - return { - doc: ann.doc ?? docFromText(ann.text), - range: null, - apply: (newDoc: RichTextDoc) => - patchOpenLayout(activeLayoutId, (l) => - patchAnnotationInLayout(l, ann.id, { doc: newDoc, text: plainText(newDoc) }), - ), - }; - } return null; }, [ selectedRoom, @@ -1936,8 +1895,6 @@ export default function App() { selectedDrawingId, project.drawings2d, updateDrawing2D, - selectedLayoutAnnotation, - activeLayoutId, ]); // ── 3D-Editier-Griffe (direkt im Viewport3D) ────────────────────────────── @@ -2287,26 +2244,7 @@ export default function App() { // ── Selektions-Attribut-Kontrakt (Attributes-/Object-Info-Paletten) ─────── // Normalisierte, effektiv aufgelöste Sicht auf das erste selektierte Element. - // Eine gewählte Layout-Annotation hat Vorrang (eigener, minimaler Zweig — - // sie ist kein Projekt-Bauteil, `deriveSelection` kennt sie nicht): Farbe - // (Linie/Rechteck/Text) + Strichstärke (nur Linie/Rechteck, s. `annotKind`- - // Prüfung in AttributesPanel) landen so in DERSELBEN Palette wie ein - // Drawing2D im Grundriss (Nutzer-Feedback). const selection = useMemo((): Selection | null => { - if (selectedLayoutAnnotation) { - const a = selectedLayoutAnnotation; - return { - kind: "layoutAnnotation", - annotKind: a.kind, - id: a.id, - categoryCode: "", - color: ("color" in a ? a.color : undefined) ?? "#111111", - weightMm: ("weightMm" in a ? a.weightMm : undefined) ?? 0.25, - isImage: a.kind === "image", - opacity: a.kind === "image" ? a.opacity ?? 1 : undefined, - bbox: { minX: 0, minY: 0, maxX: 0, maxY: 0 }, - }; - } return deriveSelection( project, selectedWallIds, @@ -2321,7 +2259,6 @@ export default function App() { selectedContextObjectIds.length === 1 ? selectedContextObjectIds[0] : null, ); }, [ - selectedLayoutAnnotation, project, selectedWallIds, selectedDrawingId, @@ -2643,6 +2580,60 @@ export default function App() { const patchOpenLayout = (id: string, fn: (l: Layout) => Layout, coalesceKey?: string) => applyChange((p) => patchItem(p, "layouts", id, fn), coalesceKey); + // Ein offenes Blatt IST eine Zeichnungsebene: seine Blatt-Ebene (`layoutId`) wird die aktive Ebene, + // damit Werkzeuge, Befehle, Fang, Griffe, Auswahl und Undo genau wie im Grundriss wirken. Beim + // Schliessen kehrt die vorige Ebene zurück; wählt man im Navigator eine andere Ebene, schliesst + // das Blatt. + const sheetLevel = activeLayout ? sheetLevelOf(project, activeLayout.id) : undefined; + const levelBeforeSheetRef = useRef(null); + const enteredSheetRef = useRef(null); + useEffect(() => { + const current = project.drawingLevels.find((l) => l.id === activeLevelId); + if (activeLayout) { + if (!sheetLevel) { + // Layout ohne Blatt-Ebene (z. B. per CLI angelegt): einmal nachtragen. + applyChange(addItems("drawingLevels", [createSheetLevel(`sheet-${activeLayout.id}`, activeLayout)])); + return; + } + if (activeLevelId === sheetLevel.id) { + enteredSheetRef.current = activeLayout.id; + return; + } + if (enteredSheetRef.current === activeLayout.id) { + enteredSheetRef.current = null; + setActiveLayoutId(null); + return; + } + if (current && !isSheetLevel(current)) levelBeforeSheetRef.current = current.id; + setActiveLevelId(sheetLevel.id); + return; + } + enteredSheetRef.current = null; + if (current && !isSheetLevel(current)) return; + const back = + project.drawingLevels.find((l) => l.id === levelBeforeSheetRef.current && !isSheetLevel(l)) ?? + project.drawingLevels.find((l) => !isSheetLevel(l)); + if (back && back.id !== activeLevelId) setActiveLevelId(back.id); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [activeLayout?.id, sheetLevel?.id, activeLevelId]); + const sheetPane = + activeLayout && sheetLevel && activeLevelId === sheetLevel.id + ? { + layout: activeLayout, + handlers: { + onBack: () => setActiveLayoutId(null), + onPatchViewport: (viewportId: string, patch: Partial>) => + patchOpenLayout(activeLayout.id, (l) => patchViewportInLayout(l, viewportId, patch)), + onRemoveViewport: (viewportId: string) => + patchOpenLayout(activeLayout.id, (l) => removeViewportFromLayout(l, viewportId)), + onAddViewport: (snapshotId: string, init: Partial>) => + patchOpenLayout(activeLayout.id, (l) => + addViewportToLayout(l, createViewport(`vp-${Date.now()}`, snapshotId, init)), + ), + }, + } + : null; + // ── Effektive Darstellung für die Hauptansicht ──────────────────────────── // 3D: Geschosse nach dem Modus des Zeichnungsebenen-Panels, Kategorien nach // dem Modus des Ebenen-Panels. Grundriss: Kategorien nach dem Ebenen-Panel. @@ -2665,8 +2656,13 @@ export default function App() { const visible = new Map( project.drawingLevels.map((z) => [z.id, z.visible]), ); + // Blatt-Ebenen stehen für sich: nur sichtbar, wenn ihr Blatt offen ist, und dann allein. + const sheets = new Set(project.drawingLevels.filter(isSheetLevel).map((z) => z.id)); + const onSheet = sheets.has(activeLevelId); return (id) => - itemDisplay(drawingLevelsMode, id === activeLevelId, visible.get(id) ?? false); + onSheet || sheets.has(id) + ? { render: id === activeLevelId, greyed: false, locked: false } + : itemDisplay(drawingLevelsMode, id === activeLevelId, visible.get(id) ?? false); }, [project.drawingLevels, drawingLevelsMode, activeLevelId]); // Resolver: je Kategorie-Code die Render-Entscheidung. „Aktiv" = die per @@ -2767,7 +2763,7 @@ export default function App() { // bewusst nicht mitgenommen). useDrawingLevelsWindowHost( { - drawingLevels: project.drawingLevels, + drawingLevels: project.drawingLevels.filter((z) => !z.layoutId), activeLevelId, displayMode: drawingLevelsMode, }, @@ -3066,6 +3062,14 @@ export default function App() { const { onImageOrPdfFileChosen } = useImageImportHandling({ activeLevelId: activeLevel.id, activeCategoryCode, + // Auf einem Blatt: 60 mm breit, mitten aufs Papier. + imagePlacement: sheetPane + ? (() => { + const m = findMaster(project, sheetPane.layout); + const size = effectiveSheetSizeMm(m ?? sheetPane.layout); + return { widthM: 0.06, center: sheetMmToModel(size.w / 2, size.h / 2) }; + })() + : undefined, applyChange, notify, setSelectedDrawingId, @@ -3113,8 +3117,6 @@ export default function App() { openSettings, onOpenStampEditor, openResources, - activeLayout, - patchOpenLayout, dxfInputRef, planViewRef, selection, @@ -3499,69 +3501,13 @@ export default function App() { Befehlszeile nur so breit wie der Viewport (nicht die ganze App), und die Docks nehmen die volle Body-Höhe ein (inkl. der Zeile). */}
- {activeLayout ? ( - /* Layout-Modus (Phase 2b): das Blatt füllt den Haupt-Viewport (statt - Grundriss/3D) und ist direkt mit der Maus editierbar — platzieren/ - verschieben/skalieren/löschen der Viewports, Pan/Zoom, mm↔Bildschirm. - Die Befehlszeile entfällt (kein Zeichnen auf dem Blatt). */ - { - setActiveLayoutId(null); - setSelectedLayoutAnnotationId(null); - // Ein auf dem Blatt armiertes Zeichenwerkzeug (line/rect/text/ - // image) hat im Grundriss KEINEN laufenden Befehl in der Engine - // (der wird für ein offenes Layout bewusst nicht gestartet, s. - // `onSelectTool`) — zurück auf „Auswahl", sonst zeigt das - // Werkzeugpanel ein „aktives" Werkzeug ohne echten Befehl dahinter. - setActiveTool("select"); - }, - onPatchViewport: (viewportId, patch) => - patchOpenLayout(activeLayout.id, (l) => - patchViewportInLayout(l, viewportId, patch), - ), - onRemoveViewport: (viewportId) => - patchOpenLayout(activeLayout.id, (l) => - removeViewportFromLayout(l, viewportId), - ), - onAddViewport: (snapshotId, init) => - patchOpenLayout(activeLayout.id, (l) => - addViewportToLayout( - l, - createViewport(`vp-${Date.now()}`, snapshotId, init), - ), - ), - onAddAnnotation: (kind, init) => { - const id = `ann-${Date.now()}`; - patchOpenLayout(activeLayout.id, (l) => - addAnnotationToLayout(l, createAnnotation(id, kind, init)), - ); - return id; - }, - onPatchAnnotation: (annotationId, patch, coalesceKey) => - patchOpenLayout( - activeLayout.id, - (l) => patchAnnotationInLayout(l, annotationId, patch), - coalesceKey, - ), - onRemoveAnnotation: (annotationId) => - patchOpenLayout(activeLayout.id, (l) => - removeAnnotationFromLayout(l, annotationId), - ), - }} - /> - ) : ( + {( <> {/* Hauptansicht (Mitte) — füllt den verbleibenden Platz. Die Plan- Ansicht meldet Cursor + Zoom an die Status-/Oberleiste und nimmt das Zoom-Handle entgegen. */} kinds.includes(l.kind)); + const levels = project.drawingLevels.filter((l) => kinds.includes(l.kind) && !l.layoutId); if (!name) return levels[0]; const n = name.toLowerCase(); return levels.find((l) => l.id.toLowerCase() === n || l.name.toLowerCase() === n); diff --git a/src/commands/createCore.ts b/src/commands/createCore.ts index 354e5304..25325f03 100644 --- a/src/commands/createCore.ts +++ b/src/commands/createCore.ts @@ -18,13 +18,17 @@ export interface CreatePreview { info: number[]; } -/** Kontext der Anfrage: aktive Ebene/Geschoss, Kategorie, Wandtyp. */ +/** Schrifthöhe neuer Texte auf einem Layout-Blatt (Papier 1:1): 3.5 mm. */ +export const SHEET_TEXT_HEIGHT_M = 0.0035; + +/** Kontext der Anfrage: aktive Ebene/Geschoss, Kategorie, Wandtyp (auf einem Blatt: Papier-Schrifthöhe). */ function ctxReq(ctx: CommandContext): object { return { level: ctx.level.id, floorHeight: ctx.level.floorHeight ?? null, cat: ctx.defaultCategoryCode, wallType: ctx.activeWallTypeId, + ...(ctx.level.layoutId ? { textHeight: SHEET_TEXT_HEIGHT_M } : {}), }; } diff --git a/src/export/layoutPdf.ts b/src/export/layoutPdf.ts index a1f04b8f..39b0094b 100644 --- a/src/export/layoutPdf.ts +++ b/src/export/layoutPdf.ts @@ -12,17 +12,19 @@ import { jsPDF } from "jspdf"; import "svg2pdf.js"; -import type { Layout, LayoutAnnotation, MasterLayout, Project } from "../model/types"; +import type { Layout, MasterLayout, Project } from "../model/types"; import { generatePlan } from "../plan/generatePlan"; import { planToPrintSvg } from "./planToPrintSvg"; -import { annotationTextLines } from "../text/renderHtml"; -import { docFromText } from "../text/richText"; +import { collectVisibleCodes } from "../model/types"; import { findMaster, findSnapshot, folderPdfPages, resolveTitleBlock, resolveViewportScale, + SHEET_SCALE_DENOMINATOR, + sheetLevelOf, + sheetMmToModel, visibleCodesFromSnapshot, type FolderPdfPage, type ResolvedTitleBlock, @@ -79,110 +81,36 @@ function clip(s: string, max: number): string { return s.length > max ? s.slice(0, max - 1) + "…" : s; } -/** "#rrggbb"/"#rgb" → [r,g,b] (0..255); ungültige Eingabe fällt auf Tinte zurück. */ -function hexToRgb(hex: string): [number, number, number] { - const h = hex.replace("#", "").trim(); - const full = h.length === 3 ? h.split("").map((c) => c + c).join("") : h; - const n = parseInt(full, 16); - if (full.length !== 6 || !Number.isFinite(n)) return [17, 17, 17]; - return [(n >> 16) & 255, (n >> 8) & 255, n & 255]; -} - -/** Bildformat aus dem MIME-Teil der Data-URL ableiten (jsPDF `addImage` braucht es explizit). */ -function imageFormatFromDataUrl(src: string): string { - const ext = (/^data:image\/(\w+)/i.exec(src)?.[1] ?? "png").toLowerCase(); - if (ext === "jpg" || ext === "jpeg") return "JPEG"; - if (ext === "webp") return "WEBP"; - return "PNG"; -} - -const SVG_NS = "http://www.w3.org/2000/svg"; - /** - * Baut EIN Mini-SVG (Blattgrösse) mit allen Text-Markups einer Seite — reiche - * Docs (mehrere Absätze/gemischte Formatierung) + Wortumbruch bei gesetzter - * Rahmenbreite, exakt wie `LayoutSheet.tsx`s `AnnotationSvg`. Ein gemeinsamer - * `doc.svg()`-Aufruf statt einem je Annotation (einfacher, ein Layout-Pass). - * `null`, wenn die Seite keine Text-Markups trägt. + * Die 2D-Zeichnung des Blatts (Blatt-Ebene, `DrawingLevel.layoutId`) über Viewports und Master: + * derselbe Plan wie am Bildschirm (`generatePlan`, Massstab 1:1, Export-Modus), über + * `planToPrintSvg` fest aufs Papier gelegt (Ursprung oben links), ohne eigenes weisses Blatt. */ -function buildAnnotationTextsSvg( - annotations: LayoutAnnotation[], - sheetW: number, - sheetH: number, -): SVGSVGElement | null { - const texts = annotations.filter( - (a): a is Extract => a.kind === "text", +async function renderSheetDrawing(doc: jsPDF, project: Project, layout: Layout, widthMm: number, heightMm: number): Promise { + const level = sheetLevelOf(project, layout.id); + if (!level || !project.drawings2d.some((d) => d.levelId === level.id)) return; + const a = sheetMmToModel(0, heightMm); + const b = sheetMmToModel(widthMm, 0); + const plan = generatePlan( + project, + level.id, + collectVisibleCodes(project.layers), + undefined, + "fein", + false, + false, + false, + SHEET_SCALE_DENOMINATOR, + true, ); - if (texts.length === 0) return null; - - const svg = document.createElementNS(SVG_NS, "svg") as SVGSVGElement; - svg.setAttribute("xmlns", SVG_NS); - svg.setAttribute("width", String(sheetW)); - svg.setAttribute("height", String(sheetH)); - svg.setAttribute("viewBox", `0 0 ${sheetW} ${sheetH}`); - - for (const ann of texts) { - const el = document.createElementNS(SVG_NS, "text"); - for (const line of annotationTextLines(ann, ann.doc ?? docFromText(ann.text))) { - const lineTspan = document.createElementNS(SVG_NS, "tspan"); - lineTspan.setAttribute("x", String(line.x)); - lineTspan.setAttribute("y", String(line.y)); - lineTspan.setAttribute("text-anchor", line.anchor); - if (line.tspans.length === 0) { - lineTspan.textContent = "​"; - } else { - for (const ts of line.tspans) { - const run = document.createElementNS(SVG_NS, "tspan"); - run.setAttribute("font-size", String(ts.fontSize)); - run.setAttribute("fill", ts.fill); - if (ts.fontWeight) run.setAttribute("font-weight", ts.fontWeight); - if (ts.fontStyle) run.setAttribute("font-style", ts.fontStyle); - run.setAttribute("font-family", ts.fontFamily ?? "Helvetica, Arial, sans-serif"); - if (ts.textDecoration) run.setAttribute("text-decoration", ts.textDecoration); - run.textContent = ts.text; - lineTspan.appendChild(run); - } - } - el.appendChild(lineTspan); - } - svg.appendChild(el); - } - return svg; -} - -/** - * Zeichnet die 2D-Markups (Linie/Rechteck/Bild) EINER Seite direkt via jsPDF- - * Vektorprimitive — dieselbe Schicht wie `LayoutSheet.tsx`s Annotations-SVG, - * hier aber ÜBER Viewports UND Master gezeichnet (Aufrufreihenfolge in - * `renderPage`), analog zur Zeichenreihenfolge im In-Viewport-Editor. - */ -function drawAnnotationShapes(doc: jsPDF, layout: Layout): void { - for (const ann of layout.annotations ?? []) { - if (ann.kind === "line") { - const [r, g, b] = hexToRgb(ann.color ?? "#111111"); - doc.setDrawColor(r, g, b); - doc.setLineWidth(ann.weightMm ?? 0.25); - doc.line(ann.x1Mm, ann.y1Mm, ann.x2Mm, ann.y2Mm); - } else if (ann.kind === "rect") { - const [r, g, b] = hexToRgb(ann.color ?? "#111111"); - doc.setDrawColor(r, g, b); - doc.setLineWidth(ann.weightMm ?? 0.25); - doc.rect(ann.xMm, ann.yMm, ann.widthMm, ann.heightMm); - } else if (ann.kind === "image" && ann.widthMm > 0 && ann.heightMm > 0 && ann.src) { - try { - doc.addImage( - ann.src, - imageFormatFromDataUrl(ann.src), - ann.xMm, - ann.yMm, - ann.widthMm, - ann.heightMm, - ); - } catch { - // Defekte/leere Data-URL überspringt nur dieses Bild, nicht die Seite. - } - } - } + const print = planToPrintSvg(plan, { + scaleDenominator: SHEET_SCALE_DENOMINATOR, + pageWidthMm: widthMm, + pageHeightMm: heightMm, + bounds: { minX: a.x, minY: a.y, maxX: b.x, maxY: b.y }, + transparent: true, + }); + await doc.svg(print.svg, { x: 0, y: 0, width: widthMm, height: heightMm }); } /** Zeichnet die Viewports + Master-Elemente EINER Seite in das jsPDF-Dokument. */ @@ -242,16 +170,11 @@ async function renderPage( drawTitleBlock(doc, widthMm, heightMm, tb, layout.paper, layout.orientation); } - // 2D-Markups (Linie/Rechteck/Bild/Text) — ÜBER Viewports + Master, wie im - // In-Viewport-Editor (LayoutSheet.tsx). Fehlte bisher komplett im Export. - drawAnnotationShapes(doc, layout); - const textsSvg = buildAnnotationTextsSvg(layout.annotations ?? [], widthMm, heightMm); - if (textsSvg) { - try { - await doc.svg(textsSvg, { x: 0, y: 0, width: widthMm, height: heightMm }); - } catch { - // Rich-Text-Rendering eines Markups darf die Seite nicht killen. - } + // 2D-Zeichnung des Blatts — ÜBER Viewports + Master, wie am Bildschirm. + try { + await renderSheetDrawing(doc, project, layout, widthMm, heightMm); + } catch { + // Eine Blatt-Zeichnung, die nicht rendert, darf die Seite nicht killen. } } diff --git a/src/export/planToPrintSvg.sheet.test.ts b/src/export/planToPrintSvg.sheet.test.ts new file mode 100644 index 00000000..15cb498c --- /dev/null +++ b/src/export/planToPrintSvg.sheet.test.ts @@ -0,0 +1,99 @@ +// Blatt-Zeichnung im Layout-PDF: die Blatt-Ebene eines Layouts (`DrawingLevel.layoutId`, Papier 1:1 in +// Metern) liegt über `planToPrintSvg` mit festem Bereich genau auf dem Papier — Ursprung oben links, +// Strichstärken unverändert (auch mit `scaleLineWeights`), ohne weisses Blatt dahinter. + +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { generatePlan } from "../plan/generatePlan"; +import { sampleProject } from "../model/sampleProject"; +import { collectVisibleCodes, type Project } from "../model/types"; +import { createSheetLevel, sheetMmToModel, SHEET_SCALE_DENOMINATOR } from "../model/layoutModel"; +import { planToPrintSvg } from "./planToPrintSvg"; + +interface El { + tag: string; + attrs: Map; + kids: El[]; + textContent: string; + setAttribute(k: string, v: unknown): void; + getAttribute(k: string): string | null; + appendChild(c: El): El; + insertBefore(n: El, r: El | null): El; + readonly firstChild: El | null; +} + +function el(tag: string): El { + return { + tag, + attrs: new Map(), + kids: [], + textContent: "", + setAttribute(k, v) { + this.attrs.set(k, String(v)); + }, + getAttribute(k) { + return this.attrs.get(k) ?? null; + }, + appendChild(c) { + this.kids.push(c); + return c; + }, + insertBefore(n) { + this.kids.unshift(n); + return n; + }, + get firstChild() { + return this.kids[0] ?? null; + }, + }; +} + +const all = (e: El): El[] => [e, ...e.kids.flatMap(all)]; + +const sheet = createSheetLevel("blatt", { id: "L1", name: "Blatt 1" }); +const a = sheetMmToModel(10, 20); +const b = sheetMmToModel(110, 20); +const project: Project = { + ...sampleProject, + scaleLineWeights: true, + drawingLevels: [...sampleProject.drawingLevels, sheet], + drawings2d: [ + ...sampleProject.drawings2d, + { id: "s1", type: "drawing2d", levelId: "blatt", categoryCode: "20", geom: { shape: "line", a, b }, weightMm: 0.5, color: "#ff0000" }, + ] as Project["drawings2d"], +}; + +describe("Druck-SVG der Blatt-Ebene", () => { + let prev: unknown; + beforeAll(() => { + const g = globalThis as { document?: unknown }; + prev = g.document; + g.document = { createElementNS: (_: string, tag: string) => el(tag) }; + }); + afterAll(() => { + (globalThis as { document?: unknown }).document = prev; + }); + + it("liegt mm-genau auf dem Papier, Stärke 1:1, ohne weisses Blatt", () => { + const plan = generatePlan(project, "blatt", collectVisibleCodes(project.layers), undefined, "fein", false, false, false, SHEET_SCALE_DENOMINATOR, true); + // Nur die Blatt-Zeichnung: keine Wände des Geschosses, keine projektglobalen Zutaten. + expect(plan.primitives.every((p) => !("wallId" in p && p.wallId))).toBe(true); + const lo = sheetMmToModel(0, 297); + const hi = sheetMmToModel(210, 0); + const print = planToPrintSvg(plan, { + scaleDenominator: SHEET_SCALE_DENOMINATOR, + pageWidthMm: 210, + pageHeightMm: 297, + bounds: { minX: lo.x, minY: lo.y, maxX: hi.x, maxY: hi.y }, + transparent: true, + }); + const svg = print.svg as unknown as El; + expect(svg.kids.some((k) => k.tag === "rect" && k.getAttribute("fill") === "#ffffff")).toBe(false); + const red = all(svg).filter((e) => e.getAttribute("stroke") === "#ff0000"); + expect(red.length).toBeGreaterThan(0); + const geo = red.map((e) => e.getAttribute("points") ?? `${e.getAttribute("x1")},${e.getAttribute("y1")} ${e.getAttribute("x2")},${e.getAttribute("y2")}`).join(" "); + const nums = geo.split(/[\s,]+/).map(Number); + expect(nums).toHaveLength(4); + [10, 20, 110, 20].forEach((v, i) => expect(nums[i]).toBeCloseTo(v, 6)); + expect(Number(red[0].getAttribute("stroke-width"))).toBeCloseTo(0.5, 9); + }); +}); diff --git a/src/export/planToPrintSvg.ts b/src/export/planToPrintSvg.ts index 19e0f048..730ca814 100644 --- a/src/export/planToPrintSvg.ts +++ b/src/export/planToPrintSvg.ts @@ -100,6 +100,13 @@ export interface PrintSvgOptions { pageHeightMm: number; /** Rand um den Plan-Inhalt in mm (weisser Blattrand). */ marginMm?: number; + /** + * Fester Modell-Bereich, der das Blatt füllt (statt den Inhalt zu zentrieren) — die Blatt-Ebene + * eines Layouts liegt so genau auf dem Papier (Ursprung oben links, s. `DrawingLevel.layoutId`). + */ + bounds?: { minX: number; minY: number; maxX: number; maxY: number }; + /** Ohne weisses Blatt dahinter (als Schicht über anderem Inhalt). */ + transparent?: boolean; } /** Modell-Meter → Papier-Millimeter im Massstab 1:N. */ @@ -120,7 +127,7 @@ export function planToPrintSvg(plan: Plan, opts: PrintSvgOptions): PrintSvg { // bewusst, ohne ihn aktuell für einen Versatz zu nutzen (zentrierte Lage). void (opts.marginMm ?? 10); - const b = plan.bounds; + const b = opts.bounds ?? plan.bounds; // Inhalts-Maße in mm (massstäblich), unverschoben. const contentWmm = (b.maxX - b.minX) * k; const contentHmm = (b.maxY - b.minY) * k; @@ -151,7 +158,7 @@ export function planToPrintSvg(plan: Plan, opts: PrintSvgOptions): PrintSvg { bg.setAttribute("width", String(opts.pageWidthMm)); bg.setAttribute("height", String(opts.pageHeightMm)); bg.setAttribute("fill", "#ffffff"); - svg.appendChild(bg); + if (!opts.transparent) svg.appendChild(bg); // Jedes Primitiv in mm-Knoten übersetzen (Kern, Anweisungsliste s. `plan_print_svg.rs`). const o = Float64Array.of(n, opts.pageWidthMm, opts.pageHeightMm, b.minX, b.minY, b.maxX, b.maxY); diff --git a/src/i18n/de.ts b/src/i18n/de.ts index 427278b1..fcefb9db 100644 --- a/src/i18n/de.ts +++ b/src/i18n/de.ts @@ -435,8 +435,6 @@ export const de = { "objinfo.kind.column": "Stütze", "objinfo.kind.roof": "Dach", "objinfo.kind.contextObject": "Kontext-Objekt", - "objinfo.kind.layoutAnnotation": "Blatt-Markup", - "objinfo.layoutAnnotationHint": "Position/Grösse in mm direkt am Rahmen auf dem Blatt bearbeiten (Greifpunkte oder die Felder dort).", // ── Kontext-Objekt-Attribute (Object-Info-Panel) ──────────────────────── "objinfo.contextObject.section": "Georeferenzierung", "objinfo.contextObject.type": "Art", @@ -2427,7 +2425,6 @@ export const de = { // Editor "layouts.editorTitle": "Layout-Editor", "layouts.fit": "Einpassen", - "layouts.zoom100": "Echte Grösse (100 %, 1:1 auf dem Bildschirm)", "layouts.addViewport": "Viewport hinzufügen", "layouts.pickSnapshot": "Ausschnitt wählen …", "layouts.noSnapshots": "Keine Ausschnitte vorhanden. Zuerst einen Ausschnitt speichern.", @@ -2446,23 +2443,9 @@ export const de = { "layouts.placeViewport": "Viewport aufziehen", "layouts.placeHint": "Rechteck auf dem Blatt aufziehen, dann Ausschnitt binden.", "layouts.bindSnapshot": "Ausschnitt binden", - "layouts.emptyViewports": - "Noch keine Viewports. „Viewport aufziehen\" wählen und ein Rechteck auf dem Blatt ziehen.", // Annotationen (Linie/Rechteck/Text/Bild) direkt auf dem Blatt — gezeichnet // mit denselben Werkzeugen wie im Grundriss (linkes Werkzeugpanel), kein // eigenes Werkzeug nur fürs Layout. - "layouts.annotTextTitle": "Text", - "layouts.annotTextLabel": "Textinhalt:", - "layouts.annotEditText": "Text ändern", - "layouts.annotRemove": "Annotation entfernen", - "layouts.annotX": "X (mm)", - "layouts.annotY": "Y (mm)", - "layouts.annotWidth": "Breite (mm)", - "layouts.annotHeight": "Höhe (mm)", - "layouts.annot.line": "Linie", - "layouts.annot.rect": "Rechteck", - "layouts.annot.text": "Text", - "layouts.annot.image": "Bild", // Baum / „+"-Menü / Ordner "layouts.add": "Neu …", "layouts.addFolder": "Ordner erstellen", diff --git a/src/i18n/en.ts b/src/i18n/en.ts index 4229b486..3913db35 100644 --- a/src/i18n/en.ts +++ b/src/i18n/en.ts @@ -433,8 +433,6 @@ export const en: Record = { "objinfo.kind.column": "Column", "objinfo.kind.roof": "Roof", "objinfo.kind.contextObject": "Context object", - "objinfo.kind.layoutAnnotation": "Sheet markup", - "objinfo.layoutAnnotationHint": "Edit position/size in mm directly on the frame on the sheet (grips or the fields there).", // ── Context object attributes (object info panel) ─────────────────────── "objinfo.contextObject.section": "Georeferencing", "objinfo.contextObject.type": "Type", @@ -2414,7 +2412,6 @@ export const en: Record = { // Editor "layouts.editorTitle": "Layout editor", "layouts.fit": "Fit", - "layouts.zoom100": "True size (100%, 1:1 on screen)", "layouts.addViewport": "Add viewport", "layouts.pickSnapshot": "Pick a view …", "layouts.noSnapshots": "No views available. Save a view first.", @@ -2433,22 +2430,8 @@ export const en: Record = { "layouts.placeViewport": "Draw viewport", "layouts.placeHint": "Drag a rectangle on the sheet, then bind a snapshot.", "layouts.bindSnapshot": "Bind snapshot", - "layouts.emptyViewports": - "No viewports yet. Choose “Draw viewport” and drag a rectangle on the sheet.", // Annotations (line/rect/text/image) drawn directly on the sheet — with the // same tools as the plan (left tools panel), no layout-only tool. - "layouts.annotTextTitle": "Text", - "layouts.annotTextLabel": "Text content:", - "layouts.annotEditText": "Edit text", - "layouts.annotRemove": "Remove annotation", - "layouts.annotX": "X (mm)", - "layouts.annotY": "Y (mm)", - "layouts.annotWidth": "Width (mm)", - "layouts.annotHeight": "Height (mm)", - "layouts.annot.line": "Line", - "layouts.annot.rect": "Rectangle", - "layouts.annot.text": "Text", - "layouts.annot.image": "Image", // Tree / “+” menu / folders "layouts.add": "New …", "layouts.addFolder": "Create folder", diff --git a/src/io/imageAsset.ts b/src/io/imageAsset.ts index 128965cb..937dbaa5 100644 --- a/src/io/imageAsset.ts +++ b/src/io/imageAsset.ts @@ -1,6 +1,6 @@ // Bild-Datei → eingebettete Data-URL + natürliche Pixelgrösse — gemeinsame -// Grundlage für „Bild einfügen" im Plan (Drawing2D `{shape:"image"}`) UND im -// Layout (LayoutAnnotation `kind:"image"`). Reine Browser-API (FileReader + +// Grundlage für „Bild einfügen" (Drawing2D `{shape:"image"}`, auch auf einem +// Layout-Blatt). Reine Browser-API (FileReader + // Image), kein Tauri-fs nötig — funktioniert identisch im Web-Preview. export interface LoadedImageAsset { @@ -36,13 +36,3 @@ export function defaultImageSizeM( const ratio = naturalHeight / Math.max(1, naturalWidth); return { widthM, heightM: Math.max(0.05, widthM * ratio) }; } - -/** Default-Grösse (mm) fürs Layout-Blatt, analog mit anderer Default-Breite. */ -export function defaultImageSizeMm( - naturalWidth: number, - naturalHeight: number, - widthMm = 60, -): { widthMm: number; heightMm: number } { - const ratio = naturalHeight / Math.max(1, naturalWidth); - return { widthMm, heightMm: Math.max(2, widthMm * ratio) }; -} diff --git a/src/io/pdfImport.ts b/src/io/pdfImport.ts index 4e0bd039..5553344f 100644 --- a/src/io/pdfImport.ts +++ b/src/io/pdfImport.ts @@ -2,7 +2,7 @@ // (pdfjs-dist, reine Browser-/Webview-API — kein Tauri-fs nötig) und als // Data-URL zurückgegeben. Kein eigener PDF-Rendering-Pfad im Plan/Layout — // eine importierte PDF-Seite ist danach ein ganz normales Bild-Element -// (Drawing2D `{shape:"image"}` bzw. LayoutAnnotation `kind:"image"`). +// (Drawing2D `{shape:"image"}`, auch auf einem Layout-Blatt). import * as pdfjsLib from "pdfjs-dist"; import type { LoadedImageAsset } from "./imageAsset"; diff --git a/src/io/projectFormat.ts b/src/io/projectFormat.ts index dcf09894..f9b3e1b9 100644 --- a/src/io/projectFormat.ts +++ b/src/io/projectFormat.ts @@ -21,7 +21,7 @@ import { documentFor, sharedDocument } from "../core/document"; import type { LoadFileResult } from "../core/document"; /** Aktuelle Version des Dateiformats (muss `PROJECT_FORMAT_VERSION` im Kern entsprechen — Test). */ -export const PROJECT_FORMAT_VERSION = 2; +export const PROJECT_FORMAT_VERSION = 3; export type ParseProjectResult = LoadFileResult; diff --git a/src/model/layoutModel.test.ts b/src/model/layoutModel.test.ts index 96795ea8..bbf5baff 100644 --- a/src/model/layoutModel.test.ts +++ b/src/model/layoutModel.test.ts @@ -11,15 +11,14 @@ import type { ViewSnapshot, } from "./types"; import { - addAnnotation, addViewport, buildLayoutTree, buildMasterTree, collectFolderLayouts, - createAnnotation, createLayout, createLayoutFolder, createMasterLayout, + createSheetLevel, createViewport, deleteFolder, deleteMasterFolder, @@ -28,15 +27,18 @@ import { findSnapshot, folderPdfPages, isDescendant, + isSheetLevel, moveFolderToFolder, moveLayoutToFolder, PAPER_FORMATS, - patchAnnotation, patchViewport, - removeAnnotation, removeViewport, resolveTitleBlock, resolveViewportScale, + SHEET_SCALE_DENOMINATOR, + sheetLevelOf, + sheetMmToModel, + sheetModelToMm, sheetSizeMm, visibleCodesFromSnapshot, } from "./layoutModel"; @@ -139,91 +141,29 @@ describe("Viewport-CRUD (immutabel)", () => { }); }); -// ── Annotationen (Linie/Rechteck/Text) ─────────────────────────────────────── +// ── Blatt-Ebene (2D-Zeichnung auf dem Blatt) ──────────────────────────────── -describe("createAnnotation — Defaults je Art", () => { - it("line: Default-Geometrie ohne Farbe/Strichstärke", () => { - const a = createAnnotation("a1", "line"); - expect(a).toEqual({ id: "a1", kind: "line", x1Mm: 20, y1Mm: 20, x2Mm: 80, y2Mm: 20 }); - }); - it("line: init überschreibt einzelne Felder + optionale Farbe/Strichstärke", () => { - const a = createAnnotation("a1", "line", { x1Mm: 5, color: "#f00", weightMm: 0.5 }); - expect(a).toMatchObject({ x1Mm: 5, y1Mm: 20, color: "#f00", weightMm: 0.5 }); - }); - it("rect: Default-Grösse", () => { - const a = createAnnotation("a2", "rect"); - expect(a).toEqual({ id: "a2", kind: "rect", xMm: 20, yMm: 20, widthMm: 40, heightMm: 30 }); - }); - it("text: Default-Zeilenhöhe 3.5mm, leerer Text", () => { - const a = createAnnotation("a3", "text"); - expect(a).toEqual({ id: "a3", kind: "text", xMm: 20, yMm: 20, text: "", heightMm: 3.5 }); - }); - it("text: init setzt Inhalt + Höhe", () => { - const a = createAnnotation("a3", "text", { text: "EG", heightMm: 5 }); - expect(a).toMatchObject({ text: "EG", heightMm: 5 }); - }); - it("text: init mit doc/widthMm (Rich-Text-Frame) wird übernommen", () => { - const doc = { version: 1 as const, paragraphs: [{ runs: [{ text: "Hi", marks: {} }] }] }; - const a = createAnnotation("a3", "text", { doc, widthMm: 50 }); - expect(a).toMatchObject({ doc, widthMm: 50 }); - }); - it("image: Default-Grösse, leere Quelle", () => { - const a = createAnnotation("a4", "image"); - expect(a).toEqual({ id: "a4", kind: "image", xMm: 20, yMm: 20, widthMm: 60, heightMm: 40, src: "" }); - }); - it("image: init setzt Quelle + Grösse + Deckkraft", () => { - const a = createAnnotation("a4", "image", { src: "data:image/png;base64,x", widthMm: 30, heightMm: 20, opacity: 0.5 }); - expect(a).toMatchObject({ src: "data:image/png;base64,x", widthMm: 30, heightMm: 20, opacity: 0.5 }); - }); -}); +describe("Blatt-Ebene", () => { + const lay = createLayout("l1", "Blatt 1", "a3", "landscape"); + const sheet = createSheetLevel("sheet-l1", lay); -describe("Annotations-CRUD (immutabel)", () => { - const base = createLayout("l1", "L", "a4", "portrait"); - - it("addAnnotation verändert das Original nicht", () => { - const after = addAnnotation(base, createAnnotation("a1", "line")); - expect(base.annotations).toBeUndefined(); - expect(after.annotations).toHaveLength(1); - expect(after).not.toBe(base); + it("ist eine Zeichnungsebene mit Layout-Bezug", () => { + expect(sheet).toEqual({ id: "sheet-l1", name: "Blatt 1", kind: "drawing", visible: true, locked: false, layoutId: "l1" }); + expect(isSheetLevel(sheet)).toBe(true); + expect(isSheetLevel({ layoutId: undefined })).toBe(false); + expect(isSheetLevel(undefined)).toBe(false); }); - it("addAnnotation baut auf einer fehlenden `annotations`-Liste auf (Alt-Layout)", () => { - const legacy: Layout = { id: "old", name: "Alt", paper: "a4", orientation: "portrait", viewports: [] }; - const after = addAnnotation(legacy, createAnnotation("a1", "rect")); - expect(after.annotations).toHaveLength(1); - expect(legacy.annotations).toBeUndefined(); + it("wird über das Layout gefunden", () => { + const p = { drawingLevels: [{ id: "eg", name: "EG", kind: "floor", visible: true, locked: false }, sheet] } as unknown as Project; + expect(sheetLevelOf(p, "l1")).toBe(sheet); + expect(sheetLevelOf(p, "nope")).toBeUndefined(); }); - it("removeAnnotation entfernt per Id", () => { - let l = addAnnotation(base, createAnnotation("a1", "line")); - l = addAnnotation(l, createAnnotation("a2", "rect")); - const removed = removeAnnotation(l, "a1"); - expect(removed.annotations!.map((a) => a.id)).toEqual(["a2"]); - }); - - it("removeAnnotation auf Alt-Layout ohne `annotations` bleibt heil (No-op)", () => { - const legacy: Layout = { id: "old", name: "Alt", paper: "a4", orientation: "portrait", viewports: [] }; - const r = removeAnnotation(legacy, "nope"); - expect(r.annotations).toEqual([]); - }); - - it("patchAnnotation ändert nur das Ziel, immutabel", () => { - const l = addAnnotation(base, createAnnotation("a1", "line", { color: "#111" })); - const patched = patchAnnotation(l, "a1", { x1Mm: 42, color: "#0f0" }); - expect(patched.annotations![0]).toMatchObject({ x1Mm: 42, color: "#0f0" }); - expect((l.annotations![0] as { color?: string }).color).toBe("#111"); - }); - - it("patchAnnotation: unbekannte Id → No-op (gleiche Werte, neue Liste)", () => { - const l = addAnnotation(base, createAnnotation("a1", "line")); - const noop = patchAnnotation(l, "nope", { x1Mm: 1 }); - expect((noop.annotations![0] as { x1Mm: number }).x1Mm).toBe(20); - }); - - it("patchAnnotation auf einer Text-Annotation ändert den Inhalt", () => { - const l = addAnnotation(base, createAnnotation("t1", "text", { text: "EG" })); - const patched = patchAnnotation(l, "t1", { text: "1. OG" }); - expect(patched.annotations![0]).toMatchObject({ text: "1. OG" }); + it("Papier-mm ↔ Meter (1:1, y nach unten = −y), hin und zurück", () => { + expect(sheetMmToModel(420, 297)).toEqual({ x: 0.42, y: -0.297 }); + expect(sheetModelToMm({ x: 0.42, y: -0.297 })).toEqual({ xMm: 420, yMm: 297 }); + expect(SHEET_SCALE_DENOMINATOR).toBe(1); }); }); diff --git a/src/model/layoutModel.ts b/src/model/layoutModel.ts index 3cfce168..f09f3eb6 100644 --- a/src/model/layoutModel.ts +++ b/src/model/layoutModel.ts @@ -7,22 +7,22 @@ // // Rechnung im Rust-Kern ([K4] S3, `src-tauri/core/src/layout_model.rs`, `folder_tree.rs`): Blattgrössen, // Ordner-Bäume (Aufbau, Blätter eines Ordners, Löschen, Nachfahren-Test), Seitenplanung des Ordner-PDF und -// Titelblock. Hier bleiben Fabriken, einfache Listen-Änderungen (Viewports, Annotationen, Blatt verschieben) +// Titelblock. Hier bleiben Fabriken, einfache Listen-Änderungen (Viewports, Blatt verschieben), die Blatt-Ebene // und Nachschlagen; die Baum-Fassaden setzen die Knoten aus den Indizes des Kerns mit den Original-Objekten // zusammen (Objekt-Identität bleibt). // // Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md). import type { + DrawingLevel, Layout, - LayoutAnnotation, - LayoutAnnotationPatch, LayoutFolder, LayoutOrientation, LayoutPaperFormat, LayoutViewport, MasterLayout, Project, + Vec2, ViewSnapshot, } from "./types"; import { core } from "../engine/coreWasm"; @@ -413,103 +413,40 @@ export function patchViewport( }; } -// ── Fabrik + immutable CRUD (Annotationen auf einem Layout) ───────────────── -// Analog zu Viewports: Linie/Rechteck/Text als vom Viewport-Baum unabhängige -// Markup-Schicht in Papier-mm. `annotations ?? []` ist überall die Basis, damit -// Alt-Layouts (ohne das Feld) unverändert bleiben (additiv). +// ── Blatt-Ebene (2D-Zeichnung auf dem Blatt) ───────────────────────────────── +// Was auf einem Blatt gezeichnet wird, sind gewöhnliche `drawings2d` auf der Blatt-Ebene des Layouts +// (`DrawingLevel.layoutId`, Art "drawing"): dieselben Werkzeuge, Fang, Griffe, Auswahl und dasselbe +// Rendering wie im Grundriss. Koordinaten = Papier 1:1 in Metern, Ursprung oben links, Papier-y nach +// unten = −y (s. {@link sheetMmToModel}). -/** - * Neue Annotation mit Default-Geometrie je Art (Linie/Rechteck: sichtbare - * Mindestgrösse; Text: 3.5 mm Zeilenhöhe, wie im Attribute-Editor üblich). - * `init` überschreibt einzelne Felder — der Aufrufer (Editor) übergibt i. d. R. - * die vollständige, aus dem Zeichnen gewonnene Geometrie. - */ -export function createAnnotation( - id: string, - kind: LayoutAnnotation["kind"], - init: LayoutAnnotationPatch = {}, -): LayoutAnnotation { - const colorPatch = init.color !== undefined ? { color: init.color } : {}; - if (kind === "line") { - return { - id, - kind: "line", - x1Mm: init.x1Mm ?? 20, - y1Mm: init.y1Mm ?? 20, - x2Mm: init.x2Mm ?? 80, - y2Mm: init.y2Mm ?? 20, - ...colorPatch, - ...(init.weightMm !== undefined ? { weightMm: init.weightMm } : {}), - }; - } - if (kind === "rect") { - return { - id, - kind: "rect", - xMm: init.xMm ?? 20, - yMm: init.yMm ?? 20, - widthMm: init.widthMm ?? 40, - heightMm: init.heightMm ?? 30, - ...colorPatch, - ...(init.weightMm !== undefined ? { weightMm: init.weightMm } : {}), - }; - } - if (kind === "image") { - return { - id, - kind: "image", - xMm: init.xMm ?? 20, - yMm: init.yMm ?? 20, - widthMm: init.widthMm ?? 60, - heightMm: init.heightMm ?? 40, - src: init.src ?? "", - ...(init.opacity !== undefined ? { opacity: init.opacity } : {}), - }; - } - return { - id, - kind: "text", - xMm: init.xMm ?? 20, - yMm: init.yMm ?? 20, - text: init.text ?? "", - heightMm: init.heightMm ?? 3.5, - ...colorPatch, - ...(init.doc !== undefined ? { doc: init.doc } : {}), - ...(init.widthMm !== undefined ? { widthMm: init.widthMm } : {}), - }; +/** Ist die Ebene die Blatt-Ebene eines Layouts (nicht im Navigator, nur bei offenem Blatt sichtbar)? */ +export function isSheetLevel(level: Pick | undefined | null): boolean { + return !!level?.layoutId; } -/** Fügt eine Annotation an (immutabel). */ -export function addAnnotation(layout: Layout, annotation: LayoutAnnotation): Layout { - return { ...layout, annotations: [...(layout.annotations ?? []), annotation] }; +/** Die Blatt-Ebene des Layouts `layoutId`, falls vorhanden. */ +export function sheetLevelOf(project: Project, layoutId: string): DrawingLevel | undefined { + return project.drawingLevels.find((l) => l.layoutId === layoutId); } -/** Entfernt eine Annotation per Id (immutabel). */ -export function removeAnnotation(layout: Layout, annotationId: string): Layout { - return { - ...layout, - annotations: (layout.annotations ?? []).filter((a) => a.id !== annotationId), - }; +/** Neue (leere) Blatt-Ebene für `layout`. */ +export function createSheetLevel(id: string, layout: Pick): DrawingLevel { + return { id, name: layout.name, kind: "drawing", visible: true, locked: false, layoutId: layout.id }; } -/** - * Ändert Felder einer Annotation (immutabel). No-op, wenn die Id fehlt. Der - * Patch ist bewusst art-unabhängig ({@link LayoutAnnotationPatch}) — es werden - * nur die tatsächlich übergebenen Felder gemergt. - */ -export function patchAnnotation( - layout: Layout, - annotationId: string, - patch: LayoutAnnotationPatch, -): Layout { - return { - ...layout, - annotations: (layout.annotations ?? []).map((a) => - a.id === annotationId ? ({ ...a, ...patch } as LayoutAnnotation) : a, - ), - }; +/** Papier-mm (x nach rechts, y nach unten) → Blatt-Ebene (Meter, y nach oben). */ +export function sheetMmToModel(xMm: number, yMm: number): Vec2 { + return { x: xMm / 1000, y: -yMm / 1000 }; } +/** Blatt-Ebene (Meter) → Papier-mm. */ +export function sheetModelToMm(p: Vec2): { xMm: number; yMm: number } { + return { xMm: p.x * 1000, yMm: -p.y * 1000 }; +} + +/** Massstab der Blatt-Ebene: Papier 1:1. */ +export const SHEET_SCALE_DENOMINATOR = 1; + // ── Auflösungen ────────────────────────────────────────────────────────────── /** Findet einen Ausschnitt (View-Snapshot) im Projekt. */ diff --git a/src/model/richProject.testing.ts b/src/model/richProject.testing.ts index 222d7196..00d3bad5 100644 --- a/src/model/richProject.testing.ts +++ b/src/model/richProject.testing.ts @@ -3,7 +3,7 @@ // Genutzt von der Modell-Rundreise und dem Robustheitstest des Kerns. import { sampleProject } from "./sampleProject"; -import type { Drawing2DGeom, LayoutAnnotation, ParametricRule, Project, RichTextDoc } from "./types"; +import type { Drawing2DGeom, ParametricRule, Project, RichTextDoc } from "./types"; export const plain = (p: unknown): unknown => JSON.parse(JSON.stringify(p)); @@ -47,19 +47,14 @@ const rules: ParametricRule[] = [ { type: "sequence", rules: [{ type: "reference-line", referenceLine: "right", target: "exterior" }], stopOnMatch: true }, ]; -const annotations: LayoutAnnotation[] = [ - { kind: "line", id: "a1", x1Mm: 0, y1Mm: 0, x2Mm: 10, y2Mm: 10, color: "#000000", weightMm: 0.25 }, - { kind: "rect", id: "a2", xMm: 1, yMm: 2, widthMm: 30, heightMm: 20 }, - { kind: "text", id: "a3", xMm: 1, yMm: 2, text: "Titel", heightMm: 5, doc, widthMm: 40 }, - { kind: "image", id: "a4", xMm: 1, yMm: 2, widthMm: 30, heightMm: 20, src: "data:image/png;base64,AAAA", opacity: 1 }, -]; - /** Beispielprojekt, ergänzt um alle Element-Arten, die es selbst nicht enthält. */ export function richProject(): Project { const lvl = sampleProject.drawingLevels[0].id; return { ...sampleProject, - formatVersion: 2, + formatVersion: 3, + // Blatt-Ebene des Layouts „lay1" (2D-Zeichnung auf dem Blatt). + drawingLevels: [...sampleProject.drawingLevels, { id: "sheet-lay1", name: "Blatt 1", kind: "drawing", visible: true, locked: false, layoutId: "lay1" }], textStyles: [{ id: "ts1", label: "Titel", marks: { bold: true, font: "Helvetica", sizePt: 14 } }], blockDefs: [{ id: "blk1", name: "Nordpfeil", geom2d: geoms.slice(0, 4) }], pens: [{ id: "pen1", name: "Kontur" }], @@ -111,7 +106,7 @@ export function richProject(): Project { layerVisibility: { "10": true, "20": false }, drawingVisibility: { [lvl]: true }, enabledOverrideRuleIds: ["or1"], cameraCenter: { x: 1, y: 2 }, cameraPxPerMeter: 40, }], viewSnapshotFolders: [{ id: "vf1", name: "Pläne" }, { id: "vf2", name: "Unter", parentId: "vf1" }], - layouts: [{ id: "lay1", name: "Blatt 1", paper: "a3", orientation: "landscape", planNumber: "A-12", masterId: "m1", folderId: "lf1", viewports: [{ id: "vp1", snapshotId: "vs1", xMm: 10, yMm: 10, widthMm: 200, heightMm: 150, scaleDenominator: 50 }], annotations }], + layouts: [{ id: "lay1", name: "Blatt 1", paper: "a3", orientation: "landscape", planNumber: "A-12", masterId: "m1", folderId: "lf1", viewports: [{ id: "vp1", snapshotId: "vs1", xMm: 10, yMm: 10, widthMm: 200, heightMm: 150, scaleDenominator: 50 }] }], masterLayouts: [{ id: "m1", name: "Master", paper: "a3", orientation: "landscape", titleBlock: { projectName: "P", sheetName: "S", scale: "1:100", date: "28.10.", author: "K" }, border: true }], layoutFolders: [{ id: "lf1", name: "Pläne", kind: "layout" }], referenceElevationMasl: 432.1, diff --git a/src/model/types.generated.ts b/src/model/types.generated.ts index fc493bac..80bed9c0 100644 --- a/src/model/types.generated.ts +++ b/src/model/types.generated.ts @@ -927,6 +927,14 @@ export type DrawingLevel = { * Fehlt ⇒ an; `false` ⇒ aus. */ levelMarks?: boolean; + /** + * Blatt-Ebene (nur kind "drawing"): gehört zum Layout mit dieser ID und trägt dessen + * 2D-Zeichnung (Linien, Texte, Bilder …) als gewöhnliche `drawings2d`. Koordinaten = Papier + * im Massstab 1:1 in Metern, Ursprung oben links am Blatt, Papier-y nach unten = −y + * (Papier-mm (x, y) ↔ Modell (x/1000, −y/1000)). Nicht im Navigator; nur sichtbar, wenn das + * Blatt offen ist. Fehlt ⇒ gewöhnliche Ebene. + */ + layoutId?: string; }; /** @@ -1275,65 +1283,13 @@ export type Layout = { customWidthMm?: number; /** Freie Blatthöhe in mm (siehe {@link Layout.customWidthMm}). */ customHeightMm?: number; - viewports: Array; /** - * 2D-Markups direkt auf dem Blatt (Linie/Rechteck/Text), siehe - * {@link LayoutAnnotation}. Additiv — Alt-Layouts ohne dieses Feld laden - * unverändert (Editor/CRUD behandeln ein fehlendes Array wie ein leeres). + * Die 2D-Zeichnung auf dem Blatt liegt auf der Blatt-Ebene ({@link DrawingLevel.layoutId}), + * nicht im Layout (bis Format 2: `annotations`, s. `project_format::migrate_layout_annotations`). */ - annotations?: Array; + viewports: Array; }; -/** Layout-Beschriftung (Tag `kind`). */ -export type LayoutAnnotation = - | { - kind: "line"; - id: string; - x1Mm: number; - y1Mm: number; - x2Mm: number; - y2Mm: number; - color?: string; - weightMm?: number; - } - | { - kind: "rect"; - id: string; - xMm: number; - yMm: number; - widthMm: number; - heightMm: number; - color?: string; - weightMm?: number; - } - | { - kind: "text"; - id: string; - xMm: number; - yMm: number; - text: string; - heightMm: number; - color?: string; - /** - * Reiches Textfeld (mehrere Absätze, gemischte Formatierung) — Vorrang vor - * `text`, s. gleichnamiges Feld bei `Drawing2DGeom["text"]`. - */ - doc?: RichTextDoc; - /** Optionale Rahmenbreite (mm) — bricht `doc` wortweise um; fehlt sie: einzeilig. */ - widthMm?: number; - } - | { - kind: "image"; - id: string; - xMm: number; - yMm: number; - widthMm: number; - heightMm: number; - /** Bildquelle als Data-URL (PNG/JPEG) — eingebettet, keine externe Datei. */ - src: string; - opacity?: number; - }; - /** * Ein Ordner im Layouts-Baum (DOSSIER A3). Layouts verweisen per `folderId` auf * ihren Ordner; `parentId` erlaubt Verschachtelung (Ordner in Ordner). Fehlt diff --git a/src/model/types.ts b/src/model/types.ts index 637bc915..6ed39479 100644 --- a/src/model/types.ts +++ b/src/model/types.ts @@ -26,7 +26,6 @@ import type { LineStyle, Opening, Project, - RichTextDoc, Roof, SashDef, Vec2, @@ -84,29 +83,6 @@ export interface ImportedText { layer?: string; } -/** - * Flaches Patch-Objekt für {@link LayoutAnnotation} — alle Felder ALLER Arten - * optional (statt eines pro Art unterscheidenden Unions), damit CRUD/Handler - * unabhängig von der konkreten `kind` bleiben (der Aufrufer setzt ohnehin nur - * die zur gewählten Annotation passenden Felder). - */ -export type LayoutAnnotationPatch = Partial<{ - x1Mm: number; - y1Mm: number; - x2Mm: number; - y2Mm: number; - xMm: number; - yMm: number; - widthMm: number; - heightMm: number; - text: string; - color: string; - weightMm: number; - doc: RichTextDoc; - src: string; - opacity: number; -}>; - // ── Helfer ─────────────────────────────────────────────────────────────── export const getWallType = (project: Project, wall: Wall): WallType => { diff --git a/src/panels/AttributesPanel.tsx b/src/panels/AttributesPanel.tsx index 37470306..4f70f1c6 100644 --- a/src/panels/AttributesPanel.tsx +++ b/src/panels/AttributesPanel.tsx @@ -124,21 +124,14 @@ export function AttributesPanel() { } const isDrawing = sel.kind === "drawing2d"; - // Layout-Annotation (Linie/Rechteck/Text/Bild auf einem Blatt) — kein - // Projekt-Bauteil, daher ohne Ebene/Bauteil-Vererbung: Farbe/Strichstärke - // sind IMMER ein eigener Wert (kein 3-Quellen-Dropdown, keine Füllung/ - // Schraffur/Masse — s. Ausblendungen weiter unten). - const isAnnotation = sel.kind === "layoutAnnotation"; // Strichstärke: Wand/Decke/Stütze/Drawing2D tragen einen eigenen Override // (`strokeWeight`/`weightMm`) + Quellen-Dropdown; andere Elementarten erben - // stets aus der Kategorie (kein Setter im Kontrakt → nicht editierbar). Bei - // Annotationen nur Linie/Rechteck (Text/Bild kennen keine Strichstärke). + // stets aus der Kategorie (kein Setter im Kontrakt → nicht editierbar). const weightEditable = sel.kind === "wall" || sel.kind === "ceiling" || sel.kind === "column" || - isDrawing || - (isAnnotation && (sel.annotKind === "line" || sel.annotKind === "rect")); + isDrawing; // Schraffur: Wand/Decke/Stütze (Schnitt-/Ansichts-Schraffur) oder // geschlossene 2D-Form. const fillEditable = @@ -312,29 +305,7 @@ export function AttributesPanel() { GESPERRT und zeigt die Strichstärke DES STIFTS (ein Stift trägt beides zusammen, s. model/penSets.ts) statt des sonst aufgelösten `weightMm`. */} - {isAnnotation ? ( - weightEditable && ( - <> - {t("attr.weight")} - - { - const v = Number(e.target.value); - if (Number.isFinite(v)) host.onSetSelectionWeight(v); - }} - /> - - - ) - ) : ( - sourceRow( + {sourceRow( "attr.weight", weightEditable && !sel.colorPenId, weightUi, @@ -360,8 +331,7 @@ export function AttributesPanel() { ))} , - ) - )} + )} {/* Deckkraft (0..1) — bei BILDERN deren eigene Bild-Deckkraft, bei allen übrigen 2D-Formen die Objekt-Transparenz (wirkt auf Strich @@ -429,7 +399,7 @@ export function AttributesPanel() { {/* Linienstil — nur Drawing2D trägt ihn (Wand/Decke/Annotation etc. read-only), Rest wie gehabt. */} - {!isAnnotation && ( + {( <> {t("attr.lineStyle")} @@ -608,7 +578,7 @@ export function AttributesPanel() { Nach Bauteil (erbt vom Component-Manager, Default) / eigener Wert. Eine Layout-Annotation kennt keine Füllung (nur Umriss) — Sektion entfällt komplett statt drei bedeutungslose Dropdowns zu zeigen. */} - {!isAnnotation && ( + {( <>
{t("attr.fill")}
@@ -797,7 +767,7 @@ export function AttributesPanel() { „Ausdehnung X/Y" beschriften (Nutzer-Report: Fenster zeigte „Höhe 0.34 m" = Wanddicke). Öffnungen tragen Breite/Höhe im eigenen Abschnitt, dort entfällt die bbox ganz. */} - {!isAnnotation && !sel.opening && ( + {!sel.opening && ( <>
{t("attr.size")}
{t(isModelElement ? "attr.extentX" : "attr.width")} diff --git a/src/panels/DrawingLevelsPanel.tsx b/src/panels/DrawingLevelsPanel.tsx index ad20c355..2e5aa958 100644 --- a/src/panels/DrawingLevelsPanel.tsx +++ b/src/panels/DrawingLevelsPanel.tsx @@ -77,7 +77,8 @@ export function DrawingLevelsPanel() { }; // Oberstes Geschoss zuoberst (wie DOSSIER): Anzeige umkehren. - const levelsTopDown = [...project.drawingLevels].reverse(); + // Blatt-Ebenen (Layout-Zeichnung) gehören zum Blatt, nicht in den Navigator. + const levelsTopDown = project.drawingLevels.filter((z) => !z.layoutId).reverse(); // Klick aufs Auge in „Alle anzeigen"/„Nur aktive" schaltet automatisch auf // „Ausgewählte" (DOSSIER-Regel), damit das Sichtbarkeits-Flag sofort greift. diff --git a/src/panels/ObjectInfoPanel.tsx b/src/panels/ObjectInfoPanel.tsx index 73b626a6..3a707d83 100644 --- a/src/panels/ObjectInfoPanel.tsx +++ b/src/panels/ObjectInfoPanel.tsx @@ -168,16 +168,7 @@ export function ObjectInfoPanel() {
- {/* Bezugspunkt/X-Y/Maße sind MODELL-Meter (Grundriss) — für eine Layout- - Annotation (Papier-Millimeter, eigenes Koordinatensystem) gibt es - keinen sinnvollen Bezugspunkt hier; Position/Grösse editiert man - direkt am Rahmen auf dem Blatt (Greifpunkte + das dortige HUD in - mm — `layout-sheet-hud` in LayoutSheet.tsx). Sonst zeigte dieses - Panel für sie fest 0/0 (Selection.bbox ist für sie ein Platzhalter, - s. App.tsx) — verwirrend statt nur „nicht anwendbar". */} - {sel.kind === "layoutAnnotation" ? ( -
{t("objinfo.layoutAnnotationHint")}
- ) : ( + {( <> {/* Bezugspunkt-Würfel (3×3, immer quadratisch) links, X/Y/Z als Spalte rechts daneben (Nutzer-Wunsch). */} diff --git a/src/plan/generatePlan.ts b/src/plan/generatePlan.ts index ddd2e1ed..01dd1d32 100644 --- a/src/plan/generatePlan.ts +++ b/src/plan/generatePlan.ts @@ -241,6 +241,9 @@ export function generatePlan( compactUnderlay = false, ): Plan { const compact = compactUnderlay && !mono && !forPrint; + // Blatt-Ebene eines Layouts (Papier 1:1): ohne projektglobale Zutaten (Kontext, Luftbilder, + // Schnittlinien, Schatten, Baurecht) — die gehören zum Modell, nicht aufs Papier. + if (project.drawingLevels.some((l) => l.id === floorId && l.layoutId)) includeGlobal = false; // Den ganzen Grundriss rechnet der Kern auf dem Dokument ([K3d]/[K4], `plan/{domains,walls,stairs, // drawings,extras}.rs`): Schattenstudie und Baurecht zuunterst, Decken, Dächer, Räume, Wände mit // Öffnungen, Treppen, Stützen, 2D-Zeichnungen, Extrusions-Umrisse, Kontext und Schnittführung, diff --git a/src/state/selectionInfo.ts b/src/state/selectionInfo.ts index f914b7a5..b4ddd9e4 100644 --- a/src/state/selectionInfo.ts +++ b/src/state/selectionInfo.ts @@ -352,15 +352,8 @@ export interface Selection { | "extrudedSolid" | "column" | "roof" - | "contextObject" - | "layoutAnnotation"; + | "contextObject"; id: string; - /** - * Konkrete Art der Layout-Annotation (nur `kind === "layoutAnnotation"`) — - * steuert z. B., ob die Strichstärke editierbar ist (Linie/Rechteck ja, - * Text/Bild nein). - */ - annotKind?: "line" | "rect" | "text" | "image"; /** Grafik-Kategorie (Ebene) des Elements. */ categoryCode: string; /** diff --git a/src/state/setProjectOps.test.ts b/src/state/setProjectOps.test.ts index 1f47a83b..eb4fa494 100644 --- a/src/state/setProjectOps.test.ts +++ b/src/state/setProjectOps.test.ts @@ -52,7 +52,7 @@ describe("Projekt laden ([K4] S4)", () => { st().undo(); expect(st().project).toBe(next); // Kern-Dokument = Leseansicht (Speichern aus dem Kern). - expect(JSON.parse(serializeProject(st().project))).toEqual({ ...next, formatVersion: 2 }); + expect(JSON.parse(serializeProject(st().project))).toEqual({ ...next, formatVersion: 3 }); }); it("openProjectFile: Kern liest, migriert und lädt direkt; Verlauf leer; kaputte Datei ändert nichts", () => { @@ -70,7 +70,7 @@ describe("Projekt laden ([K4] S4)", () => { expect(r.ok && r.migratedFrom).toBe(1); expect(st().undoDepth).toBe(0); expect(st().redoDepth).toBe(0); - expect(st().project.formatVersion).toBe(2); + expect(st().project.formatVersion).toBe(3); expect(st().project.openings?.some((o) => o.id === "TX" && o.kind === "door")).toBe(true); expect("doors" in st().project).toBe(false); // Danach normal weiterarbeiten: ein Schritt, Undo zurück auf den geladenen Stand. @@ -78,6 +78,6 @@ describe("Projekt laden ([K4] S4)", () => { st().setProject(opsMutation((p) => patchItem(p, "walls", p.walls[0].id, { height: 7 }))); st().undo(); expect(st().project).toEqual(loaded); - expect(serializeProject(st().project)).toBe(JSON.stringify({ formatVersion: 2, ...loaded }, null, 2)); + expect(serializeProject(st().project)).toBe(JSON.stringify({ formatVersion: 3, ...loaded }, null, 2)); }); }); diff --git a/src/state/useImportHandling.ts b/src/state/useImportHandling.ts index 1fcb6e4c..a755ba72 100644 --- a/src/state/useImportHandling.ts +++ b/src/state/useImportHandling.ts @@ -27,6 +27,11 @@ import type { Vec2 } from "../model/types"; export function useImageImportHandling(opts: { activeLevelId: string; activeCategoryCode: string; + /** + * Einfügen auf einem Layout-Blatt (Papier 1:1 in Metern): Bildbreite und Mitte des Bilds + * (sonst 2 m breit am Modell-Nullpunkt). + */ + imagePlacement?: { widthM: number; center: Vec2 }; /** Änderung als Ops (Store `applyChange`): alle Bilder eines Einfügens = ein Undo-Schritt. */ applyChange: (ops: readonly CoreOp[]) => void; notify: (message: string, kind?: NotifyKind) => void; @@ -48,6 +53,7 @@ export function useImageImportHandling(opts: { const { activeLevelId, activeCategoryCode, + imagePlacement, applyChange, notify, setSelectedDrawingId, @@ -67,9 +73,10 @@ export function useImageImportHandling(opts: { assets: { src: string; naturalWidth: number; naturalHeight: number }[], ) => { const drawings = assets.map((a, i) => { - const { widthM, heightM } = defaultImageSizeM(a.naturalWidth, a.naturalHeight); - const cascade = i * 0.3; - const at: Vec2 = { x: -widthM / 2 + cascade, y: -heightM / 2 - cascade }; + const { widthM, heightM } = defaultImageSizeM(a.naturalWidth, a.naturalHeight, imagePlacement?.widthM); + const cascade = i * 0.15 * widthM; + const c = imagePlacement?.center ?? { x: 0, y: 0 }; + const at: Vec2 = { x: c.x - widthM / 2 + cascade, y: c.y - heightM / 2 - cascade }; return imageDrawing2d(activeLevelId, activeCategoryCode, a.src, at, widthM, heightM); }); applyChange(addItems("drawings2d", drawings)); diff --git a/src/state/usePanelHostBase.ts b/src/state/usePanelHostBase.ts index 56ee80d1..07533c51 100644 --- a/src/state/usePanelHostBase.ts +++ b/src/state/usePanelHostBase.ts @@ -11,7 +11,7 @@ import { applyFillMode } from "./fillMode"; import { addItems, fieldOps, opsMutation, patchItem, patchItems, removeItems, removeRoofHole, setFieldIfChanged, setRoofEdge } from "../core"; import type { CoreOp, ProjectMutation } from "../core"; import { useMemo, type RefObject } from "react"; -import type { DrawingLevel, Layout, Project } from "../model/types"; +import type { DrawingLevel, Project } from "../model/types"; import { resolvePenColor } from "../model/penSets"; import type { ToolId } from "../tools/types"; import type { ViewType } from "../model/viewTypes"; @@ -52,7 +52,7 @@ import { deleteMasterFolder, moveLayoutToFolder, moveFolderToFolder, - patchAnnotation as patchAnnotationInLayout, + createSheetLevel, } from "../model/layoutModel"; import { folderPdfBytes } from "../export/layoutPdf"; import { saveBinaryFile } from "../native/saveFile"; @@ -124,8 +124,6 @@ export function usePanelHostBase(opts: { openSettings: () => void; onOpenStampEditor: (roomId: string) => void; openResources: (tab?: ResourceTabId) => void; - activeLayout: Layout | undefined; - patchOpenLayout: (id: string, fn: (l: Layout) => Layout) => void; dxfInputRef: RefObject; planViewRef: RefObject; selection: Selection | null; @@ -244,8 +242,6 @@ export function usePanelHostBase(opts: { openSettings, onOpenStampEditor, openResources, - activeLayout, - patchOpenLayout, dxfInputRef, planViewRef, selection, @@ -422,15 +418,9 @@ export function usePanelHostBase(opts: { updateStair(selection.id, { color }); else if (selection.kind === "room") updateRoom(selection.id, { color }); - else if (selection.kind === "layoutAnnotation" && activeLayout) - patchOpenLayout(activeLayout.id, (l) => - patchAnnotationInLayout(l, selection.id, { color }), - ); }, // Stift-Kopplung der Farbe oben (s. `Selection.colorPenId`-Doku) — - // dieselben Selektionsarten wie `onSetSelectionColor`, MINUS Layout- - // Annotation (kein `colorPenId`-Feld dort, bewusster Scope-Schnitt s. - // PENDENZEN.md). `penId` gesetzt ⇒ Farbe sofort aus dem aktiven + // dieselben Selektionsarten wie `onSetSelectionColor`. `penId` gesetzt ⇒ Farbe sofort aus dem aktiven // Stiftsatz backen; `undefined` ⇒ nur die Kopplung lösen, letzter // gebackener Wert bleibt als freie Farbe stehen. onSetSelectionColorPen: (penId) => { @@ -445,15 +435,10 @@ export function usePanelHostBase(opts: { else if (selection.kind === "room") updateRoom(selection.id, patch); }, onSetSelectionWeight: (weightMm) => { - // Strichstärke-Override: Wand/Decke (`strokeWeight`) oder Drawing2D/ - // Layout-Annotation (`weightMm`, Alt-Feldname bleibt). + // Strichstärke-Override: Wand/Decke (`strokeWeight`) oder Drawing2D (`weightMm`). if (selection?.kind === "wall") updateWall(selection.id, { strokeWeight: weightMm }); else if (selection?.kind === "ceiling") updateCeiling(selection.id, { strokeWeight: weightMm }); - else if (selection?.kind === "layoutAnnotation" && activeLayout) - patchOpenLayout(activeLayout.id, (l) => - patchAnnotationInLayout(l, selection.id, { weightMm }), - ); else if (selection?.kind === "drawing2d") setElementWeight(selection.id, weightMm); }, @@ -507,10 +492,6 @@ export function usePanelHostBase(opts: { ), ), ); - else if (selection?.kind === "layoutAnnotation" && activeLayout) - patchOpenLayout(activeLayout.id, (l) => - patchAnnotationInLayout(l, selection.id, { opacity }), - ); else if (selection?.kind === "contextObject") applyChange((p) => patchItem(p, "context", selection.id, (o) => (o.type === "image" ? { ...o, opacity } : o)), @@ -1324,14 +1305,24 @@ export function usePanelHostBase(opts: { // Anlegen öffnet es direkt; Löschen schliesst es, falls es das offene trifft. onAddLayout: (name, paper, orientation) => { const lay = createLayout(`lay-${Date.now()}`, name, paper, orientation); - applyChange(addItems("layouts", [lay])); + // Jedes Blatt trägt seine Blatt-Ebene (2D-Zeichnung auf dem Blatt, s. layoutModel). + applyChange([...addItems("layouts", [lay]), ...addItems("drawingLevels", [createSheetLevel(`sheet-${lay.id}`, lay)])]); setActiveLayoutId(lay.id); }, onRenameLayout: (id, name) => { applyChange((p) => patchItem(p, "layouts", id, { name })); }, onDeleteLayout: (id) => { - applyChange((p) => removeItems(p, "layouts", [id])); + // Mit dem Layout gehen seine Blatt-Ebene und deren Zeichnungen (ein Undo-Schritt). + applyChange((p) => { + const levels = p.drawingLevels.filter((l) => l.layoutId === id).map((l) => l.id); + const drawings = p.drawings2d.filter((d) => levels.includes(d.levelId)).map((d) => d.id); + return [ + ...removeItems(p, "drawings2d", drawings), + ...removeItems(p, "drawingLevels", levels), + ...removeItems(p, "layouts", [id]), + ]; + }); setActiveLayoutId((cur) => (cur === id ? null : cur)); }, onOpenLayout: (id) => setActiveLayoutId(id), @@ -1413,7 +1404,7 @@ export function usePanelHostBase(opts: { ? { customWidthMm, customHeightMm } : {}), }; - applyChange(addItems("layouts", [full])); + applyChange([...addItems("layouts", [full]), ...addItems("drawingLevels", [createSheetLevel(`sheet-${id}`, full)])]); return id; }, onCreateMasterLayout: (opts) => { diff --git a/src/styles.css b/src/styles.css index c8a8c32f..5ea9979c 100644 --- a/src/styles.css +++ b/src/styles.css @@ -7417,134 +7417,9 @@ body { background: var(--sheet); touch-action: none; user-select: none; -} - -.layout-sheet-paper { - position: absolute; - background: #ffffff; - border: 1px solid rgba(26, 26, 24, 0.18); - box-shadow: 0 4px 22px rgba(26, 26, 24, 0.22); -} - -.layout-sheet-vp { - position: absolute; - overflow: hidden; - background: #ffffff; - outline: 1px solid rgba(0, 0, 0, 0.35); -} -.layout-sheet-vp.selected { - outline: 1.5px solid #3b82f6; - z-index: 2; -} - -.layout-sheet-vp-missing { - width: 100%; - height: 100%; + /* Darin die Plan-Ansicht der Blatt-Ebene (füllt die Fläche). */ display: flex; - align-items: center; - justify-content: center; - font-size: 10px; - color: #b00; - text-align: center; - padding: 4px; -} - -/* Resize-Griffe (8 Stück) — kleine blaue Quadrate am Rand des gewählten VP. */ -.layout-sheet-grip { - position: absolute; - width: 9px; - height: 9px; - margin: -5px 0 0 -5px; /* auf den Ankerpunkt zentrieren */ - background: #ffffff; - border: 1.5px solid #3b82f6; - border-radius: 2px; - z-index: 4; -} - -/* Ghost-Rechteck beim Aufziehen einer neuen Platzierung. */ -.layout-sheet-ghost { - position: absolute; - border: 1.5px dashed #3b82f6; - background: rgba(59, 130, 246, 0.12); - z-index: 4; - pointer-events: none; -} - -/* Transparenter Vollflächen-Fänger hinter dem Inline-Text-Editor — ein Klick - daneben schliesst ihn (jede Änderung ist bereits live gespeichert). */ -.layout-sheet-inline-backdrop { - position: absolute; - inset: 0; - z-index: 6; -} - -/* Inline-Text-Editor DIREKT auf dem Blatt (kein schwebendes Fenster) — weisser - Rahmen wie Papier, blauer Rand während der Bearbeitung. WYSIWYG: Schrift- - grösse UND Feldhöhe der Textfläche folgen dem echten Blatt-Zoom über - `--rt-font-size`/`--rt-min-height` (inline von LayoutSheet.tsx gesetzt) — - NUR die Textfläche, NICHT die Toolbar (dasselbe Muster wie - .planview-inline-text, s. dort; ersetzt das vorige `transform:scale()` auf - die GANZE Box, das die Toolbar beim Reinzoomen mit aufblies). */ -.layout-sheet-inline-text { - position: absolute; - z-index: 7; - background: #ffffff; - outline: 1.5px solid #3b82f6; - box-shadow: 0 2px 10px rgba(0, 0, 0, 0.35); -} -.layout-sheet-inline-text .rt-editor { - min-height: inherit; - /* Toolbar verlässt den Fluss (s. .rt-toolbar unten) — nur noch die - Textfläche bleibt im normalen Fluss, damit ihre Oberkante GENAU an der - positionierten Box-Oberkante liegt (= Zeilenanfang der Annotation). - `overflow:visible` (Basisregel setzt `hidden`), sonst würde die frei - schwebende Toolbar oben abgeschnitten. `border:none` (Basisregel: 1px) — - jeder Rahmen/jedes Padding auf `.rt-editor`/`.rt-surface` verschiebt den - sichtbaren Text nach rechts/unten relativ zur positionierten Ecke (Bug- - Meldung "Sprung nach rechts oben"); die blaue `outline` auf - `.layout-sheet-inline-text` selbst übernimmt weiterhin die visuelle - Rahmen-Anzeige (outline verschiebt den Inhalt NICHT, da ausserhalb der - Box gezeichnet). */ - display: block; - overflow: visible; - border: none; - /* s. .planview-inline-text .rt-editor — explizite Breite gegen "Wort läuft - aus der Fläche raus statt umzubrechen" (die Aussen-Box hat eine feste - `width` per Inline-Style, aber ohne diese Zeile war das für lange, - leerzeichenlose Wörter nicht garantiert). */ - width: 100%; - box-sizing: border-box; -} -/* REGRESSION-Fix "Editor ist tiefer als der Text": vorher stand die Toolbar - IM normalen Fluss ÜBER der Textfläche (column-flex in .rt-editor) — ihre - feste, zoomunabhängige Höhe (~38px: Padding+Button+Rahmen) schob die - Fläche um diesen Betrag nach unten, während die Positionierung (JS) nur - mit EINER Zeilenhöhe Abstand zur Baseline rechnete. Bei üblichem Zoom ist - eine Zeilenhöhe kleiner als die Toolbar-Höhe → die Fläche landete UNTER - dem eigentlichen Text. Jetzt schwebt die Toolbar frei OBERHALB der Box, - ausserhalb ihres Flusses — sie verschiebt die Textfläche nicht mehr. */ -.layout-sheet-inline-text .rt-toolbar { - position: absolute; - left: 0; - right: 0; - bottom: 100%; - margin-bottom: 4px; - border: 1px solid var(--border); - border-radius: 6px; - box-shadow: var(--shadow-1); -} -.layout-sheet-inline-text .rt-surface { - font-size: var(--rt-font-size, 16px); - line-height: 1.25; /* deckt sich mit primitives.tsx "drawingText" (fontSize*1.25) */ - min-height: var(--rt-min-height, 1.4em); - padding: 0; /* kein Padding — verschiebt sonst den Text relativ zur Anker-Ecke */ - /* s. .planview-inline-text .rt-surface — harter Umbruch auch mitten im - Wort statt Überlauf, plus Sicherheitsnetz gegen intrinsische - Mindestbreite. */ - width: 100%; - box-sizing: border-box; - overflow-wrap: anywhere; - min-width: 0; + flex-direction: column; } /* Inline-Text-Editor auf der 2D-Zeichenfläche (PlanView) — dasselbe Prinzip diff --git a/src/text/fontMetrics.ts b/src/text/fontMetrics.ts index 509aaa61..2fec6db3 100644 --- a/src/text/fontMetrics.ts +++ b/src/text/fontMetrics.ts @@ -18,10 +18,9 @@ export interface FontMetricRatios { } /** Zeilenabstand-Vielfaches für gezeichneten Text, EINE Quelle für alle - * Verbraucher (primitives.tsx "drawingText" fontSize*1.25, PlanView.tsx/ - * LayoutSheet.tsx Inline-Editor-Anker UND deren CSS `line-height` in - * styles.css `.planview-inline-text .rt-surface`/`.layout-sheet-inline-text - * .rt-surface` — alle MÜSSEN denselben Wert verwenden, sonst driften + * Verbraucher (primitives.tsx "drawingText" fontSize*1.25, PlanView.tsx + * Inline-Editor-Anker UND dessen CSS `line-height` in styles.css + * `.planview-inline-text .rt-surface` — alle MÜSSEN denselben Wert verwenden, sonst driften * Editor-Position und späteres Rendering wieder auseinander). */ export const TEXT_LINE_HEIGHT_MULT = 1.25; diff --git a/src/text/renderHtml.test.ts b/src/text/renderHtml.test.ts index 45ee579a..18ca49f0 100644 --- a/src/text/renderHtml.test.ts +++ b/src/text/renderHtml.test.ts @@ -3,7 +3,7 @@ import { describe, expect, it } from "vitest"; import { docFromText, makeRun, type RichTextDoc } from "./richText"; -import { annotationTextLines, docToHtml, layoutText, runCssProps } from "./renderHtml"; +import { docToHtml, layoutText, runCssProps } from "./renderHtml"; const OPTS = { x: 0, y: 0, lineHeight: 10, unitPerPt: 1, basePt: 10, color: "#000000" }; @@ -29,16 +29,6 @@ describe("layoutText", () => { expect(at({ columnWidth: NaN })).toEqual(at({})); }); - it("Layout-Markup: Basis = Höhe in mm, Vorschub 1.25 × Höhe, Rahmen nur bei Breite > 0 umbrochen", () => { - const doc = docFromText("eins zwei drei"); - const l = annotationTextLines({ xMm: 10, yMm: 20, heightMm: 4, widthMm: 15 }, doc); - expect(l.map((x) => x.y)).toEqual([20, 25, 30]); - expect(l[0].tspans[0]).toMatchObject({ fontSize: 4, fill: "#111111" }); - // Negative Breite: kein Umbruch, aber (wie früher) Spalte für die Lage. - const r = annotationTextLines({ xMm: 10, yMm: 20, heightMm: 4, widthMm: -6 }, { version: 1, paragraphs: [{ runs: [makeRun("x")], align: "right" }] }); - expect([r.length, r[0].x]).toEqual([1, 4]); - }); - it("bricht lange Absätze wortweise auf mehrere Zeilen um", () => { const doc = docFromText("eins zwei drei vier fünf"); const lines = layoutText(doc, { ...OPTS, wrapWidthUnits: 30 }); diff --git a/src/text/renderHtml.ts b/src/text/renderHtml.ts index d3bb1878..d1f0e67c 100644 --- a/src/text/renderHtml.ts +++ b/src/text/renderHtml.ts @@ -264,27 +264,6 @@ export function layoutText(doc: RichTextDoc, opts: SvgTextOptions): SvgLine[] { return lines; } -/** - * Zeilen eines Text-Markups auf dem Layout-Blatt (Papier-mm; Layout-Blatt und Layout-PDF): Höhe - * `heightMm` als Basisgrösse, Vorschub 1.25 × Höhe, erste Grundlinie bei `yMm`; mit Rahmenbreite - * (`widthMm` > 0) wortweise umbrochen, Mitte/rechts im Rahmen (jede Breite ≠ 0 zählt dafür, wie früher). - */ -export function annotationTextLines( - ann: { xMm: number; yMm: number; heightMm: number; widthMm?: number; color?: string }, - doc: RichTextDoc, -): SvgLine[] { - return layoutText(doc, { - x: ann.xMm, - y: ann.yMm, - lineHeight: ann.heightMm * 1.25, - unitPerPt: 25.4 / 72, - basePt: (ann.heightMm / 25.4) * 72, - color: ann.color ?? "#111111", - wrapWidthUnits: ann.widthMm && ann.widthMm > 0 ? ann.widthMm : undefined, - columnWidth: ann.widthMm, - }); -} - /** * Raumstempel-Block (Kern `stamp_block`): Rich-Text-Zeilen (Vorschub 1.3 × Basisgrösse bzw. die * Absatz-Zeilenhöhe) und darunter die Live-Zeilen (0.8 × Basisgrösse), vertikal um `y0` zentriert, diff --git a/src/ui/ImportDialog.tsx b/src/ui/ImportDialog.tsx index ed0103a6..3cfbca08 100644 --- a/src/ui/ImportDialog.tsx +++ b/src/ui/ImportDialog.tsx @@ -432,7 +432,7 @@ export function ImportDialog({ value={existingLevelId} onChange={(v) => setExistingLevelId(v)} title={t("import.target.existing")} - options={project.drawingLevels.map((z) => ({ + options={project.drawingLevels.filter((z) => !z.layoutId).map((z) => ({ value: z.id, label: `${z.name} · ${t(kindBadgeKey(z.kind))}`, }))} diff --git a/src/ui/LayoutSheet.tsx b/src/ui/LayoutSheet.tsx index 9b987e83..6f530415 100644 --- a/src/ui/LayoutSheet.tsx +++ b/src/ui/LayoutSheet.tsx @@ -1,29 +1,27 @@ -// Layout-Blatt als erstklassige Ansicht im HAUPT-Viewport (Phase 2b) — das Blatt -// liegt auf einem papierartigen „Tisch", ist pan-/zoombar (Zoom-to-Cursor) und -// die platzierten Viewports lassen sich mit der Maus platzieren/verschieben/ -// skalieren/löschen (wie ArchiCAD/Vectorworks). Der Render-Kern (echter Plan je -// Viewport, Master-Titelblock) lebt hier zentral (ViewportPlan, TitleBlockSvg -// unten) und ersetzt das frühere schwebende Layout-Fenster (Phase 2a). +// Layout-Blatt im Haupt-Viewport. Das Blatt ist KEINE eigene Zeichenfläche mehr: gezeichnet wird in +// der gewöhnlichen Plan-Ansicht (PlanView) auf der Blatt-Ebene des Layouts (`DrawingLevel.layoutId`, +// Papier 1:1 in Metern) — dieselben Werkzeuge, Befehle, Fang, Griffe, Vorschau/HUD, Auswahl, Undo und +// dasselbe Rendering wie im Grundriss (Wartungs-Feedback: „genau gleich wie im normalen Ausschnitt"). // -// Geometrie/Transform/Trefferlogik liegen rein + testbar in layoutSheetMath.ts. +// Diese Datei liefert nur, was das Blatt zusätzlich hat: den Hintergrund unter der Zeichnung +// (Papier, Master-Rahmen + Titelblock, die platzierten Viewports mit ihrem echten Plan) als +// `backdrop` der PlanView, das Platzieren/Verschieben/Skalieren der Viewports (in Papier-mm) und +// die schlanke Blatt-Leiste (Zurück, Viewport aufziehen, Einpassen). +// +// Geometrie der Viewport-Griffe liegt rein + testbar in layoutSheetMath.ts. // Bezeichner englisch, UI-Text/Kommentare deutsch (CONVENTIONS.md). -import { useEffect, useRef, useState } from "react"; -import type { - PointerEvent as ReactPointerEvent, - MouseEvent as ReactMouseEvent, - CSSProperties, -} from "react"; +import { useEffect, useMemo, useRef, useState } from "react"; +import type { PointerEvent as ReactPointerEvent, ReactNode, RefObject } from "react"; import type { Layout, - LayoutAnnotation, - LayoutAnnotationPatch, LayoutOrientation, LayoutPaperFormat, LayoutViewport, Project, + Vec2, } from "../model/types"; -import { generatePlan } from "../core"; +import { generatePlan, PX_PER_M } from "../core"; import { planToPrintSvg } from "../export/planToPrintSvg"; import { effectiveSheetSizeMm, @@ -31,58 +29,42 @@ import { findSnapshot, resolveTitleBlock, resolveViewportScale, + sheetMmToModel, + sheetModelToMm, visibleCodesFromSnapshot, } from "../model/layoutModel"; import { - annotationBoundsMm, applyHandleDrag, - applyLineHandleDrag, clampRectToSheet, - fitTransform, handleAnchors, handleCursor, - lineHandleAnchors, - mmToScreen, normalizeRect, - panBy, - pickAnnotationHandle, pickViewport, - screenToMm, - translateAnnotation, vpRect, - zoomAtCursor, - type AnnotHandleHit, type Handle, - type LineHandle, type RectMm, - type SheetTransform, } from "./layoutSheetMath"; -import { RichTextEditor } from "../editors/RichTextEditor"; -import { docFromText } from "../text/richText"; -import { annotationTextLines } from "../text/renderHtml"; -import { contentFontBaselineFromTop, TEXT_LINE_HEIGHT_MULT } from "../text/fontMetrics"; -import { readImageFile, defaultImageSizeMm } from "../io/imageAsset"; -import { rasterizePdfPages } from "../io/pdfImport"; -import type { ToolId } from "../tools/types"; +import type { PlanSelection, PlanViewHandle } from "../views/plan/PlanView"; import { t } from "../i18n"; -// ── Geteilter Render-Kern (auch vom schwebenden LayoutEditor genutzt) ───────── +// ── Geteilter Render-Kern ───────────────────────────────────────────────────── /** - * Rendert den ECHTEN Plan eines Viewports: Ausschnitt auflösen → `generatePlan` - * → `planToPrintSvg` beim effektiven Viewport-Massstab, Blattgrösse = Viewport- - * mm-Grösse. Das SVG (viewBox in mm) wird per 100 % in den Rahmen skaliert - * (`overflow:hidden` → Clipping). Neu-Aufbau nur bei relevanten Änderungen - * (Projekt/Bindung/Grösse/Massstab), NICHT beim Verschieben (x/y) oder Zoomen. + * Rendert den ECHTEN Plan eines Viewports als verschachteltes `` in Blatt-mm: Ausschnitt + * auflösen → `generatePlan` → `planToPrintSvg` beim effektiven Viewport-Massstab (Blattgrösse = + * Viewport-mm-Grösse; das innere SVG klippt). Neu-Aufbau nur bei Projekt/Bindung/Grösse/Massstab, + * nicht beim Verschieben (x/y setzt nur Attribute). */ -export function ViewportPlan({ +export function ViewportPlanSvg({ project, viewport, + rect, }: { project: Project; viewport: LayoutViewport; + rect: RectMm; }) { - const ref = useRef(null); + const ref = useRef(null); useEffect(() => { const el = ref.current; if (!el) return; @@ -93,46 +75,35 @@ export function ViewportPlan({ } try { const codes = visibleCodesFromSnapshot(snap); - // Massstab ZUERST auflösen: er geht in die Plan-Erzeugung ein, weil - // Bemassungs-Feinheiten in Papier-mm angegeben sind (s. model/dimension.ts). + // Massstab ZUERST: er geht in die Plan-Erzeugung ein (Bemassung in Papier-mm, s. model/dimension.ts). const scaleN = resolveViewportScale(viewport, snap); - const plan = generatePlan( - project, - snap.activeLevelId, - codes, - undefined, - snap.detail, - false, - false, - true, - scaleN, - ); + const plan = generatePlan(project, snap.activeLevelId, codes, undefined, snap.detail, false, false, true, scaleN); const print = planToPrintSvg(plan, { scaleDenominator: scaleN, pageWidthMm: viewport.widthMm, pageHeightMm: viewport.heightMm, }); - const svg = print.svg; - svg.setAttribute("width", "100%"); - svg.setAttribute("height", "100%"); - svg.style.display = "block"; - el.replaceChildren(svg); + el.replaceChildren(print.svg); } catch { el.replaceChildren(); } - }, [ - project, - viewport.snapshotId, - viewport.widthMm, - viewport.heightMm, - viewport.scaleDenominator, - ]); - return
; + }, [project, viewport.snapshotId, viewport.widthMm, viewport.heightMm, viewport.scaleDenominator]); + // Lage/Grösse über die Attribute des inneren SVG (folgt auch dem Ghost beim Ziehen). + useEffect(() => { + const svg = ref.current?.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)); + svg.setAttribute("preserveAspectRatio", "none"); + }); + return ; } /** - * Schlichtes Schriftfeld unten rechts (mm-Koordinaten des Blatt-viewBox) mit den - * aufgelösten Master-Werten — dieselbe Anmutung wie der PDF-Titelblock. + * Schlichtes Schriftfeld unten rechts (mm-Koordinaten des Blatts) mit den aufgelösten Master-Werten — + * dieselbe Anmutung wie der PDF-Titelblock. */ export function TitleBlockSvg({ sheet, @@ -184,673 +155,335 @@ function clip(s: string, max: number): string { return s.length > max ? s.slice(0, max - 1) + "…" : s; } -// ── In-Viewport-Layout-Ansicht ──────────────────────────────────────────────── +// ── Blatt im Haupt-Viewport ─────────────────────────────────────────────────── export interface LayoutSheetHandlers { /** Zurück zur Modell-Ansicht (Grundriss/3D). */ onBack: () => void; /** Ändert Position/Grösse/Massstab eines Viewports (mm). */ - onPatchViewport: ( - viewportId: string, - patch: Partial>, - ) => void; + onPatchViewport: (viewportId: string, patch: Partial>) => void; /** Entfernt einen Viewport per Id. */ onRemoveViewport: (viewportId: string) => void; /** Fügt einen Viewport (gebunden an `snapshotId`) mit gegebener Geometrie an. */ - onAddViewport: ( - snapshotId: string, - init: Partial>, - ) => void; - /** - * Fügt eine neue Annotation (Linie/Rechteck/Text/Bild) mit gegebener - * Geometrie an — liefert die neue Id zurück (z. B. um nach dem Aufziehen - * eines Text-Rahmens sofort inline hineinzuschreiben, s. `inlineEdit`). - */ - onAddAnnotation: (kind: LayoutAnnotation["kind"], init: LayoutAnnotationPatch) => string; - /** - * Ändert Felder einer Annotation (Position/Farbe/Strichstärke/Text). - * `coalesceKey`: s. `projectSlice.ts` `setProject` — vom Inline-Text-Editor - * genutzt, damit EIN Tipp-Vorgang EINEN Undo-Schritt erzeugt statt bei - * jedem Tastendruck einen neuen zu pushen (s. `inlineEdit`-Block unten). - */ - onPatchAnnotation: ( - annotationId: string, - patch: LayoutAnnotationPatch, - coalesceKey?: string, - ) => void; - /** Entfernt eine Annotation per Id. */ - onRemoveAnnotation: (annotationId: string) => void; + onAddViewport: (snapshotId: string, init: Partial>) => void; } -/** Fangzone der Resize-Griffe in Bildschirm-Pixeln (→ mm über den Massstab). */ -const HANDLE_TOL_PX = 7; +/** Was die Plan-Ansicht der Blatt-Ebene vom Blatt bekommt. */ +export interface SheetPlanProps { + /** Papier, Master und Viewports unter der Zeichnung (s. `PlanView.backdrop`). */ + backdrop: (origin: Vec2, pxPerMeter: number) => ReactNode; + /** Einpassen = das ganze Blatt. */ + fitBounds: { minX: number; minY: number; maxX: number; maxY: number }; + /** Klick-Auswahl: trifft sie nichts Gezeichnetes, wählt sie den Viewport darunter. */ + onPlanSelect: (sel: PlanSelection) => void; +} + +/** Fangzone/Grösse der Viewport-Griffe in Bildschirm-Pixeln. */ +const GRIP_PX = 9; /** Mindest-Kantenlänge eines Viewports (mm). */ const MIN_VP_MM = 8; /** Mindest-Kantenlänge eines aufgezogenen Platzierungs-Rechtecks (mm). */ const MIN_PLACE_MM = 6; -/** Mindestgrösse einer neu gezeichneten Linie/eines Rechtecks (mm) — sonst verworfen. */ -const MIN_ANNOT_MM = 3; -/** Default-Zeilenhöhe eines neuen Text-Markups (mm). */ -const DEFAULT_ANNOT_TEXT_MM = 3.5; -/** - * CSS-Pixel pro Millimeter bei „echten" 100 % — der CSS-Referenzpixel ist per - * Spezifikation auf 1/96 Zoll fixiert (96 px = 25.4 mm), UNABHÄNGIG von der - * physischen Bildschirmauflösung (`devicePixelRatio` gleicht das pro Gerät - * wieder aus). `SheetTransform.scale` ist „Pixel pro Millimeter" — bei diesem - * Wert misst ein A4-Blatt (210 mm) auf dem Bildschirm also wirklich 21 cm - * (Nutzer-Wunsch), nicht nur „passt ins Fenster" wie bei „Einpassen". - */ -const PX_PER_MM_AT_100 = 96 / 25.4; - -/** Zeichenwerkzeug für die Annotations-Schicht (zusätzlich zum Viewport-„placing"). */ -type AnnotTool = "select" | "line" | "rect" | "text" | "image"; - -/** - * Bildet das GLOBALE Werkzeug (linkes Werkzeugpanel, `ToolId`) auf ein - * `AnnotTool` ab — das Blatt hat keine eigene Werkzeugleiste mehr (Nutzer- - * Feedback: „ein Layout soll daherkommen wie eine normale Zeichnung, nur dass - * ein Blatt drin liegt" — dieselben Zeichenwerkzeuge links wie im Grundriss, - * nichts Eigenes nur fürs Layout). `textbox` zeichnet hier wie `text` (kein - * eigener Spaltenbreite-Ablauf im Blatt); alle übrigen Werkzeuge (Wand, Fenster, - * Kreis, …) ergeben auf dem Blatt keinen Sinn → „select". - */ -function annotToolFromGlobal(tool: ToolId): AnnotTool { - if (tool === "line" || tool === "rect" || tool === "image") return tool; - if (tool === "text" || tool === "textbox") return "text"; - return "select"; -} +/** Akzent der Viewport-Auswahl (wie bisher). */ +const ACCENT = "#3b82f6"; type Drag = - | { mode: "pan"; lastX: number; lastY: number } - | { mode: "move"; id: string; start: RectMm; grabX: number; grabY: number } - | { mode: "resize"; id: string; handle: Handle; start: RectMm; grabX: number; grabY: number } | { mode: "place"; x0: number; y0: number } - | { mode: "annot-move"; id: string; start: LayoutAnnotation; grabX: number; grabY: number } - | { - mode: "annot-resize"; - id: string; - hit: AnnotHandleHit; - start: LayoutAnnotation; - grabX: number; - grabY: number; - } - | null; + | { mode: "edit"; id: string; handle: Handle; grab: { xMm: number; yMm: number }; start: RectMm }; -/** Cursor für einen Linien-Endpunkt-Griff (kein direktes `Handle`-Äquivalent). */ -function lineHandleCursor(handle: LineHandle): string { - return handle === "body" ? "move" : "crosshair"; +function round1(v: number): number { + return Math.round(v * 10) / 10; } -/** Annotation abzüglich `id`/`kind` als Patch — für den Commit nach Move/Draw. */ -function annotationPatch(a: LayoutAnnotation): LayoutAnnotationPatch { - const { id: _id, kind: _kind, ...rest } = a as LayoutAnnotation & Record; - return rest as LayoutAnnotationPatch; +/** Trifft die Klick-Auswahl gar nichts Gezeichnetes (Leerraum)? */ +function isEmptyPick(s: PlanSelection): boolean { + return ( + s.hitIndex === null && + !s.wallId && + !s.drawingId && + !s.ceilingId && + !s.openingId && + !s.stairId && + !s.roomId && + !s.extrudedSolidId && + !s.columnId && + !s.roofId && + !s.sectionLineId && + !s.contextObjectId + ); } -export function LayoutSheetView({ +/** + * Rahmen eines offenen Layout-Blatts um die Plan-Ansicht der Blatt-Ebene (`children`). Hält nur + * den Viewport-Zustand (Auswahl, Platzieren, Ziehen); alles Zeichnen läuft in der Plan-Ansicht. + */ +export function LayoutSheetPane({ project, layout, handlers, - activeTool, - onToolChange, - selectedAnnotId, - onSelectAnnot, + toolInputActive, + onPlanSelect, + planViewRef, + children, }: { project: Project; layout: Layout; handlers: LayoutSheetHandlers; - /** Globales Werkzeug (linkes Werkzeugpanel) — s. `annotToolFromGlobal`. */ - activeTool: ToolId; - /** Setzt das globale Werkzeug (z. B. zurück auf „select" nach einer Platzierung). */ - onToolChange: (id: ToolId) => void; - /** - * Gewählte Annotation — von App.tsx gehoben (statt lokalem State), damit die - * echte Attribute-Palette (rechtes Panel) dieselbe Auswahl sieht wie ein - * Drawing2D im Grundriss (Nutzer-Feedback: „Attribute genau wie bei - * normalen Linien beim Zeichnen"). - */ - selectedAnnotId: string | null; - onSelectAnnot: (id: string | null) => void; + /** Liegt die linke Maustaste beim Werkzeug/Befehl? Dann sind die Viewports nicht greifbar. */ + toolInputActive: boolean; + onPlanSelect: (sel: PlanSelection) => void; + planViewRef: RefObject; + children: (props: SheetPlanProps) => ReactNode; }) { - // Alias, damit die bestehenden `setSelectedAnnotId(...)`-Aufrufe unten - // unverändert bleiben (jetzt ein gehobener Prop-Setter statt lokalem State). - const setSelectedAnnotId = onSelectAnnot; - const stageRef = useRef(null); - const [canvas, setCanvas] = useState({ w: 800, h: 600 }); - const [transform, setTransform] = useState(null); const [selectedId, setSelectedId] = useState(null); - const [hoverCursor, setHoverCursor] = useState("default"); - // Werkzeug-Modus „Viewport aufziehen" (armiert). Danach folgt der Ausschnitt-Picker. + // „Viewport aufziehen" armiert; danach folgt ggf. die Ausschnitt-Bindung. const [placing, setPlacing] = useState(false); - // Live-Geometrie während eines Move/Resize/Place-Drags (Ghost), sonst null. - const [previewRect, setPreviewRect] = useState(null); - // Nach dem Aufziehen: das fertige Rechteck (mm) wartet auf die Ausschnitt-Bindung. + // Live-Geometrie während Platzieren/Verschieben/Skalieren (Ghost), sonst null. + const [preview, setPreview] = useState<{ drag: Drag; rect: RectMm } | null>(null); const [pendingRect, setPendingRect] = useState(null); - const [bindSnapId, setBindSnapId] = useState(""); - const dragRef = useRef(null); - const spaceDownRef = useRef(false); - - // ── Annotationen (Linie/Rechteck/Text) — eigenständige Zusatzschicht ──────── - // Werkzeug „select" = normale Auswahl/Verschieben von Viewports+Annotationen; - // line/rect/text armieren das jeweilige Zeichnen (analog `placing` für Viewports). - // KEIN eigener Werkzeug-Zustand mehr — armiert wird über das globale Werkzeug - // (linkes Panel), s. `annotToolFromGlobal`. - const annotTool = annotToolFromGlobal(activeTool); - // Ghost-Geometrie: beim Aufziehen einer NEUEN Linie/eines Rechtecks (id="draft") - // ODER beim Verschieben einer bestehenden Annotation (id = deren echte Id). - const [annotPreview, setAnnotPreview] = useState(null); - // Textwerkzeug: Rahmen aufziehen (Ghost, wie ein Rechteck) — direkt danach - // öffnet `inlineEdit` den Editor IM Rahmen (kein eigenes Fenster). - const [textFrameDraft, setTextFrameDraft] = useState(null); - // Erster Klick von Linie/Rechteck/Text: KEIN Ziehen nötig (Nutzer-Feedback — - // „alle 2D-Werkzeuge sollen sich gleich verhalten wie im Grundriss"), also - // Klick-Bewegen-Klick wie die Plan-Zeichenwerkzeuge (tools.ts `lineTool`/ - // `rectTool`): erster Klick setzt diesen Punkt, die Maus bewegt den Ghost - // (`onPointerMove` läuft auch OHNE gehaltene Taste), der zweite Klick - // schliesst ab. `null` = kein Werkzeug wartet auf den zweiten Klick. - const [pendingPoint, setPendingPoint] = useState< - { tool: "line" | "rect" | "text"; xMm: number; yMm: number } | null - >(null); - // Wechselt der Nutzer das Werkzeug, während ein erster Klick offen ist (z. B. - // Escape/anderes Werkzeug im linken Panel), verwirft das den offenen Entwurf. - useEffect(() => { - setPendingPoint(null); - setAnnotPreview((p) => (p?.id === "draft" ? null : p)); - setTextFrameDraft(null); - }, [annotTool]); - // Aktuell inline bearbeitete Text-Annotation (neu erstellt ODER per HUD „✎" - // geöffnet) — `minHeightMm` ist die beim Aufziehen gewählte Rahmenhöhe (rein - // fürs Editor-Startmass, nicht Teil des Modells — Text wächst mit dem Inhalt). - const [inlineEdit, setInlineEdit] = useState<{ id: string; minHeightMm: number } | null>(null); - // Bild-Werkzeug: nach dem Klick wartet die Position auf die Datei-Auswahl - // (async, s. imageInputRef weiter unten). - const [imagePendingAt, setImagePendingAt] = useState<{ xMm: number; yMm: number } | null>(null); - const imageInputRef = useRef(null); + const [bindSnapId, setBindSnapId] = useState(""); + const gRef = useRef(null); const master = findMaster(project, layout); - // Effektive Grösse respektiert freie Grösse (custom Width/Height) — bindet - // das Layout an ein Masterlayout, gewinnt dessen Grösse (wie im PDF-Export, - // `folderPdfPages`: `effectiveSheetSizeMm(master ?? layout)`). + // Effektive Grösse: ein gebundener Master gewinnt (wie im PDF-Export, `folderPdfPages`). const sheet = effectiveSheetSizeMm(master ?? layout); const titleBlock = resolveTitleBlock(project, layout, master); const drawBorder = master ? master.border ?? true : false; const snapshots = project.viewSnapshots ?? []; const selectedVp = layout.viewports.find((v) => v.id === selectedId) ?? null; - const annotations = layout.annotations ?? []; - const selectedAnnot = annotations.find((a) => a.id === selectedAnnotId) ?? null; - // Verfügbare Fläche messen. + // Gelöschter Viewport / anderes Blatt → Auswahl und laufendes Platzieren verwerfen. useEffect(() => { - const el = stageRef.current; - if (!el) return; - const ro = new ResizeObserver((entries) => { - for (const e of entries) { - setCanvas({ w: e.contentRect.width, h: e.contentRect.height }); - } - }); - ro.observe(el); - return () => ro.disconnect(); - }, []); - - // Erst-Einpassung, sobald die Fläche gemessen ist (einmal). Bei Blattwechsel - // (Papier/Ausrichtung) neu einpassen. - useEffect(() => { - if (canvas.w <= 0 || canvas.h <= 0) return; - setTransform((cur) => - cur ?? fitTransform(sheet.w, sheet.h, canvas.w, canvas.h), - ); - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [canvas.w, canvas.h]); - useEffect(() => { - if (canvas.w <= 0 || canvas.h <= 0) return; - setTransform(fitTransform(sheet.w, sheet.h, canvas.w, canvas.h)); - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [sheet.w, sheet.h]); - - const fit = () => setTransform(fitTransform(sheet.w, sheet.h, canvas.w, canvas.h)); - const zoomStep = (factor: number) => - setTransform((t) => (t ? zoomAtCursor(t, factor, canvas.w / 2, canvas.h / 2) : t)); - // Springt auf echte 1:1-Grösse (s. PX_PER_MM_AT_100), zentriert auf die - // Canvas-Mitte statt den Cursor (kein aktives Zoom-Gesten-Event hier). - const zoomTo100 = () => - setTransform((t) => - t ? zoomAtCursor(t, PX_PER_MM_AT_100 / t.scale, canvas.w / 2, canvas.h / 2) : t, - ); - const zoomPercent = Math.round(((transform?.scale ?? 0) / PX_PER_MM_AT_100) * 100); - - // Leertaste = Pan-Modifikator (wie in CAD). Delete/Backspace löscht die Auswahl. - useEffect(() => { - const down = (e: KeyboardEvent) => { - const el = e.target as HTMLElement | null; - const typing = - el && (el.tagName === "INPUT" || el.tagName === "TEXTAREA" || el.isContentEditable); - if (typing) return; - if (e.code === "Space") { - spaceDownRef.current = true; - e.preventDefault(); // kein Button-Reklick / Seiten-Scroll - return; - } - if (e.key === "Escape") { - if (placing) { - setPlacing(false); - setPreviewRect(null); - } else if (annotTool !== "select") { - onToolChange("select"); - setAnnotPreview(null); - setTextFrameDraft(null); - } else if (pendingRect) { - setPendingRect(null); - } else if (selectedAnnotId) { - setSelectedAnnotId(null); - } else { - setSelectedId(null); - } - } else if ((e.key === "Delete" || e.key === "Backspace") && selectedId) { - handlers.onRemoveViewport(selectedId); - setSelectedId(null); - e.preventDefault(); - } else if ((e.key === "Delete" || e.key === "Backspace") && selectedAnnotId) { - handlers.onRemoveAnnotation(selectedAnnotId); - setSelectedAnnotId(null); - e.preventDefault(); - } - }; - const up = (e: KeyboardEvent) => { - if (e.code === "Space") spaceDownRef.current = false; - }; - window.addEventListener("keydown", down); - window.addEventListener("keyup", up); - return () => { - window.removeEventListener("keydown", down); - window.removeEventListener("keyup", up); - }; - }, [ - placing, - pendingRect, - selectedId, - selectedAnnotId, - annotTool, - handlers, - onToolChange, - ]); - - // Bildschirm-Pixel (canvas-lokal) eines Pointer-Events. - const localXY = (e: { clientX: number; clientY: number }) => { - const rect = stageRef.current?.getBoundingClientRect(); - return { x: e.clientX - (rect?.left ?? 0), y: e.clientY - (rect?.top ?? 0) }; - }; - - // Zoom-to-Cursor am Rad: nativer, NICHT-passiver Listener (preventDefault muss - // greifen — React-onWheel ist passiv). Funktionales setTransform, damit der - // Listener nur einmal registriert werden muss. - useEffect(() => { - const el = stageRef.current; - if (!el) return; - const onWheel = (e: WheelEvent) => { - e.preventDefault(); - const rect = el.getBoundingClientRect(); - const x = e.clientX - rect.left; - const y = e.clientY - rect.top; - const factor = e.deltaY < 0 ? 1.12 : 1 / 1.12; - setTransform((t) => (t ? zoomAtCursor(t, factor, x, y) : t)); - }; - el.addEventListener("wheel", onWheel, { passive: false }); - return () => el.removeEventListener("wheel", onWheel); - }, []); - - // Schliesst Linie/Rechteck/Text-Rahmen beim ZWEITEN Klick ab (erster Punkt = - // `pendingPoint`, zweiter = `mm`) — dieselbe Zwei-Klick-Logik, die vorher am - // `pointerup` einer gehaltenen Ziehgeste hing (s. Git-Historie), jetzt ohne - // gehaltene Taste nötig. - const commitTwoPointAnnot = ( - tool: "line" | "rect" | "text", - p0: { xMm: number; yMm: number }, - p1: { xMm: number; yMm: number }, - ) => { - if (tool === "line") { - const len = Math.hypot(p1.xMm - p0.xMm, p1.yMm - p0.yMm); - if (len >= MIN_ANNOT_MM) { - handlers.onAddAnnotation("line", { - x1Mm: round1(p0.xMm), - y1Mm: round1(p0.yMm), - x2Mm: round1(p1.xMm), - y2Mm: round1(p1.yMm), - }); - } - return; - } - const r = normalizeRect(p0.xMm, p0.yMm, p1.xMm, p1.yMm); - if (tool === "rect") { - if (r.widthMm >= MIN_ANNOT_MM && r.heightMm >= MIN_ANNOT_MM) { - const clamped = clampRectToSheet(r, sheet.w, sheet.h); - handlers.onAddAnnotation("rect", { - xMm: round1(clamped.xMm), - yMm: round1(clamped.yMm), - widthMm: round1(clamped.widthMm), - heightMm: round1(clamped.heightMm), - }); - } - return; - } - // Text: zu klein aufgezogen (praktisch ein Doppelklick auf der Stelle) → - // Default-Rahmen an der Klickstelle, statt eine Mini-Box zu erzwingen. - const tooSmall = r.widthMm < MIN_ANNOT_MM || r.heightMm < MIN_ANNOT_MM; - const widthMm = tooSmall ? 60 : r.widthMm; - const frameHeightMm = tooSmall ? 20 : r.heightMm; - const clamped = clampRectToSheet({ xMm: r.xMm, yMm: r.yMm, widthMm, heightMm: frameHeightMm }, sheet.w, sheet.h); - // `yMm` einer Text-Annotation ist die BASELINE der ersten Zeile (s. - // `annotationBoundsMm`) — der aufgezogene Rahmen liefert die OBERE Kante, - // daher + eine Zeilenhöhe (heightMm = Schriftgrösse). - const id = handlers.onAddAnnotation("text", { - xMm: round1(clamped.xMm), - yMm: round1(clamped.yMm + DEFAULT_ANNOT_TEXT_MM), - widthMm: round1(clamped.widthMm), - heightMm: DEFAULT_ANNOT_TEXT_MM, - text: "", - }); - setSelectedAnnotId(id); - setInlineEdit({ id, minHeightMm: clamped.heightMm }); - }; - - const onPointerDown = (e: ReactPointerEvent) => { - if (!transform) return; - // Klicks aus dem HUD/Popover (echte Bedienelemente) NICHT als Blatt-Geste werten. - if ((e.target as HTMLElement).closest("[data-sheet-ui]")) return; - const { x, y } = localXY(e); - (e.currentTarget as HTMLElement).setPointerCapture(e.pointerId); - - // Pan: mittlere Maustaste oder Leertaste-Drag. - if (e.button === 1 || spaceDownRef.current) { - dragRef.current = { mode: "pan", lastX: x, lastY: y }; - return; - } - if (e.button !== 0) return; - - const mm = screenToMm(transform, x, y); - - // Platzierungs-Modus: Rechteck aufziehen. - if (placing) { - dragRef.current = { mode: "place", x0: mm.xMm, y0: mm.yMm }; - setPreviewRect({ xMm: mm.xMm, yMm: mm.yMm, widthMm: 0, heightMm: 0 }); - return; - } - - // Annotations-Werkzeuge Linie/Rechteck/Text: Klick-Bewegen-Klick wie im - // Grundriss (kein Ziehen nötig) — erster Klick merkt sich den Punkt - // (`pendingPoint`), der zweite (hier) schliesst ab. Bild bleibt ein - // Einzelklick, der sofort den Datei-Dialog öffnet (async, s. imageInputRef). - if (annotTool === "image") { - setImagePendingAt({ xMm: mm.xMm, yMm: mm.yMm }); - imageInputRef.current?.click(); - return; - } - if (annotTool === "line" || annotTool === "rect" || annotTool === "text") { - if (pendingPoint && pendingPoint.tool === annotTool) { - commitTwoPointAnnot(annotTool, pendingPoint, mm); - setPendingPoint(null); - setAnnotPreview(null); - setTextFrameDraft(null); - // Linie/Rechteck bleiben armiert für die nächste (Plan-Konvention: - // tools.ts `lineTool`/`rectTool` bleiben nach dem Commit ebenfalls - // aktiv statt auf „Auswahl" zu springen — mehrere Linien am Stück ohne - // erneuten Werkzeug-Klick). Text springt zurück auf „Auswahl": direkt - // danach öffnet der Inline-Editor, ein weiterer Klick soll den Cursor - // darin setzen, keinen neuen Rahmen aufziehen. - if (annotTool === "text") onToolChange("select"); - return; - } - setPendingPoint({ tool: annotTool, xMm: mm.xMm, yMm: mm.yMm }); - if (annotTool === "line") { - setAnnotPreview({ id: "draft", kind: "line", x1Mm: mm.xMm, y1Mm: mm.yMm, x2Mm: mm.xMm, y2Mm: mm.yMm }); - } else if (annotTool === "rect") { - setAnnotPreview({ id: "draft", kind: "rect", xMm: mm.xMm, yMm: mm.yMm, widthMm: 0, heightMm: 0 }); - } else { - setTextFrameDraft({ xMm: mm.xMm, yMm: mm.yMm, widthMm: 0, heightMm: 0 }); - } - return; - } - - const tolMm = HANDLE_TOL_PX / transform.scale; - const hit = pickViewport(layout.viewports, mm.xMm, mm.yMm, tolMm); - if (hit) { - setSelectedId(hit.id); - setSelectedAnnotId(null); - const vp = layout.viewports.find((v) => v.id === hit.id)!; - if (hit.handle === "body") { - dragRef.current = { - mode: "move", - id: hit.id, - start: vpRect(vp), - grabX: mm.xMm, - grabY: mm.yMm, - }; - } else { - dragRef.current = { - mode: "resize", - id: hit.id, - handle: hit.handle, - start: vpRect(vp), - grabX: mm.xMm, - grabY: mm.yMm, - }; - } - return; - } - - const annotHit = pickAnnotationHandle(annotations, mm.xMm, mm.yMm, tolMm); - if (annotHit) { - setSelectedId(null); - setSelectedAnnotId(annotHit.id); - const ann = annotations.find((a) => a.id === annotHit.id)!; - if (annotHit.hit.handle === "body") { - dragRef.current = { - mode: "annot-move", - id: annotHit.id, - start: ann, - grabX: mm.xMm, - grabY: mm.yMm, - }; - } else { - dragRef.current = { - mode: "annot-resize", - id: annotHit.id, - hit: annotHit.hit, - start: ann, - grabX: mm.xMm, - grabY: mm.yMm, - }; - } - } else { - setSelectedId(null); - setSelectedAnnotId(null); - } - }; - - // Doppelklick auf ein bestehendes Textfeld öffnet die Bearbeitung wieder — - // wie InDesign/Affinity (bisher nur über den „✎"-Knopf im HUD erreichbar). - const onDoubleClick = (e: ReactMouseEvent) => { - if (!transform || annotTool !== "select") return; - if ((e.target as HTMLElement).closest("[data-sheet-ui]")) return; - const { x, y } = localXY(e); - const mm = screenToMm(transform, x, y); - const tolMm = HANDLE_TOL_PX / transform.scale; - const hit = pickAnnotationHandle(annotations, mm.xMm, mm.yMm, tolMm); - if (!hit) return; - const ann = annotations.find((a) => a.id === hit.id); - if (!ann || ann.kind !== "text") return; setSelectedId(null); - setSelectedAnnotId(ann.id); - setInlineEdit({ id: ann.id, minHeightMm: annotationBoundsMm(ann).heightMm }); + setPlacing(false); + setPendingRect(null); + }, [layout.id]); + // Ein Werkzeug/Befehl übernimmt die Maus → Viewport-Auswahl und Platzieren ruhen. + useEffect(() => { + if (toolInputActive) { + setSelectedId(null); + setPlacing(false); + } + }, [toolInputActive]); + + // Entf löscht den gewählten Viewport, Escape hebt Auswahl/Platzieren auf (nicht in Eingabefeldern). + useEffect(() => { + if (!selectedVp && !placing) return; + const onKey = (e: KeyboardEvent) => { + const el = e.target as HTMLElement | null; + if (el && (el.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(el.tagName))) return; + if (e.key === "Escape") { + setSelectedId(null); + setPlacing(false); + } else if ((e.key === "Delete" || e.key === "Backspace") && selectedVp) { + e.preventDefault(); + e.stopPropagation(); + handlers.onRemoveViewport(selectedVp.id); + setSelectedId(null); + } + }; + window.addEventListener("keydown", onKey, true); + return () => window.removeEventListener("keydown", onKey, true); + }, [selectedVp, placing, handlers]); + + // Client-Pixel → Blatt-mm über die Bildschirm-Matrix der Blatt-Gruppe (enthält Pan/Zoom). + const toMm = (clientX: number, clientY: number): { xMm: number; yMm: number } | null => { + const m = gRef.current?.getScreenCTM(); + if (!m) return null; + const p = new DOMPoint(clientX, clientY).matrixTransform(m.inverse()); + return { xMm: p.x, yMm: p.y }; }; - const onPointerMove = (e: ReactPointerEvent) => { - if (!transform) return; - const { x, y } = localXY(e); - const drag = dragRef.current; - - if (!drag) { - // Wartet Linie/Rechteck/Text auf den zweiten Klick (`pendingPoint`), folgt - // der Ghost dem Cursor auch OHNE gehaltene Taste (Klick-Bewegen-Klick wie - // im Grundriss) — kein Hover-Cursor-Update nötig, das Werkzeug ist eh aktiv. - if (pendingPoint) { - const mm = screenToMm(transform, x, y); - if (pendingPoint.tool === "line") { - setAnnotPreview({ - id: "draft", - kind: "line", - x1Mm: pendingPoint.xMm, - y1Mm: pendingPoint.yMm, - x2Mm: mm.xMm, - y2Mm: mm.yMm, - }); - } else if (pendingPoint.tool === "rect") { - const r = normalizeRect(pendingPoint.xMm, pendingPoint.yMm, mm.xMm, mm.yMm); - setAnnotPreview({ id: "draft", kind: "rect", ...r }); - } else { - setTextFrameDraft(normalizeRect(pendingPoint.xMm, pendingPoint.yMm, mm.xMm, mm.yMm)); + const startDrag = (e: ReactPointerEvent, drag: Drag) => { + if (e.button !== 0) return; // Mitte = Schwenken der Plan-Ansicht + e.stopPropagation(); + e.preventDefault(); + const rect0 = drag.mode === "edit" ? drag.start : { xMm: drag.x0, yMm: drag.y0, widthMm: 0, heightMm: 0 }; + setPreview({ drag, rect: rect0 }); + let last = rect0; + const move = (ev: PointerEvent) => { + const mm = toMm(ev.clientX, ev.clientY); + if (!mm) return; + if (drag.mode === "place") { + last = normalizeRect(drag.x0, drag.y0, mm.xMm, mm.yMm); + } else { + const r = applyHandleDrag(drag.start, drag.handle, mm.xMm - drag.grab.xMm, mm.yMm - drag.grab.yMm, MIN_VP_MM); + last = drag.handle === "body" ? clampRectToSheet(r, sheet.w, sheet.h) : r; + } + setPreview({ drag, rect: last }); + }; + const up = () => { + window.removeEventListener("pointermove", move); + window.removeEventListener("pointerup", up); + window.removeEventListener("pointercancel", up); + setPreview(null); + if (drag.mode === "place") { + setPlacing(false); + if (last.widthMm >= MIN_PLACE_MM && last.heightMm >= MIN_PLACE_MM) { + const r = clampRectToSheet(last, sheet.w, sheet.h); + if (snapshots.length === 1) handlers.onAddViewport(snapshots[0].id, r); + else { + setPendingRect(r); + setBindSnapId(""); + } } return; } - // Nur Hover-Cursor aktualisieren (Griffe/Körper), wenn nicht am Ziehen. - const mm = screenToMm(transform, x, y); - const tolMm = HANDLE_TOL_PX / transform.scale; - const hit = pickViewport(layout.viewports, mm.xMm, mm.yMm, tolMm); - const annotHit = !hit ? pickAnnotationHandle(annotations, mm.xMm, mm.yMm, tolMm) : null; - setHoverCursor( - placing || annotTool !== "select" - ? "crosshair" - : hit - ? handleCursor(hit.handle) - : annotHit - ? annotHit.hit.kind === "line" - ? lineHandleCursor(annotHit.hit.handle) - : handleCursor(annotHit.hit.handle) - : "default", - ); - return; - } - - if (drag.mode === "pan") { - setTransform((t) => (t ? panBy(t, x - drag.lastX, y - drag.lastY) : t)); - dragRef.current = { ...drag, lastX: x, lastY: y }; - return; - } - - const mm = screenToMm(transform, x, y); - if (drag.mode === "place") { - setPreviewRect(normalizeRect(drag.x0, drag.y0, mm.xMm, mm.yMm)); - return; - } - if (drag.mode === "move") { - const dx = mm.xMm - drag.grabX; - const dy = mm.yMm - drag.grabY; - const moved = applyHandleDrag(drag.start, "body", dx, dy, MIN_VP_MM); - setPreviewRect(clampRectToSheet(moved, sheet.w, sheet.h)); - return; - } - if (drag.mode === "resize") { - const dx = mm.xMm - drag.grabX; - const dy = mm.yMm - drag.grabY; - setPreviewRect(applyHandleDrag(drag.start, drag.handle, dx, dy, MIN_VP_MM)); - return; - } - if (drag.mode === "annot-move") { - const dx = mm.xMm - drag.grabX; - const dy = mm.yMm - drag.grabY; - setAnnotPreview(translateAnnotation(drag.start, dx, dy)); - return; - } - if (drag.mode === "annot-resize") { - const dx = mm.xMm - drag.grabX; - const dy = mm.yMm - drag.grabY; - if (drag.hit.kind === "line") { - if (drag.start.kind === "line") { - setAnnotPreview({ ...drag.start, ...applyLineHandleDrag(drag.start, drag.hit.handle, dx, dy) }); - } - } else if (drag.start.kind === "rect" || drag.start.kind === "image") { - const r = applyHandleDrag( - { xMm: drag.start.xMm, yMm: drag.start.yMm, widthMm: drag.start.widthMm, heightMm: drag.start.heightMm }, - drag.hit.handle, - dx, - dy, - MIN_ANNOT_MM, - ); - setAnnotPreview({ ...drag.start, ...r }); - } - return; - } - }; - - const endDrag = (e: ReactPointerEvent) => { - const el = e.currentTarget as HTMLElement; - if (el.hasPointerCapture(e.pointerId)) el.releasePointerCapture(e.pointerId); - const drag = dragRef.current; - dragRef.current = null; - if (!drag) return; - - if (drag.mode === "place") { - const r = previewRect; - setPreviewRect(null); - setPlacing(false); - if (r && r.widthMm >= MIN_PLACE_MM && r.heightMm >= MIN_PLACE_MM) { - const clamped = clampRectToSheet(r, sheet.w, sheet.h); - if (snapshots.length === 1) { - // Nur ein Ausschnitt → direkt binden. - handlers.onAddViewport(snapshots[0].id, clamped); - } else { - setPendingRect(clamped); - setBindSnapId(""); - } - } - return; - } - - if ((drag.mode === "move" || drag.mode === "resize") && previewRect) { - const r = clampRectToSheet(previewRect, sheet.w, sheet.h); + 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, { 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)), }); - } - setPreviewRect(null); + }; + window.addEventListener("pointermove", move); + window.addEventListener("pointerup", up); + window.addEventListener("pointercancel", up); + }; - if (drag.mode === "annot-move" || drag.mode === "annot-resize") { - if (annotPreview) { - handlers.onPatchAnnotation(drag.id, annotationPatch(annotPreview)); - } - setAnnotPreview(null); - return; + const displayRect = (vp: LayoutViewport): RectMm => + preview && preview.drag.mode === "edit" && preview.drag.id === vp.id ? preview.rect : vpRect(vp); + + const backdrop = (origin: Vec2, pxPerMeter: number): ReactNode => { + const k = PX_PER_M / 1000; // viewBox-Einheiten je mm + const pxPerMm = pxPerMeter / 1000; + const grip = pxPerMm > 0 ? GRIP_PX / pxPerMm : 2; + const hair = pxPerMm > 0 ? 1 / pxPerMm : 0.3; // 1 Bildschirm-Pixel in mm + const editable = !toolInputActive; + return ( + + {/* Papier mit leichtem Schatten (Bildschirm-Pixel), Rand 1 px. */} + + + {drawBorder && ( + + )} + {master && ( + + + + )} + {layout.viewports.map((vp) => { + const r = displayRect(vp); + const snap = findSnapshot(project, vp.snapshotId); + return ( + + {snap ? ( + + ) : ( + + + + {t("layouts.missingSnapshot")} + + + )} + + + ); + })} + {/* Gewählter Viewport: Körper (verschieben) + 8 Griffe (skalieren) — nur im Auswahl-Modus. */} + {selectedVp && editable && ( + + { + const grab = toMm(e.clientX, e.clientY); + if (grab) startDrag(e, { mode: "edit", id: selectedVp.id, handle: "body", grab, start: vpRect(selectedVp) }); + }} + /> + {handleAnchors(displayRect(selectedVp)).map((a) => ( + { + const grab = toMm(e.clientX, e.clientY); + if (grab) startDrag(e, { mode: "edit", id: selectedVp.id, handle: a.handle, grab, start: vpRect(selectedVp) }); + }} + /> + ))} + + )} + {/* Viewport aufziehen: das ganze Blatt fängt den Zug. */} + {placing && editable && ( + { + const p = toMm(e.clientX, e.clientY); + if (p) startDrag(e, { mode: "place", x0: p.xMm, y0: p.yMm }); + }} + /> + )} + {preview && preview.drag.mode === "place" && ( + + )} + + ); + }; + + // Einpassen = das Blatt (Modell-Meter, y nach oben). + const fitBounds = useMemo(() => { + const a = sheetMmToModel(0, sheet.h); + const b = sheetMmToModel(sheet.w, 0); + return { minX: a.x, minY: a.y, maxX: b.x, maxY: b.y }; + }, [sheet.w, sheet.h]); + + // Klick ins Leere über einem Viewport wählt ihn (Zeichnung darüber hat Vorrang: PlanView trifft sie). + const onSheetSelect = (sel: PlanSelection) => { + if (!toolInputActive && isEmptyPick(sel)) { + const mm = sheetModelToMm(sel.model); + const hit = pickViewport(layout.viewports, mm.xMm, mm.yMm, 0); + setSelectedId(hit ? hit.id : null); + } else { + setSelectedId(null); } + onPlanSelect(sel); }; const confirmBind = () => { - if (bindSnapId && pendingRect) { - handlers.onAddViewport(bindSnapId, pendingRect); - } + if (bindSnapId && pendingRect) handlers.onAddViewport(bindSnapId, pendingRect); setPendingRect(null); setBindSnapId(""); }; - // Blatt-Position (canvas-lokale Pixel) + Grösse. - const tf = transform ?? fitTransform(sheet.w, sheet.h, canvas.w, canvas.h); - const paperLeft = tf.tx; - const paperTop = tf.ty; - const paperW = sheet.w * tf.scale; - const paperH = sheet.h * tf.scale; - - // Effektives Rechteck eines Viewports (Ghost während seines Drags). - const displayRect = (vp: LayoutViewport): RectMm => - previewRect && - (dragRef.current?.mode === "move" || dragRef.current?.mode === "resize") && - dragRef.current?.id === vp.id - ? previewRect - : vpRect(vp); - return (
- {/* Werkzeugleiste (Blatt-Navigation + Platzieren + Zurück). */}
- - {/* Zeigt den echten Massstab (100 % = 1:1 auf dem Bildschirm, s. - PX_PER_MM_AT_100) und setzt ihn per Klick — wie die %-Anzeige in - Affinity/Figma, nicht nur „Einpassen" (das passt bloss ins Fenster). */} - - -
- {/* Blatt-Tisch: papierartiger Hintergrund, weisses Blatt zentriert. */} -
- {/* Weisses Papier. */} -
- {/* Master: Rahmen + Titelblock (read-only). */} - - {drawBorder && ( - - )} - {master && ( - - )} - +
+ {children({ backdrop, fitBounds, onPlanSelect: onSheetSelect })} - {/* Platzierte Viewports (echter Plan, geklippt). */} - {layout.viewports.map((vp) => { - const r = displayRect(vp); - const snap = findSnapshot(project, vp.snapshotId); - const selected = vp.id === selectedId; - return ( -
- {snap ? ( - - ) : ( -
{t("layouts.missingSnapshot")}
- )} -
- ); - })} - - {/* Annotationen (Linie/Rechteck/Text) — eigene Schicht ÜBER den Viewports, - in mm über dieselbe viewBox wie Rahmen/Titelblock. Während des - Zeichnens/Verschiebens ersetzt `annotPreview` die betroffene Annotation - (Ghost); ein neu gezeichnetes Element (id="draft") ist noch nicht in - `layout.annotations` und wird zusätzlich gerendert. */} - - {annotations.map((ann) => { - // Während des Inline-Editors NICHT zusätzlich statisch zeichnen - // (nur bei Text-Annotationen möglich, s. `inlineEdit`-Block - // unten) — sonst blieben Reste des alten Umbruchs sichtbar, - // weil das SVG nach geschätzter Zeichenbreite umbricht, der - // Editor-Browser aber nach echter Font-Metrik (leicht andere - // Zeilenumbrüche, Editor-Weiss deckt nicht jede Abweichung). - if (ann.id === inlineEdit?.id) return null; - const a = annotPreview && annotPreview.id === ann.id ? annotPreview : ann; - return ; - })} - {annotPreview && annotPreview.id === "draft" && ( - - )} - {/* Gestrichelter Auswahl-Rahmen um die gewählte Annotation. */} - {selectedAnnot && - (() => { - const display = - annotPreview && annotPreview.id === selectedAnnot.id - ? annotPreview - : selectedAnnot; - const b = annotationBoundsMm(display); - return ( - - ); - })()} - - - {/* Auswahl-Griffe des gewählten Viewports. */} - {selectedVp && - handleAnchors(displayRect(selectedVp)).map((a) => ( -
- ))} - - {/* Auswahl-Griffe der gewählten Annotation — Rechteck/Bild wie ein - Viewport (8 Ecken/Kanten), Linie mit ihren zwei Endpunkten (wie im - Grundriss). Text hat (noch) keine Griffe. */} - {selectedAnnot && - (() => { - const display = - annotPreview && annotPreview.id === selectedAnnot.id ? annotPreview : selectedAnnot; - if (display.kind === "rect" || display.kind === "image") { - return handleAnchors({ - xMm: display.xMm, - yMm: display.yMm, - widthMm: display.widthMm, - heightMm: display.heightMm, - }).map((a) => ( -
- )); - } - if (display.kind === "line") { - return lineHandleAnchors(display).map((p, i) => ( -
- )); - } - return null; - })()} - - {/* Ghost-Rechteck beim Aufziehen (Platzieren). */} - {previewRect && dragRef.current?.mode === "place" && ( -
- )} - - {/* Ghost-Rahmen beim Aufziehen eines neuen Textfelds. */} - {textFrameDraft && ( -
- )} -
- - {/* HUD: Eigenschaften des gewählten Viewports (Massstab/Grösse/Löschen). */} + {/* Eigenschaften des gewählten Viewports (Massstab/Grösse/Löschen). */} {selectedVp && (
- {findSnapshot(project, selectedVp.snapshotId)?.name ?? - t("layouts.missingSnapshot")} + {findSnapshot(project, selectedVp.snapshotId)?.name ?? t("layouts.missingSnapshot")}
)} - {/* HUD: Eigenschaften der gewählten Annotation (Farbe/Strichstärke/Text/ - Bild-Grösse/Löschen — je nach Art). */} - {selectedAnnot && ( -
-
{t(`layouts.annot.${selectedAnnot.kind}`)}
- {/* Position (mm, Blattkoordinaten oben-links) — für ALLE Arten über - dieselbe Bbox-Ableitung wie die Griffe (`annotationBoundsMm`); - der Commit verschiebt die ganze Annotation um das Delta - (`translateAnnotation`, dieselbe Funktion wie beim Ziehen). - Das ist der eigentliche Ort für X/Y einer Blatt-Annotation - (Papier-Millimeter) — NICHT das Objekt-Info-Panel (Modell-Meter, - zeigt für Layout-Markups bewusst „nicht anwendbar" statt 0/0). */} - {(() => { - const b = annotationBoundsMm(selectedAnnot); - const moveTo = (nxMm: number, nyMm: number) => { - const moved = translateAnnotation(selectedAnnot, nxMm - b.xMm, nyMm - b.yMm); - handlers.onPatchAnnotation(selectedAnnot.id, annotationPatch(moved)); - }; - return ( - <> - - - - ); - })()} - {/* Farbe/Strichstärke stehen jetzt in der echten Attribute-Palette - (dieselbe wie bei einer Linie im Grundriss, Nutzer-Feedback) — - hier nur noch Position + Grösse (Bild) + Aktionen, keine Dopplung. */} - {selectedAnnot.kind === "text" && ( -
{clip(selectedAnnot.text, 40)}
- )} - {selectedAnnot.kind === "image" && ( - <> - - - - )} -
- {selectedAnnot.kind === "text" && ( - - )} - -
-
- )} - {/* Ausschnitt-Bindung nach dem Aufziehen (Inline-Dropdown, kein prompt). */} {pendingRect && (
@@ -1282,259 +590,17 @@ export function LayoutSheetView({
)} - {/* Leer-Hinweis (keine Ausschnitte / keine Viewports). */} - {layout.viewports.length === 0 && - annotations.length === 0 && - !previewRect && - !pendingRect && ( -
- {snapshots.length === 0 - ? t("layouts.noSnapshots") - : placing - ? t("layouts.placeHint") - : t("layouts.emptyViewports")} -
- )} + {/* Hinweis beim Platzieren bzw. ohne Ausschnitte. */} + {(placing || snapshots.length === 0) && !pendingRect && layout.viewports.length === 0 && ( +
+ {snapshots.length === 0 ? t("layouts.noSnapshots") : t("layouts.placeHint")} +
+ )}
- - {/* Inline-Text-Editor DIREKT im Rahmen auf dem Blatt (kein eigenes Fenster, - Nutzer-Feedback) — für eine neu aufgezogene Text-Annotation (sofort - nach dem Aufziehen) ODER eine per HUD „✎" geöffnete bestehende. Jede - Änderung schreibt sofort zurück (`onPatchAnnotation`); ein Klick - daneben (Backdrop) oder Escape schliesst nur, es gibt nichts zu - verwerfen. WYSIWYG: Schriftgrösse UND Feldhöhe folgen dem echten - Blatt-Zoom über die CSS-Variablen `--rt-font-size`/`--rt-min-height` - (identisches Muster wie PlanView.tsx, s. dort) — NUR die Textfläche - skaliert, NICHT die Toolbar. Vorher lief das über ein - `transform:scale()` auf die GANZE Box (inkl. Toolbar, die dadurch - beim Reinzoomen riesig/unbedienbar wurde) UND `RichTextEditor` - schrieb pro Run trotzdem eine ABSOLUTE `pt`-Grösse (per Inline- - `style` auf jedem ``), die die geerbte Container-Grösse - ignoriert hätte, ohne den Transform-Umweg — beides zusammen war der - Bug hinter "Editor ist immer unterschiedlich gross wie der Text". - `sizeUnit="em"` auf `RichTextEditor` lässt Runs jetzt relativ zur - geerbten Grösse skalieren, s. `text/renderHtml.ts`. ZUSÄTZLICHER - Positions-Fix (Folgemeldung "Editor ist tiefer als der Text"): die - Toolbar stand bisher im normalen Fluss ÜBER der Textfläche und - schob sie um ihre eigene, zoomunabhängige Höhe nach unten — bei - üblichem Zoom mehr als die EINE Zeilenhöhe Versatz, mit der die - Box positioniert wird. `.rt-toolbar` schwebt jetzt per CSS - (`position:absolute; bottom:100%`, s. styles.css) OBERHALB der - Fläche, ausserhalb von deren Layout-Fluss. */} - {inlineEdit && - (() => { - const ann = annotations.find((a) => a.id === inlineEdit.id); - if (!ann || ann.kind !== "text") return null; - const doc = ann.doc ?? docFromText(ann.text); - const widthMm = ann.widthMm ?? 60; - const contentHeightMm = annotationBoundsMm(ann).heightMm; - const heightMm = Math.max(inlineEdit.minHeightMm, contentHeightMm); - const fontSizePx = Math.max(9, ann.heightMm * tf.scale); - const widthPx = widthMm * tf.scale; - const minHeightPx = heightMm * tf.scale; - // Baseline → Box-Oberkante: echtes Font-Measuring statt der groben - // "ganzes heightMm"-Näherung (s. PlanView.tsx, identischer Fix). - const baselineFromTop = contentFontBaselineFromTop(TEXT_LINE_HEIGHT_MULT); - const screen = mmToScreen(tf, { - xMm: ann.xMm, - yMm: ann.yMm - ann.heightMm * baselineFromTop, - }); - const cssVars = { - "--rt-font-size": `${fontSizePx}px`, - "--rt-min-height": `${minHeightPx}px`, - } as CSSProperties; - const commit = (edited: typeof doc) => - handlers.onPatchAnnotation( - ann.id, - { - doc: edited, - text: edited.paragraphs.map((p) => p.runs.map((r) => r.text).join("")).join("\n"), - }, - `layoutAnnotationText:${ann.id}`, - ); - return ( - <> -
setInlineEdit(null)} - /> -
e.stopPropagation()} - onKeyDown={(e) => { - if (e.key === "Escape") { - e.stopPropagation(); - setInlineEdit(null); - } - }} - > - -
- - ); - })()} - - {/* Verstecktes Bild/PDF-Datei-Input (Werkzeug „image"). */} - { - const f = e.target.files?.[0]; - e.target.value = ""; - onToolChange("select"); - const at = imagePendingAt; - setImagePendingAt(null); - if (!f || !at) return; - const isPdf = f.type === "application/pdf" || f.name.toLowerCase().endsWith(".pdf"); - if (isPdf) { - void rasterizePdfPages(f).then((pages) => { - pages.forEach((pg, i) => { - const { widthMm, heightMm } = defaultImageSizeMm(pg.naturalWidth, pg.naturalHeight); - const cascade = i * 6; - handlers.onAddAnnotation("image", { - xMm: at.xMm - widthMm / 2 + cascade, - yMm: at.yMm - heightMm / 2 + cascade, - widthMm, - heightMm, - src: pg.src, - }); - }); - }); - } else { - void readImageFile(f).then(({ src, naturalWidth, naturalHeight }) => { - const { widthMm, heightMm } = defaultImageSizeMm(naturalWidth, naturalHeight); - handlers.onAddAnnotation("image", { - xMm: at.xMm - widthMm / 2, - yMm: at.yMm - heightMm / 2, - widthMm, - heightMm, - src, - }); - }); - } - }} - />
); } -/** - * Rendert EINE Annotation im mm-viewBox: Linie/Rechteck als Umriss (Default - * `#111111`/0.25 mm, überschreibbar), Text als Baseline-`` mit - * `font-size = heightMm`. Ausgewählte Annotationen werden blau eingefärbt; - * `ghost` (Zeichnen-Vorschau) wird gestrichelt + halbtransparent dargestellt. - */ -function AnnotationSvg({ - ann, - selected, - ghost, -}: { - ann: LayoutAnnotation; - selected?: boolean; - ghost?: boolean; -}) { - const selectedColor = "#2478ff"; - const dash = ghost ? "2 1.5" : undefined; - const opacity = ghost ? 0.7 : 1; - if (ann.kind === "line") { - return ( - - ); - } - if (ann.kind === "rect") { - return ( - - ); - } - if (ann.kind === "image") { - return ( - - ); - } - // Text: reiches Doc (mehrere Absätze/gemischte Formatierung) hat Vorrang vor - // dem einfachen String — bricht bei gesetzter Rahmenbreite (`widthMm`) - // wortweise um (Run-Grenzen bleiben erhalten); Zeilen samt Lage aus dem Kern (`layoutText`). - if (ann.doc) { - const lines = annotationTextLines(ann, ann.doc); - return ( - - {lines.map((line, k) => { - return ( - - {line.tspans.length === 0 - ? "​" - : line.tspans.map((ts, j) => ( - - {ts.text} - - ))} - - ); - })} - - ); - } - return ( - - {ann.text} - - ); +function rectAttrs(r: RectMm) { + return { x: r.xMm, y: r.yMm, width: r.widthMm, height: r.heightMm }; } - -/** Auf 0.1 mm runden (weniger Rausch-Nachkommastellen beim Commit). */ -function round1(v: number): number { - return Math.round(v * 10) / 10; -} - diff --git a/src/ui/layoutSheetMath.test.ts b/src/ui/layoutSheetMath.test.ts index b1618b81..d998afd3 100644 --- a/src/ui/layoutSheetMath.test.ts +++ b/src/ui/layoutSheetMath.test.ts @@ -1,27 +1,13 @@ import { describe, expect, it } from "vitest"; -import type { LayoutAnnotation, LayoutViewport } from "../model/types"; +import type { LayoutViewport } from "../model/types"; import { - annotationBoundsMm, - annotationHandleAt, applyHandleDrag, - applyLineHandleDrag, clampRectToSheet, - distanceToSegment, - fitTransform, handleAt, - lineHandleAt, - mmToScreen, normalizeRect, - panBy, - pickAnnotation, - pickAnnotationHandle, pickViewport, - screenToMm, - translateAnnotation, vpRect, - zoomAtCursor, type RectMm, - type SheetTransform, } from "./layoutSheetMath"; const vp = ( @@ -32,64 +18,6 @@ const vp = ( heightMm: number, ): LayoutViewport => ({ id, snapshotId: "s", xMm, yMm, widthMm, heightMm }); -describe("mm ↔ screen", () => { - const t: SheetTransform = { scale: 2, tx: 100, ty: 50 }; - it("mmToScreen applies scale + translate", () => { - expect(mmToScreen(t, { xMm: 10, yMm: 20 })).toEqual({ x: 120, y: 90 }); - }); - it("screenToMm is the inverse", () => { - const p = screenToMm(t, 120, 90); - expect(p.xMm).toBeCloseTo(10); - expect(p.yMm).toBeCloseTo(20); - }); - it("roundtrips arbitrary points", () => { - const s = mmToScreen(t, { xMm: 37.5, yMm: -12.25 }); - const m = screenToMm(t, s.x, s.y); - expect(m.xMm).toBeCloseTo(37.5); - expect(m.yMm).toBeCloseTo(-12.25); - }); -}); - -describe("fitTransform", () => { - it("centres an A4 portrait sheet in a wide canvas", () => { - const t = fitTransform(210, 297, 1000, 600, 0.92); - // Höhe ist der Engpass: scale = 600*0.92/297. - expect(t.scale).toBeCloseTo((600 * 0.92) / 297); - // Zentriert: linker Rand = (1000 - 210*scale)/2. - expect(t.tx).toBeCloseTo((1000 - 210 * t.scale) / 2); - expect(t.ty).toBeCloseTo((600 - 297 * t.scale) / 2); - }); - it("falls back to scale 1 on degenerate canvas", () => { - const t = fitTransform(210, 297, 0, 0); - expect(t.scale).toBe(1); - }); -}); - -describe("zoomAtCursor", () => { - it("keeps the mm point under the cursor fixed", () => { - const t: SheetTransform = { scale: 2, tx: 100, ty: 50 }; - const cursor = { x: 300, y: 220 }; - const before = screenToMm(t, cursor.x, cursor.y); - const zt = zoomAtCursor(t, 1.25, cursor.x, cursor.y); - expect(zt.scale).toBeCloseTo(2.5); - const after = screenToMm(zt, cursor.x, cursor.y); - expect(after.xMm).toBeCloseTo(before.xMm); - expect(after.yMm).toBeCloseTo(before.yMm); - }); - it("clamps scale to bounds", () => { - const t: SheetTransform = { scale: 30, tx: 0, ty: 0 }; - const zt = zoomAtCursor(t, 4, 0, 0); - expect(zt.scale).toBeLessThanOrEqual(40); - }); -}); - -describe("panBy", () => { - it("shifts translation, keeps scale", () => { - const t = panBy({ scale: 3, tx: 10, ty: 20 }, 5, -7); - expect(t).toEqual({ scale: 3, tx: 15, ty: 13 }); - }); -}); - describe("handleAt", () => { const r: RectMm = { xMm: 20, yMm: 20, widthMm: 100, heightMm: 60 }; it("detects corners with priority over edges", () => { @@ -203,189 +131,3 @@ describe("vpRect", () => { }); }); }); - -// ── Annotationen (Linie/Rechteck/Text) ────────────────────────────────────── - -const line = (id: string, x1: number, y1: number, x2: number, y2: number): LayoutAnnotation => ({ - id, - kind: "line", - x1Mm: x1, - y1Mm: y1, - x2Mm: x2, - y2Mm: y2, -}); -const rect = (id: string, x: number, y: number, w: number, h: number): LayoutAnnotation => ({ - id, - kind: "rect", - xMm: x, - yMm: y, - widthMm: w, - heightMm: h, -}); -const text = (id: string, x: number, y: number, t: string, h = 3.5): LayoutAnnotation => ({ - id, - kind: "text", - xMm: x, - yMm: y, - text: t, - heightMm: h, -}); -const image = (id: string, x: number, y: number, w: number, h: number): LayoutAnnotation => ({ - id, - kind: "image", - xMm: x, - yMm: y, - widthMm: w, - heightMm: h, - src: "data:image/png;base64,", -}); - -describe("distanceToSegment", () => { - it("returns perpendicular distance for a point beside the segment", () => { - expect(distanceToSegment(5, 3, 0, 0, 10, 0)).toBeCloseTo(3); - }); - it("clamps to the nearest endpoint beyond the segment", () => { - expect(distanceToSegment(-4, 0, 0, 0, 10, 0)).toBeCloseTo(4); - expect(distanceToSegment(14, 0, 0, 0, 10, 0)).toBeCloseTo(4); - }); - it("degenerates to point distance for a zero-length segment", () => { - expect(distanceToSegment(3, 4, 0, 0, 0, 0)).toBeCloseTo(5); - }); -}); - -describe("annotationBoundsMm", () => { - it("rect: its own rectangle", () => { - expect(annotationBoundsMm(rect("r", 10, 20, 30, 40))).toEqual({ - xMm: 10, - yMm: 20, - widthMm: 30, - heightMm: 40, - }); - }); - it("line: normalized bounding rect of both endpoints", () => { - expect(annotationBoundsMm(line("l", 30, 30, 10, 10))).toEqual({ - xMm: 10, - yMm: 10, - widthMm: 20, - heightMm: 20, - }); - }); - it("text: box sits above the baseline, width grows with character count", () => { - const b = annotationBoundsMm(text("t", 10, 20, "AB", 4)); - expect(b.xMm).toBe(10); - expect(b.yMm).toBe(16); // 20 - heightMm - expect(b.heightMm).toBeCloseTo(5); // heightMm * 1.25 - expect(b.widthMm).toBeGreaterThan(0); - }); - it("image: its own rectangle, like rect", () => { - expect(annotationBoundsMm(image("i", 5, 5, 40, 30))).toEqual({ - xMm: 5, - yMm: 5, - widthMm: 40, - heightMm: 30, - }); - }); -}); - -describe("pickAnnotation", () => { - it("hits a line within tolerance of the segment", () => { - expect(pickAnnotation([line("l", 0, 0, 10, 0)], 5, 1, 2)).toBe("l"); - expect(pickAnnotation([line("l", 0, 0, 10, 0)], 5, 5, 2)).toBe(null); - }); - it("hits a rect on its border and its interior", () => { - const r = rect("r", 20, 20, 10, 10); - expect(pickAnnotation([r], 20, 20, 1)).toBe("r"); // corner - expect(pickAnnotation([r], 25, 25, 1)).toBe("r"); // interior - expect(pickAnnotation([r], 100, 100, 1)).toBe(null); - }); - it("hits a text annotation near its baseline box", () => { - const tx = text("t", 10, 20, "Hallo", 4); - expect(pickAnnotation([tx], 12, 18, 1)).toBe("t"); - expect(pickAnnotation([tx], 200, 200, 1)).toBe(null); - }); - it("returns the topmost (last) annotation in overlap, like pickViewport", () => { - const overlapping = [rect("a", 0, 0, 50, 50), rect("b", 10, 10, 50, 50)]; - expect(pickAnnotation(overlapping, 30, 30, 1)).toBe("b"); - }); - it("hits an image on its border and its interior, like rect", () => { - const img = image("i", 20, 20, 10, 10); - expect(pickAnnotation([img], 20, 20, 1)).toBe("i"); // corner - expect(pickAnnotation([img], 25, 25, 1)).toBe("i"); // interior - expect(pickAnnotation([img], 100, 100, 1)).toBe(null); - }); -}); - -describe("lineHandleAt", () => { - it("hits the first endpoint within tolerance", () => { - expect(lineHandleAt(0, 0, 10, 0, 0.5, 0.5, 2)).toBe("p1"); - }); - it("hits the second endpoint within tolerance", () => { - expect(lineHandleAt(0, 0, 10, 0, 9.5, 0.5, 2)).toBe("p2"); - }); - it("hits the body between the endpoints", () => { - expect(lineHandleAt(0, 0, 10, 0, 5, 1, 2)).toBe("body"); - }); - it("misses far away", () => { - expect(lineHandleAt(0, 0, 10, 0, 5, 20, 2)).toBe(null); - }); -}); - -describe("annotationHandleAt / pickAnnotationHandle", () => { - it("line: endpoint takes priority over body", () => { - const l = line("l", 0, 0, 10, 0); - expect(annotationHandleAt(l, 0, 0.5, 2)).toEqual({ kind: "line", handle: "p1" }); - expect(annotationHandleAt(l, 5, 0.5, 2)).toEqual({ kind: "line", handle: "body" }); - }); - it("rect: corner/edge/body like a viewport", () => { - const r = rect("r", 20, 20, 10, 10); - expect(annotationHandleAt(r, 20, 20, 1)).toEqual({ kind: "rect", handle: "nw" }); - expect(annotationHandleAt(r, 25, 25, 1)).toEqual({ kind: "rect", handle: "body" }); - }); - it("image: same handle set as rect", () => { - const img = image("i", 20, 20, 10, 10); - expect(annotationHandleAt(img, 30, 30, 1)).toEqual({ kind: "image", handle: "se" }); - }); - it("text: no handle system, plain bbox hit still reported as pickAnnotationHandle body", () => { - const tx = text("t", 10, 20, "Hallo", 4); - expect(annotationHandleAt(tx, 12, 18, 1)).toBe(null); - expect(pickAnnotationHandle([tx], 12, 18, 1)).toEqual({ - id: "t", - hit: { kind: "line", handle: "body" }, - }); - }); - it("pickAnnotationHandle returns null outside every annotation", () => { - expect(pickAnnotationHandle([line("l", 0, 0, 10, 0)], 500, 500, 1)).toBe(null); - }); -}); - -describe("applyLineHandleDrag", () => { - const l = line("l", 0, 0, 10, 0) as Extract; - it("p1 moves only the first endpoint", () => { - expect(applyLineHandleDrag(l, "p1", 2, 3)).toEqual({ x1Mm: 2, y1Mm: 3, x2Mm: 10, y2Mm: 0 }); - }); - it("p2 moves only the second endpoint", () => { - expect(applyLineHandleDrag(l, "p2", 2, 3)).toEqual({ x1Mm: 0, y1Mm: 0, x2Mm: 12, y2Mm: 3 }); - }); - it("body moves both endpoints", () => { - expect(applyLineHandleDrag(l, "body", 2, 3)).toEqual({ x1Mm: 2, y1Mm: 3, x2Mm: 12, y2Mm: 3 }); - }); -}); - -describe("translateAnnotation", () => { - it("moves both endpoints of a line", () => { - const moved = translateAnnotation(line("l", 0, 0, 10, 10), 5, -5); - expect(moved).toMatchObject({ x1Mm: 5, y1Mm: -5, x2Mm: 15, y2Mm: 5 }); - }); - it("moves the origin of a rect", () => { - const moved = translateAnnotation(rect("r", 10, 10, 20, 20), 3, 4); - expect(moved).toMatchObject({ xMm: 13, yMm: 14, widthMm: 20, heightMm: 20 }); - }); - it("moves the anchor point of a text annotation", () => { - const moved = translateAnnotation(text("t", 10, 10, "Hi"), 1, 2); - expect(moved).toMatchObject({ xMm: 11, yMm: 12, text: "Hi" }); - }); - it("moves the origin of an image, like rect", () => { - const moved = translateAnnotation(image("i", 10, 10, 20, 20), 3, 4); - expect(moved).toMatchObject({ xMm: 13, yMm: 14, widthMm: 20, heightMm: 20 }); - }); -}); diff --git a/src/ui/layoutSheetMath.ts b/src/ui/layoutSheetMath.ts index aa92f610..db003841 100644 --- a/src/ui/layoutSheetMath.ts +++ b/src/ui/layoutSheetMath.ts @@ -1,25 +1,14 @@ -// Reine, testbare Geometrie für die In-Viewport-Layout-Ansicht (Phase 2b): -// Bildschirm↔Blatt-mm-Transform (Pan/Zoom-to-Cursor/Einpassen), Viewport- +// Reine, testbare Geometrie für die Viewports auf dem Layout-Blatt: Viewport- // Trefferlogik (Body + 8 Resize-Griffe), Resize-Mathe mit Mindestgrösse, // Rechteck-Normalisierung (Aufziehen) und Clamp an die Blattkanten. // // KEINE React-/DOM-Abhängigkeit — nur Zahlen. Das UI (LayoutSheet.tsx) baut // darauf auf. Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md). -import type { LayoutAnnotation, LayoutViewport } from "../model/types"; +import type { LayoutViewport } from "../model/types"; -/** - * Affine Blatt-Transform: Bildschirm-Pixel = mm · scale + translate. - * `scale` ist px pro mm (immer > 0), `tx/ty` die Blatt-Ursprungslage (mm 0,0) - * in Canvas-Pixeln. - */ -export interface SheetTransform { - /** Pixel pro Millimeter (> 0). */ - scale: number; - /** Bildschirm-X des Blatt-Ursprungs (mm x=0) in Canvas-Pixeln. */ - tx: number; - /** Bildschirm-Y des Blatt-Ursprungs (mm y=0) in Canvas-Pixeln. */ - ty: number; +function clamp(v: number, lo: number, hi: number): number { + return v < lo ? lo : v > hi ? hi : v; } /** Ein Punkt in Blatt-Millimetern. */ @@ -48,68 +37,6 @@ export type Handle = | "w" | "body"; -export const MIN_SCALE = 0.05; -export const MAX_SCALE = 40; - -function clamp(v: number, lo: number, hi: number): number { - return v < lo ? lo : v > hi ? hi : v; -} - -// ── Transform ──────────────────────────────────────────────────────────────── - -/** Blatt-mm → Canvas-Pixel. */ -export function mmToScreen(t: SheetTransform, p: Mm): { x: number; y: number } { - return { x: p.xMm * t.scale + t.tx, y: p.yMm * t.scale + t.ty }; -} - -/** Canvas-Pixel → Blatt-mm. */ -export function screenToMm(t: SheetTransform, sx: number, sy: number): Mm { - return { xMm: (sx - t.tx) / t.scale, yMm: (sy - t.ty) / t.scale }; -} - -/** - * Einpass-Transform: Blatt (mm) zentriert in die Canvas-Fläche (px), mit - * `margin` (Anteil, z. B. 0.92 = 8 % Rand). Degenerierte Eingaben → scale=1. - */ -export function fitTransform( - sheetWMm: number, - sheetHMm: number, - canvasWPx: number, - canvasHPx: number, - margin = 0.92, -): SheetTransform { - const sx = (canvasWPx * margin) / sheetWMm; - const sy = (canvasHPx * margin) / sheetHMm; - let scale = Math.min(sx, sy); - if (!Number.isFinite(scale) || scale <= 0) scale = 1; - scale = clamp(scale, MIN_SCALE, MAX_SCALE); - const tx = (canvasWPx - sheetWMm * scale) / 2; - const ty = (canvasHPx - sheetHMm * scale) / 2; - return { scale, tx, ty }; -} - -/** - * Zoom um den Cursor: der mm-Punkt unter (sx,sy) bleibt fix. `factor` > 1 zoomt - * rein, < 1 raus; der Massstab wird auf [MIN_SCALE, MAX_SCALE] geklemmt. - */ -export function zoomAtCursor( - t: SheetTransform, - factor: number, - sx: number, - sy: number, -): SheetTransform { - const newScale = clamp(t.scale * factor, MIN_SCALE, MAX_SCALE); - // mm-Punkt unter dem Cursor VOR dem Zoom. - const m = screenToMm(t, sx, sy); - // Neue Translation, damit derselbe mm-Punkt wieder unter (sx,sy) liegt. - return { scale: newScale, tx: sx - m.xMm * newScale, ty: sy - m.yMm * newScale }; -} - -/** Verschiebt die Transform um (dxPx,dyPx) Canvas-Pixel (Pan). */ -export function panBy(t: SheetTransform, dxPx: number, dyPx: number): SheetTransform { - return { scale: t.scale, tx: t.tx + dxPx, ty: t.ty + dyPx }; -} - // ── Viewport-Rechtecke / Treffer ───────────────────────────────────────────── /** Rechteck-Sicht eines Viewports (nur die Blattgeometrie). */ @@ -320,221 +247,3 @@ export function handleAnchors(r: RectMm): { handle: Handle; xMm: number; yMm: nu { handle: "w", xMm: x, yMm: cy }, ]; } - -// ── Annotationen (Linie/Rechteck/Text/Bild) ───────────────────────────────── -// Rechteck/Bild teilen sich die Viewport-Griff-Mathe (dieselbe RectMm-Form, -// 8 Ecken/Kanten-Griffe). Linie bekommt zwei Endpunkt-Griffe (wie eine Linie -// im Grundriss). Text bleibt vorerst griff-los (Rahmen kommt beim Aufziehen). - -/** Kürzester Abstand (mm) eines Punkts zu einem Liniensegment. */ -export function distanceToSegment( - px: number, - py: number, - x1: number, - y1: number, - x2: number, - y2: number, -): number { - const dx = x2 - x1; - const dy = y2 - y1; - const lenSq = dx * dx + dy * dy; - if (lenSq === 0) return Math.hypot(px - x1, py - y1); - const t = clamp(((px - x1) * dx + (py - y1) * dy) / lenSq, 0, 1); - const cx = x1 + t * dx; - const cy = y1 + t * dy; - return Math.hypot(px - cx, py - cy); -} - -/** - * Umhüllendes Rechteck (mm) einer Annotation — für Text nur eine GROBE Box - * (kein echtes Font-Measuring im SVG; Breite aus Zeichenzahl geschätzt), reicht - * aber für Trefferlogik + Auswahl-Rahmen. `yMm` einer Text-Annotation ist die - * Baseline, die Box liegt daher oberhalb davon. - */ -export function annotationBoundsMm(ann: LayoutAnnotation): RectMm { - if (ann.kind === "rect" || ann.kind === "image") { - return { xMm: ann.xMm, yMm: ann.yMm, widthMm: ann.widthMm, heightMm: ann.heightMm }; - } - if (ann.kind === "line") { - return normalizeRect(ann.x1Mm, ann.y1Mm, ann.x2Mm, ann.y2Mm); - } - // Text: grobe Box aus Zeichenzahl geschätzt (kein echtes Font-Measuring im - // SVG) — bei gesetzter Rahmenbreite (`widthMm`, Rich-Text-Frame) gilt diese - // statt der Schätzung; die Höhe bleibt eine grobe Zeilenschätzung. - const estWidthMm = Math.max(ann.heightMm, ann.text.length * ann.heightMm * 0.6); - const lines = ann.doc ? Math.max(1, ann.doc.paragraphs.length) : 1; - return { - xMm: ann.xMm, - yMm: ann.yMm - ann.heightMm, - widthMm: ann.widthMm ?? estWidthMm, - heightMm: ann.heightMm * 1.25 * lines, - }; -} - -/** - * Trefferlogik (mm) für EINE Annotation: Linie → Abstand zum Segment ≤ tolMm; - * Rechteck → Rahmen ODER Innenfläche (wiederverwendet {@link handleAt}, jeder - * Nicht-null-Rückgabewert zählt als Treffer); Text → Bounding-Box + Toleranz. - */ -export function annotationHit( - ann: LayoutAnnotation, - xMm: number, - yMm: number, - tolMm: number, -): boolean { - if (ann.kind === "line") { - return distanceToSegment(xMm, yMm, ann.x1Mm, ann.y1Mm, ann.x2Mm, ann.y2Mm) <= tolMm; - } - if (ann.kind === "rect" || ann.kind === "image") { - const r: RectMm = { xMm: ann.xMm, yMm: ann.yMm, widthMm: ann.widthMm, heightMm: ann.heightMm }; - return handleAt(r, xMm, yMm, tolMm) !== null; - } - const b = annotationBoundsMm(ann); - return ( - xMm >= b.xMm - tolMm && - xMm <= b.xMm + b.widthMm + tolMm && - yMm >= b.yMm - tolMm && - yMm <= b.yMm + b.heightMm + tolMm - ); -} - -/** - * Topmost-Treffer über eine Annotations-Liste (letzte = oberste, wie - * {@link pickViewport}). Liefert die Id des ERSTEN Treffers von oben, sonst null. - */ -export function pickAnnotation( - annotations: LayoutAnnotation[], - xMm: number, - yMm: number, - tolMm: number, -): string | null { - for (let i = annotations.length - 1; i >= 0; i--) { - const a = annotations[i]; - if (annotationHit(a, xMm, yMm, tolMm)) return a.id; - } - return null; -} - -// ── Resize-Griffe für Annotationen (wie im Grundriss: Endpunkte/Ecken) ────── - -/** Griff einer Linien-Annotation: die beiden Endpunkte oder der Körper. */ -export type LineHandle = "p1" | "p2" | "body"; - -/** Griff-Ergebnis für EINE Annotation — je Art ein anderer Griff-Typ. */ -export type AnnotHandleHit = - | { kind: "rect" | "image"; handle: Handle } - | { kind: "line"; handle: LineHandle }; - -/** - * Griff (oder Körper) einer Linien-Annotation an einem mm-Punkt: die - * Endpunkte haben Vorrang vor dem Segment (wie ein Linien-Griff im Grundriss). - */ -export function lineHandleAt( - x1: number, - y1: number, - x2: number, - y2: number, - xMm: number, - yMm: number, - tolMm: number, -): LineHandle | null { - if (Math.hypot(xMm - x1, yMm - y1) <= tolMm) return "p1"; - if (Math.hypot(xMm - x2, yMm - y2) <= tolMm) return "p2"; - if (distanceToSegment(xMm, yMm, x1, y1, x2, y2) <= tolMm) return "body"; - return null; -} - -/** - * Griff (oder Körper) EINER Annotation an einem mm-Punkt — Linie liefert einen - * Endpunkt-Griff, Rechteck/Bild die 8 Viewport-artigen Ecken-/Kanten-Griffe - * (wiederverwendet {@link handleAt}). Text hat (noch) keine Griffe → `null`. - */ -export function annotationHandleAt( - ann: LayoutAnnotation, - xMm: number, - yMm: number, - tolMm: number, -): AnnotHandleHit | null { - if (ann.kind === "line") { - const h = lineHandleAt(ann.x1Mm, ann.y1Mm, ann.x2Mm, ann.y2Mm, xMm, yMm, tolMm); - return h ? { kind: "line", handle: h } : null; - } - if (ann.kind === "rect" || ann.kind === "image") { - const r: RectMm = { xMm: ann.xMm, yMm: ann.yMm, widthMm: ann.widthMm, heightMm: ann.heightMm }; - const h = handleAt(r, xMm, yMm, tolMm); - return h ? { kind: ann.kind, handle: h } : null; - } - return null; -} - -/** - * Topmost Griff-Treffer über eine Annotations-Liste (wie {@link pickAnnotation}, - * aber liefert zusätzlich den konkreten Griff für Resize statt nur Verschieben). - */ -export function pickAnnotationHandle( - annotations: LayoutAnnotation[], - xMm: number, - yMm: number, - tolMm: number, -): { id: string; hit: AnnotHandleHit } | null { - for (let i = annotations.length - 1; i >= 0; i--) { - const a = annotations[i]; - const hit = annotationHandleAt(a, xMm, yMm, tolMm); - if (hit) return { id: a.id, hit }; - if (annotationHit(a, xMm, yMm, tolMm)) { - // Text (kein Griff-System) oder ein Nicht-Griff-Treffer im Inneren. - return { id: a.id, hit: { kind: "line", handle: "body" } }; - } - } - return null; -} - -/** Endpunkte einer Linien-Annotation als mm-Punkte (für die Griff-Darstellung). */ -export function lineHandleAnchors(ann: Extract): Mm[] { - return [ - { xMm: ann.x1Mm, yMm: ann.y1Mm }, - { xMm: ann.x2Mm, yMm: ann.y2Mm }, - ]; -} - -/** - * Wendet einen Linien-Griff-Drag an: `p1`/`p2` verschiebt genau diesen - * Endpunkt, `body` das ganze Segment (Delta). - */ -export function applyLineHandleDrag( - start: Extract, - handle: LineHandle, - dxMm: number, - dyMm: number, -): { x1Mm: number; y1Mm: number; x2Mm: number; y2Mm: number } { - if (handle === "p1") { - return { x1Mm: start.x1Mm + dxMm, y1Mm: start.y1Mm + dyMm, x2Mm: start.x2Mm, y2Mm: start.y2Mm }; - } - if (handle === "p2") { - return { x1Mm: start.x1Mm, y1Mm: start.y1Mm, x2Mm: start.x2Mm + dxMm, y2Mm: start.y2Mm + dyMm }; - } - return { - x1Mm: start.x1Mm + dxMm, - y1Mm: start.y1Mm + dyMm, - x2Mm: start.x2Mm + dxMm, - y2Mm: start.y2Mm + dyMm, - }; -} - -/** Verschiebt eine Annotation um ein mm-Delta — alle ihre Punkte wandern mit. */ -export function translateAnnotation( - ann: LayoutAnnotation, - dxMm: number, - dyMm: number, -): LayoutAnnotation { - if (ann.kind === "line") { - return { - ...ann, - x1Mm: ann.x1Mm + dxMm, - y1Mm: ann.y1Mm + dyMm, - x2Mm: ann.x2Mm + dxMm, - y2Mm: ann.y2Mm + dyMm, - }; - } - return { ...ann, xMm: ann.xMm + dxMm, yMm: ann.yMm + dyMm }; -} diff --git a/src/views/plan/PlanView.tsx b/src/views/plan/PlanView.tsx index b0bbaab9..46f29eb6 100644 --- a/src/views/plan/PlanView.tsx +++ b/src/views/plan/PlanView.tsx @@ -14,7 +14,7 @@ import { useRef, useState, } from "react"; -import type { ComponentProps, CSSProperties } from "react"; +import type { ComponentProps, CSSProperties, ReactNode } from "react"; import type { HatchRender, Plan, PlanImage, Primitive } from "../../core"; import { materializeGreyed, materializeUnderlay, type UnderlayGroup } from "../../core"; import type { Drawing2D, EdgeGrip, Vec2 } from "../../model/types"; @@ -580,6 +580,15 @@ export interface PlanViewProps { * (`SnapSettings.hoverDivideCount`); Default 2. */ hoverDivideCount?: number; + /** + * Hintergrund unter der Zeichnung (z. B. das Layout-Blatt: Papier, Master, Viewports), gezeichnet + * im SVG zwischen Raster und Geometrie. `origin` = Ursprung des Overlays (viewBox-Einheiten, s. + * planView/overlayOrigin.ts), `pxPerMeter` = aktueller Zoom. Mit Hintergrund zeichnet der SVG-Pfad + * (wie bei Luftbildern), damit er sichtbar bleibt. + */ + backdrop?: (origin: Vec2, pxPerMeter: number) => ReactNode; + /** Einpass-Bereich (Modell-Meter) statt der Plan-Grenzen — z. B. das Blatt. */ + fitBounds?: { minX: number; minY: number; maxX: number; maxY: number }; } /** Treiber für das Ziehen von Editier-Griffen (von App bereitgestellt). */ @@ -705,6 +714,8 @@ export const PlanView = forwardRef( snapColor = DEFAULT_SNAP_COLOR, hoverDivideDelayMs = 300, hoverDivideCount = 2, + backdrop, + fitBounds, }, ref, ) { @@ -720,14 +731,16 @@ export const PlanView = forwardRef( // toScreen-Abbildung. Reset-/Einpassen-Ziel + Bezug für die Zoom-Grenzen; wird // NICHT automatisch angewandt (nur bei resetKey-Wechsel und „Einpassen"). const defaultView = useMemo(() => { - const { minX, minY, maxX, maxY } = planRaw.bounds; + const { minX, minY, maxX, maxY } = fitBounds ?? planRaw.bounds; + // Fester Einpass-Bereich (Blatt): Rand relativ zu seiner Grösse statt der festen Modell-Marge. + const pad = fitBounds ? Math.max(maxX - minX, maxY - minY) * PX_PER_M * 0.04 : PAD; return { - x: minX * PX_PER_M - PAD, - y: -maxY * PX_PER_M - PAD, - w: (maxX - minX) * PX_PER_M + PAD * 2, - h: (maxY - minY) * PX_PER_M + PAD * 2, + x: minX * PX_PER_M - pad, + y: -maxY * PX_PER_M - pad, + w: (maxX - minX) * PX_PER_M + pad * 2, + h: (maxY - minY) * PX_PER_M + pad * 2, }; - }, [planRaw]); + }, [planRaw, fitBounds]); // Aktueller Ausschnitt; treibt die viewBox des SVG. Initial = eingepasst. const [view, setView] = useState(defaultView); @@ -823,7 +836,7 @@ export const PlanView = forwardRef( ); // Engine WIRKLICH aktiv? Steuert das Umschalten SVG↔GPU: bei false rendert der // volle SVG-Pfad (Fallback), bei true übernimmt die GPU-Ebene + Text-Overlay. - const useGpuRenderer = wantGpu && glReady && !hasBgImages && !hasDrawingImages; + const useGpuRenderer = wantGpu && glReady && !hasBgImages && !hasDrawingImages && !backdrop; // `planRaw.greyedRanges` (andere Ebenen als gedimmte Referenz) ohne Klonen der // Primitive: der WebGL-Pfad dimmt selbst beim Zeichnen (nur planRaw), alle @@ -3035,7 +3048,7 @@ export const PlanView = forwardRef( glReady bleibt false → Deadlock). Bei WebGL-Fehler bleibt es leer hinten und der volle SVG-Pfad übernimmt sichtbar. NICHT montiert, wenn ein Luftbild aktiv ist — dann rendert der SVG-Pfad alles inkl. Bild-Ebene. */} - {wantGpu && !hasBgImages && ( + {wantGpu && !hasBgImages && !backdrop && ( ( pxPerMeter={currentPxPerMeter()} /> )} + {backdrop?.(overlayOrigin, currentPxPerMeter())} {/* Georeferenzierte Luftbilder ZWISCHEN Blatt-Hintergrund und Geometrie: Modell-Meter × PX_PER_M mit negierter y-Achse (s. toScreen) → Bild-Norden (max.y) oben bei y=−max.y·PX; das Bild zeichnet natürlich von oben (kein diff --git a/src/views/viewportContent.tsx b/src/views/viewportContent.tsx index 6cdf68a4..ed1c9c65 100644 --- a/src/views/viewportContent.tsx +++ b/src/views/viewportContent.tsx @@ -9,11 +9,14 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { t } from "../i18n"; +import { LayoutSheetPane, type LayoutSheetHandlers, type SheetPlanProps } from "../ui/LayoutSheet"; +import { SHEET_SCALE_DENOMINATOR } from "../model/layoutModel"; import type { Ceiling, Drawing2D, DrawingLevel, EdgeGrip, + Layout, Project, Roof, Vec2, @@ -141,7 +144,14 @@ export function Content({ onEdit3dGroup, onGrip3dEditTab, onGrip3dEditCancel, + sheet, }: { + /** + * Offenes Layout-Blatt: `level` ist dann dessen Blatt-Ebene (`layoutId`). Gezeichnet wird in + * derselben Plan-Ansicht wie auf jeder Zeichnungsebene; das Blatt liefert nur den Hintergrund + * (Papier, Master, Viewports) und das Platzieren der Viewports (ui/LayoutSheet.tsx). + */ + sheet?: { layout: Layout; handlers: LayoutSheetHandlers } | null; project: Project; level: DrawingLevel; viewType: ViewType; @@ -372,10 +382,11 @@ export function Content({ // 3D-Umschaltung — eine Zeichnung hat keine Höhe/3D. So sind importierte // DXF-Polylinien hier sofort sichtbar und mit den 2D-Werkzeugen bearbeitbar. if (level.kind === "drawing") { - return ( -
- + // Blatt-Ebene eines offenen Layouts: Papier 1:1 (Massstab 1), Hintergrund + Viewports vom Blatt. + const plan = (sheetPlan?: SheetPlanProps) => ( + ); + if (level.layoutId && sheet && sheet.layout.id === level.layoutId) { + return ( +
+ + {plan} + +
+ ); + } + return ( +
+ + {plan()}
); } @@ -663,6 +695,8 @@ function useCrossKindOverlay( /** Abgeleiteter Grundriss eines Geschosses. */ function LevelPlanView({ + backdrop, + fitBounds, project, level, visibleCodes, @@ -719,6 +753,10 @@ function LevelPlanView({ selectedDrawingIds, gripHandlers, }: { + /** Hintergrund unter der Zeichnung (Layout-Blatt), s. `PlanView.backdrop`. */ + backdrop?: SheetPlanProps["backdrop"]; + /** Einpass-Bereich statt der Plan-Grenzen (Layout-Blatt). */ + fitBounds?: SheetPlanProps["fitBounds"]; project: Project; level: DrawingLevel; visibleCodes: Set; @@ -913,6 +951,8 @@ function LevelPlanView({ selectedDrawingId={selectedDrawingId} selectedDrawingIds={selectedDrawingIds} gripHandlers={gripHandlers} + backdrop={backdrop} + fitBounds={fitBounds} /> {/* NACH PlanView gerendert (nicht als box-shadow auf .pane), damit der Isolations-Rahmen über der PlanView-SVG sichtbar bleibt. */}