Skip to main content

flm_core/stdlib/backends/html/
names.rs

1//! The naming functions of the HTML contract: how a presentation element's
2//! name, a role and a payload field become the class names, attribute names
3//! and custom properties the output carries, and the checks a name passes
4//! before it is written.
5//!
6//! The **HTML contract** is the set of class names and attributes a stylesheet
7//! or a script may rely on in the HTML backend's output, stated as data in
8//! [`CONVENTIONS`](super::CONVENTIONS). Its names are not written down one by
9//! one: the four functions below derive them from the names the presentation
10//! vocabulary already has, so that a class cannot drift from the element it
11//! represents.
12//!
13//! - [`class_of_element`] — the class every node of a presentation element
14//!   carries: the element's name with every hyphen doubled and every dot turned
15//!   into one hyphen, so `flm.pres.block-heading` is written
16//!   `flm-pres-block--heading`.
17//! - [`class_of_role`] — the second class, for the payload's **role**: the
18//!   dotted, feature-owned name saying what a container is
19//!   (`flm.heading.number`; see [decorations, roles and
20//!   kinds](crate::guide::concepts_overview#decorations-roles-and-kinds)),
21//!   rewritten the same way (`flm-heading-number`).
22//! - [`data_attribute`] — the attribute one other payload field is written
23//!   under: [`DATA_PREFIX`] followed by the field's name with `_` and `.`
24//!   turned into hyphens, so the field `source_span` is written
25//!   `data-flm-source-span`.
26//! - [`style_property`] — the custom property a payload's **length** field is
27//!   written as, in the element's `style` attribute: [`STYLE_PROPERTY_PREFIX`]
28//!   followed by the field's name turned by the same rule, so the field
29//!   `indent_left` is written `--flm-element-indent-left`.
30//!
31//! The [conventions table](super::conventions), not these functions, decides
32//! which field becomes which attribute and which elements carry a role: these
33//! functions only say how a name is written once the table has chosen it.
34//!
35//! [`is_valid_token`] is the check a role and a kind token pass before they
36//! are written: the `class` attribute and `data-flm-kind` both hold a list of
37//! tokens separated by whitespace, so a name holding whitespace would be read
38//! as several of them.
39//!
40//! The two remaining functions, [`is_valid_tag_name`] and
41//! [`is_valid_attribute_name`], are the check applied to a tag or attribute
42//! name that comes from a [construct node](super::construct) (a node that a
43//! lowering rule stages, that is, builds into the lowered tree, to write one
44//! HTML tag of its own; see [`Lowerer`](crate::core::lowering::Lowerer)) or
45//! from the render options. Such a name is chosen by the rule's author or the host, so it is
46//! checked before it is written; the names this module derives pass the
47//! check by construction.
48
49/// The prefix of every attribute this backend writes for a payload field that
50/// is not one of HTML's own attributes: `data-flm-`.
51///
52/// `data-*` is HTML's own space for attributes an application defines, so an
53/// attribute written under this prefix is valid HTML and collides with nothing
54/// a browser or another library defines. See [`data_attribute`].
55pub const DATA_PREFIX: &str = "data-flm-";
56
57/// The prefix of every custom property this backend writes in an element's
58/// `style` attribute for a payload's length field: `--flm-element-`.
59///
60/// A custom property is a CSS variable: it sets nothing by itself, and a
61/// stylesheet rule applies it (`padding-left:
62/// var(--flm-element-indent-left, 0)`), so a page's own rules remain free to
63/// apply it differently. See [`style_property`].
64pub const STYLE_PROPERTY_PREFIX: &str = "--flm-element-";
65
66/// A dotted name as one class name: every `-` becomes `--`, and every `.`
67/// becomes `-`.
68///
69/// The two replacements happen together, in one pass over the characters, so
70/// that a hyphen the name already held is doubled and a hyphen written for a
71/// dot is not.
72///
73/// **A class produced here reads back to exactly one name**: reading the class
74/// from left to right, a single hyphen was a dot and a double hyphen was a
75/// hyphen, so `flm-pres-block--heading` can only have come from
76/// `flm.pres.block-heading`. That property holds for a **well-formed dotted
77/// name**, which is one whose segments — the parts between the dots — are
78/// non-empty and neither begin nor end with a hyphen. A name that breaks the
79/// condition can share its class with another one: `flm.pres.-x` and
80/// `flm.pres-.x` are both written `flm-pres---x`, and `flm.pres..x` is written
81/// `flm-pres--x`, the class of the well-formed name `flm.pres-x`. **Nothing
82/// checks the condition**: the names of this library's own vocabulary and the
83/// dotted names features declare satisfy it by the way dotted names are
84/// written, and a check at every class would cost more than it is worth.
85fn dotted_as_class(name: &str) -> String {
86    let mut class = String::with_capacity(name.len());
87    for ch in name.chars() {
88        match ch {
89            '-' => class.push_str("--"),
90            '.' => class.push('-'),
91            _ => class.push(ch),
92        }
93    }
94    class
95}
96
97/// Returns the class a node of the presentation element `element` carries: the
98/// element's name with every hyphen doubled and every dot turned into one
99/// hyphen.
100///
101/// The doubling keeps the class readable backwards: a single hyphen in the
102/// class represents a dot in the name and a double hyphen a hyphen, so
103/// one class can come from one element name only. That holds for a
104/// **well-formed dotted name** — one whose segments, the parts between the
105/// dots, are non-empty and neither begin nor end with a hyphen — and **nothing
106/// checks the condition**, neither here nor at the registry: a name that
107/// breaks it can share its class with another one (`flm.pres.-x` and
108/// `flm.pres-.x` are both written `flm-pres---x`; `flm.pres..x` is written
109/// `flm-pres--x`, the class of `flm.pres-x`). A feature
110/// author who writes names the way dotted names are written never breaks it.
111/// [`class_of_role`] applies the same rewriting to a role.
112///
113/// # Examples
114///
115/// ```
116/// use flm_core::stdlib::backends::html::names::class_of_element;
117/// use flm_core::stdlib::backends::pres;
118///
119/// assert_eq!(class_of_element(pres::BLOCK_HEADING), "flm-pres-block--heading");
120/// assert_eq!(class_of_element(pres::PAR), "flm-pres-par");
121/// assert_eq!(class_of_element(pres::DECO_RUNIN), "flm-pres-deco-runin");
122/// ```
123pub fn class_of_element(element: &str) -> String {
124    dotted_as_class(element)
125}
126
127/// Returns the class a node carries for its payload's role: the role's name with every
128/// hyphen doubled and every dot turned into one hyphen.
129///
130/// A **role** is a feature-owned dotted name on a presentation payload that
131/// says what a container is (a theorem's heading, a quotation's attribution;
132/// see [`payload`](crate::stdlib::backends::pres::payload)). Because the
133/// feature that introduced it owns the name, two features cannot declare the
134/// same role by accident. The class is the same rewriting [`class_of_element`]
135/// applies, applied to the role's name.
136///
137/// A class reads back to exactly one role name when the name is well formed;
138/// [`class_of_element`] states the condition, which nothing checks.
139///
140/// Because a stylesheet selects on these classes, **a role's name is a public
141/// interface**: renaming a role changes the class, and every stylesheet written
142/// against the old one stops matching. The same is true of a presentation
143/// element's name.
144///
145/// A role is one class and no more, which holds as long as the role's name is
146/// one token: a name holding whitespace would be read as several classes,
147/// because that is how the `class` attribute separates them. Nothing in the
148/// library's name type enforces that, so the emitter checks a role with
149/// [`is_valid_token`] before it writes the class and refuses a name that fails
150/// — see that function for what is refused and what the emitter does instead.
151///
152/// # Examples
153///
154/// ```
155/// use flm_core::stdlib::backends::html::names::class_of_role;
156///
157/// assert_eq!(class_of_role("flm.heading"), "flm-heading");
158/// ```
159pub fn class_of_role(role: &str) -> String {
160    dotted_as_class(role)
161}
162
163/// Returns whether `name` may be written as **one token**: one class among the
164/// classes of an element, or one token of the `data-flm-kind` attribute.
165///
166/// Both of those attributes hold a list of tokens separated by whitespace, so
167/// a name holding whitespace would be read as several tokens, and an empty
168/// name as none: a node whose role is `flm.a b` would carry the classes
169/// `flm-a` and `b`, the second representing nothing. A name that passes this
170/// check is one token wherever it is written.
171///
172/// Such a name comes from a feature author, not from a document: it is the
173/// role or the kind a lowering rule put in a presentation node's payload, and
174/// the library's name type accepts any text. The emitter therefore checks it
175/// with this function, leaves out the class or the token that fails, and
176/// reports it as `flm.html.invalid-name`
177/// ([`InvalidName`](super::emit::InvalidName)); everything else about the node
178/// is written as usual.
179///
180/// # Examples
181///
182/// ```
183/// use flm_core::stdlib::backends::html::names::is_valid_token;
184///
185/// assert!(is_valid_token("flm.heading"));
186/// assert!(is_valid_token("enumerate"));
187/// assert!(!is_valid_token(""));
188/// assert!(!is_valid_token("flm.a b"));
189/// ```
190pub fn is_valid_token(name: &str) -> bool {
191    !name.is_empty() && !name.chars().any(char::is_whitespace)
192}
193
194/// Returns the attribute name a payload field is written under: [`DATA_PREFIX`]
195/// followed by `field` with every `_` and `.` turned into `-`.
196///
197/// # Examples
198///
199/// ```
200/// use flm_core::stdlib::backends::html::names::data_attribute;
201///
202/// assert_eq!(data_attribute("level"), "data-flm-level");
203/// assert_eq!(data_attribute("source_span"), "data-flm-source-span");
204/// ```
205pub fn data_attribute(field: &str) -> String {
206    prefixed_field(DATA_PREFIX, field)
207}
208
209/// Returns the custom property a payload's length field is written as, in the
210/// element's `style` attribute: [`STYLE_PROPERTY_PREFIX`] followed by `field`
211/// turned into a name by the rule of [`data_attribute`], every `_` and `.`
212/// turned into `-`.
213///
214/// # Examples
215///
216/// ```
217/// use flm_core::stdlib::backends::html::names::style_property;
218///
219/// assert_eq!(style_property("indent_left"), "--flm-element-indent-left");
220/// assert_eq!(style_property("width"), "--flm-element-width");
221/// ```
222pub fn style_property(field: &str) -> String {
223    prefixed_field(STYLE_PROPERTY_PREFIX, field)
224}
225
226/// `prefix` followed by `field` with every `_` and `.` turned into `-`: the
227/// only rule by which a payload field's name becomes a name on the page.
228fn prefixed_field(prefix: &str, field: &str) -> String {
229    let mut name = String::with_capacity(prefix.len() + field.len());
230    name.push_str(prefix);
231    for ch in field.chars() {
232        name.push(if ch == '_' || ch == '.' { '-' } else { ch });
233    }
234    name
235}
236
237/// Returns whether `name` may be written as a tag name: an ASCII letter followed by
238/// any number of ASCII letters, digits and `-`.
239///
240/// This is narrower than HTML's own rule, so that the check stays simple and
241/// safe. It admits every element name HTML has and every custom element name
242/// written in ASCII (which must hold a `-`), and it admits nothing that could
243/// end the tag early or start something else (no space, no `/`, no `>`, no
244/// `<`, nothing outside ASCII), so a name that passes is written unchanged and
245/// the tag it opens is the tag that was asked for.
246///
247/// A name reaches this check from a [construct node](super::construct)'s
248/// payload, which a lowering rule wrote, or from the tag a host maps a heading
249/// kind to ([`HtmlRenderOptions::heading_tags`](super::HtmlRenderOptions::heading_tags));
250/// the emitter checks it before opening the tag and reports a name that fails
251/// instead of writing it.
252///
253/// # Examples
254///
255/// ```
256/// use flm_core::stdlib::backends::html::names::is_valid_tag_name;
257///
258/// assert!(is_valid_tag_name("div"));
259/// assert!(is_valid_tag_name("tex-html"));
260/// assert!(!is_valid_tag_name(""));
261/// assert!(!is_valid_tag_name("2div"));
262/// assert!(!is_valid_tag_name("div onclick=x"));
263/// assert!(!is_valid_tag_name("div>"));
264/// ```
265pub fn is_valid_tag_name(name: &str) -> bool {
266    let mut chars = name.chars();
267    match chars.next() {
268        Some(first) if first.is_ascii_alphabetic() => {}
269        _ => return false,
270    }
271    chars.all(|ch| ch.is_ascii_alphanumeric() || ch == '-')
272}
273
274/// Returns whether `name` may be written as an attribute name: an ASCII letter
275/// followed by any number of ASCII letters, digits, `-`, `_`, `:` and `.`.
276///
277/// It is [`is_valid_tag_name`]'s set with the three characters attribute names
278/// carry in practice — `data-flm-level`, `aria-label`, `xml:lang`,
279/// `data.pinned` — and, like it, admits nothing that could end the attribute
280/// or start another: no space, no `=`, no quotation mark, no `/`, no `>`.
281///
282/// # Examples
283///
284/// ```
285/// use flm_core::stdlib::backends::html::names::is_valid_attribute_name;
286///
287/// assert!(is_valid_attribute_name("data-flm-level"));
288/// assert!(is_valid_attribute_name("xml:lang"));
289/// assert!(!is_valid_attribute_name("href=\"x\" onclick"));
290/// assert!(!is_valid_attribute_name("-hidden"));
291/// ```
292pub fn is_valid_attribute_name(name: &str) -> bool {
293    let mut chars = name.chars();
294    match chars.next() {
295        Some(first) if first.is_ascii_alphabetic() => {}
296        _ => return false,
297    }
298    chars.all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '-' | '_' | ':' | '.'))
299}
300
301#[cfg(test)]
302mod tests {
303    use super::*;
304    use crate::stdlib::backends::pres;
305
306    /// The other direction of the mapping, written only here: a class back to
307    /// the name it came from. A double hyphen was a hyphen, a single one a dot.
308    fn name_of_class(class: &str) -> String {
309        let mut name = String::with_capacity(class.len());
310        let mut chars = class.chars().peekable();
311        while let Some(ch) = chars.next() {
312            if ch == '-' {
313                if chars.peek() == Some(&'-') {
314                    chars.next();
315                    name.push('-');
316                } else {
317                    name.push('.');
318                }
319            } else {
320                name.push(ch);
321            }
322        }
323        name
324    }
325
326    #[test]
327    fn every_element_of_the_vocabulary_has_a_class_of_its_own() {
328        let mut classes: Vec<String> = pres::ALL.iter().map(|e| class_of_element(e)).collect();
329        classes.sort();
330        let count = classes.len();
331        classes.dedup();
332        assert_eq!(classes.len(), count, "two elements share one class");
333        assert!(classes.iter().all(|class| !class.contains('.')));
334        assert!(classes.iter().all(|class| is_valid_attribute_name(class)));
335    }
336
337    #[test]
338    fn a_hyphen_is_doubled_and_a_dot_becomes_one_hyphen() {
339        assert_eq!(class_of_element(pres::BLOCK_HEADING), "flm-pres-block--heading");
340        assert_eq!(class_of_element(pres::MATH_PASSTHROUGH), "flm-pres-math--passthrough");
341        assert_eq!(class_of_element(pres::MATH_TEXT), "flm-pres-math--text");
342        assert_eq!(class_of_element(pres::DECO_MARK), "flm-pres-deco--mark");
343        assert_eq!(class_of_element(pres::DECO_RUNIN), "flm-pres-deco-runin");
344        assert_eq!(class_of_element(pres::PAR), "flm-pres-par");
345        assert_eq!(class_of_role("flm.heading"), "flm-heading");
346    }
347
348    #[test]
349    fn a_class_reads_back_to_exactly_one_name() {
350        // Every element of the vocabulary, and every role the standard features
351        // write — today the one role of the headings feature.
352        let roles = [crate::stdlib::features::headings::numbers::NUMBER_ROLE];
353        for name in pres::ALL.iter().chain(roles.iter()) {
354            assert_eq!(&name_of_class(&class_of_element(name)), name, "{name:?}");
355            assert_eq!(&name_of_class(&class_of_role(name)), name, "{name:?}");
356        }
357        // And a feature author's own well-formed names.
358        for name in ["mypkg.theorem.body", "mypkg.run-in", "a-b.c-d.e"] {
359            assert_eq!(name_of_class(&class_of_role(name)), name, "{name:?}");
360        }
361    }
362
363    #[test]
364    fn a_role_becomes_the_same_kind_of_class() {
365        assert_eq!(class_of_role("flm.heading"), "flm-heading");
366        assert_eq!(class_of_role("mypkg.theorem.body"), "mypkg-theorem-body");
367        assert_eq!(class_of_role("mypkg.run-in.body"), "mypkg-run--in-body");
368    }
369
370    #[test]
371    fn a_name_that_would_be_read_as_several_tokens_is_not_one() {
372        // The vocabulary's own names, and every role and kind spelled the way
373        // a dotted name is spelled, are one token.
374        for name in ["flm.heading", "enumerate", "mypkg.theorem.body", "ref"] {
375            assert!(is_valid_token(name), "{name:?}");
376        }
377        // Whitespace separates tokens in a class attribute and in
378        // `data-flm-kind`, and an empty name is no token at all.
379        for name in ["", " ", "flm.a b", "a\tb", "a\nb", "trailing "] {
380            assert!(!is_valid_token(name), "{name:?}");
381        }
382        // Every element of the vocabulary passes it, as does every class
383        // derived from one.
384        for element in pres::ALL {
385            assert!(is_valid_token(element), "{element:?}");
386            assert!(is_valid_token(&class_of_element(element)), "{element:?}");
387        }
388    }
389
390    #[test]
391    fn a_field_becomes_a_data_attribute_with_hyphens() {
392        assert_eq!(data_attribute("kind"), "data-flm-kind");
393        assert_eq!(data_attribute("indent_right"), "data-flm-indent-right");
394        assert_eq!(data_attribute("a.b_c"), "data-flm-a-b-c");
395        assert!(is_valid_attribute_name(&data_attribute("indent_left")));
396    }
397
398    #[test]
399    fn a_name_that_could_break_out_of_its_tag_is_refused() {
400        for bad in ["", " div", "div ", "div/", "div>", "<div", "di v", "café", "d\"v", "-x", "1x"]
401        {
402            assert!(!is_valid_tag_name(bad), "{bad:?}");
403            assert!(!is_valid_attribute_name(bad), "{bad:?}");
404        }
405        for good in ["a", "div", "tex-html", "h1", "myElement-x"] {
406            assert!(is_valid_tag_name(good), "{good:?}");
407            assert!(is_valid_attribute_name(good), "{good:?}");
408        }
409        // The three characters an attribute name may hold and a tag name may not.
410        for name in ["xml:lang", "data_flm", "a.b"] {
411            assert!(is_valid_attribute_name(name), "{name:?}");
412            assert!(!is_valid_tag_name(name), "{name:?}");
413        }
414    }
415}