[K3d][K4] Text-Layout im Kern: Raumstempel, Rich-Text, Umbruch, Text-Rahmen

Neu `core/src/text_layout.rs` (Rich-Text → Zeilen/Tspans, Wortumbruch, Raumstempel-Block,
einfacher Umbruch, Text-Rahmen, fontNameOf) und `core/src/plan_text.rs` (Texte aus dem
Text-JSON des Plan-Puffers). Render-Szene, DXF und Druck-SVG setzen die Texte selbst beim
Massstab der Ausgabe; TS übergibt kein Layout mehr. renderHtml.ts/textFrame.ts sind dünne
Fassaden. Gelöscht: planSceneTexts, stampLines/textInput, drawingTextNode, runToTspan und
Umbruch in TS, dxfCadParts.ts, texts_from (Szene, DXF).

Gleichheit alt/neu (temporäre Tests, entfernt): 288 Pläne Szene/DXF/Druck-SVG, 600 Layouts,
3000 Stempel-Blöcke/Umbrüche, 230 CLI-Dateien byte-gleich.
This commit is contained in:
Claude committed 2026-10-29 09:36:23 +00:00
1 parent 24735a4b53
commit ce0d9950d0
20 files changed
+1456 -720

No files matched your search

-13
View File
@@ -1,13 +0,0 @@
import { describe, expect, it } from "vitest";
import { fontNameOf } from "./dxfCadParts";
describe("fontNameOf", () => {
it("erste echte Familie, ohne Anführungszeichen; generische/Variablen übersprungen", () => {
expect(fontNameOf('"Helvetica Neue", Arial, sans-serif')).toBe("Helvetica Neue");
expect(fontNameOf("var(--font-ui, sans-serif)")).toBeNull();
expect(fontNameOf("sans-serif, Arial")).toBe("Arial");
expect(fontNameOf("'Source Sans 3'")).toBe("Source Sans 3");
expect(fontNameOf(undefined)).toBeNull();
expect(fontNameOf("")).toBeNull();
});
});
-16
View File
@@ -1,16 +0,0 @@
// Baustein des Fachplaner-Exports ([C2], 28.10.): Schriftname aus CSS-Familie (Text-Layout bleibt TS).
// Linientypen, blocklokale Primitive, Papierformate und der Sammler selbst liegen seit [K3d] im Kern
// (`src-tauri/core/src/plan_dxf.rs`).
/** Erste Schriftfamilie aus einem CSS-`font-family`-Wert ohne Anführungszeichen; generische Familien/CSS-Variablen → null. */
export function fontNameOf(css: string | undefined | null): string | null {
if (!css) return null;
// `var(--font-ui, sans-serif)` enthält selbst ein Komma: vor dem Teilen entfernen.
for (const raw of css.replace(/var\([^)]*\)/g, "").split(",")) {
const name = raw.trim().replace(/^["']|["']$/g, "").trim();
if (!name) continue;
if (/^(sans-serif|serif|monospace|cursive|fantasy|system-ui|ui-sans-serif|inherit|initial)$/i.test(name)) continue;
return name;
}
return null;
}
+5 -93
View File
@@ -11,9 +11,9 @@
// Seit [K3d] (29.10.) sammelt der Kern (`src-tauri/core/src/plan_dxf.rs`) Ebenen und Entitäten
// direkt aus den Plan-Puffern und dem Projekt-Dokument in die flache Zeichnung (Kodierung s.
// `src-tauri/fileio/src/export.rs`); Rust (acadrust, fileio) schreibt die Datei ([C1]/[C2]).
// DXF = R2018 ASCII (UTF-8), DWG = R2018. Hier bleibt das Text-Layout (Zeilen der Raumstempel,
// Absätze/Wörter der Einzeltexte, Schriftfamilien) — es geht als flache Eingabe an den Kern —
// und die Übergabe an fileio. Das Format-Modul wird nachgeladen: vor `buildPlanDxf`/
// DXF = R2018 ASCII (UTF-8), DWG = R2018. Auch die Texte (Zeilen der Raumstempel, Absätze/Wörter
// der Einzeltexte, Schriftfamilien) setzt der Kern aus dem Text-JSON der Puffer; hier bleibt die
// Übergabe an fileio. Das Format-Modul wird nachgeladen: vor `buildPlanDxf`/
// `buildPlanDwg` einmal `await loadFileio()` (savePlanDxf und die CLI tun das).
//
// Fachplaner-Export (28.10., [C2]): damit in AutoCAD/BricsCAD weitergearbeitet werden kann, entstehen
@@ -27,18 +27,13 @@
// Ausrichtung (Raumstempel mit Fläche als TEXT, links/Mitte/rechts), optional Papierbereich.
// Alles andere (Wände, Umrisse, Schraffuren) bleibt wie bisher Linie/Polylinie/HATCH.
import type { Plan, Primitive } from "../plan/generatePlan";
import type { Plan } from "../plan/generatePlan";
import type { Project } from "../model/types";
import type { Marks } from "../text/richText";
import { DEFAULT_SCALE_DENOMINATOR } from "../model/dimension";
import { plainText } from "../text/richText";
import { docToLines } from "../text/renderHtml";
import { fileio, loadFileio } from "../engine/fileioWasm";
import { core } from "../engine/coreWasm";
import { documentFor } from "../core/document";
import { planParts, withPlanParts } from "../plan/planParts";
import { planTextEntries } from "../plan/planLazy";
import { fontNameOf } from "./dxfCadParts";
export interface ExportDxfOptions {
/** Titel/Geschossname (nur als Kommentar-freundlicher Dateiname genutzt). */
@@ -82,61 +77,11 @@ export interface FlatDrawing {
stats(): { model: Record<string, number>; blocks: Record<string, number> };
}
/** Eine Zeile einer (Rich-)Text-Ausgabe. */
interface OutLine {
text: string;
/** Schrifthöhe (Meter). */
height: number;
align: 0 | 1 | 2;
marks?: Marks;
/** Versatz der Grundlinie vom Anker nach unten (Meter, ≥ 0 für spätere Zeilen). */
down: number;
}
/** Massstab des Exports (endlich und > 0, sonst 1:100). */
function scaleOf(opts: ExportDxfOptions): number {
return opts.scaleDenominator && Number.isFinite(opts.scaleDenominator) && opts.scaleDenominator > 0 ? opts.scaleDenominator : DEFAULT_SCALE_DENOMINATOR;
}
/**
* Text-Eingabe für den Kern (`plan_dxf::texts_from`): je Raumstempel die gesetzten Zeilen, je
* Einzeltext Anker/Winkel/Höhe/Spalte, Schrift und Absätze mit ihren Wörtern (`split(/\s+/)`).
* Nur die Text-Einträge des Plans werden gelesen.
*/
function textInput(plan: Plan, scale: number, defaultFont: string): { nums: Float64Array; strs: string } {
const nums: number[] = [];
const strs: string[] = [];
const idx = new Map<string, number>();
const S = (s: string): number => {
let i = idx.get(s);
if (i === undefined) {
i = strs.length;
strs.push(s);
idx.set(s, i);
}
return i;
};
const family = (marks: Marks | undefined): number => S(fontNameOf(marks?.font) ?? defaultFont);
for (const { i, p } of planTextEntries(plan)) {
if (p.kind === "text") {
const lines = stampLines(p, scale);
nums.push(i, 6, p.at.x, p.at.y, lines.length);
for (const l of lines) nums.push(S(l.text), l.height, l.align, family(l.marks), l.marks?.bold ? 1 : 0, l.marks?.italic ? 1 : 0, l.down);
} else if (p.kind === "drawingText") {
const paragraphs = p.doc ? plainText(p.doc).split("\n") : p.text.split(/\r?\n/);
const marks = p.marks ?? p.doc?.paragraphs[0]?.runs[0]?.marks;
const wrap = typeof p.wrapWidth === "number" ? p.wrapWidth : NaN;
nums.push(i, 7, p.at.x, p.at.y, p.angle, p.heightM, wrap, family(marks), marks?.bold ? 1 : 0, marks?.italic ? 1 : 0, paragraphs.length);
for (const para of paragraphs) {
const words = para.split(/\s+/);
nums.push(S(para), words.length);
for (const w of words) nums.push(S(w));
}
}
}
return { nums: Float64Array.from(nums), strs: strs.map((s) => "\0" + s).join("") };
}
/** Kern-Antwort (`plan_dxf::encode`) → flache Zeichnung; leer = Fehler. */
function decodeFlat(bytes: Uint8Array): FlatDrawing {
const b = bytes.byteOffset % 8 === 0 ? bytes : bytes.slice();
@@ -184,14 +129,11 @@ export function collectPlanDrawing(
opts: ExportDxfOptions = {},
): FlatDrawing {
const scale = scaleOf(opts);
// Standard-Schrift: erste im Projekt hinterlegte Schrift der Textstile, sonst Arial.
const defaultFont = (project.textStyles ?? []).map((s) => fontNameOf(s.marks.font)).find((f) => f) ?? "Arial";
const { nums, strs } = textInput(plan, scale, defaultFont);
const b = plan.bounds;
const o = Float64Array.of(scale, (opts.includeHatches ?? true) ? 1 : 0, opts.dimUnit === "cm" ? 1 : 0, opts.paperLayout ? 1 : 0, b.minX, b.minY, b.maxX, b.maxY);
const doc = documentFor(project).id;
// Eigener Puffer mit Schraffur-JSON (Verlauf-Schraffuren brauchen ihre Farben).
const bytes = withPlanParts(planParts(plan, true), (segs) => core().plan_dxf_flat(doc, segs, nums, strs, o, defaultFont));
const bytes = withPlanParts(planParts(plan, true), (segs) => core().plan_dxf_flat(doc, segs, o));
return decodeFlat(bytes);
}
@@ -242,36 +184,6 @@ function writeCad(format: CadExportFormat, drawing: FlatDrawing): Uint8Array {
return bytes;
}
/** Stempel-/Textzeilen eines Primitivs `text` (Raumstempel): Rich-Text-Doc + Live-Zeilen, vertikal um den Anker zentriert wie in der Plan-Ansicht. */
function stampLines(p: Extract<Primitive, { kind: "text" }>, scale: number): OutLine[] {
const unitPerPt = (0.0254 / 72) * scale; // 1 pt Papier in Modell-Metern
const baseFs = p.basePt * unitPerPt;
const lineGap = baseFs * 1.3;
const docLines = docToLines(p.doc, { x: 0, y: 0, lineHeight: lineGap, unitPerPt, basePt: p.basePt, color: p.color });
const lines = [
...docLines.map((l) => ({ align: l.align, lineHeight: l.lineHeight, ts: l.tspans })),
...p.extraLines.map((l) => ({ align: l.align, lineHeight: lineGap, ts: [{ text: l.text, fontSize: baseFs * 0.8, fontFamily: undefined as string | undefined, fontWeight: undefined as string | undefined, fontStyle: undefined as string | undefined }] })),
];
if (lines.length === 0) return [];
const totalH = baseFs + lines.slice(1).reduce((s, l) => s + l.lineHeight, 0);
let down = -totalH / 2 + baseFs * 0.8;
const out: OutLine[] = [];
lines.forEach((l, k) => {
if (k > 0) down += l.lineHeight;
const text = l.ts.map((t) => t.text).join("");
const first = l.ts[0];
if (!text.trim() || !first) return;
out.push({
text,
height: Math.max(...l.ts.map((t) => t.fontSize)),
align: l.align === "center" ? 1 : l.align === "right" ? 2 : 0,
marks: { font: first.fontFamily, bold: first.fontWeight === "700", italic: first.fontStyle === "italic" },
down,
});
});
return out;
}
/** Baut die Datei und löst den Download aus (Browser). Lädt das Format-Modul bei Bedarf. */
export async function savePlanDxf(
plan: Plan,
+30 -101
View File
@@ -20,19 +20,15 @@
// Vektorlinien direkt ins SVG. So bleibt das PDF rein vektoriell und scharf.
//
// Seit [K3d] (29.10.) rechnet der Kern die Knoten aus den Plan-Puffern
// (`src-tauri/core/src/plan_print_svg.rs`, Anweisungsliste); hier bleiben der
// <svg>-Rahmen, die Bild-<pattern> (laufende Ids) und die Einzeltexte
// (Text-Layout `wrapDocToLines`). Ausgabe unverändert (gleiche Knoten/Attribute).
// (`src-tauri/core/src/plan_print_svg.rs`, Anweisungsliste) samt gesetzter Einzeltexte;
// hier bleiben der <svg>-Rahmen und die Bild-<pattern> (laufende Ids). Ausgabe unverändert
// (gleiche Knoten/Attribute).
//
// Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md).
import type { HatchRender, Plan, Primitive } from "../plan/generatePlan";
import type { Vec2 } from "../model/types";
import { wrapDocToLines, type SvgLine } from "../text/renderHtml";
import { docFromText } from "../text/richText";
import type { HatchRender, Plan } from "../plan/generatePlan";
import { core } from "../engine/coreWasm";
import { planParts, withPlanParts } from "../plan/planParts";
import { planPrimAt } from "../plan/planLazy";
/** SVG-Namespace für die programmatisch erzeugten Knoten. */
const SVG_NS = "http://www.w3.org/2000/svg";
@@ -111,15 +107,6 @@ function mmPerMeter(n: number): number {
return 1000 / n;
}
/**
* Bildet einen Welt-Punkt (Meter) auf Papier-Millimeter ab. Der Inhalt wird so
* verschoben, dass die Plan-Bounds (in mm) zentriert auf dem Blatt liegen.
* Plan-Y zeigt nach oben → SVG-Y nach unten (Spiegelung), daher das Minus.
*/
interface Mapper {
(p: Vec2): Vec2;
}
/**
* Erzeugt das Druck-SVG aus einem Plan. Reihenfolge der Primitive bleibt
* erhalten (Zeichenreihenfolge = Stapelung); Schraffuren werden als geklippte
@@ -147,11 +134,6 @@ export function planToPrintSvg(plan: Plan, opts: PrintSvgOptions): PrintSvg {
// Blatt. Wir mappen maxY → offsetYmm.
const offsetYmm = (opts.pageHeightMm - contentHmm) / 2;
const map: Mapper = (p) => ({
x: offsetXmm + (p.x - b.minX) * k,
y: offsetYmm + (b.maxY - p.y) * k,
});
const svg = document.createElementNS(SVG_NS, "svg") as SVGSVGElement;
svg.setAttribute("xmlns", SVG_NS);
// Breite/Höhe als REINE Zahlen (= viewBox-Einheiten), KEINE „mm"-Einheit: so
@@ -175,7 +157,7 @@ export function planToPrintSvg(plan: Plan, opts: PrintSvgOptions): PrintSvg {
const o = Float64Array.of(n, opts.pageWidthMm, opts.pageHeightMm, b.minX, b.minY, b.maxX, b.maxY);
const ops = withPlanParts(planParts(plan, true), (segs) => core().plan_print_svg_ops(segs, o));
if (!ops) throw new Error("Druck-SVG: Plan im Kern unlesbar");
applyOps(svg, ops.slice(1), plan, map, k);
applyOps(svg, ops.slice(1));
return {
svg,
@@ -187,17 +169,22 @@ export function planToPrintSvg(plan: Plan, opts: PrintSvgOptions): PrintSvg {
/**
* Legt die Knoten der Kern-Anweisungsliste an (Format s. `plan_print_svg.rs`): Elemente mit ihren
* Attributen in Reihenfolge, Gruppen, Bild-Schraffuren (`<pattern>` hier) und Einzeltexte (Layout hier).
* Attributen in Reihenfolge, Gruppen, Bild-Schraffuren (`<pattern>` hier) und gesetzte Einzeltexte.
*/
function applyOps(svg: SVGSVGElement, ops: string, plan: Plan, map: Mapper, mmPerM: number): void {
function applyOps(svg: SVGSVGElement, ops: string): void {
if (!ops) return;
let g: SVGElement | null = null;
let text: SVGElement | null = null;
let line: SVGElement | null = null;
const attrs = (el: SVGElement, f: string[], from: number) => {
for (let i = from; i + 1 < f.length; i += 2) el.setAttribute(f[i], f[i + 1]);
};
for (const rec of ops.split("\u001e")) {
const f = rec.split("\u001f");
switch (f[0]) {
case "E": {
const el = document.createElementNS(SVG_NS, f[2]) as SVGElement;
for (let i = 3; i + 1 < f.length; i += 2) el.setAttribute(f[i], f[i + 1]);
attrs(el, f, 3);
(f[1] === "1" && g ? g : svg).appendChild(el);
break;
}
@@ -219,87 +206,29 @@ function applyOps(svg: SVGSVGElement, ops: string, plan: Plan, map: Mapper, mmPe
g?.appendChild(el);
break;
}
case "T": {
const p = planPrimAt(plan, Number(f[1]));
if (p?.kind !== "drawingText") break;
const node = drawingTextNode(p, map, mmPerM);
if (node) {
if (f[2]) node.setAttribute("opacity", f[2]);
svg.appendChild(node);
}
case "X":
// Einzeltext: <text> mit Zeilen-<tspan>s, darin je Run/Wort ein <tspan>.
text = document.createElementNS(SVG_NS, "text") as SVGElement;
attrs(text, f, 1);
svg.appendChild(text);
break;
case "L":
line = document.createElementNS(SVG_NS, "tspan") as SVGElement;
attrs(line, f, 2);
if (f[1]) line.textContent = f[1];
text?.appendChild(line);
break;
case "R": {
const run = document.createElementNS(SVG_NS, "tspan") as SVGElement;
attrs(run, f, 2);
run.textContent = f[1];
line?.appendChild(run);
break;
}
}
}
}
/**
* Modellverankerter Einzeltext (Text-Werkzeug/DXF-Import) als `<text>` mit
* `<tspan>`-Zeilen — analog zur Bildschirm-Darstellung (PlanView.tsx
* `case "drawingText"`), aber DOM-Knoten statt JSX. Bricht bei gesetzter
* Spaltenbreite wortweise um (Run-Grenzen bleiben erhalten).
*/
function drawingTextNode(
p: Extract<Primitive, { kind: "drawingText" }>,
map: Mapper,
mmPerM: number,
): SVGTextElement | null {
const doc = p.doc ?? docFromText(p.text, p.marks ?? {});
const c = map(p.at);
const fontSizeMm = p.heightM * mmPerM;
const unitPerPt = (0.0254 / 72) * mmPerM;
const basePt = unitPerPt > 0 ? p.heightM / unitPerPt : 0;
const lineHeight = fontSizeMm * 1.25;
const wrapWidthUnits = p.wrapWidth && p.wrapWidth > 0 ? p.wrapWidth * mmPerM : undefined;
const lines: SvgLine[] = wrapDocToLines(doc, {
x: 0,
y: 0,
lineHeight,
unitPerPt,
basePt,
color: p.color,
...(wrapWidthUnits ? { wrapWidthUnits } : {}),
});
if (lines.length === 0) return null;
const el = document.createElementNS(SVG_NS, "text");
const deg = -(p.angle * 180) / Math.PI;
if (deg) el.setAttribute("transform", `rotate(${round(deg)} ${round(c.x)} ${round(c.y)})`);
let y = c.y;
lines.forEach((line, k) => {
if (k > 0) y += line.lineHeight;
const anchor = line.align === "center" ? "middle" : line.align === "right" ? "end" : "start";
const x = !wrapWidthUnits
? c.x
: line.align === "center"
? c.x + wrapWidthUnits / 2
: line.align === "right"
? c.x + wrapWidthUnits
: c.x;
const lineTspan = document.createElementNS(SVG_NS, "tspan");
lineTspan.setAttribute("x", String(round(x)));
lineTspan.setAttribute("y", String(round(y)));
lineTspan.setAttribute("text-anchor", anchor);
if (line.tspans.length === 0) {
lineTspan.textContent = "​";
} else {
for (const ts of line.tspans) {
const run = document.createElementNS(SVG_NS, "tspan");
run.setAttribute("font-size", String(round(ts.fontSize)));
run.setAttribute("fill", ts.fill);
if (ts.fontWeight) run.setAttribute("font-weight", ts.fontWeight);
if (ts.fontStyle) run.setAttribute("font-style", ts.fontStyle);
run.setAttribute("font-family", ts.fontFamily ?? "Helvetica, Arial, sans-serif");
if (ts.textDecoration) run.setAttribute("text-decoration", ts.textDecoration);
run.textContent = ts.text;
lineTspan.appendChild(run);
}
}
el.appendChild(lineTspan);
});
return el;
}
/** Auf 3 Nachkommastellen runden (kompaktes, exaktes SVG). */
function round(v: number): number {
return Math.round(v * 1000) / 1000;