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