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
133#[non_exhaustive]
135pub struct FlowElements {
136 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
146pub 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 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 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 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
289fn 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 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 let is_monospace = format
339 .font_family
340 .as_deref()
341 .map(|f| f.eq_ignore_ascii_case("monospace"))
342 .unwrap_or(false);
343 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 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 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
470fn 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
493fn 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
510pub 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
542pub 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
592fn parse_css_color(s: &str) -> Option<[f32; 4]> {
597 let s = s.trim();
598
599 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 if let Some(hex) = s.strip_prefix('#') {
616 let hex = hex.trim();
617 return match hex.len() {
618 3 => {
619 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 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 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 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 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
701fn 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 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 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 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 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}