|
| 1 | +use cosmic::{ |
| 2 | + cosmic_theme, |
| 3 | + iced::{ |
| 4 | + Font, |
| 5 | + font::{Style, Weight}, |
| 6 | + }, |
| 7 | + iced_core::text::Span, |
| 8 | +}; |
| 9 | + |
| 10 | +// Handle break lines, etc. in the future |
| 11 | +// Used only in `parse_html` function |
| 12 | +fn _prepare_html(text: &str) -> String { |
| 13 | + let text = text |
| 14 | + // handle break lines |
| 15 | + .replace("<br>", "\n") |
| 16 | + .replace("<br/>", "\n") |
| 17 | + .replace("<br />", "\n"); |
| 18 | + |
| 19 | + text.to_owned() |
| 20 | +} |
| 21 | + |
| 22 | +// Sanitize only tags allowed by Freedesktop Notification Specifications |
| 23 | +// https://specifications.freedesktop.org/notification/1.2/markup.html |
| 24 | +// TODO: impl <img> tag handling |
| 25 | +fn sanitize_html(tags: &[String], content: &str) -> Span<'static> { |
| 26 | + let mut font = Font::default(); |
| 27 | + let mut span = Span::new(content.to_owned()); |
| 28 | + |
| 29 | + for tag in tags { |
| 30 | + match tag.as_str() { |
| 31 | + "b" => font.weight = Weight::Bold, |
| 32 | + "i" => font.style = Style::Italic, |
| 33 | + "u" => span = span.underline(true), |
| 34 | + "a" => { |
| 35 | + let theme = cosmic_theme::Theme::preferred_theme(); |
| 36 | + span = span.underline(true).color(theme.accent_text_color()); |
| 37 | + } |
| 38 | + _ => {} |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + span.font(font) |
| 43 | +} |
| 44 | + |
| 45 | +fn _handle_recursive( |
| 46 | + handle: &tl::NodeHandle, |
| 47 | + parser: &tl::Parser, |
| 48 | + tags: &mut Vec<String>, |
| 49 | + buffer: &mut Vec<Span<'static>>, |
| 50 | +) { |
| 51 | + if let Some(node) = handle.get(parser) { |
| 52 | + match node { |
| 53 | + tl::Node::Tag(tag) => { |
| 54 | + let tag_name = tag.name().as_utf8_str(); |
| 55 | + tags.push(tag_name.into_owned()); |
| 56 | + |
| 57 | + tag.children().top().iter().for_each(|t| { |
| 58 | + _handle_recursive(t, parser, tags, buffer); |
| 59 | + }); |
| 60 | + |
| 61 | + tags.pop(); |
| 62 | + } |
| 63 | + tl::Node::Raw(bytes) => { |
| 64 | + buffer.push(sanitize_html(tags, &bytes.as_utf8_str())); |
| 65 | + } |
| 66 | + _ => {} |
| 67 | + } |
| 68 | + } |
| 69 | +} |
| 70 | + |
| 71 | +pub fn html_to_spans(text: &str) -> Vec<Span<'static>> { |
| 72 | + let mut buffer = Vec::new(); |
| 73 | + let html = _prepare_html(text); |
| 74 | + let dom = tl::parse(&html, tl::ParserOptions::default()); |
| 75 | + |
| 76 | + if let Ok(vdom) = dom { |
| 77 | + let parser = vdom.parser(); |
| 78 | + let elements = vdom.children(); |
| 79 | + let mut tags = Vec::new(); |
| 80 | + |
| 81 | + for node_handle in elements { |
| 82 | + _handle_recursive(node_handle, parser, &mut tags, &mut buffer); |
| 83 | + } |
| 84 | + } |
| 85 | + |
| 86 | + buffer |
| 87 | +} |
0 commit comments