html2md/
anchors.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
use crate::common::get_tag_attr;
use crate::dummy::IdentityHandler;

use super::TagHandler;
use super::StructuredPrinter;

use markup5ever_rcdom::{Handle,NodeData};

#[derive(Default)]
pub struct AnchorHandler {
    start_pos: usize,
    url: String,
    emit_unchanged: bool,
}

impl TagHandler for AnchorHandler {
    fn handle(&mut self, tag: &Handle, printer: &mut StructuredPrinter) {
        // Check for a `name` attribute. If it exists, we can't support this
        // in markdown, so we must emit this tag unchanged.
        if get_tag_attr(tag, "name").is_some() {
            let mut identity = IdentityHandler::default();
            identity.handle(tag, printer);
            self.emit_unchanged = true;
        }

        self.start_pos = printer.data.len();

        // try to extract a hyperlink
        self.url = match tag.data {
             NodeData::Element { ref attrs, .. } => {
                let attrs = attrs.borrow();
                let href = attrs.iter().find(|attr| attr.name.local.to_string() == "href");
                match href {
                    Some(link) => link.value.to_string(),
                    None => String::new()
                }
             }
             _ => String::new()
        };
    }

    fn after_handle(&mut self, printer: &mut StructuredPrinter) {
        if !self.emit_unchanged {
            // add braces around already present text, put an url afterwards
            printer.insert_str(self.start_pos, "[");
            printer.append_str(&format!("]({})", self.url))
        }
    }
}