typlite/parser/
media.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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
//! Media processing module, handles images, SVG and Frame media elements

use core::fmt;
use std::path::PathBuf;
use std::sync::{Arc, LazyLock};

use base64::Engine;
use cmark_writer::ast::{HtmlAttribute, HtmlElement as CmarkHtmlElement, Node};
use ecow::{eco_format, EcoString};
use tinymist_project::{base::ShadowApi, EntryReader, TaskInputs, MEMORY_MAIN_ENTRY};
use typst::{
    foundations::{Bytes, Dict, IntoValue},
    html::{HtmlElement, HtmlNode},
    layout::{Abs, Frame},
    utils::LazyHash,
    World,
};

use crate::{
    attributes::{md_attr, IdocAttr, TypliteAttrsParser},
    common::ExternalFrameNode,
    ColorTheme,
};

use super::core::HtmlToAstParser;

enum AssetUrl {
    /// Embedded Base64 SVG data
    Embedded(String),
    /// External file path
    External(PathBuf),
}

impl fmt::Display for AssetUrl {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            AssetUrl::Embedded(data) => write!(f, "data:image/svg+xml;base64,{data}"),
            // todo: correct relative path?
            AssetUrl::External(path) => write!(f, "{}", path.display()),
        }
    }
}

impl HtmlToAstParser {
    /// Convert Typst source to CommonMark node
    pub fn convert_source(&mut self, element: &HtmlElement) -> Node {
        if element.children.len() != 1 {
            // Construct error node
            return Node::HtmlElement(CmarkHtmlElement {
                tag: EcoString::inline("div"),
                attributes: vec![HtmlAttribute {
                    name: EcoString::inline("class"),
                    value: EcoString::inline("error"),
                }],
                children: vec![Node::Text(eco_format!(
                    "source contains not only one child: {}, whose attrs: {:?}",
                    element.children.len(),
                    element.attrs
                ))],
                self_closing: false,
            });
        }

        let Some(HtmlNode::Frame(frame)) = element.children.first() else {
            // todo: utils to remove duplicated error construction
            return Node::HtmlElement(CmarkHtmlElement {
                tag: EcoString::inline("div"),
                attributes: vec![HtmlAttribute {
                    name: EcoString::inline("class"),
                    value: EcoString::inline("error"),
                }],
                children: vec![Node::Text(eco_format!(
                    "source contains not a frame, but: {:?}",
                    element.children
                ))],
                self_closing: false,
            });
        };

        let svg = typst_svg::svg_frame(frame);
        let frame_url = match self.create_asset_url(&svg) {
            Ok(url) => url,
            Err(e) => {
                // Construct error node
                return Node::HtmlElement(CmarkHtmlElement {
                    tag: EcoString::inline("div"),
                    attributes: vec![HtmlAttribute {
                        name: EcoString::inline("class"),
                        value: EcoString::inline("error"),
                    }],
                    children: vec![Node::Text(eco_format!("Error creating source URL: {e}"))],
                    self_closing: false,
                });
            }
        };

        let media = element.attrs.0.iter().find_map(|(name, data)| {
            if *name == md_attr::media {
                Some(data.clone())
            } else {
                None
            }
        });

        Node::HtmlElement(CmarkHtmlElement {
            tag: EcoString::inline("source"),
            attributes: vec![
                HtmlAttribute {
                    name: EcoString::inline("media"),
                    value: media.unwrap_or_else(|| "all".into()),
                },
                HtmlAttribute {
                    name: EcoString::inline("srcset"),
                    value: frame_url.to_string().into(),
                },
            ],
            children: vec![],
            self_closing: true,
        })
    }

    /// Convert Typst frame to CommonMark node
    pub fn convert_frame(&mut self, frame: &Frame) -> Node {
        if self.feat.remove_html {
            // todo: make error silent is not good.
            return Node::Text(EcoString::new());
        }

        let svg = typst_svg::svg_frame(frame);
        self.convert_svg(svg)
    }

    fn convert_svg(&mut self, svg: String) -> Node {
        let frame_url = self.create_asset_url(&svg);

        match frame_url {
            Ok(url @ AssetUrl::Embedded(..)) => Self::create_embedded_frame(&url),
            Ok(AssetUrl::External(file_path)) => Node::Custom(Box::new(ExternalFrameNode {
                file_path,
                alt_text: EcoString::inline("typst-frame"),
                svg,
            })),
            Err(e) => {
                if self.feat.soft_error {
                    let b64_data = Self::base64_url(&svg);
                    Self::create_embedded_frame(&b64_data)
                } else {
                    // Construct error node
                    Node::HtmlElement(CmarkHtmlElement {
                        tag: EcoString::inline("div"),
                        attributes: vec![HtmlAttribute {
                            name: EcoString::inline("class"),
                            value: EcoString::inline("error"),
                        }],
                        children: vec![Node::Text(eco_format!("Error creating frame URL: {e}"))],
                        self_closing: false,
                    })
                }
            }
        }
    }

    /// Create embedded frame node
    fn create_embedded_frame(url: &AssetUrl) -> Node {
        Node::HtmlElement(CmarkHtmlElement {
            tag: EcoString::inline("img"),
            attributes: vec![
                HtmlAttribute {
                    name: EcoString::inline("alt"),
                    value: EcoString::inline("typst-block"),
                },
                HtmlAttribute {
                    name: EcoString::inline("src"),
                    value: url.to_string().into(),
                },
            ],
            children: vec![],
            self_closing: true,
        })
    }

    /// Convert asset to asset url
    fn create_asset_url(&mut self, svg: &str) -> crate::Result<AssetUrl> {
        if let Some(assets_path) = &self.feat.assets_path {
            let file_id = self.asset_counter;
            self.asset_counter += 1;
            let file_name = format!("frame_{file_id}.svg");
            let file_path = assets_path.join(&file_name);

            std::fs::write(&file_path, svg.as_bytes())?;
            return Ok(AssetUrl::External(file_path));
        }

        // Fall back to embedded mode if no external asset path is specified
        Ok(Self::base64_url(svg))
    }

    /// Create embedded frame node
    fn base64_url(data: &str) -> AssetUrl {
        AssetUrl::Embedded(base64::engine::general_purpose::STANDARD.encode(data.as_bytes()))
    }
    /// Convert Typst inline document to CommonMark node
    pub fn convert_idoc(&mut self, element: &HtmlElement) -> Node {
        static DARK_THEME_INPUT: LazyLock<Arc<LazyHash<Dict>>> = LazyLock::new(|| {
            Arc::new(LazyHash::new(Dict::from_iter(std::iter::once((
                "x-color-theme".into(),
                "dark".into_value(),
            )))))
        });

        if self.feat.remove_html {
            eprintln!("Removing idoc element due to remove_html feature");
            // todo: make error silent is not good.
            return Node::Text(EcoString::new());
        }
        let attrs = match IdocAttr::parse(&element.attrs) {
            Ok(attrs) => attrs,
            Err(e) => {
                if self.feat.soft_error {
                    return Node::Text(eco_format!("Error parsing idoc attributes: {e}"));
                } else {
                    // Construct error node
                    return Node::HtmlElement(CmarkHtmlElement {
                        tag: EcoString::inline("div"),
                        attributes: vec![HtmlAttribute {
                            name: EcoString::inline("class"),
                            value: EcoString::inline("error"),
                        }],
                        children: vec![Node::Text(eco_format!(
                            "Error parsing idoc attributes: {e}"
                        ))],
                        self_closing: false,
                    });
                }
            }
        };

        let src = attrs.src;
        let mode = attrs.mode;

        let mut world = self.world.clone().task(TaskInputs {
            entry: Some(
                self.world
                    .entry_state()
                    .select_in_workspace(MEMORY_MAIN_ENTRY.vpath().as_rooted_path()),
            ),
            inputs: match self.feat.color_theme {
                Some(ColorTheme::Dark) => Some(DARK_THEME_INPUT.clone()),
                None | Some(ColorTheme::Light) => None,
            },
        });
        // todo: cost some performance.
        world.take_db();

        let main = world.main();

        const PRELUDE: &str = r##"#set page(width: auto, height: auto, margin: (y: 0.45em, rest: 0em), fill: none);
            #set text(fill: rgb("#c0caf5")) if sys.inputs.at("x-color-theme", default: none) == "dark";"##;

        let import_prefix = if let Some(ref import_ctx) = self.feat.import_context {
            format!("{}\n", import_ctx)
        } else {
            String::new()
        };

        world
            .map_shadow_by_id(
                main,
                Bytes::from_string(match mode.as_str() {
                    "code" => eco_format!("{}{PRELUDE}#{{{src}}}", import_prefix),
                    "math" => eco_format!("{}{PRELUDE}${src}$", import_prefix),
                    "markup" => eco_format!("{}{PRELUDE}#[{}]", import_prefix, src),
                    // todo check mode
                    //  "markup" |
                    _ => eco_format!("{}{PRELUDE}#[{}]", import_prefix, src),
                }),
            )
            .unwrap();

        let doc = typst::compile(&world);
        let doc = match doc.output {
            Ok(doc) => doc,
            Err(e) => {
                if self.feat.soft_error {
                    return Node::Text(eco_format!("Error compiling idoc: {e:?}"));
                } else {
                    // Construct error node
                    return Node::HtmlElement(CmarkHtmlElement {
                        tag: EcoString::inline("div"),
                        attributes: vec![HtmlAttribute {
                            name: EcoString::inline("class"),
                            value: EcoString::inline("error"),
                        }],
                        children: vec![Node::Text(eco_format!("Error compiling idoc: {e:?}"))],
                        self_closing: false,
                    });
                }
            }
        };

        let svg = typst_svg::svg_merged(&doc, Abs::zero());
        self.convert_svg(svg)
    }
}