diff --git a/TODO.md b/TODO.md index 6979d4a9..1381ee61 100644 --- a/TODO.md +++ b/TODO.md @@ -319,6 +319,23 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern Kern lesen); Fassade `wrapDocToLines` ungemerkt ~7 → ~28 µs je Aufruf (JSON hin, flache Zeilen zurück), gemerkt < 1 µs. Gefunden, bewusst unverändert: im Druck-SVG (Layout-Viewports) tragen die Runs der Einzeltexte `font-size` = Höhe in Metern statt Papier-mm (alte TS-Formel `basePt · unitPerPt`); offen als eigener Fehler. + ✅ (30.10.) behoben: Basisgrösse der Einzeltexte im Druck-SVG = Höhe × mm je Meter (wie die Plan-Ansicht beim + Massstab; betraf auch Masszahlen, Höhenkoten, Schnittlinien-Bezeichner — alles `drawingText`, im Layout 1:50 20-mal + zu klein). Raumstempel fehlten im Druck-SVG ganz (Eintrag `text` übergangen): jetzt als Block wie die Plan-Ansicht im + Druckmodus (`stamp_block`, 10 pt Papier). Test `planToPrintSvg.text.test.ts` (Layout-Viewport 1:50: Einzeltext, + 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. diff --git a/src-tauri/core/src/plan_print_svg.rs b/src-tauri/core/src/plan_print_svg.rs index 26bafa99..549a5bcb 100644 --- a/src-tauri/core/src/plan_print_svg.rs +++ b/src-tauri/core/src/plan_print_svg.rs @@ -6,8 +6,8 @@ //! Polylinie, Bögen als ``. //! //! In TS bleiben: der ``-Rahmen und das weisse Blatt und die Bild-Schraffur-`` -//! (laufende Ids im Dokument). Die Einzeltexte setzt der Kern (`crate::text_layout`, Zeilen als -//! `` je Zeile mit je einem `` je Run/Wort). +//! (laufende Ids im Dokument). Einzeltexte und Raumstempel setzt der Kern (`crate::text_layout`, +//! Zeilen als `` je Zeile mit je einem `` je Run/Wort), Grössen in Papier-mm. //! //! Format: Datensätze getrennt durch `\x1e`, Felder durch `\x1f`: //! - `E`, Ebene (0 = ins ``, 1 = in die offene Gruppe), Tag, dann Name/Wert-Paare; @@ -24,10 +24,10 @@ use crate::hatch::{self, Hatch, Motif, Pattern, V2}; use crate::js_fmt::js_number; 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}; +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; -use crate::text_layout::{wrap_doc_to_lines, LayoutOpts, LineAlign, TEXT_LINE_HEIGHT_MULT}; +use crate::plan_text::{SingleText, StampText}; +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`). @@ -414,6 +414,15 @@ fn entry(out: &mut Out, view: &View, i: usize, hatches: &[(i32, Hatch, i32)], m: } out.el(0, "path", &attrs); } + T_TEXT => { + let js = view.string(whole(f[0])?)?; + let j: serde_json::Value = serde_json::from_str(&js).ok()?; + let jg = j.get("greyed").and_then(|g| g.as_bool()).unwrap_or(false); + let obj = j.get("opacity").and_then(|o| o.as_f64()).unwrap_or(1.0); + if let Ok(t) = serde_json::from_str::(&js) { + stamp_node(out, &t, m, opacity_of(jg, obj)); + } + } T_DRAWING_TEXT | T_IMAGE => { let js = view.string(whole(f[0])?)?; let j: serde_json::Value = serde_json::from_str(&js).ok()?; @@ -458,14 +467,18 @@ fn entry(out: &mut Out, view: &View, i: usize, hatches: &[(i32, Hatch, i32)], m: Some(()) } -/// Einzeltext (Text-Werkzeug/DXF-Import) als `` mit ``-Zeilen (früher -/// `drawingTextNode` in `planToPrintSvg.ts`): Grösse in Papier-mm, bei Spaltenbreite wortweise -/// umbrochen (Run-Grenzen bleiben), gedreht um den Anker. +/// Einzeltext (Text-Werkzeug/DXF-Import, auch Masszahlen und Koten) als `` mit +/// ``-Zeilen (früher `drawingTextNode` in `planToPrintSvg.ts`): Grösse in Papier-mm (Höhe × +/// mm je Meter, wie die Plan-Ansicht beim Massstab), bei Spaltenbreite wortweise umbrochen +/// (Run-Grenzen bleiben), gedreht um den Anker. Run-eigene `sizePt` wie in der SVG-Plan-Ansicht als +/// Modell-pt (1 pt = 0.0254/72 m), also auch × mm je Meter. fn text_node(out: &mut Out, t: &SingleText, m: Map, opacity: String) { let k = m.k; let c = m.at(t.at.x, t.at.y); let unit_per_pt = (0.0254 / 72.0) * k; - let base_pt = if unit_per_pt > 0.0 { t.height_m / unit_per_pt } else { 0.0 }; + // Basisgrösse in Modell-pt (bis 30.10. `height_m / unit_per_pt`: Meter durch mm je pt — die + // Runs kamen in Metern statt Papier-mm heraus, im Layout k-mal zu klein). + let base_pt = if unit_per_pt > 0.0 { t.height_m * k / unit_per_pt } else { 0.0 }; let wrap = t.wrap().map(|w| w * k); let o = LayoutOpts { line_height: t.height_m * k * TEXT_LINE_HEIGHT_MULT, unit_per_pt, base_pt, color: t.color.as_deref().unwrap_or("#000000") }; let lines = wrap_doc_to_lines(&t.doc(), &o, wrap); @@ -481,36 +494,46 @@ 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 { "" }; - out.tagged(&["L", content], &[("x", r3(x)), ("y", r3(y)), ("text-anchor", 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() { - a.push(("font-weight", w.to_string())); - } - if let Some(st) = ts.font_style() { - a.push(("font-style", st.to_string())); - } - a.push(("font-family", ts.font_family.clone().unwrap_or_else(|| "Helvetica, Arial, sans-serif".to_string()))); - if let Some(d) = ts.text_decoration { - a.push(("text-decoration", d.to_string())); - } - out.tagged(&["R", &ts.text], &a); + line_node(out, line, content, x, y); + } +} + +/// Zeilen-`` mit je einem Run-``. +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() { + a.push(("font-weight", w.to_string())); } + if let Some(st) = ts.font_style() { + a.push(("font-style", st.to_string())); + } + a.push(("font-family", ts.font_family.clone().unwrap_or_else(|| "Helvetica, Arial, sans-serif".to_string()))); + if let Some(d) = ts.text_decoration { + a.push(("text-decoration", d.to_string())); + } + out.tagged(&["R", &ts.text], &a); + } +} + +/// Raumstempel als `` (fehlte im Druck-SVG bis 30.10.): wie die Plan-Ansicht im Druckmodus — +/// Rich-Text-Zeilen und Live-Zeilen (Fläche, Nutzung) als Block um den Anker zentriert +/// ([`stamp_block`]), Grösse in Papier-pt (unabhängig vom Massstab). +fn stamp_node(out: &mut Out, t: &StampText, m: Map, opacity: String) { + let c = m.at(t.at.x, t.at.y); + let extra: Vec<(&str, LineAlign)> = t.extra_lines.iter().map(|l| (l.text.as_str(), LineAlign::of(Some(l.align)))).collect(); + let placed = stamp_block(&t.doc, &extra, t.base_pt, PT_TO_MM, t.color.as_deref().unwrap_or("#000000"), c.y); + if placed.is_empty() { + return; + } + let attrs: Vec<(&str, String)> = if opacity.is_empty() { Vec::new() } else { vec![("opacity", opacity)] }; + out.tagged(&["X"], &attrs); + for p in &placed { + line_node(out, &p.line, "", c.x, p.y); } } @@ -565,21 +588,57 @@ mod tests { #[test] fn einzeltext_als_zeilen_und_runs() { - let js = "{\"kind\":\"drawingText\",\"at\":{\"x\":1,\"y\":2},\"text\":\"aa bb\",\"heightM\":0.5,\"angle\":0.5,\"color\":\"#123\",\"wrapWidth\":0.6,\"marks\":{\"bold\":true}}"; + let js = "{\"kind\":\"drawingText\",\"at\":{\"x\":1,\"y\":2},\"text\":\"aa bb\",\"heightM\":0.5,\"angle\":0.5,\"color\":\"#123\",\"wrapWidth\":2,\"marks\":{\"bold\":true}}"; let t: SingleText = serde_json::from_str(js).unwrap(); let m = Map { off_x: 0.0, off_y: 0.0, min_x: 0.0, max_y: 10.0, k: 10.0 }; let mut out = Out { s: String::new(), first: true }; text_node(&mut out, &t, m, "0.5".into()); let recs: Vec> = out.s.split('\u{1e}').map(|r| r.split('\u{1f}').collect()).collect(); - // Drehung um den Anker (10, 80 mm), eine Zeile (Spalte 6 mm), je Wort/Leerraum ein Run. + // Drehung um den Anker (10, 80 mm), eine Zeile (Spalte 20 mm), je Wort/Leerraum ein Run. assert_eq!(recs[0], ["X", "transform", "rotate(-28.648 10 80)", "opacity", "0.5"]); assert_eq!(recs[1], ["L", "", "x", "10", "y", "80", "text-anchor", "start"]); - // Run-Grösse = heightM (wie die frühere TS-Fassung: `basePt · unitPerPt` mit `unitPerPt` in - // pt→mm, also Meter statt Papier-mm — bekannte Abweichung, bewusst unverändert übernommen). - assert_eq!(recs[2], ["R", "aa", "font-size", "0.5", "fill", "#123", "font-weight", "700", "font-family", "Helvetica, Arial, sans-serif"]); + // Run-Grösse in Papier-mm: 0.5 m × 10 mm/m (wie die Plan-Ansicht beim Massstab). + assert_eq!(recs[2], ["R", "aa", "font-size", "5", "fill", "#123", "font-weight", "700", "font-family", "Helvetica, Arial, sans-serif"]); assert_eq!((recs[3][1], recs[4][1], recs.len()), (" ", "bb", 5)); } + #[test] + fn einzeltext_umbruch_und_zeilen_in_papier_mm() { + // Spalte 2 m = 20 mm, Höhe 0.25 m = 2.5 mm: «aaaa bbbb» (je 4 × 2.5 × 0.55 = 5.5 mm) passt in + // eine Zeile; Run mit eigener Grösse 72 pt = 1 Modell-Zoll = 0.254 mm bei 10 mm/m. + let js = r##"{"at":{"x":0,"y":10},"text":"","heightM":0.25,"angle":0,"wrapWidth":2,"doc":{"version":1,"paragraphs":[{"runs":[{"text":"aaaa bbbb","marks":{}}]},{"runs":[{"text":"c","marks":{"sizePt":72}}],"lineHeight":2}]}}"##; + let t: SingleText = serde_json::from_str(js).unwrap(); + let m = Map { off_x: 0.0, off_y: 0.0, min_x: 0.0, max_y: 10.0, k: 10.0 }; + let mut out = Out { s: String::new(), first: true }; + text_node(&mut out, &t, m, String::new()); + let recs: Vec> = out.s.split('\u{1e}').map(|r| r.split('\u{1f}').collect()).collect(); + let lines: Vec<&Vec<&str>> = recs.iter().filter(|r| r[0] == "L").collect(); + assert_eq!(lines.len(), 2); + // Absatz-Zeilenhöhe 2 × Basisgrösse (2.5 mm). + assert_eq!((lines[0][5], lines[1][5]), ("0", "5")); + let sizes: Vec<&str> = recs.iter().filter(|r| r[0] == "R").map(|r| r[3]).collect(); + assert_eq!(sizes, ["2.5", "2.5", "2.5", "0.254"]); + } + + #[test] + fn raumstempel_als_block_in_papier_pt() { + let js = r##"{"at":{"x":2,"y":3},"doc":{"version":1,"paragraphs":[{"runs":[{"text":"Wohnen","marks":{"bold":true}}],"align":"center"}]},"extraLines":[{"text":"17.01 m²","align":"center"}],"basePt":10,"color":"#333"}"##; + let t: StampText = serde_json::from_str(js).unwrap(); + let m = Map { off_x: 0.0, off_y: 0.0, min_x: 0.0, max_y: 10.0, k: 20.0 }; + let mut out = Out { s: String::new(), first: true }; + stamp_node(&mut out, &t, m, "0.3".into()); + let recs: Vec> = out.s.split('\u{1e}').map(|r| r.split('\u{1f}').collect()).collect(); + assert_eq!(recs[0], ["X", "opacity", "0.3"]); + // Anker (40, 140 mm); 10 pt = 3.528 mm, Live-Zeile 0.8 ×; Block um den Anker zentriert. + assert_eq!(&recs[1][..4], ["L", "", "x", "40"]); + assert_eq!(recs[1][7], "middle"); + assert_eq!(recs[2], ["R", "Wohnen", "font-size", "3.528", "fill", "#333", "font-weight", "700", "font-family", "Helvetica, Arial, sans-serif"]); + assert_eq!((recs[4][1], recs[4][3]), ("17.01 m²", "2.822")); + let y0: f64 = recs[1][5].parse().unwrap(); + let y1: f64 = recs[3][5].parse().unwrap(); + assert!(y0 < 140.0 && y1 > 140.0 && (y1 - y0 - 10.0 * PT_TO_MM * 1.3).abs() < 1e-3); + } + #[test] fn schraffur_parallel_geklippt() { let sq = [V2 { x: 0.0, y: 0.0 }, V2 { x: 10.0, y: 0.0 }, V2 { x: 10.0, y: 10.0 }, V2 { x: 0.0, y: 10.0 }]; diff --git a/src-tauri/core/src/text_layout.rs b/src-tauri/core/src/text_layout.rs index f336d98e..f9fbec46 100644 --- a/src-tauri/core/src/text_layout.rs +++ b/src-tauri/core/src/text_layout.rs @@ -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) - 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, x: f64, y: f64, col: Option) -> 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()); diff --git a/src-tauri/core/src/web/text_layout.rs b/src-tauri/core/src/web/text_layout.rs index 8661938b..b6254852 100644 --- a/src-tauri/core/src/web/text_layout.rs +++ b/src-tauri/core/src/web/text_layout.rs @@ -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 { +/// `at` = (x, Grundlinie) je Zeile. +fn encode_lines(lines: &[LineRef], at: &[(f64, f64)], style: impl Fn(&Tok) -> Tspan) -> Vec { let mut styles: Vec = Vec::new(); let mut keys: Vec<(usize, usize)> = Vec::new(); let mut key_style: Vec = Vec::new(); let mut body: Vec = 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) -> Vec { - 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::(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 { } /// 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 { +pub fn text_stamp_block(prim_json: &str, unit_per_pt: f64, x0: f64, y0: f64) -> Vec { let Ok(p) = serde_json::from_str::(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 = placed.iter().map(|q| q.1).collect(); + let at: Vec<(f64, f64)> = placed.iter().map(|q| (x0, q.1)).collect(); let lines: Vec = 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 { diff --git a/src/export/layoutPdf.ts b/src/export/layoutPdf.ts index 59756f42..a1f04b8f 100644 --- a/src/export/layoutPdf.ts +++ b/src/export/layoutPdf.ts @@ -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; diff --git a/src/export/planToPrintSvg.text.test.ts b/src/export/planToPrintSvg.text.test.ts new file mode 100644 index 00000000..7ed6350d --- /dev/null +++ b/src/export/planToPrintSvg.text.test.ts @@ -0,0 +1,148 @@ +// Texte im Druck-SVG (Layout-Viewport, `planToPrintSvg`): Grösse in Papier-mm wie die Plan-Ansicht beim +// Massstab des Viewports — Einzeltexte (einfach und Rich-Text), Masszahlen, Höhenkoten, Raumstempel. + +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { generatePlan } from "../plan/generatePlan"; +import { sampleProject } from "../model/sampleProject"; +import { flattenCategories, type Project } from "../model/types"; +import { planToPrintSvg } from "./planToPrintSvg"; + +interface El { + tag: string; + attrs: Map; + kids: El[]; + textContent: string; + setAttribute(k: string, v: unknown): void; + getAttribute(k: string): string | null; + appendChild(c: El): El; + insertBefore(n: El, r: El | null): El; + querySelector(s: string): El | null; + readonly firstChild: El | null; +} + +function el(tag: string): El { + return { + tag, + attrs: new Map(), + kids: [], + textContent: "", + setAttribute(k, v) { + this.attrs.set(k, String(v)); + }, + getAttribute(k) { + return this.attrs.get(k) ?? null; + }, + appendChild(c) { + this.kids.push(c); + return c; + }, + insertBefore(n) { + this.kids.unshift(n); + return n; + }, + querySelector(s) { + for (const c of this.kids) { + if (c.tag === s) return c; + const r = c.querySelector(s); + if (r) return r; + } + return null; + }, + get firstChild() { + return this.kids[0] ?? null; + }, + }; +} + +const textOf = (e: El): string => e.textContent + e.kids.map(textOf).join(""); + +/** ``-Knoten des SVG mit Inhalt und ihren Run-Grössen (mm) und Zeilen-y. */ +function texts(svg: El): Array<{ text: string; sizes: number[]; ys: number[]; xs: number[] }> { + return svg.kids + .filter((k) => k.tag === "text") + .map((t) => ({ + text: textOf(t), + sizes: t.kids.flatMap((l) => l.kids.map((r) => Number(r.getAttribute("font-size")))), + ys: t.kids.map((l) => Number(l.getAttribute("y"))), + xs: t.kids.map((l) => Number(l.getAttribute("x"))), + })); +} + +const N = 50; +const K = 1000 / N; // Papier-mm je Meter + +const project: Project = { + ...sampleProject, + drawings2d: [ + ...sampleProject.drawings2d, + { id: "t1", type: "drawing2d", levelId: "eg", categoryCode: "60", geom: { shape: "text", at: { x: 1, y: 2 }, text: "Einzeltext", height: 0.3, angle: 0 } }, + { + id: "t2", + type: "drawing2d", + levelId: "eg", + categoryCode: "60", + geom: { + shape: "text", + at: { x: 1, y: 1 }, + text: "Titel\nzweite Zeile", + height: 0.2, + angle: 0, + width: 4, + doc: { + version: 1, + paragraphs: [ + { runs: [{ text: "Titel", marks: { bold: true } }], align: "center" }, + { runs: [{ text: "zweite ", marks: {} }, { text: "Zeile", marks: { italic: true } }] }, + ], + }, + }, + }, + { id: "d1", type: "drawing2d", levelId: "eg", categoryCode: "60", geom: { shape: "dimension", pts: [{ x: 0, y: -2 }, { x: 5, y: -2 }], offset: 0.5 } }, + { id: "k1", type: "drawing2d", levelId: "eg", categoryCode: "60", geom: { shape: "kote", at: { x: 6, y: 1 }, value: 0, kind: "okFertig", rotation: 0 } }, + ] as Project["drawings2d"], +}; + +describe("Druck-SVG: Textgrössen in Papier-mm", () => { + let prev: unknown; + beforeAll(() => { + const g = globalThis as { document?: unknown }; + prev = g.document; + g.document = { createElementNS: (_: string, tag: string) => el(tag) }; + }); + afterAll(() => { + (globalThis as { document?: unknown }).document = prev; + }); + + const codes = new Set(flattenCategories(project.layers).map((c) => c.code)); + const print = () => { + const plan = generatePlan(project, "eg", codes, undefined, "mittel", false, false, true, N); + return texts(planToPrintSvg(plan, { scaleDenominator: N, pageWidthMm: 420, pageHeightMm: 297 }).svg as unknown as El); + }; + + it("Einzeltext: Höhe 0.3 m bei 1:50 = 6 mm", () => { + const t = print().find((x) => x.text === "Einzeltext")!; + expect(t.sizes).toEqual([0.3 * K]); + }); + + it("Rich-Text: Runs in Papier-mm, Zeilenvorschub 1.25 × Höhe, Mitte in der Spalte", () => { + const t = print().find((x) => x.text.startsWith("Titel"))!; + expect(t.sizes.every((s) => s === 0.2 * K)).toBe(true); + expect(t.ys[1] - t.ys[0]).toBeCloseTo(0.2 * K * 1.25, 3); + expect(t.xs[0] - t.xs[1]).toBeCloseTo((4 * K) / 2, 3); + }); + + it("Masszahl in der Papier-Schrifthöhe (4 mm), Höhenkote lesbar gross", () => { + const all = print(); + const dim = all.find((x) => x.text === "5.00")!; + expect(dim.sizes[0]).toBeCloseTo(4, 3); + const kote = all.find((x) => /0[.,]00/.test(x.text) && x !== dim); + expect(kote).toBeDefined(); + expect(kote!.sizes[0]).toBeGreaterThan(1); + }); + + it("Raumstempel im Viewport, Grösse in Papier-pt (10 pt)", () => { + const stamp = print().find((x) => x.text.includes("Wohnen"))!; + expect(stamp).toBeDefined(); + expect(stamp.sizes[0]).toBeCloseTo(10 * (25.4 / 72), 3); + }); +}); diff --git a/src/text/renderHtml.test.ts b/src/text/renderHtml.test.ts index cfede8f1..45ee579a 100644 --- a/src/text/renderHtml.test.ts +++ b/src/text/renderHtml.test.ts @@ -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"]); }); diff --git a/src/text/renderHtml.ts b/src/text/renderHtml.ts index e7046533..d3bb1878 100644 --- a/src/text/renderHtml.ts +++ b/src/text/renderHtml.ts @@ -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 { +function decodeLines(f: Float64Array, text: (para: number, run: number) => string): SvgLine[] { if (f.length < 2) return []; let k = 2; const styles: Array> = []; @@ -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 = 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>(); -/** 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); } /** diff --git a/src/ui/LayoutSheet.tsx b/src/ui/LayoutSheet.tsx index 90e68253..9b987e83 100644 --- a/src/ui/LayoutSheet.tsx +++ b/src/ui/LayoutSheet.tsx @@ -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 ( {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 ( - + {line.tspans.length === 0 ? "​" : line.tspans.map((ts, j) => ( diff --git a/src/views/plan/planView/primitives.tsx b/src/views/plan/planView/primitives.tsx index e4dad6d5..b25cbbec 100644 --- a/src/views/plan/planView/primitives.tsx +++ b/src/views/plan/planView/primitives.tsx @@ -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 ( {lines.map((line, k) => { - const anchor = - line.align === "center" - ? "middle" - : line.align === "right" - ? "end" - : "start"; return ( {line.tspans.map((ts, j) => ( 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 ( {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 ( - + {line.tspans.length === 0 ? "​" : line.tspans.map((ts, j) => (