Skip to main content

fc_ui/capabilities/content/
html.rs

1#[cfg(feature = "html-render")]
2use html5ever::parse_document;
3#[cfg(feature = "html-render")]
4use html5ever::tendril::TendrilSink;
5#[cfg(feature = "html-render")]
6use markup5ever_rcdom::{Handle, NodeData, RcDom};
7
8use gpui::*;
9
10use std::rc::Rc;
11
12use crate::capabilities::content::rich_text::LinkClickHandler;
13#[cfg(feature = "html-render")]
14use crate::capabilities::content::rich_text::{
15    render_blocks, ListItem, RichBlock, RichInline, TableAlignment,
16};
17#[cfg(feature = "html-render")]
18use crate::capabilities::foundation::theme::use_theme;
19
20#[cfg(feature = "html-render")]
21static ALLOWED_TAGS: &[&str] = &[
22    "p",
23    "h1",
24    "h2",
25    "h3",
26    "h4",
27    "h5",
28    "h6",
29    "br",
30    "hr",
31    "strong",
32    "b",
33    "em",
34    "i",
35    "s",
36    "strike",
37    "del",
38    "code",
39    "pre",
40    "a",
41    "img",
42    "ul",
43    "ol",
44    "li",
45    "blockquote",
46    "table",
47    "thead",
48    "tbody",
49    "tr",
50    "th",
51    "td",
52    "span",
53    "div",
54];
55
56/// Renders trusted-or-untrusted HTML source as rich text blocks, limited to
57/// the whitelisted tags in `ALLOWED_TAGS`.
58///
59/// Input is rejected before parsing when it exceeds 4 MiB or nests deeper
60/// than 4096 elements: html5ever has no depth cap and degrades quadratically
61/// (servo/html5ever#788). Rejected input renders as empty and logs to stderr.
62#[derive(IntoElement)]
63pub struct Html {
64    base: Div,
65    source: SharedString,
66    base_font_size: Option<Pixels>,
67    on_link_click: Option<LinkClickHandler>,
68}
69
70impl Html {
71    pub fn new(source: impl Into<SharedString>) -> Self {
72        Self {
73            base: div(),
74            source: source.into(),
75            base_font_size: None,
76            on_link_click: None,
77        }
78    }
79
80    pub fn base_font_size(mut self, size: Pixels) -> Self {
81        self.base_font_size = Some(size);
82        self
83    }
84
85    pub fn on_link_click(
86        mut self,
87        handler: impl Fn(&str, &mut Window, &mut App) + 'static,
88    ) -> Self {
89        self.on_link_click = Some(Rc::new(handler));
90        self
91    }
92}
93
94/// Upper bound on element nesting depth. html5ever's tree builder grows
95/// quadratically with nesting depth and imposes no cap of its own, so a few
96/// hundred KB of nested markup can occupy the UI thread for seconds to minutes
97/// (servo/html5ever#788). Chromium and WebKit stop nesting at 512; this is
98/// deliberately more permissive while still bounding the work.
99#[cfg(feature = "html-render")]
100const MAX_NESTING_DEPTH: usize = 4096;
101
102/// Upper bound on input length. Depth is the dominant cost, but bounding length
103/// keeps a single pathological document from monopolizing the parse.
104#[cfg(feature = "html-render")]
105const MAX_SOURCE_LEN: usize = 4 * 1024 * 1024;
106
107/// Scan `source` without building a tree and report the deepest element nesting
108/// it reaches. Only tags are counted, so text containing `<` is not charged as
109/// markup. Unbalanced closing tags are ignored rather than treated as errors —
110/// html5ever tolerates them and the caller only needs a safe upper bound.
111/// Self-closing slashes count as opening tags: HTML5 ignores them outside
112/// foreign content, so `<div/>` realises as nesting in the parsed tree.
113#[cfg(feature = "html-render")]
114fn max_nesting_depth(source: &str) -> usize {
115    const VOID_ELEMENTS: &[&str] = &[
116        "area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param",
117        "source", "track", "wbr",
118    ];
119
120    let bytes = source.as_bytes();
121    let mut depth = 0usize;
122    let mut max_depth = 0usize;
123    let mut i = 0usize;
124
125    while i < bytes.len() {
126        if bytes[i] != b'<' {
127            i += 1;
128            continue;
129        }
130
131        // Skip comments and declarations wholesale.
132        if source[i..].starts_with("<!--") {
133            match source[i + 4..].find("-->") {
134                Some(offset) => {
135                    i += 4 + offset + 3;
136                    continue;
137                }
138                None => break,
139            }
140        }
141        if source[i..].starts_with("<!") || source[i..].starts_with("<?") {
142            match source[i..].find('>') {
143                Some(offset) => {
144                    i += offset + 1;
145                    continue;
146                }
147                None => break,
148            }
149        }
150
151        let closing = bytes.get(i + 1) == Some(&b'/');
152        let name_start = if closing { i + 2 } else { i + 1 };
153        let mut name_end = name_start;
154        while name_end < bytes.len()
155            && (bytes[name_end].is_ascii_alphanumeric() || bytes[name_end] == b'-')
156        {
157            name_end += 1;
158        }
159        if name_end == name_start {
160            // Not a tag after all (e.g. a bare `<`); move past it.
161            i += 1;
162            continue;
163        }
164        let name = source[name_start..name_end].to_ascii_lowercase();
165
166        let tag_end = match source[name_end..].find('>') {
167            Some(offset) => name_end + offset,
168            None => break,
169        };
170        if closing {
171            depth = depth.saturating_sub(1);
172        } else if !VOID_ELEMENTS.contains(&name.as_str()) {
173            // A trailing `/` does not exempt the tag: per HTML5, html5ever
174            // ignores the self-closing slash on non-void elements, so `<div/>`
175            // nests just like `<div>` and must be charged a level. Foreign
176            // content (SVG/MathML) self-closing tags are over-counted here,
177            // which fails safe.
178            depth += 1;
179            if depth > max_depth {
180                max_depth = depth;
181            }
182        }
183
184        i = tag_end + 1;
185    }
186
187    max_depth
188}
189
190#[cfg(feature = "html-render")]
191fn parse_html(source: &str) -> Vec<RichBlock> {
192    if source.len() > MAX_SOURCE_LEN || max_nesting_depth(source) > MAX_NESTING_DEPTH {
193        eprintln!(
194            "fc-ui: html-render refused to parse {} bytes with nesting deeper than {} \
195             (html5ever has no depth cap and degrades quadratically)",
196            source.len(),
197            MAX_NESTING_DEPTH
198        );
199        return Vec::new();
200    }
201
202    let wrapped = format!("<html><body>{}</body></html>", source);
203    let dom = parse_document(RcDom::default(), Default::default())
204        .from_utf8()
205        .read_from(&mut wrapped.as_bytes())
206        .expect("html parse");
207
208    let body = find_body(&dom.document);
209    match body {
210        Some(node) => walk_children_blocks(&node),
211        None => Vec::new(),
212    }
213}
214
215#[cfg(feature = "html-render")]
216fn find_body(node: &Handle) -> Option<Handle> {
217    match &node.data {
218        NodeData::Element { name, .. } if name.local.as_ref() == "body" => {
219            return Some(node.clone());
220        }
221        _ => {}
222    }
223    for child in node.children.borrow().iter() {
224        if let Some(found) = find_body(child) {
225            return Some(found);
226        }
227    }
228    None
229}
230
231#[cfg(feature = "html-render")]
232fn flush_inlines(pending: &mut Vec<RichInline>, blocks: &mut Vec<RichBlock>) {
233    if !pending.is_empty() {
234        let mut inlines = std::mem::take(pending);
235        collapse_boundary_spaces(&mut inlines);
236        trim_inlines(&mut inlines);
237        if !inlines.is_empty() {
238            blocks.push(RichBlock::Paragraph(inlines));
239        }
240    }
241}
242
243#[cfg(feature = "html-render")]
244fn walk_children_blocks(node: &Handle) -> Vec<RichBlock> {
245    let mut blocks = Vec::new();
246    let mut pending_inlines: Vec<RichInline> = Vec::new();
247
248    for child in node.children.borrow().iter() {
249        match &child.data {
250            NodeData::Element { name, .. } => {
251                let tag = name.local.as_ref();
252                if !is_allowed_tag(tag) {
253                    continue;
254                }
255                match tag {
256                    "p" | "div" => {
257                        flush_inlines(&mut pending_inlines, &mut blocks);
258                        let inlines = walk_block_inlines(child);
259                        if !inlines.is_empty() {
260                            blocks.push(RichBlock::Paragraph(inlines));
261                        }
262                    }
263                    "h1" | "h2" | "h3" | "h4" | "h5" | "h6" => {
264                        flush_inlines(&mut pending_inlines, &mut blocks);
265                        let level = tag.as_bytes()[1] - b'0';
266                        let inlines = walk_block_inlines(child);
267                        blocks.push(RichBlock::Heading {
268                            level,
269                            content: inlines,
270                        });
271                    }
272                    "pre" => {
273                        flush_inlines(&mut pending_inlines, &mut blocks);
274                        let (lang, code) = extract_code_block(child);
275                        blocks.push(RichBlock::CodeBlock {
276                            language: lang,
277                            code,
278                        });
279                    }
280                    "blockquote" => {
281                        flush_inlines(&mut pending_inlines, &mut blocks);
282                        let inner = walk_children_blocks(child);
283                        blocks.push(RichBlock::BlockQuote(inner));
284                    }
285                    "ul" => {
286                        flush_inlines(&mut pending_inlines, &mut blocks);
287                        let items = walk_list_items(child);
288                        blocks.push(RichBlock::UnorderedList { items });
289                    }
290                    "ol" => {
291                        flush_inlines(&mut pending_inlines, &mut blocks);
292                        let start = get_attr(child, "start")
293                            .and_then(|s| s.parse::<u64>().ok())
294                            .unwrap_or(1);
295                        let items = walk_list_items(child);
296                        blocks.push(RichBlock::OrderedList { start, items });
297                    }
298                    "hr" => {
299                        flush_inlines(&mut pending_inlines, &mut blocks);
300                        blocks.push(RichBlock::HorizontalRule);
301                    }
302                    "table" => {
303                        flush_inlines(&mut pending_inlines, &mut blocks);
304                        let table = walk_table(child);
305                        blocks.push(table);
306                    }
307                    "img" => {
308                        flush_inlines(&mut pending_inlines, &mut blocks);
309                        let src = get_attr(child, "src").unwrap_or_default();
310                        let alt = get_attr(child, "alt").unwrap_or_default();
311                        blocks.push(RichBlock::Image { alt, url: src });
312                    }
313                    _ => {
314                        let inlines = walk_children_inlines(child);
315                        pending_inlines.extend(inlines);
316                    }
317                }
318            }
319            NodeData::Text { contents } => {
320                let text = collapse_html_whitespace(&contents.borrow());
321                if !text.trim().is_empty() {
322                    pending_inlines.push(RichInline::Text(text));
323                }
324            }
325            _ => {}
326        }
327    }
328
329    flush_inlines(&mut pending_inlines, &mut blocks);
330    blocks
331}
332
333#[cfg(feature = "html-render")]
334fn walk_children_inlines(node: &Handle) -> Vec<RichInline> {
335    let mut inlines = Vec::new();
336
337    for child in node.children.borrow().iter() {
338        match &child.data {
339            NodeData::Text { contents } => {
340                let text = collapse_html_whitespace(&contents.borrow());
341                if !text.is_empty() {
342                    inlines.push(RichInline::Text(text));
343                }
344            }
345            NodeData::Element { name, attrs: _, .. } => {
346                let tag = name.local.as_ref();
347                if !is_allowed_tag(tag) {
348                    continue;
349                }
350                match tag {
351                    "strong" | "b" => {
352                        let children = walk_children_inlines(child);
353                        inlines.push(RichInline::Bold(children));
354                    }
355                    "em" | "i" => {
356                        let children = walk_children_inlines(child);
357                        inlines.push(RichInline::Italic(children));
358                    }
359                    "s" | "strike" | "del" => {
360                        let children = walk_children_inlines(child);
361                        inlines.push(RichInline::Strikethrough(children));
362                    }
363                    "code" => {
364                        let text = collect_text(child);
365                        inlines.push(RichInline::Code(text));
366                    }
367                    "a" => {
368                        let href = get_attr(child, "href").unwrap_or_default();
369                        let children = walk_children_inlines(child);
370                        inlines.push(RichInline::Link {
371                            text: children,
372                            url: href,
373                        });
374                    }
375                    "br" => {
376                        inlines.push(RichInline::LineBreak);
377                    }
378                    "img" => {
379                        let src = get_attr(child, "src").unwrap_or_default();
380                        let alt = get_attr(child, "alt").unwrap_or_default();
381                        inlines.push(RichInline::Image { alt, url: src });
382                    }
383                    "span" | "div" => {
384                        let children = walk_children_inlines(child);
385                        let style_attr = get_attr(child, "style");
386                        if let Some(style_str) = style_attr {
387                            let parsed = parse_inline_style(&style_str);
388                            if parsed.has_any() {
389                                inlines.push(RichInline::Styled {
390                                    children,
391                                    color: parsed.color,
392                                    background_color: parsed.background_color,
393                                    bold: parsed.bold,
394                                    italic: parsed.italic,
395                                    font_size: parsed.font_size,
396                                });
397                            } else {
398                                inlines.extend(children);
399                            }
400                        } else {
401                            inlines.extend(children);
402                        }
403                    }
404                    "ul" | "ol" => {}
405                    _ => {
406                        let children = walk_children_inlines(child);
407                        inlines.extend(children);
408                    }
409                }
410            }
411            _ => {}
412        }
413    }
414
415    collapse_boundary_spaces(&mut inlines);
416    inlines
417}
418
419#[cfg(feature = "html-render")]
420fn walk_block_inlines(node: &Handle) -> Vec<RichInline> {
421    let mut inlines = walk_children_inlines(node);
422    trim_inlines(&mut inlines);
423    inlines
424}
425
426#[cfg(feature = "html-render")]
427fn collapse_html_whitespace(text: &str) -> String {
428    let mut out = String::with_capacity(text.len());
429    let mut in_whitespace = false;
430    for ch in text.chars() {
431        if ch.is_whitespace() {
432            if !in_whitespace {
433                out.push(' ');
434                in_whitespace = true;
435            }
436        } else {
437            out.push(ch);
438            in_whitespace = false;
439        }
440    }
441    out
442}
443
444#[cfg(feature = "html-render")]
445fn starts_with_space(inline: &RichInline) -> bool {
446    match inline {
447        RichInline::Text(s) => s.starts_with(' '),
448        RichInline::Bold(children)
449        | RichInline::Italic(children)
450        | RichInline::Strikethrough(children) => children.first().is_some_and(starts_with_space),
451        RichInline::Link { text, .. } => text.first().is_some_and(starts_with_space),
452        RichInline::Styled { children, .. } => children.first().is_some_and(starts_with_space),
453        _ => false,
454    }
455}
456
457#[cfg(feature = "html-render")]
458fn ends_with_space(inline: &RichInline) -> bool {
459    match inline {
460        RichInline::Text(s) => s.ends_with(' '),
461        RichInline::Bold(children)
462        | RichInline::Italic(children)
463        | RichInline::Strikethrough(children) => children.last().is_some_and(ends_with_space),
464        RichInline::Link { text, .. } => text.last().is_some_and(ends_with_space),
465        RichInline::Styled { children, .. } => children.last().is_some_and(ends_with_space),
466        _ => false,
467    }
468}
469
470#[cfg(feature = "html-render")]
471fn strip_leading_space(inline: &mut RichInline) {
472    match inline {
473        RichInline::Text(s) => {
474            *s = s.trim_start().to_string();
475        }
476        RichInline::Bold(children)
477        | RichInline::Italic(children)
478        | RichInline::Strikethrough(children) => {
479            if let Some(first) = children.first_mut() {
480                strip_leading_space(first);
481            }
482        }
483        RichInline::Link { text, .. } => {
484            if let Some(first) = text.first_mut() {
485                strip_leading_space(first);
486            }
487        }
488        RichInline::Styled { children, .. } => {
489            if let Some(first) = children.first_mut() {
490                strip_leading_space(first);
491            }
492        }
493        _ => {}
494    }
495}
496
497#[cfg(feature = "html-render")]
498fn strip_trailing_space(inline: &mut RichInline) {
499    match inline {
500        RichInline::Text(s) => {
501            *s = s.trim_end().to_string();
502        }
503        RichInline::Bold(children)
504        | RichInline::Italic(children)
505        | RichInline::Strikethrough(children) => {
506            if let Some(last) = children.last_mut() {
507                strip_trailing_space(last);
508            }
509        }
510        RichInline::Link { text, .. } => {
511            if let Some(last) = text.last_mut() {
512                strip_trailing_space(last);
513            }
514        }
515        RichInline::Styled { children, .. } => {
516            if let Some(last) = children.last_mut() {
517                strip_trailing_space(last);
518            }
519        }
520        _ => {}
521    }
522}
523
524#[cfg(feature = "html-render")]
525fn is_empty_text(inline: &RichInline) -> bool {
526    matches!(inline, RichInline::Text(s) if s.is_empty())
527}
528
529#[cfg(feature = "html-render")]
530fn collapse_boundary_spaces(inlines: &mut Vec<RichInline>) {
531    let mut after_space = false;
532    let mut i = 0;
533    while i < inlines.len() {
534        if after_space && starts_with_space(&inlines[i]) {
535            strip_leading_space(&mut inlines[i]);
536            if is_empty_text(&inlines[i]) {
537                inlines.remove(i);
538                continue;
539            }
540        }
541        after_space = ends_with_space(&inlines[i]);
542        i += 1;
543    }
544}
545
546#[cfg(feature = "html-render")]
547fn trim_inlines(inlines: &mut Vec<RichInline>) {
548    loop {
549        match inlines.first() {
550            Some(first) if starts_with_space(first) => {
551                strip_leading_space(&mut inlines[0]);
552                if is_empty_text(&inlines[0]) {
553                    inlines.remove(0);
554                } else {
555                    break;
556                }
557            }
558            _ => break,
559        }
560    }
561    loop {
562        match inlines.last() {
563            Some(last) if ends_with_space(last) => {
564                let idx = inlines.len() - 1;
565                strip_trailing_space(&mut inlines[idx]);
566                if is_empty_text(&inlines[idx]) {
567                    inlines.pop();
568                } else {
569                    break;
570                }
571            }
572            _ => break,
573        }
574    }
575}
576
577#[cfg(feature = "html-render")]
578fn extract_code_block(pre_node: &Handle) -> (Option<String>, String) {
579    for child in pre_node.children.borrow().iter() {
580        if let NodeData::Element { name, .. } = &child.data {
581            if name.local.as_ref() == "code" {
582                let lang = get_attr(child, "class").and_then(|cls| {
583                    cls.strip_prefix("language-")
584                        .map(|l| l.to_string())
585                        .or_else(|| cls.strip_prefix("lang-").map(|l| l.to_string()))
586                });
587                let code = collect_text(child);
588                return (lang, code);
589            }
590        }
591    }
592    (None, collect_text(pre_node))
593}
594
595#[cfg(feature = "html-render")]
596fn walk_list_items(node: &Handle) -> Vec<ListItem> {
597    let mut items = Vec::new();
598
599    for child in node.children.borrow().iter() {
600        if let NodeData::Element { name, .. } = &child.data {
601            if name.local.as_ref() == "li" {
602                let inlines = walk_block_inlines(child);
603                let mut sub_items = Vec::new();
604
605                for sub in child.children.borrow().iter() {
606                    if let NodeData::Element { name: sub_name, .. } = &sub.data {
607                        let sub_tag = sub_name.local.as_ref();
608                        if sub_tag == "ul" || sub_tag == "ol" {
609                            sub_items = walk_list_items(sub);
610                        }
611                    }
612                }
613
614                items.push(ListItem {
615                    checked: None,
616                    content: inlines,
617                    children: sub_items,
618                });
619            }
620        }
621    }
622
623    items
624}
625
626#[cfg(feature = "html-render")]
627fn walk_table(node: &Handle) -> RichBlock {
628    let mut headers: Vec<Vec<RichInline>> = Vec::new();
629    let mut rows: Vec<Vec<Vec<RichInline>>> = Vec::new();
630    let mut alignments: Vec<TableAlignment> = Vec::new();
631
632    for child in node.children.borrow().iter() {
633        if let NodeData::Element { name, .. } = &child.data {
634            match name.local.as_ref() {
635                "thead" => {
636                    for tr in child.children.borrow().iter() {
637                        if let NodeData::Element { name: tr_name, .. } = &tr.data {
638                            if tr_name.local.as_ref() == "tr" {
639                                headers = walk_table_cells(tr, &mut alignments, true);
640                            }
641                        }
642                    }
643                }
644                "tbody" => {
645                    for tr in child.children.borrow().iter() {
646                        if let NodeData::Element { name: tr_name, .. } = &tr.data {
647                            if tr_name.local.as_ref() == "tr" {
648                                let mut dummy = Vec::new();
649                                let row = walk_table_cells(tr, &mut dummy, false);
650                                rows.push(row);
651                            }
652                        }
653                    }
654                }
655                "tr" => {
656                    if headers.is_empty() {
657                        headers = walk_table_cells(child, &mut alignments, true);
658                    } else {
659                        let mut dummy = Vec::new();
660                        let row = walk_table_cells(child, &mut dummy, false);
661                        rows.push(row);
662                    }
663                }
664                _ => {}
665            }
666        }
667    }
668
669    RichBlock::Table {
670        headers,
671        alignments,
672        rows,
673    }
674}
675
676#[cfg(feature = "html-render")]
677fn walk_table_cells(
678    tr: &Handle,
679    alignments: &mut Vec<TableAlignment>,
680    is_header: bool,
681) -> Vec<Vec<RichInline>> {
682    let mut cells = Vec::new();
683
684    for child in tr.children.borrow().iter() {
685        if let NodeData::Element { name, .. } = &child.data {
686            let tag = name.local.as_ref();
687            if tag == "th" || tag == "td" {
688                let inlines = walk_block_inlines(child);
689                cells.push(inlines);
690
691                if is_header {
692                    let align = get_attr(child, "align")
693                        .map(|a| match a.as_str() {
694                            "center" => TableAlignment::Center,
695                            "right" => TableAlignment::Right,
696                            _ => TableAlignment::Left,
697                        })
698                        .unwrap_or(TableAlignment::Left);
699                    alignments.push(align);
700                }
701            }
702        }
703    }
704
705    cells
706}
707
708#[cfg(feature = "html-render")]
709fn collect_text(node: &Handle) -> String {
710    let mut out = String::new();
711    collect_text_recursive(node, &mut out);
712    out
713}
714
715#[cfg(feature = "html-render")]
716fn collect_text_recursive(node: &Handle, out: &mut String) {
717    match &node.data {
718        NodeData::Text { contents } => {
719            out.push_str(&contents.borrow());
720        }
721        _ => {
722            for child in node.children.borrow().iter() {
723                collect_text_recursive(child, out);
724            }
725        }
726    }
727}
728
729#[cfg(feature = "html-render")]
730fn get_attr(node: &Handle, attr_name: &str) -> Option<String> {
731    if let NodeData::Element { attrs, .. } = &node.data {
732        for attr in attrs.borrow().iter() {
733            if attr.name.local.as_ref() == attr_name {
734                return Some(attr.value.to_string());
735            }
736        }
737    }
738    None
739}
740
741#[cfg(feature = "html-render")]
742fn is_allowed_tag(tag: &str) -> bool {
743    ALLOWED_TAGS.contains(&tag)
744}
745
746#[cfg(feature = "html-render")]
747struct InlineStyle {
748    color: Option<Hsla>,
749    background_color: Option<Hsla>,
750    bold: Option<bool>,
751    italic: Option<bool>,
752    font_size: Option<f32>,
753}
754
755#[cfg(feature = "html-render")]
756impl InlineStyle {
757    fn has_any(&self) -> bool {
758        self.color.is_some()
759            || self.background_color.is_some()
760            || self.bold.is_some()
761            || self.italic.is_some()
762            || self.font_size.is_some()
763    }
764}
765
766#[cfg(feature = "html-render")]
767fn parse_inline_style(style: &str) -> InlineStyle {
768    let mut result = InlineStyle {
769        color: None,
770        background_color: None,
771        bold: None,
772        italic: None,
773        font_size: None,
774    };
775
776    for declaration in style.split(';') {
777        let declaration = declaration.trim();
778        if declaration.is_empty() {
779            continue;
780        }
781        if let Some((prop, value)) = declaration.split_once(':') {
782            let prop = prop.trim().to_lowercase();
783            let value = value.trim();
784
785            match prop.as_str() {
786                "color" => {
787                    result.color = parse_css_color(value);
788                }
789                "background-color" | "background" => {
790                    result.background_color = parse_css_color(value);
791                }
792                "font-weight" => match value {
793                    "bold" | "700" | "800" | "900" => result.bold = Some(true),
794                    "normal" | "400" => result.bold = Some(false),
795                    _ => {}
796                },
797                "font-style" => match value {
798                    "italic" | "oblique" => result.italic = Some(true),
799                    "normal" => result.italic = Some(false),
800                    _ => {}
801                },
802                "font-size" => {
803                    if let Some(stripped) = value.strip_suffix("px") {
804                        if let Ok(size) = stripped.trim().parse::<f32>() {
805                            result.font_size = Some(size);
806                        }
807                    } else if let Some(stripped) = value.strip_suffix("em") {
808                        if let Ok(size) = stripped.trim().parse::<f32>() {
809                            result.font_size = Some(size * 14.0);
810                        }
811                    }
812                }
813                _ => {}
814            }
815        }
816    }
817
818    result
819}
820
821#[cfg(feature = "html-render")]
822fn parse_css_color(value: &str) -> Option<Hsla> {
823    let value = value.trim();
824
825    if let Some(hex) = value.strip_prefix('#') {
826        return parse_hex_color(hex);
827    }
828
829    if let Some(inner) = value
830        .strip_prefix("rgb(")
831        .or_else(|| value.strip_prefix("RGB("))
832        .and_then(|s| s.strip_suffix(')'))
833    {
834        let parts: Vec<&str> = inner.split(',').collect();
835        if parts.len() == 3 {
836            let r = parts[0].trim().parse::<u8>().ok()?;
837            let g = parts[1].trim().parse::<u8>().ok()?;
838            let b = parts[2].trim().parse::<u8>().ok()?;
839            return Some(rgb_to_hsla(r, g, b, 1.0));
840        }
841    }
842
843    if let Some(inner) = value
844        .strip_prefix("rgba(")
845        .or_else(|| value.strip_prefix("RGBA("))
846        .and_then(|s| s.strip_suffix(')'))
847    {
848        let parts: Vec<&str> = inner.split(',').collect();
849        if parts.len() == 4 {
850            let r = parts[0].trim().parse::<u8>().ok()?;
851            let g = parts[1].trim().parse::<u8>().ok()?;
852            let b = parts[2].trim().parse::<u8>().ok()?;
853            let a = parts[3].trim().parse::<f32>().ok()?;
854            return Some(rgb_to_hsla(r, g, b, a));
855        }
856    }
857
858    match value.to_lowercase().as_str() {
859        "red" => Some(rgb_to_hsla(255, 0, 0, 1.0)),
860        "green" => Some(rgb_to_hsla(0, 128, 0, 1.0)),
861        "blue" => Some(rgb_to_hsla(0, 0, 255, 1.0)),
862        "yellow" => Some(rgb_to_hsla(255, 255, 0, 1.0)),
863        "orange" => Some(rgb_to_hsla(255, 165, 0, 1.0)),
864        "purple" => Some(rgb_to_hsla(128, 0, 128, 1.0)),
865        "white" => Some(rgb_to_hsla(255, 255, 255, 1.0)),
866        "black" => Some(rgb_to_hsla(0, 0, 0, 1.0)),
867        "gray" | "grey" => Some(rgb_to_hsla(128, 128, 128, 1.0)),
868        "cyan" => Some(rgb_to_hsla(0, 255, 255, 1.0)),
869        "magenta" => Some(rgb_to_hsla(255, 0, 255, 1.0)),
870        "pink" => Some(rgb_to_hsla(255, 192, 203, 1.0)),
871        "brown" => Some(rgb_to_hsla(165, 42, 42, 1.0)),
872        "coral" => Some(rgb_to_hsla(255, 127, 80, 1.0)),
873        "teal" => Some(rgb_to_hsla(0, 128, 128, 1.0)),
874        "navy" => Some(rgb_to_hsla(0, 0, 128, 1.0)),
875        "maroon" => Some(rgb_to_hsla(128, 0, 0, 1.0)),
876        "lime" => Some(rgb_to_hsla(0, 255, 0, 1.0)),
877        "olive" => Some(rgb_to_hsla(128, 128, 0, 1.0)),
878        "silver" => Some(rgb_to_hsla(192, 192, 192, 1.0)),
879        "gold" => Some(rgb_to_hsla(255, 215, 0, 1.0)),
880        _ => None,
881    }
882}
883
884#[cfg(feature = "html-render")]
885fn parse_hex_color(hex: &str) -> Option<Hsla> {
886    match hex.len() {
887        3 => {
888            let r = u8::from_str_radix(&hex[0..1].repeat(2), 16).ok()?;
889            let g = u8::from_str_radix(&hex[1..2].repeat(2), 16).ok()?;
890            let b = u8::from_str_radix(&hex[2..3].repeat(2), 16).ok()?;
891            Some(rgb_to_hsla(r, g, b, 1.0))
892        }
893        6 => {
894            let r = u8::from_str_radix(&hex[0..2], 16).ok()?;
895            let g = u8::from_str_radix(&hex[2..4], 16).ok()?;
896            let b = u8::from_str_radix(&hex[4..6], 16).ok()?;
897            Some(rgb_to_hsla(r, g, b, 1.0))
898        }
899        8 => {
900            let r = u8::from_str_radix(&hex[0..2], 16).ok()?;
901            let g = u8::from_str_radix(&hex[2..4], 16).ok()?;
902            let b = u8::from_str_radix(&hex[4..6], 16).ok()?;
903            let a = u8::from_str_radix(&hex[6..8], 16).ok()?;
904            Some(rgb_to_hsla(r, g, b, a as f32 / 255.0))
905        }
906        _ => None,
907    }
908}
909
910#[cfg(feature = "html-render")]
911fn rgb_to_hsla(r: u8, g: u8, b: u8, a: f32) -> Hsla {
912    let rf = r as f32 / 255.0;
913    let gf = g as f32 / 255.0;
914    let bf = b as f32 / 255.0;
915
916    let max = rf.max(gf).max(bf);
917    let min = rf.min(gf).min(bf);
918    let delta = max - min;
919
920    let lightness = (max + min) / 2.0;
921
922    if delta < f32::EPSILON {
923        return hsla(0.0, 0.0, lightness, a);
924    }
925
926    let saturation = if lightness <= 0.5 {
927        delta / (max + min)
928    } else {
929        delta / (2.0 - max - min)
930    };
931
932    let hue = if (max - rf).abs() < f32::EPSILON {
933        ((gf - bf) / delta + if gf < bf { 6.0 } else { 0.0 }) / 6.0
934    } else if (max - gf).abs() < f32::EPSILON {
935        ((bf - rf) / delta + 2.0) / 6.0
936    } else {
937        ((rf - gf) / delta + 4.0) / 6.0
938    };
939
940    hsla(hue, saturation, lightness, a)
941}
942
943#[cfg(feature = "html-render")]
944impl RenderOnce for Html {
945    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
946        let theme = use_theme(cx);
947        let base_size = self.base_font_size.unwrap_or(px(14.0));
948
949        let blocks = parse_html(&self.source);
950        let elements = render_blocks(&blocks, base_size, &self.on_link_click, "html", cx);
951
952        self.base
953            .flex()
954            .flex_col()
955            .font_family(theme.tokens.font_family.clone())
956            .text_color(theme.tokens.foreground)
957            .children(elements)
958    }
959}
960
961#[cfg(not(feature = "html-render"))]
962impl RenderOnce for Html {
963    fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement {
964        let _ = &self.source;
965        self.base
966            .child("Enable the 'html-render' feature to render HTML content.")
967    }
968}
969
970impl Styled for Html {
971    fn style(&mut self) -> &mut StyleRefinement {
972        self.base.style()
973    }
974}
975
976#[cfg(all(test, feature = "html-render"))]
977mod tests {
978    use super::{max_nesting_depth, parse_html, Html, MAX_NESTING_DEPTH};
979    use gpui::{
980        point, px, Context, IntoElement, Modifiers, MouseButton, Render, TestAppContext, Window,
981    };
982    use std::{cell::Cell, rc::Rc};
983
984    struct HtmlLinkTestView {
985        calls: Rc<Cell<usize>>,
986    }
987
988    impl Render for HtmlLinkTestView {
989        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
990            let calls = self.calls.clone();
991            Html::new("<p><a href=\"https://example.com\">link</a></p>").on_link_click(
992                move |url, _, _| {
993                    assert_eq!(url, "https://example.com");
994                    calls.set(calls.get() + 1);
995                },
996            )
997        }
998    }
999
1000    #[gpui::test]
1001    fn clicking_an_html_link_invokes_the_custom_handler(cx: &mut TestAppContext) {
1002        let calls = Rc::new(Cell::new(0));
1003        let (_, cx) = cx.add_window_view(|_, _| HtmlLinkTestView {
1004            calls: calls.clone(),
1005        });
1006
1007        cx.update(|window, cx| window.draw(cx).clear());
1008        let link_bounds = cx
1009            .debug_bounds("rich-text-link")
1010            .expect("HTML link should have rendered bounds");
1011        let link_position = point(
1012            link_bounds.origin.x + px(2.0),
1013            link_bounds.origin.y + px(8.0),
1014        );
1015        cx.simulate_mouse_move(link_position, None, Modifiers::none());
1016        cx.simulate_mouse_down(link_position, MouseButton::Left, Modifiers::none());
1017        cx.update(|window, cx| window.draw(cx).clear());
1018        cx.simulate_mouse_up(link_position, MouseButton::Left, Modifiers::none());
1019
1020        assert_eq!(calls.get(), 1);
1021    }
1022
1023    #[test]
1024    fn nested_list_text_is_not_duplicated_in_parent_item() {
1025        use super::parse_html;
1026        use crate::capabilities::content::rich_text::{RichBlock, RichInline};
1027
1028        let blocks = parse_html("<ul><li>a\n  <ul><li>b</li></ul>\n</li></ul>");
1029        assert_eq!(blocks.len(), 1);
1030        match &blocks[0] {
1031            RichBlock::UnorderedList { items } => {
1032                assert_eq!(items.len(), 1);
1033                assert_eq!(items[0].content.len(), 1);
1034                assert!(matches!(&items[0].content[0], RichInline::Text(t) if t == "a"));
1035                assert_eq!(items[0].children.len(), 1);
1036                assert!(
1037                    matches!(&items[0].children[0].content[0], RichInline::Text(t) if t == "b")
1038                );
1039            }
1040            other => panic!("expected unordered list, got {:?}", other),
1041        }
1042    }
1043
1044    #[test]
1045    fn inline_whitespace_collapses_and_trims_at_block_edges() {
1046        use super::parse_html;
1047        use crate::capabilities::content::rich_text::{RichBlock, RichInline};
1048
1049        let blocks = parse_html("<p>\n  hello\n   <strong>world</strong>\n</p>");
1050        assert_eq!(blocks.len(), 1);
1051        match &blocks[0] {
1052            RichBlock::Paragraph(inlines) => {
1053                assert_eq!(inlines.len(), 2);
1054                assert!(matches!(&inlines[0], RichInline::Text(t) if t == "hello "));
1055                assert!(
1056                    matches!(&inlines[1], RichInline::Bold(children) if children.len() == 1 && matches!(&children[0], RichInline::Text(t) if t == "world"))
1057                );
1058            }
1059            other => panic!("expected paragraph, got {:?}", other),
1060        }
1061    }
1062
1063    #[test]
1064    fn nesting_depth_counts_only_open_elements() {
1065        assert_eq!(max_nesting_depth("plain text"), 0);
1066        assert_eq!(max_nesting_depth("<p>hello</p>"), 1);
1067        assert_eq!(max_nesting_depth("<div><p><strong>x</strong></p></div>"), 3);
1068        // Void elements do not open a level.
1069        assert_eq!(max_nesting_depth("<p><br><hr><img src=\"x\"></p>"), 1);
1070        // Self-closing slashes on non-void elements still open a level:
1071        // html5ever ignores the slash (HTML5), so these nest in the real tree.
1072        assert_eq!(max_nesting_depth("<p><span/></p>"), 2);
1073        assert_eq!(max_nesting_depth(&"<div/>".repeat(10)), 10);
1074        // Comments and declarations are skipped, including markup inside them.
1075        assert_eq!(max_nesting_depth("<!-- <div><div><div> --><p>x</p>"), 1);
1076        assert_eq!(max_nesting_depth("<!DOCTYPE html><p>x</p>"), 1);
1077        // Sibling elements do not accumulate depth.
1078        assert_eq!(max_nesting_depth("<p>a</p><p>b</p><p>c</p>"), 1);
1079        // A bare `<` in text is not a tag.
1080        assert_eq!(max_nesting_depth("1 < 2 and 3 < 4"), 0);
1081        // Unbalanced closing tags saturate rather than underflow.
1082        assert_eq!(max_nesting_depth("</div></div><p>x</p>"), 1);
1083    }
1084
1085    #[test]
1086    fn deeply_nested_input_is_refused_instead_of_parsed() {
1087        let depth = MAX_NESTING_DEPTH + 1;
1088        let deep = format!("{}x{}", "<div>".repeat(depth), "</div>".repeat(depth));
1089        assert!(max_nesting_depth(&deep) > MAX_NESTING_DEPTH);
1090        assert!(parse_html(&deep).is_empty());
1091    }
1092
1093    #[test]
1094    fn self_closing_chains_are_refused_like_explicit_nesting() {
1095        // html5ever ignores the slash on non-void elements, so `<div/>` nests.
1096        let deep = "<div/>".repeat(MAX_NESTING_DEPTH + 1);
1097        assert!(max_nesting_depth(&deep) > MAX_NESTING_DEPTH);
1098        assert!(parse_html(&deep).is_empty());
1099    }
1100
1101    #[test]
1102    fn nesting_within_the_limit_still_parses() {
1103        let depth = 64;
1104        let nested = format!("{}x{}", "<div>".repeat(depth), "</div>".repeat(depth));
1105        assert_eq!(max_nesting_depth(&nested), depth);
1106        assert!(!parse_html(&nested).is_empty());
1107    }
1108}