[66] Merge: Präsentationsplan mit einem Klick (site_and_shadow mit Massstab und Baurecht-Schalter)

This commit is contained in:
Claude committed 2026-11-05 13:44:08 +00:00
commit 553e026b86
28 files changed
+1184 -39

No files matched your search

+15 -2
View File
@@ -2095,10 +2095,23 @@ Reihenfolge = Abhängigkeiten. Neue Geometrie entsteht in Rust ([K]).
(`pattern_lines_3d_exploded`, `emitSurfacePatternLines(project, explode)`).
Offen: nur im Linux-Container geprüft (Zahlen, kein Bild, kein Metal/Tauri); Abzugskörper (truck-Booleans) werden bei
reiner Abstandsänderung neu gerechnet (Cache ohne Abstand + Verschieben nicht umgesetzt).
- ◐ **[66] Präsentationspläne mit einem Klick.** · M — 4.11.: Standard-Ansichtsvorlagen (neue Projekte, „Standards
- ✅ **[66] Präsentationspläne mit einem Klick.** · M — 4.11.: Standard-Ansichtsvorlagen (neue Projekte, „Standards
laden/aktualisieren"): „Präsentation" (farbig, Schatten, ohne Referenzen/Konstruktion), „Eingabeplan 1:100" und
„Ausführungsplan 1:50" (schwarz-weiss, fein, Strichstärken nach Massstab) — an Geschoss/Schnitt/Ansicht binden ([34]).
Offen: eigener Knopf „Präsentationsplan" (Blatt mit Grundrissen/Ansichten und Vorlage in einem Schritt).
5.11.: Knopf „Präsentationsplan" (Layouts-Panel „Mappe", Befehl `praesentation`, Aliase `praesentationsplan`/
`presentation`) mit Overlay-Dialog (Geschosse, Ansichten, ein Schnitt, Blattformat/Ausrichtung, Skizzenstil [67]):
neues Blatt in EINEM Undo-Schritt — Master passenden Formats (sonst neu, Schriftfeld vom ersten Master), je Ebene ein
an „Präsentation" gebundener Ausschnitt + Viewport, Titel „Name 1:N", Nordpfeil und Massstabsbalken beim ersten
Grundriss, Schatten der Ansichten nach Vorlage; Ausschnitte ohne Umgebung (Vermessung `01`, Umgebung `05`+, Kategorien
der Kontext-Objekte), sonst bestimmen Parzelle/Gelände Grösse und Massstab (Musterhaus komplex: A1 → 1:200 statt 1:500).
Kern dazu: Plan-Ausmass zählt ausgeblendete Kontext-Objekte nicht mehr (Zoom/Viewport-Mitte), Baurecht im Grundriss
entfällt bei ausgeblendeter Kategorie „01" (wenn vorhanden). Massstab/Raster im Kern (`presentation_sheet.rs`, Abfrage
`presentationSheet`): grösster aus 1:50/100/200/500/1000, bei dem alle Gruppen (Grundrisse, Ansichten, Schnitt)
zeilenweise ohne Überlappung neben dem Schriftfeld Platz haben. Tests: Rust-Packer, vitest (Rahmen auf dem Blatt,
keine Überlappung, ein Undo-Schritt), e2e `presentationSheet.spec.ts`. Offen: nur Linux-Container/Chromium geprüft
(nicht in Tauri); Ausschnitte sind an die Vorlage gebunden — ändert man die Vorlage, kommt die Umgebung zurück;
Viewport kann nur auf die Plan-Mitte zentrieren (kein eigener Ausschnitt-Mittelpunkt); Titelbreite geschätzt (Massstabsbalken entfällt bei schmalem Rahmen); keine Anpassung der
Anordnung von Hand im Dialog.
- ◐ **[67] Skizzenstil.** · M — 5.11.: `DrawingLevel.sketch` (+ `ViewTemplate.sketch`, über `LEVEL_KEYS` an verknüpfte
Ansichten): Kern `plan/sketch.rs` bearbeitet beim Schreiben des Plan-Puffers (`extras::Post::sketch`, Grundriss
`post_for`, Schnitt/Ansicht `sketch_post`) Linien und Polygon-Umrisse nach — leicht gebogen/gewellt, an Enden und
+44
View File
@@ -0,0 +1,44 @@
// [66] Präsentationsplan mit einem Klick: Musterhaus komplex → Knopf im Layouts-Panel → Dialog → Blatt mit je
// einem Viewport für die gewählten Geschosse, alle Ansichten und einen Schnitt; ein Undo-Schritt entfernt es.
import { blurFocus, discardIfAsked, expect, fileMenu, openTab, startNewProject, test, typeCommand } from "./app";
test.use({ viewport: { width: 1600, height: 1000 } });
test("Präsentationsplan: Dialog erstellt Blatt mit N Viewports, Undo entfernt es", async ({ page }) => {
test.setTimeout(120_000);
await startNewProject(page);
await fileMenu(page, /Musterhaus \(komplex\)/);
await discardIfAsked(page);
await expect(page.locator(".project-name")).toHaveText("Musterhaus komplex", { timeout: 30_000 });
// Über die Befehlszeile (Alias) öffnen, Dialog schliessen, dann über den Knopf im Layouts-Panel.
await typeCommand(page, "praesentationsplan");
const dialog = page.getByRole("dialog", { name: "Präsentationsplan" });
await expect(dialog).toBeVisible();
await dialog.getByRole("button", { name: "Abbrechen" }).click();
await expect(dialog).toBeHidden();
await openTab(page, "Mappe");
await page.locator("[data-testid=presentation-open]").click();
await expect(dialog).toBeVisible();
const floors = dialog.locator("input[data-floor]");
const nFloors = await floors.count();
expect(nFloors).toBeGreaterThanOrEqual(4);
// Erstes Geschoss abwählen, Ansichten + Schnitt bleiben.
await floors.first().uncheck();
await expect(dialog.locator("[data-testid=presentation-elevations]")).toBeChecked();
expect(await dialog.locator("[data-testid=presentation-section]").inputValue()).not.toBe("");
await dialog.locator("[data-testid=presentation-create]").click();
await expect(dialog).toBeHidden();
// Blatt ist offen: Grundrisse (ohne das abgewählte) + 4 Ansichten + 1 Schnitt.
const vps = page.locator("[data-viewport-id]");
await expect(vps).toHaveCount(nFloors - 1 + 4 + 1, { timeout: 20_000 });
await page.waitForTimeout(1500);
const shots = process.env.DOSSIER_SHOTS;
if (shots) await page.screenshot({ path: `${shots}/presentation-sheet.png` });
await blurFocus(page);
await page.keyboard.press("Control+z");
await expect(vps).toHaveCount(0, { timeout: 10_000 });
});
+1
View File
@@ -123,3 +123,4 @@ pub mod dim_assoc;
#[cfg(feature = "web")]
mod web;
pub mod presentation_sheet;
+6 -4
View File
@@ -790,7 +790,7 @@ pub fn plan_domains_buf(p: &Project, a: &PlanArgs) -> Result<Vec<u8>, String> {
w.group(g);
}
w.group(&violations);
w.bounds = Some(super::extras::plan_bounds(&bounds, &super::extras::extra_bounds(p, &under)));
w.bounds = Some(super::extras::plan_bounds(&bounds, &super::extras::extra_bounds(p, &under, |k| c.shown(k))));
Ok(w.finish())
}
@@ -798,7 +798,9 @@ pub fn plan_domains_buf(p: &Project, a: &PlanArgs) -> Result<Vec<u8>, String> {
/// beim projektglobalen Aufruf (`global`).
fn extras_of(p: &Project, a: &PlanArgs) -> (Vec<(Primitive, u32)>, Vec<Primitive>) {
if a.global {
super::extras::site_and_shadow(p, &a.floor, a.sun_when, a.scale)
// [66] Baurecht (Parzelle, Baubereich, Verstösse) gehört zur Vermessung: ausgeblendete Kategorie „01" ⇒ ohne.
let site = !(p.flat_categories().iter().any(|c| c.code == super::extras::SITE_CATEGORY) && !a.show.contains(super::extras::SITE_CATEGORY));
super::extras::site_and_shadow(p, &a.floor, a.sun_when, a.scale, site)
} else {
(Vec::new(), Vec::new())
}
@@ -908,7 +910,7 @@ fn assemble_cached(c: &Ctx, revs: &crate::document::Revs, cc: &mut super::cache:
domains_before(c, &mut d, &mut b)?;
domains_after(c, &mut d);
let (under, violations) = extras_of(c.p, c.a);
let extra = super::extras::extra_bounds(c.p, &under);
let extra = super::extras::extra_bounds(c.p, &under, |k| c.shown(k));
apply_voids(c.p, c.a, &mut d);
let plain = |g: Vec<Primitive>| g.into_iter().map(|q| (q, 0)).collect::<Vec<_>>();
let mut lists = vec![under];
@@ -1247,7 +1249,7 @@ mod tests {
// Ausmass: Domänen und Kontext.
let mut db = Bounds::new();
db.merge(d.bounds.unwrap());
assert_eq!(bounds, Some(super::super::extras::plan_bounds(&db, &super::super::extras::extra_bounds(&p, &[]))));
assert_eq!(bounds, Some(super::super::extras::plan_bounds(&db, &super::super::extras::extra_bounds(&p, &[], |_| true))));
}
#[test]
+45 -9
View File
@@ -158,11 +158,18 @@ fn seg_band(a: Vec2, b: Vec2, half: f64) -> Option<Primitive> {
/// Unterste Gruppe: Schatten, dann Parzellengrenze (Strich-Punkt) und zulässige Fläche
/// (gestrichelt); mit Strichmuster-Kennung je Primitiv. Dazu die Verstösse (Gebäude-Grundfläche
/// ausserhalb der zulässigen Fläche) für die oberste Gruppe.
pub fn site_and_shadow(p: &Project, floor: &str, when_ms: Option<f64>, scale: f64) -> (Vec<(Primitive, u32)>, Vec<Primitive>) {
/// Kategorie der Vermessung; ist sie im Projekt und ausgeblendet, entfällt das Baurecht im Grundriss ([66]).
pub const SITE_CATEGORY: &str = "01";
/// `site = false`: nur der Schatten, ohne Baurecht.
pub fn site_and_shadow(p: &Project, floor: &str, when_ms: Option<f64>, scale: f64, site: bool) -> (Vec<(Primitive, u32)>, Vec<Primitive>) {
let mut shadow = Vec::new();
sun_shadow(p, floor, when_ms, &mut shadow);
let mut under: Vec<(Primitive, u32)> = shadow.into_iter().map(|q| (q, 0)).collect();
let mut violations = Vec::new();
if !site {
return (under, violations);
}
if let (Some(check), Some(rules)) = (site_check(p, floor), p.site_rules.as_ref()) {
let mut r = 1;
ring_lines(&mut under, &rules.parcel, SITE_PARCEL_CLS, PARCEL_COLOR, 0.35, &PARCEL_DASH, r);
@@ -484,7 +491,9 @@ pub fn sketch_post(on: Option<bool>, scale: f64) -> Option<Post> {
/// Ausmass der Zutaten, die „Einpassen" und Druck ganz zeigen sollen: Schatten und Baurechts-Linien
/// (`extra`) und die ganze Kontext-Schicht (Konturen, Netze, Luftbilder) — Rohwerte für
/// [`plan_bounds`].
pub fn extra_bounds(p: &Project, extra: &[(Primitive, u32)]) -> Bounds {
/// Kontext-Objekte zählen nur, wenn ihre Kategorie gezeigt wird (`shown`, wie `plan_context`; ohne Kategorie
/// immer) — sonst bestimmt ein ausgeblendetes Gelände Zoom und Viewport-Grösse ([66]).
pub fn extra_bounds(p: &Project, extra: &[(Primitive, u32)], shown: impl Fn(&str) -> bool) -> Bounds {
let mut b = Bounds::new();
for (e, _) in extra {
match e {
@@ -501,6 +510,16 @@ pub fn extra_bounds(p: &Project, extra: &[(Primitive, u32)]) -> Bounds {
}
}
for obj in p.context.as_deref().unwrap_or(&[]) {
let code = match obj {
ContextObject::ImportedMesh(m) => m.category_code.as_deref(),
ContextObject::ContourSet(s) => s.category_code.as_deref(),
ContextObject::TerrainMesh(t) => t.category_code.as_deref(),
ContextObject::Image(i) => i.category_code.as_deref(),
ContextObject::Excavation(e) => e.category_code.as_deref(),
};
if code.is_some_and(|k| !shown(k)) {
continue;
}
match obj {
ContextObject::ContourSet(cs) => {
for c in &cs.contours {
@@ -553,6 +572,20 @@ mod tests {
serde_json::from_str(include_str!("../../tests/fixtures/sample_project.json")).unwrap()
}
/// [66] Ausgeblendete Kontext-Kategorien (Höhenlinien) bestimmen das Ausmass nicht mit.
#[test]
fn ausmass_ohne_ausgeblendeten_kontext() {
let mut p = sample();
p.context = Some(vec![serde_json::from_value(serde_json::json!({
"type": "contourSet", "id": "hl", "name": "HL", "categoryCode": "14",
"contours": [{"z": 0.0, "pts": [{"x": -100.0, "y": -100.0}, {"x": 100.0, "y": 100.0}]}]
}))
.unwrap()]);
let on = extra_bounds(&p, &[], |_| true).get().unwrap();
assert_eq!(on, [-100.0, -100.0, 100.0, 100.0]);
assert!(extra_bounds(&p, &[], |k| k != "14").get().is_none());
}
/// [63] Profilverstösse erscheinen im Grundriss (schwächeres Rot); ohne Profil nichts.
#[test]
fn profilverstoesse_im_grundriss() {
@@ -564,12 +597,15 @@ mod tests {
serde_json::from_value(v).unwrap()
};
p.site_rules = Some(rules(serde_json::json!({})));
let n0 = site_and_shadow(&p, &floor, None, 100.0).1.len();
let n0 = site_and_shadow(&p, &floor, None, 100.0, true).1.len();
p.site_rules = Some(rules(serde_json::json!({"profileAngle": 10.0, "profileHeight": 0.01})));
let c = crate::site_rules::check_project(&p).unwrap();
assert!(c.profile_exceeded);
let n1 = site_and_shadow(&p, &floor, None, 100.0).1.len();
let n1 = site_and_shadow(&p, &floor, None, 100.0, true).1.len();
assert!(n1 > n0, "{n0} {n1}");
// [66] Ohne Vermessung (Kategorie aus) kein Baurecht.
let (under, viol) = site_and_shadow(&p, &floor, None, 100.0, false);
assert!(under.is_empty() && viol.is_empty());
}
/// Oberste Fläche mit Pick-Id unter dem Punkt (wie `PickIndex::polygons_at`, Maske „Kontext").
@@ -592,7 +628,7 @@ mod tests {
let floor = ground_floor_id(&p).unwrap().to_string();
p.sun_study = Some(SunStudy { when: "2026-12-21T09:00:00Z".into(), show: true, ..Default::default() });
let when = Some(1_797_843_600_000.0); // 2026-12-21T09:00:00Z
let (under, _) = site_and_shadow(&p, &floor, when, 100.0);
let (under, _) = site_and_shadow(&p, &floor, when, 100.0, true);
let shadows: Vec<&Primitive> = under.iter().map(|(q, _)| q).filter(|q| matches!(q, Primitive::Polygon { fill, .. } if fill == SUN_SHADOW_FILL)).collect();
assert!(!shadows.is_empty());
assert!(shadows.iter().all(|q| matches!(q, Primitive::Polygon { context_object_id: Some(id), .. } if id == SITE_PICK_SUN)));
@@ -604,17 +640,17 @@ mod tests {
let inside = (0..400).map(|k| (x0 + (x1 - x0) * ((k % 20) as f64 + 0.5) / 20.0, y0 + (y1 - y0) * ((k / 20) as f64 + 0.5) / 20.0)).find(|q| crate::plan::pick::point_in_polygon(q.0, q.1, &flat)).unwrap();
assert_eq!(top_pick(&under, inside.0, inside.1).as_deref(), Some(SITE_PICK_SUN));
assert_eq!(top_pick(&under, 1e4, 1e4), None);
assert!(site_and_shadow(&p, "anderes-geschoss", when, 100.0).0.is_empty());
assert!(site_and_shadow(&p, "anderes-geschoss", when, 100.0, true).0.is_empty());
p.sun_study.as_mut().unwrap().show = false;
assert_eq!(top_pick(&site_and_shadow(&p, &floor, when, 100.0).0, inside.0, inside.1), None);
assert_eq!(top_pick(&site_and_shadow(&p, &floor, when, 100.0, true).0, inside.0, inside.1), None);
// Baurecht: Parzellengrenze bei x = −30, Grenzabstand 3 m → zulässige Fläche ab x = −27; Band ±0.15 m bei 1:100.
p.site_rules = Some(serde_json::from_value(serde_json::json!({"parcel": [{"x": -30, "y": -30}, {"x": 40, "y": -30}, {"x": 40, "y": 40}, {"x": -30, "y": 40}], "defaultSetback": 3.0})).unwrap());
let (under, _) = site_and_shadow(&p, &floor, when, 100.0);
let (under, _) = site_and_shadow(&p, &floor, when, 100.0, true);
assert_eq!(top_pick(&under, -30.1, 5.0).as_deref(), Some(SITE_PICK_RULES));
assert_eq!(top_pick(&under, -27.0, 5.0).as_deref(), Some(SITE_PICK_RULES), "zulässige Fläche");
assert_eq!(top_pick(&under, -28.5, 5.0), None);
// Massstab 1:500: Band ±0.75 m.
assert_eq!(top_pick(&site_and_shadow(&p, &floor, when, 500.0).0, -29.4, 5.0).as_deref(), Some(SITE_PICK_RULES));
assert_eq!(top_pick(&site_and_shadow(&p, &floor, when, 500.0, true).0, -29.4, 5.0).as_deref(), Some(SITE_PICK_RULES));
}
#[test]
+274
View File
@@ -0,0 +1,274 @@
//! [66] Präsentationsplan mit einem Klick: gemeinsamen Massstab wählen und die Ansichten (Grundrisse,
//! Ansichten, Schnitt) in einem ruhigen Raster auf dem Blatt anordnen.
//!
//! Jede Gruppe (Grundrisse, Ansichten, Schnitte) bekommt gleich grosse Rahmen (grösster Inhalt der Gruppe
//! plus Rand) und füllt Zeilen von links nach rechts; jede Zeile ist waagrecht zentriert, der ganze Block
//! senkrecht, soweit Platz ist. Das Schriftfeld des Masters (unten rechts, wie `TitleBlockSvg`) bleibt frei.
//! Gewählt wird der grösste Massstab aus [`SCALES`], bei dem alles auf das Blatt passt.
use crate::model::{DetailLevel, Project, ViewSnapshot};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::collections::BTreeMap;
/// Massstäbe in Wahlreihenfolge (grösster zuerst).
pub const SCALES: [f64; 5] = [50.0, 100.0, 200.0, 500.0, 1000.0];
/// Rand zwischen Inhalt und Viewport-Rahmen (mm).
pub const FRAME_PAD_MM: f64 = 4.0;
/// Abstand zwischen Rahmen (mm).
pub const GAP_MM: f64 = 12.0;
/// Platz für den Titel unter jedem Rahmen (mm).
pub const TITLE_MM: f64 = 9.0;
/// Blattrand (mm, innerhalb des Master-Rahmens bei 5 mm).
pub const MARGIN_MM: f64 = 15.0;
/// Schriftfeld des Masters: Breite, Höhe, Abstand zum Blattrand (mm, wie `TitleBlockSvg`).
pub const TITLE_BLOCK_MM: [f64; 3] = [70.0, 30.0, 6.0];
/// Rahmen eines Viewports auf dem Blatt (mm, Ursprung oben links).
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Rect {
pub x_mm: f64,
pub y_mm: f64,
pub width_mm: f64,
pub height_mm: f64,
}
/// Blatt: Grösse (mm) und das freizuhaltende Schriftfeld `[x, y, w, h]`.
#[derive(Clone, Copy, Debug)]
pub struct Sheet {
pub w: f64,
pub h: f64,
pub title_block: Option<[f64; 4]>,
}
impl Sheet {
pub fn new(w: f64, h: f64, title_block: bool) -> Sheet {
let [tw, th, pad] = TITLE_BLOCK_MM;
Sheet { w, h, title_block: title_block.then(|| [w - tw - pad, h - th - pad, tw, th]) }
}
}
/// Zeilen ab `y0` füllen; `strict`: `None`, wenn eine Zeile oder der Block nicht aufs Blatt passt.
fn pack_from(items: &[(u32, f64, f64)], sheet: &Sheet, y0: f64, strict: bool) -> Option<(Vec<Rect>, f64)> {
let (l, r, b) = (MARGIN_MM, sheet.w - MARGIN_MM, sheet.h - MARGIN_MM);
let mut out = vec![Rect::default(); items.len()];
let mut y = y0;
let mut i = 0;
while i < items.len() {
let g = items[i].0;
let j = i + items[i..].iter().take_while(|it| it.0 == g).count();
let cw = items[i..j].iter().fold(0.0_f64, |m, it| m.max(it.1)) + 2.0 * FRAME_PAD_MM;
let ch = items[i..j].iter().fold(0.0_f64, |m, it| m.max(it.2)) + 2.0 * FRAME_PAD_MM;
let mut k = i;
while k < j {
let row_bottom = y + ch + TITLE_MM;
let right = match sheet.title_block {
Some([tx, ty, _, th]) if row_bottom > ty - GAP_MM && y < ty + th => tx - GAP_MM,
_ => r,
};
let fit = ((right - l + GAP_MM) / (cw + GAP_MM)).floor();
let n = if fit.is_finite() && fit >= 1.0 { fit as usize } else if strict { return None } else { 1 };
let cnt = n.min(j - k);
let row_w = cnt as f64 * cw + (cnt as f64 - 1.0) * GAP_MM;
let x0 = l + ((right - l - row_w) / 2.0).max(0.0);
for c in 0..cnt {
out[k + c] = Rect { x_mm: x0 + c as f64 * (cw + GAP_MM), y_mm: y, width_mm: cw, height_mm: ch };
}
k += cnt;
y = row_bottom + GAP_MM;
}
i = j;
}
let bottom = y - GAP_MM;
if strict && bottom > b + 1e-9 {
return None;
}
Some((out, bottom))
}
/// Rahmen für Inhalte `(Gruppe, Breite, Höhe)` (Papier-mm, Gruppen aufsteigend sortiert) in Eingabe-
/// reihenfolge; `None`, wenn sie nicht aufs Blatt passen. Der Block wird senkrecht zentriert, wenn das
/// die Zeilen nicht verändert.
pub fn pack(items: &[(u32, f64, f64)], sheet: &Sheet) -> Option<Vec<Rect>> {
let (top, b) = (MARGIN_MM, sheet.h - MARGIN_MM);
let (first, bottom) = pack_from(items, sheet, top, true)?;
let off = (b - bottom) / 2.0;
if off > 0.0 {
if let Some((centered, _)) = pack_from(items, sheet, top + off, true) {
return Some(centered);
}
}
Some(first)
}
/// Ergebnis der Wahl: Massstab, ob alles passt, Rahmen je Inhalt.
#[derive(Debug, Clone, PartialEq)]
pub struct Choice {
pub scale: f64,
pub fits: bool,
pub rects: Vec<Rect>,
}
/// Grösster Massstab aus [`SCALES`], bei dem alles passt (`sizes_at(scale)` = Inhalte beim Massstab);
/// passt nichts, der kleinste Massstab mit überlaufenden Zeilen (`fits = false`).
pub fn choose(mut sizes_at: impl FnMut(f64) -> Vec<(u32, f64, f64)>, sheet: &Sheet) -> Choice {
for s in SCALES {
if let Some(rects) = pack(&sizes_at(s), sheet) {
return Choice { scale: s, fits: true, rects };
}
}
let s = SCALES[SCALES.len() - 1];
let rects = pack_from(&sizes_at(s), sheet, MARGIN_MM, false).map(|r| r.0).unwrap_or_default();
Choice { scale: s, fits: false, rects }
}
/// Anfrage der Abfrage `presentationSheet`.
#[derive(Deserialize, Default)]
#[serde(rename_all = "camelCase", default)]
pub struct Request {
/// Ebenen (Geschosse, Ansichten, Schnitte) in Blattreihenfolge.
pub levels: Vec<String>,
/// Gruppe je Ebene (0 Grundrisse, 1 Ansichten, 2 Schnitte), aufsteigend.
pub groups: Vec<u32>,
pub layer_visibility: BTreeMap<String, bool>,
pub detail: DetailLevel,
pub sheet_w: f64,
pub sheet_h: f64,
pub title_block: bool,
/// Schatten der Ansichten (Vorlage „Präsentation").
pub shadows: bool,
}
/// Abfrage `presentationSheet`: Massstab und Rahmen für die Ebenen; Ebenen ohne Inhalt stehen unter
/// `skipped`.
pub fn query(p: &Project, text: &str) -> Result<Value, String> {
let req: Request = serde_json::from_str(text).map_err(|e| format!("presentationSheet: {e}"))?;
if !(req.sheet_w > 0.0 && req.sheet_h > 0.0 && req.sheet_w.is_finite() && req.sheet_h.is_finite()) {
return Err("presentationSheet: Blattgrösse ungültig".into());
}
let snap = |level: &str| ViewSnapshot {
active_level_id: level.to_string(),
layer_visibility: req.layer_visibility.clone(),
detail: req.detail,
scale_denominator: 100.0,
..Default::default()
};
let bounds_at = |level: &str, s: f64| crate::sheet_viewports::snapshot_bounds(p, &snap(level), s, Some(req.shadows));
// Ebenen ohne Inhalt fallen weg (geprüft beim mittleren Massstab).
let mut kept: Vec<(String, u32)> = Vec::new();
let mut skipped: Vec<String> = Vec::new();
for (i, id) in req.levels.iter().enumerate() {
let ok = p.drawing_levels.iter().any(|l| &l.id == id) && bounds_at(id, 100.0).is_some_and(|b| b.iter().all(|v| v.is_finite()) && b[2] > b[0] && b[3] > b[1]);
if ok {
kept.push((id.clone(), req.groups.get(i).copied().unwrap_or(0)));
} else {
skipped.push(id.clone());
}
}
kept.sort_by_key(|k| k.1);
let sheet = Sheet::new(req.sheet_w, req.sheet_h, req.title_block);
let choice = choose(
|s| {
kept.iter()
.map(|(id, g)| {
let b = bounds_at(id, s).unwrap_or([0.0, 0.0, 1.0, 1.0]);
(*g, (b[2] - b[0]) * 1000.0 / s, (b[3] - b[1]) * 1000.0 / s)
})
.collect()
},
&sheet,
);
let items: Vec<Value> = kept
.iter()
.zip(&choice.rects)
.map(|((id, g), r)| json!({"levelId": id, "group": g, "xMm": r.x_mm, "yMm": r.y_mm, "widthMm": r.width_mm, "heightMm": r.height_mm}))
.collect();
Ok(json!({"scale": choice.scale, "fits": choice.fits, "items": items, "skipped": skipped}))
}
#[cfg(test)]
mod tests {
use super::*;
fn inside(r: &Rect, s: &Sheet) -> bool {
r.x_mm >= MARGIN_MM - 1e-9
&& r.y_mm >= MARGIN_MM - 1e-9
&& r.x_mm + r.width_mm <= s.w - MARGIN_MM + 1e-9
&& r.y_mm + r.height_mm + TITLE_MM <= s.h - MARGIN_MM + 1e-9
}
fn overlap(a: &Rect, b: &Rect) -> bool {
a.x_mm < b.x_mm + b.width_mm && b.x_mm < a.x_mm + a.width_mm && a.y_mm < b.y_mm + b.height_mm + TITLE_MM && b.y_mm < a.y_mm + a.height_mm + TITLE_MM
}
fn check(rects: &[Rect], s: &Sheet) {
for (i, a) in rects.iter().enumerate() {
assert!(inside(a, s), "{a:?} ausserhalb");
if let Some([tx, ty, tw, th]) = s.title_block {
let tb = Rect { x_mm: tx, y_mm: ty, width_mm: tw, height_mm: th - TITLE_MM };
assert!(!overlap(a, &tb), "{a:?} über dem Schriftfeld");
}
for b in &rects[i + 1..] {
assert!(!overlap(a, b), "{a:?} überlappt {b:?}");
}
}
}
/// Haus 12 × 10 m (4 Geschosse), Ansichten 12 × 9 m: A1 quer (841 × 594): 1:50 passt nicht,
/// 1:100 schon.
#[test]
fn a1_waehlt_1_100_und_alles_liegt_auf_dem_blatt() {
let s = Sheet::new(841.0, 594.0, true);
let sizes = |sc: f64| {
let mut v: Vec<(u32, f64, f64)> = (0..4).map(|_| (0, 12000.0 / sc, 10000.0 / sc)).collect();
v.extend((0..4).map(|_| (1, 12000.0 / sc, 9000.0 / sc)));
v.push((2, 12000.0 / sc, 9000.0 / sc));
v
};
let c = choose(sizes, &s);
assert!(c.fits);
assert_eq!(c.scale, 100.0);
assert_eq!(c.rects.len(), 9);
check(&c.rects, &s);
// Gleiche Rahmen je Gruppe, Grundrisse oben.
assert!(c.rects[..4].iter().all(|r| r.width_mm == c.rects[0].width_mm && r.height_mm == c.rects[0].height_mm));
assert!(c.rects[4].y_mm > c.rects[0].y_mm);
}
/// Grosser Bau auf A3: 1:100 passt nicht, 1:200 auch nicht, 1:500 schon.
#[test]
fn kleines_blatt_waehlt_kleineren_massstab() {
let s = Sheet::new(420.0, 297.0, true);
let c = choose(|sc| (0..3).map(|g| (g, 60000.0 / sc, 30000.0 / sc)).collect(), &s);
assert!(c.fits);
assert_eq!(c.scale, 500.0);
check(&c.rects, &s);
}
#[test]
fn passt_nichts_dann_kleinster_massstab_ohne_passt() {
let s = Sheet::new(210.0, 297.0, false);
let c = choose(|sc| vec![(0, 900_000.0 / sc, 900_000.0 / sc)], &s);
assert!(!c.fits);
assert_eq!(c.scale, 1000.0);
assert_eq!(c.rects.len(), 1);
}
#[test]
fn schriftfeld_bleibt_frei_und_leere_liste() {
let s = Sheet::new(594.0, 420.0, true);
let items: Vec<(u32, f64, f64)> = (0..12).map(|i| (i / 6, 70.0, 50.0)).collect();
let r = pack(&items, &s).expect("passt");
check(&r, &s);
assert_eq!(pack(&[], &s), Some(vec![]));
}
#[test]
fn unsinn_wird_abgelehnt() {
let p = Project::default();
assert!(query(&p, "kein json").is_err());
assert!(query(&p, r#"{"sheetW": -1, "sheetH": 5}"#).is_err());
let v = query(&p, r#"{"levels": ["fehlt"], "groups": [0], "sheetW": 841, "sheetH": 594}"#).unwrap();
assert_eq!(v["skipped"][0], "fehlt");
assert_eq!(v["items"].as_array().map(|a| a.len()), Some(0));
}
}
+1
View File
@@ -75,6 +75,7 @@ pub fn run(p: &Project, name: &str, args: &[f64], text: &str) -> Result<String,
("elementSchedule", _) => json(&crate::u_value::element_schedule(p)),
("sheetTables", _) => Ok(crate::sheet_table::query(p, text).to_string()),
("sheetTableCatalog", _) => Ok(crate::sheet_table::catalog_json().to_string()),
("presentationSheet", _) => Ok(crate::presentation_sheet::query(p, text)?.to_string()),
("uValue", _) => json(&crate::u_value::query(p, text)),
("surfaceOpening", _) => json(&crate::opening_shape::surface_opening_info(p, text)),
("openingPreview", _) => json(&crate::opening_preview::opening_preview(p, text)),
+20 -6
View File
@@ -99,12 +99,7 @@ pub fn viewport_maps(p: &Project, layout: &Layout) -> Vec<VpMap> {
continue;
}
let scale = viewport_scale(vp, Some(snap));
let level = p.drawing_levels.iter().find(|l| l.id == snap.active_level_id);
let buf = match level {
Some(l) if matches!(l.kind, DrawingLevelKind::Section | DrawingLevelKind::Elevation) => section_view_buf(p, l, snap, scale),
_ => plan_domains_buf(p, &viewport_args(snap, scale)).ok(),
};
let Some(buf) = buf else { continue };
let Some(buf) = snapshot_buf(p, snap, scale, None) else { continue };
let Some(b) = crate::plan::buf::View::parse(&buf).and_then(|v| v.bounds()) else { continue };
out.push(VpMap {
x_mm: vp.x_mm,
@@ -121,6 +116,25 @@ pub fn viewport_maps(p: &Project, layout: &Layout) -> Vec<VpMap> {
out
}
/// Plan-Puffer des Inhalts eines Ausschnitts beim Massstab 1:`scale` (Grundriss bzw. Schnitt/Ansicht wie
/// im Viewport). `shadows` übersteuert den Schatten der Ansicht (Präsentationsplan [66]: Vorlage vor dem Anwenden).
pub fn snapshot_buf(p: &Project, snap: &ViewSnapshot, scale: f64, shadows: Option<bool>) -> Option<Vec<u8>> {
match p.drawing_levels.iter().find(|l| l.id == snap.active_level_id) {
Some(l) if matches!(l.kind, DrawingLevelKind::Section | DrawingLevelKind::Elevation) => match shadows {
Some(s) => section_view_buf(p, &DrawingLevel { shadows: Some(s), ..l.clone() }, snap, scale),
None => section_view_buf(p, l, snap, scale),
},
_ => plan_domains_buf(p, &viewport_args(snap, scale)).ok(),
}
}
/// Ausmass (Modell-Meter `[minX, minY, maxX, maxY]`) des Ausschnitt-Inhalts — das Rechteck, dessen Mitte
/// der Viewport zentriert.
pub fn snapshot_bounds(p: &Project, snap: &ViewSnapshot, scale: f64, shadows: Option<bool>) -> Option<[f64; 4]> {
let buf = snapshot_buf(p, snap, scale, shadows)?;
crate::plan::buf::View::parse(&buf).and_then(|v| v.bounds())
}
/// Kategorie-Codes, die Schnitt/Ansicht prüfen (`candidateCodes` in `toSection.ts`).
fn candidate_codes(p: &Project) -> HashSet<String> {
let mut codes: HashSet<String> = p.flat_categories().iter().map(|c| c.code.clone()).collect();
+3
View File
@@ -33,6 +33,7 @@ import { programStatusLabel } from "./panels/KennzahlenSection";
import { sectionPlaneFromLevel, sectionUAxisModel } from "./core";
import { setDxfImportTrigger } from "./io/dxfImportHook";
import { ImportDialog } from "./ui/ImportDialog";
import { PresentationDialogHost } from "./ui/PresentationDialog";
import { BusyOverlay } from "./ui/BusyOverlay";
import { ExportPdfDialog } from "./ui/ExportPdfDialog";
import { ExportDxfDialog } from "./ui/ExportDxfDialog";
@@ -2670,6 +2671,8 @@ export default function App() {
{/* Modaler Import-Dialog (DXF/DWG) — offen, sobald eine Datei gewählt/
fallengelassen wurde. Liefert eine strukturierte Entscheidung an
runImport (Ebene anlegen / Drawings anhängen / Meshes als Kontext). */}
{/* [66] Präsentationsplan: Dialog (Befehl `praesentation`, Knopf im Layouts-Panel) */}
<PresentationDialogHost onCreated={setActiveLayoutId} />
{importState && (
<ImportDialog
fileName={importState.fileName}
+42
View File
@@ -0,0 +1,42 @@
import { beforeEach, describe, expect, it } from "vitest";
import { COMMANDS, ALIASES } from "../registry";
import { setPresentationDialogOpener } from "../../state/presentationSheetHook";
import { createPresentationSheet } from "../../state/presentationSheet";
import { getState } from "../../state/appStore";
import { buildComplexSampleProject } from "../../model/sampleProjectComplex";
import { presentationDefaults } from "../../core";
describe("[66] Befehl praesentation", () => {
beforeEach(() => {
getState().loadProject(buildComplexSampleProject());
getState().clearHistory();
});
it("Aliase führen auf den Befehl, der den Dialog öffnet", () => {
expect(ALIASES.praesentationsplan).toBe("praesentation");
expect(ALIASES.presentation).toBe("praesentation");
let opened = 0;
setPresentationDialogOpener(() => opened++);
const res = COMMANDS.praesentation.autoRun!({} as never);
expect(res.done).toBe(true);
expect(opened).toBe(1);
setPresentationDialogOpener(null);
});
it("Bestätigen legt das Blatt in EINEM Undo-Schritt an", () => {
const before = getState().project;
const o = presentationDefaults(before);
const id = createPresentationSheet({ ...o, sketch: true });
expect(id).toBeTruthy();
const p = getState().project;
const lay = p.layouts!.find((l) => l.id === id)!;
expect(lay.viewports.length).toBeGreaterThanOrEqual(o.floors.length);
expect(p.drawingLevels.some((l) => l.sketch)).toBe(true);
expect(getState().undoDepth).toBe(1);
getState().undo();
const q = getState().project;
expect(q.layouts?.some((l) => l.id === id)).toBe(false);
expect(q.drawingLevels.some((l) => l.sketch)).toBe(false);
expect(q.drawingLevels.length).toBe(before.drawingLevels.length);
});
});
+29
View File
@@ -0,0 +1,29 @@
// [66] Präsentationsplan — öffnet den Dialog (in App montiert) und endet sofort; das Blatt entsteht beim
// Bestätigen in einem Undo-Schritt (`state/presentationSheet.ts`). Muster wie `import`.
import { openPresentationDialog } from "../../state/presentationSheetHook";
import type { Command, CommandResult, CommandState } from "../types";
const IDLE: CommandState = { phase: "idle", lastPoint: null };
function open(): [CommandState, CommandResult] {
openPresentationDialog();
return [{ ...IDLE }, { draft: null, done: true }];
}
export const presentationCommand: Command = {
name: "praesentation",
labelKey: "cmd.praesentation.label",
prompt: () => "cmd.praesentation.prompt",
accepts: () => [],
options: () => [],
init: () => ({ ...IDLE }),
autoRun: (): CommandResult => {
openPresentationDialog();
return { draft: null, done: true };
},
onInput: () => open(),
onMove: (state): [CommandState, CommandResult] => [state, { draft: null }],
onConfirm: () => open(),
onCancel: (): [CommandState, CommandResult] => [{ ...IDLE }, { draft: null, done: true }],
};
+5
View File
@@ -71,6 +71,7 @@ import { sectionLineCommand, viewLineCommand } from "./cmds/sectionline";
import { georefCommand } from "./cmds/georef";
import { blockCommand } from "./cmds/block";
import { defblockCommand } from "./cmds/defblock";
import { presentationCommand } from "./cmds/presentation";
/** Alle bekannten Befehle, Schlüssel = Befehlsname (lowercase). */
export const COMMANDS: Record<string, Command> = {
@@ -140,6 +141,7 @@ export const COMMANDS: Record<string, Command> = {
chamfer: chamferCommand,
multiline: multilineCommand,
import: importCommand,
praesentation: presentationCommand,
terrain: terrainCommand,
excavation: excavationCommand,
measure: measureCommand,
@@ -184,6 +186,9 @@ export const ALIASES: Record<string, string> = {
dachfenster: "roofwindow",
oberlicht: "roofwindow",
gaube: "dormer",
praesentationsplan: "praesentation",
präsentation: "praesentation",
presentation: "praesentation",
lukarne: "dormer",
dachhof: "roofhole",
lichthof: "roofhole",
+1
View File
@@ -123,6 +123,7 @@ export type RootQueryName = "penRebakeOps" | "penDeleteOps" | "penSeedOps" | "st
/** Abfragen des Kerns (`queries.rs`). */
export type QueryName =
| "surfaceOpening"
| "presentationSheet"
| "kennzahlen"
| "areaTable"
| "programCompare"
+2
View File
@@ -82,3 +82,5 @@ export { AI_TOOLS, AI_BRIDGE_DEFAULT_PORT, aiText, aiToolDef, hmacHex, randomHex
export type { AiToolDef, AiToolResult, AiBridgeMsg } from "./aiToolDefs";
export { callAiTool } from "./aiTools";
export type { AiHost } from "./aiTools";
export { PRESENTATION_TEMPLATE_ID, presentationDefaults, presentationSheetOps, planPresentationSheet } from "../plan/presentationSheet";
export type { PresentationOptions, PresentationPlan, PresentationLabels } from "../plan/presentationSheet";
+19
View File
@@ -3293,6 +3293,25 @@ export const de = {
"publish.empty": "Der Satz enthält keine Blätter.",
"publish.done": "Publiziert (Dateien)",
"publish.failed": "Publikation fehlgeschlagen",
"cmd.praesentation.label": "Präsentationsplan",
"cmd.praesentation.prompt": "Präsentationsplan einrichten …",
"presentation.title": "Präsentationsplan",
"presentation.button": "Präsentationsplan erstellen",
"presentation.floors": "Geschosse",
"presentation.elevations": "Ansichten",
"presentation.section": "Schnitt",
"presentation.noSection": "Kein Schnitt",
"presentation.sheet": "Blatt",
"presentation.sketch": "Skizzenstil (gezeigte Ebenen)",
"presentation.hint": "Der gemeinsame Massstab wird so gewählt, dass alles aufs Blatt passt; die Ausschnitte folgen der Vorlage „Präsentation“.",
"presentation.create": "Erstellen",
"presentation.sheetName": "Präsentationsplan",
"presentation.masterName": "Planrahmen {format}",
"presentation.north": "N",
"presentation.done": "Präsentationsplan 1:{scale} mit {n} Ansichten erstellt",
"presentation.tooBig": "Präsentationsplan: passt auch 1:{scale} nicht ganz aufs Blatt – grösseres Format wählen",
"presentation.empty": "Präsentationsplan: keine Ansicht mit Inhalt gewählt",
"presentation.failed": "Präsentationsplan konnte nicht erstellt werden",
} as const;
export type TranslationKey = keyof typeof de;
+19
View File
@@ -3279,4 +3279,23 @@ export const en: Record<TranslationKey, string> = {
"publish.empty": "The set contains no sheets.",
"publish.done": "Published (files)",
"publish.failed": "Publishing failed",
"cmd.praesentation.label": "Presentation sheet",
"cmd.praesentation.prompt": "Set up presentation sheet …",
"presentation.title": "Presentation sheet",
"presentation.button": "Create presentation sheet",
"presentation.floors": "Floors",
"presentation.elevations": "Elevations",
"presentation.section": "Section",
"presentation.noSection": "No section",
"presentation.sheet": "Sheet",
"presentation.sketch": "Sketch style (shown views)",
"presentation.hint": "A common scale is chosen so that everything fits on the sheet; the views follow the “Presentation” template.",
"presentation.create": "Create",
"presentation.sheetName": "Presentation sheet",
"presentation.masterName": "Sheet frame {format}",
"presentation.north": "N",
"presentation.done": "Presentation sheet 1:{scale} with {n} views created",
"presentation.tooBig": "Presentation sheet: does not fully fit even at 1:{scale} – choose a larger format",
"presentation.empty": "Presentation sheet: no view with content chosen",
"presentation.failed": "Could not create the presentation sheet",
};
+22
View File
@@ -34,6 +34,7 @@ import {
type LayoutSizeStart,
type NewLayoutStart,
} from "../ui/LayoutCreateDialogs";
import { openPresentationDialog } from "../state/presentationSheetHook";
import { PublishSection } from "./PublishSection";
import { t } from "../i18n";
@@ -809,6 +810,15 @@ export function LayoutsPanel() {
>
<PlusIcon />
</button>
<button
className="nav-add"
data-testid="presentation-open"
style={{ display: "inline-flex", padding: "1px 5px" }}
title={t("presentation.button")}
onClick={openPresentationDialog}
>
<PresentationIcon />
</button>
</span>
</header>
@@ -913,3 +923,15 @@ export function LayoutsTabIcon() {
</svg>
);
}
/** [66] Symbol „Präsentationsplan" — Blatt mit vier Ausschnitten. */
function PresentationIcon() {
return (
<svg width={13} height={13} viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth={1.3} aria-hidden="true">
<rect x={1.5} y={2.5} width={13} height={11} rx={1} />
<rect x={3.5} y={4.5} width={4} height={3} />
<rect x={8.5} y={4.5} width={4} height={3} />
<rect x={3.5} y={9} width={9} height={2.5} />
</svg>
);
}
@@ -1,5 +1,5 @@
viewBox -16.5 0 49 35.22
bytes 339975
viewBox -4 0 23 18
bytes 335733
circle 14
line 3490
path 7
@@ -7,4 +7,4 @@ polygon 84
rect 1
svg 1
text 36
hash 54cda2b02ff24629
hash ee49c09d752ec831
@@ -1,5 +1,5 @@
viewBox -16.5 0 49 35.22
bytes 343360
viewBox -4 0 23 18
bytes 339126
circle 14
line 3490
path 7
@@ -7,4 +7,4 @@ polygon 84
rect 1
svg 1
text 36
hash 63500897d4b9b701
hash 6d7a49d4aa11cf99
@@ -1,5 +1,5 @@
viewBox -16.5 0 49 35.22
bytes 420969
viewBox -4.055 0 25.109 23.11
bytes 413037
circle 14
line 4009
path 40
@@ -7,4 +7,4 @@ polygon 226
rect 1
svg 1
text 91
hash eef8a2ed5b92de94
hash 7d43d37dc2df5f36
@@ -1,5 +1,5 @@
viewBox -16.5 0 49 35.22
bytes 424473
viewBox -4.055 0 25.109 23.11
bytes 416536
circle 14
line 4009
path 40
@@ -7,4 +7,4 @@ polygon 226
rect 1
svg 1
text 91
hash c04769d56ef373e5
hash 63761ac76b26d6f6
@@ -1,5 +1,5 @@
viewBox -16.5 0 49 35.22
bytes 83590
viewBox -10.004 0 31.058 26.958
bytes 83162
circle 14
line 481
path 30
@@ -7,4 +7,4 @@ polygon 107
rect 1
svg 1
text 75
hash 51d02b12b3f8d6a0
hash 53f7fc8b03f80857
@@ -1,5 +1,5 @@
viewBox -16.5 0 49 35.22
bytes 83694
viewBox -10.004 0 31.058 26.958
bytes 83325
circle 14
line 481
path 30
@@ -7,4 +7,4 @@ polygon 107
rect 1
svg 1
text 75
hash be6844edd22e12d2
hash 46946bd19183e627
+93
View File
@@ -0,0 +1,93 @@
import { beforeEach, describe, expect, it } from "vitest";
import { buildComplexSampleProject } from "../model/sampleProjectComplex";
import { getState } from "../state/appStore";
import { sheetSizeMm } from "../model/layoutModel";
import { PRESENTATION_TEMPLATE_ID, presentationDefaults, presentationSheetOps } from "./presentationSheet";
import type { Project } from "../model/types";
const LABELS = { sheetName: "Präsentationsplan", masterName: "Planrahmen", north: "N" };
const st = () => getState();
function overlaps(a: { xMm: number; yMm: number; widthMm: number; heightMm: number }, b: typeof a): boolean {
return a.xMm < b.xMm + b.widthMm && b.xMm < a.xMm + a.widthMm && a.yMm < b.yMm + b.heightMm && b.yMm < a.yMm + a.heightMm;
}
describe("[66] Präsentationsplan", () => {
let project: Project;
beforeEach(() => {
st().loadProject(buildComplexSampleProject());
st().clearHistory();
project = st().project;
});
it("Vorschlag: alle Geschosse, Ansichten, ein Schnitt, A1 quer (Master)", () => {
const d = presentationDefaults(project);
expect(d.floors.length).toBeGreaterThanOrEqual(4);
expect(d.elevations).toBe(true);
expect(d.sectionId).not.toBeNull();
expect([d.paper, d.orientation]).toEqual(["a1", "landscape"]);
expect(d.sketch).toBe(false);
});
it("ein Undo-Schritt: Blatt mit je einem Viewport pro Ebene, alle auf dem Blatt, ohne Überlappung", () => {
const o = presentationDefaults(project);
const elevations = project.drawingLevels.filter((l) => l.kind === "elevation").length;
const layoutsBefore = (project.layouts ?? []).length;
const res = presentationSheetOps(project, o, LABELS, "t1");
expect(res).not.toBeNull();
const { ops, layoutId, plan } = res!;
expect([50, 100, 200]).toContain(plan.scale);
expect(plan.fits).toBe(true);
st().applyChange(ops);
expect(st().undoDepth).toBe(1);
const p = st().project;
const lay = p.layouts!.find((l) => l.id === layoutId)!;
expect(lay.viewports.length).toBe(o.floors.length + elevations + 1);
expect(lay.masterId).toBeTruthy();
const size = sheetSizeMm(lay.paper, lay.orientation);
for (const [i, v] of lay.viewports.entries()) {
expect(v.xMm).toBeGreaterThanOrEqual(0);
expect(v.yMm).toBeGreaterThanOrEqual(0);
expect(v.xMm + v.widthMm).toBeLessThanOrEqual(size.w);
expect(v.yMm + v.heightMm).toBeLessThanOrEqual(size.h);
expect(v.scaleDenominator).toBe(plan.scale);
for (const w of lay.viewports.slice(i + 1)) expect(overlaps(v, w)).toBe(false);
const snap = p.viewSnapshots!.find((s) => s.id === v.snapshotId)!;
expect(snap.templateId).toBe(PRESENTATION_TEMPLATE_ID);
expect(snap.templateLinked).toBe(true);
}
// Titel je Viewport + Nordpfeil + Massstabsbalken (2 Beschriftungen) auf der Blatt-Ebene.
const sheet = p.drawingLevels.find((l) => l.layoutId === layoutId)!;
const onSheet = p.drawings2d.filter((d) => d.levelId === sheet.id);
const texts = onSheet.filter((d) => d.geom.shape === "text");
expect(texts.length).toBe(lay.viewports.length + 1 + 2);
expect(onSheet.filter((d) => /-s\d$/.test(d.id) && d.geom.shape === "polyline").length).toBe(5);
// Titel und Balken liegen auf dem Blatt.
for (const d of onSheet) if (d.geom.shape === "text") {
expect(d.geom.at.x * 1000).toBeGreaterThan(0);
expect(d.geom.at.x * 1000).toBeLessThan(size.w);
expect(-d.geom.at.y * 1000).toBeLessThan(size.h);
}
// Skizze aus: Ebenen unverändert; Ansichten mit Schatten (Vorlage).
expect(p.drawingLevels.some((l) => l.sketch)).toBe(false);
expect(p.drawingLevels.filter((l) => l.kind === "elevation").every((l) => l.shadows)).toBe(true);
st().undo();
expect((st().project.layouts ?? []).length).toBe(layoutsBefore);
expect(st().project.viewSnapshots?.some((s) => s.id.startsWith("vs-pres-"))).toBe(false);
});
it("gewählte Geschosse, ohne Ansichten/Schnitt, Skizze an, A3: kleinerer Massstab", () => {
const floors = project.drawingLevels.filter((l) => l.kind === "floor" && !l.layoutId).slice(0, 2).map((l) => l.id);
const res = presentationSheetOps(project, { floors, elevations: false, sectionId: null, paper: "a3", orientation: "landscape", sketch: true }, LABELS, "t2")!;
expect(res.plan.items.map((i) => i.levelId)).toEqual(floors);
expect(res.plan.scale).toBeGreaterThanOrEqual(100);
st().applyChange(res.ops);
const p = st().project;
expect(p.layouts!.find((l) => l.id === res.layoutId)!.viewports.length).toBe(2);
expect(floors.every((id) => p.drawingLevels.find((l) => l.id === id)!.sketch)).toBe(true);
});
it("nichts gewählt ⇒ null, Projekt unverändert", () => {
expect(presentationSheetOps(project, { floors: [], elevations: false, sectionId: null, paper: "a1", orientation: "landscape", sketch: false }, LABELS, "t3")).toBeNull();
});
});
+316
View File
@@ -0,0 +1,316 @@
// [66] Präsentationsplan mit einem Klick: neues Blatt mit den Grundrissen (alle oder gewählte Geschosse),
// den Ansichten und optional einem Schnitt, in gemeinsamem Massstab im Raster angeordnet, mit Titeln,
// Nordpfeil und Schriftfeld (Master), Ausschnitte an die Standard-Vorlage „Präsentation" gebunden.
// Massstabswahl und Anordnung rechnet der Kern (`presentation_sheet.rs`, Abfrage `presentationSheet`);
// hier entstehen daraus die Ops (ein Undo-Schritt beim Aufrufer).
import type {
DetailLevel,
Drawing2D,
Drawing2DGeom,
DrawingLevel,
LayerCategory,
Layout,
LayoutOrientation,
LayoutPaperFormat,
LayoutViewport,
MasterLayout,
Project,
ViewSnapshot,
ViewTemplate,
} from "../model/types";
import type { CoreOp } from "../core/ops";
import { documentFor } from "../core/document";
import { addedItems, addItems, patchItem } from "../core/opsBuild";
import { standardsMergeOps } from "../model/standards";
import { createLayout, createMasterLayout, createSheetLevel, sheetMmToModel, sheetSizeMm } from "../model/layoutModel";
/** Id der Standard-Ansichtsvorlage „Präsentation" (`standards.rs`). */
export const PRESENTATION_TEMPLATE_ID = "std-vt-praesentation";
/** Rand zwischen Inhalt und Rahmen (mm, wie `FRAME_PAD_MM` im Kern). */
const FRAME_PAD_MM = 4;
export interface PresentationOptions {
/** Geschosse (Ebenen der Art `floor`) in Blattreihenfolge. */
floors: string[];
/** Alle Ansichten (Ebenen der Art `elevation`) aufnehmen. */
elevations: boolean;
/** Ein Schnitt (Ebene der Art `section`) oder keiner. */
sectionId: string | null;
paper: LayoutPaperFormat;
orientation: LayoutOrientation;
/** Skizzenstil ([67]) für die gezeigten Ebenen. */
sketch: boolean;
}
export interface PresentationItem {
levelId: string;
group: number;
xMm: number;
yMm: number;
widthMm: number;
heightMm: number;
}
export interface PresentationPlan {
scale: number;
fits: boolean;
items: PresentationItem[];
skipped: string[];
}
/** Beschriftungen (vom Aufrufer über `t()`). */
export interface PresentationLabels {
sheetName: string;
/** Name eines neu angelegten Masters, z. B. „Planrahmen A1 quer". */
masterName: string;
north: string;
}
const isFloor = (l: DrawingLevel) => l.kind === "floor" && !l.layoutId;
/** Vorschlag für den Dialog: alle Geschosse, Ansichten, erster Schnitt; Blatt des meistgenutzten Masters, sonst A1 quer. */
export function presentationDefaults(project: Project): PresentationOptions {
const levels = project.drawingLevels;
const masters = project.masterLayouts ?? [];
const uses = new Map<string, number>();
for (const l of project.layouts ?? []) if (l.masterId) uses.set(l.masterId, (uses.get(l.masterId) ?? 0) + 1);
const master = [...masters].sort((a, b) => (uses.get(b.id) ?? 0) - (uses.get(a.id) ?? 0))[0];
const usable = master && !master.customWidthMm;
return {
floors: levels.filter(isFloor).map((l) => l.id),
elevations: levels.some((l) => l.kind === "elevation"),
sectionId: levels.find((l) => l.kind === "section")?.id ?? null,
paper: usable ? master.paper : "a1",
orientation: usable ? master.orientation : "landscape",
sketch: false,
};
}
/** Die Vorlage „Präsentation" des Projekts bzw. aus den Standards (dann muss sie mit angelegt werden). */
export function presentationTemplate(project: Project): { template: ViewTemplate; isNew: boolean } {
const own = (project.viewTemplates ?? []).find((t) => t.id === PRESENTATION_TEMPLATE_ID);
if (own) return { template: own, isNew: false };
const std = (addedItems(standardsMergeOps(project), "viewTemplates") as ViewTemplate[]).find((t) => t.id === PRESENTATION_TEMPLATE_ID);
return {
template: std ?? { id: PRESENTATION_TEMPLATE_ID, name: "Präsentation", detail: "mittel", mono: false, shadows: true, hiddenLines: false },
isNew: true,
};
}
function categoryCodes(cats: readonly LayerCategory[], out: string[] = []): string[] {
for (const c of cats) {
out.push(c.code);
if (c.children) categoryCodes(c.children, out);
}
return out;
}
/**
* Sichtbarkeit nach Vorlage (alle Kategorien sichtbar, ausser die von der Vorlage ausgeblendeten), dazu ohne
* Umgebung (Kataster, Strassen, Baurecht, Gelände, Höhenlinien — dafür gibt es den Situationsplan): sonst
* bestimmen Parzelle und Geländemodell Grösse und Massstab jeder Zeichnung.
*/
function presentationVisibility(project: Project, t: ViewTemplate): Record<string, boolean> {
const vis: Record<string, boolean> = {};
for (const c of categoryCodes(project.layers)) vis[c] = true;
const out: Record<string, boolean> = { ...vis, ...(t.layerVisibility ?? {}) };
for (const c of siteCodes(project)) out[c] = false;
return out;
}
/** Vermessung und Umgebung im Standard-Ebenenbaum (`01`, `05` mit Unterkategorien Situation/Strasse/Bäume …). */
const SITE_ROOTS = ["01", "05"];
/** Codes der Umgebung: Vermessung/Umgebung samt Unterkategorien und die Kategorien der Kontext-Objekte (Gelände …). */
function siteCodes(project: Project): Set<string> {
const out = new Set<string>();
const walk = (cs: readonly LayerCategory[], inSite: boolean) => {
for (const c of cs) {
const site = inSite || SITE_ROOTS.includes(c.code);
if (site) out.add(c.code);
if (c.children) walk(c.children, site);
}
};
walk(project.layers, false);
for (const c of project.context ?? []) if (c.categoryCode) out.add(c.categoryCode);
return out;
}
/** Die gewählten Ebenen in Blattreihenfolge mit Gruppe (0 Grundrisse, 1 Ansichten, 2 Schnitt). */
function chosenLevels(project: Project, o: PresentationOptions): { id: string; group: number }[] {
const byId = new Map(project.drawingLevels.map((l) => [l.id, l]));
const out: { id: string; group: number }[] = [];
for (const id of o.floors) if (byId.get(id) && isFloor(byId.get(id)!)) out.push({ id, group: 0 });
if (o.elevations) for (const l of project.drawingLevels) if (l.kind === "elevation") out.push({ id: l.id, group: 1 });
if (o.sectionId && byId.get(o.sectionId)?.kind === "section") out.push({ id: o.sectionId, group: 2 });
return out;
}
/** Master des Blatts: einer mit gleichem Format und gleicher Ausrichtung, sonst ein neuer. */
function masterFor(project: Project, o: PresentationOptions): MasterLayout | undefined {
return (project.masterLayouts ?? []).find(
(m) => m.paper === o.paper && m.orientation === o.orientation && m.customWidthMm === undefined,
);
}
/** Massstab und Rahmen aus dem Kern (ohne das Projekt zu ändern). */
export function planPresentationSheet(project: Project, o: PresentationOptions): PresentationPlan {
const { template } = presentationTemplate(project);
const size = sheetSizeMm(o.paper, o.orientation);
const levels = chosenLevels(project, o);
const vis = presentationVisibility(project, template);
const text = JSON.stringify({
levels: levels.map((l) => l.id),
groups: levels.map((l) => l.group),
layerVisibility: vis,
detail: (template.detail ?? "mittel") satisfies DetailLevel,
sheetW: size.w,
sheetH: size.h,
titleBlock: true,
shadows: template.shadows ?? false,
});
return documentFor(project).query<PresentationPlan>("presentationSheet", [], text);
}
/** Text auf der Blatt-Ebene (Papier-mm, Schrifthöhe mm). */
function sheetText(id: string, levelId: string, cat: string, xMm: number, yMm: number, text: string, hMm: number, bold = false): Drawing2D {
return {
id,
type: "drawing2d",
levelId,
categoryCode: cat,
geom: { shape: "text", at: sheetMmToModel(xMm, yMm), text, height: hMm / 1000, angle: 0, ...(bold ? { marks: { bold: true } } : {}) },
color: "#111111",
} as Drawing2D;
}
function sheetShape(id: string, levelId: string, cat: string, geom: Drawing2DGeom, extra: Partial<Drawing2D> = {}): Drawing2D {
return { id, type: "drawing2d", levelId, categoryCode: cat, geom, color: "#111111", weightMm: 0.25, ...extra } as Drawing2D;
}
/** Nordpfeil (Norden = +y im Modell, Grundrisse sind nicht gedreht): Kreis, halb gefüllte Spitze, „N". */
function northArrow(stamp: string, levelId: string, cat: string, cx: number, cy: number, r: number, north: string): Drawing2D[] {
const P = (x: number, y: number) => sheetMmToModel(cx + x, cy + y);
return [
sheetShape(`d-pres-${stamp}-n0`, levelId, cat, { shape: "circle", center: P(0, 0), r: r / 1000 }),
sheetShape(`d-pres-${stamp}-n1`, levelId, cat, { shape: "polyline", closed: true, pts: [P(0, -r), P(r * 0.45, r * 0.75), P(0, r * 0.35)] }, { fillColor: "#111111" }),
sheetShape(`d-pres-${stamp}-n2`, levelId, cat, { shape: "polyline", closed: true, pts: [P(0, -r), P(0, r * 0.35), P(-r * 0.45, r * 0.75)] }),
sheetText(`d-pres-${stamp}-n3`, levelId, cat, cx - r - 4, cy + 1.4, north, r * 0.8, true),
];
}
/** Massstabsbalken-Längen (Modell-Meter), kleinste zuerst. */
const SCALEBAR_TOTALS = [1, 2, 5, 10, 20, 50, 100, 200];
/**
* Massstabsbalken auf der Blatt-Ebene (Papier-mm): fünf abwechselnd gefüllte Felder, rechtes Ende bei `rightMm`,
* Mitte bei `cyMm`; Gesamtlänge die grösste runde Länge bis 50 mm auf dem Papier. Ein Massstabsbalken-Element
* (`shape: "scalebar"`) passt nicht, weil die Blatt-Ebene 1:1 in Papier-mm rechnet.
*/
export function scaleBar(stamp: string, levelId: string, cat: string, rightMm: number, cyMm: number, scale: number): Drawing2D[] {
const total = [...SCALEBAR_TOTALS].reverse().find((m) => (m * 1000) / scale <= 50) ?? SCALEBAR_TOTALS[0];
const len = (total * 1000) / scale;
const n = 5;
const h = 1.6;
const x0 = rightMm - len;
const out: Drawing2D[] = [];
for (let i = 0; i < n; i++) {
const a = x0 + (len * i) / n;
const b = x0 + (len * (i + 1)) / n;
const pts = [sheetMmToModel(a, cyMm - h / 2), sheetMmToModel(b, cyMm - h / 2), sheetMmToModel(b, cyMm + h / 2), sheetMmToModel(a, cyMm + h / 2)];
out.push(sheetShape(`d-pres-${stamp}-s${i}`, levelId, cat, { shape: "polyline", closed: true, pts }, { weightMm: 0.18, ...(i % 2 === 0 ? { fillColor: "#111111" } : {}) }));
}
out.push(sheetText(`d-pres-${stamp}-s${n}`, levelId, cat, x0 - 0.6, cyMm + h / 2 + 2.6, "0", 2));
const label = `${total} m`;
out.push(sheetText(`d-pres-${stamp}-s${n + 1}`, levelId, cat, rightMm - label.length * 1.2, cyMm + h / 2 + 2.6, label, 2));
return out;
}
/** Kategorie für Titel und Nordpfeil: „Text"/„Beschriftung", sonst die erste. */
function annotationCategory(project: Project): string {
const all: LayerCategory[] = [];
const walk = (cs: readonly LayerCategory[]) => cs.forEach((c) => (all.push(c), c.children && walk(c.children)));
walk(project.layers);
return (all.find((c) => /beschrift|text|annot/i.test(c.name)) ?? all.find((c) => c.code === "80") ?? all[0])?.code ?? "0";
}
/**
* Ops für das Präsentationsblatt (ein Undo-Schritt, wenn sie zusammen angewendet werden): Layout mit
* Blatt-Ebene und Master (neu, falls keiner zum Format passt), je Ebene ein an „Präsentation" gebundener
* Ausschnitt und ein Viewport, Titel und Nordpfeil auf der Blatt-Ebene, Schatten/Skizze an den Ebenen.
* `stamp` macht die Ids eindeutig. Keine Ebene mit Inhalt ⇒ `null`.
*/
export function presentationSheetOps(
project: Project,
o: PresentationOptions,
labels: PresentationLabels,
stamp: string,
): { ops: CoreOp[]; layoutId: string; plan: PresentationPlan } | null {
const plan = planPresentationSheet(project, o);
if (plan.items.length === 0) return null;
const { template, isNew } = presentationTemplate(project);
const ops: CoreOp[] = [];
if (isNew) ops.push(...addItems("viewTemplates", [template]));
let master = masterFor(project, o);
if (!master) {
const first = (project.masterLayouts ?? [])[0];
master = { ...createMasterLayout(`mas-pres-${stamp}`, labels.masterName, o.paper, o.orientation), titleBlock: { ...(first?.titleBlock ?? {}) } };
ops.push(...addItems("masterLayouts", [master]));
}
const layoutId = `lay-pres-${stamp}`;
const layout: Layout = { ...createLayout(layoutId, labels.sheetName, o.paper, o.orientation), masterId: master.id };
const sheetLevel = createSheetLevel(`sheet-${layoutId}`, layout);
const vis = presentationVisibility(project, template);
const cat = annotationCategory(project);
const byId = new Map(project.drawingLevels.map((l) => [l.id, l]));
const snaps: ViewSnapshot[] = [];
const vps: LayoutViewport[] = [];
const drawings: Drawing2D[] = [];
plan.items.forEach((it, i) => {
const level = byId.get(it.levelId)!;
const snapId = `vs-pres-${stamp}-${i}`;
snaps.push({
id: snapId,
name: `${level.name} · ${template.name}`,
viewType: "grundriss",
view3d: "top",
scaleDenominator: plan.scale,
detail: template.detail ?? "mittel",
activeLevelId: level.id,
layerVisibility: vis,
drawingVisibility: {},
...(template.enabledOverrideRuleIds ? { enabledOverrideRuleIds: [...template.enabledOverrideRuleIds] } : {}),
templateId: template.id,
templateLinked: true,
} as ViewSnapshot);
vps.push({ id: `vp-pres-${stamp}-${i}`, snapshotId: snapId, xMm: it.xMm, yMm: it.yMm, widthMm: it.widthMm, heightMm: it.heightMm, scaleDenominator: plan.scale });
drawings.push(
sheetText(`d-pres-${stamp}-t${i}`, sheetLevel.id, cat, it.xMm + FRAME_PAD_MM, it.yMm + it.heightMm + 6, `${level.name} 1:${plan.scale}`, 4, true),
);
});
// Nordpfeil rechts neben dem Titel des ersten Grundrisses.
const firstFloor = plan.items.find((it) => it.group === 0);
if (firstFloor) {
const cx = firstFloor.xMm + firstFloor.widthMm - 8;
const cy = firstFloor.yMm + firstFloor.heightMm + 4.8;
drawings.push(...northArrow(stamp, sheetLevel.id, cat, cx, cy, 3.6, labels.north));
// Massstabsbalken links vom Nordpfeil, sofern er den Titel nicht berührt (Breite grob 0.65 × Schrifthöhe je Zeichen).
const bar = scaleBar(stamp, sheetLevel.id, cat, cx - 3.6 - 10, cy - 1, plan.scale);
const title = byId.get(firstFloor.levelId)!.name;
const titleEnd = firstFloor.xMm + FRAME_PAD_MM + (title.length + 8) * 4 * 0.65;
const barLeft = Math.min(...bar.flatMap((d) => (d.geom.shape === "polyline" ? d.geom.pts.map((p) => p.x * 1000) : [])));
if (barLeft - 6 > titleEnd) drawings.push(...bar);
}
ops.push(...addItems("layouts", [{ ...layout, viewports: vps }]), ...addItems("drawingLevels", [sheetLevel]));
ops.push(...addItems("viewSnapshots", snaps), ...addItems("drawings2d", drawings));
// Schatten (Vorlage) für Ansichten/Schnitt, Skizze nach Wahl für alle gezeigten Ebenen.
for (const it of plan.items) {
const level = byId.get(it.levelId)!;
const patch: Partial<DrawingLevel> = {};
if (it.group > 0 && template.shadows !== undefined && level.shadows !== template.shadows) patch.shadows = template.shadows;
if (o.sketch && !level.sketch) patch.sketch = true;
if (Object.keys(patch).length > 0) ops.push(...patchItem(project, "drawingLevels", level.id, patch));
}
return { ops, layoutId, plan };
}
+30
View File
@@ -0,0 +1,30 @@
// [66] Präsentationsplan anlegen: Ops aus dem Kern-Fassadenteil (`plan/presentationSheet.ts`), angewendet
// als EIN Undo-Schritt, Meldung über `notify`. Liefert die Id des neuen Blatts (zum Öffnen) oder `null`.
import { presentationSheetOps, type PresentationOptions } from "../core";
import { t } from "../i18n";
import { getState } from "./appStore";
export function createPresentationSheet(o: PresentationOptions): string | null {
const st = getState();
try {
const format = `${o.paper.toUpperCase()} ${o.orientation === "landscape" ? t("layouts.landscape") : t("layouts.portrait")}`;
const res = presentationSheetOps(
st.project,
o,
{ sheetName: t("presentation.sheetName"), masterName: t("presentation.masterName", { format }), north: t("presentation.north") },
String(Date.now()),
);
if (!res) {
st.notify(t("presentation.empty"), "warning");
return null;
}
st.applyChange(res.ops);
if (res.plan.fits) st.notify(t("presentation.done", { scale: res.plan.scale, n: res.plan.items.length }), "info");
else st.notify(t("presentation.tooBig", { scale: res.plan.scale }), "warning");
return res.layoutId;
} catch (e) {
st.notify(`${t("presentation.failed")}: ${e instanceof Error ? e.message : String(e)}`, "error");
return null;
}
}
+14
View File
@@ -0,0 +1,14 @@
// [66] Modul-Hook: App registriert den Öffner des Präsentationsplan-Dialogs; Befehl `praesentation` und
// der Knopf im Layouts-Panel rufen ihn auf, ohne an React/App gekoppelt zu sein (Muster `io/dxfImportHook`).
let opener: (() => void) | null = null;
/** App registriert hier den Öffner (oder hebt ihn beim Unmount auf). */
export function setPresentationDialogOpener(fn: (() => void) | null): void {
opener = fn;
}
/** Öffnet den Dialog „Präsentationsplan", falls App ihn registriert hat. */
export function openPresentationDialog(): void {
opener?.();
}
+165
View File
@@ -0,0 +1,165 @@
// [66] Dialog „Präsentationsplan": Geschosse, Ansichten/Schnitt, Blattformat, Skizzenstil. Registriert sich
// selbst als Öffner (`state/presentationSheetHook`), damit Befehl `praesentation` und der Knopf im
// Layouts-Panel ihn öffnen. Beim Bestätigen entsteht das Blatt in EINEM Undo-Schritt
// (`state/presentationSheet.ts`); `onCreated` öffnet es. Overlay wie `LayoutCreateDialogs` (kein window.prompt).
import { useCallback, useEffect, useState } from "react";
import { t } from "../i18n";
import { presentationDefaults, type PresentationOptions } from "../core";
import type { LayoutOrientation, LayoutPaperFormat } from "../model/types";
import { PAPER_FORMAT_GROUPS } from "../model/layoutModel";
import { getState, useStore } from "../state/appStore";
import { setPresentationDialogOpener } from "../state/presentationSheetHook";
import { createPresentationSheet } from "../state/presentationSheet";
export function PresentationDialogHost({ onCreated }: { onCreated: (layoutId: string) => void }) {
const [opts, setOpts] = useState<PresentationOptions | null>(null);
const project = useStore((s) => s.project);
useEffect(() => {
setPresentationDialogOpener(() => setOpts(presentationDefaults(getState().project)));
return () => setPresentationDialogOpener(null);
}, []);
const close = useCallback(() => setOpts(null), []);
const confirm = useCallback(() => {
if (!opts) return;
const id = createPresentationSheet(opts);
setOpts(null);
if (id) onCreated(id);
}, [opts, onCreated]);
useEffect(() => {
if (!opts) return;
const onKey = (e: KeyboardEvent) => {
// Enter aus der Befehlszeile (die den Dialog eben geöffnet hat) bestätigt nicht.
if (e.target instanceof Element && e.target.closest("input, textarea") && !e.target.closest(".presentation-dialog")) return;
if (e.key === "Escape") close();
else if (e.key === "Enter") confirm();
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [opts, close, confirm]);
if (!opts) return null;
const floors = project.drawingLevels.filter((l) => l.kind === "floor" && !l.layoutId);
const sections = project.drawingLevels.filter((l) => l.kind === "section");
const hasElevations = project.drawingLevels.some((l) => l.kind === "elevation");
const set = (patch: Partial<PresentationOptions>) => setOpts({ ...opts, ...patch });
const toggleFloor = (id: string, on: boolean) =>
// Blattreihenfolge = Reihenfolge der Geschosse im Projekt.
set({ floors: floors.map((f) => f.id).filter((f) => (f === id ? on : opts.floors.includes(f))) });
const empty = opts.floors.length === 0 && !(opts.elevations && hasElevations) && !opts.sectionId;
return (
<div className="imp-overlay" onClick={close}>
<div
className="imp-dialog presentation-dialog"
role="dialog"
aria-modal="true"
aria-label={t("presentation.title")}
onClick={(e) => e.stopPropagation()}
>
<header className="imp-head">
<span className="imp-head-title">{t("presentation.title")}</span>
<button className="imp-close" onClick={close} aria-label={t("export.close")}>
×
</button>
</header>
<div className="imp-body">
<section className="imp-section">
<div className="imp-section-title">{t("presentation.floors")}</div>
{floors.map((f) => (
<label key={f.id} className="imp-check" style={{ display: "flex", gap: 6, alignItems: "center" }}>
<input
type="checkbox"
data-floor={f.id}
checked={opts.floors.includes(f.id)}
onChange={(e) => toggleFloor(f.id, e.target.checked)}
/>
{f.name}
</label>
))}
</section>
<section className="imp-section">
<label className="imp-check" style={{ display: "flex", gap: 6, alignItems: "center" }}>
<input
type="checkbox"
data-testid="presentation-elevations"
disabled={!hasElevations}
checked={opts.elevations && hasElevations}
onChange={(e) => set({ elevations: e.target.checked })}
/>
{t("presentation.elevations")}
</label>
</section>
<section className="imp-section">
<div className="imp-section-title">{t("presentation.section")}</div>
<select
className="imp-select"
data-testid="presentation-section"
value={opts.sectionId ?? ""}
onChange={(e) => set({ sectionId: e.target.value || null })}
>
<option value="">{t("presentation.noSection")}</option>
{sections.map((s) => (
<option key={s.id} value={s.id}>
{s.name}
</option>
))}
</select>
</section>
<section className="imp-section">
<div className="imp-section-title">{t("presentation.sheet")}</div>
<div style={{ display: "flex", gap: 8, alignItems: "center" }}>
<select
className="imp-select"
data-testid="presentation-paper"
value={opts.paper}
onChange={(e) => set({ paper: e.target.value as LayoutPaperFormat })}
>
{PAPER_FORMAT_GROUPS.flatMap((g) => g.formats).map((f) => (
<option key={f} value={f}>
{f.toUpperCase()}
</option>
))}
</select>
<div className="imp-seg">
{(["portrait", "landscape"] as LayoutOrientation[]).map((o) => (
<button
key={o}
type="button"
className={`imp-seg-btn${opts.orientation === o ? " active" : ""}`}
onClick={() => set({ orientation: o })}
>
{o === "portrait" ? t("layouts.portrait") : t("layouts.landscape")}
</button>
))}
</div>
</div>
</section>
<section className="imp-section">
<label className="imp-check" style={{ display: "flex", gap: 6, alignItems: "center" }}>
<input
type="checkbox"
data-testid="presentation-sketch"
checked={opts.sketch}
onChange={(e) => set({ sketch: e.target.checked })}
/>
{t("presentation.sketch")}
</label>
</section>
<p style={{ fontSize: 11, color: "var(--muted)", margin: "4px 0 0" }}>{t("presentation.hint")}</p>
</div>
<footer className="imp-foot">
<button className="imp-btn" onClick={close}>
{t("export.cancel")}
</button>
<button className="imp-btn primary" data-testid="presentation-create" disabled={empty} onClick={confirm}>
{t("presentation.create")}
</button>
</footer>
</div>
</div>
);
}