[79][80][82] Publikationssätze, PDF-Ebenen und grafische Legenden auf Layout-Blättern
Publikationssätze: Satz aus Layouts/Ansichten mit Ausgabe (PDF ein Dokument oder je Blatt, DXF/DWG mit Layouts), Dateinamen-Muster, Papier-/Massstab-Übersteuerung, Revisionsindex (im Titelblock, optional hochgezählt) und Protokoll. PDF-Ebenen: Optional Content selbst geschrieben (jsPDF kennt keine), je Kategorie/Viewport, Rahmen, Blatt-Zeichnung, Legende. Legenden: Material/Schraffur, Linientyp, Kategorie aus den Viewports (oder Handauswahl), Muster vom Kern-Generator. Modellfelder nur in Rust (optional): publishSets, publishLog, projectNumber, Layout.revision, Layout.legends.
This commit is contained in:
27 files changed
+1979
-68
No files matched your search
+132
-59
@@ -12,12 +12,17 @@
|
||||
|
||||
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 { collectVisibleCodes } from "../model/types";
|
||||
import {
|
||||
effectiveSheetSizeMm,
|
||||
findMaster,
|
||||
sheetSizeMm,
|
||||
findSnapshot,
|
||||
folderPdfPages,
|
||||
resolveTitleBlock,
|
||||
@@ -40,6 +45,7 @@ function drawTitleBlock(
|
||||
tb: ResolvedTitleBlock,
|
||||
paper: string,
|
||||
orientation: string,
|
||||
showRevision: boolean,
|
||||
): void {
|
||||
const boxW = 70;
|
||||
const boxH = 30;
|
||||
@@ -65,6 +71,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);
|
||||
@@ -113,12 +124,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<void>): Promise<void> | 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<void> {
|
||||
const { layout, widthMm, heightMm } = page;
|
||||
|
||||
@@ -130,85 +165,123 @@ 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<string>) => generatePlan(project, snap.activeLevelId, visible, undefined, snap.detail, false, false, true, scaleN, true);
|
||||
const draw = async (plan: ReturnType<typeof planOf>, 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);
|
||||
});
|
||||
}
|
||||
|
||||
// 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<jsPDF | null> {
|
||||
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<jsPDF | null> {
|
||||
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<jsPDF | null> {
|
||||
return buildPagesPdf(project, folderPdfPages(project, folderId));
|
||||
}
|
||||
|
||||
/** Baut das Ordner-PDF als Bytes (`null`, wenn nichts zu exportieren war). Speichern macht die Hülle. */
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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<typeof legendDrawings>["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;
|
||||
}
|
||||
@@ -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"]]]);
|
||||
});
|
||||
});
|
||||
@@ -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<T>(name: string, fn: () => T | Promise<T>): Promise<T>;
|
||||
/** 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<string, string>(); // Name → Ressourcen-Schlüssel
|
||||
const oids = new Map<string, number>(); // 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<string>,
|
||||
otherName: string,
|
||||
): { name: string; codes: Set<string> }[] {
|
||||
const out: { name: string; codes: Set<string> }[] = [];
|
||||
const known = new Set<string>();
|
||||
const walk = (c: LayerCategory, into: Set<string>) => {
|
||||
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<string>();
|
||||
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;
|
||||
}
|
||||
@@ -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<PublishedFile> {
|
||||
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<PublishedFile[]> {
|
||||
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<PublishedFile | null> {
|
||||
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" };
|
||||
}
|
||||
@@ -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>): 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>): 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);
|
||||
});
|
||||
});
|
||||
@@ -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, string>): 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;
|
||||
}
|
||||
Reference in new issue
Block a user