Skip to main content

glory_html/
serialize.rs

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