1use 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
20fn 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#[derive(Clone, Copy)]
41pub struct BridgeOptions {
42 pub code_block_background: [f32; 4],
47 pub code_block_foreground: Option<[f32; 4]>,
53 pub link_foreground: Option<[f32; 4]>,
66 pub echo_char: Option<char>,
76 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
98pub fn convert_flow(flow: &FlowSnapshot) -> FlowElements {
102 convert_flow_with(flow, &BridgeOptions::default())
103}
104
105pub 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
133pub struct FlowElements {
135 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
145pub 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 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 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
286fn 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 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 let is_monospace = format
336 .font_family
337 .as_deref()
338 .map(|f| f.eq_ignore_ascii_case("monospace"))
339 .unwrap_or(false);
340 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 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 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
468fn 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
491fn 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
508pub 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
540pub 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
590fn parse_css_color(s: &str) -> Option<[f32; 4]> {
595 let s = s.trim();
596
597 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 if let Some(hex) = s.strip_prefix('#') {
614 let hex = hex.trim();
615 return match hex.len() {
616 3 => {
617 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 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 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 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 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
699fn 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 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 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 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 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}