Skip to main content

glory_html/
serialize.rs

1use crate::{Kind, Part, Property, Shape};
2use glory_render::memory::Memory;
3use glory_render::{Error, NodeId};
4use std::fmt::Write;
5
6pub fn escape(value: &str) -> String {
7    let mut out = String::with_capacity(value.len());
8    escape_into(value, &mut out);
9    out
10}
11fn escape_into(value: &str, out: &mut String) {
12    for ch in value.chars() {
13        match ch {
14            '&' => out.push_str("&"),
15            '<' => out.push_str("&lt;"),
16            '>' => out.push_str("&gt;"),
17            '"' => out.push_str("&quot;"),
18            '\'' => out.push_str("&#39;"),
19            '\0' => out.push('\u{fffd}'),
20            _ => out.push(ch),
21        }
22    }
23}
24pub fn serialize(tree: &Memory, key: impl Fn(NodeId) -> Option<u64>) -> Result<String, Error> {
25    fn node(
26        tree: &Memory,
27        id: NodeId,
28        key: &impl Fn(NodeId) -> Option<u64>,
29        out: &mut String,
30    ) -> Result<(), Error> {
31        let model = tree.node(id)?;
32        if model.suspended {
33            return Ok(());
34        }
35        let key_value = key(id).ok_or(Error::NodeGone(id))?;
36        let shape = crate::shape_in(tree, id)?;
37        if shape.pieces.is_empty() {
38            write!(out, "<!--gly:s:{key_value}-->").expect("writing to a String");
39            if let Some(crate::display::Placement::Root(frame)) = &shape.display {
40                for child in &model.children {
41                    if !matches!(tree.node(*child)?.descriptor.view().options.get::<crate::display::Placement>(),Some(crate::display::Placement::Outlet{frame:other,..}) if std::rc::Rc::ptr_eq(frame,other))
42                    {
43                        return Err(Error::InvalidPlacement("display child has no outlet"));
44                    }
45                }
46                fn display(
47                    nodes: &[crate::display::Tree],
48                    frame: &crate::display::Frame,
49                    parent: u64,
50                    out: &mut String,
51                    outlet: &mut dyn FnMut(u16, &mut String) -> Result<(), Error>,
52                ) -> Result<(), Error> {
53                    for item in nodes {
54                        match item {
55                            crate::display::Tree::Text(text) => {
56                                out.push_str("<!--gly:dt-->");
57                                escape_into(text, out);
58                            }
59                            crate::display::Tree::Element {
60                                tag,
61                                attrs,
62                                children,
63                            } => {
64                                out.push('<');
65                                out.push_str(tag);
66                                for (name, value) in attrs {
67                                    out.push(' ');
68                                    out.push_str(name);
69                                    out.push_str("=\"");
70                                    escape_into(value, out);
71                                    out.push('"');
72                                }
73                                out.push('>');
74                                display(children, frame, parent, out, outlet)?;
75                                out.push_str("</");
76                                out.push_str(tag);
77                                out.push('>');
78                            }
79                            crate::display::Tree::Outlet(slot) => {
80                                let marker = |out: &mut String| {
81                                    write!(out, "<!--gly:slot:{parent}:{slot}-->")
82                                        .expect("writing to a String");
83                                };
84                                if frame.compiled().slots[*slot as usize].kind
85                                    == crate::template::Kind::Children
86                                {
87                                    marker(out);
88                                    outlet(*slot, out)?;
89                                } else {
90                                    outlet(*slot, out)?;
91                                    marker(out);
92                                }
93                            }
94                        }
95                    }
96                    Ok(())
97                }
98                display(&frame.tree(), frame, key_value, out, &mut |slot, out| {
99                    for child in &model.children {
100                        if matches!(tree.node(*child)?.descriptor.view().options.get::<crate::display::Placement>(),Some(crate::display::Placement::Outlet{frame:other,slot:other_slot}) if std::rc::Rc::ptr_eq(frame,other) && slot==*other_slot)
101                        {
102                            node(tree, *child, key, out)?;
103                        }
104                    }
105                    Ok(())
106                })?;
107            } else {
108                for child in &model.children {
109                    node(tree, *child, key, out)?;
110                }
111            }
112            write!(out, "<!--gly:e:{key_value}-->").expect("writing to a String");
113        } else {
114            piece(&shape, shape.root_part()?, key_value, out, &mut |out| {
115                for child in &model.children {
116                    node(tree, *child, key, out)?;
117                }
118                Ok(())
119            })?;
120        }
121        Ok(())
122    }
123    fn piece(
124        shape: &Shape,
125        part: Part,
126        key: u64,
127        out: &mut String,
128        children: &mut dyn FnMut(&mut String) -> Result<(), Error>,
129    ) -> Result<(), Error> {
130        let item = shape
131            .pieces
132            .iter()
133            .find(|piece| piece.part == part)
134            .expect("HTML part");
135        match &item.kind {
136            Kind::Text(value) => {
137                write!(out, "<!--gly:t:{key}-->").expect("writing to a String");
138                escape_into(value, out);
139            }
140            Kind::Element {
141                tag,
142                attributes,
143                properties,
144            } => {
145                out.push('<');
146                out.push_str(tag);
147                write!(
148                    out,
149                    " data-gly-key=\"{key}\" data-gly-part=\"{}\"",
150                    part.name()
151                )
152                .expect("writing to a String");
153                for (name, value) in attributes {
154                    out.push(' ');
155                    out.push_str(name);
156                    out.push_str("=\"");
157                    escape_into(value, out);
158                    out.push('"');
159                }
160                out.push('>');
161                if let Some(Property::RichDocument(document)) = properties.get("richDocument") {
162                    rich_document_into(document, out);
163                }
164                if *tag == "select"
165                    && let Some(options) = &shape.select_options
166                {
167                    let keys = match properties.get("selectedKeys") {
168                        Some(Property::SelectedKeys(keys)) => keys.as_slice(),
169                        _ => &[],
170                    };
171                    select_options_into(options, keys, out);
172                }
173                if matches!(*tag, "input" | "img") {
174                    return Ok(());
175                }
176                if *tag == "textarea"
177                    && let Some(Property::Text(value)) = properties.get("value")
178                {
179                    // HTML parsers drop one leading LF immediately after textarea.
180                    if value.starts_with('\n') {
181                        out.push('\n');
182                    }
183                    escape_into(value, out);
184                }
185                for child in shape
186                    .pieces
187                    .iter()
188                    .filter(|piece| piece.parent == Some(part))
189                {
190                    piece(shape, child.part, key, out, &mut |_| Ok(()))?;
191                }
192                if shape.children == Some(part) {
193                    children(out)?;
194                }
195                out.push_str("</");
196                out.push_str(tag);
197                out.push('>');
198            }
199        }
200        Ok(())
201    }
202    let mut out = String::new();
203    for root in tree.roots() {
204        node(tree, *root, &key, &mut out)?;
205    }
206    Ok(out)
207}
208
209/// Serialize the finite intrinsic editor document; never accepts raw markup.
210pub fn rich_document(document: &glory_render::RichDocument) -> String {
211    let mut out = String::new();
212    rich_document_into(document, &mut out);
213    out
214}
215
216fn rich_document_into(document: &glory_render::RichDocument, out: &mut String) {
217    use glory_render::RichBlockKind;
218    for block in &document.blocks {
219        let tag = match block.kind {
220            RichBlockKind::Paragraph => "p",
221            RichBlockKind::Heading(1) => "h1",
222            RichBlockKind::Heading(2) => "h2",
223            RichBlockKind::Heading(3) => "h3",
224            RichBlockKind::Heading(4) => "h4",
225            RichBlockKind::Heading(5) => "h5",
226            RichBlockKind::Heading(6) => "h6",
227            RichBlockKind::Quote => "blockquote",
228            RichBlockKind::Heading(_) => unreachable!("validated rich heading"),
229        };
230        out.push('<');
231        out.push_str(tag);
232        out.push('>');
233        for run in &block.runs {
234            if let Some(link) = &run.marks.link {
235                out.push_str("<a href=\"");
236                escape_into(link, out);
237                out.push_str("\">");
238            }
239            if run.marks.bold {
240                out.push_str("<strong>");
241            }
242            if run.marks.italic {
243                out.push_str("<em>");
244            }
245            if run.marks.code {
246                out.push_str("<code>");
247            }
248            escape_into(&run.text, out);
249            if run.marks.code {
250                out.push_str("</code>");
251            }
252            if run.marks.italic {
253                out.push_str("</em>");
254            }
255            if run.marks.bold {
256                out.push_str("</strong>");
257            }
258            if run.marks.link.is_some() {
259                out.push_str("</a>");
260            }
261        }
262        if block.runs.iter().all(|run| run.text.is_empty()) {
263            out.push_str("<br>");
264        }
265        out.push_str("</");
266        out.push_str(tag);
267        out.push('>');
268    }
269}
270
271/// Serialize only the finite intrinsic children of a native select.
272pub fn select_options(config: &crate::SelectOptions, keys: &[String]) -> String {
273    let mut out = String::new();
274    select_options_into(config, keys, &mut out);
275    out
276}
277
278fn select_options_into(config: &crate::SelectOptions, keys: &[String], out: &mut String) {
279    fn option(value: &glory_render::SelectOption, keys: &[String], out: &mut String) {
280        out.push_str("<option data-gly-option=\"");
281        escape_into(value.key.as_str(), out);
282        out.push_str("\" value=\"");
283        escape_into(&value.value, out);
284        out.push('"');
285        if value.disabled {
286            out.push_str(" disabled");
287        }
288        if keys.iter().any(|key| key == value.key.as_str()) {
289            out.push_str(" selected");
290        }
291        out.push('>');
292        escape_into(&value.label, out);
293        out.push_str("</option>");
294    }
295    if let Some(placeholder) = &config.placeholder {
296        out.push_str("<option data-gly-placeholder=\"\" value=\"\" disabled hidden");
297        if keys.is_empty() {
298            out.push_str(" selected");
299        }
300        out.push('>');
301        escape_into(placeholder, out);
302        out.push_str("</option>");
303    }
304    for entry in config.entries.iter() {
305        match entry {
306            glory_render::SelectEntry::Divider => out.push_str("<hr>"),
307            glory_render::SelectEntry::Option(value) => option(value, keys, out),
308            glory_render::SelectEntry::Group(group) => {
309                out.push_str("<optgroup label=\"");
310                escape_into(&group.label, out);
311                out.push('"');
312                if group.disabled {
313                    out.push_str(" disabled");
314                }
315                out.push('>');
316                for value in &group.options {
317                    option(value, keys, out);
318                }
319                out.push_str("</optgroup>");
320            }
321        }
322    }
323}