Skip to main content

flm_core/stdlib/backends/html/
construct.rs

1//! The HTML construct element: one HTML tag, as a node in the lowered tree.
2//!
3//! A construct element is a presentation element that mirrors one fundamental
4//! construct of an output format, so that format-specific output is structured
5//! data in the lowered tree rather than a string (see [backends, lowering, and
6//! outputs](crate::guide::concepts_overview#backends-lowering-and-outputs)).
7//! HTML's fundamental construct is the tag, and this module holds the only
8//! element that mirrors it, [`TAG`] (`flm.pres.html.tag`), with its payload
9//! [`HtmlTagPayload`]: a tag name, attributes, and either children or one
10//! string of HTML that is already formed ([`Markup`]).
11//!
12//! | element | payload | slots |
13//! |---|---|---|
14//! | [`TAG`] (`flm.pres.html.tag`) | [`HtmlTagPayload`]: the tag name, the attributes in order, the body, and whether the tag is block-level | one [`BODY_SLOT`](crate::stdlib::backends::pres::BODY_SLOT) when the body is [`TagBody::Children`]; none when it is [`TagBody::Markup`] |
15//!
16//! The `html` feature ([`super::HtmlBackend`]), which registers the HTML
17//! backend, registers this element through [`register`], and the HTML backend
18//! writes it natively. It is **not** part of the shared presentation
19//! vocabulary ([`ALL`](crate::stdlib::backends::pres::ALL)): a backend that
20//! is not an HTML backend cannot write it, and a lowering rule that stages it
21//! (builds a node of it into the lowered tree; see
22//! [`Lowerer`](crate::core::lowering::Lowerer)) is a rule for HTML. A feature
23//! that stages it without registering the `html` feature itself declares it
24//! through a peer declaration ([`PeerName`](crate::core::registry::PeerName),
25//! [`FeatureBuilder::peer_element`](crate::core::registry::FeatureBuilder::peer_element)).
26//!
27//! # When a rule uses it
28//!
29//! Rarely. A lowering rule normally builds with the shared presentation
30//! vocabulary (a paragraph, a block with a role, a span with a style, a list,
31//! a link, an image), which every backend can write, so the rule's output is
32//! also written as plain text and as LaTeX. A rule stages a tag when it must
33//! put HTML in the page that no shared element carries: a formula an external
34//! tool typeset as `<svg>`, a widget a feature of its own defines, a tag the
35//! browser must see for a script to find it.
36//!
37//! The rule's author is then responsible for everything about that tag. The
38//! [HTML contract](super::CONVENTIONS) (the classes and attributes derived
39//! from the presentation vocabulary that a stylesheet may rely on) does not
40//! apply to a construct node: the emitter writes the tag, the attributes and
41//! the body as the payload states them and adds nothing of its own. The
42//! [address policy](super::check_address), which refuses an address a browser would
43//! execute, does not apply either. So the rule's author writes the classes its
44//! own stylesheet needs, checks the addresses it writes (with
45//! [`check_address`](super::check_address), under the value of
46//! [`HtmlAllowedUrlSchemes`](super::HtmlAllowedUrlSchemes) that its rule reads),
47//! and, where the body
48//! is markup, accepts the requirement stated at
49//! [`Markup::trusted`](super::Markup::trusted): the bytes are HTML that is
50//! safe to place in a page, and anything that came from a document or from
51//! another input the author does not control is sanitized first. The emitter
52//! still checks the tag name and the attribute names, and writes a node whose
53//! name fails as the unsupported stand-in
54//! ([`flm.html.invalid-name`](super::emit::InvalidName)).
55
56use std::sync::Arc;
57
58use techy::serialize::{DeserializeContext, DeserializeError, SerialValue};
59
60use crate::core::registry::{BuildError, FeatureBuilder};
61use crate::dump::session::PayloadReaders;
62use crate::lang::{Flm, PresPayload};
63use crate::stdlib::backends::pres::payload::{bad, entries, field, map, string, text};
64
65use super::markup::Markup;
66
67/// `flm.pres.html.tag` — one HTML tag: a name, attributes, and either children
68/// or one string of HTML that is already formed ([`Markup`]).
69pub const TAG: &str = "flm.pres.html.tag";
70
71/// The content between the opening and the closing tag of a [`TAG`] node.
72///
73/// A tag either holds content the lowering rule built out of presentation
74/// nodes, which the emitter writes as it writes any other content, or one
75/// [`Markup`] value: HTML that is already formed and is written through
76/// unchanged. It
77/// cannot hold both: markup the emitter could not look inside and nodes it
78/// would have to place around it have no defined order.
79#[derive(Debug, Clone, PartialEq, Eq, Default)]
80pub enum TagBody {
81    /// The node's content slot ([`BODY_SLOT`](crate::stdlib::backends::pres::BODY_SLOT))
82    /// holds the body, as lowered nodes. This is the default: a tag with no
83    /// content at all is a `Children` body whose slot is empty.
84    #[default]
85    Children,
86    /// The body is this HTML, written through unchanged, and the node is
87    /// childless. See [`Markup`] for the requirement its creator accepts.
88    Markup(Markup),
89}
90
91/// The payload of `flm.pres.html.tag`: one HTML tag as structured data.
92///
93/// A lowering rule stages a node of this element instead of assembling a
94/// string of HTML; the emitter writes the tag from the payload, escaping every
95/// attribute value, and writes the body as [`TagBody`] says (see [the module
96/// documentation](self) for when a rule uses it and what its author is then
97/// responsible for). Build one with [`new`](Self::new) and the chained
98/// setters.
99///
100/// # A tag inside a formula
101///
102/// Mathematics is handed to a formula renderer in the reader's browser as
103/// LaTeX, and content inside the formula is written as HTML inside that LaTeX.
104/// The renderer finds the end of a formula by searching all its characters,
105/// the HTML written inside it included, for the closing delimiter and for its
106/// `<tex-html>` tag. So a tag staged inside a formula is written under two
107/// extra rules:
108///
109/// - its **attribute values** are checked by the emitter, as every attribute
110///   written there is, and one holding the closing delimiter of the
111///   surrounding formula (`\)`, `\]` or `\end{<env>}`), `<tex-html` or
112///   `</tex-html` is left out and reported
113///   ([`flm.html.refused-in-math`](super::emit::RefusedInMath)), the tag and
114///   its content kept. The emitter does this because a rule cannot: only the
115///   emitter knows which delimiter it wrote around the formula.
116/// - a **[`TagBody::Markup`] body is written unchanged**, there as anywhere
117///   else. Inside a formula, the author of those bytes must therefore ensure
118///   one thing more than the requirement of [`Markup::trusted`]: the markup
119///   must not hold the closing delimiter of the surrounding formula, nor a
120///   `<tex-html>` or `</tex-html>` tag. Markup that holds one ends the formula
121///   early, and the reader gets an error in place of the formula.
122///
123/// A tag named `tex-html` is the renderer's element itself: a rule that writes
124/// a formula as text stages one to put HTML inside it. The emitter repairs
125/// the text written among its children as it repairs the text inside its own
126/// `<tex-html>` elements, breaking `\)`, `\]`, `\end{`, `<tex-html` and
127/// `</tex-html` with an empty element; a [`TagBody::Markup`] body is still
128/// written unchanged.
129///
130/// [`Markup::trusted`]: super::Markup::trusted
131#[derive(Debug, Clone, PartialEq, Eq, Default)]
132pub struct HtmlTagPayload {
133    /// The tag name, without its angle brackets (`div`, `svg`, `tex-html`).
134    ///
135    /// The emitter checks it
136    /// ([`is_valid_tag_name`](super::names::is_valid_tag_name)); a node whose
137    /// name fails is reported and written as the unsupported stand-in. A
138    /// paragraph holding a tag that HTML does not allow inside a `<p>` (a
139    /// `div`, a `ul`, a `table`, …) is written as a `<div>` (see [the
140    /// emitter](super::emit)).
141    pub tag: String,
142    /// The attributes, each a name and a value, written in this order.
143    ///
144    /// The names are checked as the tag name is
145    /// ([`is_valid_attribute_name`](super::names::is_valid_attribute_name));
146    /// the values are escaped where they are written and may hold anything.
147    pub attributes: Vec<(String, String)>,
148    /// The content inside the tag.
149    pub body: TagBody,
150    /// Whether the tag is **block-level**: whether the emitter may write a
151    /// line break and indentation around it.
152    ///
153    /// The rule that stages the tag knows whether it is block-level (a `<div>`
154    /// is, a `<span>` is not), and the sink takes this field rather than a
155    /// list of tag names, so that a tag the rule invented is laid out as its
156    /// author meant. Inside inline content, and inside a preformatted region,
157    /// no whitespace is added regardless of this field.
158    pub block: bool,
159}
160
161impl HtmlTagPayload {
162    /// Returns a tag with the given name, no attributes, a body held by its
163    /// node's content slot, and inline layout.
164    ///
165    /// # Examples
166    ///
167    /// ```
168    /// use flm_core::stdlib::backends::html::{HtmlTagPayload, TagBody};
169    ///
170    /// let payload = HtmlTagPayload::new("span");
171    /// assert_eq!(payload.tag, "span");
172    /// assert_eq!(payload.body, TagBody::Children);
173    /// assert!(!payload.block);
174    /// ```
175    pub fn new(tag: impl Into<String>) -> HtmlTagPayload {
176        HtmlTagPayload {
177            tag: tag.into(),
178            attributes: Vec::new(),
179            body: TagBody::Children,
180            block: false,
181        }
182    }
183
184    /// Returns the same tag with `attributes`, written in the order given.
185    pub fn attributes<N, V>(mut self, attributes: impl IntoIterator<Item = (N, V)>) -> Self
186    where
187        N: Into<String>,
188        V: Into<String>,
189    {
190        self.attributes =
191            attributes.into_iter().map(|(name, value)| (name.into(), value.into())).collect();
192        self
193    }
194
195    /// Returns the same tag with `markup` as its body, which makes the node
196    /// childless.
197    pub fn markup(mut self, markup: Markup) -> Self {
198        self.body = TagBody::Markup(markup);
199        self
200    }
201
202    /// Returns the same tag, marked as block-level (the `block` field).
203    pub fn block(mut self) -> Self {
204        self.block = true;
205        self
206    }
207
208    /// Rebuilds the payload from its projection, the value
209    /// [`project`](PresPayload::project) produced.
210    ///
211    /// # Errors
212    ///
213    /// Returns a [`DeserializeError`] that identifies `flm.pres.html.tag` when the
214    /// projection is not a map, when `tag` is missing or is not a string, when
215    /// `attributes` is present and is not a list of two-element lists of
216    /// strings, when `markup` is present and is not a string, or when `block`
217    /// is present and is not a boolean.
218    pub fn from_projection(value: &SerialValue) -> Result<HtmlTagPayload, DeserializeError> {
219        let e = entries(TAG, value)?;
220        let tag = string(TAG, e, "tag")?;
221        let attributes = match field(e, "attributes") {
222            None | Some(SerialValue::Null) => Vec::new(),
223            Some(SerialValue::List(items)) => items
224                .iter()
225                .map(|item| match item {
226                    SerialValue::List(pair) => match pair.as_slice() {
227                        [SerialValue::Str(name), SerialValue::Str(value)] => {
228                            Ok((name.clone(), value.clone()))
229                        }
230                        other => Err(bad(
231                            TAG,
232                            format!("`attributes` holds {other:?}, not a name and a value"),
233                        )),
234                    },
235                    other => {
236                        Err(bad(TAG, format!("`attributes` holds a non-list {other:?}")))
237                    }
238                })
239                .collect::<Result<Vec<_>, _>>()?,
240            Some(other) => {
241                return Err(bad(TAG, format!("`attributes` must be a list, found {other:?}")));
242            }
243        };
244        let body = match field(e, "markup") {
245            None | Some(SerialValue::Null) => TagBody::Children,
246            Some(SerialValue::Str(html)) => TagBody::Markup(Markup::from_library(html.clone())),
247            Some(other) => {
248                return Err(bad(TAG, format!("`markup` must be a string, found {other:?}")));
249            }
250        };
251        let block = match field(e, "block") {
252            None | Some(SerialValue::Null) => false,
253            Some(SerialValue::Bool(block)) => *block,
254            Some(other) => {
255                return Err(bad(TAG, format!("`block` must be a boolean, found {other:?}")));
256            }
257        };
258        Ok(HtmlTagPayload { tag, attributes, body, block })
259    }
260}
261
262impl PresPayload for HtmlTagPayload {
263    fn project(&self) -> SerialValue {
264        let mut fields = vec![("tag", text(&self.tag))];
265        if !self.attributes.is_empty() {
266            fields.push((
267                "attributes",
268                SerialValue::List(
269                    self.attributes
270                        .iter()
271                        .map(|(name, value)| {
272                            SerialValue::List(vec![text(name.as_str()), text(value.as_str())])
273                        })
274                        .collect(),
275                ),
276            ));
277        }
278        if let TagBody::Markup(markup) = &self.body {
279            fields.push(("markup", text(markup.as_str())));
280        }
281        if self.block {
282            fields.push(("block", SerialValue::Bool(true)));
283        }
284        map(fields)
285    }
286}
287
288/// Returns the payload reader of the construct element: what a reading session
289/// ([`reader_with`](crate::dump::session::reader_with)) needs, beside the
290/// shared vocabulary's own
291/// ([`payload_readers`](crate::stdlib::backends::pres::payload_readers)), to
292/// read a stored lowered tree of the HTML backend back into typed payloads.
293///
294/// # Examples
295///
296/// ```
297/// use flm_core::stdlib::backends::html::construct::{TAG, payload_readers};
298///
299/// let readers = payload_readers();
300/// assert_eq!(readers.len(), 1);
301/// assert!(readers.elements().any(|element| element.as_str() == TAG));
302/// ```
303pub fn payload_readers() -> PayloadReaders {
304    let mut readers = PayloadReaders::new();
305    readers.register(TAG, |value: &SerialValue, _cx: &mut DeserializeContext<'_, Flm>| {
306        HtmlTagPayload::from_projection(value)
307            .map(|payload| Arc::new(payload) as Arc<dyn PresPayload>)
308    });
309    readers
310}
311
312/// Registers the construct element `flm.pres.html.tag` with its payload type.
313/// The `html` feature ([`super::HtmlBackend`]) calls this from its own
314/// registration; a second registration in one registry declares the element
315/// twice and fails the build.
316///
317/// # Errors
318///
319/// Returns the [`BuildError`] the feature builder raises for a presentation
320/// element already declared in this registry.
321pub fn register(b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
322    b.presentation_element::<HtmlTagPayload>(
323        TAG,
324        "one HTML tag: its name, its attributes, and either children or one piece of markup",
325    )?;
326    Ok(())
327}
328
329#[cfg(test)]
330mod tests {
331    use super::*;
332
333    #[test]
334    fn a_projection_holds_the_keys_that_have_a_value() {
335        let plain = HtmlTagPayload::new("span");
336        assert_eq!(plain.project(), map(vec![("tag", text("span"))]));
337
338        let full = HtmlTagPayload::new("div")
339            .attributes([("class", "mine"), ("data-x", "1")])
340            .markup(Markup::trusted("<svg></svg>"))
341            .block();
342        assert_eq!(
343            full.project(),
344            map(vec![
345                ("tag", text("div")),
346                (
347                    "attributes",
348                    SerialValue::List(vec![
349                        SerialValue::List(vec![text("class"), text("mine")]),
350                        SerialValue::List(vec![text("data-x"), text("1")]),
351                    ])
352                ),
353                ("markup", text("<svg></svg>")),
354                ("block", SerialValue::Bool(true)),
355            ])
356        );
357    }
358
359    #[test]
360    fn a_projection_reads_back_as_the_payload_it_came_from() {
361        for payload in [
362            HtmlTagPayload::new("span"),
363            HtmlTagPayload::new("div").block(),
364            HtmlTagPayload::new("tex-html")
365                .attributes([("id", "eq-1")])
366                .markup(Markup::trusted("<span></span>")),
367        ] {
368            let read = HtmlTagPayload::from_projection(&payload.project()).expect("reads back");
369            assert_eq!(read, payload);
370        }
371    }
372
373    #[test]
374    fn a_projection_that_is_not_one_is_refused() {
375        let cases = [
376            map(vec![]),
377            map(vec![("tag", SerialValue::Int(3))]),
378            map(vec![("tag", text("p")), ("block", text("yes"))]),
379            map(vec![("tag", text("p")), ("markup", SerialValue::Bool(true))]),
380            map(vec![("tag", text("p")), ("attributes", text("class"))]),
381        ];
382        for projection in &cases {
383            assert!(HtmlTagPayload::from_projection(projection).is_err(), "{projection:?}");
384        }
385    }
386
387    #[test]
388    fn an_attributes_list_of_the_wrong_shape_is_refused() {
389        let projection = map(vec![
390            ("tag", text("p")),
391            (
392                "attributes",
393                SerialValue::List(vec![SerialValue::List(vec![text("only-a-name")])]),
394            ),
395        ]);
396        assert!(HtmlTagPayload::from_projection(&projection).is_err());
397    }
398}