[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;
+4 -4
View File
@@ -59,8 +59,8 @@ const cache = new WeakMap<object, { text: PlanParts | null; noText: PlanParts |
/**
* Abschnitte eines Plans; einmal je Plan (lazy, s. `planLazy.ts`) bzw. je `plan.primitives` (und
* Modus) gebaut. `texts`: der eigene Puffer trägt Texte/Bilder und Schraffuren mit JSON (SVG-/DXF-Export, Auswahl) —
* sonst nur deren Typ (Szene). Ein lazy Plan wird dabei nicht gelesen.
* Modus) gebaut. Texte/Bilder tragen im eigenen Puffer immer ihr JSON (der Kern setzt die Texte selbst);
* `texts`: zusätzlich das Schraffur-JSON (SVG-/DXF-Export, Auswahl). Ein lazy Plan wird dabei nicht gelesen.
*/
export function planParts(plan: Plan, texts = false): PlanParts {
const lazy = lazyPieces(plan);
@@ -82,7 +82,7 @@ export function planParts(plan: Plan, texts = false): PlanParts {
function partsFromPieces(pieces: readonly PlanPiece[], texts: boolean): PlanParts {
const rest: Primitive[] = [];
for (const pc of pieces) if (!isBufPiece(pc)) for (const p of pc) rest.push(p);
const own: HoldableBuf | null = rest.length ? { bytes: encodePlanBuf(rest, { textJson: texts, hatchJson: texts }), hold: 0 } : null;
const own: HoldableBuf | null = rest.length ? { bytes: encodePlanBuf(rest, { textJson: true, hatchJson: texts }), hold: 0 } : null;
const bufs: HoldableBuf[] = [];
const segs: number[] = [];
let ownAt = 0;
@@ -133,7 +133,7 @@ function partsFromRuns(plan: Plan, texts: boolean): PlanParts {
at = r.end;
}
gap(prims.length);
const own: HoldableBuf | null = rest.length ? { bytes: encodePlanBuf(rest, { textJson: texts, hatchJson: texts }), hold: 0 } : null;
const own: HoldableBuf | null = rest.length ? { bytes: encodePlanBuf(rest, { textJson: true, hatchJson: texts }), hold: 0 } : null;
const segs: number[] = [];
let gi = 0;
let ri = 0;
+38 -170
View File
@@ -2,9 +2,9 @@
// `push_native_scene`) und für den Druck-/SVG-Export. Die Geometrie (Füllungen, Umrisse,
// Polylinien, Bögen, Linien samt Maler-Reihenfolge `z`, Verkettung, Kantennaht, Schraffur-Läufe,
// Zickzack/Motiv) rechnet der Kern direkt aus dem Plan-Puffer ([K3d], `src-tauri/core/src/
// plan_scene.rs`, über die Abschnitte aus `planParts.ts`) — ohne Umweg über `Primitive[]`. Hier
// bleibt das Text-Layout (Rich-Text-Zeilen + Live-Zusatzzeilen, die Glyphen rastert render2d)
// und das Durchreichen eingebetteter Bilder.
// plan_scene.rs`, über die Abschnitte aus `planParts.ts`) — ohne Umweg über `Primitive[]`, ebenso
// das Text-Layout (Rich-Text-Zeilen + Live-Zusatzzeilen beim Massstab, `plan_text.rs`; die Glyphen
// rastert render2d). Hier bleibt das Durchreichen eingebetteter Bilder.
//
// Das Szenen-Objekt matcht 1:1 die serde-Structs render2d::types::Scene
// { fills:[{pts,color}], outlines:[{pts,color,widthMm,dash}],
@@ -14,9 +14,6 @@
// (render2d zeichnet sie per SDF-Shader), Strichmuster (Papier-mm) werden durchgereicht.
import type { Plan } from "./generatePlan";
import { inGreyedRange } from "./generatePlan";
import { docToLines, wrapDocToLines } from "../text/renderHtml";
import { docFromText } from "../text/richText";
import { core } from "../engine/coreWasm";
import { greyedFlat, planParts, withPlanParts } from "./planParts";
import { planTextEntries } from "./planLazy";
@@ -129,161 +126,46 @@ export interface RScene {
}
/**
* Fester Grauton gedimmter (greyed) Texte — gleicher Ton wie GREYED_COLOR in PlanView.tsx und
* `GREY_RGB` im Kern (#8c8c8c ≈ 0.549).
*/
const GREY_RGB = 0.549;
/** Textfarbe gedimmt: auf den festen Grauton umfärben (Deckkraft bleibt). */
function greyedColor(col: RRgba, greyed: boolean | undefined): RRgba {
return greyed ? [GREY_RGB, GREY_RGB, GREY_RGB, col[3]] : col;
}
/** 1 Punkt (pt) in Papier-Millimetern. */
const PT_TO_MM = 25.4 / 72;
/**
* Default-Referenzmaßstab (1:100) für Aufrufer ohne Massstabskontext (WASM-
* Viewport, `nativeSync.ts`) — identisch zu PlanView (`nRef`) im Display-
* Modus: dort belegt 1 pt Schrift (1/72)·0.0254·100 Modell-Meter. Der native
* Renderer rechnet im Anzeigemodus mit `paper_scale_n = 100`, damit ist
* `sizeMm = pt · PT_TO_MM` exakt die Browser-Darstellung. Für Aufrufer MIT
* Massstabskontext (z. B. PDF-Export) übersteuert `paperScaleN` diesen Default.
* Default-Referenzmaßstab (1:100) für Aufrufer ohne Massstabskontext (WASM-Viewport, `nativeSync.ts`)
* — identisch zu PlanView (`nRef`) im Display-Modus; der native Renderer rechnet im Anzeigemodus
* mit `paper_scale_n = 100`. Für Aufrufer MIT Massstabskontext (z. B. PDF-Export) übersteuert
* `paperScaleN` diesen Default.
*/
const STAMP_DEFAULT_N = 100;
/** Wenige benannte Farben, die in Klassen/Defaults vorkommen können. */
const NAMED: Record<string, string> = {
black: "#000000",
white: "#ffffff",
red: "#ff0000",
none: "none",
transparent: "none",
};
/** Hex/Named-Farbe → [r,g,b,a] in 0..1, oder null bei "none"/leer (Kern: `plan_scene::to_rgba`). */
function toRgba(input: string | undefined, alpha = 1): RRgba | null {
if (!input) return null;
let h = input.trim().toLowerCase();
if (h === "none" || h === "transparent") return null;
if (h[0] !== "#") {
const mapped = NAMED[h];
if (!mapped) return [0, 0, 0, alpha];
if (mapped === "none") return null;
h = mapped;
}
h = h.slice(1);
// Kurzformen auf Langform expandieren (#rgb → #rrggbb, #rgba → #rrggbbaa).
if (h.length === 3 || h.length === 4) h = h.split("").map((c) => c + c).join("");
if (h.length !== 6 && h.length !== 8) return [0, 0, 0, alpha];
const r = parseInt(h.slice(0, 2), 16) / 255;
const g = parseInt(h.slice(2, 4), 16) / 255;
const b = parseInt(h.slice(4, 6), 16) / 255;
// 8-stelliges Hex trägt den Alpha-Kanal selbst; sonst der Parameter.
const a = h.length === 8 ? parseInt(h.slice(6, 8), 16) / 255 : alpha;
if (![r, g, b, a].every((v) => Number.isFinite(v))) return [0, 0, 0, alpha];
return [r, g, b, a];
}
const ALIGNS: readonly RTextAlign[] = ["left", "center", "right"];
/**
* Textzeilen und eingebettete Bilder eines Plans in Zeichenreihenfolge. Layout wie im SVG-Pfad
* (PlanView, case "text"): Rich-Text-Zeilen + Live-Zusatzzeilen, Block vertikal um den Anker
* zentriert, Zeilenvorschub 1.3·Basisgröße; Einzeltexte (`drawingText`) top-down ab `at` mit
* `heightM` als Basisgrösse. `paperScaleN` (1:N) rechnet Papier-mm in Modell-Meter um.
* Textzeilen eines Plans in Zeichenreihenfolge, gesetzt im Kern (`plan_text::scene_texts`): Raumstempel
* = Rich-Text-Zeilen + Live-Zusatzzeilen, Block vertikal um den Anker zentriert, Vorschub 1.3·Basisgrösse;
* Einzeltexte (`drawingText`) top-down ab `at` mit `heightM` als Basisgrösse, umbrochen auf die Spalte.
* `paperScaleN` (1:N) rechnet Papier-mm in Modell-Meter um.
*/
export function planSceneTexts(plan: Plan, paperScaleN: number = STAMP_DEFAULT_N): { texts: RText[]; images: RImage[] } {
const mmToM = paperScaleN / 1000; // Papier-mm → Modell-Meter beim gewählten Massstab.
const texts: RText[] = [];
const images: RImage[] = [];
const ranges = plan.greyedRanges;
// Nur die Text-/Bild-Einträge ([K3d], aus den Typ-Kennungen des Plan-Puffers).
for (const { i, p } of planTextEntries(plan)) {
if (p.kind === "text") {
const greyed = p.greyed || inGreyedRange(ranges, i);
const defCol = greyedColor(toRgba(p.color, 1) ?? [0.1, 0.1, 0.1, 1], greyed);
// unitPerPt = PT_TO_MM → tspan.fontSize ist direkt die Papier-mm-Größe.
const docLines = docToLines(p.doc, {
x: 0,
y: 0,
lineHeight: 0,
unitPerPt: PT_TO_MM,
basePt: p.basePt,
color: p.color,
});
const baseMm = p.basePt * PT_TO_MM;
const flat: { content: string; sizeMm: number; color: RRgba; align: RTextAlign }[] = [];
for (const line of docLines) {
flat.push({
// Runs einer Zeile werden zusammengelegt (ein Buffer je Zeile);
// Größe/Farbe des größten bzw. ersten Runs gelten für die Zeile.
content: line.tspans.map((t) => t.text).join(""),
sizeMm: line.tspans.length ? Math.max(...line.tspans.map((t) => t.fontSize)) : baseMm,
color: greyedColor(toRgba(line.tspans[0]?.fill ?? p.color, 1) ?? defCol, greyed),
align: line.align,
});
}
for (const line of p.extraLines) {
flat.push({ content: line.text, sizeMm: baseMm * 0.8, color: defCol, align: line.align });
}
if (flat.length > 0) {
const baseH = baseMm * mmToM; // Basisgröße in Modell-Metern, beim gewählten Massstab
const lineGap = baseH * 1.3;
const totalH = baseH + (flat.length - 1) * lineGap;
flat.forEach((line, k) => {
if (!line.content.trim()) return; // Leerzeile: nur Vorschub
texts.push({
// Baseline der Zeile k (Modell-Y nach oben, deshalb minus):
// Browser: startY = c.y − H/2 + 0.8·fs (Bildschirm-Y nach unten).
pos: [p.at.x, p.at.y + totalH / 2 - baseH * 0.8 - k * lineGap],
content: line.content,
sizeMm: line.sizeMm,
color: line.color,
align: line.align,
});
});
}
} else if (p.kind === "drawingText") {
// Modellverankerter Einzeltext (Text-Werkzeug/DXF-Import): top-down ab `at`, `heightM`
// (Modell-Meter) als Basisgrösse — massstabsfrei an der Modellgeometrie verankert.
const greyed = p.greyed || inGreyedRange(ranges, i);
const doc = p.doc ?? docFromText(p.text, p.marks ?? {});
const defCol = greyedColor(toRgba(p.color, 1) ?? [0.1, 0.1, 0.1, 1], greyed);
const unitPerPt = PT_TO_MM * mmToM; // pt (Run-Override) -> Papier-mm -> Modell-Meter.
const basePt = unitPerPt > 0 ? p.heightM / unitPerPt : 0;
const lineHeight = p.heightM * 1.25;
const wrapWidthUnits = p.wrapWidth && p.wrapWidth > 0 ? p.wrapWidth : undefined;
const docLines = wrapDocToLines(doc, {
x: 0,
y: 0,
lineHeight,
unitPerPt,
basePt,
color: p.color,
...(wrapWidthUnits ? { wrapWidthUnits } : {}),
});
let dy = 0;
docLines.forEach((line, k) => {
if (k > 0) dy += line.lineHeight;
const content = line.tspans.map((t) => t.text).join("");
if (!content.trim()) return;
const sizeM = line.tspans.length ? Math.max(...line.tspans.map((t) => t.fontSize)) : p.heightM;
texts.push({
pos: [p.at.x, p.at.y - dy],
content,
sizeMm: unitPerPt > 0 ? sizeM / mmToM : sizeM,
color: greyedColor(toRgba(line.tspans[0]?.fill ?? p.color, 1) ?? defCol, greyed),
align: line.align,
});
});
} else if (p.kind === "drawingImage") {
// Eingebettetes Rasterbild — keine Rust-Textur (s. `RImage`); `sceneToPrintSvg.ts` liest es.
images.push({ min: [p.min.x, p.min.y], max: [p.max.x, p.max.y], src: p.src, opacity: p.opacity });
}
function sceneTexts(plan: Plan, paperScaleN: number): RText[] {
const greyed = greyedFlat(plan);
const f = withPlanParts(planParts(plan), (segs) => core().plan_scene_texts(segs, greyed, paperScaleN));
const n = f[0] ?? 0;
const out: RText[] = new Array(n);
let u = 1 + n * 9;
for (let k = 0; k < n; k++) {
const o = 1 + k * 9;
const len = f[o + 8];
let content = "";
for (let j = 0; j < len; j += 8192) content += String.fromCharCode.apply(null, Array.from(f.subarray(u + j, u + Math.min(len, j + 8192))));
u += len;
out[k] = { pos: [f[o], f[o + 1]], content, sizeMm: f[o + 2], color: [f[o + 3], f[o + 4], f[o + 5], f[o + 6]], align: ALIGNS[f[o + 7]] ?? "left" };
}
return { texts, images };
return out;
}
const ALIGN: Record<RTextAlign, number> = { left: 0, center: 1, right: 2 };
const textEncoder = new TextEncoder();
/** Eingebettete Bilder des Plans (nur Text-/Bild-Einträge, kein Layout). */
function sceneImages(plan: Plan): RImage[] {
const images: RImage[] = [];
for (const { p } of planTextEntries(plan)) {
if (p.kind === "drawingImage") images.push({ min: [p.min.x, p.min.y], max: [p.max.x, p.max.y], src: p.src, opacity: p.opacity });
}
return images;
}
/** Leere render2d-Szene (nur Kopf), falls der Kern nichts liefern kann. */
function emptySceneBin(): Uint8Array {
@@ -295,24 +177,12 @@ function emptySceneBin(): Uint8Array {
/**
* render2d-Szene (Binärformat v1, `render2d/src/scene_bin.rs`) für `set_scene_bin` bzw.
* `push_native_scene`. Geometrie aus dem Kern, Texte aus {@link planSceneTexts};
* `push_native_scene`. Geometrie und Texte (beim Massstab 1:`paperScaleN`) aus dem Kern;
* `plan.greyedRanges` gelten wie materialisiertes `greyed`.
*/
export function planSceneBin(plan: Plan, paperScaleN: number = STAMP_DEFAULT_N): Uint8Array {
const { texts } = planSceneTexts(plan, paperScaleN);
const nums = new Float64Array(texts.length * 9);
const strs = texts.map((t) => textEncoder.encode(t.content));
let nBytes = 0;
for (const s of strs) nBytes += s.length;
const bytes = new Uint8Array(nBytes);
let o = 0;
texts.forEach((t, i) => {
nums.set([t.pos[0], t.pos[1], t.sizeMm, t.color[0], t.color[1], t.color[2], t.color[3], ALIGN[t.align] ?? 0, strs[i].length], i * 9);
bytes.set(strs[i], o);
o += strs[i].length;
});
const greyed = greyedFlat(plan);
const out = withPlanParts(planParts(plan), (segs) => core().plan_scene_bin(segs, greyed, nums, bytes));
const out = withPlanParts(planParts(plan), (segs) => core().plan_scene_bin(segs, greyed, paperScaleN));
return out.length ? out : emptySceneBin();
}
@@ -385,12 +255,10 @@ function decodeSceneF64(f: Float64Array): SceneGeometry {
/**
* Plan → Render-Szene als Objekte (Druck-/SVG-Export, `dossier-cli plan --format json`).
* `paperScaleN` ist der Massstab-Nenner N (1:N) für die Zeilenlage der Texte (s.
* {@link planSceneTexts}).
* `paperScaleN` ist der Massstab-Nenner N (1:N) für die Zeilenlage der Texte.
*/
export function planToRenderScene(plan: Plan, paperScaleN: number = STAMP_DEFAULT_N): RScene {
const greyed = greyedFlat(plan);
const geo = decodeSceneF64(withPlanParts(planParts(plan), (segs) => core().plan_scene_f64(segs, greyed)));
const { texts, images } = planSceneTexts(plan, paperScaleN);
return { ...geo, texts, images, bounds: { ...plan.bounds } };
return { ...geo, texts: sceneTexts(plan, paperScaleN), images: sceneImages(plan), bounds: { ...plan.bounds } };
}
+109 -98
View File
@@ -3,8 +3,12 @@
// nach SVG-<tspan> (für den vektoriellen Grundriss-/Print-Renderer). Beide Wege
// bilden dieselbe Mark→Stil-Zuordnung ab, damit Editor-Vorschau und gezeichneter
// Text identisch aussehen. Reines Modul: keine React-/App-Abhängigkeit.
//
// Das Zeilen-Layout (`docToLines`/`wrapDocToLines`: Run→Tspan, Wortumbruch) rechnet der Rust-Kern
// (`src-tauri/core/src/text_layout.rs`, Bindung `text_lines`); hier nur die Fassade.
import type { Marks, Paragraph, RichTextDoc, TextRun } from "./richText";
import { core } from "../engine/coreWasm";
// ── Text-Escaping ───────────────────────────────────────────────────────────
@@ -172,116 +176,123 @@ export interface SvgTextOptions {
color?: string;
}
/**
* Zerlegt das Dokument in Zeilen/Tspans mit bereits in Benutzereinheiten
* umgerechneten Grössen. Der Aufrufer positioniert die Zeilen selbst (Baseline
* der Zeile i = `y + Σ lineHeight[0..i-1]`).
*/
export function docToLines(doc: RichTextDoc, opts: SvgTextOptions): SvgLine[] {
const basePt = opts.basePt ?? 12;
const color = opts.color ?? "#000000";
const baseUnit = basePt * opts.unitPerPt;
return doc.paragraphs.map((p) => ({
align: p.align ?? "left",
lineHeight: p.lineHeight != null ? baseUnit * p.lineHeight : opts.lineHeight,
tspans: p.runs
.filter((r) => r.text.length > 0)
.map((r) => runToTspan(r, basePt, opts.unitPerPt, color)),
}));
const ALIGNS = ["left", "center", "right"] as const;
/** UTF-16-Einheiten `f[at…at+n)` als Text. */
function unitsText(f: Float64Array, at: number, n: number): string {
let s = "";
for (let j = 0; j < n; j += 4096) s += String.fromCharCode.apply(null, Array.from(f.subarray(at + j, at + Math.min(n, j + 4096))));
return s;
}
/** Geschätzte Zeichenbreite als Vielfaches der Schriftgrösse (gleiche Heuristik
* wie der bisherige Wortumbruch für einheitlich formatierten Text, s.
* PlanView.tsx `case "drawingText"`) — kein echtes Font-Metrics-Messen, aber
* für die Platzierung von Zeilenumbrüchen ausreichend. */
const CHAR_WIDTH_FACTOR = 0.55;
/**
* Flache Zeilen des Kerns (Format s. `src-tauri/core/src/web/text_layout.rs`) → `SvgLine[]`, mit
* `withY` samt Grundlinie `y`. Die Tspan-Texte sind Ausschnitte der Eingabe (`text(Absatz, Run)`).
* Feldreihenfolge der Tspans wie früher in TS.
*/
function decodeLines(f: Float64Array, text: (para: number, run: number) => string, withY: true): PlacedLine[];
function decodeLines(f: Float64Array, text: (para: number, run: number) => string, withY: false): SvgLine[];
function decodeLines(f: Float64Array, text: (para: number, run: number) => string, withY: boolean): Array<SvgLine | PlacedLine> {
if (f.length < 2) return [];
let k = 2;
const styles: Array<Omit<SvgTspan, "text">> = [];
for (let i = 0; i < f[1]; i++) {
const [fontSize, bits, shift, nFill, nFam] = [f[k], f[k + 1], f[k + 2], f[k + 3], f[k + 4]];
k += 5;
const fill = unitsText(f, k, nFill);
k += nFill;
const st: Omit<SvgTspan, "text"> = { fontSize, fill };
if (bits & 1) st.fontWeight = "700";
if (bits & 2) st.fontStyle = "italic";
if (nFam >= 0) {
st.fontFamily = unitsText(f, k, nFam);
k += nFam;
}
const deco = bits & 12;
if (deco) st.textDecoration = deco === 4 ? "underline" : deco === 8 ? "line-through" : "underline line-through";
if (bits & 16) st.baselineShift = shift;
styles.push(st);
}
const out: Array<SvgLine | PlacedLine> = new Array(f[0]);
for (let i = 0; i < f[0]; i++) {
const align = ALIGNS[f[k]] ?? "left";
const lineHeight = f[k + 1];
const y = f[k + 2];
const n = f[k + 3];
k += 4;
const tspans: SvgTspan[] = new Array(n);
for (let j = 0; j < n; j++, k += 5) {
const src = text(f[k + 1], f[k + 2]);
tspans[j] = { text: f[k + 3] === 0 && f[k + 4] === src.length ? src : src.slice(f[k + 3], f[k + 4]), ...styles[f[k]] };
}
out[i] = withY ? { tspans, align, lineHeight, y } : { tspans, align, lineHeight };
}
return out;
}
/** Zuletzt gesetzte Zeilen je Dokument-Objekt und Optionen (Neuzeichnen beim Zoomen/Verschieben). */
const memo = new WeakMap<RichTextDoc, Map<string, SvgLine[]>>();
/** Zeilen aus dem Kern (`text_lines`); kaputte Eingabe → keine Zeilen. Ergebnis nicht verändern (geteilt). */
function kernelLines(doc: RichTextDoc, opts: SvgTextOptions, wrap: number | undefined): SvgLine[] {
const key = `${opts.lineHeight}|${opts.unitPerPt}|${opts.basePt}|${wrap}|${opts.color}`;
let byOpts = memo.get(doc);
const hit = byOpts?.get(key);
if (hit) return hit;
const o = Float64Array.of(opts.lineHeight, opts.unitPerPt, opts.basePt == null ? 0 : 1, opts.basePt ?? 0, wrap ?? NaN);
const lines = decodeLines(core().text_lines(JSON.stringify(doc), o, opts.color ?? undefined), (p, r) => doc.paragraphs[p].runs[r].text, false);
if (!byOpts) memo.set(doc, (byOpts = new Map()));
if (byOpts.size > 8) byOpts.clear();
byOpts.set(key, lines);
return lines;
}
/**
* Zerlegt das Dokument in Zeilen/Tspans mit bereits in Benutzereinheiten
* umgerechneten Grössen (eine Zeile je Absatz). Der Aufrufer positioniert die Zeilen selbst
* (Baseline der Zeile i = `y + Σ lineHeight[0..i-1]`).
*/
export function docToLines(doc: RichTextDoc, opts: SvgTextOptions): SvgLine[] {
return kernelLines(doc, opts, undefined);
}
/**
* Wie {@link docToLines}, bricht aber zusätzlich wortweise auf `wrapWidthUnits`
* um (in denselben Benutzereinheiten wie `SvgTextOptions.x`) — für Textfelder/
* -rahmen mit fester Breite (InDesign-artig). Ohne `wrapWidthUnits` identisch
* zu `docToLines` (eine Zeile je Absatz). Respektiert Run-Grenzen: ein Wort
* behält die Formatierung seines Runs, auch wenn die Zeile mehrere Runs mischt.
* -rahmen mit fester Breite (InDesign-artig). Wortbreite geschätzt (UTF-16-Länge ×
* Schriftgrösse × 0.55, kein Font-Messen). Ohne `wrapWidthUnits` identisch zu `docToLines`.
* Respektiert Run-Grenzen: ein Wort behält die Formatierung seines Runs.
*/
export function wrapDocToLines(
doc: RichTextDoc,
opts: SvgTextOptions & { wrapWidthUnits?: number },
): SvgLine[] {
if (!opts.wrapWidthUnits || opts.wrapWidthUnits <= 0) return docToLines(doc, opts);
const basePt = opts.basePt ?? 12;
const color = opts.color ?? "#000000";
const baseUnit = basePt * opts.unitPerPt;
const maxWidth = opts.wrapWidthUnits;
interface Token {
tspan: SvgTspan;
widthUnits: number;
isSpace: boolean;
}
const lines: SvgLine[] = [];
for (const p of doc.paragraphs) {
const lineHeight = p.lineHeight != null ? baseUnit * p.lineHeight : opts.lineHeight;
const align = p.align ?? "left";
const tokens: Token[] = [];
for (const run of p.runs) {
if (run.text.length === 0) continue;
const base = runToTspan(run, basePt, opts.unitPerPt, color);
for (const part of run.text.split(/(\s+)/).filter((s) => s.length > 0)) {
const isSpace = /^\s/.test(part);
tokens.push({
tspan: { ...base, text: part },
widthUnits: part.length * base.fontSize * CHAR_WIDTH_FACTOR,
isSpace,
});
}
}
if (tokens.length === 0) {
lines.push({ tspans: [], align, lineHeight });
continue;
}
let current: Token[] = [];
let currentWidth = 0;
const flush = () => {
while (current.length && current[current.length - 1].isSpace) current.pop();
lines.push({ tspans: current.map((t) => t.tspan), align, lineHeight });
current = [];
currentWidth = 0;
};
for (const tok of tokens) {
if (current.length === 0 && tok.isSpace) continue;
if (current.length > 0 && currentWidth + tok.widthUnits > maxWidth) {
flush();
if (tok.isSpace) continue;
}
current.push(tok);
currentWidth += tok.widthUnits;
}
flush();
}
return lines;
return kernelLines(doc, opts, opts.wrapWidthUnits);
}
function runToTspan(run: TextRun, basePt: number, unitPerPt: number, color: string): SvgTspan {
const m = run.marks;
const script = m.super || m.sub;
const sizePt = (m.sizePt ?? basePt) * (script ? SCRIPT_SCALE : 1);
const fontSize = sizePt * unitPerPt;
const tspan: SvgTspan = {
text: run.text,
fontSize: round(fontSize),
fill: m.color ?? color,
};
if (m.bold) tspan.fontWeight = "700";
if (m.italic) tspan.fontStyle = "italic";
if (m.font) tspan.fontFamily = m.font;
const deco = textDecoration(m);
if (deco) tspan.textDecoration = deco;
if (m.super) tspan.baselineShift = round(fontSize * 0.35);
if (m.sub) tspan.baselineShift = round(-fontSize * 0.2);
return tspan;
/** Eine gesetzte Zeile mit ihrer Grundlinie `y` (Bildschirm: nach unten wachsend). */
export type PlacedLine = SvgLine & { y: number };
/**
* Raumstempel-Block (Kern `stamp_block`): Rich-Text-Zeilen (Vorschub 1.3 × Basisgrösse bzw. die
* Absatz-Zeilenhöhe) und darunter die Live-Zeilen (0.8 × Basisgrösse), vertikal um `y0` zentriert.
* `stamp` ist das Plan-Primitiv `text`.
*/
export function stampBlockLines(
stamp: { at: { x: number; y: number }; doc: RichTextDoc; extraLines: ReadonlyArray<{ text: string; align: string }>; basePt: number; color?: string },
unitPerPt: number,
y0: number,
): PlacedLine[] {
const n = stamp.doc.paragraphs.length;
const text = (p: number, r: number): string => (p < n ? stamp.doc.paragraphs[p].runs[r].text : stamp.extraLines[p - n].text);
return decodeLines(core().text_stamp_block(JSON.stringify(stamp), unitPerPt, y0), text, true);
}
/**
* Einfacher Text (ohne Rich-Dokument) auf die Spalte `wrap` umbrochen: Absätze an `\n`, Wörter mit
* einem Leerzeichen verbunden, geschätzte Zeichenbreite 0.55 × `fontSize` (gleiche Einheiten).
*/
export function wrapPlainText(text: string, wrap: number, fontSize: number): string[] {
const json = core().text_wrap_plain(text, wrap, fontSize);
return json ? (JSON.parse(json) as string[]) : [text];
}
+10 -43
View File
@@ -11,8 +11,8 @@
import type { Vec2 } from "../model/types";
import type { Marks, RichTextDoc } from "./richText";
import { docFromText } from "./richText";
import { wrapDocToLines } from "./renderHtml";
import { contentFontBaselineFromTop, TEXT_LINE_HEIGHT_MULT } from "./fontMetrics";
import { core } from "../engine/coreWasm";
/** Minimale Felder, die `textFrameCorners` braucht — sowohl `Primitive`
* ("drawingText", PlanView.tsx) als auch `Drawing2DGeom["text"]`
@@ -30,52 +30,19 @@ export interface TextFrameInput {
wrapWidth?: number;
}
/** Geschätzter Zeichenbreite-Faktor je Schriftgrösse — deckt sich mit
* `CHAR_WIDTH_FACTOR` in `renderHtml.ts` (dort nicht exportiert; kein echtes
* Font-Measuring im SVG, reicht aber für Rahmen/Griffe). */
const TEXT_CHAR_WIDTH_FACTOR = 0.55;
/**
* Vier Eckpunkte (Modell-Meter, Reihenfolge oben-links · oben-rechts ·
* unten-rechts · unten-links VOR Rotation) eines groben Rahmens um einen
* gezeichneten Text. Höhe aus der ECHTEN Zeilenzahl (`wrapDocToLines`,
* dieselbe Umbruch-Logik wie beim Rendern in `primitives.tsx`
* "drawingText"), Breite aus der längsten Zeile geschätzt (oder `wrapWidth`,
* falls gesetzt — dann ist die Spaltenbreite exakt bekannt). `at` ist die
* Baseline-links der ERSTEN Zeile; Rotation um `angle` (CCW, Modell-Radiant)
* um genau diesen Punkt, analog zum SVG-`rotate` beim eigentlichen Rendern.
* gezeichneten Text. Rechnet der Kern (`text_layout::text_frame_corners`): Höhe aus der
* ECHTEN Zeilenzahl (derselbe Umbruch wie beim Rendern), Breite aus der längsten Zeile
* geschätzt (UTF-16-Länge × Höhe × 0.55, oder `wrapWidth`, falls gesetzt). `at` ist die
* Baseline-links der ERSTEN Zeile; Rotation um `angle` (CCW, Modell-Radiant) um genau
* diesen Punkt. Hier bleibt nur die Canvas-Messung Baseline → Oberkante.
*/
export function textFrameCorners(p: TextFrameInput): Vec2[] {
const doc = p.doc ?? docFromText(p.text, p.marks ?? {});
const lineHeight = p.heightM * TEXT_LINE_HEIGHT_MULT;
const wrapWidthUnits = p.wrapWidth && p.wrapWidth > 0 ? p.wrapWidth : undefined;
const lines = wrapDocToLines(doc, {
x: 0,
y: 0,
lineHeight,
unitPerPt: 1,
basePt: p.heightM,
...(wrapWidthUnits ? { wrapWidthUnits } : {}),
});
const maxLineChars = lines.length
? Math.max(1, ...lines.map((l) => l.tspans.reduce((n, t) => n + t.text.length, 0)))
: 1;
const width =
wrapWidthUnits ?? Math.max(p.heightM, maxLineChars * p.heightM * TEXT_CHAR_WIDTH_FACTOR);
const height = Math.max(1, lines.length) * lineHeight;
// Baseline → Oberkante erste Zeile: echtes Font-Measuring statt der groben
// "ganzes heightM"-Näherung.
const top = p.heightM * contentFontBaselineFromTop(TEXT_LINE_HEIGHT_MULT);
const local: Vec2[] = [
{ x: 0, y: top },
{ x: width, y: top },
{ x: width, y: top - height },
{ x: 0, y: top - height },
];
const cos = Math.cos(p.angle);
const sin = Math.sin(p.angle);
return local.map((l) => ({
x: p.at.x + l.x * cos - l.y * sin,
y: p.at.y + l.x * sin + l.y * cos,
}));
const top = contentFontBaselineFromTop(TEXT_LINE_HEIGHT_MULT);
const f = core().text_frame(JSON.stringify(doc), Float64Array.of(p.at.x, p.at.y, p.heightM, p.angle, p.wrapWidth ?? NaN, top));
if (f.length !== 8) return [p.at, p.at, p.at, p.at].map((q) => ({ x: q.x, y: q.y }));
return [0, 2, 4, 6].map((i) => ({ x: f[i], y: f[i + 1] }));
}
+7 -50
View File
@@ -5,7 +5,7 @@
import type { HatchRender, Primitive } from "../../../core";
import { NO_HATCH } from "../../../core";
import { docToLines, wrapDocToLines, type SvgLine } from "../../../text/renderHtml";
import { stampBlockLines, wrapDocToLines, wrapPlainText, type SvgLine } from "../../../text/renderHtml";
import type { Vec2 } from "../../../model/types";
import { quantizePen } from "../../../export/sceneToPrintSvg";
import { buildRandomHatchRuns, zigzagPoints, motifPoints, DASH_MM_TO_M } from "../../../core";
@@ -707,37 +707,10 @@ export function renderPrimitive(
// verankert). unitPerPt bildet 1 pt auf viewBox-Einheiten ab.
const nRef = print ? paperScale! : 100;
const unitPerPt = (1 / 72) * 0.0254 * nRef * PX_PER_M;
const baseFs = p.basePt * unitPerPt;
const lineGap = baseFs * 1.3;
// Rich-Text-Zeilen (Stempel-Doc) + LIVE-Zusatzzeilen (Fläche/SIA) darunter.
const docLines: SvgLine[] = docToLines(p.doc, {
x: 0,
y: 0,
lineHeight: lineGap,
unitPerPt,
basePt: p.basePt,
color: p.color,
});
const extra: SvgLine[] = p.extraLines.map((line) => ({
align: line.align,
lineHeight: lineGap,
tspans: [{ text: line.text, fontSize: baseFs * 0.8, fill: p.color }],
}));
const lines = [...docLines, ...extra];
// Rich-Text-Zeilen (Stempel-Doc) + LIVE-Zusatzzeilen (Fläche/SIA) darunter, Block vertikal
// um den Anker zentriert (Kern `stamp_block`, absatzeigene Zeilenhöhen inbegriffen).
const lines = stampBlockLines(p, unitPerPt, c.y);
if (lines.length === 0) return null;
// Block vertikal um den Anker zentrieren. Absätze können eine eigene
// Zeilenhöhe tragen (Text-Gruppe, Zeilenhöhe-Regler) — darum kumulierte
// Vorschübe statt eines einzigen festen lineGap.
const totalH = baseFs + lines.slice(1).reduce((sum, l) => sum + l.lineHeight, 0);
const startY = c.y - totalH / 2 + baseFs * 0.8;
const lineYs: number[] = [];
{
let y = startY;
lines.forEach((line, k) => {
if (k > 0) y += line.lineHeight;
lineYs.push(y);
});
}
return (
<text style={{ pointerEvents: "none", userSelect: "none" }}>
{lines.map((line, k) => {
@@ -751,7 +724,7 @@ export function renderPrimitive(
<tspan
key={k}
x={c.x}
y={lineYs[k]}
y={line.y}
textAnchor={anchor}
>
{line.tspans.map((ts, j) => (
@@ -870,25 +843,9 @@ export function renderPrimitive(
// Alt-Pfad: einfacher String + einheitliche `marks` (Text-Werkzeug/DXF-Import
// ohne Rich-Doc) — unverändert.
// Spaltentext: bei gesetzter `wrapWidth` den Text wortweise auf die Breite
// umbrechen (Zeichenbreite ≈ 0.55·fontSize geschätzt), sonst eine Zeile.
// umbrechen (Kern `wrap_plain`, Zeichenbreite ≈ 0.55·fontSize geschätzt), sonst eine Zeile.
const lineH = fontSize * 1.25;
const lines: string[] = [];
if (p.wrapWidth && p.wrapWidth > 0) {
const maxPx = p.wrapWidth * PX_PER_M;
const charPx = fontSize * 0.55;
const maxChars = Math.max(1, Math.floor(maxPx / charPx));
for (const paragraph of p.text.split("\n")) {
let line = "";
for (const word of paragraph.split(/\s+/)) {
if (line === "") line = word;
else if ((line.length + 1 + word.length) <= maxChars) line += " " + word;
else { lines.push(line); line = word; }
}
lines.push(line);
}
} else {
lines.push(p.text);
}
const lines: string[] = p.wrapWidth && p.wrapWidth > 0 ? wrapPlainText(p.text, p.wrapWidth * PX_PER_M, fontSize) : [p.text];
// Einheitliche Formatierung (Text-Werkzeug + Oberleisten-Formatier-Gruppe):
// Schriftfamilie/fett/kursiv/Unterstreichung aus `marks`; Grösse bleibt über
// heightM (Modell-Meter). Farbe steckt bereits in p.color (marks.color-Vorrang