BlueGit

ict rusty-teams

Files

rusty-teams / vendor / gpui-base / src / text / format / html.rs

html.rs

eef6c0a4 History
html.rs 25.7 KiB Download Raw
1use std::cell::RefCell;
2use std::collections::HashMap;
3use std::ops::Range;
4use std::rc::Rc;
5use std::sync::Arc;
6
7use gpui::{DefiniteLength, Hsla, SharedString, px, relative};
8use html5ever::tendril::TendrilSink;
9use html5ever::{LocalName, ParseOpts, local_name, parse_document};
10use markup5ever_rcdom::{Node, NodeData, RcDom};
11
12use crate::text::document::ParsedDocument;
13use crate::text::node::{
14 self, BlockNode, ImageNode, InlineNode, LinkMark, NodeContext, Paragraph, Table, TableRow,
15 TextMark,
16};
17
18const BLOCK_ELEMENTS: [&str; 35] = [
19 "html",
20 "body",
21 "head",
22 "address",
23 "article",
24 "aside",
25 "blockquote",
26 "details",
27 "summary",
28 "dialog",
29 "div",
30 "dl",
31 "fieldset",
32 "figcaption",
33 "figure",
34 "footer",
35 "form",
36 "h1",
37 "h2",
38 "h3",
39 "h4",
40 "h5",
41 "h6",
42 "header",
43 "hr",
44 "main",
45 "nav",
46 "ol",
47 "p",
48 "pre",
49 "section",
50 "table",
51 "ul",
52 "style",
53 "script",
54];
55
56/// Parse HTML into AST Node.
57pub(crate) fn parse(source: &str, cx: &mut NodeContext) -> Result<ParsedDocument, SharedString> {
58 let opts = ParseOpts {
59 ..Default::default()
60 };
61
62 let bytes = cleanup_html(&source);
63 let mut cursor = std::io::Cursor::new(bytes);
64 // Ref
65 // https://github.com/servo/html5ever/blob/main/rcdom/examples/print-rcdom.rs
66 let dom = parse_document(RcDom::default(), opts)
67 .from_utf8()
68 .read_from(&mut cursor)
69 .map_err(|e| SharedString::from(format!("{:?}", e)))?;
70
71 let mut paragraph = Paragraph::default();
72 // NOTE: The outer paragraph is not used.
73 let node: BlockNode =
74 parse_node(&dom.document, &mut paragraph, cx).unwrap_or(BlockNode::Unknown);
75 let node = node.compact();
76
77 Ok(ParsedDocument {
78 source: source.to_string().into(),
79 blocks: Arc::new(vec![node]),
80 })
81}
82
83fn cleanup_html(source: &str) -> Vec<u8> {
84 let mut w = std::io::Cursor::new(vec![]);
85 let mut r = std::io::Cursor::new(source);
86 let mut minify = super::html5minify::Minifier::new(&mut w);
87 minify.omit_doctype(true);
88 if let Ok(()) = minify.minify(&mut r) {
89 w.into_inner()
90 } else {
91 source.bytes().collect()
92 }
93}
94
95fn attr_value(attrs: &RefCell<Vec<html5ever::Attribute>>, name: LocalName) -> Option<String> {
96 attrs.borrow().iter().find_map(|attr| {
97 if attr.name.local == name {
98 Some(attr.value.to_string())
99 } else {
100 None
101 }
102 })
103}
104
105/// Get the highlight background color for a `<mark>` element.
106///
107/// Reads the `color` attribute first, then the `background-color` declaration
108/// from the `style` attribute. Base accepts CSS hex plus common named colors.
109fn mark_color(attrs: &RefCell<Vec<html5ever::Attribute>>) -> Option<Hsla> {
110 let color_attr = attrs.borrow().iter().find_map(|attr| {
111 if &*attr.name.local == "color" {
112 Some(attr.value.to_string())
113 } else {
114 None
115 }
116 });
117
118 if let Some(value) = color_attr
119 && let Some(color) = parse_mark_color(value.trim())
120 {
121 return Some(color);
122 }
123
124 style_attrs(attrs)
125 .get("background-color")
126 .and_then(|v| parse_mark_color(v.trim()))
127}
128
129fn parse_mark_color(value: &str) -> Option<Hsla> {
130 if value.starts_with('#') {
131 return gpui::Rgba::try_from(value).ok().map(Into::into);
132 }
133 match value.to_ascii_lowercase().as_str() {
134 "black" => Some(gpui::rgb(0x000000).into()),
135 "white" => Some(gpui::rgb(0xffffff).into()),
136 "blue" => Some(gpui::rgb(0x3b82f6).into()),
137 "yellow" => Some(gpui::rgb(0xfacc15).into()),
138 _ => None,
139 }
140}
141
142/// Get style properties to HashMap
143/// TODO: Use cssparser to parse style attribute.
144fn style_attrs(attrs: &RefCell<Vec<html5ever::Attribute>>) -> HashMap<String, String> {
145 let mut styles = HashMap::new();
146 let Some(css_text) = attr_value(attrs, local_name!("style")) else {
147 return styles;
148 };
149
150 for decl in css_text.split(';') {
151 let mut parts = decl.splitn(2, ':');
152 if let (Some(key), Some(value)) = (parts.next(), parts.next()) {
153 styles.insert(
154 key.trim().to_lowercase().to_string(),
155 value.trim().to_string(),
156 );
157 }
158 }
159
160 styles
161}
162
163/// Parse length value from style attribute.
164///
165/// When is percentage, it will be converted to relative length.
166/// Else, it will be converted to pixels.
167fn value_to_length(value: &str) -> Option<DefiniteLength> {
168 if value.ends_with("%") {
169 value
170 .trim_end_matches("%")
171 .parse::<f32>()
172 .ok()
173 .map(|v| relative(v / 100.))
174 } else {
175 value
176 .trim_end_matches("px")
177 .parse()
178 .ok()
179 .map(|v| px(v).into())
180 }
181}
182
183/// Get width, height from attributes or parse them from style attribute.
184fn attr_width_height(
185 attrs: &RefCell<Vec<html5ever::Attribute>>,
186) -> (Option<DefiniteLength>, Option<DefiniteLength>) {
187 let mut width = None;
188 let mut height = None;
189
190 if let Some(value) = attr_value(attrs, local_name!("width")) {
191 width = value_to_length(&value);
192 }
193
194 if let Some(value) = attr_value(attrs, local_name!("height")) {
195 height = value_to_length(&value);
196 }
197
198 if width.is_none() || height.is_none() {
199 let styles = style_attrs(attrs);
200 if width.is_none() {
201 width = styles.get("width").and_then(|v| value_to_length(&v));
202 }
203 if height.is_none() {
204 height = styles.get("height").and_then(|v| value_to_length(&v));
205 }
206 }
207
208 (width, height)
209}
210
211fn parse_table_row(table: &mut Table, node: &Rc<Node>) {
212 let mut row = TableRow::default();
213 let mut count = 0;
214 for child in node.children.borrow().iter() {
215 match child.data {
216 NodeData::Element {
217 ref name,
218 ref attrs,
219 ..
220 } if name.local == local_name!("td") || name.local == local_name!("th") => {
221 if child.children.borrow().is_empty() {
222 continue;
223 }
224
225 count += 1;
226 parse_table_cell(&mut row, child, attrs);
227 }
228 _ => {}
229 }
230 }
231
232 if count > 0 {
233 table.children.push(row);
234 }
235}
236
237fn parse_table_cell(
238 row: &mut node::TableRow,
239 node: &Rc<Node>,
240 attrs: &RefCell<Vec<html5ever::Attribute>>,
241) {
242 let mut paragraph = Paragraph::default();
243 for child in node.children.borrow().iter() {
244 parse_paragraph(&mut paragraph, child);
245 }
246 let width = attr_width_height(attrs).0;
247 let table_cell = node::TableCell {
248 children: paragraph,
249 width,
250 };
251 row.children.push(table_cell);
252}
253
254/// Trim text but leave at least one space.
255///
256/// - Before: " \r\n Hello world \t "
257/// - After: " Hello world "
258#[allow(dead_code)]
259fn trim_text(text: &str) -> String {
260 let mut out = String::with_capacity(text.len());
261
262 for (i, c) in text.chars().enumerate() {
263 if c.is_whitespace() {
264 if i > 0 && out.ends_with(' ') {
265 continue;
266 }
267 }
268 out.push(c);
269 }
270
271 out
272}
273
274fn parse_paragraph(paragraph: &mut Paragraph, node: &Rc<Node>) {
275 fn push_merged(
276 paragraph: &mut Paragraph,
277 text: String,
278 marks: Vec<(Range<usize>, TextMark)>,
279 new_mark: Option<TextMark>,
280 ) {
281 if text.is_empty() {
282 return;
283 }
284 let mut node = InlineNode::new(text).marks(marks);
285 if let Some(new_mark) = new_mark {
286 let len = node.text.len();
287 if let Some(last) = node.marks.last_mut()
288 && last.0.start == 0
289 && last.0.end == len
290 {
291 last.1.merge(new_mark);
292 } else {
293 node.marks.push((0..node.text.len(), new_mark));
294 }
295 }
296 paragraph.push(node);
297 }
298
299 fn merge_children_with_mark(
300 node: &Node,
301 paragraph: &mut Paragraph,
302 new_mark: Option<TextMark>,
303 ) {
304 let mut merged_text = String::new();
305 let mut merged_marks = Vec::new();
306
307 for child in node.children.borrow().iter() {
308 let mut child_paragraph = Paragraph::default();
309 parse_paragraph(&mut child_paragraph, &child);
310
311 for node in child_paragraph.children {
312 let offset = merged_text.len();
313 merged_text.push_str(&node.text);
314 for (range, child_mark) in node.marks {
315 merged_marks.push((range.start + offset..range.end + offset, child_mark));
316 }
317
318 if let Some(mut image) = node.image {
319 if let Some(link_mark) = new_mark.as_ref().and_then(|mark| mark.link.clone()) {
320 image.link = Some(link_mark);
321 }
322
323 push_merged(
324 paragraph,
325 std::mem::take(&mut merged_text),
326 std::mem::take(&mut merged_marks),
327 new_mark.clone(),
328 );
329
330 paragraph.push(InlineNode::image(image));
331 }
332 }
333 }
334
335 push_merged(paragraph, merged_text, merged_marks, new_mark.clone());
336 }
337
338 match &node.data {
339 NodeData::Text { contents } => {
340 let part = &contents.borrow();
341 paragraph.push_str(&part);
342 }
343 NodeData::Element { name, attrs, .. } => match name.local {
344 local_name!("em") | local_name!("i") => {
345 merge_children_with_mark(node, paragraph, Some(TextMark::default().italic()));
346 }
347 local_name!("strong") | local_name!("b") => {
348 merge_children_with_mark(node, paragraph, Some(TextMark::default().bold()));
349 }
350 local_name!("del") | local_name!("s") => {
351 merge_children_with_mark(
352 node,
353 paragraph,
354 Some(TextMark::default().strikethrough()),
355 );
356 }
357 local_name!("u") => {
358 merge_children_with_mark(node, paragraph, Some(TextMark::default().underline()));
359 }
360 local_name!("code") => {
361 merge_children_with_mark(node, paragraph, Some(TextMark::default().code()));
362 }
363 local_name!("mark") => {
364 let color = mark_color(&attrs).unwrap_or_else(|| gpui::rgb(0xfef08a).into());
365 merge_children_with_mark(
366 node,
367 paragraph,
368 Some(TextMark::default().highlight(color)),
369 );
370 }
371 local_name!("a") => {
372 let link_mark = LinkMark {
373 url: attr_value(&attrs, local_name!("href"))
374 .unwrap_or_default()
375 .into(),
376 title: attr_value(&attrs, local_name!("title")).map(Into::into),
377 ..Default::default()
378 };
379
380 merge_children_with_mark(
381 node,
382 paragraph,
383 Some(TextMark::default().link(link_mark)),
384 );
385 }
386 local_name!("img") => {
387 let Some(src) = attr_value(attrs, local_name!("src")) else {
388 if cfg!(debug_assertions) {
389 tracing::warn!("Image node missing src attribute");
390 }
391 return;
392 };
393
394 let alt = attr_value(attrs, local_name!("alt"));
395 let title = attr_value(attrs, local_name!("title"));
396 let (width, height) = attr_width_height(attrs);
397
398 paragraph.push_image(ImageNode {
399 url: src.into(),
400 alt: alt.map(Into::into),
401 width,
402 height,
403 title: title.map(Into::into),
404 ..Default::default()
405 });
406 }
407 _ => {
408 merge_children_with_mark(node, paragraph, None);
409 }
410 },
411 _ => {
412 merge_children_with_mark(node, paragraph, None);
413 }
414 }
415}
416
417fn parse_node(
418 node: &Rc<Node>,
419 paragraph: &mut Paragraph,
420 cx: &mut NodeContext,
421) -> Option<BlockNode> {
422 match node.data {
423 NodeData::Text { ref contents } => {
424 let text = contents.borrow().to_string();
425 if text.len() > 0 {
426 paragraph.push_str(&text);
427 }
428
429 None
430 }
431 NodeData::Element {
432 ref name,
433 ref attrs,
434 ..
435 } => match name.local {
436 local_name!("br") => Some(BlockNode::Break {
437 html: true,
438 span: None,
439 }),
440 local_name!("h1")
441 | local_name!("h2")
442 | local_name!("h3")
443 | local_name!("h4")
444 | local_name!("h5")
445 | local_name!("h6") => {
446 let mut children = vec![];
447 consume_paragraph(&mut children, paragraph);
448
449 let level = name
450 .local
451 .chars()
452 .last()
453 .unwrap_or('6')
454 .to_digit(10)
455 .unwrap_or(6) as u8;
456
457 let mut paragraph = Paragraph::default();
458 for child in node.children.borrow().iter() {
459 parse_paragraph(&mut paragraph, child);
460 }
461
462 let heading = BlockNode::Heading {
463 level,
464 children: paragraph,
465 span: None,
466 };
467 if children.len() > 0 {
468 children.push(heading);
469
470 Some(BlockNode::Root {
471 children,
472 span: None,
473 })
474 } else {
475 Some(heading)
476 }
477 }
478 local_name!("img") => {
479 let mut children = vec![];
480 consume_paragraph(&mut children, paragraph);
481
482 let Some(src) = attr_value(attrs, local_name!("src")) else {
483 if cfg!(debug_assertions) {
484 tracing::warn!("image node missing src attribute");
485 }
486 return None;
487 };
488
489 let alt = attr_value(&attrs, local_name!("alt"));
490 let title = attr_value(&attrs, local_name!("title"));
491 let (width, height) = attr_width_height(&attrs);
492
493 let mut paragraph = Paragraph::default();
494 paragraph.push_image(ImageNode {
495 url: src.into(),
496 title: title.map(Into::into),
497 alt: alt.map(Into::into),
498 width,
499 height,
500 ..Default::default()
501 });
502
503 if children.len() > 0 {
504 children.push(BlockNode::Paragraph(paragraph));
505 Some(BlockNode::Root {
506 children,
507 span: None,
508 })
509 } else {
510 Some(BlockNode::Paragraph(paragraph))
511 }
512 }
513 local_name!("ul") | local_name!("ol") => {
514 let ordered = name.local == local_name!("ol");
515 let children = consume_children_nodes(node, paragraph, cx);
516 Some(BlockNode::List {
517 children,
518 ordered,
519 start: None,
520 span: None,
521 })
522 }
523 local_name!("li") => {
524 let mut children = vec![];
525 consume_paragraph(&mut children, paragraph);
526
527 for child in node.children.borrow().iter() {
528 let mut child_paragraph = Paragraph::default();
529 if let Some(child_node) = parse_node(child, &mut child_paragraph, cx) {
530 children.push(child_node);
531 }
532 if child_paragraph.text_len() > 0 {
533 // If last child is paragraph, merge child
534 if let Some(last_child) = children.last_mut() {
535 if let BlockNode::Paragraph(last_paragraph) = last_child {
536 last_paragraph.merge(child_paragraph);
537 continue;
538 }
539 }
540
541 children.push(BlockNode::Paragraph(child_paragraph));
542 }
543 }
544
545 consume_paragraph(&mut children, paragraph);
546
547 Some(BlockNode::ListItem {
548 children,
549 spread: false,
550 checked: None,
551 span: None,
552 })
553 }
554 local_name!("table") => {
555 let mut children = vec![];
556 consume_paragraph(&mut children, paragraph);
557
558 let mut table = Table::default();
559 for child in node.children.borrow().iter() {
560 match child.data {
561 NodeData::Element { ref name, .. }
562 if name.local == local_name!("tbody")
563 || name.local == local_name!("thead") =>
564 {
565 for sub_child in child.children.borrow().iter() {
566 parse_table_row(&mut table, &sub_child);
567 }
568 }
569 _ => {
570 parse_table_row(&mut table, &child);
571 }
572 }
573 }
574 consume_paragraph(&mut children, paragraph);
575
576 let table = BlockNode::Table(table);
577 if children.len() > 0 {
578 children.push(table);
579 Some(BlockNode::Root {
580 children,
581 span: None,
582 })
583 } else {
584 Some(table)
585 }
586 }
587 local_name!("blockquote") => {
588 let children = consume_children_nodes(node, paragraph, cx);
589 Some(BlockNode::Blockquote {
590 children,
591 span: None,
592 })
593 }
594 local_name!("style") | local_name!("script") => None,
595 _ => {
596 if BLOCK_ELEMENTS.contains(&name.local.trim()) {
597 let mut children: Vec<BlockNode> = vec![];
598
599 // Case:
600 //
601 // Hello <p>Inner text of block element</p> World
602
603 // Insert before text as a node -- The "Hello"
604 consume_paragraph(&mut children, paragraph);
605
606 // Inner of the block element -- The "Inner text of block element"
607 for child in node.children.borrow().iter() {
608 if let Some(child_node) = parse_node(child, paragraph, cx) {
609 children.push(child_node);
610 }
611 }
612 consume_paragraph(&mut children, paragraph);
613
614 if children.is_empty() {
615 None
616 } else {
617 Some(BlockNode::Root {
618 children,
619 span: None,
620 })
621 }
622 } else {
623 // Others to as Inline
624 parse_paragraph(paragraph, node);
625
626 if paragraph.is_image() {
627 Some(BlockNode::Paragraph(paragraph.take()))
628 } else {
629 None
630 }
631 }
632 }
633 },
634 NodeData::Document => {
635 let children = consume_children_nodes(node, paragraph, cx);
636 Some(BlockNode::Root {
637 children,
638 span: None,
639 })
640 }
641 NodeData::Doctype { .. }
642 | NodeData::Comment { .. }
643 | NodeData::ProcessingInstruction { .. } => None,
644 }
645}
646
647fn consume_children_nodes(
648 node: &Node,
649 paragraph: &mut Paragraph,
650 cx: &mut NodeContext,
651) -> Vec<BlockNode> {
652 let mut children = vec![];
653 consume_paragraph(&mut children, paragraph);
654 for child in node.children.borrow().iter() {
655 if let Some(child_node) = parse_node(child, paragraph, cx) {
656 children.push(child_node);
657 }
658 consume_paragraph(&mut children, paragraph);
659 }
660
661 children
662}
663
664fn consume_paragraph(children: &mut Vec<BlockNode>, paragraph: &mut Paragraph) {
665 if paragraph.is_empty() {
666 return;
667 }
668
669 children.push(BlockNode::Paragraph(paragraph.take()));
670}
671
672#[cfg(test)]
673mod tests {
674 use gpui::{px, relative};
675 use std::sync::Arc;
676
677 use crate::text::{
678 document::ParsedDocument,
679 node::{BlockNode, ImageNode, InlineNode, NodeContext, Paragraph},
680 };
681
682 use super::trim_text;
683
684 #[test]
685 fn test_cleanup_html() {
686 let html = r#"<p>
687 and
688 <code>code</code>
689 text
690 </p>"#;
691 let cleaned = super::cleanup_html(html);
692 assert_eq!(
693 String::from_utf8(cleaned).unwrap(),
694 "<p>and <code>code</code> text"
695 );
696
697 let html = r#"<p>
698 and
699 <em> <code>code</code> <i>italic</i> </em>
700 text
701 </p>"#;
702 let cleaned = super::cleanup_html(html);
703 assert_eq!(
704 String::from_utf8(cleaned).unwrap(),
705 "<p>and <em><code>code</code> <i>italic</i></em> text"
706 );
707 }
708
709 #[test]
710 fn test_trim_text() {
711 assert_eq!(trim_text(" \n\tHello world \t\r "), " Hello world ",);
712 }
713
714 #[test]
715 fn test_mark() {
716 let mut cx = NodeContext::default();
717
718 // `<mark>` is rendered as a highlight, kept as `==...==` in markdown.
719 let html = r#"<p>Hello <mark>world</mark></p>"#;
720 let node = super::parse(html, &mut cx).unwrap();
721 assert_eq!(node.to_markdown(), "Hello ==world==");
722
723 let html = r#"<p><mark color="blue">blue</mark> and <mark style="background-color: #336699">hex</mark></p>"#;
724 let node = super::parse(html, &mut cx).unwrap();
725 assert_eq!(node.to_markdown(), "==blue== and ==hex==");
726 }
727
728 #[test]
729 fn test_keep_spaces() {
730 let html = r#"<p>and <code>code</code> text</p>"#;
731 let mut cx = NodeContext::default();
732 let node = super::parse(html, &mut cx).unwrap();
733 assert_eq!(node.to_markdown(), "and `code` text");
734
735 let html = r#"
736 <div>
737 <p>
738 and
739 <em> <code>code</code> <i>italic</i> </em>
740 text
741 </p>
742 <p>
743 <img src="https://example.com/image.png" alt="Example" width="100" height="200" title="Example Image" />
744 </p>
745 <ul>
746 <li>Item 1</li>
747 <li>Item 2
748 </li>
749 </ul>
750 </div>
751 "#;
752 let node = super::parse(html, &mut cx).unwrap();
753 assert_eq!(
754 node.to_markdown(),
755 indoc::indoc! {r#"
756 and *code italic* text
757
758 ![Example](https://example.com/image.png "Example Image")
759
760 - Item 1
761 - Item 2
762 "#}
763 .trim()
764 );
765 }
766
767 #[test]
768 fn test_value_to_length() {
769 assert_eq!(super::value_to_length("100px"), Some(px(100.).into()));
770 assert_eq!(super::value_to_length("100%"), Some(relative(1.)));
771 assert_eq!(super::value_to_length("56%"), Some(relative(0.56)));
772 assert_eq!(super::value_to_length("240"), Some(px(240.).into()));
773 }
774
775 #[test]
776 fn test_image() {
777 let html = r#"<img src="https://example.com/image.png" alt="Example" width="100" height="200" title="Example Image" />"#;
778 let mut cx = NodeContext::default();
779 let node = super::parse(html, &mut cx).unwrap();
780 assert_eq!(
781 node,
782 ParsedDocument {
783 source: html.to_string().into(),
784 blocks: Arc::new(vec![BlockNode::Paragraph(Paragraph {
785 span: None,
786 children: vec![InlineNode::image(ImageNode {
787 url: "https://example.com/image.png".to_string().into(),
788 alt: Some("Example".to_string().into()),
789 width: Some(px(100.).into()),
790 height: Some(px(200.).into()),
791 title: Some("Example Image".to_string().into()),
792 ..Default::default()
793 })],
794 ..Default::default()
795 })])
796 }
797 );
798
799 let html = r#"<img src="https://example.com/image.png" alt="Example" style="width: 80%" title="Example Image" />"#;
800 let node = super::parse(html, &mut cx).unwrap();
801 assert_eq!(
802 node,
803 ParsedDocument {
804 source: html.to_string().into(),
805 blocks: Arc::new(vec![BlockNode::Paragraph(Paragraph {
806 span: None,
807 children: vec![InlineNode::image(ImageNode {
808 url: "https://example.com/image.png".to_string().into(),
809 alt: Some("Example".to_string().into()),
810 width: Some(relative(0.8)),
811 height: None,
812 title: Some("Example Image".to_string().into()),
813 ..Default::default()
814 })],
815 ..Default::default()
816 })])
817 }
818 );
819 }
820}