typlite/
attributes.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
//! Attributes for HTML elements and parsing

use ecow::EcoString;
use tinymist_derive::TypliteAttr;
use typst::html::HtmlAttrs;

use crate::Result;

/// Tag attributes defined for HTML elements.
pub mod md_attr {
    use typst::html::HtmlAttr;

    macro_rules! attrs {
        ($($attr:ident -> $name:ident)*) => {
            $(#[allow(non_upper_case_globals)]
            pub const $attr: HtmlAttr = HtmlAttr::constant(
                stringify!($name)
            );)*
        }
    }

    attrs! {
        src -> src
        alt -> alt
        level -> level
        dest -> dest
        lang -> lang
        block -> block
        text -> text
        value -> value
        caption -> caption
    }
}

#[derive(TypliteAttr, Default)]
pub struct HeadingAttr {
    pub level: usize,
}

#[derive(TypliteAttr, Default)]
pub struct ImageAttr {
    pub src: EcoString,
    pub alt: EcoString,
}

#[derive(TypliteAttr, Default)]
pub struct FigureAttr {
    pub caption: EcoString,
}

#[derive(TypliteAttr, Default)]
pub struct LinkAttr {
    pub dest: EcoString,
}

#[derive(TypliteAttr, Default)]
pub struct RawAttr {
    pub lang: EcoString,
    pub block: bool,
    pub text: EcoString,
}

#[derive(TypliteAttr, Default)]
pub struct ListItemAttr {
    pub value: Option<u32>,
}

pub trait TypliteAttrsParser {
    fn parse(attrs: &HtmlAttrs) -> Result<Self>
    where
        Self: Sized;
}

pub trait TypliteAttrParser {
    fn parse_attr(content: &EcoString) -> Result<Self>
    where
        Self: Sized;
}

impl TypliteAttrParser for usize {
    fn parse_attr(content: &EcoString) -> Result<Self> {
        Ok(content
            .parse::<usize>()
            .map_err(|_| format!("cannot parse {} as usize", content))?)
    }
}

impl TypliteAttrParser for u32 {
    fn parse_attr(content: &EcoString) -> Result<Self> {
        Ok(content
            .parse::<u32>()
            .map_err(|_| format!("cannot parse {} as u32", content))?)
    }
}

impl TypliteAttrParser for bool {
    fn parse_attr(content: &EcoString) -> Result<Self> {
        Ok(content
            .parse::<bool>()
            .map_err(|_| format!("cannot parse {} as bool", content))?)
    }
}

impl TypliteAttrParser for EcoString {
    fn parse_attr(content: &EcoString) -> Result<Self> {
        Ok(content.clone())
    }
}

impl<T> TypliteAttrParser for Option<T>
where
    T: TypliteAttrParser,
{
    fn parse_attr(content: &EcoString) -> Result<Self> {
        if content.is_empty() {
            Ok(None)
        } else {
            T::parse_attr(content).map(Some)
        }
    }
}