1use std::sync::Arc;
11
12use super::document::{Block, BlockKind, Document, Run, Size, Style, normalise_link};
13
14const QUOTE_STYLE: &str = "margin:0 0 0 .8ex;border-left:1px solid #ccc;padding-left:1ex";
16
17pub fn escape(text: &str) -> String {
19 let mut out = String::with_capacity(text.len());
20 for c in text.chars() {
21 match c {
22 '&' => out.push_str("&"),
23 '<' => out.push_str("<"),
24 '>' => out.push_str(">"),
25 '"' => out.push_str("""),
26 _ => out.push(c),
27 }
28 }
29 out
30}
31
32fn size_css(size: Size) -> Option<&'static str> {
33 match size {
34 Size::Small => Some("font-size:small"),
35 Size::Normal => None,
36 Size::Large => Some("font-size:large"),
37 Size::Huge => Some("font-size:x-large"),
38 }
39}
40
41#[derive(Debug, Clone, PartialEq, Eq)]
42enum Tag {
43 Link(Arc<str>),
44 Size(Size),
45 Bold,
46 Italic,
47 Underline,
48 Strike,
49}
50
51impl Tag {
52 fn open(&self) -> String {
53 match self {
54 Tag::Link(url) => format!("<a href=\"{}\">", escape(url)),
55 Tag::Size(size) => format!("<span style=\"{}\">", size_css(*size).unwrap_or_default()),
56 Tag::Bold => "<strong>".into(),
57 Tag::Italic => "<em>".into(),
58 Tag::Underline => "<u>".into(),
59 Tag::Strike => "<s>".into(),
60 }
61 }
62
63 fn close(&self) -> &'static str {
64 match self {
65 Tag::Link(_) => "</a>",
66 Tag::Size(_) => "</span>",
67 Tag::Bold => "</strong>",
68 Tag::Italic => "</em>",
69 Tag::Underline => "</u>",
70 Tag::Strike => "</s>",
71 }
72 }
73}
74
75fn tags(style: &Style) -> Vec<Tag> {
78 let mut tags = Vec::new();
79 if let Some(link) = &style.link {
80 tags.push(Tag::Link(link.clone()));
81 }
82 if style.size != Size::Normal {
83 tags.push(Tag::Size(style.size));
84 }
85 for (on, tag) in [
86 (style.bold, Tag::Bold),
87 (style.italic, Tag::Italic),
88 (style.underline, Tag::Underline),
89 (style.strikethrough, Tag::Strike),
90 ] {
91 if on {
92 tags.push(tag);
93 }
94 }
95 tags
96}
97
98fn inline(block: &Block) -> String {
99 let mut out = String::new();
100 let mut open: Vec<Tag> = Vec::new();
101 for run in block.runs() {
102 let wanted = tags(&run.style);
103 let keep = open.iter().zip(&wanted).take_while(|(a, b)| a == b).count();
104 for tag in open.drain(keep..).rev() {
105 out.push_str(tag.close());
106 }
107 for tag in wanted.into_iter().skip(keep) {
108 out.push_str(&tag.open());
109 open.push(tag);
110 }
111 if run.text.is_empty() {
112 out.push_str("<br>");
113 } else {
114 out.push_str(&escape(&run.text));
115 }
116 }
117 for tag in open.iter().rev() {
118 out.push_str(tag.close());
119 }
120 out
121}
122
123#[derive(Debug, Clone, Copy, PartialEq, Eq)]
124enum Container {
125 None,
126 Bullets,
127 Numbers,
128 Quote,
129}
130
131impl Container {
132 fn of(kind: BlockKind) -> Self {
133 match kind {
134 BlockKind::Paragraph => Container::None,
135 BlockKind::Bullet => Container::Bullets,
136 BlockKind::Numbered => Container::Numbers,
137 BlockKind::Quote => Container::Quote,
138 }
139 }
140
141 fn open(self) -> String {
142 match self {
143 Container::None => String::new(),
144 Container::Bullets => "<ul>".into(),
145 Container::Numbers => "<ol>".into(),
146 Container::Quote => format!("<blockquote style=\"{QUOTE_STYLE}\">"),
147 }
148 }
149
150 fn close(self) -> &'static str {
151 match self {
152 Container::None => "",
153 Container::Bullets => "</ul>",
154 Container::Numbers => "</ol>",
155 Container::Quote => "</blockquote>",
156 }
157 }
158}
159
160pub fn to_html(document: &Document) -> String {
162 let mut out = String::from("<div style=\"white-space:pre-wrap\">");
163 let mut container = Container::None;
164 for block in document.blocks() {
165 let next = Container::of(block.kind());
166 if next != container {
167 out.push_str(container.close());
168 out.push_str(&next.open());
169 container = next;
170 }
171 let (open, close) = if block.kind().is_list() {
172 ("<li>", "</li>")
173 } else {
174 ("<div>", "</div>")
175 };
176 out.push_str(open);
177 out.push_str(&inline(block));
178 out.push_str(close);
179 }
180 out.push_str(container.close());
181 out.push_str("</div>");
182 out
183}
184
185pub fn to_html_document(document: &Document) -> String {
187 format!(
188 "<!doctype html><html><head><meta charset=\"utf-8\"></head><body>{}</body></html>",
189 to_html(document)
190 )
191}
192
193#[derive(Debug, Clone, Default)]
195struct Change {
196 bold: Option<bool>,
197 italic: Option<bool>,
198 underline: Option<bool>,
199 strikethrough: Option<bool>,
200 size: Option<Size>,
201 link: Option<Option<Arc<str>>>,
202 preserve: bool,
203}
204
205impl Change {
206 fn apply(&self, style: &mut Style) {
207 let set = |target: &mut bool, value: Option<bool>| {
208 if let Some(value) = value {
209 *target = value;
210 }
211 };
212 set(&mut style.bold, self.bold);
213 set(&mut style.italic, self.italic);
214 set(&mut style.underline, self.underline);
215 set(&mut style.strikethrough, self.strikethrough);
216 if let Some(size) = self.size {
217 style.size = size;
218 }
219 if let Some(link) = &self.link {
220 style.link = link.clone();
221 }
222 }
223
224 fn read_css(&mut self, css: &str) {
225 for declaration in css.split(';') {
226 let Some((property, value)) = declaration.split_once(':') else {
227 continue;
228 };
229 let property = property.trim().to_ascii_lowercase();
230 let value = value.trim().to_ascii_lowercase();
231 match property.as_str() {
232 "font-weight" => {
233 self.bold = match value.as_str() {
234 "bold" | "bolder" => Some(true),
235 "normal" | "lighter" => Some(false),
236 number => number.parse::<u32>().ok().map(|weight| weight >= 600),
237 };
238 }
239 "font-style" => self.italic = Some(value != "normal"),
240 "text-decoration" | "text-decoration-line" => {
241 if value.contains("none") {
242 self.underline = Some(false);
243 self.strikethrough = Some(false);
244 }
245 if value.contains("underline") {
246 self.underline = Some(true);
247 }
248 if value.contains("line-through") {
249 self.strikethrough = Some(true);
250 }
251 }
252 "font-size" => self.size = css_size(&value).or(self.size),
253 "white-space" => {
254 self.preserve = value.starts_with("pre") || value == "break-spaces"
255 }
256 _ => {}
257 }
258 }
259 }
260}
261
262fn css_size(value: &str) -> Option<Size> {
264 let keyword = match value {
265 "xx-small" | "x-small" | "small" | "smaller" => Some(Size::Small),
266 "medium" => Some(Size::Normal),
267 "large" | "larger" => Some(Size::Large),
268 "x-large" | "xx-large" | "xxx-large" => Some(Size::Huge),
269 _ => None,
270 };
271 if keyword.is_some() {
272 return keyword;
273 }
274 let (number, unit) = value
275 .find(|c: char| !(c.is_ascii_digit() || c == '.'))
276 .map_or((value, ""), |at| value.split_at(at));
277 let number: f32 = number.parse().ok()?;
278 let pixels = match unit.trim() {
279 "" | "px" => number,
280 "pt" => number * 4.0 / 3.0,
281 "em" | "rem" => number * 16.0,
282 "%" => number * 0.16,
283 _ => return None,
284 };
285 Some(if pixels < 12.5 {
286 Size::Small
287 } else if pixels <= 16.5 {
288 Size::Normal
289 } else if pixels <= 22.0 {
290 Size::Large
291 } else {
292 Size::Huge
293 })
294}
295
296fn font_size(value: &str) -> Option<Size> {
298 let value = value.trim();
299 let size: i32 = match value.strip_prefix('+') {
300 Some(step) => 3 + step.parse::<i32>().ok()?,
301 None => match value.strip_prefix('-') {
302 Some(step) => 3 - step.parse::<i32>().ok()?,
303 None => value.parse().ok()?,
304 },
305 };
306 Some(match size {
307 ..=2 => Size::Small,
308 3 => Size::Normal,
309 4 | 5 => Size::Large,
310 _ => Size::Huge,
311 })
312}
313
314fn decode_entity(name: &str) -> Option<char> {
315 if let Some(number) = name.strip_prefix('#') {
316 let code = match number.strip_prefix(['x', 'X']) {
317 Some(hex) => u32::from_str_radix(hex, 16).ok()?,
318 None => number.parse().ok()?,
319 };
320 return char::from_u32(code).filter(|c| *c != '\0');
321 }
322 Some(match name {
323 "amp" => '&',
324 "lt" => '<',
325 "gt" => '>',
326 "quot" => '"',
327 "apos" => '\'',
328 "nbsp" => '\u{A0}',
330 "ndash" => '\u{2013}',
331 "mdash" => '\u{2014}',
332 "hellip" => '\u{2026}',
333 "lsquo" => '\u{2018}',
334 "rsquo" => '\u{2019}',
335 "ldquo" => '\u{201C}',
336 "rdquo" => '\u{201D}',
337 "copy" => '\u{A9}',
338 "reg" => '\u{AE}',
339 "trade" => '\u{2122}',
340 "euro" => '\u{20AC}',
341 "pound" => '\u{A3}',
342 _ => return None,
343 })
344}
345
346fn unescape(text: &str) -> String {
348 let mut out = String::with_capacity(text.len());
349 let mut rest = text;
350 while let Some(at) = rest.find('&') {
351 out.push_str(&rest[..at]);
352 rest = &rest[at..];
353 let entity = rest[1..]
354 .find(';')
355 .filter(|end| *end <= 10)
356 .and_then(|end| decode_entity(&rest[1..=end]).map(|c| (c, end + 2)));
357 match entity {
358 Some((c, len)) => {
359 out.push(c);
360 rest = &rest[len..];
361 }
362 None => {
363 out.push('&');
364 rest = &rest[1..];
365 }
366 }
367 }
368 out.push_str(rest);
369 out
370}
371
372#[derive(Debug)]
373enum Token<'a> {
374 Text(&'a str),
375 Start {
376 name: String,
377 attributes: Vec<(String, String)>,
378 closed: bool,
379 },
380 End(String),
381}
382
383fn tokens(html: &str) -> Vec<Token<'_>> {
385 let mut out = Vec::new();
386 let mut rest = html;
387 while !rest.is_empty() {
388 let Some(at) = rest.find('<') else {
389 out.push(Token::Text(rest));
390 break;
391 };
392 if at > 0 {
393 out.push(Token::Text(&rest[..at]));
394 }
395 rest = &rest[at..];
396 if let Some(comment) = rest.strip_prefix("<!--") {
397 rest = comment.find("-->").map_or("", |end| &comment[end + 3..]);
398 continue;
399 }
400 let next = rest[1..].chars().next();
401 let is_tag =
402 next.is_some_and(|c| c.is_ascii_alphabetic() || c == '/' || c == '!' || c == '?');
403 let Some(end) = rest.find('>').filter(|_| is_tag) else {
404 out.push(Token::Text(&rest[..1]));
405 rest = &rest[1..];
406 continue;
407 };
408 let inner = &rest[1..end];
409 rest = &rest[end + 1..];
410 if inner.starts_with('!') || inner.starts_with('?') {
411 continue;
412 }
413 if let Some(name) = inner.strip_prefix('/') {
414 out.push(Token::End(name.trim().to_ascii_lowercase()));
415 continue;
416 }
417 let closed = inner.ends_with('/');
418 let inner = inner.trim_end_matches('/');
419 let name_end = inner
420 .find(|c: char| c.is_whitespace())
421 .unwrap_or(inner.len());
422 out.push(Token::Start {
423 name: inner[..name_end].to_ascii_lowercase(),
424 attributes: attributes(&inner[name_end..]),
425 closed,
426 });
427 }
428 out
429}
430
431fn attributes(text: &str) -> Vec<(String, String)> {
432 let mut out = Vec::new();
433 let mut rest = text.trim_start();
434 while !rest.is_empty() {
435 let name_end = rest
436 .find(|c: char| c.is_whitespace() || c == '=')
437 .unwrap_or(rest.len());
438 let name = rest[..name_end].to_ascii_lowercase();
439 rest = rest[name_end..].trim_start();
440 let mut value = String::new();
441 if let Some(after) = rest.strip_prefix('=') {
442 let after = after.trim_start();
443 let (raw, remaining) = match after.chars().next() {
444 Some(quote @ ('"' | '\'')) => {
445 let body = &after[1..];
446 let end = body.find(quote).unwrap_or(body.len());
447 (&body[..end], body.get(end + 1..).unwrap_or(""))
448 }
449 _ => {
450 let end = after.find(char::is_whitespace).unwrap_or(after.len());
451 (&after[..end], &after[end..])
452 }
453 };
454 value = unescape(raw);
455 rest = remaining.trim_start();
456 }
457 if !name.is_empty() {
458 out.push((name, value));
459 }
460 }
461 out
462}
463
464fn attribute<'a>(attributes: &'a [(String, String)], name: &str) -> Option<&'a str> {
465 attributes
466 .iter()
467 .find(|(key, _)| key == name)
468 .map(|(_, value)| value.as_str())
469}
470
471const VOID: [&str; 11] = [
472 "br", "img", "hr", "meta", "link", "input", "wbr", "col", "area", "base", "source",
473];
474const SKIPPED: [&str; 7] = [
475 "head", "style", "script", "title", "template", "noscript", "iframe",
476];
477const BLOCKS: [&str; 22] = [
478 "p",
479 "div",
480 "li",
481 "ul",
482 "ol",
483 "blockquote",
484 "h1",
485 "h2",
486 "h3",
487 "h4",
488 "h5",
489 "h6",
490 "pre",
491 "table",
492 "tr",
493 "section",
494 "article",
495 "header",
496 "footer",
497 "address",
498 "dl",
499 "dt",
500];
501
502struct Builder {
503 blocks: Vec<Block>,
504 runs: Vec<Run>,
505 kind: Option<BlockKind>,
506 open: Vec<(String, Change)>,
507 lists: Vec<BlockKind>,
508 items: Vec<BlockKind>,
509 quotes: usize,
510 skipping: usize,
511 space_pending: Option<Style>,
513}
514
515impl Builder {
516 fn style(&self) -> Style {
517 let mut style = Style::default();
518 for (_, change) in &self.open {
519 change.apply(&mut style);
520 }
521 style
522 }
523
524 fn preserving(&self) -> bool {
525 self.open.iter().any(|(_, change)| change.preserve)
526 }
527
528 fn context(&self) -> BlockKind {
529 match self.items.last() {
530 Some(kind) => *kind,
531 None if self.quotes > 0 => BlockKind::Quote,
532 None => BlockKind::Paragraph,
533 }
534 }
535
536 fn push_text(&mut self, text: &str) {
537 let text = text.replace('\u{A0}', " ");
538 let text = text.as_str();
539 let style = self.style();
540 if self.kind.is_none() {
541 self.kind = Some(self.context());
542 }
543 match self.runs.last_mut() {
544 Some(run) if run.style == style => run.text.push_str(text),
545 _ => self.runs.push(Run::new(text, style)),
546 }
547 }
548
549 fn text(&mut self, raw: &str) {
550 if self.skipping > 0 {
551 return;
552 }
553 let text = unescape(raw);
554 if self.preserving() {
555 let mut lines = text.split('\n');
556 if let Some(first) = lines.next() {
557 self.push_text(first);
558 }
559 for line in lines {
560 self.end_line(true);
561 self.push_text(line);
562 }
563 return;
564 }
565 for (index, word) in text.split(|c: char| c.is_ascii_whitespace()).enumerate() {
566 if index > 0 && self.space_pending.is_none() {
567 self.space_pending = Some(self.style());
568 }
569 if word.is_empty() {
570 continue;
571 }
572 if let Some(style) = self.space_pending.take()
574 && self.kind.is_some()
575 {
576 match self.runs.last_mut() {
577 Some(run) if run.style == style => run.text.push(' '),
578 _ => self.runs.push(Run::new(" ", style)),
579 }
580 }
581 self.push_text(word);
582 }
583 }
584
585 fn end_line(&mut self, force: bool) {
588 self.space_pending = None;
589 if self.kind.is_none() && !force {
590 return;
591 }
592 let kind = self.kind.take().unwrap_or_else(|| self.context());
593 let mut runs = std::mem::take(&mut self.runs);
594 if !self.preserving()
595 && let Some(last) = runs.last_mut()
596 {
597 let trimmed = last.text.trim_end_matches(' ').len();
598 last.text.truncate(trimmed);
599 }
600 if runs.iter().all(|run| run.text.is_empty()) {
601 runs = vec![Run::new("", self.style())];
602 }
603 self.blocks.push(Block::with_runs(kind, runs));
604 }
605
606 fn start(&mut self, name: &str, attributes: &[(String, String)], closed: bool) {
607 if SKIPPED.contains(&name) {
608 if !closed {
609 self.skipping += 1;
610 }
611 return;
612 }
613 if self.skipping > 0 {
614 return;
615 }
616 if name == "br" {
617 self.end_line(true);
618 return;
619 }
620 if BLOCKS.contains(&name) || name == "hr" {
621 self.end_line(false);
622 }
623 if VOID.contains(&name) || closed {
624 return;
625 }
626 match name {
627 "ul" => self.lists.push(BlockKind::Bullet),
628 "ol" => self.lists.push(BlockKind::Numbered),
629 "li" => {
630 let kind = self.lists.last().copied().unwrap_or(BlockKind::Bullet);
631 self.items.push(kind);
632 }
633 "blockquote" => self.quotes += 1,
634 _ => {}
635 }
636 let mut change = Change::default();
637 match name {
638 "b" | "strong" => change.bold = Some(true),
639 "i" | "em" | "cite" | "var" | "dfn" => change.italic = Some(true),
640 "u" | "ins" => change.underline = Some(true),
641 "s" | "strike" | "del" => change.strikethrough = Some(true),
642 "small" => change.size = Some(Size::Small),
643 "big" => change.size = Some(Size::Large),
644 "h1" => {
645 change.bold = Some(true);
646 change.size = Some(Size::Huge);
647 }
648 "h2" => {
649 change.bold = Some(true);
650 change.size = Some(Size::Large);
651 }
652 "h3" | "h4" | "h5" | "h6" | "th" | "dt" => change.bold = Some(true),
653 "pre" => change.preserve = true,
654 "a" => {
655 change.link = Some(
656 attribute(attributes, "href")
657 .and_then(normalise_link)
658 .map(Into::into),
659 );
660 }
661 "font" => change.size = attribute(attributes, "size").and_then(font_size),
662 _ => {}
663 }
664 if let Some(css) = attribute(attributes, "style") {
665 change.read_css(css);
666 }
667 self.open.push((name.to_owned(), change));
668 }
669
670 fn end(&mut self, name: &str) {
671 if SKIPPED.contains(&name) {
672 self.skipping = self.skipping.saturating_sub(1);
673 return;
674 }
675 if self.skipping > 0 {
676 return;
677 }
678 if BLOCKS.contains(&name) {
679 self.end_line(false);
680 }
681 if let Some(index) = self.open.iter().rposition(|(open, _)| open == name) {
682 self.open.truncate(index);
683 }
684 match name {
685 "ul" | "ol" => {
686 self.lists.pop();
687 }
688 "li" => {
689 self.items.pop();
690 }
691 "blockquote" => self.quotes = self.quotes.saturating_sub(1),
692 _ => {}
693 }
694 }
695}
696
697pub fn from_html(html: &str) -> Document {
700 let mut builder = Builder {
701 blocks: Vec::new(),
702 runs: Vec::new(),
703 kind: None,
704 open: Vec::new(),
705 lists: Vec::new(),
706 items: Vec::new(),
707 quotes: 0,
708 skipping: 0,
709 space_pending: None,
710 };
711 for token in tokens(html) {
712 match token {
713 Token::Text(text) => builder.text(text),
714 Token::Start {
715 name,
716 attributes,
717 closed,
718 } => builder.start(&name, &attributes, closed),
719 Token::End(name) => builder.end(&name),
720 }
721 }
722 builder.end_line(false);
723 Document::from_blocks(builder.blocks)
724}
725
726#[cfg(test)]
727mod tests {
728 use super::*;
729 use crate::forms::rich_text_editor::document::Mark;
730
731 fn bold() -> Style {
732 Style::default().with(Mark::Bold)
733 }
734
735 fn sample() -> Document {
736 Document::from_blocks([
737 Block::with_runs(
738 BlockKind::Paragraph,
739 [
740 Run::plain("Hello "),
741 Run::new("bold", bold()),
742 Run::new(" and ", Style::default()),
743 Run::new("big", bold().with(Mark::Italic).sized(Size::Huge)),
744 Run::plain(" spaced"),
745 ],
746 ),
747 Block::new(BlockKind::Paragraph),
748 Block::with_runs(
749 BlockKind::Bullet,
750 [Run::new("one", Style::default().with(Mark::Underline))],
751 ),
752 Block::with_runs(
753 BlockKind::Bullet,
754 [Run::new("two", Style::default().with(Mark::Strikethrough))],
755 ),
756 Block::with_runs(BlockKind::Numbered, [Run::plain("first")]),
757 Block::with_runs(
758 BlockKind::Paragraph,
759 [
760 Run::plain("see "),
761 Run::new(
762 "the ",
763 Style::default().linked("https://example.com/?a=1&b=2"),
764 ),
765 Run::new("site", bold().linked("https://example.com/?a=1&b=2")),
766 Run::new("small", Style::default().sized(Size::Small)),
767 Run::new("<tag> & \"quotes\"", Style::default().sized(Size::Large)),
768 ],
769 ),
770 Block::with_runs(BlockKind::Quote, [Run::plain("quoted")]),
771 Block::with_runs(BlockKind::Paragraph, [Run::new("", bold())]),
772 ])
773 }
774
775 #[test]
776 fn documents_round_trip_through_html() {
777 let document = sample();
778 let html = to_html(&document);
779 assert_eq!(from_html(&html), document);
780 assert_eq!(from_html(&to_html_document(&document)), document);
781 }
782
783 #[test]
784 fn html_output_is_small_and_nested() {
785 let html = to_html(&sample());
786 assert!(html.starts_with(
787 "<div style=\"white-space:pre-wrap\"><div>Hello <strong>bold</strong> and "
788 ));
789 assert!(
790 html.contains("<span style=\"font-size:x-large\"><strong><em>big</em></strong></span>")
791 );
792 assert!(html.contains("<div><br></div>"));
793 assert!(
794 html.contains("<ul><li><u>one</u></li><li><s>two</s></li></ul><ol><li>first</li></ol>")
795 );
796 assert!(html.contains(
797 "<a href=\"https://example.com/?a=1&b=2\">the <strong>site</strong></a>"
798 ));
799 assert!(html.contains("<tag> & "quotes""));
800 assert!(html.contains("<blockquote style="));
801 assert!(html.contains("<div><strong><br></strong></div>"));
802 }
803
804 #[test]
805 fn other_editors_html_keeps_its_formatting() {
806 let document = from_html(
807 "<html><head><style>p{color:red}</style><title>x</title></head><body>\
808 <p>One <b>bold</b> <i>it</i> <span style=\"font-weight:700;text-decoration:underline\">u</span></p>\
809 <p>Two<br>lines<br><br>after</p>\
810 <h1>Title</h1>\
811 <ul><li>a<ul><li>nested</li></ul></li></ul>\
812 <font size=\"1\">tiny</font><font size=\"+3\">huge</font>\
813 <script>alert(1)</script><!-- comment -->\
814 <a href=\"javascript:alert(1)\">bad</a> <a href='www.ok.com'>ok</a>\
815 </body></html>",
816 );
817 let lines: Vec<String> = document.blocks().iter().map(Block::text).collect();
818 assert_eq!(
819 lines,
820 [
821 "One bold it u",
822 "Two",
823 "lines",
824 "",
825 "after",
826 "Title",
827 "a",
828 "nested",
829 "tinyhugebad ok"
830 ]
831 );
832 let first = &document.blocks()[0];
833 assert!(
834 first
835 .runs()
836 .iter()
837 .any(|run| run.text == "bold" && run.style.bold)
838 );
839 assert!(
840 first
841 .runs()
842 .iter()
843 .any(|run| run.text == "it" && run.style.italic)
844 );
845 assert!(
846 first
847 .runs()
848 .iter()
849 .any(|run| run.text == "u" && run.style.bold && run.style.underline)
850 );
851 let title = &document.blocks()[5].runs()[0].style;
852 assert!(title.bold && title.size == Size::Huge);
853 assert_eq!(document.blocks()[7].kind(), BlockKind::Bullet);
854 let last = document.blocks()[8].runs();
855 assert_eq!(last[0].style.size, Size::Small);
856 assert_eq!(last[1].style.size, Size::Huge);
857 let links: Vec<_> = last
858 .iter()
859 .filter_map(|run| run.style.link.clone())
860 .collect();
861 assert_eq!(links, [Arc::from("https://www.ok.com")]);
862 }
863
864 #[test]
865 fn whitespace_collapses_outside_preserved_text() {
866 let document = from_html("<div> a \n b </div><pre>x y\nz</pre>");
867 let lines: Vec<String> = document.blocks().iter().map(Block::text).collect();
868 assert_eq!(lines, ["a b", "x y", "z"]);
869 }
870
871 #[test]
872 fn entities_and_stray_brackets_read_as_text() {
873 let document = from_html("a < b && c AB &unknown; 1 < 2");
874 assert_eq!(document.text(), "a < b && c AB &unknown; 1 < 2");
875 }
876
877 #[test]
878 fn empty_html_is_an_empty_document() {
879 assert!(from_html("").is_empty());
880 assert!(from_html("<html><body></body></html>").is_empty());
881 assert!(to_html(&Document::new()).contains("<div><br></div>"));
882 }
883
884 #[test]
885 fn css_sizes_map_to_the_nearest_size() {
886 assert_eq!(css_size("small"), Some(Size::Small));
887 assert_eq!(css_size("12px"), Some(Size::Small));
888 assert_eq!(css_size("16px"), Some(Size::Normal));
889 assert_eq!(css_size("13.5pt"), Some(Size::Large));
890 assert_eq!(css_size("2em"), Some(Size::Huge));
891 assert_eq!(css_size("100%"), Some(Size::Normal));
892 assert_eq!(css_size("x-large"), Some(Size::Huge));
893 assert_eq!(css_size("calc(1px)"), None);
894 assert_eq!(font_size("7"), Some(Size::Huge));
895 assert_eq!(font_size("-1"), Some(Size::Small));
896 assert_eq!(font_size("x"), None);
897 }
898}