[323] CLI: Befehl sheet (Layout-Blatt/Präsentationsblatt/Plakat als SVG, headless); Präsentationsplan-Rahmen mit 8 mm Rand (Achskreise/Gesamtmass oben nicht mehr abgeschnitten); Review-Bilder

This commit is contained in:
Claude committed 2026-11-20 18:49:39 +00:00
1 parent 596a03a397
commit b5b7d52d0d
15 files changed
+379 -32

No files matched your search

+48
View File
@@ -35,6 +35,9 @@
// [--scale 200] [--hatch] [--color] [--format svg|json|dxf|dxfbin|dwg] [--out axo.svg]
// [266] 3D-Dokument: Vektor-Axonometrie/-Perspektive mit verdeckten Kanten aus dem Kern
// (Linienzeichnung, Silhouette kräftig, Flächen nach Lage grau; ohne GPU)
// dossier-cli <projekt.obp> sheet [--name "Blatt"|--index N|--list] [--create-presentation [--poster poster-a0-portrait] [--scale 200]] --out blatt.svg
// [323] Layout-Blatt (Viewports, Schriftfeld/Plakat-Kopfzeile, Tabellen) wie der PDF-Export der App, als SVG;
// --create-presentation legt vorher das Präsentationsblatt (bzw. Plakat) an wie der Befehl `praesentationsplan`
// dossier-cli <projekt.obp> ifc [--ebkph] [--ebenen] [--kontext] [--entourage] (IFC mit eBKP-H-Hauptgruppen bzw. Modell-Ebenen als Klassifikation; --kontext: Gelände/Nachbarn mitgeben; --entourage: Person/Velo/Auto als Proxy, Möbel gehen immer als IfcFurniture)
// --schema 4|2x3: IFC4 (Standard) oder IFC2x3 (Coordination View 2.0)
// dossier-cli <projekt.obp> dxf [--binary] [--scale 100] [--dim-unit cm] [--layout]|dwg|ifc|step|obj [--no-mtl]|stl|glb|gltf|schedule [--openings|--elements|--rooms] [--format json|csv|svg|pdf]|kennzahlen [--sia416] [--ivhb] [--nachweis] [--wohnungsspiegel] [--format json|csv|svg|pdf] [--agsf m2] [--gruenflaeche m2] [--agf-basis gf|ngf|nf] [--untergeschosse]|raumprogramm [--import tabelle] [--sheet name|nr] [--mode replace|append] [--tolerance %] [--generate] [--format json|csv|svg|pdf] [--save projekt.obp]|sun [--level EG] [--out datei]
@@ -205,6 +208,12 @@ import {
buildCyclesPackage,
runCyclesRender,
CyclesMissingError,
buildLayoutSvg,
presentationSheetLabels,
presentationDefaults,
presentationSheetOps,
posterExtrasDefault,
fittingPresentationScale,
} from "../core";
import type { BlenderHost, CyclesHost, ExportView, Filter3d, Project, RenderMode, RenderPackage, RenderViewPreset, TextureLoader, ViewTemplate } from "../core";
import { serveStdio } from "./mcp";
@@ -1267,6 +1276,45 @@ async function execute(project: Project, file: string, command: string, rest: st
out(args, planToSvgString(plan, { scaleDenominator: tv.scale, hatch: args.flags.has("hatch") && args.flags.get("hatch") !== "false" }), `${lvl.name}.svg`);
return 0;
}
case "sheet":
case "layout": {
// [323] Layout-Blatt als SVG (Viewports, Schriftfeld/Kopfzeile, Tabellen) über denselben Weg wie der PDF-Export der App.
const target = args.flags.get("out");
if (target && /\.pdf$/i.test(target)) fail("sheet: PDF braucht ein DOM (jsPDF/svg2pdf, nur App/Browser) — headless als .svg ausgeben");
let sheetProject = project;
let pickId: string | undefined;
if (args.flags.has("create-presentation")) {
const poster = args.flags.get("poster");
const base = presentationDefaults(project);
const sc = args.flags.get("scale");
const o = { ...base, ...(poster && poster !== "true" ? { poster, extras: posterExtrasDefault(project) } : {}), ...(sc ? { scale: Number(sc) } : {}) };
const format = `${o.paper.toUpperCase()} ${o.orientation === "landscape" ? "quer" : "hoch"}`;
const res = withDocument(project, () => presentationSheetOps(project, o, presentationSheetLabels(format), "cli"));
if (!res) fail("sheet: kein Geschoss mit Inhalt — Präsentationsblatt nicht erzeugt");
if (!res.plan.fits) fail(`sheet: Inhalt passt bei 1:${res.plan.scale} nicht aufs Blatt (grösseren Nenner wählen: --scale ${fittingPresentationScale(project, o) ?? "…"})`);
sheetProject = applyOps(project, res.ops);
pickId = res.layoutId;
process.stderr.write(`Präsentationsblatt angelegt: ${res.layoutIds.join(", ")} (Massstab 1:${res.plan.scale})\n`);
}
const layouts = sheetProject.layouts ?? [];
if (args.flags.has("list")) {
layouts.forEach((l, i) => process.stdout.write(`${i + 1}\t${l.id}\t${l.name}\t${l.paper} ${l.orientation}\t${l.viewports.length} Viewports\n`));
return 0;
}
const name = args.flags.get("name");
const idx = args.flags.get("index");
let found: (typeof layouts)[number] | undefined = layouts[0];
if (name && name !== "true") found = layouts.find((l) => l.id === name || l.name.toLowerCase() === name.toLowerCase());
else if (idx && idx !== "true") found = layouts[Number(idx) - 1];
else if (pickId) found = layouts.find((l) => l.id === pickId);
if (!found) fail(`Blatt nicht gefunden: ${name ?? idx ?? "(erstes)"} (vorhanden: ${layouts.map((l) => l.name).join(", ") || "keine"})`);
const layout = found;
const scaleFlag = args.flags.get("scale");
const res = await withDocument(sheetProject, () => buildLayoutSvg(sheetProject, layout, { scaleOverride: !args.flags.has("create-presentation") && scaleFlag && scaleFlag !== "true" ? Number(scaleFlag) : undefined }));
for (const w of res.warnings) process.stderr.write(`Warnung: ${w}\n`);
out(args, res.svg, `${layout.name}.svg`);
return 0;
}
case "axo": {
// [266] 3D-Dokument aus dem Kern: Vorgabe (`--view`, `--projection`), Kamera-Element (`--camera`) oder Ausschnitt (`--snapshot`).
const f = args.flags;
+66
View File
@@ -0,0 +1,66 @@
// [323] dossier-cli sheet: Layout-Blatt als SVG (Viewports, Schriftfeld, Tabellen) und Präsentationsblatt/Plakat headless anlegen.
import { beforeAll, describe, expect, it, vi } from "vitest";
import { existsSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { run } from "./main";
import { makeTmpDir } from "../test/tmpDir";
const dir = makeTmpDir("dossier-sheet-");
beforeAll(() => {
process.env.DOSSIER_WASM_DIR = join(process.cwd(), "src", "engine");
});
async function quiet<T>(fn: () => Promise<T>): Promise<{ code: T; err: string }> {
const chunks: string[] = [];
const spy = vi.spyOn(process.stderr, "write").mockImplementation((c) => (chunks.push(String(c)), true));
try {
return { code: await fn(), err: chunks.join("") };
} finally {
spy.mockRestore();
}
}
describe("dossier-cli sheet", () => {
it("exportiert das Präsentationsblatt des Wettbewerb-Beispiels mit Viewports und Schriftfeld", async () => {
const out = join(dir, "pres.svg");
const r = await quiet(() => run([":wettbewerb", "sheet", "--name", "Präsentationsplan", "--out", out]));
expect(r.code).toBe(0);
const svg = readFileSync(out, "utf8");
expect(svg).toContain('viewBox="0 0 841 594"');
// Neun Viewports (3 Geschosse, 4 Ansichten, 2 Schnitte) als verschachtelte <svg>, dazu Schriftfeld mit Projektname.
expect((svg.match(/<svg /g) ?? []).length).toBeGreaterThanOrEqual(10);
expect(svg).toContain("Wettbewerb Hofwiesen");
expect(svg).toContain("Erdgeschoss");
});
it("--create-presentation --poster: Plakat mit Kopfzeile und Tabellen", async () => {
const out = join(dir, "plakat.svg");
const r = await quiet(() => run([":wettbewerb", "sheet", "--create-presentation", "--poster", "poster-a0-portrait", "--out", out]));
expect(r.code).toBe(0);
expect(r.err).toContain("Präsentationsblatt angelegt");
const svg = readFileSync(out, "utf8");
expect(svg).toContain('viewBox="0 0 841 1189"');
expect(svg).toContain("Kennzahlen (SIA 416)");
expect(svg).toContain("Plan 1/1");
expect(svg).toContain("1:500");
});
it("--list nennt die Blätter, unbekannter Name und PDF-Ziel scheitern verständlich", async () => {
expect((await quiet(() => run([":wettbewerb", "sheet", "--list"]))).code).toBe(0);
const exit = vi.spyOn(process, "exit").mockImplementation((code) => {
throw new Error(`exit ${code}`);
});
try {
const bad = await quiet(() => run([":wettbewerb", "sheet", "--name", "gibtsnicht", "--out", join(dir, "x.svg")]).catch((e: Error) => e.message));
expect(bad.code).toBe("exit 1");
expect(bad.err).toContain("Blatt nicht gefunden");
const pdf = await quiet(() => run([":wettbewerb", "sheet", "--out", join(dir, "x.pdf")]).catch((e: Error) => e.message));
expect(pdf.code).toBe("exit 1");
expect(pdf.err).toContain("PDF braucht ein DOM");
} finally {
exit.mockRestore();
}
expect(existsSync(join(dir, "x.pdf"))).toBe(false);
});
});
+1
View File
@@ -102,6 +102,7 @@ export { callAiTool } from "./aiTools";
export type { AiHost } from "./aiTools";
export { PRESENTATION_SCALES, POSTER_EXTRAS_DEFAULT, posterExtrasDefault, POSTER_SITUATION_SCALE, PRESENTATION_DEFAULT_SCALE, levelHasContent, PRESENTATION_TEMPLATE_ID, presentationDefaults, presentationSheetOps, planPresentationSheet, fittingPresentationScale, finerPresentationScale } from "../plan/presentationSheet";
export type { PresentationOptions, PosterExtras, PosterTableKind, PresentationPlan, PresentationLabels } from "../plan/presentationSheet";
export { buildLayoutSvg, presentationSheetLabels } from "../export/layoutSvg";
export { lineEndsOf, lineEndsCode, lineEndsFromCode, lineEndsSvgAttrs, planLineEndsProps, MITER_LIMIT as LINE_MITER_LIMIT } from "../model/lineEnds";
export type { LineEnds } from "../model/lineEnds";
export type { LineCap, LineJoin } from "../model/types";
+22
View File
@@ -0,0 +1,22 @@
// Minimales DOM für den Headless-Betrieb (dossier-cli, vitest in Node): `planToPrintSvg`/`sceneToPrintSvg`
// bauen ihr SVG über `document.createElementNS`. Im Browser gibt es das; in Node stellen wir für die Dauer des
// Aufrufs ein xmldom-Dokument bereit. Keine zweite Logik — dieselben Druck-Serializer, nur ein anderes DOM.
import { DOMImplementation, XMLSerializer } from "@xmldom/xmldom";
/** Führt `fn` mit einem `document` aus; ohne vorhandenes (Browser) wird ein xmldom-Dokument ein- und danach ausgehängt. */
export async function withHeadlessDom<T>(fn: () => Promise<T> | T): Promise<T> {
const g = globalThis as { document?: unknown };
if (g.document) return fn();
g.document = new DOMImplementation().createDocument(null, null, null);
try {
return await fn();
} finally {
delete g.document;
}
}
/** SVG-Element (Browser oder xmldom) als Text. */
export function serializeSvg(el: Element | SVGElement): string {
return new XMLSerializer().serializeToString(el as never);
}
+41 -23
View File
@@ -99,7 +99,7 @@ function drawTitleBlock(
/** Schrifthöhe in mm → pt (jsPDF misst Schriftgrössen in pt). */
const MM_TO_PT = 72 / 25.4;
function clip(s: string, max: number): string {
export function clip(s: string, max: number): string {
return s.length > max ? s.slice(0, max - 1) + "…" : s;
}
@@ -108,9 +108,10 @@ function clip(s: string, max: number): string {
* derselbe Plan wie am Bildschirm (`generatePlan`, Massstab 1:1, Export-Modus), über
* `planToPrintSvg` fest aufs Papier gelegt (Ursprung oben links), ohne eigenes weisses Blatt.
*/
async function renderSheetDrawing(doc: jsPDF, project: Project, layout: Layout, widthMm: number, heightMm: number): Promise<void> {
/** Druck-SVG der Blatt-Zeichnung (`null` ohne Zeichnungen) — gemeinsam für PDF und SVG-Blatt (`layoutSvg.ts`). */
export function sheetDrawingPrint(project: Project, layout: Layout, widthMm: number, heightMm: number): SVGSVGElement | null {
const level = sheetLevelOf(project, layout.id);
if (!level || !project.drawings2d.some((d) => d.levelId === level.id)) return;
if (!level || !project.drawings2d.some((d) => d.levelId === level.id)) return null;
const a = sheetMmToModel(0, heightMm);
const b = sheetMmToModel(widthMm, 0);
const plan = generatePlan(
@@ -125,15 +126,20 @@ async function renderSheetDrawing(doc: jsPDF, project: Project, layout: Layout,
SHEET_SCALE_DENOMINATOR,
true,
);
const print = planToPrintSvg(plan, {
return planToPrintSvg(plan, {
scaleDenominator: SHEET_SCALE_DENOMINATOR,
pageWidthMm: widthMm,
pageHeightMm: heightMm,
bounds: { minX: a.x, minY: a.y, maxX: b.x, maxY: b.y },
transparent: true,
});
await prepareSvgFonts(doc, print.svg);
await doc.svg(print.svg, { x: 0, y: 0, width: widthMm, height: heightMm });
}).svg;
}
async function renderSheetDrawing(doc: jsPDF, project: Project, layout: Layout, widthMm: number, heightMm: number): Promise<void> {
const svg = sheetDrawingPrint(project, layout, widthMm, heightMm);
if (!svg) return;
await prepareSvgFonts(doc, svg);
await doc.svg(svg, { x: 0, y: 0, width: widthMm, height: heightMm });
}
/** Optionen des Seiten-Aufbaus (Publikationssätze, [79]/[80]). */
@@ -209,6 +215,31 @@ function drawPosterHeaderPdf(doc: jsPDF, project: Project, layout: Layout, maste
}
}
/**
* Plan-Quelle EINES Viewports (Ausschnitt, Massstab, Vorlage, Varianten) — gemeinsam für PDF ({@link renderPage}) und
* SVG-Blatt (`layoutSvg.ts`), damit beide dieselben Pläne zeigen. `null`, wenn der Ausschnitt fehlt.
*/
export function viewportPlanSource(project: Project, vp: Layout["viewports"][number], scaleOverride?: number) {
const snap = findSnapshot(project, vp.snapshotId);
if (!snap) return null;
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 = scaleOverride ?? resolveViewportScale(vp, snap);
// Geschoss/Zeichnung, Schnitt oder Ansicht ([115]) — wie ViewportPlanSvg, im Druck-Modus.
// [33] Override-Regeln des Ausschnitts bzw. seiner verknüpften Ansichtsvorlage (wie am Bildschirm).
const ruleIds = snapshotOverrideRuleIds(project, snap);
const template = snapshotTemplate(project, snap);
// [266] 3D-Ausschnitt: 3D-Dokument aus dem Kern (`viewportSnapshotPlan`).
// [272] Variantenkombination des Ausschnitts/Viewports.
const dopts = viewportDesignOptions(project, snap, vp);
const planOf = async (visible: Set<string>): Promise<Plan> =>
isDoc3dSnapshot(snap) ? viewportSnapshotPlan(project, snap, visible, scaleN, true, vp) : viewportLevelPlan(project, snap.activeLevelId, visible, snap.detail, scaleN, true, snapshotMono(project, snap), ruleIds, template, snap.modelViewOptionId, dopts);
// [208] Eigene Bildmitte (Plakat): Ausschnitt um die Mitte; was darüber hinausgeht, schneidet der Rahmen ab.
const centered = viewportCenterBounds(vp, scaleN);
return { snap, codes, scaleN, planOf, centered };
}
/** Zeichnet die Viewports + Master-Elemente EINER Seite in das jsPDF-Dokument. */
async function renderPage(
doc: jsPDF,
@@ -221,23 +252,10 @@ async function renderPage(
// Echte Viewport-Pläne (wie ViewportPlan in LayoutSheet.tsx).
for (const vp of layout.viewports) {
const snap = findSnapshot(project, vp.snapshotId);
if (!snap) continue;
const src = viewportPlanSource(project, vp, ctx.scaleOverride);
if (!src) continue;
try {
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 = ctx.scaleOverride ?? resolveViewportScale(vp, snap);
// Geschoss/Zeichnung, Schnitt oder Ansicht ([115]) — wie ViewportPlanSvg, im Druck-Modus.
// [33] Override-Regeln des Ausschnitts bzw. seiner verknüpften Ansichtsvorlage (wie am Bildschirm).
const ruleIds = snapshotOverrideRuleIds(project, snap);
const template = snapshotTemplate(project, snap);
// [266] 3D-Ausschnitt: 3D-Dokument aus dem Kern (`viewportSnapshotPlan`).
// [272] Variantenkombination des Ausschnitts/Viewports.
const dopts = viewportDesignOptions(project, snap, vp);
const planOf = (visible: Set<string>) => (isDoc3dSnapshot(snap) ? viewportSnapshotPlan(project, snap, visible, scaleN, true, vp) : viewportLevelPlan(project, snap.activeLevelId, visible, snap.detail, scaleN, true, snapshotMono(project, snap), ruleIds, template, snap.modelViewOptionId, dopts));
// [208] Eigene Bildmitte (Plakat): Ausschnitt um die Mitte; was darüber hinausgeht, schneidet der Rahmen ab.
const centered = viewportCenterBounds(vp, scaleN);
const { codes, scaleN, planOf, centered } = src;
const draw = async (plan: Plan, transparent: boolean, bounds?: Plan["bounds"]) => {
const print = planToPrintSvg(plan, { scaleDenominator: scaleN, pageWidthMm: vp.widthMm, pageHeightMm: vp.heightMm, transparent, bounds: centered ?? bounds });
await prepareSvgFonts(doc, print.svg);
+163
View File
@@ -0,0 +1,163 @@
// Layout-Blatt als SVG (headless, `dossier-cli sheet`): dieselben Pläne wie der PDF-Export (`layoutPdf.ts`:
// `viewportPlanSource`, `sheetDrawingPrint`, Druck-Serializer `planToPrintSvg`) und dieselben Blatt-Elemente
// (Rahmen, Schriftfeld bzw. Plakat-Kopfzeile, Massstabsangaben, Legenden, Bilder, Tabellen) — nur als SVG-Text statt jsPDF.
// Vektor-PDF braucht jsPDF + svg2pdf und damit ein echtes DOM (Browser/Tauri): hier nicht.
import type { Layout, MasterLayout, Project } from "../model/types";
import { t } from "../i18n/translate";
import { effectiveSheetSizeMm, findMaster, resolveTitleBlock, type ResolvedTitleBlock } from "../model/layoutModel";
import { imageGeometry } from "../model/layoutImages";
import { posterHeaderItems, viewportScaleLabel, viewportVariantLabel } from "../model/posterTemplates";
import { legendPlan, legendPrintSvg } from "./legendSvg";
import { clip, sheetDrawingPrint, viewportPlanSource } from "./layoutPdf";
import { planToPrintSvg } from "./planToPrintSvg";
import { sheetTables, PDF_TABLE_FONT } from "./sheetTable";
import { serializeSvg, withHeadlessDom } from "./headlessDom";
import type { PresentationLabels } from "../plan/presentationSheet";
const INK = "#111111";
const FONT = "Inter, Helvetica, Arial, sans-serif";
const esc = (s: string): string => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
const num = (v: number): string => String(Math.round(v * 1000) / 1000);
/** Beschriftungen des Präsentationsblatts (de/en über `t`), gemeinsam für App und CLI. */
export function presentationSheetLabels(format: string): PresentationLabels {
return {
sheetName: t("presentation.sheetName"),
masterName: t("presentation.masterName", { format }),
north: t("presentation.north"),
northGroup: t("presentation.northGroup"),
scaleBarGroup: t("presentation.scaleBarGroup"),
situation: t("presentation.situation"),
tableAreas: t("presentation.table.areas"),
tableSiteProof: t("presentation.table.siteProof"),
tableUnits: t("presentation.table.units"),
imagePlaceholder: t("presentation.image.placeholder"),
imageHint: t("presentation.image.hint"),
axo: t("presentation.axo"),
};
}
function textEl(x: number, y: number, s: string, size: number, o: { bold?: boolean; italic?: boolean; anchor?: "start" | "middle" | "end"; fill?: string; family?: string } = {}): string {
const a = [`x="${num(x)}"`, `y="${num(y)}"`, `font-size="${num(size)}"`, `font-family="${o.family ?? FONT}"`, `fill="${o.fill ?? INK}"`];
if (o.bold) a.push('font-weight="bold"');
if (o.italic) a.push('font-style="italic"');
if (o.anchor && o.anchor !== "start") a.push(`text-anchor="${o.anchor}"`);
return `<text ${a.join(" ")}>${esc(s)}</text>`;
}
/** Schriftfeld unten rechts (Mass wie `drawTitleBlock` im PDF). */
function titleBlockSvg(w: number, h: number, tb: ResolvedTitleBlock, layout: Layout): string {
const bw = 70;
const bh = 30;
const x = w - bw - 6;
const y = h - bh - 6;
const fmt = `${layout.paper.toUpperCase()} ${layout.orientation === "landscape" ? "quer" : "hoch"}`;
const o: string[] = [
`<rect x="${x}" y="${y}" width="${bw}" height="${bh}" fill="#fff" stroke="${INK}" stroke-width="0.35"/>`,
`<line x1="${x}" y1="${y + 8}" x2="${x + bw}" y2="${y + 8}" stroke="${INK}" stroke-width="0.2"/>`,
`<line x1="${x}" y1="${y + bh - 7}" x2="${x + bw}" y2="${y + bh - 7}" stroke="${INK}" stroke-width="0.2"/>`,
textEl(x + 3, y + 5.6, clip(tb.projectName, 28), 3.2, { bold: true }),
textEl(x + bw - 3, y + 5.6, tb.planNumber, 3.2, { bold: true, anchor: "end" }),
textEl(x + 3, y + 13, clip(tb.sheetName, 36), 2.8),
];
if (tb.revision) o.push(textEl(x + bw - 3, y + 13, `${t("layouts.revision.short")} ${tb.revision}`, 2.5, { anchor: "end" }));
if (tb.author) o.push(textEl(x + 3, y + 18, clip(tb.author, 40), 2.5, { fill: "#444" }));
o.push(textEl(x + 3, y + bh - 2.4, tb.scale, 2.8), textEl(x + bw - 3, y + bh - 2.4, `${tb.date} · ${fmt}`, 2.5, { anchor: "end" }));
return o.join("");
}
function posterHeaderSvg(project: Project, layout: Layout, master: MasterLayout, w: number, h: number): string {
return posterHeaderItems(project, layout, master, { w, h })
.map((it) =>
it.kind === "rect"
? `<rect x="${num(it.x)}" y="${num(it.y)}" width="${num(it.w)}" height="${num(it.h)}" fill="none" stroke="${INK}" stroke-width="${num(it.stroke)}"/>`
: textEl(it.x, it.y, it.text, it.sizeMm, { bold: it.bold, anchor: it.align === "left" ? "start" : it.align === "center" ? "middle" : "end" }),
)
.join("");
}
/** Eingebettetes SVG-Element an Blatt-Position `x,y` (verschachteltes `<svg>` schneidet am eigenen Rahmen ab). */
function nested(svg: SVGSVGElement, x: number, y: number, w: number, h: number): string {
svg.setAttribute("x", num(x));
svg.setAttribute("y", num(y));
svg.setAttribute("width", num(w));
svg.setAttribute("height", num(h));
svg.setAttribute("overflow", "hidden");
return serializeSvg(svg);
}
export interface LayoutSvgOptions {
/** Massstab (1:N) für alle Viewports statt dem eigenen. */
scaleOverride?: number;
}
/**
* Das Blatt `layout` als SVG-Text (Papier-mm, Ursprung oben links): Viewports, Bilder, Massstabsangaben, Legenden,
* Rahmen + Schriftfeld/Kopfzeile, Tabellen, Blatt-Zeichnung — Stapelung wie im PDF. Ein Viewport, der nicht rendert,
* lässt nur sich selbst weg (Meldung in `warnings`).
*/
export async function buildLayoutSvg(project: Project, layout: Layout, opts: LayoutSvgOptions = {}): Promise<{ svg: string; widthMm: number; heightMm: number; warnings: string[] }> {
const master = findMaster(project, layout);
const { w, h } = effectiveSheetSizeMm(master ?? layout);
const warnings: string[] = [];
const parts: string[] = [];
await withHeadlessDom(async () => {
for (const vp of layout.viewports) {
const src = viewportPlanSource(project, vp, opts.scaleOverride);
if (!src) {
warnings.push(`Viewport ${vp.id}: Ausschnitt ${vp.snapshotId} fehlt`);
continue;
}
try {
const plan = await src.planOf(src.codes);
const print = planToPrintSvg(plan, { scaleDenominator: src.scaleN, pageWidthMm: vp.widthMm, pageHeightMm: vp.heightMm, transparent: false, bounds: src.centered ?? undefined });
parts.push(nested(print.svg, vp.xMm, vp.yMm, vp.widthMm, vp.heightMm));
} catch (e) {
warnings.push(`Viewport ${vp.id}: ${e instanceof Error ? e.message : String(e)}`);
}
}
for (const img of layout.images ?? []) {
if (!/^data:image\/(png|jpeg);base64,/.test(img.src) || img.widthMm <= 0 || img.heightMm <= 0) continue;
const g = imageGeometry(img);
const id = `clip-${esc(img.id)}`;
parts.push(`<clipPath id="${id}"><rect x="${num(g.clip.x)}" y="${num(g.clip.y)}" width="${num(g.clip.w)}" height="${num(g.clip.h)}"/></clipPath><image clip-path="url(#${id})" href="${img.src}" x="${num(g.draw.x)}" y="${num(g.draw.y)}" width="${num(g.draw.w)}" height="${num(g.draw.h)}" preserveAspectRatio="none"/>`);
}
if (master?.viewportScaleLabels || project.designOptionSets?.length) {
for (const vp of layout.viewports) {
const l = master?.viewportScaleLabels ? viewportScaleLabel(project, vp, { w, h }, opts.scaleOverride) : viewportVariantLabel(project, vp, { w, h });
if (l) parts.push(textEl(l.x, l.y, l.text, l.sizeMm));
}
}
for (const lg of layout.legends ?? []) {
try {
const lp = legendPlan(project, layout, lg);
if (lp) parts.push(nested(legendPrintSvg(lp), lp.xMm, lp.yMm, lp.widthMm, lp.heightMm));
} catch (e) {
warnings.push(`Legende ${lg.id}: ${e instanceof Error ? e.message : String(e)}`);
}
}
if (master) {
if (master.border ?? true) parts.push(`<rect x="5" y="5" width="${w - 10}" height="${h - 10}" fill="none" stroke="${INK}" stroke-width="0.35"/>`);
parts.push(master.posterHeader ? posterHeaderSvg(project, layout, master, w, h) : titleBlockSvg(w, h, resolveTitleBlock(project, layout, master), layout));
}
try {
for (const tb of sheetTables(project, layout.id)) {
for (const p of tb.prims) {
if (p.k === "line") parts.push(`<line x1="${num(p.x1)}" y1="${num(p.y1)}" x2="${num(p.x2)}" y2="${num(p.y2)}" stroke="${INK}" stroke-width="${num(p.w)}"/>`);
else parts.push(textEl(p.x, p.y, p.s, p.size, { bold: p.bold, italic: p.italic, family: `'${PDF_TABLE_FONT[p.font]}', ${FONT}`, anchor: p.align === "r" ? "end" : p.align === "c" ? "middle" : "start" }));
}
}
} catch (e) {
warnings.push(`Tabellen: ${e instanceof Error ? e.message : String(e)}`);
}
try {
const drawing = sheetDrawingPrint(project, layout, w, h);
if (drawing) parts.push(nested(drawing, 0, 0, w, h));
} catch (e) {
warnings.push(`Blatt-Zeichnung: ${e instanceof Error ? e.message : String(e)}`);
}
});
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${w}mm" height="${h}mm" viewBox="0 0 ${w} ${h}"><rect width="${w}" height="${h}" fill="#fff"/>${parts.join("")}</svg>\n`;
return { svg, widthMm: w, heightMm: h, warnings };
}
+21
View File
@@ -35,6 +35,27 @@ describe("[66] Präsentationsplan", () => {
project = st().project;
});
// [323] Achskreise und Masszahlen der Aussenbemassung ragen über das Plan-Ausmass hinaus: der Rahmen lässt 8 mm Rand, nicht 4.
it("[323] Präsentationsplan: Rahmen der Grundrisse mit 8 mm Rand um das gemeinsame Ausmass", () => {
const o = { ...presentationDefaults(project), scale: 200 };
const plan = planPresentationSheet(project, o);
const res = presentationSheetOps(project, o, LABELS, "p323")!;
st().applyChange(res.ops);
const q = st().project;
let h = 0;
let w = 0;
for (const f of plan.items.filter((i) => q.drawingLevels.find((l) => l.id === i.levelId)?.kind === "floor")) {
const snap = q.viewSnapshots!.find((v) => v.id === `vs-pres-p323-${plan.items.indexOf(f)}`)!;
const vis = new Set(Object.entries(snap.layerVisibility).filter(([, v]) => v).map(([k]) => k));
const b = generatePlan(q, f.levelId, vis, undefined, snap.detail, false, true, true, 200, false, false).bounds;
h = Math.max(h, ((b.maxY - b.minY) * 1000) / 200);
w = Math.max(w, ((b.maxX - b.minX) * 1000) / 200);
}
const eg = plan.items.find((i) => q.drawingLevels.find((l) => l.id === i.levelId)?.kind === "floor")!;
expect(eg.heightMm).toBeGreaterThanOrEqual(h + 16 - 1e-6);
expect(eg.widthMm).toBeGreaterThanOrEqual(w + 16 - 1e-6);
});
it("Vorschlag: alle Geschosse, Ansichten, ein Schnitt, A1 quer (Master)", () => {
const d = presentationDefaults(project);
expect(d.floors.length).toBeGreaterThanOrEqual(4);
+4 -2
View File
@@ -37,6 +37,8 @@ import { generateAxoPlan } from "./toAxo";
export const PRESENTATION_TEMPLATE_ID = "std-vt-praesentation";
/** Rand zwischen Inhalt und Rahmen (mm, wie `FRAME_PAD_MM` im Kern). */
const FRAME_PAD_MM = 4;
/** [323] Rand im Präsentationsplan ohne Plakat (`SHEET_PAD_MM` im Kern). */
const SHEET_PAD_MM = 8;
export interface PresentationOptions {
/** Geschosse (Ebenen der Art `floor`) in Blattreihenfolge. */
@@ -661,7 +663,7 @@ export function presentationSheetOps(
drawings.push(
tpl
? sheetText(`d-pres-${stamp}-t${i}`, sheetLevels[page].id, cat, it.xMm + labelM.sizeMm * 3.6, it.yMm + it.heightMm + labelM.dyMm, title, labelM.sizeMm, true)
: sheetText(`d-pres-${stamp}-t${i}`, sheetLevels[page].id, cat, it.xMm + FRAME_PAD_MM, it.yMm + it.heightMm + 6, `${title} 1:${it.scale}`, 4, true),
: sheetText(`d-pres-${stamp}-t${i}`, sheetLevels[page].id, cat, it.xMm + SHEET_PAD_MM, it.yMm + it.heightMm + 6, `${title} 1:${it.scale}`, 4, true),
);
});
// Nordpfeil rechts neben dem Titel des ersten Grundrisses, Massstabsbalken links davon, sofern er den Titel nicht berührt
@@ -672,7 +674,7 @@ export function presentationSheetOps(
const lvl = sheetLevels[it.page ?? 0].id;
const titleEnd = tpl
? it.xMm + labelM.sizeMm * 3.6 + title.length * labelM.sizeMm * 0.65
: it.xMm + FRAME_PAD_MM + (title.length + 8) * 4 * 0.65;
: it.xMm + SHEET_PAD_MM + (title.length + 8) * 4 * 0.65;
const cx = it.xMm + it.widthMm - 8;
const beside = cx - 8 > titleEnd;
const cy = beside ? it.yMm + it.heightMm + 4.8 : it.yMm + 8;