diff --git a/TODO.md b/TODO.md index 99f2c3e7..48703e2a 100644 --- a/TODO.md +++ b/TODO.md @@ -1456,7 +1456,17 @@ Reihenfolge = Abhängigkeiten. Neue Geometrie entsteht in Rust ([K]). - ○ **[77] Zauberstab.** · M - ✅ **[78] Autotext im Plankopf.** Titelblock löst Projekt/Blatt/Massstab/Datum auf; Plannummer laufend oder `Layout.planNumber` (27.10.). -- ○ **[79] Publikationssätze.** · M +- ◐ **[79] Publikationssätze.** (30.10.) Modell (Rust, optional): `Project.publishSets` (`PublishSet`: Layouts in Reihenfolge, + optional gespeicherte Ansichten, Ausgabe pdf-multi / pdf-single / dxf / dwg mit Layouts, Dateinamen-Muster + `{Projektnummer} {Projekt} {Blattnummer} {Blattname} {Index} {Datum} {Satz}`, Papier-/Massstab-Übersteuerung, Index ausgeben, + Index beim Publizieren erhöhen, PDF-Ebenen), `Project.publishLog` (Datum, Blätter mit Nummer/Index, Dateien), + `Project.projectNumber`, `Layout.revision` (Index; steht im Titelblock auf Bildschirm und PDF). Logik `export/publishSet.ts` + (Index A→B→…→AA, 2→3; Plan, Ops), Ausführung `export/publishRun.ts` (PDF über `layoutPdf.buildPagesPdf`, DXF/DWG über den + Papierbereich-Export; mehrere Dateien als ZIP), Hülle `state/publishActions.ts`, UI-Abschnitt „Publikation“ im Mappe-Reiter + (`panels/PublishSection.tsx`: Sätze, Einstellungen, ein Klick, Protokoll). Publizieren = ein Undo-Schritt (Index + Protokoll). + Offen: Reihenfolge der Blätter im Satz per Ziehen (heute Projekt-Reihenfolge beim Anhaken), DXF/DWG enthält die Papierbereiche + der Satz-Blätter, aber Papier-/Massstab-Übersteuerung wirkt dort nur als Export-Massstab, Satz je Ordner, Protokoll als Export. + Nicht in der Tauri-App getestet (Browser-Download-Pfad geprüft). - ✅ **[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, @@ -1561,11 +1571,24 @@ Reihenfolge = Abhängigkeiten. Neue Geometrie entsteht in Rust ([K]). `dashScale`); SVG-Rückfall: Linientypen in Papier-mm im Plot-Massstab, unter `non-scaling-stroke` über die meet-Variable `--plan-dash-k` (`dashArrayCss`). Test: Modell-Periode bei zwei Zoomstufen gleich und = Druck-SVG. Offen: Bildschirm (WebGPU/macOS) nicht angesehen; CPU-Rückfall (> 8 Einträge) verliert Punkte. · S -- ○ **[80] PDF mit Ebenen.** · M +- ✅ **[80] PDF mit Ebenen.** (30.10.) jsPDF kennt keine optionalen Inhalte → `export/pdfLayers.ts` schreibt Optional Content + selbst (OCG je Ebenenname, `/OC … BDC … EMC` im Seitenstrom, `/Properties`, `/OCProperties` im Katalog; gleiche Namen auf + mehreren Seiten = eine in Acrobat schaltbare Ebene). Layout-PDF (`buildPagesPdf`, Ordner-PDF und Publikationssätze) legt je Viewport + und Wurzel-Kategorie (Name aus dem Kategorie-Baum, sichtbare Codes samt Unterkategorien) eine Ebene an, dazu „Rahmen und + Titelblock“, „Blatt-Zeichnung“, „Legende“. Geprüft mit pypdf (OCProperties, Namen); Ordner-PDF bleibt ohne Ebenen. + Offen: Elemente ohne Kategorie-Bezug (Massstabsleiste, Ebenen-Marken) erscheinen in jeder Kategorie-Ebene des Viewports; + Einzel-Plan-PDF (`exportPdf.ts`) noch ohne Ebenen. - ◐ **[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. (30.10.) Ketten assoziativ [38] (Ecken/Leibungen, nur mittige Wände). -- ○ **[82] Grafische Legenden.** · M +- ✅ **[82] Grafische Legenden.** (30.10.) `Layout.legends` (`LayoutLegend`: Lage, Titel, Arten Schraffur/Material · Linientyp · + Kategorie, optional Handauswahl `manualKeys`). `analysis/legend.ts`: Einträge automatisch aus den Viewports (Material der + Wand-/Decken-/Dach-Aufbauten und Stützen im gezeigten Geschoss, Schraffuren/Linientypen der Zeichnungen, sichtbare + Kategorien) und die Legende als gewöhnliche 2D-Elemente der Blatt-Ebene — Muster, Linien und Schrift erzeugt derselbe Kern wie + im Plan (`export/legendSvg.ts`: Hilfsprojekt → `generatePlan` → `planToPrintSvg`); Bildschirm (`LayoutSheet`, folgt dem Projekt + live) und PDF teilen den Weg; im DXF/DWG-Papierbereich eines Publikationssatzes als Blatt-Zeichnung (Weg gebaut, aber nicht mit echter Datei geprüft). Bedienung: „+ Legende“ in + der Blatt-Leiste, Klick wählt sie, HUD: Titel, X/Y, Arten, „Auswahl festhalten“ / automatisch. + Offen: Verschieben per Ziehen (heute X/Y-Felder), DXF-Legende nur im Satz-Export (nicht im allgemeinen DXF-Dialog). - ○ **[65] Explosionsaxonometrie.** · S–M - ○ **[66] Präsentationspläne mit einem Klick.** · M - ○ **[67] Skizzenstil.** · M diff --git a/e2e/publish.spec.ts b/e2e/publish.spec.ts new file mode 100644 index 00000000..17f09a27 --- /dev/null +++ b/e2e/publish.spec.ts @@ -0,0 +1,90 @@ +// Publikationssätze [79], PDF-Ebenen [80], Legenden [82]: ein Projekt mit Blatt (Viewport + Legende) und +// einem Publikationssatz wird geladen; „Publizieren" liefert das PDF (mit Ebenen), erhöht den Index und +// schreibt das Protokoll; das Blatt zeigt die Legende. Ergebnisse als PNG/PDF in test-results/ zum Ansehen. +import { mkdir, readFile, writeFile } from "node:fs/promises"; +import type { Page } from "@playwright/test"; +import { discardIfAsked, expect, fileMenu, openTab, startNewProject, test } from "./app"; +import { BEISPIEL_OBP } from "./paths"; + +interface Cat { + code: string; + children?: Cat[]; +} +const codesOf = (cs: Cat[]): string[] => cs.flatMap((c) => [c.code, ...codesOf(c.children ?? [])]); + +async function projectWithSheet(): Promise { + const j = JSON.parse(await readFile(BEISPIEL_OBP, "utf8")); + const level = j.drawingLevels.find((l: { kind: string }) => l.kind === "floor"); + j.viewSnapshots = [ + { + id: "s1", + name: "EG 1:100", + viewType: "plan", + scaleDenominator: 100, + detail: "fein", + activeLevelId: level.id, + layerVisibility: Object.fromEntries(codesOf(j.layers).map((c) => [c, true])), + drawingVisibility: {}, + }, + ]; + j.masterLayouts = [{ id: "m1", name: "A3", paper: "a3", orientation: "landscape", titleBlock: { author: "KG" }, border: true }]; + j.layouts = [ + { + id: "l1", + name: "Grundriss EG", + paper: "a3", + orientation: "landscape", + masterId: "m1", + planNumber: "101", + revision: "A", + viewports: [{ id: "v1", snapshotId: "s1", xMm: 15, yMm: 15, widthMm: 270, heightMm: 250 }], + legends: [{ id: "g1", xMm: 295, yMm: 15 }], + }, + ]; + j.drawingLevels.push({ id: "sheet-l1", name: "Grundriss EG", kind: "drawing", visible: true, locked: false, layoutId: "l1" }); + j.projectNumber = "2026-14"; + j.publishSets = [{ id: "p1", name: "Baueingabe", layoutIds: ["l1"], bumpRevision: true, pdfLayers: true }]; + return Buffer.from(JSON.stringify(j)); +} + +async function load(page: Page): Promise { + await startNewProject(page); + const chooser = page.waitForEvent("filechooser"); + await fileMenu(page, "Projekt öffnen"); + await (await chooser).setFiles({ name: "publikation.obp", mimeType: "application/json", buffer: await projectWithSheet() }); + await discardIfAsked(page); + await expect(page.locator(".project-name")).toBeVisible(); + await openTab(page, "Mappe"); +} + +test("Blatt zeigt die Legende der Viewports", async ({ page }) => { + await load(page); + await page.locator(".nav-row", { hasText: "Grundriss EG" }).first().dblclick(); + await expect(page.locator(".layout-sheet-pane")).toBeVisible(); + const legend = page.locator("[data-legend-id=g1] svg"); + await expect(legend).toHaveCount(1, { timeout: 8000 }); + await expect(legend.locator("text").first()).toHaveText("Legende"); + // Mindestens ein Material mit Namen in der Legende. + await expect.poll(async () => legend.locator("text").count()).toBeGreaterThan(2); + await mkdir("test-results", { recursive: true }); + await page.screenshot({ path: "test-results/legend-sheet.png" }); +}); + +test("Satz publizieren: PDF mit Ebenen, Index erhöht, Protokoll", async ({ page }) => { + await load(page); + await expect(page.locator("[data-publish-set=p1]")).toBeVisible(); + const pending = page.waitForEvent("download"); + await page.locator("[data-publish-set=p1] [data-publish-run]").click(); + const dl = await pending; + expect(dl.suggestedFilename()).toBe("Baueingabe.pdf"); + const bytes = await readFile(await dl.path()); + expect(bytes.subarray(0, 5).toString("latin1")).toBe("%PDF-"); + const text = bytes.toString("latin1"); + expect(text).toContain("/OCProperties"); + await mkdir("test-results", { recursive: true }); + await writeFile("test-results/publish-set.pdf", bytes); + // Index A → B und Protokoll. + await expect(page.locator("[data-publish-log]")).toContainText("Baueingabe"); + await expect(page.locator("[data-publish-log]")).toContainText("Index B"); + await page.screenshot({ path: "test-results/publish-panel.png" }); +}); diff --git a/src-tauri/core/src/model/generated.rs b/src-tauri/core/src/model/generated.rs index 4fecc60b..5abbb8fa 100644 --- a/src-tauri/core/src/model/generated.rs +++ b/src-tauri/core/src/model/generated.rs @@ -4218,6 +4218,15 @@ pub struct Layout { /// 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, + /// Revisionsindex des Blatts (z. B. "A", "B" oder "2"); steht im Titelblock, wird beim + /// Publizieren eines Satzes optional hochgezählt ([79]). + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub revision: Option, + /// Grafische Legenden auf dem Blatt ([82]). + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub legends: Option>, /// Lebendige Tabellen auf dem Blatt ([111]); fehlt = keine. #[serde(default, skip_serializing_if = "Option::is_none")] #[ts(optional)] @@ -4227,6 +4236,114 @@ pub struct Layout { pub extra: Extra, } +/// Grafische Legende auf einem Layout-Blatt ([82]): listet Schraffuren/Materialien, Linientypen und/oder +/// Kategorien der gezeigten Viewports (`manualKeys` leer) oder einer Handauswahl, mit Muster und Name. +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, TS)] +#[serde(default)] +pub struct LayoutLegend { + pub id: String, + /// Linke Kante auf dem Blatt (mm). + #[serde(rename = "xMm")] + pub x_mm: f64, + /// Obere Kante auf dem Blatt (mm). + #[serde(rename = "yMm")] + pub y_mm: f64, + /// Titel; fehlt = „Legende". + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub title: Option, + /// Gezeigte Arten: "hatch", "lineType", "category"; fehlt = nur Schraffuren. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub kinds: Option>, + /// Handauswahl als Schlüssel "hatch:", "lineType:", "category:"; leer/fehlt = automatisch + /// aus den Viewports des Blatts. + #[serde(rename = "manualKeys", default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub manual_keys: Option>, + #[serde(flatten)] + #[ts(skip)] + pub extra: Extra, +} + +/// Publikationssatz ([79]): benannte Menge von Layouts (und optional Ansichten) mit Ausgabe-Einstellungen. +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, TS)] +#[serde(default)] +pub struct PublishSet { + pub id: String, + pub name: String, + /// Layouts des Satzes in Ausgabe-Reihenfolge. + #[serde(rename = "layoutIds")] + pub layout_ids: Vec, + /// Gespeicherte Ansichten, die zusätzlich als eigene Seiten ausgegeben werden. + #[serde(rename = "snapshotIds", default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub snapshot_ids: Option>, + /// "pdf-multi" (ein PDF, Standard), "pdf-single" (je Blatt eine Datei), "dxf" (DXF mit Layouts). + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub format: Option, + /// Dateinamen-Muster mit {Projektnummer} {Projekt} {Blattnummer} {Blattname} {Index} {Datum} {Satz}. + #[serde(rename = "namePattern", default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub name_pattern: Option, + /// Papierformat-Übersteuerung für alle Blätter des Satzes. + #[serde(rename = "paperOverride", default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub paper_override: Option, + /// Massstab-Übersteuerung (1:N) für alle Viewports des Satzes. + #[serde(rename = "scaleOverride", default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub scale_override: Option, + /// Revisionsindex im Titelblock/Dateinamen ausgeben (Standard ja). + #[serde(rename = "includeRevision", default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub include_revision: Option, + /// Revisionsindex je Blatt beim Publizieren erhöhen (A→B, 1→2). + #[serde(rename = "bumpRevision", default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub bump_revision: Option, + /// PDF-Ebenen (Optional Content) je Kategorie. + #[serde(rename = "pdfLayers", default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub pdf_layers: Option, + #[serde(flatten)] + #[ts(skip)] + pub extra: Extra, +} + +/// Ein Blatt im Publikationsprotokoll. +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, TS)] +#[serde(default)] +pub struct PublishLogSheet { + #[serde(rename = "layoutId")] + pub layout_id: String, + pub number: String, + pub name: String, + pub revision: String, + #[serde(flatten)] + #[ts(skip)] + pub extra: Extra, +} + +/// Protokolleintrag einer Publikation ([79]): Datum, Blätter mit Revision, erzeugte Dateien. +#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, TS)] +#[serde(default)] +pub struct PublishLogEntry { + pub id: String, + #[serde(rename = "setId")] + pub set_id: String, + #[serde(rename = "setName")] + pub set_name: String, + /// ISO-Zeitstempel. + pub date: String, + pub sheets: Vec, + pub files: Vec, + #[serde(flatten)] + #[ts(skip)] + pub extra: Extra, +} + /// Einfache Textfelder des Titelblocks (Master). Alle optional — leere Felder /// werden beim Auflösen aus dem Projekt/Layout mit sinnvollen Defaults gefüllt /// (Projektname ← `Project.name`, Blattname ← `Layout.name`, Datum ← heute). @@ -4592,6 +4709,18 @@ pub struct Project { #[serde(rename = "layoutFolders", default, skip_serializing_if = "Option::is_none")] #[ts(optional)] pub layout_folders: Option>, + /// Publikationssätze ([79]). + #[serde(rename = "publishSets", default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub publish_sets: Option>, + /// Publikationsprotokoll ([79]), neueste zuletzt. + #[serde(rename = "publishLog", default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub publish_log: Option>, + /// Projektnummer für Titelblock und Dateinamen ([79]). + #[serde(rename = "projectNumber", default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub project_number: Option, /// Referenzhöhe des Erdgeschosses in Metern über Meer (m ü. M.), editierbar /// im Einstellungs-Fenster. Optional, damit bestehende Projekte ohne diesen /// Wert gültig bleiben (Default: unbestimmt/0). NUR Speicherfeld — die @@ -5312,6 +5441,24 @@ impl Project { None => Default::default(), }; } + "publishSets" => { + self.publish_sets = match v { + Some(v) => >>::deserialize(v).map_err(|e| e.to_string())?, + None => Default::default(), + }; + } + "publishLog" => { + self.publish_log = match v { + Some(v) => >>::deserialize(v).map_err(|e| e.to_string())?, + None => Default::default(), + }; + } + "projectNumber" => { + self.project_number = match v { + Some(v) => >::deserialize(v).map_err(|e| e.to_string())?, + None => Default::default(), + }; + } "referenceElevationMasl" => { self.reference_elevation_masl = match v { Some(v) => >::deserialize(v).map_err(|e| e.to_string())?, diff --git a/src-tauri/core/src/project_format.rs b/src-tauri/core/src/project_format.rs index 33888d59..449673d8 100644 --- a/src-tauri/core/src/project_format.rs +++ b/src-tauri/core/src/project_format.rs @@ -15,13 +15,13 @@ const REQUIRED_ARRAYS: [&str; 3] = ["walls", "layers", "drawingLevels"]; const DEFAULT_ARRAYS: [&str; 5] = ["lineStyles", "hatches", "components", "wallTypes", "drawings2d"]; /// Bekannte Felder von `Project` (für die Meldung unbekannter Felder). -const KNOWN_KEYS: [&str; 48] = [ +const KNOWN_KEYS: [&str; 51] = [ "formatVersion", "id", "name", "lineStyles", "textStyles", "hatches", "components", "wallTypes", "ceilingTypes", "roofTypes", "blockDefs", "doorTypes", "windowTypes", "stairTypes", "pens", "penSets", "activePenSetId", "customPalettes", "builtinPaletteBanks", "drawingLevels", "layers", "walls", "ceilings", "roofs", "openings", "stairs", "rooms", "drawings2d", "context", "extrudedSolids", "columns", "groups", "parametricWalls", "overrideRules", "viewSnapshots", - "viewSnapshotFolders", "viewTemplates", "layouts", "masterLayouts", "layoutFolders", "referenceElevationMasl", + "viewSnapshotFolders", "viewTemplates", "layouts", "masterLayouts", "layoutFolders", "publishSets", "publishLog", "projectNumber", "referenceElevationMasl", "geoAnchor", "roomProgram", "roomProgramTolerance", "parcelArea", "sunStudy", "siteRules", "scaleLineWeights", ]; diff --git a/src/App.tsx b/src/App.tsx index 19d05757..f9de7adc 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -16,6 +16,7 @@ // fünf DOSSIER-Modi): das Zeichnungsebenen-Panel steuert das 3D, das // Ebenen-Panel die Kategorie-Darstellung in Grundriss UND 3D. +import { addLegend, patchLegend, removeLegend } from "./analysis/legend"; import { lengthFromDisplay, unitsForLevel } from "./tools/displayUnits"; import { NON_LENGTH_FIELDS } from "./commands/parseInput"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; @@ -29,6 +30,7 @@ import type { Drawing2D, DrawingLevel, Layout, + LayoutLegend, LayoutTable, LayoutViewport, Project, @@ -2683,6 +2685,14 @@ export default function App() { patchOpenLayout(activeLayout.id, (l) => addViewportToLayout(l, createViewport(`vp-${Date.now()}`, snapshotId, init)), ), + onAddLegend: (init: Omit) => { + const id = `legend-${Date.now()}`; + patchOpenLayout(activeLayout.id, (l) => addLegend(l, { ...init, id })); + return id; + }, + onPatchLegend: (legendId: string, patch: Partial>) => + patchOpenLayout(activeLayout.id, (l) => patchLegend(l, legendId, patch), `legend-${legendId}`), + onRemoveLegend: (legendId: string) => patchOpenLayout(activeLayout.id, (l) => removeLegend(l, legendId)), }, } : null; diff --git a/src/analysis/legend.test.ts b/src/analysis/legend.test.ts new file mode 100644 index 00000000..58e53050 --- /dev/null +++ b/src/analysis/legend.test.ts @@ -0,0 +1,105 @@ +// [82] Grafische Legende: Einträge aus den Viewports (automatisch) oder der Handauswahl, Zeichnungselemente. + +import { describe, expect, it } from "vitest"; +import { sampleProject } from "../model/sampleProject"; +import type { Layout, LayoutLegend, Project, ViewSnapshot } from "../model/types"; +import { addLegend, legendBox, legendDrawings, legendEntries, legendKeysOfViewports, patchLegend, removeLegend } from "./legend"; + +function proj(): Project { + const snap = { + id: "s1", + name: "EG", + activeLevelId: "eg", + layerVisibility: Object.fromEntries(sampleProject.layers.map((c) => [c.code, true])), + } as unknown as ViewSnapshot; + const layout: Layout = { + id: "l1", + name: "Blatt", + paper: "a3", + orientation: "landscape", + viewports: [{ id: "v1", snapshotId: "s1", xMm: 10, yMm: 10, widthMm: 200, heightMm: 150 }], + }; + return { ...sampleProject, viewSnapshots: [snap], layouts: [layout] }; +} +const legend = (extra?: Partial): LayoutLegend => ({ id: "g1", xMm: 20, yMm: 30, ...extra }); + +describe("legendKeysOfViewports", () => { + it("findet die Materialien (Bauteile) der Wände im gezeigten Geschoss", () => { + const p = proj(); + const keys = legendKeysOfViewports(p, p.layouts![0]); + const wallType = p.wallTypes.find((w) => w.id === "aw")!; + for (const l of wallType.layers) expect(keys).toContain(`component:${l.componentId}`); + expect(keys.every((k) => /^(component|hatch|lineType|category):/.test(k))).toBe(true); + }); + it("ohne Viewports nichts; ausgeblendete Kategorien zählen nicht", () => { + const p = proj(); + expect(legendKeysOfViewports(p, { ...p.layouts![0], viewports: [] })).toEqual([]); + const snap = { ...p.viewSnapshots![0], layerVisibility: {} } as ViewSnapshot; + expect(legendKeysOfViewports({ ...p, viewSnapshots: [snap] }, p.layouts![0]).filter((k) => k.startsWith("component:"))).toEqual([]); + }); +}); + +describe("legendEntries", () => { + it("Standard: nur Schraffuren/Materialien, mit Name und Schraffur-Id, ohne Doppelte", () => { + const p = proj(); + const e = legendEntries(p, p.layouts![0], legend()); + expect(e.length).toBeGreaterThan(0); + expect(e.every((x) => x.kind === "hatch")).toBe(true); + expect(new Set(e.map((x) => x.key)).size).toBe(e.length); + const comp = p.components.find((c) => e[0].key === `component:${c.id}`)!; + expect(e[0]).toMatchObject({ label: comp.name, hatchId: comp.hatchId }); + }); + it("Handauswahl gewinnt, unbekannte Schlüssel entfallen, Kategorien tragen Code und Name", () => { + const p = proj(); + const cat = p.layers[0]; + const e = legendEntries(p, p.layouts![0], legend({ kinds: ["hatch", "category"], manualKeys: [`category:${cat.code}`, "component:gibtsnicht", `hatch:${p.hatches[0].id}`] })); + expect(e.map((x) => x.key)).toEqual([`category:${cat.code}`, `hatch:${p.hatches[0].id}`]); + expect(e[0].label).toContain(cat.name); + expect(e[1].label).toBe(p.hatches[0].name); + }); + it("Linientypen aus den Zeichnungen des Geschosses", () => { + const p = proj(); + const ls = p.lineStyles[0]; + const q: Project = { + ...p, + drawings2d: [{ id: "d1", type: "drawing2d", levelId: "eg", categoryCode: p.layers[0].code, geom: { shape: "line", a: { x: 0, y: 0 }, b: { x: 1, y: 0 } }, lineStyleId: ls.id }], + }; + const e = legendEntries(q, q.layouts![0], legend({ kinds: ["lineType"] })); + expect(e.map((x) => x.key)).toEqual([`lineType:${ls.id}`]); + }); +}); + +describe("legendDrawings", () => { + it("erzeugt Titel, Rahmen, je Eintrag Muster + Name in Papier-Metern auf der Blatt-Ebene", () => { + const p = proj(); + const lg = legend({ title: "Materialien" }); + const e = legendEntries(p, p.layouts![0], lg); + const out = legendDrawings(p, lg, e, "lvl"); + expect(out.widthMm).toBeGreaterThan(20); + expect(out.heightMm).toBeGreaterThan(5 * e.length); + const texts = out.drawings.filter((d) => d.geom.shape === "text").map((d) => (d.geom as { text: string }).text); + expect(texts).toContain("Materialien"); + for (const x of e) expect(texts).toContain(x.label); + const swatches = out.drawings.filter((d) => d.hatchId !== undefined); + expect(swatches).toHaveLength(e.length); + expect(out.drawings.every((d) => d.levelId === "lvl")).toBe(true); + // Position: x = 20 mm → 0.02 m, y = 30 mm → −0.03 m (Papier-y nach unten). + const frame = out.drawings.find((d) => d.geom.shape === "rect")!; + expect((frame.geom as { min: { x: number } }).min.x).toBeCloseTo(0.02, 9); + }); +}); + +describe("Legende-Liste am Layout", () => { + it("hinzufügen, ändern, entfernen; Fläche folgt dem Inhalt", () => { + const p = proj(); + let l = addLegend(p.layouts![0], legend()); + expect(l.legends).toHaveLength(1); + l = patchLegend(l, "g1", { xMm: 50, title: "Material" }); + expect(l.legends![0]).toMatchObject({ xMm: 50, yMm: 30, title: "Material" }); + const box = legendBox(p, l, l.legends![0]); + expect(box.xMm).toBe(50); + expect(box.widthMm).toBeGreaterThan(20); + l = removeLegend(l, "g1"); + expect(l.legends).toBeUndefined(); + }); +}); diff --git a/src/analysis/legend.ts b/src/analysis/legend.ts new file mode 100644 index 00000000..41914b8b --- /dev/null +++ b/src/analysis/legend.ts @@ -0,0 +1,226 @@ +// Grafische Legende auf dem Layout-Blatt ([82]): welche Schraffuren/Materialien, Linientypen und Kategorien +// die gezeigten Viewports verwenden (oder die Handauswahl der Legende) und wie die Legende als Zeichnung +// aussieht. Die Legende ist KEIN eigener Renderer: sie wird als gewöhnliche 2D-Elemente auf der Blatt-Ebene +// (Papier 1:1 in Metern) beschrieben — Schraffur-Muster, Linien und Schrift erzeugt derselbe Kern wie im +// Plan; Bildschirm, PDF und DXF lesen dasselbe Ergebnis, und sie folgt dem Projekt bei jeder Änderung. + +import type { Drawing2D, Layout, LayoutLegend, Project, ViewSnapshot } from "../model/types"; +import { getLayerCategory } from "../model/types"; +import { findSnapshot, sheetMmToModel, visibleCodesFromSnapshot } from "../model/layoutModel"; + +export type LegendKind = "hatch" | "lineType" | "category"; + +export interface LegendEntry { + /** `component:` (Material mit Schnitt-Schraffur), `hatch:`, `lineType:`, `category:`. */ + key: string; + kind: LegendKind; + label: string; + /** Schraffur des Musters (kind "hatch"). */ + hatchId?: string; + /** Linienfarbe der Schraffur bzw. des Linientyps / Füllfarbe der Kategorie. */ + color?: string; + /** Füllfarbe hinter der Schraffur. */ + background?: string; + lineStyleId?: string; +} + +const DEFAULT_KINDS: LegendKind[] = ["hatch"]; +const MIN_ORDER: Record = { hatch: 0, lineType: 1, category: 2 }; + +function kindOfKey(key: string): LegendKind | undefined { + const k = key.slice(0, key.indexOf(":")); + if (k === "component" || k === "hatch") return "hatch"; + return k === "lineType" || k === "category" ? k : undefined; +} + +/** Schlüssel, die EIN Ausschnitt braucht: Material der Wände/Decken/Dächer/Stützen, Schraffuren/Linientypen der Zeichnungen, Kategorien. */ +function keysOfSnapshot(project: Project, snap: ViewSnapshot, out: Set): void { + const visible = visibleCodesFromSnapshot(snap); + const level = snap.activeLevelId; + const comps = (layers: { componentId: string }[] | undefined) => { + for (const l of layers ?? []) out.add(`component:${l.componentId}`); + }; + const cat = (code: string | undefined) => { + if (code && visible.has(code)) out.add(`category:${code}`); + return !!code && visible.has(code); + }; + for (const w of project.walls) { + if (w.floorId !== level || !cat(w.categoryCode)) continue; + if (w.hatchId) out.add(`hatch:${w.hatchId}`); + comps(project.wallTypes.find((t) => t.id === w.wallTypeId)?.layers); + } + for (const c of project.ceilings ?? []) { + if (c.floorId !== level || !cat(c.categoryCode)) continue; + if (c.hatchId) out.add(`hatch:${c.hatchId}`); + comps((project.ceilingTypes ?? []).find((t) => t.id === c.ceilingTypeId)?.layers ?? project.wallTypes.find((t) => t.id === c.wallTypeId)?.layers); + } + for (const r of project.roofs ?? []) { + if (r.floorId !== level || !cat(r.categoryCode)) continue; + comps((project.roofTypes ?? []).find((t) => t.id === r.roofTypeId)?.layers); + } + for (const c of project.columns ?? []) { + if (c.floorId !== level || !cat(c.categoryCode)) continue; + if (c.hatchId) out.add(`hatch:${c.hatchId}`); + if (c.componentId) out.add(`component:${c.componentId}`); + } + for (const r of project.rooms ?? []) if (r.floorId === level) cat(r.categoryCode); + for (const d of project.drawings2d) { + if (d.levelId !== level || !cat(d.categoryCode)) continue; + if (d.hatchId) out.add(`hatch:${d.hatchId}`); + if (d.lineStyleId) out.add(`lineType:${d.lineStyleId}`); + } +} + +/** Alle Schlüssel der Viewports eines Blatts (Reihenfolge des ersten Auftretens). */ +export function legendKeysOfViewports(project: Project, layout: Layout): string[] { + const out = new Set(); + for (const vp of layout.viewports) { + const snap = findSnapshot(project, vp.snapshotId); + if (snap) keysOfSnapshot(project, snap, out); + } + return [...out]; +} + +function entryOf(project: Project, key: string): LegendEntry | undefined { + const i = key.indexOf(":"); + const id = key.slice(i + 1); + switch (key.slice(0, i)) { + case "component": { + const c = project.components.find((x) => x.id === id); + if (!c?.hatchId) return undefined; + return { key, kind: "hatch", label: c.name, hatchId: c.hatchId, color: c.foreground, background: c.background ?? c.color }; + } + case "hatch": { + const h = project.hatches.find((x) => x.id === id); + return h ? { key, kind: "hatch", label: h.name, hatchId: h.id, color: h.color } : undefined; + } + case "lineType": { + const l = project.lineStyles.find((x) => x.id === id); + return l ? { key, kind: "lineType", label: l.name, lineStyleId: l.id, color: l.color } : undefined; + } + case "category": { + const c = getLayerCategory(project, id); + return c ? { key, kind: "category", label: `${c.code} ${c.name}`, color: c.color } : undefined; + } + } + return undefined; +} + +/** + * Einträge der Legende: Handauswahl (`manualKeys`) in deren Reihenfolge, sonst automatisch aus den Viewports; + * nur die gewählten Arten (`kinds`, Standard Schraffuren), ohne Doppelte, Unbekanntes entfällt. + */ +export function legendEntries(project: Project, layout: Layout, legend: LayoutLegend): LegendEntry[] { + const kinds = new Set((legend.kinds as LegendKind[] | undefined)?.length ? (legend.kinds as LegendKind[]) : DEFAULT_KINDS); + const manual = legend.manualKeys ?? []; + const keys = manual.length > 0 ? manual : legendKeysOfViewports(project, layout); + const seen = new Set(); + const out: LegendEntry[] = []; + for (const key of keys) { + const kind = kindOfKey(key); + if (!kind || !kinds.has(kind) || seen.has(key)) continue; + seen.add(key); + const e = entryOf(project, key); + if (e) out.push(e); + } + if (manual.length === 0) out.sort((a, b) => MIN_ORDER[a.kind] - MIN_ORDER[b.kind]); + return out; +} + +// ── Aussehen (Papier-mm) ────────────────────────────────────────────────────── + +const TITLE_H = 3.5; // Schrifthöhe Titel +const TEXT_H = 2.5; // Schrifthöhe Einträge +const PAD = 3; +const SWATCH_W = 14; +const SWATCH_H = 6; +const GAP = 2; +const ROW = SWATCH_H + GAP; +const CHAR_W = 0.65; // mittlere Zeichenbreite in Schrifthöhen (nur für die Rahmenbreite, grosszügig) + +export interface LegendDrawings { + drawings: Drawing2D[]; + widthMm: number; + heightMm: number; +} + +/** Die Legende als 2D-Elemente auf der Blatt-Ebene `levelId` (Papier 1:1, Ursprung oben links, Papier-y = −y). */ +export function legendDrawings(project: Project, legend: LayoutLegend, entries: readonly LegendEntry[], levelId: string): LegendDrawings { + const title = legend.title?.trim() || "Legende"; + const categoryCode = project.layers[0]?.code ?? ""; + const textW = Math.max(title.length * TITLE_H, ...entries.map((e) => e.label.length * TEXT_H)) * CHAR_W; + const w = PAD * 2 + SWATCH_W + 3 + textW; + const h = PAD * 2 + TITLE_H + GAP + Math.max(1, entries.length) * ROW - GAP; + const x0 = legend.xMm; + const y0 = legend.yMm; + const p = (x: number, y: number) => sheetMmToModel(x, y); + const m = (v: number) => v / 1000; + let n = 0; + const base = (): Pick => ({ id: `${legend.id}-${n++}`, type: "drawing2d", levelId, categoryCode }); + const out: Drawing2D[] = []; + out.push({ ...base(), geom: { shape: "rect", min: p(x0, y0 + h), max: p(x0 + w, y0) }, background: "#ffffff", color: "#111111", weightMm: 0.25 }); + out.push({ + ...base(), + geom: { shape: "text", at: p(x0 + PAD, y0 + PAD + TITLE_H), text: title, height: m(TITLE_H), angle: 0 }, + color: "#111111", + }); + let y = y0 + PAD + TITLE_H + GAP; + for (const e of entries) { + const sx = x0 + PAD; + if (e.kind === "hatch") { + out.push({ + ...base(), + geom: { shape: "rect", min: p(sx, y + SWATCH_H), max: p(sx + SWATCH_W, y) }, + hatchId: e.hatchId, + ...(e.color ? { foreground: e.color } : {}), + background: e.background ?? "#ffffff", + color: "#111111", + weightMm: 0.18, + }); + } else if (e.kind === "lineType") { + out.push({ + ...base(), + geom: { shape: "line", a: p(sx, y + SWATCH_H / 2), b: p(sx + SWATCH_W, y + SWATCH_H / 2) }, + lineStyleId: e.lineStyleId, + weightMm: 0.35, + }); + } else { + out.push({ + ...base(), + geom: { shape: "rect", min: p(sx, y + SWATCH_H), max: p(sx + SWATCH_W, y) }, + background: e.color ?? "#cccccc", + color: "#111111", + weightMm: 0.18, + }); + } + out.push({ + ...base(), + geom: { shape: "text", at: p(sx + SWATCH_W + 3, y + SWATCH_H / 2 + TEXT_H * 0.35), text: e.label, height: m(TEXT_H), angle: 0 }, + color: "#111111", + }); + y += ROW; + } + return { drawings: out, widthMm: w, heightMm: h }; +} + +// ── Listen-Änderungen am Layout ─────────────────────────────────────────────── + +/** Fläche der Legende auf dem Blatt (mm): Lage aus dem Modell, Grösse aus Inhalt (Treffer-Test, Rahmen). */ +export function legendBox(project: Project, layout: Layout, legend: LayoutLegend): { xMm: number; yMm: number; widthMm: number; heightMm: number } { + const { widthMm, heightMm } = legendDrawings(project, legend, legendEntries(project, layout, legend), "x"); + return { xMm: legend.xMm, yMm: legend.yMm, widthMm, heightMm }; +} + +export function addLegend(layout: Layout, legend: LayoutLegend): Layout { + return { ...layout, legends: [...(layout.legends ?? []), legend] }; +} + +export function patchLegend(layout: Layout, id: string, patch: Partial>): Layout { + return { ...layout, legends: (layout.legends ?? []).map((l) => (l.id === id ? { ...l, ...patch } : l)) }; +} + +export function removeLegend(layout: Layout, id: string): Layout { + const legends = (layout.legends ?? []).filter((l) => l.id !== id); + const { legends: _old, ...rest } = layout; + return legends.length > 0 ? { ...rest, legends } : rest; +} diff --git a/src/export/layoutPdf.ts b/src/export/layoutPdf.ts index 70ddfa6d..c90dfe76 100644 --- a/src/export/layoutPdf.ts +++ b/src/export/layoutPdf.ts @@ -12,13 +12,18 @@ import { jsPDF } from "jspdf"; import "svg2pdf.js"; -import type { Layout, MasterLayout, Project } from "../model/types"; +import type { Layout, LayoutPaperFormat, MasterLayout, Project } from "../model/types"; +import { t } from "../i18n"; +import { legendPlan, legendPrintSvg } from "./legendSvg"; +import { categoryLayerGroups, enablePdfLayers, type PdfLayers } from "./pdfLayers"; import { generatePlan } from "../plan/generatePlan"; import { planToPrintSvg } from "./planToPrintSvg"; import { drawTablesPdf, sheetTables } from "./sheetTable"; import { collectVisibleCodes } from "../model/types"; import { + effectiveSheetSizeMm, findMaster, + sheetSizeMm, findSnapshot, folderPdfPages, resolveTitleBlock, @@ -41,6 +46,7 @@ function drawTitleBlock( tb: ResolvedTitleBlock, paper: string, orientation: string, + showRevision: boolean, ): void { const boxW = 70; const boxH = 30; @@ -66,6 +72,11 @@ function drawTitleBlock( doc.setFont("helvetica", "normal"); doc.setFontSize(8); doc.text(clip(tb.sheetName, 36), x + 3, y + 13); + if (showRevision && tb.revision) { + doc.setFontSize(7); + doc.text(`${t("layouts.revision.short")} ${tb.revision}`, x + boxW - 3, y + 13, { align: "right" }); + doc.setFontSize(8); + } if (tb.author) { doc.setFontSize(7); doc.setTextColor(68, 68, 68); @@ -114,12 +125,36 @@ async function renderSheetDrawing(doc: jsPDF, project: Project, layout: Layout, await doc.svg(print.svg, { x: 0, y: 0, width: widthMm, height: heightMm }); } +/** Optionen des Seiten-Aufbaus (Publikationssätze, [79]/[80]). */ +export interface PdfPagesOptions { + /** PDF-Ebenen (Optional Content) je Kategorie, Rahmen/Titelblock, Blatt-Zeichnung und Legende. */ + layers?: boolean; + /** Massstab (1:N) für alle Viewports. */ + scaleOverride?: number; + /** Papierformat für alle Seiten: der Blatt-Inhalt wird einheitlich eingepasst und zentriert. */ + paperOverride?: LayoutPaperFormat; + /** Revisionsindex im Titelblock (Standard ja). */ + includeRevision?: boolean; +} + +interface PageCtx { + layers?: PdfLayers; + scaleOverride?: number; + includeRevision: boolean; +} + +/** `fn` in der PDF-Ebene `name` (ohne Ebenen: direkt). */ +function inLayer(ctx: PageCtx, name: string, fn: () => void | Promise): Promise | void { + return ctx.layers ? ctx.layers.run(name, fn) : fn(); +} + /** Zeichnet die Viewports + Master-Elemente EINER Seite in das jsPDF-Dokument. */ async function renderPage( doc: jsPDF, project: Project, page: FolderPdfPage, master: MasterLayout | undefined, + ctx: PageCtx, ): Promise { const { layout, widthMm, heightMm } = page; @@ -131,92 +166,130 @@ async function renderPage( const codes = visibleCodesFromSnapshot(snap); // Massstab zuerst: er geht in die Plan-Erzeugung ein (Bemassung in Papier-mm, Strichstärken // nach Massstab) — wie ViewportPlan in LayoutSheet.tsx, sonst wiche das PDF von der Vorschau ab. - const scaleN = resolveViewportScale(vp, snap); - const plan = generatePlan( - project, - snap.activeLevelId, - codes, - undefined, - snap.detail, - false, - false, - true, - scaleN, - true, - ); - const print = planToPrintSvg(plan, { - scaleDenominator: scaleN, - pageWidthMm: vp.widthMm, - pageHeightMm: vp.heightMm, - }); - await doc.svg(print.svg, { - x: vp.xMm, - y: vp.yMm, - width: vp.widthMm, - height: vp.heightMm, - }); + const scaleN = ctx.scaleOverride ?? resolveViewportScale(vp, snap); + const planOf = (visible: Set) => generatePlan(project, snap.activeLevelId, visible, undefined, snap.detail, false, false, true, scaleN, true); + const draw = async (plan: ReturnType, transparent: boolean, bounds?: typeof plan.bounds) => { + const print = planToPrintSvg(plan, { scaleDenominator: scaleN, pageWidthMm: vp.widthMm, pageHeightMm: vp.heightMm, transparent, bounds }); + await doc.svg(print.svg, { x: vp.xMm, y: vp.yMm, width: vp.widthMm, height: vp.heightMm }); + }; + const full = planOf(codes); + if (!ctx.layers) { + await draw(full, false); + } else { + // Weisser Grund bleibt ausserhalb der Ebenen; der Inhalt je Wurzel-Kategorie in eigener Ebene. + // Alle Ebenen mit den Grenzen des GANZEN Plans, sonst läge jede anders zentriert. + doc.setFillColor(255, 255, 255); + doc.rect(vp.xMm, vp.yMm, vp.widthMm, vp.heightMm, "F"); + for (const g of categoryLayerGroups(project.layers, codes, t("pdfLayers.other"))) { + const plan = planOf(g.codes); + if (plan.primitives.length === 0) continue; // leere Ebenen nicht anlegen + await ctx.layers.run(g.name, () => draw(plan, true, full.bounds)); + } + } } catch { // Einzelner Viewport, der nicht rendert, darf die Seite nicht killen. } } + // Legenden ([82]): live aus den Viewports (oder Handauswahl), Muster vom Kern-Schraffurgenerator. + for (const lg of layout.legends ?? []) { + try { + const lp = legendPlan(project, layout, lg); + if (!lp) continue; + await inLayer(ctx, t("pdfLayers.legend"), async () => { + await doc.svg(legendPrintSvg(lp), { x: lp.xMm, y: lp.yMm, width: lp.widthMm, height: lp.heightMm }); + }); + } catch { + // Eine Legende, die nicht rendert, darf die Seite nicht killen. + } + } + // Master: Rahmen + Titelblock (read-only, wie im In-Viewport-Editor). if (master) { - if (master.border ?? true) { - doc.setDrawColor(17, 17, 17); - doc.setLineWidth(0.35); - doc.rect(5, 5, widthMm - 10, heightMm - 10); - } - const tb = resolveTitleBlock(project, layout, master); - drawTitleBlock(doc, widthMm, heightMm, tb, layout.paper, layout.orientation); + await inLayer(ctx, t("pdfLayers.frame"), () => { + if (master.border ?? true) { + doc.setDrawColor(17, 17, 17); + doc.setLineWidth(0.35); + doc.rect(5, 5, widthMm - 10, heightMm - 10); + } + const tb = resolveTitleBlock(project, layout, master); + drawTitleBlock(doc, widthMm, heightMm, tb, layout.paper, layout.orientation, ctx.includeRevision); + }); } // Lebendige Tabellen ([111]): Vektortext + Linien wie in der Blattansicht. try { - drawTablesPdf(doc, sheetTables(project, layout.id)); + await inLayer(ctx, t("pdfLayers.tables"), () => drawTablesPdf(doc, sheetTables(project, layout.id))); } catch { // Eine Tabelle, die nicht rechnet, darf die Seite nicht killen. } // 2D-Zeichnung des Blatts — ÜBER Viewports + Master, wie am Bildschirm. try { - await renderSheetDrawing(doc, project, layout, widthMm, heightMm); + await inLayer(ctx, t("pdfLayers.sheetDrawing"), () => renderSheetDrawing(doc, project, layout, widthMm, heightMm)); } catch { // Eine Blatt-Zeichnung, die nicht rendert, darf die Seite nicht killen. } } +/** Seiten für Layouts nach ids (Reihenfolge der ids; ein gebundener Master gibt die Blattgrösse vor). */ +export function layoutPages(project: Project, layoutIds: readonly string[]): FolderPdfPage[] { + const all = project.layouts ?? []; + return layoutIds.flatMap((id) => { + const layout = all.find((l) => l.id === id); + if (!layout) return []; + const { w, h } = effectiveSheetSizeMm(findMaster(project, layout) ?? layout); + return [{ layout, widthMm: w, heightMm: h }]; + }); +} + +/** + * Baut ein Mehrseiten-PDF aus Seiten (eine Seite je Layout) und liefert das jsPDF-Dokument; `null` ohne Seiten. + * Optionen: PDF-Ebenen, Massstab-/Papier-Übersteuerung, Revisionsindex ([79]/[80]). + */ +export async function buildPagesPdf(project: Project, pages: FolderPdfPage[], opts: PdfPagesOptions = {}): Promise { + if (pages.length === 0) return null; + const sizeOf = (p: FolderPdfPage) => (opts.paperOverride ? sheetSizeMm(opts.paperOverride, p.widthMm > p.heightMm ? "landscape" : "portrait") : { w: p.widthMm, h: p.heightMm }); + const orientOf = (s: { w: number; h: number }) => (s.w > s.h ? "landscape" : "portrait"); + + const first = sizeOf(pages[0]); + const doc = new jsPDF({ unit: "mm", format: [first.w, first.h], orientation: orientOf(first), compress: true }); + const ctx: PageCtx = { + layers: opts.layers ? enablePdfLayers(doc) : undefined, + scaleOverride: opts.scaleOverride && opts.scaleOverride > 0 ? opts.scaleOverride : undefined, + includeRevision: opts.includeRevision ?? true, + }; + const internal = doc.internal as unknown as { write: (s: string) => void; scaleFactor: number }; + + for (let i = 0; i < pages.length; i++) { + const page = pages[i]; + const size = sizeOf(page); + if (i > 0) doc.addPage([size.w, size.h], orientOf(size)); + // Papier-Übersteuerung: Inhalt einheitlich auf die neue Seite einpassen (oben-links-Ursprung, zentriert). + const fit = size.w !== page.widthMm || size.h !== page.heightMm; + if (fit) { + const s = Math.min(size.w / page.widthMm, size.h / page.heightMm); + const k = internal.scaleFactor; + const tx = ((size.w - s * page.widthMm) / 2) * k; + const ty = (1 - s) * size.h * k - ((size.h - s * page.heightMm) / 2) * k; + internal.write(`q ${s} 0 0 ${s} ${tx} ${ty} cm`); + } + try { + await renderPage(doc, project, page, findMaster(project, page.layout), ctx); + } finally { + if (fit) internal.write("Q"); + } + } + return doc; +} + /** * Baut das Mehrseiten-PDF eines Ordners und liefert das jsPDF-Dokument. Jede * Seite = ein Layout in Baum-Reihenfolge. Gibt `null`, wenn der Ordner keine * Layouts enthält (der Aufrufer meldet das dann in der UI). */ -export async function buildFolderPdf( - project: Project, - folderId: string, -): Promise { - const pages = folderPdfPages(project, folderId); - if (pages.length === 0) return null; - - const orientOf = (p: FolderPdfPage) => - p.widthMm > p.heightMm ? "landscape" : "portrait"; - - const first = pages[0]; - const doc = new jsPDF({ - unit: "mm", - format: [first.widthMm, first.heightMm], - orientation: orientOf(first), - compress: true, - }); - - for (let i = 0; i < pages.length; i++) { - const page = pages[i]; - if (i > 0) doc.addPage([page.widthMm, page.heightMm], orientOf(page)); - const master = findMaster(project, page.layout); - await renderPage(doc, project, page, master); - } - - return doc; +export async function buildFolderPdf(project: Project, folderId: string): Promise { + return buildPagesPdf(project, folderPdfPages(project, folderId)); } /** Baut das Ordner-PDF als Bytes (`null`, wenn nichts zu exportieren war). Speichern macht die Hülle. */ diff --git a/src/export/legendSvg.test.ts b/src/export/legendSvg.test.ts new file mode 100644 index 00000000..fe993204 --- /dev/null +++ b/src/export/legendSvg.test.ts @@ -0,0 +1,40 @@ +// [82] Legende → Plan: Schraffur-Muster kommen vom Kern-Generator, Namen als Text, live mit dem Projekt. + +import { describe, expect, it } from "vitest"; +import { sampleProject } from "../model/sampleProject"; +import type { Layout, Project, ViewSnapshot } from "../model/types"; +import { legendPlan } from "./legendSvg"; + +function proj(): Project { + const snap = { + id: "s1", + name: "EG", + activeLevelId: "eg", + layerVisibility: Object.fromEntries(sampleProject.layers.map((c) => [c.code, true])), + } as unknown as ViewSnapshot; + const layout: Layout = { + id: "l1", + name: "Blatt", + paper: "a3", + orientation: "landscape", + viewports: [{ id: "v1", snapshotId: "s1", xMm: 10, yMm: 10, widthMm: 200, heightMm: 150 }], + }; + return { ...sampleProject, viewSnapshots: [snap], layouts: [layout] }; +} + +describe("legendPlan", () => { + it("enthält je Material eine geschraffte Fläche und den Namen, im Legende-Rahmen", () => { + const p = proj(); + const lp = legendPlan(p, p.layouts![0], { id: "g", xMm: 20, yMm: 30, title: "Legende" })!; + const polys = lp.plan.primitives.filter((x) => x.kind === "polygon"); + expect(polys.length).toBeGreaterThanOrEqual(1 + 6); // Rahmen + 6 Materialien der Aussenwand/Decke + expect(polys.filter((x) => x.kind === "polygon" && x.hatch.pattern !== "none").length).toBeGreaterThanOrEqual(4); + const names = JSON.stringify(lp.plan.primitives); + for (const c of p.components.filter((c) => ["brick", "insulation", "concrete"].includes(c.id))) expect(names).toContain(c.name); + expect(lp.widthMm).toBeGreaterThan(20); + // Live: andere Wandart → andere Einträge. + const q: Project = { ...p, walls: [] }; + const lq = legendPlan(q, q.layouts![0], { id: "g", xMm: 20, yMm: 30 })!; + expect(lq.heightMm).toBeLessThan(lp.heightMm); + }); +}); diff --git a/src/export/legendSvg.ts b/src/export/legendSvg.ts new file mode 100644 index 00000000..b51bcb88 --- /dev/null +++ b/src/export/legendSvg.ts @@ -0,0 +1,63 @@ +// Legende → Plan/Druck-SVG ([82]). Die Legende-Elemente (`analysis/legend.ts`) liegen auf einer Blatt-Ebene +// eines Hilfsprojekts ohne Bauteile; `generatePlan` (Kern: Schraffur-Muster, Linientypen, Schrift) und +// `planToPrintSvg` erzeugen daraus genau das, was auch eine Blatt-Zeichnung ergäbe — Bildschirm und PDF +// teilen diesen Weg. + +import type { Layout, LayoutLegend, Project } from "../model/types"; +import { collectVisibleCodes } from "../model/types"; +import { generatePlan, type Plan } from "../plan/generatePlan"; +import { legendDrawings, legendEntries } from "../analysis/legend"; +import { SHEET_SCALE_DENOMINATOR, sheetMmToModel } from "../model/layoutModel"; +import { planToPrintSvg } from "./planToPrintSvg"; + +export interface LegendPlan { + plan: Plan; + /** Linke obere Ecke und Grösse der Legende auf dem Blatt (mm). */ + xMm: number; + yMm: number; + widthMm: number; + heightMm: number; +} + +/** Hilfsprojekt: nur Stile/Kategorien des Projekts + die Legende-Elemente auf einer Blatt-Ebene. */ +function legendProject(project: Project, layout: Layout, drawings: ReturnType["drawings"], levelId: string): Project { + return { + ...project, + walls: [], + ceilings: [], + roofs: [], + openings: [], + stairs: [], + rooms: [], + columns: [], + groups: [], + extrudedSolids: [], + context: [], + parametricWalls: [], + drawings2d: drawings, + drawingLevels: [{ id: levelId, name: layout.name, kind: "drawing", visible: true, locked: false, layoutId: layout.id }], + }; +} + +/** Plan der Legende (`null`, wenn es nichts aufzulisten gibt und die Legende automatisch ist). */ +export function legendPlan(project: Project, layout: Layout, legend: LayoutLegend): LegendPlan | null { + const entries = legendEntries(project, layout, legend); + const levelId = `legend-${legend.id}`; + const { drawings, widthMm, heightMm } = legendDrawings(project, legend, entries, levelId); + const tmp = legendProject(project, layout, drawings, levelId); + const plan = generatePlan(tmp, levelId, collectVisibleCodes(tmp.layers), undefined, "fein", false, false, false, SHEET_SCALE_DENOMINATOR, true); + return { plan, xMm: legend.xMm, yMm: legend.yMm, widthMm, heightMm }; +} + +/** Druck-SVG der Legende in einem eigenen Koordinatensystem (0..width, 0..height in mm), ohne weisses Blatt. */ +export function legendPrintSvg(lp: LegendPlan): SVGSVGElement { + const a = sheetMmToModel(lp.xMm, lp.yMm + lp.heightMm); + const b = sheetMmToModel(lp.xMm + lp.widthMm, lp.yMm); + return planToPrintSvg(lp.plan, { + scaleDenominator: SHEET_SCALE_DENOMINATOR, + pageWidthMm: lp.widthMm, + pageHeightMm: lp.heightMm, + bounds: { minX: a.x, minY: a.y, maxX: b.x, maxY: b.y }, + transparent: true, + }).svg; +} diff --git a/src/export/pdfLayers.test.ts b/src/export/pdfLayers.test.ts new file mode 100644 index 00000000..ba7d5b04 --- /dev/null +++ b/src/export/pdfLayers.test.ts @@ -0,0 +1,53 @@ +// [80] PDF-Ebenen (Optional Content): Ebenen im Katalog, Inhalt in /OC-Marken, gleiche Namen = eine Ebene. + +import { describe, expect, it } from "vitest"; +import { jsPDF } from "jspdf"; +import { categoryLayerGroups, enablePdfLayers } from "./pdfLayers"; +import type { LayerCategory } from "../model/types"; + +const text = (doc: jsPDF) => Buffer.from(doc.output("arraybuffer")).toString("latin1"); +const utf16Hex = (s: string) => "FEFF" + [...s].map((c) => c.charCodeAt(0).toString(16).padStart(4, "0")).join("").toUpperCase(); + +describe("enablePdfLayers", () => { + it("schreibt OCProperties, OCGs mit Namen und markiert den Inhalt", async () => { + const doc = new jsPDF({ unit: "mm", compress: false }); + const layers = enablePdfLayers(doc); + await layers.run("Wände", () => doc.rect(10, 10, 20, 20)); + doc.addPage(); + await layers.run("Wände", () => doc.rect(10, 10, 5, 5)); + await layers.run("Möbel", () => doc.line(0, 0, 10, 10)); + doc.rect(1, 1, 1, 1); // ausserhalb jeder Ebene + const s = text(doc); + expect(s).toContain("/OCProperties"); + expect(s.match(/\/Type \/OCG/g)?.length).toBe(2); // „Wände" gemeinsam auf beiden Seiten + expect(s).toContain(`/Name <${utf16Hex("Wände")}>`); + expect(s).toContain(`/Name <${utf16Hex("Möbel")}>`); + expect(s.match(/\/OC \/\w+ BDC/g)?.length).toBe(3); + expect(s.match(/\bEMC\b/g)?.length).toBe(3); + expect(s).toContain("/Properties <<"); + expect(layers.names()).toEqual(["Wände", "Möbel"]); + }); + + it("ohne benutzte Ebene bleibt das PDF unverändert (kein OCProperties)", () => { + const doc = new jsPDF({ unit: "mm", compress: false }); + enablePdfLayers(doc); + doc.rect(1, 1, 1, 1); + expect(text(doc)).not.toContain("OCProperties"); + }); + + it("Marken sind auch bei werfendem Inhalt ausgeglichen", async () => { + const doc = new jsPDF({ unit: "mm", compress: false }); + const layers = enablePdfLayers(doc); + await expect(layers.run("A", () => { throw new Error("x"); })).rejects.toThrow(); + expect(text(doc).match(/\/OC \/\w+ BDC/g)?.length).toBe(text(doc).match(/\bEMC\b/g)?.length); + }); +}); + +describe("categoryLayerGroups", () => { + const cat = (code: string, name: string, children?: LayerCategory[]) => ({ code, name, children }) as LayerCategory; + it("eine Gruppe je Wurzel mit sichtbaren Unterkategorien; Verwaistes in „Übrige“; Leeres entfällt", () => { + const tree = [cat("1", "Bau", [cat("11", "Wände"), cat("12", "Decken")]), cat("2", "Möbel"), cat("3", "Leer")]; + const g = categoryLayerGroups(tree, new Set(["11", "2", "99"]), "Übrige"); + expect(g.map((x) => [x.name, [...x.codes]])).toEqual([["Bau", ["11"]], ["Möbel", ["2"]], ["Übrige", ["99"]]]); + }); +}); diff --git a/src/export/pdfLayers.ts b/src/export/pdfLayers.ts new file mode 100644 index 00000000..a89692a8 --- /dev/null +++ b/src/export/pdfLayers.ts @@ -0,0 +1,103 @@ +// PDF-Ebenen (Optional Content Groups, [80]): jsPDF kennt keine optionalen Inhalte. Wir schreiben sie +// minimal selbst — je Ebenenname EIN OCG-Objekt (gleiche Namen auf mehreren Seiten = eine in Acrobat +// schaltbare Ebene), der Inhalt steht zwischen `/OC /ocN BDC` … `EMC` im Seitenstrom, die Namen stehen im +// Ressourcen-Wörterbuch (`/Properties`), die Liste im Katalog (`/OCProperties`). Eingehängt über die +// Ereignisse von jsPDF (`putResources`, `putXobjectDict`, `putCatalog`); ohne benutzte Ebene schreibt +// nichts etwas ins PDF. + +import type { jsPDF } from "jspdf"; +import type { LayerCategory } from "../model/types"; + +export interface PdfLayers { + /** Führt `fn` aus; was es ins PDF zeichnet, gehört zur Ebene `name` (Marken bleiben auch bei Fehlern ausgeglichen). */ + run(name: string, fn: () => T | Promise): Promise; + /** Bisher benutzte Ebenennamen in Reihenfolge. */ + names(): string[]; +} + +/** PDF-Textstring (UTF-16BE, hex) — Umlaute und alles ausserhalb ASCII bleiben lesbar. */ +function pdfText(s: string): string { + let hex = "FEFF"; + for (let i = 0; i < s.length; i++) hex += s.charCodeAt(i).toString(16).padStart(4, "0"); + return `<${hex.toUpperCase()}>`; +} + +/** Schaltet Ebenen für das Dokument frei; Aufrufer legen Inhalt mit `run` in Ebenen. */ +export function enablePdfLayers(doc: jsPDF): PdfLayers { + const names: string[] = []; + const keys = new Map(); // Name → Ressourcen-Schlüssel + const oids = new Map(); // Name → OCG-Objektnummer + const internal = doc.internal as unknown as { + write: (...s: string[]) => void; + newObject: () => number; + events: { subscribe: (topic: string, fn: () => void) => void }; + }; + + internal.events.subscribe("putResources", () => { + for (const n of names) { + const oid = internal.newObject(); + internal.write(`<< /Type /OCG /Name ${pdfText(n)} >>`); + internal.write("endobj"); + oids.set(n, oid); + } + }); + // Im XObject-Wörterbuch: dieses schliessen, `/Properties` öffnen — das schliessende `>>` setzt jsPDF. + internal.events.subscribe("putXobjectDict", () => { + if (names.length === 0) return; + internal.write(">>"); + internal.write("/Properties <<"); + for (const n of names) { + const oid = oids.get(n); + if (oid !== undefined) internal.write(`/${keys.get(n)} ${oid} 0 R`); + } + }); + internal.events.subscribe("putCatalog", () => { + if (names.length === 0) return; + const refs = names.map((n) => `${oids.get(n)} 0 R`).join(" "); + internal.write(`/OCProperties << /OCGs [${refs}] /D << /Order [${refs}] /ON [${refs}] /BaseState /ON >> >>`); + }); + + return { + async run(name, fn) { + let key = keys.get(name); + if (!key) { + key = `oc${names.length + 1}`; + keys.set(name, key); + names.push(name); + } + internal.write(`/OC /${key} BDC`); + try { + return await fn(); + } finally { + internal.write("EMC"); + } + }, + names: () => [...names], + }; +} + +/** + * PDF-Ebenen aus dem Kategorie-Baum: je Wurzel-Kategorie eine Gruppe mit ihren sichtbaren Codes (samt + * Unterkategorien); sichtbare Codes ausserhalb des Baums landen in `otherName`. Leere Gruppen entfallen. + */ +export function categoryLayerGroups( + layers: readonly LayerCategory[], + visible: ReadonlySet, + otherName: string, +): { name: string; codes: Set }[] { + const out: { name: string; codes: Set }[] = []; + const known = new Set(); + const walk = (c: LayerCategory, into: Set) => { + known.add(c.code); + if (visible.has(c.code)) into.add(c.code); + for (const k of c.children ?? []) walk(k, into); + }; + for (const root of layers) { + const codes = new Set(); + walk(root, codes); + if (codes.size > 0) out.push({ name: root.name, codes }); + } + const rest = new Set([...visible].filter((c) => !known.has(c))); + if (rest.size > 0) out.push({ name: otherName, codes: rest }); + return out; +} diff --git a/src/export/publishRun.ts b/src/export/publishRun.ts new file mode 100644 index 00000000..f1bcfa34 --- /dev/null +++ b/src/export/publishRun.ts @@ -0,0 +1,103 @@ +// Publikationssatz ausführen ([79]): erzeugt die Dateien des Plans (`publishSet.ts`) — PDF mit Ebenen/Index +// (`layoutPdf.ts`), DXF/DWG mit den Papierbereichen der Blätter des Satzes. Braucht ein DOM (jsPDF/svg2pdf); +// Speichern, Revisionen und Protokoll macht der Aufrufer (`publishOps`). + +import JSZip from "jszip"; +import type { Layout, Project, PublishSet, ViewSnapshot } from "../model/types"; +import { collectVisibleCodes } from "../model/types"; +import { generatePlan } from "../plan/generatePlan"; +import { sheetLevelOf } from "../model/layoutModel"; +import { legendDrawings, legendEntries } from "../analysis/legend"; +import { buildPagesPdf, layoutPages } from "./layoutPdf"; +import { buildPlanDwg, buildPlanDxfBinary } from "./exportDxf"; +import { loadFileio } from "../engine/fileioWasm"; +import type { PublishPlan } from "./publishSet"; +import type { FolderPdfPage } from "../model/layoutModel"; + +export interface PublishedFile { + fileName: string; + bytes: Uint8Array; + mime: string; +} + +/** Eine gespeicherte Ansicht als eigene A3-Querseite mit einem Viewport über das ganze Blatt. */ +function snapshotPage(snap: ViewSnapshot): FolderPdfPage { + const layout: Layout = { + id: `snap-${snap.id}`, + name: snap.name, + paper: "a3", + orientation: "landscape", + viewports: [{ id: "v", snapshotId: snap.id, xMm: 10, yMm: 10, widthMm: 400, heightMm: 277 }], + }; + return { layout, widthMm: 420, heightMm: 297 }; +} + +/** Das Projekt, wie es veröffentlicht wird: Revisionsindex der Blätter schon hochgezählt (Titelblock). */ +export function projectForPublish(project: Project, plan: PublishPlan): Project { + const rev = new Map(plan.sheets.map((s) => [s.layoutId, s.revision])); + return { + ...project, + layouts: (project.layouts ?? []).map((l) => (rev.has(l.id) && rev.get(l.id) ? { ...l, revision: rev.get(l.id) } : l)), + }; +} + +/** Legenden der Blätter als Zeichnungen auf deren Blatt-Ebene — so landen sie im DXF-Papierbereich. */ +function withLegendDrawings(project: Project, layoutIds: readonly string[]): Project { + const extra = layoutIds.flatMap((id) => { + const layout = (project.layouts ?? []).find((l) => l.id === id); + const level = layout && sheetLevelOf(project, id); + if (!layout || !level) return []; + return (layout.legends ?? []).flatMap((lg) => legendDrawings(project, lg, legendEntries(project, layout, lg), level.id).drawings); + }); + return extra.length > 0 ? { ...project, drawings2d: [...project.drawings2d, ...extra] } : project; +} + +async function cadFile(project: Project, set: PublishSet, plan: PublishPlan, fileName: string, format: "dxf" | "dwg"): Promise { + await loadFileio(); + const layouts = plan.sheets.map((s) => s.layoutId); + const scoped = withLegendDrawings({ ...project, layouts: (project.layouts ?? []).filter((l) => layouts.includes(l.id)) }, layouts); + // Modell-Ebene: die des ersten gezeigten Ausschnitts, sonst die erste Nicht-Blatt-Ebene. + const firstSnap = layouts + .flatMap((id) => scoped.layouts?.find((l) => l.id === id)?.viewports ?? []) + .map((vp) => (scoped.viewSnapshots ?? []).find((v) => v.id === vp.snapshotId)) + .find(Boolean); + const levelId = firstSnap?.activeLevelId ?? scoped.drawingLevels.find((l) => !l.layoutId)?.id ?? scoped.drawingLevels[0]?.id ?? ""; + const scale = set.scaleOverride ?? 100; + const p = generatePlan(scoped, levelId, collectVisibleCodes(scoped.layers), undefined, "fein", false, false, true, scale, true); + const opts = { scaleDenominator: scale, paperLayout: true, levelId, title: set.name }; + const bytes = format === "dwg" ? buildPlanDwg(p, scoped, opts) : buildPlanDxfBinary(p, scoped, opts); + return { fileName, bytes, mime: format === "dwg" ? "image/vnd.dwg" : "application/dxf" }; +} + +/** Erzeugt alle Dateien des Plans. */ +export async function runPublish(project: Project, set: PublishSet, plan: PublishPlan): Promise { + const shown = projectForPublish(project, plan); + const out: PublishedFile[] = []; + for (const f of plan.files) { + if (f.format === "dxf" || f.format === "dwg") { + out.push(await cadFile(shown, set, plan, f.fileName, f.format)); + continue; + } + const pages = [ + ...layoutPages(shown, f.layoutIds), + ...f.snapshotIds.flatMap((id) => (shown.viewSnapshots ?? []).filter((v) => v.id === id).map(snapshotPage)), + ]; + const doc = await buildPagesPdf(shown, pages, { + layers: plan.pdfLayers, + scaleOverride: plan.scaleOverride, + paperOverride: plan.paperOverride, + includeRevision: plan.includeRevision, + }); + if (doc) out.push({ fileName: f.fileName, bytes: new Uint8Array(doc.output("arraybuffer")), mime: "application/pdf" }); + } + return out; +} + +/** Mehrere Dateien als ein ZIP; eine einzelne bleibt sie selbst. */ +export async function bundlePublished(files: PublishedFile[], zipName: string): Promise { + if (files.length === 0) return null; + if (files.length === 1) return files[0]; + const zip = new JSZip(); + for (const f of files) zip.file(f.fileName, f.bytes); + return { fileName: zipName, bytes: await zip.generateAsync({ type: "uint8array" }), mime: "application/zip" }; +} diff --git a/src/export/publishSet.test.ts b/src/export/publishSet.test.ts new file mode 100644 index 00000000..05b4fb04 --- /dev/null +++ b/src/export/publishSet.test.ts @@ -0,0 +1,105 @@ +// [79] Publikationssätze: Revisionsindex, Dateinamen-Muster, Satz → Dateien, Protokoll. + +import { describe, expect, it } from "vitest"; +import { sampleProject } from "../model/sampleProject"; +import type { Layout, Project, PublishSet, ViewSnapshot } from "../model/types"; +import { applyOps } from "../core/ops"; +import { + DEFAULT_NAME_PATTERN, + expandNamePattern, + nextRevision, + planPublish, + publishOps, +} from "./publishSet"; + +function proj(): Project { + const base = sampleProject; + const l = (id: string, name: string, extra?: Partial): Layout => ({ id, name, paper: "a3", orientation: "landscape", viewports: [], ...extra }); + return { + ...base, + name: "Haus Müller", + projectNumber: "2026-14", + layouts: [l("l1", "Grundriss EG", { planNumber: "101", revision: "A" }), l("l2", "Schnitt A/A", { planNumber: "201" }), l("l3", "Fassade")], + }; +} +const set = (extra?: Partial): PublishSet => ({ id: "s1", name: "Baueingabe", layoutIds: ["l2", "l1"], ...extra }); + +describe("nextRevision", () => { + it("zählt Buchstaben und Zahlen hoch", () => { + expect(nextRevision(undefined)).toBe("A"); + expect(nextRevision("")).toBe("A"); + expect(nextRevision("A")).toBe("B"); + expect(nextRevision("Z")).toBe("AA"); + expect(nextRevision("AZ")).toBe("BA"); + expect(nextRevision("2")).toBe("3"); + expect(nextRevision("09")).toBe("10"); + expect(nextRevision("v-x")).toBe("v-x2"); + }); +}); + +describe("expandNamePattern", () => { + it("ersetzt Platzhalter, säubert Dateinamen und lässt leere Teile weg", () => { + expect(expandNamePattern(DEFAULT_NAME_PATTERN, { Projektnummer: "2026-14", Blattnummer: "101", Blattname: "Grundriss EG", Index: "B" })).toBe( + "2026-14_101_Grundriss EG_B", + ); + expect(expandNamePattern(DEFAULT_NAME_PATTERN, { Projektnummer: "", Blattnummer: "201", Blattname: "Schnitt A/A", Index: "" })).toBe("201_Schnitt A_A"); + expect(expandNamePattern("{Unbekannt}-{Satz}", { Satz: "X" })).toBe("X"); + expect(expandNamePattern(" ", { Satz: "X" })).toBe("X"); + }); +}); + +describe("planPublish", () => { + it("pdf-multi: eine Datei, Blätter in Satz-Reihenfolge, Index mit Titelblock-Nummer", () => { + const plan = planPublish(proj(), set(), "2026-10-30"); + expect(plan.sheets.map((s) => s.layoutId)).toEqual(["l2", "l1"]); + expect(plan.files).toHaveLength(1); + expect(plan.files[0].fileName).toBe("Baueingabe.pdf"); + expect(plan.files[0].layoutIds).toEqual(["l2", "l1"]); + }); + it("pdf-single: je Blatt eine Datei nach Muster, Revision erst nach dem Hochzählen sichtbar", () => { + const plan = planPublish(proj(), set({ format: "pdf-single", bumpRevision: true }), "2026-10-30"); + expect(plan.files.map((f) => f.fileName)).toEqual(["2026-14_201_Schnitt A_A_A.pdf", "2026-14_101_Grundriss EG_B.pdf"]); + expect(plan.sheets.map((s) => s.revision)).toEqual(["A", "B"]); + }); + it("ohne includeRevision kein Index im Namen und im Protokoll bleibt er leer", () => { + const plan = planPublish(proj(), set({ format: "pdf-single", includeRevision: false }), "2026-10-30"); + expect(plan.files[1].fileName).toBe("2026-14_101_Grundriss EG.pdf"); + }); + it("dxf: eine Datei .dxf; fehlende Layouts werden übersprungen", () => { + const plan = planPublish(proj(), set({ format: "dxf", layoutIds: ["l1", "weg"] }), "2026-10-30"); + expect(plan.files.map((f) => f.fileName)).toEqual(["Baueingabe.dxf"]); + expect(plan.sheets).toHaveLength(1); + }); + it("gespeicherte Ansichten: eigene Seiten (multi) bzw. eigene Dateien (single); dwg als .dwg", () => { + const p: Project = { ...proj(), viewSnapshots: [{ id: "v1", name: "Ansicht Süd" } as ViewSnapshot] }; + const multi = planPublish(p, set({ snapshotIds: ["v1", "weg"] }), "2026-10-30"); + expect(multi.files[0].snapshotIds).toEqual(["v1"]); + const single = planPublish(p, set({ format: "pdf-single", snapshotIds: ["v1"] }), "2026-10-30"); + expect(single.files.map((f) => f.fileName).at(-1)).toBe("2026-14_Ansicht Süd.pdf"); + expect(planPublish(p, set({ format: "dwg" }), "2026-10-30").files[0].fileName).toBe("Baueingabe.dwg"); + }); + it("paperOverride/Massstab liegen im Plan", () => { + const plan = planPublish(proj(), set({ paperOverride: "a4", scaleOverride: 200 }), "2026-10-30"); + expect(plan.paperOverride).toBe("a4"); + expect(plan.scaleOverride).toBe(200); + }); +}); + +describe("publishOps", () => { + it("erhöht Revisionen, hängt Protokoll an; ohne bumpRevision bleiben Layouts unverändert", () => { + const p = proj(); + const plan = planPublish(p, set({ bumpRevision: true }), "2026-10-30"); + const q = applyOps(p, publishOps(p, set({ bumpRevision: true }), plan, "2026-10-30T10:00:00.000Z", "log-1")); + expect(q.layouts!.find((l) => l.id === "l1")!.revision).toBe("B"); + expect(q.layouts!.find((l) => l.id === "l2")!.revision).toBe("A"); + expect(q.layouts!.find((l) => l.id === "l3")!.revision).toBeUndefined(); + expect(q.publishLog).toHaveLength(1); + expect(q.publishLog![0]).toMatchObject({ id: "log-1", setId: "s1", setName: "Baueingabe", date: "2026-10-30T10:00:00.000Z" }); + expect(q.publishLog![0].sheets.map((s) => [s.number, s.revision])).toEqual([["201", "A"], ["101", "B"]]); + + const plan2 = planPublish(p, set(), "2026-10-30"); + const r = applyOps(p, publishOps(p, set(), plan2, "2026-10-30T10:00:00.000Z", "log-2")); + expect(r.layouts!.find((l) => l.id === "l1")!.revision).toBe("A"); + expect(r.publishLog).toHaveLength(1); + }); +}); diff --git a/src/export/publishSet.ts b/src/export/publishSet.ts new file mode 100644 index 00000000..1cc3f11b --- /dev/null +++ b/src/export/publishSet.ts @@ -0,0 +1,141 @@ +// Publikationssätze ([79]): welche Dateien ein Satz erzeugt, mit welchen Namen und Revisionsindizes, und +// die Ops, die Index und Protokoll im Projekt nachführen. Reine Logik ohne DOM — das Rendern der PDFs +// macht `publishRun.ts`. + +import type { Layout, LayoutPaperFormat, Project, PublishLogSheet, PublishSet } from "../model/types"; +import { findMaster, resolveTitleBlock } from "../model/layoutModel"; +import { fieldOps, patchItem } from "../core/opsBuild"; +import type { CoreOp } from "../core/ops"; + +/** Standard-Muster für Einzeldateien (je Blatt). */ +export const DEFAULT_NAME_PATTERN = "{Projektnummer}_{Blattnummer}_{Blattname}_{Index}"; + +export type PublishFormat = "pdf-multi" | "pdf-single" | "dxf" | "dwg"; + +/** Revisionsindex hochzählen: "" → A, A → B, Z → AA, 2 → 3, 09 → 10; sonst wird "2" angehängt. */ +export function nextRevision(rev: string | undefined): string { + const r = (rev ?? "").trim(); + if (r === "") return "A"; + if (/^[A-Z]+$/.test(r)) { + const c = r.split(""); + let i = c.length - 1; + while (i >= 0) { + if (c[i] === "Z") { + c[i] = "A"; + i--; + } else { + c[i] = String.fromCharCode(c[i].charCodeAt(0) + 1); + return c.join(""); + } + } + return "A" + c.join(""); + } + const m = /^(.*?)(\d+)$/.exec(r); + if (m) { + const n = String(Number(m[2]) + 1); + return m[1] + n.padStart(m[2].length, "0"); + } + return r + "2"; +} + +/** Dateiname aus Muster: `{Projektnummer} {Projekt} {Blattnummer} {Blattname} {Index} {Datum} {Satz}`; Unbekanntes/Leeres entfällt. */ +export function expandNamePattern(pattern: string, vars: Record): string { + const clean = (s: string) => s.replace(/[\\/:*?"<>|\u0000-\u001f]/g, "_").trim(); + const out = pattern + .replace(/\{([^{}]+)\}/g, (_m, k: string) => clean(vars[k] ?? "")) + .replace(/_{2,}/g, "_") + .replace(/^[\s_.-]+|[\s_.-]+$/g, ""); + return out || clean(vars.Satz ?? "") || "publikation"; +} + +export interface PublishPlanFile { + fileName: string; + /** Blätter dieser Datei in Reihenfolge (leer bei DXF: Papierbereiche des Projekts). */ + layoutIds: string[]; + /** Gespeicherte Ansichten, die als eigene Seiten in diese Datei kommen (nur PDF). */ + snapshotIds: string[]; + format: PublishFormat; +} + +export interface PublishPlan { + files: PublishPlanFile[]; + /** Blätter mit Nummer und dem Index, der in der Ausgabe steht (nach dem Hochzählen). */ + sheets: PublishLogSheet[]; + paperOverride?: LayoutPaperFormat; + scaleOverride?: number; + pdfLayers: boolean; + includeRevision: boolean; +} + +/** Die Layouts des Satzes in Satz-Reihenfolge (unbekannte ids entfallen). */ +export function setLayouts(project: Project, set: PublishSet): Layout[] { + const all = project.layouts ?? []; + return set.layoutIds.flatMap((id) => all.filter((l) => l.id === id)); +} + +/** Plant die Ausgabe: Dateien mit Namen, Blätter mit Nummer/Index (Index schon hochgezählt, wenn `bumpRevision`). */ +export function planPublish(project: Project, set: PublishSet, today: string): PublishPlan { + const includeRevision = set.includeRevision ?? true; + const bump = set.bumpRevision ?? false; + const format = (set.format as PublishFormat | undefined) ?? "pdf-multi"; + const layouts = setLayouts(project, set); + + const sheets = layouts.map((l) => { + const tb = resolveTitleBlock(project, l, findMaster(project, l)); + const revision = includeRevision ? (bump ? nextRevision(l.revision) : (l.revision ?? "")) : ""; + return { layoutId: l.id, number: tb.planNumber, name: l.name, revision }; + }); + const base = { + Projektnummer: project.projectNumber ?? "", + Projekt: project.name ?? "", + Datum: today, + Satz: set.name, + }; + const cad = format === "dxf" || format === "dwg"; + const ext = cad ? format : "pdf"; + const snaps = cad ? [] : (set.snapshotIds ?? []).flatMap((id) => (project.viewSnapshots ?? []).filter((v) => v.id === id)); + const pattern = set.namePattern || DEFAULT_NAME_PATTERN; + const files: PublishPlanFile[] = + format === "pdf-single" + ? [ + ...sheets.map((s) => ({ + fileName: `${expandNamePattern(pattern, { ...base, Blattnummer: s.number, Blattname: s.name, Index: s.revision })}.${ext}`, + layoutIds: [s.layoutId], + snapshotIds: [], + format, + })), + ...snaps.map((v) => ({ + fileName: `${expandNamePattern(pattern, { ...base, Blattnummer: "", Blattname: v.name, Index: "" })}.${ext}`, + layoutIds: [], + snapshotIds: [v.id], + format, + })), + ] + : [ + { + fileName: `${expandNamePattern(set.namePattern || "{Satz}", { ...base, Blattnummer: "", Blattname: "", Index: "" })}.${ext}`, + layoutIds: cad ? [] : sheets.map((s) => s.layoutId), + snapshotIds: snaps.map((v) => v.id), + format, + }, + ]; + return { + files, + sheets, + ...(set.paperOverride ? { paperOverride: set.paperOverride } : {}), + ...(set.scaleOverride ? { scaleOverride: set.scaleOverride } : {}), + pdfLayers: set.pdfLayers ?? true, + includeRevision, + }; +} + +/** Ops einer Publikation: Index je Blatt hochzählen (`bumpRevision`) und Protokolleintrag anhängen. */ +export function publishOps(project: Project, set: PublishSet, plan: PublishPlan, nowIso: string, logId: string): CoreOp[] { + const ops: CoreOp[] = []; + if (set.bumpRevision) { + for (const s of plan.sheets) ops.push(...patchItem(project, "layouts", s.layoutId, { revision: nextRevision(project.layouts?.find((l) => l.id === s.layoutId)?.revision) })); + } + const entry = { id: logId, setId: set.id, setName: set.name, date: nowIso, sheets: plan.sheets, files: plan.files.map((f) => f.fileName) }; + ops.push(...fieldOps(project, "publishLog", [...(project.publishLog ?? []), entry])); + return ops; +} diff --git a/src/i18n/de.ts b/src/i18n/de.ts index 7100c27b..48d1cee3 100644 --- a/src/i18n/de.ts +++ b/src/i18n/de.ts @@ -3040,6 +3040,52 @@ export const de = { "openings.empty": "Keine Fenster oder Türen im Projekt.", "openings.markAuto": "automatische Nummer, zum Festlegen eintippen", "openings.extAuto": "automatisch", + "layouts.revision.short": "Index", + "pdfLayers.other": "Übrige", + "pdfLayers.frame": "Rahmen und Titelblock", + "pdfLayers.sheetDrawing": "Blatt-Zeichnung", + "pdfLayers.legend": "Legende", + "pdfLayers.tables": "Tabellen", + "legend.add": "Legende", + "legend.defaultTitle": "Legende", + "legend.title": "Titel", + "legend.kind.hatch": "Schraffuren / Materialien", + "legend.kind.lineType": "Linientypen", + "legend.kind.category": "Kategorien", + "legend.entries": "Einträge", + "legend.auto": "automatisch", + "legend.manual": "festgehalten", + "legend.freeze": "Auswahl festhalten", + "legend.freeze.hint": "Die jetzt gezeigten Einträge fest übernehmen (folgt den Viewports nicht mehr)", + "legend.remove": "Legende entfernen", + "publish.title": "Publikation", + "publish.add": "Publikationssatz anlegen", + "publish.none": "Kein Publikationssatz. Mit + Blätter zu einem Satz bündeln.", + "publish.defaultName": "Neuer Satz", + "publish.projectNumber": "Projektnummer", + "publish.name": "Name", + "publish.format": "Ausgabe", + "publish.format.pdf-multi": "PDF, ein Dokument", + "publish.format.pdf-single": "PDF, je Blatt eine Datei", + "publish.format.dxf": "DXF mit Layouts", + "publish.format.dwg": "DWG mit Layouts", + "publish.sheets": "Blätter", + "publish.views": "Gespeicherte Ansichten", + "publish.pattern": "Dateiname", + "publish.pattern.hint": "Platzhalter: {Projektnummer} {Projekt} {Blattnummer} {Blattname} {Index} {Datum} {Satz}", + "publish.paper": "Papier", + "publish.scale": "Massstab 1:", + "publish.keep": "wie Blatt", + "publish.includeRevision": "Index im Titelblock und Dateinamen", + "publish.bumpRevision": "Index beim Publizieren erhöhen", + "publish.pdfLayers": "PDF-Ebenen (je Kategorie)", + "publish.run": "Publizieren", + "publish.delete": "Satz löschen", + "publish.log": "Publikationsprotokoll", + "publish.sheetsShort": "Blätter", + "publish.empty": "Der Satz enthält keine Blätter.", + "publish.done": "Publiziert (Dateien)", + "publish.failed": "Publikation fehlgeschlagen", } as const; export type TranslationKey = keyof typeof de; diff --git a/src/i18n/en.ts b/src/i18n/en.ts index f1b679c3..da3c3821 100644 --- a/src/i18n/en.ts +++ b/src/i18n/en.ts @@ -3026,4 +3026,50 @@ export const en: Record = { "openings.empty": "No windows or doors in the project.", "openings.markAuto": "automatic number, type to set your own", "openings.extAuto": "automatic", + "layouts.revision.short": "Rev.", + "pdfLayers.other": "Other", + "pdfLayers.frame": "Frame and title block", + "pdfLayers.sheetDrawing": "Sheet drawing", + "pdfLayers.legend": "Legend", + "pdfLayers.tables": "Tables", + "legend.add": "Legend", + "legend.defaultTitle": "Legend", + "legend.title": "Title", + "legend.kind.hatch": "Hatches / materials", + "legend.kind.lineType": "Line types", + "legend.kind.category": "Categories", + "legend.entries": "Entries", + "legend.auto": "automatic", + "legend.manual": "fixed", + "legend.freeze": "Fix selection", + "legend.freeze.hint": "Keep the entries shown now (no longer follows the viewports)", + "legend.remove": "Remove legend", + "publish.title": "Publishing", + "publish.add": "Add publication set", + "publish.none": "No publication set. Use + to bundle sheets into a set.", + "publish.defaultName": "New set", + "publish.projectNumber": "Project number", + "publish.name": "Name", + "publish.format": "Output", + "publish.format.pdf-multi": "PDF, one document", + "publish.format.pdf-single": "PDF, one file per sheet", + "publish.format.dxf": "DXF with layouts", + "publish.format.dwg": "DWG with layouts", + "publish.sheets": "Sheets", + "publish.views": "Saved views", + "publish.pattern": "File name", + "publish.pattern.hint": "Placeholders: {Projektnummer} {Projekt} {Blattnummer} {Blattname} {Index} {Datum} {Satz}", + "publish.paper": "Paper", + "publish.scale": "Scale 1:", + "publish.keep": "as sheet", + "publish.includeRevision": "Revision in title block and file name", + "publish.bumpRevision": "Increase revision when publishing", + "publish.pdfLayers": "PDF layers (per category)", + "publish.run": "Publish", + "publish.delete": "Delete set", + "publish.log": "Publication log", + "publish.sheetsShort": "sheets", + "publish.empty": "The set contains no sheets.", + "publish.done": "Published (files)", + "publish.failed": "Publishing failed", }; diff --git a/src/model/layoutModel.test.ts b/src/model/layoutModel.test.ts index bbf5baff..22454cb4 100644 --- a/src/model/layoutModel.test.ts +++ b/src/model/layoutModel.test.ts @@ -211,6 +211,12 @@ describe("resolveTitleBlock — Master-Vererbung + Defaults", () => { expect(tb.date).toBe("2026-07-07"); expect(tb.author).toBe(""); expect(tb.planNumber).toBe("01"); // nicht in project.layouts → erste Nummer + expect(tb.revision).toBeUndefined(); + }); + + it("[79] Revisionsindex des Blatts steht im Titelblock", () => { + const l = { ...createLayout("l1", "EG", "a4", "portrait"), revision: "C" }; + expect(resolveTitleBlock(p, l, undefined, "2026-07-07").revision).toBe("C"); }); it("Plannummer: laufend nach Reihenfolge, eigene Nummer übersteuert", () => { diff --git a/src/model/layoutModel.ts b/src/model/layoutModel.ts index 3727fbee..1f3843a6 100644 --- a/src/model/layoutModel.ts +++ b/src/model/layoutModel.ts @@ -517,6 +517,8 @@ export interface ResolvedTitleBlock { author: string; /** Plannummer: `Layout.planNumber`, sonst laufende Nummer des Blatts im Projekt ("01", "02" …). */ planNumber: string; + /** Revisionsindex des Blatts (`Layout.revision`, [79]); fehlt = keiner. */ + revision?: string; } /** @@ -538,7 +540,8 @@ export function resolveTitleBlock( master: master ? { titleBlock: master.titleBlock } : null, today, }; - return documentFor(project).queryRoot("layoutTitleBlock", JSON.stringify(arg)); + const tb = documentFor(project).queryRoot("layoutTitleBlock", JSON.stringify(arg)); + return layout.revision ? { ...tb, revision: layout.revision } : tb; } /** diff --git a/src/model/richProject.testing.ts b/src/model/richProject.testing.ts index 53db5b5c..effa53ca 100644 --- a/src/model/richProject.testing.ts +++ b/src/model/richProject.testing.ts @@ -125,7 +125,7 @@ const OPTIONAL_KEYS = [ "formatVersion", "textStyles", "ceilingTypes", "roofTypes", "blockDefs", "doorTypes", "windowTypes", "stairTypes", "pens", "penSets", "activePenSetId", "customPalettes", "builtinPaletteBanks", "roomProgram", "roomProgramTolerance", "parcelArea", "sunStudy", "siteRules", "scaleLineWeights", "ceilings", "roofs", "openings", "stairs", "rooms", "context", "extrudedSolids", "columns", "groups", - "parametricWalls", "overrideRules", "viewSnapshots", "viewSnapshotFolders", "layouts", "masterLayouts", "layoutFolders", + "parametricWalls", "overrideRules", "viewSnapshots", "viewSnapshotFolders", "layouts", "masterLayouts", "layoutFolders", "publishSets", "publishLog", "projectNumber", "referenceElevationMasl", "geoAnchor", ] as const satisfies readonly (keyof Project)[]; diff --git a/src/model/types.generated.ts b/src/model/types.generated.ts index 6c38816b..946eb4d6 100644 --- a/src/model/types.generated.ts +++ b/src/model/types.generated.ts @@ -1515,6 +1515,13 @@ export type Layout = { * nicht im Layout (bis Format 2: `annotations`, s. `project_format::migrate_layout_annotations`). */ viewports: Array; + /** + * Revisionsindex des Blatts (z. B. "A", "B" oder "2"); steht im Titelblock, wird beim + * Publizieren eines Satzes optional hochgezählt ([79]). + */ + revision?: string; + /** Grafische Legenden auf dem Blatt ([82]). */ + legends?: Array; /** Lebendige Tabellen auf dem Blatt ([111]); fehlt = keine. */ tables?: Array; }; @@ -1539,6 +1546,27 @@ export type LayoutFolder = { kind?: "layout" | "master"; }; +/** + * Grafische Legende auf einem Layout-Blatt ([82]): listet Schraffuren/Materialien, Linientypen und/oder + * Kategorien der gezeigten Viewports (`manualKeys` leer) oder einer Handauswahl, mit Muster und Name. + */ +export type LayoutLegend = { + id: string; + /** Linke Kante auf dem Blatt (mm). */ + xMm: number; + /** Obere Kante auf dem Blatt (mm). */ + yMm: number; + /** Titel; fehlt = „Legende". */ + title?: string; + /** Gezeigte Arten: "hatch", "lineType", "category"; fehlt = nur Schraffuren. */ + kinds?: Array; + /** + * Handauswahl als Schlüssel "hatch:", "lineType:", "category:"; leer/fehlt = automatisch + * aus den Viewports des Blatts. + */ + manualKeys?: Array; +}; + /** Ausrichtung eines Layout-Blatts. */ export type LayoutOrientation = "portrait" | "landscape"; @@ -2279,6 +2307,12 @@ export type Project = { * gültig bleiben (Default: leer → alle Layouts auf Wurzelebene). */ layoutFolders?: Array; + /** Publikationssätze ([79]). */ + publishSets?: Array; + /** Publikationsprotokoll ([79]), neueste zuletzt. */ + publishLog?: Array; + /** Projektnummer für Titelblock und Dateinamen ([79]). */ + projectNumber?: string; /** * Referenzhöhe des Erdgeschosses in Metern über Meer (m ü. M.), editierbar * im Einstellungs-Fenster. Optional, damit bestehende Projekte ohne diesen @@ -2316,6 +2350,50 @@ export type Project = { }; }; +/** Protokolleintrag einer Publikation ([79]): Datum, Blätter mit Revision, erzeugte Dateien. */ +export type PublishLogEntry = { + id: string; + setId: string; + setName: string; + /** ISO-Zeitstempel. */ + date: string; + sheets: Array; + files: Array; +}; + +/** Ein Blatt im Publikationsprotokoll. */ +export type PublishLogSheet = { layoutId: string; number: string; name: string; revision: string }; + +/** + * Publikationssatz ([79]): benannte Menge von Layouts (und optional Ansichten) mit Ausgabe-Einstellungen. + */ +export type PublishSet = { + id: string; + name: string; + /** Layouts des Satzes in Ausgabe-Reihenfolge. */ + layoutIds: Array; + /** Gespeicherte Ansichten, die zusätzlich als eigene Seiten ausgegeben werden. */ + snapshotIds?: Array; + /** + * "pdf-multi" (ein PDF, Standard), "pdf-single" (je Blatt eine Datei), "dxf" (DXF mit Layouts). + */ + format?: string; + /** + * Dateinamen-Muster mit {Projektnummer} {Projekt} {Blattnummer} {Blattname} {Index} {Datum} {Satz}. + */ + namePattern?: string; + /** Papierformat-Übersteuerung für alle Blätter des Satzes. */ + paperOverride?: LayoutPaperFormat; + /** Massstab-Übersteuerung (1:N) für alle Viewports des Satzes. */ + scaleOverride?: number; + /** Revisionsindex im Titelblock/Dateinamen ausgeben (Standard ja). */ + includeRevision?: boolean; + /** Revisionsindex je Blatt beim Publizieren erhöhen (A→B, 1→2). */ + bumpRevision?: boolean; + /** PDF-Ebenen (Optional Content) je Kategorie. */ + pdfLayers?: boolean; +}; + /** * Referenzlinien-Regel: setzt die `referenceLine`-Eigenschaft bei passenden * Wänden einheitlich (Vectorworks-Stil). diff --git a/src/panels/LayoutsPanel.tsx b/src/panels/LayoutsPanel.tsx index e8d8222d..4be7ef9d 100644 --- a/src/panels/LayoutsPanel.tsx +++ b/src/panels/LayoutsPanel.tsx @@ -34,6 +34,7 @@ import { type LayoutSizeStart, type NewLayoutStart, } from "../ui/LayoutCreateDialogs"; +import { PublishSection } from "./PublishSection"; import { t } from "../i18n"; // ── Baum-Icons (inline-SVG im Panel-Stil: 14px, stroke currentColor 1.4) ────── @@ -873,6 +874,8 @@ export function LayoutsPanel() { )} + + {dialog === "layout" && ( x !== id); +} + +function SetEditor({ set }: { set: PublishSet }) { + const host = usePanelHost(); + const project = host.project; + const patch = (p: Partial>) => host.onPatchPublishSet(set.id, p); + const layouts = project.layouts ?? []; + const snapshots = project.viewSnapshots ?? []; + const format = set.format ?? "pdf-multi"; + const pdf = format === "pdf-multi" || format === "pdf-single"; + return ( +
+ + +
+
{t("publish.sheets")}
+ {layouts.length === 0 &&
{t("layouts.tree.empty")}
} + {layouts.map((l) => ( + + ))} +
+ {pdf && snapshots.length > 0 && ( +
+
{t("publish.views")}
+ {snapshots.map((v) => ( + + ))} +
+ )} + +
{t("publish.pattern.hint")}
+ {pdf && ( +
+ + +
+ )} + + + {pdf && ( + + )} +
+ ); +} + +export function PublishSection() { + const host = usePanelHost(); + const project = host.project; + const sets = project.publishSets ?? []; + const log = (project.publishLog ?? []).slice(-LOG_SHOWN).reverse(); + const [open, setOpen] = useState(null); + return ( +
+
+ {t("publish.title")} + + + +
+ + {sets.length === 0 &&
{t("publish.none")}
} + {sets.map((s) => ( +
+
setOpen(open === s.id ? null : s.id)}> + + {s.name} + {s.layoutIds.length} + + + +
+ {open === s.id && } +
+ ))} + {log.length > 0 && ( +
+
{t("publish.log")}
+ {log.map((e) => ( +
`${s.number} ${s.name} ${s.revision}`.trim()).join("\n")}> + {e.date.slice(0, 16).replace("T", " ")} · {e.setName} · {e.sheets.length} {t("publish.sheetsShort")} + {e.sheets.some((s) => s.revision) ? ` · ${t("layouts.revision.short")} ${[...new Set(e.sheets.map((s) => s.revision).filter(Boolean))].join("/")}` : ""} +
+ ))} +
+ )} +
+ ); +} diff --git a/src/panels/host.ts b/src/panels/host.ts index 4a7bd745..7b83da72 100644 --- a/src/panels/host.ts +++ b/src/panels/host.ts @@ -29,6 +29,7 @@ import type { LayoutPaperFormat, LineStyle, MasterLayout, + PublishSet, Project, SiaCategory, SliceTermination, @@ -749,6 +750,18 @@ export interface PanelHostValue { * werden verworfen (No-op). */ onMoveFolderToFolder: (folderId: string, parentId: string | null) => void; + + // ── Publikationssätze ([79]) ──────────────────────────────────────────── + /** Legt einen Publikationssatz mit allen Layouts an; liefert die Id. */ + onAddPublishSet: () => string; + /** Ändert Felder eines Satzes (Name, Layouts, Format, Namensmuster, Übersteuerungen …). */ + onPatchPublishSet: (id: string, patch: Partial>) => void; + /** Löscht einen Satz. */ + onDeletePublishSet: (id: string) => void; + /** Erzeugt und speichert alle Dateien des Satzes; zählt Indizes hoch und protokolliert. */ + onPublishSet: (id: string) => void; + /** Setzt die Projektnummer (Dateinamen-Muster `{Projektnummer}`). */ + onSetProjectNumber: (value: string) => void; } /** Startwerte eines neuen Layouts (aus dem „Neues Layout"-Dialog). */ diff --git a/src/state/publishActions.ts b/src/state/publishActions.ts new file mode 100644 index 00000000..39d4abdb --- /dev/null +++ b/src/state/publishActions.ts @@ -0,0 +1,47 @@ +// Publikationssätze ([79]) in der Hülle: Satz anlegen/ändern/löschen als Ops, Satz ausführen = Dateien erzeugen, +// speichern (mehrere als ZIP), Revisionsindex erhöhen und ins Protokoll schreiben (ein Undo-Schritt). + +import { fieldOps, type CoreOp } from "../core"; +import type { Project, PublishSet } from "../model/types"; +import { planPublish, publishOps } from "../export/publishSet"; +import { bundlePublished, runPublish } from "../export/publishRun"; +import { saveBinaryFile } from "../native/saveFile"; +import { getState } from "./appStore"; +import { t } from "../i18n"; + +export function addPublishSetOps(p: Project, id: string): CoreOp[] { + const set: PublishSet = { id, name: t("publish.defaultName"), layoutIds: (p.layouts ?? []).map((l) => l.id) }; + return fieldOps(p, "publishSets", [...(p.publishSets ?? []), set]); +} + +export function patchPublishSetOps(p: Project, id: string, patch: Partial>): CoreOp[] { + return fieldOps(p, "publishSets", (p.publishSets ?? []).map((s) => (s.id === id ? { ...s, ...patch } : s))); +} + +export function deletePublishSetOps(p: Project, id: string): CoreOp[] { + return fieldOps(p, "publishSets", (p.publishSets ?? []).filter((s) => s.id !== id)); +} + +/** Führt einen Satz aus; liefert die Ops (Index + Protokoll), wenn gespeichert wurde, sonst `null`. */ +export async function publishSet(project: Project, setId: string): Promise { + const set = (project.publishSets ?? []).find((s) => s.id === setId); + if (!set) return null; + const now = new Date(); + const plan = planPublish(project, set, now.toISOString().slice(0, 10)); + if (plan.files.length === 0) { + getState().notify(t("publish.empty"), "error"); + return null; + } + try { + const files = await runPublish(project, set, plan); + const bundle = await bundlePublished(files, `${set.name}.zip`); + if (!bundle) return null; + const saved = await saveBinaryFile(bundle.bytes, bundle.fileName, bundle.mime); + if (!saved) return null; + getState().notify(`${t("publish.done")}: ${files.length}`, "info"); + return publishOps(project, set, plan, now.toISOString(), `pub-${now.getTime()}`); + } catch (err) { + getState().notify(`${t("publish.failed")}: ${err instanceof Error ? err.message : String(err)}`, "error"); + return null; + } +} diff --git a/src/state/usePanelHostBase.ts b/src/state/usePanelHostBase.ts index 5f7ed8f5..c8ce7ed1 100644 --- a/src/state/usePanelHostBase.ts +++ b/src/state/usePanelHostBase.ts @@ -55,6 +55,7 @@ import { createSheetLevel, } from "../model/layoutModel"; import { folderPdfBytes } from "../export/layoutPdf"; +import { addPublishSetOps, deletePublishSetOps, patchPublishSetOps, publishSet } from "./publishActions"; import { saveBinaryFile } from "../native/saveFile"; import type { useProjectActions } from "./useProjectActions"; import type { useSelectionState } from "./useSelectionState"; @@ -1447,6 +1448,19 @@ export function usePanelHostBase(opts: { fieldOps(p, "layoutFolders", moveFolderToFolder(p.layoutFolders ?? [], folderId, parentId)), ); }, + onAddPublishSet: () => { + const id = `pubset-${Date.now()}`; + applyChange((p) => addPublishSetOps(p, id)); + return id; + }, + onPatchPublishSet: (id, patch) => applyChange((p) => patchPublishSetOps(p, id, patch), `pubset-${id}`), + onSetProjectNumber: (value) => applyChange((p) => fieldOps(p, "projectNumber", value.trim() ? value : undefined), "projectNumber"), + onDeletePublishSet: (id) => applyChange((p) => deletePublishSetOps(p, id)), + onPublishSet: (id) => { + void publishSet(project, id).then((ops) => { + if (ops && ops.length > 0) applyChange(ops); + }); + }, }; return value; // setProject-Closures sind stabil genug; Neuberechnung bei project/active. diff --git a/src/ui/LayoutSheet.tsx b/src/ui/LayoutSheet.tsx index 5e0ac243..ddc6f869 100644 --- a/src/ui/LayoutSheet.tsx +++ b/src/ui/LayoutSheet.tsx @@ -15,6 +15,7 @@ import { useEffect, useMemo, useRef, useState } from "react"; import type { PointerEvent as ReactPointerEvent, ReactNode, RefObject } from "react"; import type { Layout, + LayoutLegend, LayoutOrientation, LayoutPaperFormat, LayoutTable, @@ -27,6 +28,8 @@ import { createTable, generatePlan, PX_PER_M, sheetTables, TABLE_SOURCES, tableS import type { TableOut } from "../core"; import { SheetTableHud } from "./SheetTableHud"; import { planToPrintSvg } from "../export/planToPrintSvg"; +import { legendPlan, legendPrintSvg } from "../export/legendSvg"; +import { legendBox, legendEntries, legendKeysOfViewports, type LegendKind } from "../analysis/legend"; import { effectiveSheetSizeMm, findMaster, @@ -105,6 +108,31 @@ export function ViewportPlanSvg({ return ; } +/** + * Legende ([82]) als verschachteltes `` in Blatt-mm: derselbe Weg wie im PDF (`legendPlan`, Schraffur-Muster + * und Schrift vom Kern); folgt dem Projekt live, weil sie bei jeder Änderung neu aufgebaut wird. + */ +export function LegendSvg({ project, layout, legend }: { project: Project; layout: Layout; legend: LayoutLegend }) { + const ref = useRef(null); + useEffect(() => { + const el = ref.current; + if (!el) return; + try { + const lp = legendPlan(project, layout, legend); + if (!lp) return void el.replaceChildren(); + const svg = legendPrintSvg(lp); + svg.setAttribute("x", String(lp.xMm)); + svg.setAttribute("y", String(lp.yMm)); + svg.setAttribute("width", String(lp.widthMm)); + svg.setAttribute("height", String(lp.heightMm)); + el.replaceChildren(svg); + } catch { + el.replaceChildren(); + } + }, [project, layout, legend]); + return ; +} + /** * Schlichtes Schriftfeld unten rechts (mm-Koordinaten des Blatts) mit den aufgelösten Master-Werten — * dieselbe Anmutung wie der PDF-Titelblock. @@ -116,7 +144,7 @@ export function TitleBlockSvg({ orientation, }: { sheet: { w: number; h: number }; - tb: { projectName: string; sheetName: string; scale: string; date: string; author: string; planNumber: string }; + tb: { projectName: string; sheetName: string; scale: string; date: string; author: string; planNumber: string; revision?: string }; paper: LayoutPaperFormat; orientation: LayoutOrientation; }) { @@ -140,6 +168,11 @@ export function TitleBlockSvg({ {clip(tb.sheetName, 36)} + {tb.revision && ( + + {t("layouts.revision.short")} {tb.revision} + + )} {tb.author && ( {clip(tb.author, 40)} @@ -170,6 +203,12 @@ export interface LayoutSheetHandlers { onRemoveViewport: (viewportId: string) => void; /** Fügt einen Viewport (gebunden an `snapshotId`) mit gegebener Geometrie an. */ onAddViewport: (snapshotId: string, init: Partial>) => void; + /** Legt eine Legende ([82]) an; liefert deren Id. */ + onAddLegend: (init: Omit) => string; + /** Ändert Felder einer Legende (Titel, Lage, Arten, Handauswahl). */ + onPatchLegend: (legendId: string, patch: Partial>) => void; + /** Entfernt eine Legende. */ + onRemoveLegend: (legendId: string) => void; /** Legt eine lebendige Tabelle auf dem Blatt an ([111]). */ onAddTable: (table: LayoutTable) => void; /** Ändert eine Tabelle (Teil-Patch; gleiche `coalesceKey` fassen sich zu einem Undo-Schritt zusammen). */ @@ -245,6 +284,7 @@ export function LayoutSheetPane({ children: (props: SheetPlanProps) => ReactNode; }) { const [selectedId, setSelectedId] = useState(null); + const [selectedLegendId, setSelectedLegendId] = useState(null); const [selectedTableId, setSelectedTableId] = useState(null); // Tabellen-Verschiebung läuft (Versatz in mm), sonst null. const [tableDrag, setTableDrag] = useState<{ id: string; dx: number; dy: number } | null>(null); @@ -263,6 +303,7 @@ export function LayoutSheetPane({ const drawBorder = master ? master.border ?? true : false; const snapshots = project.viewSnapshots ?? []; const selectedVp = layout.viewports.find((v) => v.id === selectedId) ?? null; + const selectedLegend = (layout.legends ?? []).find((l) => l.id === selectedLegendId) ?? null; // Lebendige Tabellen: folgen dem Modell (jede Projekt-Änderung rechnet neu). const tables = useMemo(() => sheetTables(project, layout.id), [project, layout.id]); const layoutTables = layout.tables ?? []; @@ -271,6 +312,7 @@ export function LayoutSheetPane({ // Gelöschter Viewport / anderes Blatt → Auswahl und laufendes Platzieren verwerfen. useEffect(() => { setSelectedId(null); + setSelectedLegendId(null); setSelectedTableId(null); setPlacing(false); setPendingRect(null); @@ -444,6 +486,17 @@ export function LayoutSheetPane({ ); })} + {(layout.legends ?? []).map((lg) => { + const box = legendBox(project, layout, lg); + return ( + + + {lg.id === selectedLegendId && ( + + )} + + ); + })} {/* Lebendige Tabellen ([111]): Text + Linien aus dem Kern, über den Viewports. */} {tables.map((tb) => { const off = tableDrag && tableDrag.id === tb.id ? tableDrag : null; @@ -563,17 +616,25 @@ export function LayoutSheetPane({ const onSheetSelect = (sel: PlanSelection) => { if (!toolInputActive && isEmptyPick(sel)) { const mm = sheetModelToMm(sel.model); - // Tabelle zuerst (liegt über den Viewports), dann Viewport. + // Tabelle zuerst (liegt über den Viewports), dann Legende, dann Viewport. const tableHit = [...tables].reverse().find((tb) => { const src = layoutTables.find((x) => x.id === tb.id); return src && mm.xMm >= src.xMm && mm.xMm <= src.xMm + tb.widthMm && mm.yMm >= src.yMm && mm.yMm <= src.yMm + Math.max(tb.heightMm, 4); }); setSelectedTableId(tableHit ? tableHit.id : null); - const hit = tableHit ? null : pickViewport(layout.viewports, mm.xMm, mm.yMm, 0); + const lg = tableHit + ? undefined + : [...(layout.legends ?? [])].reverse().find((l) => { + const b = legendBox(project, layout, l); + return mm.xMm >= b.xMm && mm.xMm <= b.xMm + b.widthMm && mm.yMm >= b.yMm && mm.yMm <= b.yMm + b.heightMm; + }); + setSelectedLegendId(lg ? lg.id : null); + const hit = tableHit || lg ? null : pickViewport(layout.viewports, mm.xMm, mm.yMm, 0); setSelectedId(hit ? hit.id : null); } else { setSelectedId(null); setSelectedTableId(null); + setSelectedLegendId(null); } onPlanSelect(sel); }; @@ -604,6 +665,19 @@ export function LayoutSheetPane({ > + {t("layouts.placeViewport")} + { + const n = parseFloat(e.target.value); + if (Number.isFinite(n)) set(n); + }} + /> + ); + return ( +
+
{t("legend.add")}
+ +
+ X / Y mm + + {num(legend.xMm, (xMm) => onPatch({ xMm }))} + {num(legend.yMm, (yMm) => onPatch({ yMm }))} + +
+ {LEGEND_KINDS.map((k) => ( + + ))} +
+ {t("legend.entries")}: {legendEntries(project, layout, legend).length} + {manual ? ` · ${t("legend.manual")}` : ` · ${t("legend.auto")}`} +
+
+ {manual ? ( + + ) : ( + + )} + +
+
+ ); +}