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 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 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
299fn 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 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 let is_monospace = format
349 .font_family
350 .as_deref()
351 .map(|f| f.eq_ignore_ascii_case("monospace"))
352 .unwrap_or(false);
353 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 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 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
480fn 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
503fn 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
520pub 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
552pub 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
602fn parse_css_color(s: &str) -> Option<[f32; 4]> {
607 let s = s.trim();
608
609 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 if let Some(hex) = s.strip_prefix('#') {
626 let hex = hex.trim();
627 return match hex.len() {
628 3 => {
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 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 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 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 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 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
711fn 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 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 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 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 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}