[93] Merge: Zeichnen auf dem Layout-Blatt = Zeichnen im Grundriss (Blatt-Ebene mit normalen 2D-Zeichnungen, Format 3 migriert Anmerkungen)

Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67
This commit is contained in:
Claude committed 2026-10-29 20:41:54 +00:00
commit 44e17eeb97
43 files changed
+1236 -2747

No files matched your search

+19
View File
@@ -1323,6 +1323,25 @@ Reihenfolge = Abhängigkeiten. Neue Geometrie entsteht in Rust ([K]).
- ✅ **[78] Autotext im Plankopf.** Titelblock löst Projekt/Blatt/Massstab/Datum auf; Plannummer laufend - ✅ **[78] Autotext im Plankopf.** Titelblock löst Projekt/Blatt/Massstab/Datum auf; Plannummer laufend
oder `Layout.planNumber` (27.10.). oder `Layout.planNumber` (27.10.).
- ○ **[79] Publikationssätze.** · M - ○ **[79] Publikationssätze.** · M
- ✅ **[93] 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 - ○ **[80] PDF mit Ebenen.** · M
- ◐ **[81] Automatische Aussenbemassung.** (27.10.) Befehl `autodim` (Kürzel `ab`): je Seite Öffnungs-, - ◐ **[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. Vor-/Rücksprung- und Gesamtkette. Offen: schiefe Wände, Massstab aus der Ansicht statt fest 1:100.
+210
View File
@@ -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<void> {
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<Pt> {
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<Pt[]> {
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<void> {
await page.getByRole("button", { name, exact: true }).click();
await expect(page.locator(".cmdline-prompt")).toHaveText(prompt);
}
async function clickAt(page: Page, p: Pt): Promise<void> {
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<void> {
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);
});
}
+15 -3
View File
@@ -92,12 +92,22 @@ pub struct Ctx<'a> {
pub floor_height: Option<f64>, pub floor_height: Option<f64>,
pub cat: &'a str, pub cat: &'a str,
pub wall_type: &'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<'_> { pub(crate) fn ctx_of(v: &Value) -> Ctx<'_> {
let c = v.get("ctx").unwrap_or(&Value::Null); let c = v.get("ctx").unwrap_or(&Value::Null);
let fh = opt_n(c, "floorHeight").filter(|h| *h > 0.0); 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 ────────────────────────────────────────────────────────────── // ── Werte bauen ──────────────────────────────────────────────────────────────
@@ -912,20 +922,22 @@ pub struct Req {
floor_height: Option<f64>, floor_height: Option<f64>,
cat: String, cat: String,
wall_type: String, wall_type: String,
text_height: f64,
} }
impl Req { impl Req {
pub fn new(v: Value) -> Req { pub fn new(v: Value) -> Req {
let c = ctx_of(&v); 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()); 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). /// Wie [`preview`] mit gelesener Anfrage (Mausschritt: dieselbe Anfrage, neue Punkte).
pub fn preview_req(root: &Map<String, Value>, req: &Req, pts: &[f64]) -> Preview { pub fn preview_req(root: &Map<String, Value>, req: &Req, pts: &[f64]) -> Preview {
let v = &req.v; 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 pts = flat_pts(pts);
let mut p = Preview { ok: true, ..Default::default() }; let mut p = Preview { ok: true, ..Default::default() };
let out = &mut p.shapes; let out = &mut p.shapes;
+32 -15
View File
@@ -823,21 +823,22 @@ fn multiline_preview(v: &Value, pts: &[V], p: &mut Preview) {
} }
} }
const TEXT_HEIGHT: f64 = 0.25; /// Mindestgrösse eines Textrahmens als Vielfaches der Schrifthöhe (0.2 m bei 0.25 m Schrift).
const TEXTBOX_MIN: f64 = 0.2; const TEXTBOX_MIN_PER_HEIGHT: f64 = 0.8;
fn text_geom(at: Value, extra: Vec<(&str, Value)>) -> Value { 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(TEXT_HEIGHT)), ("angle", js_num(0.0))]; 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); f.extend(extra);
obj(f) obj(f)
} }
/// Textrahmen aus zwei Ecken: Anker oben links (eine Zeile tief), Breite, Mindesthöhe. /// 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 (mn, mx) = rect_geom(a, b);
let width = jsnum::max(TEXTBOX_MIN, mx.0 - mn.0); let min = TEXTBOX_MIN_PER_HEIGHT * text_height;
let height = jsnum::max(TEXTBOX_MIN, mx.1 - mn.1); let width = jsnum::max(min, mx.0 - mn.0);
((mn.0, mx.1 - TEXT_HEIGHT), width, height) 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] { fn kote_tri(at: V, kind: &str) -> [V; 3] {
@@ -1091,15 +1092,15 @@ pub fn ops(root: &Map<String, Value>, v: &Value, ctx: &Ctx, ids: &mut IdGen) ->
add_op("drawings2d", vec![d]) add_op("drawings2d", vec![d])
} }
"multiline" => multiline_ops(v, ctx, ids), "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" => { "textbox" => {
let (at, width, _) = textbox_frame(p_of(v, "a"), p_of(v, "b")); let (at, width, _) = textbox_frame(p_of(v, "a"), p_of(v, "b"), ctx.text_height);
add_drawing(v, ctx, ids, text_geom(pv(at), vec![("width", js_num(width))])) add_drawing(v, ctx, ids, text_geom(ctx, pv(at), vec![("width", js_num(width))]))
} }
"textpath" => { "textpath" => {
let pts = pts_val(v, "pts"); let pts = pts_val(v, "pts");
let at = pts.get(0).cloned().unwrap_or(Value::Null); 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" => { "leader" => {
let mut extra = vec![("leaderTarget", pt_val(v, "target"))]; let mut extra = vec![("leaderTarget", pt_val(v, "target"))];
@@ -1107,7 +1108,7 @@ pub fn ops(root: &Map<String, Value>, v: &Value, ctx: &Ctx, ids: &mut IdGen) ->
if bends.as_array().is_some_and(|b| !b.is_empty()) { if bends.as_array().is_some_and(|b| !b.is_empty()) {
extra.push(("leaderBendPoints", bends)); 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( "kote" => add_drawing(
v, v,
@@ -1160,7 +1161,7 @@ pub fn preview(root: &Map<String, Value>, v: &Value, ctx: &Ctx, pts: &[V], p: &m
"textbox" => { "textbox" => {
if let [a, b] = pts { if let [a, b] = pts {
let (mn, mx) = rect_geom(*a, *b); 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.info.extend([w, h]);
p.shapes.poly(&corners_of(mn, mx)); p.shapes.poly(&corners_of(mn, mx));
} }
@@ -1232,7 +1233,23 @@ mod tests {
use super::*; use super::*;
fn ctx() -> Ctx<'static> { 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] #[test]
+1 -1
View File
@@ -819,7 +819,7 @@ mod tests {
assert_eq!(d.project().unwrap().walls.len(), 0); assert_eq!(d.project().unwrap().walls.len(), 0);
assert_eq!(d.field("openings").unwrap()[0]["kind"], "door"); assert_eq!(d.field("openings").unwrap()[0]["kind"], "door");
assert!(d.undo().is_none()); 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] #[test]
+10 -6
View File
@@ -1309,6 +1309,14 @@ pub struct DrawingLevel {
#[serde(rename = "levelMarks", default, skip_serializing_if = "Option::is_none")] #[serde(rename = "levelMarks", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)] #[ts(optional)]
pub level_marks: Option<bool>, pub level_marks: Option<bool>,
/// 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<String>,
#[serde(flatten)] #[serde(flatten)]
#[ts(skip)] #[ts(skip)]
pub extra: Extra, pub extra: Extra,
@@ -3367,13 +3375,9 @@ pub struct Layout {
#[serde(rename = "customHeightMm", default, skip_serializing_if = "Option::is_none")] #[serde(rename = "customHeightMm", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)] #[ts(optional)]
pub custom_height_mm: Option<f64>, pub custom_height_mm: Option<f64>,
/// 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<LayoutViewport>, pub viewports: Vec<LayoutViewport>,
/// 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<Vec<LayoutAnnotation>>,
#[serde(flatten)] #[serde(flatten)]
#[ts(skip)] #[ts(skip)]
pub extra: Extra, pub extra: Extra,
-82
View File
@@ -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<String>,
#[serde(rename = "weightMm", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
weight_mm: Option<f64>,
},
#[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<String>,
#[serde(rename = "weightMm", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
weight_mm: Option<f64>,
},
#[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<String>,
/// 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<RichTextDoc>,
/// 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<f64>,
},
#[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<f64>,
},
}
/// Parametrische Wandregel (Tag `type`). /// Parametrische Wandregel (Tag `type`).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)] #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[serde(tag = "type")] #[serde(tag = "type")]
+17 -1
View File
@@ -394,8 +394,10 @@ impl Post {
} }
/// Nachbearbeitung eines Plans: Schwarz-Weiss und Strichstärken-Faktor; `None`, wenn sie nichts tut. /// 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<Post> { pub fn post_for(p: &Project, a: &super::domains::PlanArgs) -> Option<Post> {
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 ───────────────────────────────────────────────────────────────────────────────────── // ── Ausmass ─────────────────────────────────────────────────────────────────────────────────────
@@ -479,6 +481,20 @@ mod tests {
assert_eq!(line_weight_factor(&on, f64::NAN), 1.0); 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] #[test]
fn abzugskoerper_spart_wand_aus() { fn abzugskoerper_spart_wand_aus() {
let mut v: serde_json::Value = serde_json::from_str(include_str!("../../tests/fixtures/sample_project.json")).unwrap(); let mut v: serde_json::Value = serde_json::from_str(include_str!("../../tests/fixtures/sample_project.json")).unwrap();
+187 -3
View File
@@ -9,7 +9,7 @@
use serde_json::{Map, Value}; use serde_json::{Map, Value};
/// Aktuelle Version des Dateiformats. Bei jeder Formatänderung erhöhen + Migration anhängen. /// 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 REQUIRED_ARRAYS: [&str; 3] = ["walls", "layers", "drawingLevels"];
const DEFAULT_ARRAYS: [&str; 5] = ["lineStyles", "hatches", "components", "wallTypes", "drawings2d"]; const DEFAULT_ARRAYS: [&str; 5] = ["lineStyles", "hatches", "components", "wallTypes", "drawings2d"];
@@ -86,6 +86,144 @@ fn migrate_doors(mut raw: Map<String, Value>) -> Map<String, Value> {
raw raw
} }
/// Kategorie für Blatt-Zeichnungen aus der Migration: „50" (Text), sonst die erste Kategorie.
fn sheet_category(raw: &Map<String, Value>) -> String {
fn walk(v: &Value, out: &mut Vec<String>) {
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<String, Value>) -> Map<String, Value> {
let Some(Value::Array(mut layouts)) = raw.get("layouts").cloned() else { return raw };
let mut levels: Vec<Value> = raw.get("drawingLevels").and_then(Value::as_array).cloned().unwrap_or_default();
let mut drawings: Vec<Value> = raw.get("drawings2d").and_then(Value::as_array).cloned().unwrap_or_default();
let mut level_ids: std::collections::HashSet<String> =
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<String> =
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 /// 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. /// eine Ersatz-ID, falls die Datei keine trägt.
pub fn parse_project_file(text: &str, now_ms: f64) -> Parsed { 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 { for i in version..PROJECT_FORMAT_VERSION {
obj = match i { obj = match i {
1 => migrate_doors(obj), 1 => migrate_doors(obj),
2 => migrate_layout_annotations(obj),
_ => obj, // 0 → 1: Einführung von `formatVersion`; Inhalt unverändert. _ => obj, // 0 → 1: Einführung von `formatVersion`; Inhalt unverändert.
}; };
} }
@@ -321,7 +460,7 @@ mod tests {
fn alte_datei_wird_migriert_und_ergaenzt() { fn alte_datei_wird_migriert_und_ergaenzt() {
let Parsed::Ok { project, warnings, migrated_from } = parse_project_object(minimal(), 0.0) else { panic!() }; let Parsed::Ok { project, warnings, migrated_from } = parse_project_object(minimal(), 0.0) else { panic!() };
assert_eq!(migrated_from, Some(0)); assert_eq!(migrated_from, Some(0));
assert_eq!(project["formatVersion"], 2); assert_eq!(project["formatVersion"], 3);
assert_eq!(project["lineStyles"], json!([])); assert_eq!(project["lineStyles"], json!([]));
assert!(warnings.is_empty()); assert!(warnings.is_empty());
} }
@@ -362,6 +501,51 @@ mod tests {
assert_eq!(o[2]["id"], "O1-t"); 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] #[test]
fn unbekannte_felder_bleiben_und_werden_gemeldet() { fn unbekannte_felder_bleiben_und_werden_gemeldet() {
let mut v = minimal(); let mut v = minimal();
@@ -420,6 +604,6 @@ mod tests {
fn serialisierung_setzt_version_nach_vorn() { fn serialisierung_setzt_version_nach_vorn() {
let Value::Object(m) = minimal() else { panic!() }; let Value::Object(m) = minimal() else { panic!() };
let s = serialize_project(&m); 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\""));
} }
} }
+82 -136
View File
@@ -27,6 +27,7 @@ import type {
Drawing2D, Drawing2D,
DrawingLevel, DrawingLevel,
Layout, Layout,
LayoutViewport,
Project, Project,
Roof, Roof,
Vec2, Vec2,
@@ -78,16 +79,18 @@ import {
} from "./viewport/grip3dHud"; } from "./viewport/grip3dHud";
import { ResourceManager } from "./ui/ResourceManager"; import { ResourceManager } from "./ui/ResourceManager";
import type { ResourceManagerHandlers, TabId as ResourceTabId } from "./ui/ResourceManager"; import type { ResourceManagerHandlers, TabId as ResourceTabId } from "./ui/ResourceManager";
import { LayoutSheetView } from "./ui/LayoutSheet";
import { import {
createViewport, createViewport,
createAnnotation, createSheetLevel,
effectiveSheetSizeMm,
findMaster,
isSheetLevel,
sheetMmToModel,
sheetLevelOf,
SHEET_SCALE_DENOMINATOR,
addViewport as addViewportToLayout, addViewport as addViewportToLayout,
removeViewport as removeViewportFromLayout, removeViewport as removeViewportFromLayout,
patchViewport as patchViewportInLayout, patchViewport as patchViewportInLayout,
addAnnotation as addAnnotationToLayout,
removeAnnotation as removeAnnotationFromLayout,
patchAnnotation as patchAnnotationInLayout,
} from "./model/layoutModel"; } from "./model/layoutModel";
import { HatchSwatch } from "./ui/hatchPreview"; import { HatchSwatch } from "./ui/hatchPreview";
import { TopBar, ViewRibbonTab } from "./ui/TopBar"; import { TopBar, ViewRibbonTab } from "./ui/TopBar";
@@ -511,13 +514,6 @@ export default function App() {
setEditTextMinHeightM, setEditTextMinHeightM,
} = useContextMenuState(); } = 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<string | null>(
null,
);
// Beim Geschosswechsel die Wand-Auswahl + offene Overlays zurücksetzen (die // Beim Geschosswechsel die Wand-Auswahl + offene Overlays zurücksetzen (die
// Wände eines anderen Geschosses sind eine andere Menge). Der Ansichtswechsel // Wände eines anderen Geschosses sind eine andere Menge). Der Ansichtswechsel
// (Grundriss ↔ 3D) lässt die Auswahl bestehen — dieselbe wallId gilt in // (Grundriss ↔ 3D) lässt die Auswahl bestehen — dieselbe wallId gilt in
@@ -602,6 +598,8 @@ export default function App() {
const activeLevel = const activeLevel =
project.drawingLevels.find((z) => z.id === activeLevelId) ?? project.drawingLevels.find((z) => z.id === activeLevelId) ??
project.drawingLevels[0]; 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. // Sichtbare Kategorie-Codes — Basisfilter für Grundriss & 3D.
const visibleCodes = useMemo( const visibleCodes = useMemo(
@@ -1041,24 +1039,10 @@ export default function App() {
// Ein Klick auf ein gekoppeltes Zeichen-Werkzeug (Wand/Linie/Rechteck/Polylinie) // Ein Klick auf ein gekoppeltes Zeichen-Werkzeug (Wand/Linie/Rechteck/Polylinie)
// STARTET den passenden Befehl in der Engine und fokussiert das Befehlsfeld // STARTET den passenden Befehl in der Engine und fokussiert das Befehlsfeld
// („Dialog drin"). „Auswahl" beendet einen laufenden Befehl (Auswahl-Modus). // („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) => { const onSelectTool = (id: ToolId) => {
// Erneuter Klick auf das bereits AKTIVE Werkzeug schaltet zurück auf // Erneuter Klick auf das bereits AKTIVE Werkzeug schaltet zurück auf
// „Auswahl" (Nutzer-Wunsch) — statt das Werkzeug einfach neu zu starten. // „Auswahl" (Nutzer-Wunsch) — statt das Werkzeug einfach neu zu starten.
if (id !== "select" && id === activeTool) id = "select"; 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") { if (id === "image") {
// Datei-Auswahl ist async (Dateidialog) — kein Klick-Platzieren wie bei // Datei-Auswahl ist async (Dateidialog) — kein Klick-Platzieren wie bei
// den übrigen Zeichen-Werkzeugen, daher hier abgefangen statt über die // 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", modelEditable: activeLevel.kind !== "section" && activeLevel.kind !== "elevation",
sheet: sectionSheet, sheet: sectionSheet,
visibleCodes, visibleCodes,
scaleDenominator, scaleDenominator: planScale,
snap, snap,
setDraft, setDraft,
snapFor, snapFor,
@@ -1864,16 +1848,6 @@ export default function App() {
planViewRef, 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) // Text-Ziel der Oberleisten-Text-Gruppe: der Stempel-Text des (einzeln)
// gewählten Raums. Ohne aktive Editor-Auswahl wirkt Formatierung auf das ganze // gewählten Raums. Ohne aktive Editor-Auswahl wirkt Formatierung auf das ganze
// Doc (range: null). Ist kein Raum gewählt → null (Controls setzen nur // 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; return null;
}, [ }, [
selectedRoom, selectedRoom,
@@ -1936,8 +1895,6 @@ export default function App() {
selectedDrawingId, selectedDrawingId,
project.drawings2d, project.drawings2d,
updateDrawing2D, updateDrawing2D,
selectedLayoutAnnotation,
activeLayoutId,
]); ]);
// ── 3D-Editier-Griffe (direkt im Viewport3D) ────────────────────────────── // ── 3D-Editier-Griffe (direkt im Viewport3D) ──────────────────────────────
@@ -2287,26 +2244,7 @@ export default function App() {
// ── Selektions-Attribut-Kontrakt (Attributes-/Object-Info-Paletten) ─────── // ── Selektions-Attribut-Kontrakt (Attributes-/Object-Info-Paletten) ───────
// Normalisierte, effektiv aufgelöste Sicht auf das erste selektierte Element. // 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 => { 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( return deriveSelection(
project, project,
selectedWallIds, selectedWallIds,
@@ -2321,7 +2259,6 @@ export default function App() {
selectedContextObjectIds.length === 1 ? selectedContextObjectIds[0] : null, selectedContextObjectIds.length === 1 ? selectedContextObjectIds[0] : null,
); );
}, [ }, [
selectedLayoutAnnotation,
project, project,
selectedWallIds, selectedWallIds,
selectedDrawingId, selectedDrawingId,
@@ -2643,6 +2580,60 @@ export default function App() {
const patchOpenLayout = (id: string, fn: (l: Layout) => Layout, coalesceKey?: string) => const patchOpenLayout = (id: string, fn: (l: Layout) => Layout, coalesceKey?: string) =>
applyChange((p) => patchItem(p, "layouts", id, fn), coalesceKey); applyChange((p) => patchItem(p, "layouts", id, fn), coalesceKey);
// Ein offenes Blatt IST eine Zeichnungsebene: seine Blatt-Ebene (`layoutId`) wird die aktive Ebene,
// damit Werkzeuge, Befehle, Fang, Griffe, Auswahl und Undo genau wie im Grundriss wirken. Beim
// Schliessen kehrt die vorige Ebene zurück; wählt man im Navigator eine andere Ebene, schliesst
// das Blatt.
const sheetLevel = activeLayout ? sheetLevelOf(project, activeLayout.id) : undefined;
const levelBeforeSheetRef = useRef<string | null>(null);
const enteredSheetRef = useRef<string | null>(null);
useEffect(() => {
const current = project.drawingLevels.find((l) => l.id === activeLevelId);
if (activeLayout) {
if (!sheetLevel) {
// Layout ohne Blatt-Ebene (z. B. per CLI angelegt): einmal nachtragen.
applyChange(addItems("drawingLevels", [createSheetLevel(`sheet-${activeLayout.id}`, activeLayout)]));
return;
}
if (activeLevelId === sheetLevel.id) {
enteredSheetRef.current = activeLayout.id;
return;
}
if (enteredSheetRef.current === activeLayout.id) {
enteredSheetRef.current = null;
setActiveLayoutId(null);
return;
}
if (current && !isSheetLevel(current)) levelBeforeSheetRef.current = current.id;
setActiveLevelId(sheetLevel.id);
return;
}
enteredSheetRef.current = null;
if (current && !isSheetLevel(current)) return;
const back =
project.drawingLevels.find((l) => l.id === levelBeforeSheetRef.current && !isSheetLevel(l)) ??
project.drawingLevels.find((l) => !isSheetLevel(l));
if (back && back.id !== activeLevelId) setActiveLevelId(back.id);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [activeLayout?.id, sheetLevel?.id, activeLevelId]);
const sheetPane =
activeLayout && sheetLevel && activeLevelId === sheetLevel.id
? {
layout: activeLayout,
handlers: {
onBack: () => setActiveLayoutId(null),
onPatchViewport: (viewportId: string, patch: Partial<Omit<LayoutViewport, "id" | "snapshotId">>) =>
patchOpenLayout(activeLayout.id, (l) => patchViewportInLayout(l, viewportId, patch)),
onRemoveViewport: (viewportId: string) =>
patchOpenLayout(activeLayout.id, (l) => removeViewportFromLayout(l, viewportId)),
onAddViewport: (snapshotId: string, init: Partial<Omit<LayoutViewport, "id" | "snapshotId">>) =>
patchOpenLayout(activeLayout.id, (l) =>
addViewportToLayout(l, createViewport(`vp-${Date.now()}`, snapshotId, init)),
),
},
}
: null;
// ── Effektive Darstellung für die Hauptansicht ──────────────────────────── // ── Effektive Darstellung für die Hauptansicht ────────────────────────────
// 3D: Geschosse nach dem Modus des Zeichnungsebenen-Panels, Kategorien nach // 3D: Geschosse nach dem Modus des Zeichnungsebenen-Panels, Kategorien nach
// dem Modus des Ebenen-Panels. Grundriss: Kategorien nach dem Ebenen-Panel. // dem Modus des Ebenen-Panels. Grundriss: Kategorien nach dem Ebenen-Panel.
@@ -2665,8 +2656,13 @@ export default function App() {
const visible = new Map( const visible = new Map(
project.drawingLevels.map((z) => [z.id, z.visible]), 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) => 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]); }, [project.drawingLevels, drawingLevelsMode, activeLevelId]);
// Resolver: je Kategorie-Code die Render-Entscheidung. „Aktiv" = die per // Resolver: je Kategorie-Code die Render-Entscheidung. „Aktiv" = die per
@@ -2767,7 +2763,7 @@ export default function App() {
// bewusst nicht mitgenommen). // bewusst nicht mitgenommen).
useDrawingLevelsWindowHost( useDrawingLevelsWindowHost(
{ {
drawingLevels: project.drawingLevels, drawingLevels: project.drawingLevels.filter((z) => !z.layoutId),
activeLevelId, activeLevelId,
displayMode: drawingLevelsMode, displayMode: drawingLevelsMode,
}, },
@@ -3066,6 +3062,14 @@ export default function App() {
const { onImageOrPdfFileChosen } = useImageImportHandling({ const { onImageOrPdfFileChosen } = useImageImportHandling({
activeLevelId: activeLevel.id, activeLevelId: activeLevel.id,
activeCategoryCode, 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, applyChange,
notify, notify,
setSelectedDrawingId, setSelectedDrawingId,
@@ -3113,8 +3117,6 @@ export default function App() {
openSettings, openSettings,
onOpenStampEditor, onOpenStampEditor,
openResources, openResources,
activeLayout,
patchOpenLayout,
dxfInputRef, dxfInputRef,
planViewRef, planViewRef,
selection, selection,
@@ -3503,69 +3505,13 @@ export default function App() {
Befehlszeile nur so breit wie der Viewport (nicht die ganze 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). */} und die Docks nehmen die volle Body-Höhe ein (inkl. der Zeile). */}
<div className="center-col"> <div className="center-col">
{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). */
<LayoutSheetView
project={project}
layout={activeLayout}
activeTool={activeTool}
onToolChange={onSelectTool}
selectedAnnotId={selectedLayoutAnnotationId}
onSelectAnnot={setSelectedLayoutAnnotationId}
handlers={{
onBack: () => {
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- {/* Hauptansicht (Mitte) — füllt den verbleibenden Platz. Die Plan-
Ansicht meldet Cursor + Zoom an die Status-/Oberleiste und nimmt Ansicht meldet Cursor + Zoom an die Status-/Oberleiste und nimmt
das Zoom-Handle entgegen. */} das Zoom-Handle entgegen. */}
<Content <Content
sheet={sheetPane}
project={project} project={project}
level={activeLevel} level={activeLevel}
viewType={viewType} viewType={viewType}
+1 -1
View File
@@ -170,7 +170,7 @@ function loadProject(path: string): Project {
} }
function findLevel(project: Project, kinds: string[], name: string | undefined) { function findLevel(project: Project, kinds: string[], name: string | undefined) {
const levels = project.drawingLevels.filter((l) => kinds.includes(l.kind)); const levels = project.drawingLevels.filter((l) => kinds.includes(l.kind) && !l.layoutId);
if (!name) return levels[0]; if (!name) return levels[0];
const n = name.toLowerCase(); const n = name.toLowerCase();
return levels.find((l) => l.id.toLowerCase() === n || l.name.toLowerCase() === n); return levels.find((l) => l.id.toLowerCase() === n || l.name.toLowerCase() === n);
+5 -1
View File
@@ -18,13 +18,17 @@ export interface CreatePreview {
info: number[]; 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 { function ctxReq(ctx: CommandContext): object {
return { return {
level: ctx.level.id, level: ctx.level.id,
floorHeight: ctx.level.floorHeight ?? null, floorHeight: ctx.level.floorHeight ?? null,
cat: ctx.defaultCategoryCode, cat: ctx.defaultCategoryCode,
wallType: ctx.activeWallTypeId, wallType: ctx.activeWallTypeId,
...(ctx.level.layoutId ? { textHeight: SHEET_TEXT_HEIGHT_M } : {}),
}; };
} }
+35 -112
View File
@@ -12,17 +12,19 @@
import { jsPDF } from "jspdf"; import { jsPDF } from "jspdf";
import "svg2pdf.js"; 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 { generatePlan } from "../plan/generatePlan";
import { planToPrintSvg } from "./planToPrintSvg"; import { planToPrintSvg } from "./planToPrintSvg";
import { annotationTextLines } from "../text/renderHtml"; import { collectVisibleCodes } from "../model/types";
import { docFromText } from "../text/richText";
import { import {
findMaster, findMaster,
findSnapshot, findSnapshot,
folderPdfPages, folderPdfPages,
resolveTitleBlock, resolveTitleBlock,
resolveViewportScale, resolveViewportScale,
SHEET_SCALE_DENOMINATOR,
sheetLevelOf,
sheetMmToModel,
visibleCodesFromSnapshot, visibleCodesFromSnapshot,
type FolderPdfPage, type FolderPdfPage,
type ResolvedTitleBlock, type ResolvedTitleBlock,
@@ -79,110 +81,36 @@ function clip(s: string, max: number): string {
return s.length > max ? s.slice(0, max - 1) + "…" : s; 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 * Die 2D-Zeichnung des Blatts (Blatt-Ebene, `DrawingLevel.layoutId`) über Viewports und Master:
* Docs (mehrere Absätze/gemischte Formatierung) + Wortumbruch bei gesetzter * derselbe Plan wie am Bildschirm (`generatePlan`, Massstab 1:1, Export-Modus), über
* Rahmenbreite, exakt wie `LayoutSheet.tsx`s `AnnotationSvg`. Ein gemeinsamer * `planToPrintSvg` fest aufs Papier gelegt (Ursprung oben links), ohne eigenes weisses Blatt.
* `doc.svg()`-Aufruf statt einem je Annotation (einfacher, ein Layout-Pass).
* `null`, wenn die Seite keine Text-Markups trägt.
*/ */
function buildAnnotationTextsSvg( async function renderSheetDrawing(doc: jsPDF, project: Project, layout: Layout, widthMm: number, heightMm: number): Promise<void> {
annotations: LayoutAnnotation[], const level = sheetLevelOf(project, layout.id);
sheetW: number, if (!level || !project.drawings2d.some((d) => d.levelId === level.id)) return;
sheetH: number, const a = sheetMmToModel(0, heightMm);
): SVGSVGElement | null { const b = sheetMmToModel(widthMm, 0);
const texts = annotations.filter( const plan = generatePlan(
(a): a is Extract<LayoutAnnotation, { kind: "text" }> => a.kind === "text", project,
level.id,
collectVisibleCodes(project.layers),
undefined,
"fein",
false,
false,
false,
SHEET_SCALE_DENOMINATOR,
true,
); );
if (texts.length === 0) return null; const print = planToPrintSvg(plan, {
scaleDenominator: SHEET_SCALE_DENOMINATOR,
const svg = document.createElementNS(SVG_NS, "svg") as SVGSVGElement; pageWidthMm: widthMm,
svg.setAttribute("xmlns", SVG_NS); pageHeightMm: heightMm,
svg.setAttribute("width", String(sheetW)); bounds: { minX: a.x, minY: a.y, maxX: b.x, maxY: b.y },
svg.setAttribute("height", String(sheetH)); transparent: true,
svg.setAttribute("viewBox", `0 0 ${sheetW} ${sheetH}`); });
await doc.svg(print.svg, { x: 0, y: 0, width: widthMm, height: heightMm });
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.
}
}
}
} }
/** Zeichnet die Viewports + Master-Elemente EINER Seite in das jsPDF-Dokument. */ /** 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); drawTitleBlock(doc, widthMm, heightMm, tb, layout.paper, layout.orientation);
} }
// 2D-Markups (Linie/Rechteck/Bild/Text) — ÜBER Viewports + Master, wie im // 2D-Zeichnung des Blatts — ÜBER Viewports + Master, wie am Bildschirm.
// In-Viewport-Editor (LayoutSheet.tsx). Fehlte bisher komplett im Export.
drawAnnotationShapes(doc, layout);
const textsSvg = buildAnnotationTextsSvg(layout.annotations ?? [], widthMm, heightMm);
if (textsSvg) {
try { try {
await doc.svg(textsSvg, { x: 0, y: 0, width: widthMm, height: heightMm }); await renderSheetDrawing(doc, project, layout, widthMm, heightMm);
} catch { } catch {
// Rich-Text-Rendering eines Markups darf die Seite nicht killen. // Eine Blatt-Zeichnung, die nicht rendert, darf die Seite nicht killen.
}
} }
} }
+99
View File
@@ -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<string, string>;
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);
});
});
+9 -2
View File
@@ -100,6 +100,13 @@ export interface PrintSvgOptions {
pageHeightMm: number; pageHeightMm: number;
/** Rand um den Plan-Inhalt in mm (weisser Blattrand). */ /** Rand um den Plan-Inhalt in mm (weisser Blattrand). */
marginMm?: number; 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. */ /** 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). // bewusst, ohne ihn aktuell für einen Versatz zu nutzen (zentrierte Lage).
void (opts.marginMm ?? 10); void (opts.marginMm ?? 10);
const b = plan.bounds; const b = opts.bounds ?? plan.bounds;
// Inhalts-Maße in mm (massstäblich), unverschoben. // Inhalts-Maße in mm (massstäblich), unverschoben.
const contentWmm = (b.maxX - b.minX) * k; const contentWmm = (b.maxX - b.minX) * k;
const contentHmm = (b.maxY - b.minY) * 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("width", String(opts.pageWidthMm));
bg.setAttribute("height", String(opts.pageHeightMm)); bg.setAttribute("height", String(opts.pageHeightMm));
bg.setAttribute("fill", "#ffffff"); 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`). // 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); const o = Float64Array.of(n, opts.pageWidthMm, opts.pageHeightMm, b.minX, b.minY, b.maxX, b.maxY);
-17
View File
@@ -435,8 +435,6 @@ export const de = {
"objinfo.kind.column": "Stütze", "objinfo.kind.column": "Stütze",
"objinfo.kind.roof": "Dach", "objinfo.kind.roof": "Dach",
"objinfo.kind.contextObject": "Kontext-Objekt", "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) ──────────────────────── // ── Kontext-Objekt-Attribute (Object-Info-Panel) ────────────────────────
"objinfo.contextObject.section": "Georeferenzierung", "objinfo.contextObject.section": "Georeferenzierung",
"objinfo.contextObject.type": "Art", "objinfo.contextObject.type": "Art",
@@ -2427,7 +2425,6 @@ export const de = {
// Editor // Editor
"layouts.editorTitle": "Layout-Editor", "layouts.editorTitle": "Layout-Editor",
"layouts.fit": "Einpassen", "layouts.fit": "Einpassen",
"layouts.zoom100": "Echte Grösse (100 %, 1:1 auf dem Bildschirm)",
"layouts.addViewport": "Viewport hinzufügen", "layouts.addViewport": "Viewport hinzufügen",
"layouts.pickSnapshot": "Ausschnitt wählen …", "layouts.pickSnapshot": "Ausschnitt wählen …",
"layouts.noSnapshots": "Keine Ausschnitte vorhanden. Zuerst einen Ausschnitt speichern.", "layouts.noSnapshots": "Keine Ausschnitte vorhanden. Zuerst einen Ausschnitt speichern.",
@@ -2446,23 +2443,9 @@ export const de = {
"layouts.placeViewport": "Viewport aufziehen", "layouts.placeViewport": "Viewport aufziehen",
"layouts.placeHint": "Rechteck auf dem Blatt aufziehen, dann Ausschnitt binden.", "layouts.placeHint": "Rechteck auf dem Blatt aufziehen, dann Ausschnitt binden.",
"layouts.bindSnapshot": "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 // Annotationen (Linie/Rechteck/Text/Bild) direkt auf dem Blatt — gezeichnet
// mit denselben Werkzeugen wie im Grundriss (linkes Werkzeugpanel), kein // mit denselben Werkzeugen wie im Grundriss (linkes Werkzeugpanel), kein
// eigenes Werkzeug nur fürs Layout. // 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 // Baum / „+"-Menü / Ordner
"layouts.add": "Neu …", "layouts.add": "Neu …",
"layouts.addFolder": "Ordner erstellen", "layouts.addFolder": "Ordner erstellen",
-17
View File
@@ -433,8 +433,6 @@ export const en: Record<TranslationKey, string> = {
"objinfo.kind.column": "Column", "objinfo.kind.column": "Column",
"objinfo.kind.roof": "Roof", "objinfo.kind.roof": "Roof",
"objinfo.kind.contextObject": "Context object", "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) ─────────────────────── // ── Context object attributes (object info panel) ───────────────────────
"objinfo.contextObject.section": "Georeferencing", "objinfo.contextObject.section": "Georeferencing",
"objinfo.contextObject.type": "Type", "objinfo.contextObject.type": "Type",
@@ -2414,7 +2412,6 @@ export const en: Record<TranslationKey, string> = {
// Editor // Editor
"layouts.editorTitle": "Layout editor", "layouts.editorTitle": "Layout editor",
"layouts.fit": "Fit", "layouts.fit": "Fit",
"layouts.zoom100": "True size (100%, 1:1 on screen)",
"layouts.addViewport": "Add viewport", "layouts.addViewport": "Add viewport",
"layouts.pickSnapshot": "Pick a view …", "layouts.pickSnapshot": "Pick a view …",
"layouts.noSnapshots": "No views available. Save a view first.", "layouts.noSnapshots": "No views available. Save a view first.",
@@ -2433,22 +2430,8 @@ export const en: Record<TranslationKey, string> = {
"layouts.placeViewport": "Draw viewport", "layouts.placeViewport": "Draw viewport",
"layouts.placeHint": "Drag a rectangle on the sheet, then bind a snapshot.", "layouts.placeHint": "Drag a rectangle on the sheet, then bind a snapshot.",
"layouts.bindSnapshot": "Bind 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 // Annotations (line/rect/text/image) drawn directly on the sheet — with the
// same tools as the plan (left tools panel), no layout-only tool. // 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 // Tree / “+” menu / folders
"layouts.add": "New …", "layouts.add": "New …",
"layouts.addFolder": "Create folder", "layouts.addFolder": "Create folder",
+2 -12
View File
@@ -1,6 +1,6 @@
// Bild-Datei → eingebettete Data-URL + natürliche Pixelgrösse — gemeinsame // Bild-Datei → eingebettete Data-URL + natürliche Pixelgrösse — gemeinsame
// Grundlage für „Bild einfügen" im Plan (Drawing2D `{shape:"image"}`) UND im // Grundlage für „Bild einfügen" (Drawing2D `{shape:"image"}`, auch auf einem
// Layout (LayoutAnnotation `kind:"image"`). Reine Browser-API (FileReader + // Layout-Blatt). Reine Browser-API (FileReader +
// Image), kein Tauri-fs nötig — funktioniert identisch im Web-Preview. // Image), kein Tauri-fs nötig — funktioniert identisch im Web-Preview.
export interface LoadedImageAsset { export interface LoadedImageAsset {
@@ -36,13 +36,3 @@ export function defaultImageSizeM(
const ratio = naturalHeight / Math.max(1, naturalWidth); const ratio = naturalHeight / Math.max(1, naturalWidth);
return { widthM, heightM: Math.max(0.05, widthM * ratio) }; 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) };
}
+1 -1
View File
@@ -2,7 +2,7 @@
// (pdfjs-dist, reine Browser-/Webview-API — kein Tauri-fs nötig) und als // (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 — // Data-URL zurückgegeben. Kein eigener PDF-Rendering-Pfad im Plan/Layout —
// eine importierte PDF-Seite ist danach ein ganz normales Bild-Element // 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 * as pdfjsLib from "pdfjs-dist";
import type { LoadedImageAsset } from "./imageAsset"; import type { LoadedImageAsset } from "./imageAsset";
+1 -1
View File
@@ -21,7 +21,7 @@ import { documentFor, sharedDocument } from "../core/document";
import type { LoadFileResult } from "../core/document"; import type { LoadFileResult } from "../core/document";
/** Aktuelle Version des Dateiformats (muss `PROJECT_FORMAT_VERSION` im Kern entsprechen — Test). */ /** 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; export type ParseProjectResult = LoadFileResult;
+24 -84
View File
@@ -11,15 +11,14 @@ import type {
ViewSnapshot, ViewSnapshot,
} from "./types"; } from "./types";
import { import {
addAnnotation,
addViewport, addViewport,
buildLayoutTree, buildLayoutTree,
buildMasterTree, buildMasterTree,
collectFolderLayouts, collectFolderLayouts,
createAnnotation,
createLayout, createLayout,
createLayoutFolder, createLayoutFolder,
createMasterLayout, createMasterLayout,
createSheetLevel,
createViewport, createViewport,
deleteFolder, deleteFolder,
deleteMasterFolder, deleteMasterFolder,
@@ -28,15 +27,18 @@ import {
findSnapshot, findSnapshot,
folderPdfPages, folderPdfPages,
isDescendant, isDescendant,
isSheetLevel,
moveFolderToFolder, moveFolderToFolder,
moveLayoutToFolder, moveLayoutToFolder,
PAPER_FORMATS, PAPER_FORMATS,
patchAnnotation,
patchViewport, patchViewport,
removeAnnotation,
removeViewport, removeViewport,
resolveTitleBlock, resolveTitleBlock,
resolveViewportScale, resolveViewportScale,
SHEET_SCALE_DENOMINATOR,
sheetLevelOf,
sheetMmToModel,
sheetModelToMm,
sheetSizeMm, sheetSizeMm,
visibleCodesFromSnapshot, visibleCodesFromSnapshot,
} from "./layoutModel"; } 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", () => { describe("Blatt-Ebene", () => {
it("line: Default-Geometrie ohne Farbe/Strichstärke", () => { const lay = createLayout("l1", "Blatt 1", "a3", "landscape");
const a = createAnnotation("a1", "line"); const sheet = createSheetLevel("sheet-l1", lay);
expect(a).toEqual({ id: "a1", kind: "line", x1Mm: 20, y1Mm: 20, x2Mm: 80, y2Mm: 20 });
}); it("ist eine Zeichnungsebene mit Layout-Bezug", () => {
it("line: init überschreibt einzelne Felder + optionale Farbe/Strichstärke", () => { expect(sheet).toEqual({ id: "sheet-l1", name: "Blatt 1", kind: "drawing", visible: true, locked: false, layoutId: "l1" });
const a = createAnnotation("a1", "line", { x1Mm: 5, color: "#f00", weightMm: 0.5 }); expect(isSheetLevel(sheet)).toBe(true);
expect(a).toMatchObject({ x1Mm: 5, y1Mm: 20, color: "#f00", weightMm: 0.5 }); expect(isSheetLevel({ layoutId: undefined })).toBe(false);
}); expect(isSheetLevel(undefined)).toBe(false);
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("Annotations-CRUD (immutabel)", () => { it("wird über das Layout gefunden", () => {
const base = createLayout("l1", "L", "a4", "portrait"); const p = { drawingLevels: [{ id: "eg", name: "EG", kind: "floor", visible: true, locked: false }, sheet] } as unknown as Project;
expect(sheetLevelOf(p, "l1")).toBe(sheet);
it("addAnnotation verändert das Original nicht", () => { expect(sheetLevelOf(p, "nope")).toBeUndefined();
const after = addAnnotation(base, createAnnotation("a1", "line"));
expect(base.annotations).toBeUndefined();
expect(after.annotations).toHaveLength(1);
expect(after).not.toBe(base);
}); });
it("addAnnotation baut auf einer fehlenden `annotations`-Liste auf (Alt-Layout)", () => { it("Papier-mm ↔ Meter (1:1, y nach unten = −y), hin und zurück", () => {
const legacy: Layout = { id: "old", name: "Alt", paper: "a4", orientation: "portrait", viewports: [] }; expect(sheetMmToModel(420, 297)).toEqual({ x: 0.42, y: -0.297 });
const after = addAnnotation(legacy, createAnnotation("a1", "rect")); expect(sheetModelToMm({ x: 0.42, y: -0.297 })).toEqual({ xMm: 420, yMm: 297 });
expect(after.annotations).toHaveLength(1); expect(SHEET_SCALE_DENOMINATOR).toBe(1);
expect(legacy.annotations).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" });
}); });
}); });
+28 -91
View File
@@ -7,22 +7,22 @@
// //
// Rechnung im Rust-Kern ([K4] S3, `src-tauri/core/src/layout_model.rs`, `folder_tree.rs`): Blattgrössen, // 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 // 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 // und Nachschlagen; die Baum-Fassaden setzen die Knoten aus den Indizes des Kerns mit den Original-Objekten
// zusammen (Objekt-Identität bleibt). // zusammen (Objekt-Identität bleibt).
// //
// Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md). // Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md).
import type { import type {
DrawingLevel,
Layout, Layout,
LayoutAnnotation,
LayoutAnnotationPatch,
LayoutFolder, LayoutFolder,
LayoutOrientation, LayoutOrientation,
LayoutPaperFormat, LayoutPaperFormat,
LayoutViewport, LayoutViewport,
MasterLayout, MasterLayout,
Project, Project,
Vec2,
ViewSnapshot, ViewSnapshot,
} from "./types"; } from "./types";
import { core } from "../engine/coreWasm"; import { core } from "../engine/coreWasm";
@@ -413,103 +413,40 @@ export function patchViewport(
}; };
} }
// ── Fabrik + immutable CRUD (Annotationen auf einem Layout) ───────────────── // ── Blatt-Ebene (2D-Zeichnung auf dem Blatt) ─────────────────────────────────
// Analog zu Viewports: Linie/Rechteck/Text als vom Viewport-Baum unabhängige // Was auf einem Blatt gezeichnet wird, sind gewöhnliche `drawings2d` auf der Blatt-Ebene des Layouts
// Markup-Schicht in Papier-mm. `annotations ?? []` ist überall die Basis, damit // (`DrawingLevel.layoutId`, Art "drawing"): dieselben Werkzeuge, Fang, Griffe, Auswahl und dasselbe
// Alt-Layouts (ohne das Feld) unverändert bleiben (additiv). // Rendering wie im Grundriss. Koordinaten = Papier 1:1 in Metern, Ursprung oben links, Papier-y nach
// unten = −y (s. {@link sheetMmToModel}).
/** /** Ist die Ebene die Blatt-Ebene eines Layouts (nicht im Navigator, nur bei offenem Blatt sichtbar)? */
* Neue Annotation mit Default-Geometrie je Art (Linie/Rechteck: sichtbare export function isSheetLevel(level: Pick<DrawingLevel, "layoutId"> | undefined | null): boolean {
* Mindestgrösse; Text: 3.5 mm Zeilenhöhe, wie im Attribute-Editor üblich). return !!level?.layoutId;
* `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 } : {}),
};
} }
/** Fügt eine Annotation an (immutabel). */ /** Die Blatt-Ebene des Layouts `layoutId`, falls vorhanden. */
export function addAnnotation(layout: Layout, annotation: LayoutAnnotation): Layout { export function sheetLevelOf(project: Project, layoutId: string): DrawingLevel | undefined {
return { ...layout, annotations: [...(layout.annotations ?? []), annotation] }; return project.drawingLevels.find((l) => l.layoutId === layoutId);
} }
/** Entfernt eine Annotation per Id (immutabel). */ /** Neue (leere) Blatt-Ebene für `layout`. */
export function removeAnnotation(layout: Layout, annotationId: string): Layout { export function createSheetLevel(id: string, layout: Pick<Layout, "id" | "name">): DrawingLevel {
return { return { id, name: layout.name, kind: "drawing", visible: true, locked: false, layoutId: layout.id };
...layout,
annotations: (layout.annotations ?? []).filter((a) => a.id !== annotationId),
};
} }
/** /** Papier-mm (x nach rechts, y nach unten) → Blatt-Ebene (Meter, y nach oben). */
* Ändert Felder einer Annotation (immutabel). No-op, wenn die Id fehlt. Der export function sheetMmToModel(xMm: number, yMm: number): Vec2 {
* Patch ist bewusst art-unabhängig ({@link LayoutAnnotationPatch}) — es werden return { x: xMm / 1000, y: -yMm / 1000 };
* 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,
),
};
} }
/** 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 ────────────────────────────────────────────────────────────── // ── Auflösungen ──────────────────────────────────────────────────────────────
/** Findet einen Ausschnitt (View-Snapshot) im Projekt. */ /** Findet einen Ausschnitt (View-Snapshot) im Projekt. */
+5 -10
View File
@@ -3,7 +3,7 @@
// Genutzt von der Modell-Rundreise und dem Robustheitstest des Kerns. // Genutzt von der Modell-Rundreise und dem Robustheitstest des Kerns.
import { sampleProject } from "./sampleProject"; 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)); 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 }, { 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. */ /** Beispielprojekt, ergänzt um alle Element-Arten, die es selbst nicht enthält. */
export function richProject(): Project { export function richProject(): Project {
const lvl = sampleProject.drawingLevels[0].id; const lvl = sampleProject.drawingLevels[0].id;
return { return {
...sampleProject, ...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 } }], textStyles: [{ id: "ts1", label: "Titel", marks: { bold: true, font: "Helvetica", sizePt: 14 } }],
blockDefs: [{ id: "blk1", name: "Nordpfeil", geom2d: geoms.slice(0, 4) }], blockDefs: [{ id: "blk1", name: "Nordpfeil", geom2d: geoms.slice(0, 4) }],
pens: [{ id: "pen1", name: "Kontur" }], 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, 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" }], 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 }], 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" }], layoutFolders: [{ id: "lf1", name: "Pläne", kind: "layout" }],
referenceElevationMasl: 432.1, referenceElevationMasl: 432.1,
+12 -56
View File
@@ -927,6 +927,14 @@ export type DrawingLevel = {
* Fehlt ⇒ an; `false` ⇒ aus. * Fehlt ⇒ an; `false` ⇒ aus.
*/ */
levelMarks?: boolean; 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,63 +1283,11 @@ export type Layout = {
customWidthMm?: number; customWidthMm?: number;
/** Freie Blatthöhe in mm (siehe {@link Layout.customWidthMm}). */ /** Freie Blatthöhe in mm (siehe {@link Layout.customWidthMm}). */
customHeightMm?: number; customHeightMm?: number;
/**
* 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`).
*/
viewports: Array<LayoutViewport>; viewports: Array<LayoutViewport>;
/**
* 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).
*/
annotations?: Array<LayoutAnnotation>;
};
/** 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;
}; };
/** /**
-24
View File
@@ -26,7 +26,6 @@ import type {
LineStyle, LineStyle,
Opening, Opening,
Project, Project,
RichTextDoc,
Roof, Roof,
SashDef, SashDef,
Vec2, Vec2,
@@ -84,29 +83,6 @@ export interface ImportedText {
layer?: string; 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 ─────────────────────────────────────────────────────────────── // ── Helfer ───────────────────────────────────────────────────────────────
export const getWallType = (project: Project, wall: Wall): WallType => { export const getWallType = (project: Project, wall: Wall): WallType => {
+6 -36
View File
@@ -124,21 +124,14 @@ export function AttributesPanel() {
} }
const isDrawing = sel.kind === "drawing2d"; 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 // Strichstärke: Wand/Decke/Stütze/Drawing2D tragen einen eigenen Override
// (`strokeWeight`/`weightMm`) + Quellen-Dropdown; andere Elementarten erben // (`strokeWeight`/`weightMm`) + Quellen-Dropdown; andere Elementarten erben
// stets aus der Kategorie (kein Setter im Kontrakt → nicht editierbar). Bei // stets aus der Kategorie (kein Setter im Kontrakt → nicht editierbar).
// Annotationen nur Linie/Rechteck (Text/Bild kennen keine Strichstärke).
const weightEditable = const weightEditable =
sel.kind === "wall" || sel.kind === "wall" ||
sel.kind === "ceiling" || sel.kind === "ceiling" ||
sel.kind === "column" || sel.kind === "column" ||
isDrawing || isDrawing;
(isAnnotation && (sel.annotKind === "line" || sel.annotKind === "rect"));
// Schraffur: Wand/Decke/Stütze (Schnitt-/Ansichts-Schraffur) oder // Schraffur: Wand/Decke/Stütze (Schnitt-/Ansichts-Schraffur) oder
// geschlossene 2D-Form. // geschlossene 2D-Form.
const fillEditable = const fillEditable =
@@ -312,29 +305,7 @@ export function AttributesPanel() {
GESPERRT und zeigt die Strichstärke DES STIFTS (ein Stift trägt GESPERRT und zeigt die Strichstärke DES STIFTS (ein Stift trägt
beides zusammen, s. model/penSets.ts) statt des sonst aufgelösten beides zusammen, s. model/penSets.ts) statt des sonst aufgelösten
`weightMm`. */} `weightMm`. */}
{isAnnotation ? ( {sourceRow(
weightEditable && (
<>
<span className="attr-key">{t("attr.weight")}</span>
<span className="attr-val">
<input
className="attr-num"
style={{ width: 72 }}
type="number"
step={0.01}
min={0}
list="attr-pen-weights"
value={sel.weightMm}
onChange={(e) => {
const v = Number(e.target.value);
if (Number.isFinite(v)) host.onSetSelectionWeight(v);
}}
/>
</span>
</>
)
) : (
sourceRow(
"attr.weight", "attr.weight",
weightEditable && !sel.colorPenId, weightEditable && !sel.colorPenId,
weightUi, weightUi,
@@ -360,7 +331,6 @@ export function AttributesPanel() {
))} ))}
</datalist> </datalist>
</>, </>,
)
)} )}
{/* Deckkraft (0..1) — bei BILDERN deren eigene Bild-Deckkraft, bei {/* Deckkraft (0..1) — bei BILDERN deren eigene Bild-Deckkraft, bei
@@ -429,7 +399,7 @@ export function AttributesPanel() {
{/* Linienstil — nur Drawing2D trägt ihn (Wand/Decke/Annotation etc. {/* Linienstil — nur Drawing2D trägt ihn (Wand/Decke/Annotation etc.
read-only), Rest wie gehabt. */} read-only), Rest wie gehabt. */}
{!isAnnotation && ( {(
<> <>
<span className="attr-key">{t("attr.lineStyle")}</span> <span className="attr-key">{t("attr.lineStyle")}</span>
<span className="attr-val"> <span className="attr-val">
@@ -608,7 +578,7 @@ export function AttributesPanel() {
Nach Bauteil (erbt vom Component-Manager, Default) / eigener Wert. Nach Bauteil (erbt vom Component-Manager, Default) / eigener Wert.
Eine Layout-Annotation kennt keine Füllung (nur Umriss) — Sektion Eine Layout-Annotation kennt keine Füllung (nur Umriss) — Sektion
entfällt komplett statt drei bedeutungslose Dropdowns zu zeigen. */} entfällt komplett statt drei bedeutungslose Dropdowns zu zeigen. */}
{!isAnnotation && ( {(
<> <>
<div className="attr-section-label">{t("attr.fill")}</div> <div className="attr-section-label">{t("attr.fill")}</div>
@@ -797,7 +767,7 @@ export function AttributesPanel() {
„Ausdehnung X/Y" beschriften (Nutzer-Report: Fenster zeigte „Höhe „Ausdehnung X/Y" beschriften (Nutzer-Report: Fenster zeigte „Höhe
0.34 m" = Wanddicke). Öffnungen tragen Breite/Höhe im eigenen 0.34 m" = Wanddicke). Öffnungen tragen Breite/Höhe im eigenen
Abschnitt, dort entfällt die bbox ganz. */} Abschnitt, dort entfällt die bbox ganz. */}
{!isAnnotation && !sel.opening && ( {!sel.opening && (
<> <>
<div className="attr-section-label">{t("attr.size")}</div> <div className="attr-section-label">{t("attr.size")}</div>
<span className="attr-key">{t(isModelElement ? "attr.extentX" : "attr.width")}</span> <span className="attr-key">{t(isModelElement ? "attr.extentX" : "attr.width")}</span>
+2 -1
View File
@@ -77,7 +77,8 @@ export function DrawingLevelsPanel() {
}; };
// Oberstes Geschoss zuoberst (wie DOSSIER): Anzeige umkehren. // 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 // Klick aufs Auge in „Alle anzeigen"/„Nur aktive" schaltet automatisch auf
// „Ausgewählte" (DOSSIER-Regel), damit das Sichtbarkeits-Flag sofort greift. // „Ausgewählte" (DOSSIER-Regel), damit das Sichtbarkeits-Flag sofort greift.
+1 -10
View File
@@ -168,16 +168,7 @@ export function ObjectInfoPanel() {
<div className="objinfo-sep" /> <div className="objinfo-sep" />
{/* 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" ? (
<div className="objinfo-empty">{t("objinfo.layoutAnnotationHint")}</div>
) : (
<> <>
{/* Bezugspunkt-Würfel (3×3, immer quadratisch) links, X/Y/Z als Spalte {/* Bezugspunkt-Würfel (3×3, immer quadratisch) links, X/Y/Z als Spalte
rechts daneben (Nutzer-Wunsch). */} rechts daneben (Nutzer-Wunsch). */}
+3
View File
@@ -241,6 +241,9 @@ export function generatePlan(
compactUnderlay = false, compactUnderlay = false,
): Plan { ): Plan {
const compact = compactUnderlay && !mono && !forPrint; 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, // 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 // 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, // Öffnungen, Treppen, Stützen, 2D-Zeichnungen, Extrusions-Umrisse, Kontext und Schnittführung,
+1 -8
View File
@@ -352,15 +352,8 @@ export interface Selection {
| "extrudedSolid" | "extrudedSolid"
| "column" | "column"
| "roof" | "roof"
| "contextObject" | "contextObject";
| "layoutAnnotation";
id: string; 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. */ /** Grafik-Kategorie (Ebene) des Elements. */
categoryCode: string; categoryCode: string;
/** /**
+3 -3
View File
@@ -52,7 +52,7 @@ describe("Projekt laden ([K4] S4)", () => {
st().undo(); st().undo();
expect(st().project).toBe(next); expect(st().project).toBe(next);
// Kern-Dokument = Leseansicht (Speichern aus dem Kern). // 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", () => { 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(r.ok && r.migratedFrom).toBe(1);
expect(st().undoDepth).toBe(0); expect(st().undoDepth).toBe(0);
expect(st().redoDepth).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(st().project.openings?.some((o) => o.id === "TX" && o.kind === "door")).toBe(true);
expect("doors" in st().project).toBe(false); expect("doors" in st().project).toBe(false);
// Danach normal weiterarbeiten: ein Schritt, Undo zurück auf den geladenen Stand. // 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().setProject(opsMutation((p) => patchItem(p, "walls", p.walls[0].id, { height: 7 })));
st().undo(); st().undo();
expect(st().project).toEqual(loaded); 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));
}); });
}); });
+10 -3
View File
@@ -27,6 +27,11 @@ import type { Vec2 } from "../model/types";
export function useImageImportHandling(opts: { export function useImageImportHandling(opts: {
activeLevelId: string; activeLevelId: string;
activeCategoryCode: 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. */ /** Änderung als Ops (Store `applyChange`): alle Bilder eines Einfügens = ein Undo-Schritt. */
applyChange: (ops: readonly CoreOp[]) => void; applyChange: (ops: readonly CoreOp[]) => void;
notify: (message: string, kind?: NotifyKind) => void; notify: (message: string, kind?: NotifyKind) => void;
@@ -48,6 +53,7 @@ export function useImageImportHandling(opts: {
const { const {
activeLevelId, activeLevelId,
activeCategoryCode, activeCategoryCode,
imagePlacement,
applyChange, applyChange,
notify, notify,
setSelectedDrawingId, setSelectedDrawingId,
@@ -67,9 +73,10 @@ export function useImageImportHandling(opts: {
assets: { src: string; naturalWidth: number; naturalHeight: number }[], assets: { src: string; naturalWidth: number; naturalHeight: number }[],
) => { ) => {
const drawings = assets.map((a, i) => { const drawings = assets.map((a, i) => {
const { widthM, heightM } = defaultImageSizeM(a.naturalWidth, a.naturalHeight); const { widthM, heightM } = defaultImageSizeM(a.naturalWidth, a.naturalHeight, imagePlacement?.widthM);
const cascade = i * 0.3; const cascade = i * 0.15 * widthM;
const at: Vec2 = { x: -widthM / 2 + cascade, y: -heightM / 2 - cascade }; 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); return imageDrawing2d(activeLevelId, activeCategoryCode, a.src, at, widthM, heightM);
}); });
applyChange(addItems("drawings2d", drawings)); applyChange(addItems("drawings2d", drawings));
+17 -26
View File
@@ -11,7 +11,7 @@ import { applyFillMode } from "./fillMode";
import { addItems, fieldOps, opsMutation, patchItem, patchItems, removeItems, removeRoofHole, setFieldIfChanged, setRoofEdge } from "../core"; import { addItems, fieldOps, opsMutation, patchItem, patchItems, removeItems, removeRoofHole, setFieldIfChanged, setRoofEdge } from "../core";
import type { CoreOp, ProjectMutation } from "../core"; import type { CoreOp, ProjectMutation } from "../core";
import { useMemo, type RefObject } from "react"; 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 { resolvePenColor } from "../model/penSets";
import type { ToolId } from "../tools/types"; import type { ToolId } from "../tools/types";
import type { ViewType } from "../model/viewTypes"; import type { ViewType } from "../model/viewTypes";
@@ -52,7 +52,7 @@ import {
deleteMasterFolder, deleteMasterFolder,
moveLayoutToFolder, moveLayoutToFolder,
moveFolderToFolder, moveFolderToFolder,
patchAnnotation as patchAnnotationInLayout, createSheetLevel,
} from "../model/layoutModel"; } from "../model/layoutModel";
import { folderPdfBytes } from "../export/layoutPdf"; import { folderPdfBytes } from "../export/layoutPdf";
import { saveBinaryFile } from "../native/saveFile"; import { saveBinaryFile } from "../native/saveFile";
@@ -124,8 +124,6 @@ export function usePanelHostBase(opts: {
openSettings: () => void; openSettings: () => void;
onOpenStampEditor: (roomId: string) => void; onOpenStampEditor: (roomId: string) => void;
openResources: (tab?: ResourceTabId) => void; openResources: (tab?: ResourceTabId) => void;
activeLayout: Layout | undefined;
patchOpenLayout: (id: string, fn: (l: Layout) => Layout) => void;
dxfInputRef: RefObject<HTMLInputElement | null>; dxfInputRef: RefObject<HTMLInputElement | null>;
planViewRef: RefObject<PlanViewHandle | null>; planViewRef: RefObject<PlanViewHandle | null>;
selection: Selection | null; selection: Selection | null;
@@ -244,8 +242,6 @@ export function usePanelHostBase(opts: {
openSettings, openSettings,
onOpenStampEditor, onOpenStampEditor,
openResources, openResources,
activeLayout,
patchOpenLayout,
dxfInputRef, dxfInputRef,
planViewRef, planViewRef,
selection, selection,
@@ -422,15 +418,9 @@ export function usePanelHostBase(opts: {
updateStair(selection.id, { color }); updateStair(selection.id, { color });
else if (selection.kind === "room") else if (selection.kind === "room")
updateRoom(selection.id, { color }); 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) — // Stift-Kopplung der Farbe oben (s. `Selection.colorPenId`-Doku) —
// dieselben Selektionsarten wie `onSetSelectionColor`, MINUS Layout- // dieselben Selektionsarten wie `onSetSelectionColor`. `penId` gesetzt ⇒ Farbe sofort aus dem aktiven
// Annotation (kein `colorPenId`-Feld dort, bewusster Scope-Schnitt s.
// PENDENZEN.md). `penId` gesetzt ⇒ Farbe sofort aus dem aktiven
// Stiftsatz backen; `undefined` ⇒ nur die Kopplung lösen, letzter // Stiftsatz backen; `undefined` ⇒ nur die Kopplung lösen, letzter
// gebackener Wert bleibt als freie Farbe stehen. // gebackener Wert bleibt als freie Farbe stehen.
onSetSelectionColorPen: (penId) => { onSetSelectionColorPen: (penId) => {
@@ -445,15 +435,10 @@ export function usePanelHostBase(opts: {
else if (selection.kind === "room") updateRoom(selection.id, patch); else if (selection.kind === "room") updateRoom(selection.id, patch);
}, },
onSetSelectionWeight: (weightMm) => { onSetSelectionWeight: (weightMm) => {
// Strichstärke-Override: Wand/Decke (`strokeWeight`) oder Drawing2D/ // Strichstärke-Override: Wand/Decke (`strokeWeight`) oder Drawing2D (`weightMm`).
// Layout-Annotation (`weightMm`, Alt-Feldname bleibt).
if (selection?.kind === "wall") updateWall(selection.id, { strokeWeight: weightMm }); if (selection?.kind === "wall") updateWall(selection.id, { strokeWeight: weightMm });
else if (selection?.kind === "ceiling") else if (selection?.kind === "ceiling")
updateCeiling(selection.id, { strokeWeight: weightMm }); 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") else if (selection?.kind === "drawing2d")
setElementWeight(selection.id, weightMm); 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") else if (selection?.kind === "contextObject")
applyChange((p) => applyChange((p) =>
patchItem(p, "context", selection.id, (o) => (o.type === "image" ? { ...o, opacity } : o)), 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. // Anlegen öffnet es direkt; Löschen schliesst es, falls es das offene trifft.
onAddLayout: (name, paper, orientation) => { onAddLayout: (name, paper, orientation) => {
const lay = createLayout(`lay-${Date.now()}`, 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); setActiveLayoutId(lay.id);
}, },
onRenameLayout: (id, name) => { onRenameLayout: (id, name) => {
applyChange((p) => patchItem(p, "layouts", id, { name })); applyChange((p) => patchItem(p, "layouts", id, { name }));
}, },
onDeleteLayout: (id) => { 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)); setActiveLayoutId((cur) => (cur === id ? null : cur));
}, },
onOpenLayout: (id) => setActiveLayoutId(id), onOpenLayout: (id) => setActiveLayoutId(id),
@@ -1413,7 +1404,7 @@ export function usePanelHostBase(opts: {
? { customWidthMm, customHeightMm } ? { customWidthMm, customHeightMm }
: {}), : {}),
}; };
applyChange(addItems("layouts", [full])); applyChange([...addItems("layouts", [full]), ...addItems("drawingLevels", [createSheetLevel(`sheet-${id}`, full)])]);
return id; return id;
}, },
onCreateMasterLayout: (opts) => { onCreateMasterLayout: (opts) => {
+2 -127
View File
@@ -7417,134 +7417,9 @@ body {
background: var(--sheet); background: var(--sheet);
touch-action: none; touch-action: none;
user-select: none; user-select: none;
} /* Darin die Plan-Ansicht der Blatt-Ebene (füllt die Fläche). */
.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%;
display: flex; display: flex;
align-items: center; flex-direction: column;
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;
} }
/* Inline-Text-Editor auf der 2D-Zeichenfläche (PlanView) — dasselbe Prinzip /* Inline-Text-Editor auf der 2D-Zeichenfläche (PlanView) — dasselbe Prinzip
+3 -4
View File
@@ -18,10 +18,9 @@ export interface FontMetricRatios {
} }
/** Zeilenabstand-Vielfaches für gezeichneten Text, EINE Quelle für alle /** Zeilenabstand-Vielfaches für gezeichneten Text, EINE Quelle für alle
* Verbraucher (primitives.tsx "drawingText" fontSize*1.25, PlanView.tsx/ * Verbraucher (primitives.tsx "drawingText" fontSize*1.25, PlanView.tsx
* LayoutSheet.tsx Inline-Editor-Anker UND deren CSS `line-height` in * Inline-Editor-Anker UND dessen CSS `line-height` in styles.css
* styles.css `.planview-inline-text .rt-surface`/`.layout-sheet-inline-text * `.planview-inline-text .rt-surface` — alle MÜSSEN denselben Wert verwenden, sonst driften
* .rt-surface` — alle MÜSSEN denselben Wert verwenden, sonst driften
* Editor-Position und späteres Rendering wieder auseinander). */ * Editor-Position und späteres Rendering wieder auseinander). */
export const TEXT_LINE_HEIGHT_MULT = 1.25; export const TEXT_LINE_HEIGHT_MULT = 1.25;
+1 -11
View File
@@ -3,7 +3,7 @@
import { describe, expect, it } from "vitest"; import { describe, expect, it } from "vitest";
import { docFromText, makeRun, type RichTextDoc } from "./richText"; 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" }; 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({})); 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", () => { it("bricht lange Absätze wortweise auf mehrere Zeilen um", () => {
const doc = docFromText("eins zwei drei vier fünf"); const doc = docFromText("eins zwei drei vier fünf");
const lines = layoutText(doc, { ...OPTS, wrapWidthUnits: 30 }); const lines = layoutText(doc, { ...OPTS, wrapWidthUnits: 30 });
-21
View File
@@ -264,27 +264,6 @@ export function layoutText(doc: RichTextDoc, opts: SvgTextOptions): SvgLine[] {
return lines; 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 * 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, * Absatz-Zeilenhöhe) und darunter die Live-Zeilen (0.8 × Basisgrösse), vertikal um `y0` zentriert,
+1 -1
View File
@@ -432,7 +432,7 @@ export function ImportDialog({
value={existingLevelId} value={existingLevelId}
onChange={(v) => setExistingLevelId(v)} onChange={(v) => setExistingLevelId(v)}
title={t("import.target.existing")} title={t("import.target.existing")}
options={project.drawingLevels.map((z) => ({ options={project.drawingLevels.filter((z) => !z.layoutId).map((z) => ({
value: z.id, value: z.id,
label: `${z.name} · ${t(kindBadgeKey(z.kind))}`, label: `${z.name} · ${t(kindBadgeKey(z.kind))}`,
}))} }))}
+318 -1252
View File
File diff suppressed because it is too large. Load diff
+1 -259
View File
@@ -1,27 +1,13 @@
import { describe, expect, it } from "vitest"; import { describe, expect, it } from "vitest";
import type { LayoutAnnotation, LayoutViewport } from "../model/types"; import type { LayoutViewport } from "../model/types";
import { import {
annotationBoundsMm,
annotationHandleAt,
applyHandleDrag, applyHandleDrag,
applyLineHandleDrag,
clampRectToSheet, clampRectToSheet,
distanceToSegment,
fitTransform,
handleAt, handleAt,
lineHandleAt,
mmToScreen,
normalizeRect, normalizeRect,
panBy,
pickAnnotation,
pickAnnotationHandle,
pickViewport, pickViewport,
screenToMm,
translateAnnotation,
vpRect, vpRect,
zoomAtCursor,
type RectMm, type RectMm,
type SheetTransform,
} from "./layoutSheetMath"; } from "./layoutSheetMath";
const vp = ( const vp = (
@@ -32,64 +18,6 @@ const vp = (
heightMm: number, heightMm: number,
): LayoutViewport => ({ id, snapshotId: "s", xMm, yMm, widthMm, heightMm }); ): 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", () => { describe("handleAt", () => {
const r: RectMm = { xMm: 20, yMm: 20, widthMm: 100, heightMm: 60 }; const r: RectMm = { xMm: 20, yMm: 20, widthMm: 100, heightMm: 60 };
it("detects corners with priority over edges", () => { 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<LayoutAnnotation, { kind: "line" }>;
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 });
});
});
+4 -295
View File
@@ -1,25 +1,14 @@
// Reine, testbare Geometrie für die In-Viewport-Layout-Ansicht (Phase 2b): // Reine, testbare Geometrie für die Viewports auf dem Layout-Blatt: Viewport-
// Bildschirm↔Blatt-mm-Transform (Pan/Zoom-to-Cursor/Einpassen), Viewport-
// Trefferlogik (Body + 8 Resize-Griffe), Resize-Mathe mit Mindestgrösse, // Trefferlogik (Body + 8 Resize-Griffe), Resize-Mathe mit Mindestgrösse,
// Rechteck-Normalisierung (Aufziehen) und Clamp an die Blattkanten. // Rechteck-Normalisierung (Aufziehen) und Clamp an die Blattkanten.
// //
// KEINE React-/DOM-Abhängigkeit — nur Zahlen. Das UI (LayoutSheet.tsx) baut // KEINE React-/DOM-Abhängigkeit — nur Zahlen. Das UI (LayoutSheet.tsx) baut
// darauf auf. Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md). // darauf auf. Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md).
import type { LayoutAnnotation, LayoutViewport } from "../model/types"; import type { LayoutViewport } from "../model/types";
/** function clamp(v: number, lo: number, hi: number): number {
* Affine Blatt-Transform: Bildschirm-Pixel = mm · scale + translate. return v < lo ? lo : v > hi ? hi : v;
* `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;
} }
/** Ein Punkt in Blatt-Millimetern. */ /** Ein Punkt in Blatt-Millimetern. */
@@ -48,68 +37,6 @@ export type Handle =
| "w" | "w"
| "body"; | "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 ───────────────────────────────────────────── // ── Viewport-Rechtecke / Treffer ─────────────────────────────────────────────
/** Rechteck-Sicht eines Viewports (nur die Blattgeometrie). */ /** 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 }, { 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<LayoutAnnotation, { kind: "line" }>): 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<LayoutAnnotation, { kind: "line" }>,
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 };
}
+23 -9
View File
@@ -14,7 +14,7 @@ import {
useRef, useRef,
useState, useState,
} from "react"; } from "react";
import type { ComponentProps, CSSProperties } from "react"; import type { ComponentProps, CSSProperties, ReactNode } from "react";
import type { HatchRender, Plan, PlanImage, Primitive } from "../../core"; import type { HatchRender, Plan, PlanImage, Primitive } from "../../core";
import { materializeGreyed, materializeUnderlay, type UnderlayGroup } from "../../core"; import { materializeGreyed, materializeUnderlay, type UnderlayGroup } from "../../core";
import type { Drawing2D, EdgeGrip, Vec2 } from "../../model/types"; import type { Drawing2D, EdgeGrip, Vec2 } from "../../model/types";
@@ -580,6 +580,15 @@ export interface PlanViewProps {
* (`SnapSettings.hoverDivideCount`); Default 2. * (`SnapSettings.hoverDivideCount`); Default 2.
*/ */
hoverDivideCount?: number; 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). */ /** Treiber für das Ziehen von Editier-Griffen (von App bereitgestellt). */
@@ -705,6 +714,8 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
snapColor = DEFAULT_SNAP_COLOR, snapColor = DEFAULT_SNAP_COLOR,
hoverDivideDelayMs = 300, hoverDivideDelayMs = 300,
hoverDivideCount = 2, hoverDivideCount = 2,
backdrop,
fitBounds,
}, },
ref, ref,
) { ) {
@@ -720,14 +731,16 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
// toScreen-Abbildung. Reset-/Einpassen-Ziel + Bezug für die Zoom-Grenzen; wird // toScreen-Abbildung. Reset-/Einpassen-Ziel + Bezug für die Zoom-Grenzen; wird
// NICHT automatisch angewandt (nur bei resetKey-Wechsel und „Einpassen"). // NICHT automatisch angewandt (nur bei resetKey-Wechsel und „Einpassen").
const defaultView = useMemo<ViewBox>(() => { const defaultView = useMemo<ViewBox>(() => {
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 { return {
x: minX * PX_PER_M - PAD, x: minX * PX_PER_M - pad,
y: -maxY * PX_PER_M - PAD, y: -maxY * PX_PER_M - pad,
w: (maxX - minX) * PX_PER_M + PAD * 2, w: (maxX - minX) * PX_PER_M + pad * 2,
h: (maxY - minY) * 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. // Aktueller Ausschnitt; treibt die viewBox des SVG. Initial = eingepasst.
const [view, setView] = useState<ViewBox>(defaultView); const [view, setView] = useState<ViewBox>(defaultView);
@@ -823,7 +836,7 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
); );
// Engine WIRKLICH aktiv? Steuert das Umschalten SVG↔GPU: bei false rendert der // Engine WIRKLICH aktiv? Steuert das Umschalten SVG↔GPU: bei false rendert der
// volle SVG-Pfad (Fallback), bei true übernimmt die GPU-Ebene + Text-Overlay. // 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 // `planRaw.greyedRanges` (andere Ebenen als gedimmte Referenz) ohne Klonen der
// Primitive: der WebGL-Pfad dimmt selbst beim Zeichnen (nur planRaw), alle // Primitive: der WebGL-Pfad dimmt selbst beim Zeichnen (nur planRaw), alle
@@ -3035,7 +3048,7 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
glReady bleibt false → Deadlock). Bei WebGL-Fehler bleibt es leer hinten glReady bleibt false → Deadlock). Bei WebGL-Fehler bleibt es leer hinten
und der volle SVG-Pfad übernimmt sichtbar. NICHT montiert, wenn ein und der volle SVG-Pfad übernimmt sichtbar. NICHT montiert, wenn ein
Luftbild aktiv ist — dann rendert der SVG-Pfad alles inkl. Bild-Ebene. */} Luftbild aktiv ist — dann rendert der SVG-Pfad alles inkl. Bild-Ebene. */}
{wantGpu && !hasBgImages && ( {wantGpu && !hasBgImages && !backdrop && (
<canvas <canvas
ref={canvasRef} ref={canvasRef}
style={{ style={{
@@ -3117,6 +3130,7 @@ export const PlanView = forwardRef<PlanViewHandle, PlanViewProps>(
pxPerMeter={currentPxPerMeter()} pxPerMeter={currentPxPerMeter()}
/> />
)} )}
{backdrop?.(overlayOrigin, currentPxPerMeter())}
{/* Georeferenzierte Luftbilder ZWISCHEN Blatt-Hintergrund und Geometrie: {/* Georeferenzierte Luftbilder ZWISCHEN Blatt-Hintergrund und Geometrie:
Modell-Meter × PX_PER_M mit negierter y-Achse (s. toScreen) → Bild-Norden 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 (max.y) oben bei y=−max.y·PX; das Bild zeichnet natürlich von oben (kein
+45 -5
View File
@@ -9,11 +9,14 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { t } from "../i18n"; import { t } from "../i18n";
import { LayoutSheetPane, type LayoutSheetHandlers, type SheetPlanProps } from "../ui/LayoutSheet";
import { SHEET_SCALE_DENOMINATOR } from "../model/layoutModel";
import type { import type {
Ceiling, Ceiling,
Drawing2D, Drawing2D,
DrawingLevel, DrawingLevel,
EdgeGrip, EdgeGrip,
Layout,
Project, Project,
Roof, Roof,
Vec2, Vec2,
@@ -141,7 +144,14 @@ export function Content({
onEdit3dGroup, onEdit3dGroup,
onGrip3dEditTab, onGrip3dEditTab,
onGrip3dEditCancel, 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; project: Project;
level: DrawingLevel; level: DrawingLevel;
viewType: ViewType; viewType: ViewType;
@@ -372,10 +382,11 @@ export function Content({
// 3D-Umschaltung — eine Zeichnung hat keine Höhe/3D. So sind importierte // 3D-Umschaltung — eine Zeichnung hat keine Höhe/3D. So sind importierte
// DXF-Polylinien hier sofort sichtbar und mit den 2D-Werkzeugen bearbeitbar. // DXF-Polylinien hier sofort sichtbar und mit den 2D-Werkzeugen bearbeitbar.
if (level.kind === "drawing") { if (level.kind === "drawing") {
return ( // Blatt-Ebene eines offenen Layouts: Papier 1:1 (Massstab 1), Hintergrund + Viewports vom Blatt.
<main className="content"> const plan = (sheetPlan?: SheetPlanProps) => (
<DrawingTabs project={project} handlers={viewSnapshotTabs} />
<LevelPlanView <LevelPlanView
backdrop={sheetPlan?.backdrop}
fitBounds={sheetPlan?.fitBounds}
project={project} project={project}
level={level} level={level}
visibleCodes={visibleCodes} visibleCodes={visibleCodes}
@@ -383,7 +394,7 @@ export function Content({
floorDisplay={floorDisplay} floorDisplay={floorDisplay}
detail={detail} detail={detail}
referenceLines={referenceLines} referenceLines={referenceLines}
scaleDenominator={scaleDenominator} scaleDenominator={sheetPlan ? SHEET_SCALE_DENOMINATOR : scaleDenominator}
hairline={hairline} hairline={hairline}
showGrid={showGrid} showGrid={showGrid}
marqueeColor={marqueeColor} marqueeColor={marqueeColor}
@@ -417,7 +428,7 @@ export function Content({
onCommitTextEdit={onCommitTextEdit} onCommitTextEdit={onCommitTextEdit}
onCloseTextEdit={onCloseTextEdit} onCloseTextEdit={onCloseTextEdit}
onOpenSectionLevel={onSelectLevel} onOpenSectionLevel={onSelectLevel}
onPlanSelect={onPlanSelect} onPlanSelect={sheetPlan?.onPlanSelect ?? onPlanSelect}
onPlanMarquee={onPlanMarquee} onPlanMarquee={onPlanMarquee}
onSegmentCut={onSegmentCut} onSegmentCut={onSegmentCut}
onPlanContextMenu={onPlanContextMenu} onPlanContextMenu={onPlanContextMenu}
@@ -432,6 +443,27 @@ export function Content({
selectedDrawingIds={selectedDrawingIds} selectedDrawingIds={selectedDrawingIds}
gripHandlers={gripHandlers} gripHandlers={gripHandlers}
/> />
);
if (level.layoutId && sheet && sheet.layout.id === level.layoutId) {
return (
<main className="content">
<LayoutSheetPane
project={project}
layout={sheet.layout}
handlers={sheet.handlers}
toolInputActive={toolInputActive}
onPlanSelect={onPlanSelect}
planViewRef={planViewRef}
>
{plan}
</LayoutSheetPane>
</main>
);
}
return (
<main className="content">
<DrawingTabs project={project} handlers={viewSnapshotTabs} />
{plan()}
</main> </main>
); );
} }
@@ -663,6 +695,8 @@ function useCrossKindOverlay(
/** Abgeleiteter Grundriss eines Geschosses. */ /** Abgeleiteter Grundriss eines Geschosses. */
function LevelPlanView({ function LevelPlanView({
backdrop,
fitBounds,
project, project,
level, level,
visibleCodes, visibleCodes,
@@ -719,6 +753,10 @@ function LevelPlanView({
selectedDrawingIds, selectedDrawingIds,
gripHandlers, 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; project: Project;
level: DrawingLevel; level: DrawingLevel;
visibleCodes: Set<string>; visibleCodes: Set<string>;
@@ -913,6 +951,8 @@ function LevelPlanView({
selectedDrawingId={selectedDrawingId} selectedDrawingId={selectedDrawingId}
selectedDrawingIds={selectedDrawingIds} selectedDrawingIds={selectedDrawingIds}
gripHandlers={gripHandlers} gripHandlers={gripHandlers}
backdrop={backdrop}
fitBounds={fitBounds}
/> />
{/* NACH PlanView gerendert (nicht als box-shadow auf .pane), damit der {/* NACH PlanView gerendert (nicht als box-shadow auf .pane), damit der
Isolations-Rahmen über der PlanView-SVG sichtbar bleibt. */} Isolations-Rahmen über der PlanView-SVG sichtbar bleibt. */}