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