Skip to main content

text_typeset/
bridge.rs

1//! Bridge between text-document snapshot types and text-typeset layout params.
2//!
3//! Converts `FlowSnapshot`, `BlockSnapshot`, `TextFormat`, etc. into
4//! `BlockLayoutParams`, `FragmentParams`, `TableLayoutParams`, etc.
5
6use text_document::{
7    BlockSnapshot, CellSnapshot, FlowElementSnapshot, FlowSnapshot, FragmentContent, FrameSnapshot,
8    TableSnapshot,
9};
10
11use crate::layout::block::{BlockLayoutParams, FragmentParams, PaintSpan};
12use crate::layout::frame::{FrameLayoutParams, FramePosition};
13use crate::layout::paragraph::Alignment;
14use crate::layout::table::{CellLayoutParams, TableLayoutParams};
15use crate::shaping::shaper::TextDirection;
16
17const DEFAULT_LIST_INDENT: f32 = 24.0;
18const INDENT_PER_LEVEL: f32 = 24.0;
19
20/// Parse a 2-letter ISO 639-1 code (e.g. "en", "fr") into a lowercased
21/// byte pair for `hypher::Lang::from_iso`. Returns `None` for anything
22/// that isn't two ASCII letters (incl. longer tags like "en-US" — only
23/// the primary subtag matters, so callers may pass that and we take the
24/// first two letters).
25fn iso639_1(code: &str) -> Option<[u8; 2]> {
26    let b = code.trim().as_bytes();
27    if b.len() >= 2 && b[0].is_ascii_alphabetic() && b[1].is_ascii_alphabetic() {
28        Some([b[0].to_ascii_lowercase(), b[1].to_ascii_lowercase()])
29    } else {
30        None
31    }
32}
33
34/// Per-call knobs threaded through the conversion functions so that a
35/// host widget can override defaults driven by its active theme.
36///
37/// Default values reproduce the historical pre-themed behaviour: a
38/// light-grey card behind fenced code blocks and no foreground
39/// override for monospaced runs.
40#[derive(Clone, Copy)]
41pub struct BridgeOptions {
42    /// Background painted behind blocks where `BlockFormat.is_code_block
43    /// == Some(true)` AND the block carries no explicit
44    /// `background_color`. Has no effect on prose blocks or blocks that
45    /// set their own background.
46    pub code_block_background: [f32; 4],
47    /// Foreground used for character runs whose font family resolves
48    /// to `monospace` (set by the markdown importer for inline `code`
49    /// spans and by `is_code_block` blocks). `None` keeps the
50    /// engine-level default text colour. Only applied when the run
51    /// carries no explicit `foreground_color`.
52    pub code_block_foreground: Option<[f32; 4]>,
53    /// Foreground used for character runs carrying a hyperlink
54    /// (`TextFormat.is_anchor == Some(true)`). `None` keeps the
55    /// engine-level default text colour — which is what a host that
56    /// never sets this gets, so a link stays indistinguishable from
57    /// prose unless the host says otherwise.
58    ///
59    /// Only applied when the run carries no explicit `foreground_color`,
60    /// the same rule `code_block_foreground` follows: an author who
61    /// picked a colour always wins over a convention.
62    ///
63    /// Wins over `code_block_foreground` when a run is both, because
64    /// "you can follow this" is the more useful of the two signals.
65    pub link_foreground: Option<[f32; 4]>,
66    /// When `Some(c)`, every character of every block laid out with
67    /// these options is replaced with `c` — one echo char per source
68    /// `char` — before shaping. This is the password / secure-field
69    /// masking path: the real text never reaches the shaper or the
70    /// glyph atlas, only the echo character does. Emitting one echo per
71    /// source `char` (not per grapheme) preserves char counts, so the
72    /// engine's char-indexed caret / selection / hit-test stay aligned
73    /// with the host document's positions. `None` (default) lays text
74    /// out verbatim.
75    pub echo_char: Option<char>,
76    /// When true, blocks that are **justified** and don't set the
77    /// `hyphenate` flag explicitly are hyphenated automatically (in the
78    /// block's `language`, defaulting to English). This pairs hyphenation
79    /// with justification — its primary use case — without requiring a
80    /// per-block flag. An explicit `BlockFormat.hyphenate` (true or false)
81    /// always wins. Hosts should enable this only for prose/rich-text
82    /// surfaces, not single-line/label widgets. `false` by default.
83    pub hyphenate_justified: bool,
84}
85
86impl Default for BridgeOptions {
87    fn default() -> Self {
88        Self {
89            code_block_background: [0.95, 0.95, 0.95, 1.0],
90            code_block_foreground: None,
91            link_foreground: None,
92            echo_char: None,
93            hyphenate_justified: false,
94        }
95    }
96}
97
98/// Convert a FlowSnapshot into layout params that can be fed to a [`DocumentFlow`].
99///
100/// [`DocumentFlow`]: crate::DocumentFlow
101pub fn convert_flow(flow: &FlowSnapshot) -> FlowElements {
102    convert_flow_with(flow, &BridgeOptions::default())
103}
104
105/// Same as [`convert_flow`] but accepts host-supplied [`BridgeOptions`]
106/// for theme-driven colour overrides.
107pub fn convert_flow_with(flow: &FlowSnapshot, opts: &BridgeOptions) -> FlowElements {
108    let mut blocks = Vec::new();
109    let mut tables = Vec::new();
110    let mut frames = Vec::new();
111
112    for (i, element) in flow.elements.iter().enumerate() {
113        match element {
114            FlowElementSnapshot::Block(block) => {
115                blocks.push((i, convert_block_with(block, opts)));
116            }
117            FlowElementSnapshot::Table(table) => {
118                tables.push((i, convert_table_with(table, opts)));
119            }
120            FlowElementSnapshot::Frame(frame) => {
121                frames.push((i, convert_frame_with(frame, opts)));
122            }
123        }
124    }
125
126    FlowElements {
127        blocks,
128        tables,
129        frames,
130    }
131}
132
133/// Converted flow elements, ordered by their position in the flow.
134pub struct FlowElements {
135    /// (flow_index, params)
136    pub blocks: Vec<(usize, BlockLayoutParams)>,
137    pub tables: Vec<(usize, TableLayoutParams)>,
138    pub frames: Vec<(usize, FrameLayoutParams)>,
139}
140
141pub fn convert_block(block: &BlockSnapshot) -> BlockLayoutParams {
142    convert_block_with(block, &BridgeOptions::default())
143}
144
145/// Same as [`convert_block`] but with theme-driven [`BridgeOptions`]
146/// for code-block colour overrides.
147pub fn convert_block_with(block: &BlockSnapshot, opts: &BridgeOptions) -> BlockLayoutParams {
148    let alignment = block
149        .block_format
150        .alignment
151        .as_ref()
152        .map(convert_alignment)
153        .unwrap_or_default();
154
155    let heading_scale = match block.block_format.heading_level {
156        Some(1) => 2.0,
157        Some(2) => 1.5,
158        Some(3) => 1.25,
159        Some(4) => 1.1,
160        _ => 1.0,
161    };
162
163    // text-document's `FragmentContent::{Text, Image}.offset` is the
164    // **character** offset of the fragment within the block. text-typeset
165    // downstream (block.rs:143 / paragraph.rs:216) treats
166    // `FragmentParams.offset` as the fragment's **byte** start in
167    // `block.text`, then adds it to glyph clusters (also bytes) to
168    // lift them into block-text byte space. The two units must
169    // agree, or any block whose first fragment carries a multi-byte
170    // character causes every subsequent fragment's glyphs to land at
171    // the wrong byte position — observed as hit-tests + formatting
172    // landing a character or two past the user's selection around
173    // em-dashes, curly quotes, accented characters, emoji, etc.
174    //
175    // Build a single char → byte index once over `block.text` (O(N)),
176    // then look each fragment's char offset up in O(1) and pass the
177    // byte offset into `convert_fragment`. The fragment stream covers
178    // the whole block text in char order, so the lookup is in range
179    // for every fragment we see.
180    let char_to_byte: Vec<usize> = block
181        .text
182        .char_indices()
183        .map(|(b, _)| b)
184        .chain(std::iter::once(block.text.len()))
185        .collect();
186    let fragments: Vec<FragmentParams> = block
187        .fragments
188        .iter()
189        .map(|f| {
190            let char_offset = match f {
191                FragmentContent::Text { offset, .. } => *offset,
192                FragmentContent::Image { offset, .. } => *offset,
193                FragmentContent::FootnoteReference { offset, .. } => *offset,
194            };
195            let byte_offset = char_to_byte
196                .get(char_offset)
197                .copied()
198                .unwrap_or(block.text.len());
199            convert_fragment(f, heading_scale, opts, byte_offset)
200        })
201        .collect();
202
203    let indent_level = block.block_format.indent.unwrap_or(0) as f32;
204
205    let (list_marker, list_indent) = if let Some(ref info) = block.list_info {
206        let list_indent_level = info.indent as f32;
207        (
208            info.marker.clone(),
209            DEFAULT_LIST_INDENT + list_indent_level * INDENT_PER_LEVEL,
210        )
211    } else {
212        (String::new(), indent_level * INDENT_PER_LEVEL)
213    };
214
215    let checkbox = match block.block_format.marker {
216        Some(text_document::MarkerType::Checked) => Some(true),
217        Some(text_document::MarkerType::Unchecked) => Some(false),
218        _ => None,
219    };
220
221    let mut params = BlockLayoutParams {
222        block_id: block.block_id,
223        position: block.position,
224        text: block.text.clone(),
225        fragments,
226        alignment,
227        base_direction: convert_direction(block.block_format.direction.as_ref()),
228        top_margin: block.block_format.top_margin.unwrap_or(0) as f32,
229        bottom_margin: block.block_format.bottom_margin.unwrap_or(0) as f32,
230        left_margin: block.block_format.left_margin.unwrap_or(0) as f32,
231        right_margin: block.block_format.right_margin.unwrap_or(0) as f32,
232        text_indent: block.block_format.text_indent.unwrap_or(0) as f32,
233        list_marker,
234        list_indent,
235        tab_positions: block
236            .block_format
237            .tab_positions
238            .iter()
239            .map(|&t| t as f32)
240            .collect(),
241        line_height_multiplier: block.block_format.line_height,
242        non_breakable_lines: block.block_format.non_breakable_lines.unwrap_or(false)
243            || block.block_format.is_code_block == Some(true),
244        // Map the document's per-block hyphenation flag + language to the
245        // engine's Hyphenation config. An explicit `hyphenate` flag always
246        // wins; when it's unset, `hyphenate_justified` opts justified
247        // blocks in (hyphenation's main use case). Language defaults to
248        // English when unset/unparseable; unsupported languages degrade to
249        // soft-hyphen-only at wrap time.
250        hyphenation: {
251            let enabled = match block.block_format.hyphenate {
252                Some(v) => v,
253                None => opts.hyphenate_justified && alignment == Alignment::Justify,
254            };
255            enabled.then(|| crate::types::Hyphenation {
256                language: block
257                    .block_format
258                    .language
259                    .as_deref()
260                    .and_then(iso639_1)
261                    .unwrap_or(*b"en"),
262            })
263        },
264        checkbox,
265        background_color: block
266            .block_format
267            .background_color
268            .as_ref()
269            .and_then(|s| parse_css_color(s))
270            .or_else(|| {
271                if block.block_format.is_code_block == Some(true) {
272                    Some(opts.code_block_background)
273                } else {
274                    None
275                }
276            }),
277    };
278
279    if let Some(echo) = opts.echo_char {
280        mask_block_params(&mut params, echo);
281    }
282
283    params
284}
285
286/// Replace every text fragment's content with `echo` repeated once per
287/// source `char`, rewriting the block text and fragment byte offsets to
288/// match. Image-placeholder fragments pass through unchanged (only their
289/// byte offset shifts). Used for password / secure-field masking: the
290/// plaintext is substituted here, before shaping, so it never reaches
291/// the shaper or the glyph atlas. Char counts are preserved per
292/// fragment, keeping the engine's char-indexed caret / selection /
293/// hit-test aligned with the host's real document positions.
294fn mask_block_params(params: &mut BlockLayoutParams, echo: char) {
295    if params.fragments.is_empty() {
296        params.text = echo.to_string().repeat(params.text.chars().count());
297        return;
298    }
299    let mut masked_block = String::new();
300    let mut byte_cursor = 0usize;
301    for frag in params.fragments.iter_mut() {
302        frag.offset = byte_cursor;
303        if frag.image_name.is_some() {
304            // Inline image placeholder — keep the object-replacement
305            // character intact; only its byte offset shifts.
306            masked_block.push_str(&frag.text);
307            byte_cursor += frag.text.len();
308            continue;
309        }
310        let masked = echo.to_string().repeat(frag.text.chars().count());
311        byte_cursor += masked.len();
312        masked_block.push_str(&masked);
313        frag.text = masked;
314    }
315    params.text = masked_block;
316}
317
318fn convert_fragment(
319    frag: &FragmentContent,
320    heading_scale: f32,
321    opts: &BridgeOptions,
322    byte_offset: usize,
323) -> FragmentParams {
324    match frag {
325        FragmentContent::Text {
326            text,
327            format,
328            length,
329            ..
330        } => {
331            // Monospaced runs without an explicit foreground pick up the
332            // host theme's code_block_foreground so `inline code` and
333            // fenced code blocks read as their own register against
334            // prose. Authors that pinned a colour explicitly always win.
335            let is_monospace = format
336                .font_family
337                .as_deref()
338                .map(|f| f.eq_ignore_ascii_case("monospace"))
339                .unwrap_or(false);
340            // A link outranks monospace: an inline-code span that is also a
341            // link should read as followable first. An explicit colour still
342            // beats both — the author asked for it.
343            let is_link = format.is_anchor.unwrap_or(false);
344            let foreground_color =
345                format
346                    .foreground_color
347                    .as_ref()
348                    .map(convert_color)
349                    .or(if is_link {
350                        opts.link_foreground
351                    } else if is_monospace {
352                        opts.code_block_foreground
353                    } else {
354                        None
355                    });
356            FragmentParams {
357                text: text.clone(),
358                offset: byte_offset,
359                length: *length,
360                font_family: format.font_family.clone(),
361                font_weight: format.font_weight,
362                font_bold: format.font_bold,
363                font_italic: format.font_italic,
364                font_point_size: if heading_scale != 1.0 {
365                    // Apply heading scale; use 16 as default if no explicit size
366                    Some((format.font_point_size.unwrap_or(16) as f32 * heading_scale) as u32)
367                } else {
368                    format.font_point_size
369                },
370                underline_style: convert_underline_style(format),
371                overline: format.font_overline.unwrap_or(false),
372                strikeout: format.font_strikeout.unwrap_or(false),
373                is_link: format.is_anchor.unwrap_or(false),
374                letter_spacing: format.letter_spacing.unwrap_or(0) as f32,
375                word_spacing: format.word_spacing.unwrap_or(0) as f32,
376                foreground_color,
377                underline_color: format.underline_color.as_ref().map(convert_color),
378                background_color: format.background_color.as_ref().map(convert_color),
379                anchor_href: format.anchor_href.clone(),
380                tooltip: format.tooltip.clone(),
381                vertical_alignment: convert_vertical_alignment(format),
382                image_name: None,
383                image_width: 0.0,
384                image_height: 0.0,
385                footnote_marker: None,
386                features: Vec::new(),
387            }
388        }
389        // A footnote reference: one sentinel character in the block's text, and
390        // the marker painted over it. `text` stays the sentinel so the fragment's
391        // bytes still match the block string the layout indexes against; the
392        // marker travels separately and is shaped on its own.
393        FragmentContent::FootnoteReference { marker, format, .. } => FragmentParams {
394            text: "\u{FFFC}".to_string(),
395            offset: byte_offset,
396            length: 1,
397            font_family: format.font_family.clone(),
398            font_weight: format.font_weight,
399            font_bold: format.font_bold,
400            font_italic: format.font_italic,
401            font_point_size: format.font_point_size,
402            underline_style: convert_underline_style(format),
403            overline: format.font_overline.unwrap_or(false),
404            strikeout: format.font_strikeout.unwrap_or(false),
405            is_link: format.is_anchor.unwrap_or(false),
406            letter_spacing: 0.0,
407            word_spacing: 0.0,
408            foreground_color: format.foreground_color.as_ref().map(convert_color),
409            underline_color: format.underline_color.as_ref().map(convert_color),
410            background_color: format.background_color.as_ref().map(convert_color),
411            anchor_href: format.anchor_href.clone(),
412            tooltip: format.tooltip.clone(),
413            vertical_alignment: convert_vertical_alignment(format),
414            image_name: None,
415            image_width: 0.0,
416            image_height: 0.0,
417            footnote_marker: Some(marker.clone()),
418            features: Vec::new(),
419        },
420        FragmentContent::Image {
421            name,
422            width,
423            height,
424            quality: _,
425            format,
426            ..
427        } => FragmentParams {
428            text: "\u{FFFC}".to_string(),
429            offset: byte_offset,
430            length: 1,
431            font_family: None,
432            font_weight: None,
433            font_bold: None,
434            font_italic: None,
435            font_point_size: None,
436            underline_style: crate::types::UnderlineStyle::None,
437            overline: false,
438            strikeout: false,
439            is_link: format.is_anchor.unwrap_or(false),
440            letter_spacing: 0.0,
441            word_spacing: 0.0,
442            foreground_color: None,
443            underline_color: None,
444            background_color: None,
445            anchor_href: format.anchor_href.clone(),
446            tooltip: format.tooltip.clone(),
447            vertical_alignment: crate::types::VerticalAlignment::Normal,
448            image_name: Some(name.clone()),
449            image_width: *width as f32,
450            image_height: *height as f32,
451            footnote_marker: None,
452            features: Vec::new(),
453        },
454    }
455}
456
457fn convert_vertical_alignment(
458    format: &text_document::TextFormat,
459) -> crate::types::VerticalAlignment {
460    use crate::types::VerticalAlignment;
461    match format.vertical_alignment {
462        Some(text_document::CharVerticalAlignment::SuperScript) => VerticalAlignment::SuperScript,
463        Some(text_document::CharVerticalAlignment::SubScript) => VerticalAlignment::SubScript,
464        _ => VerticalAlignment::Normal,
465    }
466}
467
468/// The underline a run gets, in precedence order: an explicit style, then an
469/// explicit on/off flag, then — for a link that has said nothing either way —
470/// the single underline a reader expects a link to carry.
471///
472/// The link rule is a **default, not an override**: `font_underline:
473/// Some(false)` still wins, so an author who deliberately unstyled their links
474/// keeps them unstyled. Colour follows the same rule, in `convert_fragment`.
475///
476/// `underline_color` needs no matching rule — `None` already means "use the
477/// foreground", so a link's underline picks up the link colour for free.
478fn convert_underline_style(format: &text_document::TextFormat) -> crate::types::UnderlineStyle {
479    use crate::types::UnderlineStyle;
480    match &format.underline_style {
481        Some(s) => convert_underline_style_value(s),
482        None => match format.font_underline {
483            Some(true) => UnderlineStyle::Single,
484            Some(false) => UnderlineStyle::None,
485            None if format.is_anchor.unwrap_or(false) => UnderlineStyle::Single,
486            None => UnderlineStyle::None,
487        },
488    }
489}
490
491/// Map a raw `text_document::UnderlineStyle` to the typesetter enum.
492fn convert_underline_style_value(
493    s: &text_document::UnderlineStyle,
494) -> crate::types::UnderlineStyle {
495    use crate::types::UnderlineStyle;
496    match s {
497        text_document::UnderlineStyle::SingleUnderline => UnderlineStyle::Single,
498        text_document::UnderlineStyle::DashUnderline => UnderlineStyle::Dash,
499        text_document::UnderlineStyle::DotLine => UnderlineStyle::Dot,
500        text_document::UnderlineStyle::DashDotLine => UnderlineStyle::DashDot,
501        text_document::UnderlineStyle::DashDotDotLine => UnderlineStyle::DashDotDot,
502        text_document::UnderlineStyle::WaveUnderline => UnderlineStyle::Wave,
503        text_document::UnderlineStyle::SpellCheckUnderline => UnderlineStyle::SpellCheck,
504        text_document::UnderlineStyle::NoUnderline => UnderlineStyle::None,
505    }
506}
507
508/// Convert a block snapshot's paint-only highlight overlay into the typesetter's
509/// [`PaintSpan`]s. Char offsets pass through unchanged (both sides are
510/// block-relative char offsets — the space post-layout glyph clusters live in).
511/// Underline is expressed through `underline_style`: an explicit
512/// `underline_style` wins, else `font_underline` maps to Single / None.
513pub fn convert_paint_spans(block: &BlockSnapshot) -> Vec<PaintSpan> {
514    block
515        .paint_highlights
516        .iter()
517        .map(|h| {
518            let underline_style = match &h.underline_style {
519                Some(s) => Some(convert_underline_style_value(s)),
520                None => match h.font_underline {
521                    Some(true) => Some(crate::types::UnderlineStyle::Single),
522                    Some(false) => Some(crate::types::UnderlineStyle::None),
523                    None => None,
524                },
525            };
526            PaintSpan {
527                char_start: h.start,
528                char_end: h.start + h.length,
529                foreground_color: h.foreground_color.as_ref().map(convert_color),
530                underline_color: h.underline_color.as_ref().map(convert_color),
531                background_color: h.background_color.as_ref().map(convert_color),
532                underline_style,
533                overline: h.font_overline,
534                strikeout: h.font_strikeout,
535            }
536        })
537        .collect()
538}
539
540/// Walk a whole [`FlowSnapshot`] (top-level blocks, table cells, and frames
541/// recursively) and collect the paint-only overlay for every block that has
542/// one, keyed by block_id. Blocks without paint highlights are omitted (the
543/// engine resets those to their base colors).
544pub fn collect_paint_spans(
545    flow: &FlowSnapshot,
546) -> std::collections::HashMap<usize, Vec<PaintSpan>> {
547    let mut out = std::collections::HashMap::new();
548    for el in &flow.elements {
549        collect_paint_spans_element(el, &mut out);
550    }
551    out
552}
553
554fn collect_paint_spans_element(
555    el: &FlowElementSnapshot,
556    out: &mut std::collections::HashMap<usize, Vec<PaintSpan>>,
557) {
558    match el {
559        FlowElementSnapshot::Block(b) => {
560            if !b.paint_highlights.is_empty() {
561                out.insert(b.block_id, convert_paint_spans(b));
562            }
563        }
564        FlowElementSnapshot::Table(t) => {
565            for c in &t.cells {
566                for b in &c.blocks {
567                    if !b.paint_highlights.is_empty() {
568                        out.insert(b.block_id, convert_paint_spans(b));
569                    }
570                }
571            }
572        }
573        FlowElementSnapshot::Frame(f) => {
574            for e in &f.elements {
575                collect_paint_spans_element(e, out);
576            }
577        }
578    }
579}
580
581fn convert_color(c: &text_document::Color) -> [f32; 4] {
582    [
583        c.red as f32 / 255.0,
584        c.green as f32 / 255.0,
585        c.blue as f32 / 255.0,
586        c.alpha as f32 / 255.0,
587    ]
588}
589
590/// Parse a CSS color string into RGBA floats (0.0-1.0).
591///
592/// Supports: `#RGB`, `#RRGGBB`, `#RRGGBBAA`, `rgb(r,g,b)`, `rgba(r,g,b,a)`,
593/// and common named colors.
594fn parse_css_color(s: &str) -> Option<[f32; 4]> {
595    let s = s.trim();
596
597    // Named colors
598    match s.to_ascii_lowercase().as_str() {
599        "transparent" => return Some([0.0, 0.0, 0.0, 0.0]),
600        "black" => return Some([0.0, 0.0, 0.0, 1.0]),
601        "white" => return Some([1.0, 1.0, 1.0, 1.0]),
602        "red" => return Some([1.0, 0.0, 0.0, 1.0]),
603        "green" => return Some([0.0, 128.0 / 255.0, 0.0, 1.0]),
604        "blue" => return Some([0.0, 0.0, 1.0, 1.0]),
605        "yellow" => return Some([1.0, 1.0, 0.0, 1.0]),
606        "cyan" | "aqua" => return Some([0.0, 1.0, 1.0, 1.0]),
607        "magenta" | "fuchsia" => return Some([1.0, 0.0, 1.0, 1.0]),
608        "gray" | "grey" => return Some([128.0 / 255.0, 128.0 / 255.0, 128.0 / 255.0, 1.0]),
609        _ => {}
610    }
611
612    // Hex formats
613    if let Some(hex) = s.strip_prefix('#') {
614        let hex = hex.trim();
615        return match hex.len() {
616            3 => {
617                // #RGB
618                let r = u8::from_str_radix(&hex[0..1], 16).ok()?;
619                let g = u8::from_str_radix(&hex[1..2], 16).ok()?;
620                let b = u8::from_str_radix(&hex[2..3], 16).ok()?;
621                Some([
622                    (r * 17) as f32 / 255.0,
623                    (g * 17) as f32 / 255.0,
624                    (b * 17) as f32 / 255.0,
625                    1.0,
626                ])
627            }
628            4 => {
629                // #RGBA
630                let r = u8::from_str_radix(&hex[0..1], 16).ok()?;
631                let g = u8::from_str_radix(&hex[1..2], 16).ok()?;
632                let b = u8::from_str_radix(&hex[2..3], 16).ok()?;
633                let a = u8::from_str_radix(&hex[3..4], 16).ok()?;
634                Some([
635                    (r * 17) as f32 / 255.0,
636                    (g * 17) as f32 / 255.0,
637                    (b * 17) as f32 / 255.0,
638                    (a * 17) as f32 / 255.0,
639                ])
640            }
641            6 => {
642                // #RRGGBB
643                let r = u8::from_str_radix(&hex[0..2], 16).ok()?;
644                let g = u8::from_str_radix(&hex[2..4], 16).ok()?;
645                let b = u8::from_str_radix(&hex[4..6], 16).ok()?;
646                Some([r as f32 / 255.0, g as f32 / 255.0, b as f32 / 255.0, 1.0])
647            }
648            8 => {
649                // #RRGGBBAA
650                let r = u8::from_str_radix(&hex[0..2], 16).ok()?;
651                let g = u8::from_str_radix(&hex[2..4], 16).ok()?;
652                let b = u8::from_str_radix(&hex[4..6], 16).ok()?;
653                let a = u8::from_str_radix(&hex[6..8], 16).ok()?;
654                Some([
655                    r as f32 / 255.0,
656                    g as f32 / 255.0,
657                    b as f32 / 255.0,
658                    a as f32 / 255.0,
659                ])
660            }
661            _ => None,
662        };
663    }
664
665    // rgb(r, g, b) and rgba(r, g, b, a)
666    let inner = s
667        .strip_prefix("rgba(")
668        .and_then(|s| s.strip_suffix(')'))
669        .or_else(|| s.strip_prefix("rgb(").and_then(|s| s.strip_suffix(')')))?;
670
671    let parts: Vec<&str> = inner.split(',').collect();
672    match parts.len() {
673        3 => {
674            let r: u8 = parts[0].trim().parse().ok()?;
675            let g: u8 = parts[1].trim().parse().ok()?;
676            let b: u8 = parts[2].trim().parse().ok()?;
677            Some([r as f32 / 255.0, g as f32 / 255.0, b as f32 / 255.0, 1.0])
678        }
679        4 => {
680            let r: u8 = parts[0].trim().parse().ok()?;
681            let g: u8 = parts[1].trim().parse().ok()?;
682            let b: u8 = parts[2].trim().parse().ok()?;
683            let a: f32 = parts[3].trim().parse().ok()?;
684            Some([r as f32 / 255.0, g as f32 / 255.0, b as f32 / 255.0, a])
685        }
686        _ => None,
687    }
688}
689
690fn convert_alignment(a: &text_document::Alignment) -> Alignment {
691    match a {
692        text_document::Alignment::Left => Alignment::Left,
693        text_document::Alignment::Right => Alignment::Right,
694        text_document::Alignment::Center => Alignment::Center,
695        text_document::Alignment::Justify => Alignment::Justify,
696    }
697}
698
699/// Map a block's stored reading direction onto a shaping direction.
700///
701/// `None` means the writer never set one, so the text decides
702/// (UAX #9 P2/P3). A stored direction overrides that detection — which is
703/// the point of storing it, since an Arabic paragraph opening with a
704/// Latin acronym auto-detects as left-to-right.
705fn convert_direction(d: Option<&text_document::TextDirection>) -> TextDirection {
706    match d {
707        None => TextDirection::Auto,
708        Some(text_document::TextDirection::LeftToRight) => TextDirection::LeftToRight,
709        Some(text_document::TextDirection::RightToLeft) => TextDirection::RightToLeft,
710    }
711}
712
713pub fn convert_table(table: &TableSnapshot) -> TableLayoutParams {
714    convert_table_with(table, &BridgeOptions::default())
715}
716
717pub fn convert_table_with(table: &TableSnapshot, opts: &BridgeOptions) -> TableLayoutParams {
718    let column_widths: Vec<f32> = table.column_widths.iter().map(|&w| w as f32).collect();
719
720    let cells: Vec<CellLayoutParams> = table.cells.iter().map(|c| convert_cell(c, opts)).collect();
721
722    TableLayoutParams {
723        table_id: table.table_id,
724        rows: table.rows,
725        columns: table.columns,
726        column_widths,
727        border_width: table.format.border.unwrap_or(1) as f32,
728        cell_spacing: table.format.cell_spacing.unwrap_or(0) as f32,
729        cell_padding: table.format.cell_padding.unwrap_or(4) as f32,
730        cells,
731    }
732}
733
734fn convert_cell(cell: &CellSnapshot, opts: &BridgeOptions) -> CellLayoutParams {
735    let blocks: Vec<BlockLayoutParams> = cell
736        .blocks
737        .iter()
738        .map(|b| convert_block_with(b, opts))
739        .collect();
740
741    let background_color = cell
742        .format
743        .background_color
744        .as_ref()
745        .and_then(|s| parse_css_color(s));
746
747    CellLayoutParams {
748        row: cell.row,
749        column: cell.column,
750        blocks,
751        background_color,
752    }
753}
754
755pub fn convert_frame(frame: &FrameSnapshot) -> FrameLayoutParams {
756    convert_frame_with(frame, &BridgeOptions::default())
757}
758
759pub fn convert_frame_with(frame: &FrameSnapshot, opts: &BridgeOptions) -> FrameLayoutParams {
760    let mut blocks = Vec::new();
761    let mut tables = Vec::new();
762    let mut frames = Vec::new();
763
764    for (i, element) in frame.elements.iter().enumerate() {
765        match element {
766            FlowElementSnapshot::Block(block) => {
767                // Carry the flow index so `layout_frame` can interleave
768                // blocks with sibling tables/frames in document order.
769                // Dropping the index here is the bug that caused
770                // nested-frame content (e.g. a depth-3 blockquote
771                // sitting between two depth-2 blocks) to render in the
772                // wrong visual order.
773                blocks.push((i, convert_block_with(block, opts)));
774            }
775            FlowElementSnapshot::Table(table) => {
776                tables.push((i, convert_table_with(table, opts)));
777            }
778            FlowElementSnapshot::Frame(inner_frame) => {
779                frames.push((i, convert_frame_with(inner_frame, opts)));
780            }
781        }
782    }
783
784    let position = match &frame.format.position {
785        Some(text_document::FramePosition::InFlow) | None => FramePosition::Inline,
786        Some(text_document::FramePosition::FloatLeft) => FramePosition::FloatLeft,
787        Some(text_document::FramePosition::FloatRight) => FramePosition::FloatRight,
788    };
789
790    let is_blockquote = frame.format.is_blockquote == Some(true);
791
792    FrameLayoutParams {
793        frame_id: frame.frame_id,
794        position,
795        width: frame.format.width.map(|w| w as f32),
796        height: frame.format.height.map(|h| h as f32),
797        margin_top: frame
798            .format
799            .top_margin
800            .unwrap_or(if is_blockquote { 4 } else { 0 }) as f32,
801        margin_bottom: frame
802            .format
803            .bottom_margin
804            .unwrap_or(if is_blockquote { 4 } else { 0 }) as f32,
805        margin_left: frame
806            .format
807            .left_margin
808            .unwrap_or(if is_blockquote { 16 } else { 0 }) as f32,
809        margin_right: frame.format.right_margin.unwrap_or(0) as f32,
810        padding: frame
811            .format
812            .padding
813            .unwrap_or(if is_blockquote { 8 } else { 0 }) as f32,
814        border_width: frame
815            .format
816            .border
817            .unwrap_or(if is_blockquote { 3 } else { 0 }) as f32,
818        border_style: if is_blockquote {
819            crate::layout::frame::FrameBorderStyle::LeftOnly
820        } else {
821            crate::layout::frame::FrameBorderStyle::Full
822        },
823        blocks,
824        tables,
825        frames,
826    }
827}
828
829#[cfg(test)]
830mod tests {
831    use super::iso639_1;
832
833    #[test]
834    fn iso639_1_parses_two_letter_codes_case_insensitively() {
835        assert_eq!(iso639_1("en"), Some(*b"en"));
836        assert_eq!(iso639_1("FR"), Some(*b"fr"));
837        assert_eq!(iso639_1("De"), Some(*b"de"));
838        // Region subtags are ignored — only the primary subtag matters.
839        assert_eq!(iso639_1("en-US"), Some(*b"en"));
840        assert_eq!(iso639_1("  fr  "), Some(*b"fr"));
841    }
842
843    #[test]
844    fn iso639_1_rejects_non_letter_codes() {
845        assert_eq!(iso639_1(""), None);
846        assert_eq!(iso639_1("x"), None);
847        assert_eq!(iso639_1("12"), None);
848    }
849
850    // ── Link styling ────────────────────────────────────────────
851    //
852    // Colour and underline are *defaults* a link gets when it has said
853    // nothing itself. Every one of these tests is really about precedence:
854    // what an author set explicitly must always win, or a document loses
855    // formatting it asked for.
856
857    use super::{BridgeOptions, convert_fragment, convert_underline_style};
858    use crate::types::UnderlineStyle;
859    use text_document::{FragmentContent, TextFormat};
860
861    const LINK_FG: [f32; 4] = [0.1, 0.3, 0.9, 1.0];
862    const CODE_FG: [f32; 4] = [0.5, 0.5, 0.5, 1.0];
863    const AUTHOR_FG: text_document::Color = text_document::Color {
864        red: 200,
865        green: 10,
866        blue: 10,
867        alpha: 255,
868    };
869
870    fn opts() -> BridgeOptions {
871        BridgeOptions {
872            link_foreground: Some(LINK_FG),
873            code_block_foreground: Some(CODE_FG),
874            ..Default::default()
875        }
876    }
877
878    fn fragment_of(format: TextFormat) -> FragmentContent {
879        FragmentContent::Text {
880            text: "text".to_string(),
881            format,
882            offset: 0,
883            length: 4,
884            element_id: 0,
885            word_starts: Vec::new(),
886        }
887    }
888
889    fn link() -> TextFormat {
890        TextFormat {
891            anchor_href: Some("https://example.com".into()),
892            is_anchor: Some(true),
893            ..Default::default()
894        }
895    }
896
897    #[test]
898    fn a_link_takes_the_hosts_link_colour() {
899        let params = convert_fragment(&fragment_of(link()), 1.0, &opts(), 0);
900        assert_eq!(params.foreground_color, Some(LINK_FG));
901    }
902
903    #[test]
904    fn plain_prose_takes_no_colour_at_all() {
905        let params = convert_fragment(&fragment_of(TextFormat::default()), 1.0, &opts(), 0);
906        assert_eq!(
907            params.foreground_color, None,
908            "the link colour must not leak onto ordinary text"
909        );
910    }
911
912    #[test]
913    fn an_explicit_colour_beats_the_link_colour() {
914        let fmt = TextFormat {
915            foreground_color: Some(AUTHOR_FG),
916            ..link()
917        };
918        let params = convert_fragment(&fragment_of(fmt), 1.0, &opts(), 0);
919        assert_ne!(
920            params.foreground_color,
921            Some(LINK_FG),
922            "an author who picked a colour must keep it"
923        );
924    }
925
926    #[test]
927    fn a_link_beats_monospace_when_a_run_is_both() {
928        let fmt = TextFormat {
929            font_family: Some("monospace".into()),
930            ..link()
931        };
932        let params = convert_fragment(&fragment_of(fmt), 1.0, &opts(), 0);
933        assert_eq!(
934            params.foreground_color,
935            Some(LINK_FG),
936            "\"you can follow this\" is the more useful of the two signals"
937        );
938    }
939
940    #[test]
941    fn a_link_is_underlined_by_default() {
942        assert_eq!(convert_underline_style(&link()), UnderlineStyle::Single);
943    }
944
945    #[test]
946    fn plain_prose_is_not_underlined() {
947        assert_eq!(
948            convert_underline_style(&TextFormat::default()),
949            UnderlineStyle::None
950        );
951    }
952
953    #[test]
954    fn an_author_may_turn_a_links_underline_off() {
955        // The default must be a default. A writer who unstyled their links
956        // keeps them unstyled.
957        let fmt = TextFormat {
958            font_underline: Some(false),
959            ..link()
960        };
961        assert_eq!(convert_underline_style(&fmt), UnderlineStyle::None);
962    }
963
964    #[test]
965    fn an_explicit_underline_style_beats_the_link_default() {
966        let fmt = TextFormat {
967            underline_style: Some(text_document::UnderlineStyle::WaveUnderline),
968            ..link()
969        };
970        assert_eq!(convert_underline_style(&fmt), UnderlineStyle::Wave);
971    }
972}