[K3d] Text-Lage im Kern: Zeilen x/y/Anker aus text_layout, TS legt nur Knoten an

place_lines/LineAlign::anchor im Kern; text_lines und text_stamp_block liefern
gesetzte Zeilen. layoutText/annotationTextLines ersetzen docToLines/wrapDocToLines
(gelöscht); SVG-Rückfall der Plan-Ansicht, Layout-Blatt und Layout-PDF rechnen
keine Zeilen-Lage mehr. Ausgabe byte-gleich (temporärer Paritätstest).
This commit is contained in:
Claude committed 2026-10-29 10:29:00 +00:00
1 parent 0568a8c8c8
commit 855478c636
9 files changed
+200 -182

No files matched your search

+10
View File
@@ -299,6 +299,16 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern
Rich-Text mit Spalte, Masszahl 4 mm, Kote, Raumstempel) + Rust-Tests; Druck-SVG vorher/nachher in Chromium angesehen.
Offen: Run-eigene `sizePt` in Einzeltexten bedeuten in SVG-Ansicht und Druck Modell-pt, in der Render-Szene (GPU)
Papier-pt bei 1:100 — uneinheitlich (Editor setzt sie relativ zu 12 pt); Text entlang Pfad fehlt im Druck-SVG.
✅ (30.10.) Zeilen-Lage im Kern: `text_layout::place_lines` (x/Grundlinie je Zeile, Mitte/rechts in der Spalte) und
`LineAlign::anchor`; Druck-SVG und die Bindungen `text_lines` (jetzt mit Anker x/y und Spaltenbreite) und
`text_stamp_block` (mit x) liefern gesetzte Zeilen (`x`, `y`, Anker). TS rechnet keine Zeilen-Lage mehr:
`layoutText`/`annotationTextLines` (`renderHtml.ts`) ersetzen `docToLines`/`wrapDocToLines` (gelöscht); SVG-Rückfall
der Plan-Ansicht (Einzeltexte, Raumstempel), Layout-Blatt und Layout-PDF legen nur noch Knoten an. Gleichheit
(temporärer Test alt gegen neu, danach entfernt): 400 Layout-Markups (Blatt-JSX + PDF-DOM; Breite fehlt/0/negativ/
NaN), 400 Einzeltexte/Raumstempel × Anzeige/1:50/1:200 und 3 Druck-SVG mit 80 Zufalls-Rich-Texten — Ausgabe
byte-gleich (18 819 Tspans). Der einfache Mehrzeilen-Text ohne Doc (`dy`) bleibt in der Plan-Ansicht wie er ist.
`nativeText.ts` (macOS) nicht umgestellt: setzt nur einzeilige Texte ohne Doc/Spalte, rechnet kein Layout (Anker =
`at`, Grösse = Höhe); die Farbumrechnung (`rgb()`-fähig) weicht von `plan_scene::to_rgba` ab — nicht doppelt.
Nicht in der Tauri-App angesehen (nativer Text-Pfad `nativeText.ts` unverändert).
Nachteile (bewusst): Übergang mit doppelter Datenhaltung, Format muss TS/Rust gleich bleiben
(Versionsnummer + Hin-und-zurück-Tests), Text-Layout bleibt bis [K4] in TS.
+7 -24
View File
@@ -27,7 +27,7 @@ use crate::jsnum;
use crate::plan_buf::{whole, Rec, View, F_COLOR, F_DASH_NULL, F_OPACITY, T_ARC, T_CIRCLE, T_DRAWING_ARC, T_DRAWING_TEXT, T_IMAGE, T_LINE, T_POLYGON, T_TEXT};
use crate::plan_parts::{greyed_of, Part};
use crate::plan_text::{SingleText, StampText};
use crate::text_layout::{stamp_block, wrap_doc_to_lines, Line, LayoutOpts, LineAlign, PT_TO_MM, TEXT_LINE_HEIGHT_MULT};
use crate::text_layout::{place_lines, stamp_block, wrap_doc_to_lines, Line, LayoutOpts, LineAlign, PT_TO_MM, TEXT_LINE_HEIGHT_MULT};
use std::f64::consts::PI;
/// Optionen: Massstab-Nenner, Blatt (mm) und Ausmass des Plans (`Plan.bounds`).
@@ -494,28 +494,16 @@ fn text_node(out: &mut Out, t: &SingleText, m: Map, opacity: String) {
attrs.push(("opacity", opacity));
}
out.tagged(&["X"], &attrs);
// `!wrapWidthUnits`: 0/NaN zählen wie keine Spalte.
let col = wrap.filter(|w| *w != 0.0 && !w.is_nan());
let mut y = c.y;
for (n, line) in lines.iter().enumerate() {
if n > 0 {
y += line.line_height;
}
let (anchor, x) = match (line.align, col) {
(LineAlign::Center, Some(w)) => ("middle", c.x + w / 2.0),
(LineAlign::Right, Some(w)) => ("end", c.x + w),
(LineAlign::Center, None) => ("middle", c.x),
(LineAlign::Right, None) => ("end", c.x),
(LineAlign::Left, _) => ("start", c.x),
};
let at = place_lines(lines.iter().map(|l| (l.align, l.line_height)), c.x, c.y, wrap);
for (line, (x, y)) in lines.iter().zip(at) {
let content = if line.tspans.is_empty() { "\u{200b}" } else { "" };
line_node(out, line, content, x, y, anchor);
line_node(out, line, content, x, y);
}
}
/// Zeilen-`<tspan>` mit je einem Run-`<tspan>`.
fn line_node(out: &mut Out, line: &Line, content: &str, x: f64, y: f64, anchor: &str) {
out.tagged(&["L", content], &[("x", r3(x)), ("y", r3(y)), ("text-anchor", anchor.to_string())]);
fn line_node(out: &mut Out, line: &Line, content: &str, x: f64, y: f64) {
out.tagged(&["L", content], &[("x", r3(x)), ("y", r3(y)), ("text-anchor", line.align.anchor().to_string())]);
for ts in &line.tspans {
let mut a: Vec<(&str, String)> = vec![("font-size", r3(ts.font_size)), ("fill", ts.fill.clone())];
if let Some(w) = ts.font_weight() {
@@ -545,12 +533,7 @@ fn stamp_node(out: &mut Out, t: &StampText, m: Map, opacity: String) {
let attrs: Vec<(&str, String)> = if opacity.is_empty() { Vec::new() } else { vec![("opacity", opacity)] };
out.tagged(&["X"], &attrs);
for p in &placed {
let anchor = match p.line.align {
LineAlign::Center => "middle",
LineAlign::Right => "end",
LineAlign::Left => "start",
};
line_node(out, &p.line, "", c.x, p.y, anchor);
line_node(out, &p.line, "", c.x, p.y);
}
}
+45
View File
@@ -44,6 +44,14 @@ impl LineAlign {
_ => LineAlign::Left,
}
}
/// SVG-`text-anchor` der Zeile.
pub fn anchor(self) -> &'static str {
match self {
LineAlign::Left => "start",
LineAlign::Center => "middle",
LineAlign::Right => "end",
}
}
/// 0 links · 1 Mitte · 2 rechts (render2d, DXF).
pub fn code(self) -> u32 {
match self {
@@ -346,6 +354,30 @@ pub fn wrap_doc_to_lines(doc: &RichTextDoc, o: &LayoutOpts, wrap: Option<f64>) -
lines_of(doc, layout_refs(doc, o, wrap), o)
}
/// Lage der Zeilen eines Textblocks (früher je Verbraucher in TS: SVG-Rückfall der Plan-Ansicht,
/// Layout-Blatt, Layout-PDF, Druck-SVG): `rows` = (Ausrichtung, Vorschub) je Zeile → (x, Grundlinie
/// y) je Zeile. Die erste Grundlinie liegt bei `y`, jede weitere um ihren Vorschub tiefer (`y` wächst
/// nach unten); x am Anker bzw. mit Spaltenbreite `col` Mitte/rechts in der Spalte (0/NaN = keine
/// Spalte, wie `!width` in TS).
pub fn place_lines(rows: impl IntoIterator<Item = (LineAlign, f64)>, x: f64, y: f64, col: Option<f64>) -> Vec<(f64, f64)> {
let col = col.filter(|w| *w != 0.0 && !w.is_nan());
let mut y = y;
rows.into_iter()
.enumerate()
.map(|(n, (align, lh))| {
if n > 0 {
y += lh;
}
let x = match (align, col) {
(LineAlign::Center, Some(w)) => x + w / 2.0,
(LineAlign::Right, Some(w)) => x + w,
_ => x,
};
(x, y)
})
.collect()
}
/// Eine gesetzte Zeile mit ihrer Grundlinie (`y`).
#[derive(Clone, Debug, PartialEq)]
pub struct Placed {
@@ -539,6 +571,19 @@ mod tests {
lines.iter().map(Line::content).collect()
}
#[test]
fn zeilen_lage_am_anker_und_in_der_spalte() {
let rows = [(LineAlign::Left, 9.0), (LineAlign::Center, 2.5), (LineAlign::Right, 4.0)];
// Erste Grundlinie am Anker, jede weitere um ihren Vorschub tiefer.
assert_eq!(place_lines(rows, 1.0, 10.0, None), [(1.0, 10.0), (1.0, 12.5), (1.0, 16.5)]);
// Spalte: Mitte/rechts in der Spalte; 0/NaN wie keine, negativ zählt (wie `!width` in TS).
assert_eq!(place_lines(rows, 1.0, 10.0, Some(6.0)), [(1.0, 10.0), (4.0, 12.5), (7.0, 16.5)]);
assert_eq!(place_lines(rows, 1.0, 10.0, Some(0.0)), place_lines(rows, 1.0, 10.0, None));
assert_eq!(place_lines(rows, 1.0, 10.0, Some(f64::NAN)), place_lines(rows, 1.0, 10.0, None));
assert_eq!(place_lines(rows, 1.0, 10.0, Some(-2.0))[2], (-1.0, 16.5));
assert_eq!([LineAlign::Left, LineAlign::Center, LineAlign::Right].map(LineAlign::anchor), ["start", "middle", "end"]);
}
#[test]
fn ohne_spalte_eine_zeile_je_absatz() {
let d = doc_from_text("hallo welt\n\nzwei", &Marks::default());
+18 -14
View File
@@ -6,12 +6,13 @@
//! Zeilen kommen flach zurück (`encode_lines`): `[nZeilen, nStile, Stil*, Zeile*]`;
//! Stil = `[Grösse, Bits, Versatz, nFarbe, nSchrift (−1 = keine), Farbe…, Schrift…]` (Bits: 1 fett,
//! 2 kursiv, 4 unterstrichen, 8 durchgestrichen, 16 mit Versatz; Texte als UTF-16-Einheiten);
//! Zeile = `[Ausrichtung 0/1/2, Vorschub, y (NaN = keins), nTspans, (Stil, Absatz, Run, von, bis)*]`
//! Zeile = `[Ausrichtung 0/1/2, Vorschub, x, Grundlinie y, nTspans, (Stil, Absatz, Run, von, bis)*]`
//! (Lage aus [`place_lines`] bzw. dem Raumstempel-Block — die Verbraucher rechnen keine Lage mehr)
//! — der Text eines Tspans ist `runs[Run].text.slice(von, bis)` des Absatzes in der Eingabe (TS hat
//! sie schon; keine Texte über die Grenze zurück).
use crate::model::RichTextDoc;
use crate::text_layout::{layout_refs, tspan_of, stamp_block_refs, stamp_extra_tspan, text_frame_corners, wrap_plain, LayoutOpts, LineAlign, LineRef, Tok, Tspan};
use crate::text_layout::{layout_refs, place_lines, tspan_of, stamp_block_refs, stamp_extra_tspan, text_frame_corners, wrap_plain, LayoutOpts, LineAlign, LineRef, Tok, Tspan};
use wasm_bindgen::prelude::wasm_bindgen;
fn style_bits(t: &Tspan) -> f64 {
@@ -25,14 +26,15 @@ fn style_bits(t: &Tspan) -> f64 {
}
/// Verweis-Zeilen flach (Format s. Modulkopf); `style(tok)` = Stil (Tspan ohne Text) des Stücks,
/// `ys` = Grundlinien je Zeile.
fn encode_lines(lines: &[LineRef], ys: Option<&[f64]>, style: impl Fn(&Tok) -> Tspan) -> Vec<f64> {
/// `at` = (x, Grundlinie) je Zeile.
fn encode_lines(lines: &[LineRef], at: &[(f64, f64)], style: impl Fn(&Tok) -> Tspan) -> Vec<f64> {
let mut styles: Vec<Tspan> = Vec::new();
let mut keys: Vec<(usize, usize)> = Vec::new();
let mut key_style: Vec<usize> = Vec::new();
let mut body: Vec<f64> = Vec::new();
for (k, l) in lines.iter().enumerate() {
body.extend_from_slice(&[l.align.code() as f64, l.line_height, ys.and_then(|y| y.get(k).copied()).unwrap_or(f64::NAN), l.toks.len() as f64]);
let (x, y) = at.get(k).copied().unwrap_or((f64::NAN, f64::NAN));
body.extend_from_slice(&[l.align.code() as f64, l.line_height, x, y, l.toks.len() as f64]);
for t in &l.toks {
let si = match keys.iter().position(|q| *q == (t.para, t.run)) {
Some(i) => key_style[i],
@@ -73,16 +75,18 @@ fn encode_lines(lines: &[LineRef], ys: Option<&[f64]>, style: impl Fn(&Tok) -> T
out
}
/// Zeilen eines Dokuments (`SvgLine[]`, flach). `opts` = `[lineHeight, unitPerPt, basePt gesetzt
/// 0/1, basePt, Spaltenbreite]` (Spalte ≤ 0/NaN = kein Umbruch); `color` fehlt → `#000000`.
/// Gesetzte Zeilen eines Dokuments (`PlacedLine[]`, flach). `opts` = `[lineHeight, unitPerPt,
/// basePt gesetzt 0/1, basePt, Umbruchbreite, x, y, Spaltenbreite]` (Umbruch ≤ 0/NaN = keiner;
/// Spalte 0/NaN = keine, sonst Mitte/rechts darin, s. [`place_lines`]); `color` fehlt → `#000000`.
/// Leer = kaputte Eingabe.
#[wasm_bindgen]
pub fn text_lines(doc_json: &str, opts: &[f64], color: Option<String>) -> Vec<f64> {
let Ok([line_height, unit_per_pt, has_base, base_pt, wrap]) = <[f64; 5]>::try_from(opts) else { return Vec::new() };
let Ok([line_height, unit_per_pt, has_base, base_pt, wrap, x, y, col]) = <[f64; 8]>::try_from(opts) else { return Vec::new() };
let Ok(doc) = serde_json::from_str::<RichTextDoc>(doc_json) else { return Vec::new() };
let o = LayoutOpts { line_height, unit_per_pt, base_pt: if has_base != 0.0 { base_pt } else { 12.0 }, color: color.as_deref().unwrap_or("#000000") };
let refs = layout_refs(&doc, &o, Some(wrap));
encode_lines(&refs, None, |t| tspan_of(String::new(), &doc.paragraphs[t.para].runs[t.run].marks, o.base_pt, o.unit_per_pt, o.color))
let at = place_lines(refs.iter().map(|l| (l.align, l.line_height)), x, y, Some(col));
encode_lines(&refs, &at, |t| tspan_of(String::new(), &doc.paragraphs[t.para].runs[t.run].marks, o.base_pt, o.unit_per_pt, o.color))
}
/// Rahmen eines Einzeltexts: `opts` = `[atX, atY, heightM, angle, Spaltenbreite (NaN = keine),
@@ -96,18 +100,18 @@ pub fn text_frame(doc_json: &str, opts: &[f64]) -> Vec<f64> {
}
/// Raumstempel-Block der Plan-Ansicht (`stamp_block_refs`): `prim_json` = das Primitiv `text`;
/// Zeilen flach mit Grundlinie `y` (um `y0` zentriert, `y` nach unten; Live-Zeile `i` als Absatz
/// Absatzzahl + `i`). Leer = kaputte Eingabe.
/// Zeilen flach mit x = `x0` und Grundlinie `y` (um `y0` zentriert, `y` nach unten; Live-Zeile `i`
/// als Absatz Absatzzahl + `i`). Leer = kaputte Eingabe.
#[wasm_bindgen]
pub fn text_stamp_block(prim_json: &str, unit_per_pt: f64, y0: f64) -> Vec<f64> {
pub fn text_stamp_block(prim_json: &str, unit_per_pt: f64, x0: f64, y0: f64) -> Vec<f64> {
let Ok(p) = serde_json::from_str::<crate::plan_text::StampText>(prim_json) else { return Vec::new() };
let extra: Vec<(&str, LineAlign)> = p.extra_lines.iter().map(|l| (l.text.as_str(), LineAlign::of(Some(l.align)))).collect();
let color = p.color.as_deref().unwrap_or("#000000");
let placed = stamp_block_refs(&p.doc, &extra, p.base_pt, unit_per_pt, color, y0);
let ys: Vec<f64> = placed.iter().map(|q| q.1).collect();
let at: Vec<(f64, f64)> = placed.iter().map(|q| (x0, q.1)).collect();
let lines: Vec<LineRef> = placed.into_iter().map(|q| q.0).collect();
let n = p.doc.paragraphs.len();
encode_lines(&lines, Some(&ys), |t| {
encode_lines(&lines, &at, |t| {
if t.para >= n {
stamp_extra_tspan(String::new(), p.base_pt, unit_per_pt, color)
} else {
+6 -27
View File
@@ -15,7 +15,7 @@ import "svg2pdf.js";
import type { Layout, LayoutAnnotation, MasterLayout, Project } from "../model/types";
import { generatePlan } from "../plan/generatePlan";
import { planToPrintSvg } from "./planToPrintSvg";
import { wrapDocToLines, type SvgLine } from "../text/renderHtml";
import { annotationTextLines } from "../text/renderHtml";
import { docFromText } from "../text/richText";
import {
findMaster,
@@ -122,33 +122,12 @@ function buildAnnotationTextsSvg(
svg.setAttribute("viewBox", `0 0 ${sheetW} ${sheetH}`);
for (const ann of texts) {
const doc = ann.doc ?? docFromText(ann.text);
const lineHeight = ann.heightMm * 1.25;
const lines: SvgLine[] = wrapDocToLines(doc, {
x: 0,
y: 0,
lineHeight,
unitPerPt: 25.4 / 72,
basePt: (ann.heightMm / 25.4) * 72,
color: ann.color ?? "#111111",
...(ann.widthMm && ann.widthMm > 0 ? { wrapWidthUnits: ann.widthMm } : {}),
});
let y = ann.yMm;
const el = document.createElementNS(SVG_NS, "text");
lines.forEach((line, k) => {
if (k > 0) y += line.lineHeight;
const anchor = line.align === "center" ? "middle" : line.align === "right" ? "end" : "start";
const x = !ann.widthMm
? ann.xMm
: line.align === "center"
? ann.xMm + ann.widthMm / 2
: line.align === "right"
? ann.xMm + ann.widthMm
: ann.xMm;
for (const line of annotationTextLines(ann, ann.doc ?? docFromText(ann.text))) {
const lineTspan = document.createElementNS(SVG_NS, "tspan");
lineTspan.setAttribute("x", String(x));
lineTspan.setAttribute("y", String(y));
lineTspan.setAttribute("text-anchor", anchor);
lineTspan.setAttribute("x", String(line.x));
lineTspan.setAttribute("y", String(line.y));
lineTspan.setAttribute("text-anchor", line.anchor);
if (line.tspans.length === 0) {
lineTspan.textContent = "​";
} else {
@@ -165,7 +144,7 @@ function buildAnnotationTextsSvg(
}
}
el.appendChild(lineTspan);
});
}
svg.appendChild(el);
}
return svg;
+37 -11
View File
@@ -1,21 +1,47 @@
// Tests für wrapDocToLines: Wortumbruch auf feste Breite unter Erhalt der
// Run-Grenzen (gemischte Formatierung pro Zeile bleibt möglich).
// Tests für layoutText: Wortumbruch auf feste Breite unter Erhalt der
// Run-Grenzen (gemischte Formatierung pro Zeile bleibt möglich) und Lage der Zeilen.
import { describe, expect, it } from "vitest";
import { docFromText, makeRun, type RichTextDoc } from "./richText";
import { docToHtml, docToLines, runCssProps, wrapDocToLines } from "./renderHtml";
import { annotationTextLines, docToHtml, layoutText, runCssProps } from "./renderHtml";
const OPTS = { x: 0, y: 0, lineHeight: 10, unitPerPt: 1, basePt: 10, color: "#000000" };
describe("wrapDocToLines", () => {
it("ohne wrapWidthUnits identisch zu docToLines (eine Zeile je Absatz)", () => {
const doc = docFromText("hallo welt");
expect(wrapDocToLines(doc, OPTS)).toEqual(docToLines(doc, OPTS));
describe("layoutText", () => {
it("ohne wrapWidthUnits eine Zeile je Absatz", () => {
const doc = docFromText("hallo welt\nzwei");
expect(layoutText(doc, OPTS).map((l) => l.tspans.map((t) => t.text).join(""))).toEqual(["hallo welt", "zwei"]);
expect(layoutText(doc, { ...OPTS, wrapWidthUnits: 0 })).toEqual(layoutText(doc, OPTS));
});
it("Lage: erste Grundlinie am Anker, weitere um den Vorschub tiefer; Mitte/rechts in der Spalte", () => {
const doc: RichTextDoc = {
version: 1,
paragraphs: [
{ runs: [makeRun("a")] },
{ runs: [makeRun("b")], align: "center", lineHeight: 2 },
{ runs: [makeRun("c")], align: "right" },
],
};
const at = (o: object) => layoutText(doc, { ...OPTS, x: 5, y: 7, ...o }).map((l) => [l.x, l.y, l.anchor]);
expect(at({})).toEqual([[5, 7, "start"], [5, 27, "middle"], [5, 37, "end"]]);
expect(at({ columnWidth: 40 })).toEqual([[5, 7, "start"], [25, 27, "middle"], [45, 37, "end"]]);
expect(at({ columnWidth: NaN })).toEqual(at({}));
});
it("Layout-Markup: Basis = Höhe in mm, Vorschub 1.25 × Höhe, Rahmen nur bei Breite > 0 umbrochen", () => {
const doc = docFromText("eins zwei drei");
const l = annotationTextLines({ xMm: 10, yMm: 20, heightMm: 4, widthMm: 15 }, doc);
expect(l.map((x) => x.y)).toEqual([20, 25, 30]);
expect(l[0].tspans[0]).toMatchObject({ fontSize: 4, fill: "#111111" });
// Negative Breite: kein Umbruch, aber (wie früher) Spalte für die Lage.
const r = annotationTextLines({ xMm: 10, yMm: 20, heightMm: 4, widthMm: -6 }, { version: 1, paragraphs: [{ runs: [makeRun("x")], align: "right" }] });
expect([r.length, r[0].x]).toEqual([1, 4]);
});
it("bricht lange Absätze wortweise auf mehrere Zeilen um", () => {
const doc = docFromText("eins zwei drei vier fünf");
const lines = wrapDocToLines(doc, { ...OPTS, wrapWidthUnits: 30 });
const lines = layoutText(doc, { ...OPTS, wrapWidthUnits: 30 });
expect(lines.length).toBeGreaterThan(1);
const joined = lines.map((l) => l.tspans.map((t) => t.text).join("")).join(" ");
expect(joined.replace(/\s+/g, " ").trim()).toBe("eins zwei drei vier fünf");
@@ -34,7 +60,7 @@ describe("wrapDocToLines", () => {
},
],
};
const lines = wrapDocToLines(doc, { ...OPTS, wrapWidthUnits: 1000 });
const lines = layoutText(doc, { ...OPTS, wrapWidthUnits: 1000 });
expect(lines).toHaveLength(1);
const boldTspan = lines[0].tspans.find((t) => t.text === "fett");
expect(boldTspan?.fontWeight).toBe("700");
@@ -44,14 +70,14 @@ describe("wrapDocToLines", () => {
it("leerer Absatz erzeugt eine leere Zeile (Vorschub bleibt erhalten)", () => {
const doc: RichTextDoc = { version: 1, paragraphs: [{ runs: [] }, { runs: [makeRun("x")] }] };
const lines = wrapDocToLines(doc, { ...OPTS, wrapWidthUnits: 100 });
const lines = layoutText(doc, { ...OPTS, wrapWidthUnits: 100 });
expect(lines).toHaveLength(2);
expect(lines[0].tspans).toHaveLength(0);
});
it("sehr schmale Breite bricht auf ein Wort je Zeile um, ohne Wörter zu verlieren", () => {
const doc = docFromText("aa bb cc");
const lines = wrapDocToLines(doc, { ...OPTS, wrapWidthUnits: 1 });
const lines = layoutText(doc, { ...OPTS, wrapWidthUnits: 1 });
const words = lines.map((l) => l.tspans.map((t) => t.text).join("").trim());
expect(words).toEqual(["aa", "bb", "cc"]);
});
+59 -46
View File
@@ -4,7 +4,7 @@
// 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
// Das Zeilen-Layout (`layoutText`: Run→Tspan, Wortumbruch, Lage x/y/Anker je Zeile) 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";
@@ -145,18 +145,24 @@ export interface SvgTspan {
baselineShift?: number;
}
/** Eine gerenderte Zeile (= Absatz) mit ihren Runs. */
/** Eine gesetzte Zeile (Absatz bzw. umbrochene Teilzeile) mit ihren Runs und ihrer Lage. */
export interface SvgLine {
tspans: SvgTspan[];
align: "left" | "center" | "right";
/** Zeilenhöhe dieses Absatzes (Vielfaches der Basisgrösse), s. `Paragraph.lineHeight`. */
/** SVG-`text-anchor` zur Ausrichtung. */
anchor: "start" | "middle" | "end";
/** Vorschub zu dieser Zeile (Vielfaches der Basisgrösse bzw. `lineHeight`), s. `Paragraph.lineHeight`. */
lineHeight: number;
/** x der Zeile (Anker, mit Spalte Mitte/rechts darin). */
x: number;
/** Grundlinie der Zeile (Benutzereinheiten, nach unten wachsend). */
y: number;
}
export interface SvgTextOptions {
/** Ankerpunkt X in Benutzereinheiten. */
x: number;
/** Baseline der ERSTEN Zeile, Y in Benutzereinheiten. */
/** Baseline der ERSTEN Zeile, Y in Benutzereinheiten (weitere Zeilen tiefer). */
y: number;
/**
* Zeilenvorschub (Baseline zu Baseline) in Benutzereinheiten für Zeilen OHNE
@@ -174,9 +180,17 @@ export interface SvgTextOptions {
basePt?: number;
/** Standardfarbe "#rrggbb" für Runs ohne Farbe. */
color?: string;
/**
* Wortumbruch auf diese Breite (gleiche Einheiten; ≤ 0/fehlt = keiner). Wortbreite geschätzt
* (UTF-16-Länge × Schriftgrösse × 0.55, kein Font-Messen); Run-Grenzen bleiben.
*/
wrapWidthUnits?: number;
/** Spaltenbreite für die Lage: Mitte/rechts ausgerichtete Zeilen liegen darin (0/NaN/fehlt = am Anker). */
columnWidth?: number;
}
const ALIGNS = ["left", "center", "right"] as const;
const ANCHORS = ["start", "middle", "end"] as const;
/** UTF-16-Einheiten `f[at…at+n)` als Text. */
function unitsText(f: Float64Array, at: number, n: number): string {
@@ -186,13 +200,10 @@ function unitsText(f: Float64Array, at: number, n: number): string {
}
/**
* 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.
* Gesetzte Zeilen des Kerns (Format s. `src-tauri/core/src/web/text_layout.rs`) → `SvgLine[]`. 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> {
function decodeLines(f: Float64Array, text: (para: number, run: number) => string): SvgLine[] {
if (f.length < 2) return [];
let k = 2;
const styles: Array<Omit<SvgTspan, "text">> = [];
@@ -213,34 +224,40 @@ function decodeLines(f: Float64Array, text: (para: number, run: number) => strin
if (bits & 16) st.baselineShift = shift;
styles.push(st);
}
const out: Array<SvgLine | PlacedLine> = new Array(f[0]);
const out: SvgLine[] = new Array(f[0]);
for (let i = 0; i < f[0]; i++) {
const align = ALIGNS[f[k]] ?? "left";
const a = f[k];
const lineHeight = f[k + 1];
const y = f[k + 2];
const n = f[k + 3];
k += 4;
const x = f[k + 2];
const y = f[k + 3];
const n = f[k + 4];
k += 5;
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 };
out[i] = { tspans, align: ALIGNS[a] ?? "left", anchor: ANCHORS[a] ?? "start", lineHeight, x, y };
}
return out;
}
/** Zuletzt gesetzte Zeilen je Dokument-Objekt und Optionen (Neuzeichnen beim Zoomen/Verschieben). */
/** Zuletzt gesetzte Zeilen je Dokument-Objekt und Optionen (Neuzeichnen ohne Änderung). */
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}`;
/**
* Setzt das Dokument (Kern `text_lines`: Runs → Tspans mit Grössen in Benutzereinheiten, eine Zeile
* je Absatz bzw. umbrochene Teilzeile, Lage x/y/Anker je Zeile). Der Aufrufer legt nur noch die
* Knoten an. Kaputte Eingabe → keine Zeilen. Ergebnis nicht verändern (geteilt).
*/
export function layoutText(doc: RichTextDoc, opts: SvgTextOptions): SvgLine[] {
const { x, y, lineHeight, unitPerPt, basePt, color, wrapWidthUnits, columnWidth } = opts;
const key = `${lineHeight}|${unitPerPt}|${basePt}|${wrapWidthUnits}|${color}|${x}|${y}|${columnWidth}`;
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);
const o = Float64Array.of(lineHeight, unitPerPt, basePt == null ? 0 : 1, basePt ?? 0, wrapWidthUnits ?? NaN, x, y, columnWidth ?? NaN);
const lines = decodeLines(core().text_lines(JSON.stringify(doc), o, color ?? undefined), (p, r) => doc.paragraphs[p].runs[r].text);
if (!byOpts) memo.set(doc, (byOpts = new Map()));
if (byOpts.size > 8) byOpts.clear();
byOpts.set(key, lines);
@@ -248,44 +265,40 @@ function kernelLines(doc: RichTextDoc, opts: SvgTextOptions, wrap: number | unde
}
/**
* 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]`).
* Zeilen eines Text-Markups auf dem Layout-Blatt (Papier-mm; Layout-Blatt und Layout-PDF): Höhe
* `heightMm` als Basisgrösse, Vorschub 1.25 × Höhe, erste Grundlinie bei `yMm`; mit Rahmenbreite
* (`widthMm` > 0) wortweise umbrochen, Mitte/rechts im Rahmen (jede Breite ≠ 0 zählt dafür, wie früher).
*/
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). 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(
export function annotationTextLines(
ann: { xMm: number; yMm: number; heightMm: number; widthMm?: number; color?: string },
doc: RichTextDoc,
opts: SvgTextOptions & { wrapWidthUnits?: number },
): SvgLine[] {
return kernelLines(doc, opts, opts.wrapWidthUnits);
return layoutText(doc, {
x: ann.xMm,
y: ann.yMm,
lineHeight: ann.heightMm * 1.25,
unitPerPt: 25.4 / 72,
basePt: (ann.heightMm / 25.4) * 72,
color: ann.color ?? "#111111",
wrapWidthUnits: ann.widthMm && ann.widthMm > 0 ? ann.widthMm : undefined,
columnWidth: ann.widthMm,
});
}
/** 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`.
* Absatz-Zeilenhöhe) und darunter die Live-Zeilen (0.8 × Basisgrösse), vertikal um `y0` zentriert,
* alle bei `x0`. `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,
x0: number,
y0: number,
): PlacedLine[] {
): SvgLine[] {
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);
return decodeLines(core().text_stamp_block(JSON.stringify(stamp), unitPerPt, x0, y0), text);
}
/**
+4 -21
View File
@@ -59,7 +59,7 @@ import {
} from "./layoutSheetMath";
import { RichTextEditor } from "../editors/RichTextEditor";
import { docFromText } from "../text/richText";
import { wrapDocToLines, type SvgLine } from "../text/renderHtml";
import { annotationTextLines } from "../text/renderHtml";
import { contentFontBaselineFromTop, TEXT_LINE_HEIGHT_MULT } from "../text/fontMetrics";
import { readImageFile, defaultImageSizeMm } from "../io/imageAsset";
import { rasterizePdfPages } from "../io/pdfImport";
@@ -1490,31 +1490,14 @@ function AnnotationSvg({
}
// Text: reiches Doc (mehrere Absätze/gemischte Formatierung) hat Vorrang vor
// dem einfachen String — bricht bei gesetzter Rahmenbreite (`widthMm`)
// wortweise um (Run-Grenzen bleiben erhalten, s. `wrapDocToLines`).
// wortweise um (Run-Grenzen bleiben erhalten); Zeilen samt Lage aus dem Kern (`layoutText`).
if (ann.doc) {
const lineHeight = ann.heightMm * 1.25;
const lines: SvgLine[] = wrapDocToLines(ann.doc, {
x: 0,
y: 0,
lineHeight,
unitPerPt: 25.4 / 72,
basePt: (ann.heightMm / 25.4) * 72,
color: ann.color ?? "#111111",
...(ann.widthMm && ann.widthMm > 0 ? { wrapWidthUnits: ann.widthMm } : {}),
});
let y = ann.yMm;
const lines = annotationTextLines(ann, ann.doc);
return (
<text opacity={opacity}>
{lines.map((line, k) => {
if (k > 0) y += line.lineHeight;
const anchor = line.align === "center" ? "middle" : line.align === "right" ? "end" : "start";
const x =
!ann.widthMm ? ann.xMm
: line.align === "center" ? ann.xMm + ann.widthMm / 2
: line.align === "right" ? ann.xMm + ann.widthMm
: ann.xMm;
return (
<tspan key={k} x={x} y={y} textAnchor={anchor}>
<tspan key={k} x={line.x} y={line.y} textAnchor={line.anchor}>
{line.tspans.length === 0
? "​"
: line.tspans.map((ts, j) => (
+14 -39
View File
@@ -5,7 +5,7 @@
import type { HatchRender, Primitive } from "../../../core";
import { NO_HATCH } from "../../../core";
import { stampBlockLines, wrapDocToLines, wrapPlainText, type SvgLine } from "../../../text/renderHtml";
import { layoutText, stampBlockLines, wrapPlainText } from "../../../text/renderHtml";
import type { Vec2 } from "../../../model/types";
import { quantizePen } from "../../../export/sceneToPrintSvg";
import { buildRandomHatchRuns, zigzagPoints, motifPoints, DASH_MM_TO_M } from "../../../core";
@@ -709,23 +709,17 @@ export function renderPrimitive(
const unitPerPt = (1 / 72) * 0.0254 * nRef * PX_PER_M;
// 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);
const lines = stampBlockLines(p, unitPerPt, c.x, c.y);
if (lines.length === 0) return null;
return (
<text style={{ pointerEvents: "none", userSelect: "none" }}>
{lines.map((line, k) => {
const anchor =
line.align === "center"
? "middle"
: line.align === "right"
? "end"
: "start";
return (
<tspan
key={k}
x={c.x}
x={line.x}
y={line.y}
textAnchor={anchor}
textAnchor={line.anchor}
>
{line.tspans.map((ts, j) => (
<tspan
@@ -776,30 +770,20 @@ export function renderPrimitive(
// Reiches Textfeld (InDesign-artig, mehrere Absätze/gemischte Formatierung):
// hat Vorrang vor dem Alt-Pfad (einfacher String + einheitliche `marks`)
// weiter unten. Bricht bei gesetzter Spaltenbreite wortweise um (Run-Grenzen
// bleiben erhalten, s. `wrapDocToLines`).
// bleiben erhalten); Zeilen samt Lage aus dem Kern (`layoutText`).
if (p.doc) {
const unitPerPt = (0.0254 / 72) * PX_PER_M;
const basePt = (p.heightM / 0.0254) * 72;
const lineHeight = fontSize * 1.25;
const wrapWidthUnits = p.wrapWidth && p.wrapWidth > 0 ? p.wrapWidth * PX_PER_M : undefined;
const docLines: SvgLine[] = wrapDocToLines(p.doc, {
x: 0,
y: 0,
lineHeight,
unitPerPt,
basePt,
const docLines = layoutText(p.doc, {
x: c.x,
y: c.y,
lineHeight: fontSize * 1.25,
unitPerPt: (0.0254 / 72) * PX_PER_M,
basePt: (p.heightM / 0.0254) * 72,
color: p.color,
...(wrapWidthUnits ? { wrapWidthUnits } : {}),
wrapWidthUnits,
columnWidth: wrapWidthUnits,
});
if (docLines.length === 0) return null;
const lineYs: number[] = [];
{
let y = c.y;
docLines.forEach((line, k) => {
if (k > 0) y += line.lineHeight;
lineYs.push(y);
});
}
return (
<text
opacity={p.greyed ? 0.45 : undefined}
@@ -807,17 +791,8 @@ export function renderPrimitive(
style={{ pointerEvents: "none", userSelect: "none" }}
>
{docLines.map((line, k) => {
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;
return (
<tspan key={k} x={x} y={lineYs[k]} textAnchor={anchor}>
<tspan key={k} x={line.x} y={line.y} textAnchor={line.anchor}>
{line.tspans.length === 0
? "​"
: line.tspans.map((ts, j) => (