Skip to main content

flm_core/stdlib/backends/html/
conventions.rs

1//! The HTML contract as data: one row per presentation element saying which
2//! tag, classes and attributes this backend writes for it, which payload
3//! fields it cannot express, and which style definition gives it its default
4//! look.
5//!
6//! The **HTML contract** is the set of class names and attributes a
7//! stylesheet or a script may rely on in the HTML backend's output. It is
8//! written down once, here, as [`CONVENTIONS`]: the emitter reads a row before
9//! it writes a node, [`markdown_table`] prints the rows for the [rendering
10//! guide](crate::guide::rendering#the-html-contract), and tests compare the three
11//! against each other, so that the output, this table and the documentation
12//! cannot drift apart.
13//!
14//! What the rows do **not** hold is a class name. A class is derived from the
15//! name the element already has, by [`class_of_element`] and
16//! [`class_of_role`](super::names::class_of_role), and an attribute that is
17//! not one of HTML's own is
18//! derived from the payload field's name by [`data_attribute`], as the custom
19//! property of a length field is by [`style_property`]. Storing them
20//! would let a class drift from the element it represents.
21//!
22//! # A length on the page
23//!
24//! A payload field holding a [`Length`] — a line's indentation — is written
25//! as a **custom property** (a CSS variable) in the element's `style`
26//! attribute, named after the field by [`style_property`] and valued with the
27//! CSS length [`css_length`] spells, a tab being a multiple of the custom
28//! property `--flm-tab`, which the core stylesheet declares on the page's
29//! root:
30//!
31//! ```html
32//! <div class="flm-pres-line" style="--flm-element-indent-left: calc(2 * var(--flm-tab))" data-flm-align="left">…</div>
33//! ```
34//!
35//! The property sets nothing by itself: the stylesheet applies it
36//! (`padding-left: var(--flm-element-indent-left, 0)`), so a page's own rules
37//! decide what an indentation looks like and win over the shipped ones, and
38//! a host changes the width of a tab with one property. A length is written
39//! once, as the property, never also as a `data-flm-…` attribute, and a zero
40//! length writes nothing, the stylesheet's fallback being zero, so an
41//! ordinary line carries no `style` attribute. **Nothing else ever enters
42//! `style`**: the attribute holds the custom properties the HTML contract lists —
43//! a payload's length fields, and the ratio of two of them (below) — and
44//! never a CSS property such as `padding-left`, which would outrank every
45//! stylesheet rule ([`Written::Style`], [`Written::Ratio`]).
46//!
47//! One further kind of custom property is written by the same writer: the
48//! **ratio** of two of a payload's length fields, where a stylesheet needs
49//! the proportions of a box and CSS cannot divide one length by another. An
50//! image shown at a width and a height is written with its two lengths and
51//! their ratio, which the core stylesheet reads so that the image keeps its
52//! proportions where the page is narrower than it
53//! ([`Written::Ratio`], [`css_ratio`]):
54//!
55//! ```html
56//! <img class="flm-pres-image" src="plot.png" style="--flm-element-width: 5cm; --flm-element-height: 2in; --flm-element-aspect-ratio: 141.73228 / 144">
57//! ```
58//!
59//! Three things are outside the HTML contract, because a page must stay free to
60//! change them: the whitespace between tags, the order the attributes are
61//! written in, and the choice of tag. A stylesheet that selects
62//! `.flm-pres-span[data-flm-style="bold"]` keeps working regardless of the tag the
63//! emitter picks for it; one that selects `strong` does not, and is written
64//! against something this backend never promised.
65//!
66//! # How to read a row
67//!
68//! [`Convention::tag`] says how the tag is chosen ([`TagRule`]).
69//! [`Convention::fields`] lists every field of the element's payload, in the
70//! order the attributes derived from them are written, each with what becomes
71//! of it ([`Written`]): an attribute HTML itself defines, a `data-flm-…`
72//! attribute, a custom property in the `style` attribute, the node's second
73//! class, the class of a block before the node's own, an attribute on each
74//! entry of a list, or nothing.
75//! [`Convention::style`] gives the style definition the emitter requires when
76//! it writes the element. A requirement is only an identifier; how the
77//! definition reaches the page is decided by the stage that resolves the
78//! definitions ([`super::defs`]).
79
80use super::names::{class_of_element, data_attribute, style_property};
81use crate::stdlib::backends::pres::{self, DocRole, I48F16, Length, LengthUnit};
82
83/// The attribute every length field of a payload is written in: `style`,
84/// each field as one custom property ([`Written::Style`]).
85pub const STYLE_ATTRIBUTE: &str = "style";
86
87/// The custom property holding the width of one **tab**, the unit of
88/// indentation each backend sets through one setting of its own: `--flm-tab`.
89/// The core stylesheet declares it on the page's root, `2em` by default;
90/// [`css_length`] spells a length in tabs as a multiple of it.
91pub const TAB_PROPERTY: &str = "--flm-tab";
92
93/// Returns `length` spelled as a CSS length: a length in tabs as
94/// `calc(<amount> * var(--flm-tab))` ([`TAB_PROPERTY`]), a length of any
95/// other unit as written, amount then unit (`1.5em`, `10pt`, `3mm`,
96/// `0.25in`, `2cm`).
97///
98/// The vocabulary's units other than the tab are CSS's own, spelled as CSS
99/// spells them, and its point is CSS's point, 1/72 inch. The amount is
100/// written in the decimal the length projects as — the shortest that reads
101/// back to the same exact amount — so the output is byte-identical wherever
102/// it is produced. This is the only way a length is written on the page; the
103/// emitter writes it as the value of a custom property ([`Written::Style`]).
104///
105/// # Examples
106///
107/// ```
108/// use flm_core::stdlib::backends::html::conventions::css_length;
109/// use flm_core::stdlib::backends::pres::Length;
110///
111/// assert_eq!(css_length(&Length::tabs(2)), "calc(2 * var(--flm-tab))");
112/// assert_eq!(css_length(&Length::parse("1.5em")?), "1.5em");
113/// assert_eq!(css_length(&Length::parse("10pt")?), "10pt");
114/// # Ok::<(), flm_core::stdlib::backends::pres::LengthError>(())
115/// ```
116pub fn css_length(length: &Length) -> String {
117    match length.unit {
118        LengthUnit::Tabs => format!("calc({} * var({TAB_PROPERTY}))", length.amount_decimal()),
119        LengthUnit::Ems
120        | LengthUnit::Points
121        | LengthUnit::Millimeters
122        | LengthUnit::Centimeters
123        | LengthUnit::Inches => length.to_string(),
124    }
125}
126
127/// Returns the ratio `first ÷ second` of two lengths spelled as CSS's `aspect-ratio`
128/// reads a ratio, `<first> / <second>` with both written in points; `None`
129/// unless both are greater than zero and in physical units (`pt`, `mm`, `cm`,
130/// `in`), since a tab or an em has no fixed size to compare.
131///
132/// The two amounts are the lengths converted to points
133/// ([`Length::convert_to`]), each rounded once to the nearest 1/65536 pt, and
134/// written in the shortest decimal that reads back; CSS divides them. This is
135/// the value of the custom property a [`Written::Ratio`] field declares.
136///
137/// # Examples
138///
139/// ```
140/// use flm_core::stdlib::backends::html::conventions::css_ratio;
141/// use flm_core::stdlib::backends::pres::Length;
142///
143/// let ratio = css_ratio(&Length::parse("2in")?, &Length::parse("36pt")?);
144/// assert_eq!(ratio.as_deref(), Some("144 / 36"));
145/// assert_eq!(css_ratio(&Length::parse("2em")?, &Length::parse("1em")?), None);
146/// # Ok::<(), flm_core::stdlib::backends::pres::LengthError>(())
147/// ```
148pub fn css_ratio(first: &Length, second: &Length) -> Option<String> {
149    let points = |length: &Length| {
150        length
151            .convert_to(LengthUnit::Points)
152            .ok()
153            .filter(|converted| converted.amount > I48F16::ZERO)
154    };
155    let (first, second) = (points(first)?, points(second)?);
156    Some(format!("{} / {}", first.amount_decimal(), second.amount_decimal()))
157}
158
159/// The class the page's content container carries, and the identifier it is
160/// found by: `flm-content`.
161///
162/// It is not derived from any element, because the container is the page's own
163/// and represents no node of a document. See [`page`](super::page) for the
164/// page layout it is part of.
165pub const CONTENT_CLASS: &str = "flm-content";
166
167/// The class of the element holding a list entry's label where that label is
168/// rich content rather than a marker a browser draws: `flm-pres-list-label`.
169pub const LIST_LABEL_CLASS: &str = "flm-pres-list-label";
170
171/// The class of the two marker lines of an unattributed environment — the
172/// `\begin{…}` and `\end{…}` lines the output shows as the author wrote them:
173/// `flm-pres-unknown-marker`.
174pub const UNKNOWN_MARKER_CLASS: &str = "flm-pres-unknown-marker";
175
176/// The three classes of the HTML contract that are not derived from an element
177/// or a role, in the order this module declares them.
178///
179/// They are spelled by hand, but they are spelled to the same rule: read
180/// backwards through the mapping [`class_of_element`] applies — a single hyphen
181/// was a dot, a double hyphen was a hyphen — they are `flm.content`,
182/// `flm.pres.list.label` and `flm.pres.unknown.marker`. Each is an element's
183/// name followed by the name of a part of it, which is how a role is spelled,
184/// so none of them can be read as the class of a hyphenated element name.
185pub const AUXILIARY_CLASSES: [&str; 3] =
186    [CONTENT_CLASS, LIST_LABEL_CLASS, UNKNOWN_MARKER_CLASS];
187
188// --- the style definitions the rows name ------------------------------------------------
189
190/// The style definition of the elements every document has: paragraphs,
191/// blocks, spans, links, images and decorations.
192///
193/// The mark on an unresolved reference is here rather than with the other
194/// error looks ([`STYLE_ERRORS`]), because it is a display style of a span and
195/// the row of a span gives this definition: a document whose only error is an
196/// unresolved reference requires no other definition.
197pub const STYLE_CORE: &str = "flm.html.style.core";
198/// The style definition of the six heading sizes.
199///
200/// A run-in heading is not styled here: it reaches the page as a run-in
201/// decoration, whose row gives [`STYLE_CORE`].
202pub const STYLE_HEADINGS: &str = "flm.html.style.headings";
203/// The style definition of verbatim content, inline and as a block.
204pub const STYLE_VERBATIM: &str = "flm.html.style.verbatim";
205/// The style definition of passthrough mathematics (mathematics written into
206/// the page as source, for the MathJax script to typeset): displayed formulas,
207/// and content inside a formula.
208pub const STYLE_MATH_PASSTHROUGH: &str = "flm.html.style.math-passthrough";
209/// The style definition of lists, and of a run of lines with its alignment.
210pub const STYLE_LISTS: &str = "flm.html.style.lists";
211/// The style definition of what the output shows as an error: an unattributed
212/// callable, an element this backend cannot write, and the mark a rule leaves
213/// where it dropped something.
214///
215/// An unresolved reference is marked by [`STYLE_CORE`] instead, for the reason
216/// given there.
217pub const STYLE_ERRORS: &str = "flm.html.style.errors";
218
219/// The **script** definition that turns the LaTeX of a formula into
220/// mathematics in the reader's browser: `flm.html.mathjax`.
221///
222/// It is the only definition the emitter requires that no row of the table
223/// below gives. A row's `style` column holds the definition that sets an
224/// element's default *look*, and this one is not that: it is a script, and a
225/// page needs it only because passthrough mathematics is written as LaTeX for a
226/// formula renderer to read (see [the emitter](super::emit#mathematics)). The
227/// emitter requires it at the first passthrough formula it writes in a tree, beside the style
228/// definition the mathematics rows give.
229///
230/// A requirement is only an identifier: how the definition reaches the page
231/// (a script element in the page, a file a host bundles, nothing at all
232/// because the host loads its own) is decided where the definitions are
233/// resolved ([`super::defs`]), not here.
234pub const SCRIPT_MATHJAX: &str = "flm.html.mathjax";
235
236// --- the row types ----------------------------------------------------------------------
237
238/// How the tag of one presentation element is chosen.
239///
240/// The choice is **not** part of the HTML contract (see [the module
241/// documentation](self)); it is recorded so that the table a reader sees says
242/// what the output looks like today, and so that a test can compare the table
243/// with the bytes.
244#[derive(Debug, Clone, Copy, PartialEq, Eq)]
245pub enum TagRule {
246    /// Always this tag.
247    Fixed(&'static str),
248    /// By what the paragraph holds: `<p>` when everything inside it is
249    /// **phrasing content**, the only content HTML allows inside a `<p>`, and
250    /// a [`PARAGRAPH_FLOW_TAG`] (`<div>`) carrying the role
251    /// [`PARAGRAPH_ROLE`] when it holds **flow content**: an element written
252    /// with a tag at whose start an HTML parser closes an open `<p>`, such as
253    /// a `<div>`, a `<ul>`, a `<table>`, a `<pre>` or a heading.
254    ParagraphContent,
255    /// The tag the render options map the heading kind's name to
256    /// ([`HtmlRenderOptions::heading_tags`](super::HtmlRenderOptions::heading_tags)),
257    /// else by the heading's level counted from the root heading level
258    /// ([`HtmlRenderOptions::root_heading_level`](super::HtmlRenderOptions::root_heading_level)):
259    /// `<h1>` at the root's level, `<h2>` one level deeper, and so on to
260    /// `<h6>`, which every heading five levels below the root and deeper gets;
261    /// `data-flm-level` keeps the true level. A heading above the root is
262    /// reported and written `<h1>`.
263    HeadingLevel,
264    /// By the span's display style: `<em>`, `<strong>`, `<i>`, `<code>`,
265    /// `<u>`, `<sup>`, `<sub>`, and `<span>` for every other style and for a
266    /// span with none.
267    SpanStyle,
268    /// The first tag when the payload's `display` field is inline, the second
269    /// when it is a block.
270    Display {
271        /// The tag written for inline display.
272        inline: &'static str,
273        /// The tag written for block display.
274        block: &'static str,
275    },
276    /// By the verbatim kind and the display: code (the kind `code`) is
277    /// `<code>` inline and `<pre><code>` as a block, with the class and the
278    /// attributes on the `<pre>`; plain characters and an identifier, which
279    /// are not code, are `<span>` inline and `<div>` as a block.
280    VerbatimKindAndDisplay,
281    /// `<ol>`, `<ul>` or `<dl>` by the list's structural kind token —
282    /// [`LIST_NUMBERED`](pres::LIST_NUMBERED),
283    /// [`LIST_UNNUMBERED`](pres::LIST_UNNUMBERED) or
284    /// [`LIST_TERMS`](pres::LIST_TERMS), the first of them among the kinds;
285    /// `<ul>` when none of them is.
286    ListKind,
287    /// The tag [`BLOCK_TAGS`] maps the block's role to ([`block_tag`]):
288    /// `<blockquote>` for a quotation, `<figure>` for a float,
289    /// `<figcaption>` for the line under its content and `<nav>` for a table
290    /// of contents; `<div>` for every role
291    /// the table does not name, and for a block with no role.
292    BlockRole,
293    /// No element of its own: the node stands for something else, which is
294    /// what the emitter writes in its place.
295    None,
296}
297
298impl TagRule {
299    /// Returns the rule as one line of prose, for the printed table
300    /// ([`markdown_table`]).
301    pub fn describe(self) -> String {
302        match self {
303            TagRule::Fixed(tag) => format!("`<{tag}>`"),
304            TagRule::ParagraphContent => format!(
305                "`<p>`; `<{PARAGRAPH_FLOW_TAG}>` with `role=\"{PARAGRAPH_ROLE}\"` when the \
306                 paragraph holds flow content"
307            ),
308            TagRule::HeadingLevel => String::from(
309                "`<h1>`–`<h6>` by level counted from `root_heading_level`, `<h6>` five levels \
310                 below it and deeper; a render option maps a heading kind to a tag of its own",
311            ),
312            TagRule::SpanStyle => String::from("by style; `<span>` otherwise"),
313            TagRule::Display { inline, block } => {
314                format!("`<{inline}>` inline, `<{block}>` as a block")
315            }
316            TagRule::VerbatimKindAndDisplay => String::from(
317                "for the kind `code`, `<code>` inline, `<pre><code>` as a block; for every other \
318                 kind, `<span>` inline, `<div>` as a block",
319            ),
320            TagRule::ListKind => String::from(
321                "`<ol>`, `<ul>` or `<dl>` by the kind `numbered`, `unnumbered` or `terms`; `<ul>` \
322                 otherwise",
323            ),
324            TagRule::BlockRole => {
325                let mapped: Vec<String> = BLOCK_TAGS
326                    .iter()
327                    .map(|entry| format!("`<{}>` for the role `{}`", entry.tag, entry.role))
328                    .collect();
329                format!("by role: {}; `<{DEFAULT_BLOCK_TAG}>` otherwise", mapped.join(", "))
330            }
331            TagRule::None => String::from("none of its own"),
332        }
333    }
334}
335
336/// The tag of a `flm.pres.par` that holds flow content
337/// ([`TagRule::ParagraphContent`]): `div`, which HTML allows to hold anything.
338pub const PARAGRAPH_FLOW_TAG: &str = "div";
339
340/// The value of the `role` attribute of a paragraph written as a
341/// [`PARAGRAPH_FLOW_TAG`]: `paragraph`, the accessibility role of a paragraph,
342/// so that assistive technology reads the `<div>` as the paragraph it is. A
343/// paragraph written as a `<p>` carries no `role`, the tag saying as much.
344pub const PARAGRAPH_ROLE: &str = "paragraph";
345
346/// One row of [`BLOCK_TAGS`]: the tag a block of one role is written with.
347#[derive(Debug, Clone, Copy, PartialEq, Eq)]
348pub struct BlockTag {
349    /// The block's role, as its payload spells it (`flm.quote`).
350    pub role: &'static str,
351    /// The tag written for a block of that role, without angle brackets
352    /// (`blockquote`).
353    pub tag: &'static str,
354}
355
356/// The tag of a `flm.pres.block` whose role [`BLOCK_TAGS`] does not name, and
357/// of a block with no role: `div`.
358pub const DEFAULT_BLOCK_TAG: &str = "div";
359
360/// The **tag table** of blocks: the tag a `flm.pres.block` is written with,
361/// keyed by the block's role ([`TagRule::BlockRole`]).
362///
363/// A block of a role the table lists is written with that tag — a quotation,
364/// role `flm.quote`, as a `<blockquote>`, regardless of its environment, since the
365/// environment's name is a kind a stylesheet selects on
366/// (`.flm-quote[data-flm-kind~="address"]`); a float, role
367/// `flm.floats.float`, as a `<figure>`, regardless of its float type, and the line under
368/// its content, role `flm.floats.float.caption`, as a `<figcaption>`, which
369/// the float's rule places last in the float, where HTML wants it; a table of
370/// contents, role `flm.toc`, as a `<nav>` — and
371/// every other block as a [`DEFAULT_BLOCK_TAG`] (`<div>`), a float's content
372/// among them. The table is this backend's: no feature,
373/// no configuration value and no lowering rule specifies a tag, so a feature that
374/// wants a tag for the blocks of its role gets a row here. A host wanting
375/// another tag for one block writes a lowering rule that stages (builds into
376/// the lowered tree; see [`Lowerer`](crate::core::lowering::Lowerer)) an HTML
377/// tag construct node, as for any other element. As the [module
378/// documentation](self) says of every tag, the choice is not part of the
379/// HTML contract: a stylesheet selects a quotation by `.flm-quote`, never by
380/// `blockquote`.
381///
382/// # Examples
383///
384/// ```
385/// use flm_core::stdlib::backends::html::conventions::block_tag;
386///
387/// assert_eq!(block_tag(Some("flm.quote")), "blockquote");
388/// assert_eq!(block_tag(Some("flm.floats.float")), "figure");
389/// assert_eq!(block_tag(Some("flm.floats.float.caption")), "figcaption");
390/// assert_eq!(block_tag(Some("flm.toc")), "nav");
391/// assert_eq!(block_tag(Some("flm.floats.float.content")), "div");
392/// assert_eq!(block_tag(Some("flm.theorems.theorem")), "div");
393/// assert_eq!(block_tag(None), "div");
394/// ```
395pub static BLOCK_TAGS: &[BlockTag] = &[
396    BlockTag { role: "flm.quote", tag: "blockquote" },
397    BlockTag { role: "flm.floats.float", tag: "figure" },
398    BlockTag { role: "flm.floats.float.caption", tag: "figcaption" },
399    BlockTag { role: "flm.toc", tag: "nav" },
400];
401
402/// Returns the tag a `flm.pres.block` of the role `role` is written with: the
403/// tag of the row of [`BLOCK_TAGS`] for that role, else [`DEFAULT_BLOCK_TAG`].
404pub fn block_tag(role: Option<&str>) -> &'static str {
405    role.and_then(|role| BLOCK_TAGS.iter().find(|entry| entry.role == role))
406        .map_or(DEFAULT_BLOCK_TAG, |entry| entry.tag)
407}
408
409/// What the emitter does with one field of a presentation payload.
410#[derive(Debug, Clone, Copy, PartialEq, Eq)]
411pub enum Written {
412    /// An attribute HTML itself defines, written under this name: `id`,
413    /// `href`, `src`, `alt`, `width`, `srcset`, and the two attributes of
414    /// accessibility, `role` (a [document role](DocRole), written as
415    /// [`doc_role_value`] spells it) and `aria-label`.
416    Own(&'static str),
417    /// An attribute under the prefix `data-flm-` ([`data_attribute`]), named
418    /// after the token given here — the field's own name, except in two
419    /// cases. Where one attribute carries what two fields spell differently:
420    /// a `kinds` list and a single `kind` are both written as `data-flm-kind`.
421    /// And where the attribute is named after what an author writes: a
422    /// heading's `name` is `data-flm-heading`, and its `in_toc` is
423    /// `data-flm-toc`, after the key `toc` of a heading's options.
424    Data(&'static str),
425    /// A custom property in the element's `style` attribute
426    /// ([`STYLE_ATTRIBUTE`]), named after the field by [`style_property`]
427    /// (`indent_left` is `--flm-element-indent-left`) and valued with the
428    /// field's [`Length`] as [`css_length`] spells it. For a length field
429    /// alone; a zero length writes nothing.
430    ///
431    /// This is the only thing the `style` attribute ever holds, with the
432    /// ratios of [`Written::Ratio`]: the custom properties of a payload's
433    /// length fields, which a stylesheet applies, and never a CSS property,
434    /// which would outrank every stylesheet rule. A length field is written
435    /// this way and in no other: never also as a `data-flm-…` attribute,
436    /// whose text (`2tab`) a stylesheet can do nothing with.
437    Style,
438    /// A custom property in the element's `style` attribute holding the
439    /// ratio of the two length fields named here, first over second, as
440    /// [`css_ratio`] spells it — written only where both are set, greater
441    /// than zero and in physical units. The entry's own name is not a field
442    /// of the payload but the name of the property, derived as a length
443    /// field's is ([`style_property`]): `aspect_ratio` is
444    /// `--flm-element-aspect-ratio`. It lets a stylesheet keep a box's
445    /// proportions, which CSS cannot compute from two lengths.
446    Ratio(&'static str, &'static str),
447    /// The node's second class, derived from the role's name
448    /// ([`class_of_role`](super::names::class_of_role)).
449    RoleClass,
450    /// The block class, `flm-pres-block`: the class of a block container,
451    /// [`pres::BLOCK`], which the core stylesheet spaces, written before the
452    /// element's own class where the field says the node is a block, and
453    /// nothing where it says the node is inline: an image that is a direct
454    /// child of a float's body is spaced and stacked as a block, and one
455    /// inside a line of text is not.
456    BlockClass,
457    /// An attribute HTML itself defines, written under this name on the
458    /// element of **each entry** of a list: `id`, `rowspan`, `colspan` and
459    /// `scope`.
460    ///
461    /// An entry is an item of a list — its element is the `<li>`, or a
462    /// description list's `<dt>` — or a cell of a table of cells — its
463    /// `<td>` or `<th>`. The field holds one value per entry, in the order of
464    /// the entries, and each entry's attribute is written from that entry's
465    /// value; an entry with no value gets no attribute. It is never written
466    /// on the element of the list or the table itself. The same holds of
467    /// [`Written::EntryData`].
468    Entry(&'static str),
469    /// An attribute under the prefix `data-flm-` ([`data_attribute`]),
470    /// written on the element of each entry as [`Written::Entry`] is, and
471    /// named after the token given here — the field's own name, except where
472    /// one attribute carries what two fields spell differently: a list's
473    /// `entry_levels` and a heading's `level` are both written as
474    /// `data-flm-level`. A token ending in a hyphen is a family, one
475    /// attribute per value, the value's name appended (a cell's custom style
476    /// `orange` is `data-flm-style-orange`, with an empty value).
477    EntryData(&'static str),
478    /// Nothing is written for it, for the reason given: the output cannot
479    /// express it, or it reaches the page as content rather than as an
480    /// attribute.
481    Dropped(&'static str),
482}
483
484/// One field of a presentation payload, and what becomes of it.
485#[derive(Debug, Clone, Copy, PartialEq, Eq)]
486pub struct Field {
487    /// The field's name, spelled as the payload's projection spells it.
488    pub field: &'static str,
489    /// What the emitter does with it.
490    pub written: Written,
491}
492
493impl Field {
494    /// The attribute this field is written under on the element's own tag,
495    /// when it is written as one there. A field written on each entry of a
496    /// list ([`Written::Entry`], [`Written::EntryData`]) returns `None` here and its attribute from
497    /// [`entry_attribute`](Self::entry_attribute); a length field
498    /// ([`Written::Style`]) returns `None` and its custom property from
499    /// [`style_property`](Self::style_property), all of a row's length
500    /// fields sharing the single [`STYLE_ATTRIBUTE`].
501    ///
502    /// # Examples
503    ///
504    /// ```
505    /// use flm_core::stdlib::backends::html::conventions::{Field, Written};
506    ///
507    /// let level = Field { field: "level", written: Written::Data("level") };
508    /// assert_eq!(level.attribute().as_deref(), Some("data-flm-level"));
509    ///
510    /// let role = Field { field: "role", written: Written::RoleClass };
511    /// assert_eq!(role.attribute(), None);
512    /// ```
513    pub fn attribute(&self) -> Option<String> {
514        match self.written {
515            Written::Own(name) => Some(String::from(name)),
516            Written::Data(stem) => Some(data_attribute(stem)),
517            Written::Style
518            | Written::Ratio(..)
519            | Written::RoleClass
520            | Written::BlockClass
521            | Written::Entry(_)
522            | Written::EntryData(_)
523            | Written::Dropped(_) => None,
524        }
525    }
526
527    /// The custom property this field is written as in the element's `style`
528    /// attribute, when it is a length field written there
529    /// ([`Written::Style`]) or a ratio of two ([`Written::Ratio`]).
530    ///
531    /// # Examples
532    ///
533    /// ```
534    /// use flm_core::stdlib::backends::html::conventions::row;
535    /// use flm_core::stdlib::backends::pres;
536    ///
537    /// let line = row(pres::LINE).expect("a row");
538    /// let indent = line.field("indent_left").expect("the field");
539    /// assert_eq!(indent.style_property().as_deref(), Some("--flm-element-indent-left"));
540    /// assert_eq!(indent.attribute(), None);
541    /// ```
542    pub fn style_property(&self) -> Option<String> {
543        match self.written {
544            Written::Style | Written::Ratio(..) => Some(style_property(self.field)),
545            _ => None,
546        }
547    }
548
549    /// The attribute this field is written under on the element of each
550    /// entry of a list or each cell of a table of cells, when it is written
551    /// there: the name given for [`Written::Entry`], and the name
552    /// [`data_attribute`] derives from the token for [`Written::EntryData`].
553    ///
554    /// # Examples
555    ///
556    /// ```
557    /// use flm_core::stdlib::backends::html::conventions::row;
558    /// use flm_core::stdlib::backends::pres;
559    ///
560    /// let list = row(pres::LIST).expect("a row");
561    /// let anchors = list.field("entry_anchors").expect("the field");
562    /// assert_eq!(anchors.entry_attribute().as_deref(), Some("id"));
563    /// assert_eq!(anchors.attribute(), None);
564    ///
565    /// let levels = list.field("entry_levels").expect("the field");
566    /// assert_eq!(levels.entry_attribute().as_deref(), Some("data-flm-level"));
567    /// ```
568    pub fn entry_attribute(&self) -> Option<String> {
569        match self.written {
570            Written::Entry(name) => Some(String::from(name)),
571            Written::EntryData(token) => Some(data_attribute(token)),
572            _ => None,
573        }
574    }
575}
576
577/// One row of the HTML contract: everything this backend writes for one
578/// presentation element.
579#[derive(Debug, Clone, Copy, PartialEq, Eq)]
580pub struct Convention {
581    /// The presentation element's name (`flm.pres.par`).
582    pub element: &'static str,
583    /// How the tag is chosen.
584    pub tag: TagRule,
585    /// Every field of the element's payload, in the order the attributes
586    /// derived from them are written.
587    pub fields: &'static [Field],
588    /// The style definition the emitter requires when it writes the element;
589    /// `None` for a node that writes no element of its own.
590    pub style: Option<&'static str>,
591}
592
593impl Convention {
594    /// The class every node of this element carries, derived from the
595    /// element's name.
596    ///
597    /// # Examples
598    ///
599    /// ```
600    /// use flm_core::stdlib::backends::html::conventions::row;
601    /// use flm_core::stdlib::backends::pres;
602    ///
603    /// assert_eq!(row(pres::PAR).expect("a row").class(), "flm-pres-par");
604    /// ```
605    pub fn class(&self) -> String {
606        class_of_element(self.element)
607    }
608
609    /// The field named `field`, when the row has one.
610    pub fn field(&self, field: &str) -> Option<&Field> {
611        self.fields.iter().find(|entry| entry.field == field)
612    }
613
614    /// Whether the element's payload carries a role that becomes a second
615    /// class.
616    pub fn has_role(&self) -> bool {
617        self.fields.iter().any(|entry| entry.written == Written::RoleClass)
618    }
619}
620
621// --- the table --------------------------------------------------------------------------
622
623/// A field written as an attribute HTML itself defines.
624const fn own(field: &'static str, attribute: &'static str) -> Field {
625    Field { field, written: Written::Own(attribute) }
626}
627
628/// A field written as the `data-flm-…` attribute named after it.
629const fn data(field: &'static str) -> Field {
630    Field { field, written: Written::Data(field) }
631}
632
633/// A field written as the `data-flm-…` attribute named after `stem` rather
634/// than after the field: what a `kinds` list and a single `kind` share, so
635/// that a stylesheet selects a kind token the same way whichever field carried
636/// it; and a heading's `name` and `in_toc`, written as `data-flm-heading` and
637/// `data-flm-toc`, after what an author writes.
638const fn data_as(field: &'static str, stem: &'static str) -> Field {
639    Field { field, written: Written::Data(stem) }
640}
641
642/// A field written as an attribute HTML itself defines on each entry of a
643/// list.
644const fn entry(field: &'static str, attribute: &'static str) -> Field {
645    Field { field, written: Written::Entry(attribute) }
646}
647
648/// A field written on each entry of a list as the `data-flm-…` attribute
649/// named after `token`.
650const fn entry_data(field: &'static str, token: &'static str) -> Field {
651    Field { field, written: Written::EntryData(token) }
652}
653
654/// A length field written as a custom property in the `style` attribute.
655const fn style(field: &'static str) -> Field {
656    Field { field, written: Written::Style }
657}
658
659/// The ratio of two length fields, written as the custom property named after
660/// `name` in the `style` attribute.
661const fn ratio(name: &'static str, first: &'static str, second: &'static str) -> Field {
662    Field { field: name, written: Written::Ratio(first, second) }
663}
664
665/// A field that becomes the node's second class.
666const fn role(field: &'static str) -> Field {
667    Field { field, written: Written::RoleClass }
668}
669
670/// A field that adds the class of a block before the node's own where it
671/// says the node is a block.
672const fn block_class(field: &'static str) -> Field {
673    Field { field, written: Written::BlockClass }
674}
675
676/// A field nothing is written for, with the reason.
677const fn dropped(field: &'static str, why: &'static str) -> Field {
678    Field { field, written: Written::Dropped(why) }
679}
680
681/// The HTML contract, one row per element of the [presentation
682/// vocabulary](crate::stdlib::backends::pres), in the vocabulary's own order.
683///
684/// Every name of [`pres::ALL`] has exactly
685/// one row, which a test holds; [`row`] is the lookup the emitter uses.
686pub static CONVENTIONS: &[Convention] = &[
687    Convention {
688        element: pres::PAR,
689        tag: TagRule::ParagraphContent,
690        fields: &[own("anchor", "id")],
691        style: Some(STYLE_CORE),
692    },
693    Convention {
694        element: pres::BLOCK,
695        tag: TagRule::BlockRole,
696        fields: &[
697            own("anchor", "id"),
698            role("role"),
699            own("doc_role", "role"),
700            data_as("kinds", "kind"),
701        ],
702        style: Some(STYLE_CORE),
703    },
704    Convention {
705        element: pres::BLOCK_HEADING,
706        tag: TagRule::HeadingLevel,
707        fields: &[
708            own("anchor", "id"),
709            data_as("name", "heading"),
710            data("level"),
711            data_as("in_toc", "toc"),
712            dropped("number", "the number stands in the content"),
713        ],
714        style: Some(STYLE_HEADINGS),
715    },
716    Convention {
717        element: pres::RUNIN_HEADING,
718        tag: TagRule::Fixed("span"),
719        fields: &[
720            own("anchor", "id"),
721            data_as("name", "heading"),
722            data("level"),
723            data_as("in_toc", "toc"),
724            dropped("number", "the number stands in the content"),
725        ],
726        style: Some(STYLE_CORE),
727    },
728    Convention {
729        element: pres::SPAN,
730        tag: TagRule::SpanStyle,
731        fields: &[
732            own("anchor", "id"),
733            role("role"),
734            own("doc_role", "role"),
735            data("style"),
736            data_as("kinds", "kind"),
737        ],
738        style: Some(STYLE_CORE),
739    },
740    Convention {
741        element: pres::LIST,
742        tag: TagRule::ListKind,
743        fields: &[
744            own("anchor", "id"),
745            data_as("kinds", "kind"),
746            entry("entry_anchors", "id"),
747            // The token of a heading's `level`, so that one selector
748            // matches the headings and the entries of a level.
749            entry_data("entry_levels", "level"),
750        ],
751        style: Some(STYLE_LISTS),
752    },
753    Convention {
754        element: pres::CELLS,
755        tag: TagRule::Fixed("table"),
756        fields: &[
757            dropped(
758                "rows",
759                "the grid's size is its shape: one `<tr>` per row, and in it one element per \
760                 position a span does not cover, an empty `<td>` where there is no cell",
761            ),
762            dropped("cols", "the grid's size is its shape, as for `rows`"),
763            dropped(
764                "cells",
765                "each entry is a `<td>`, or a `<th>` for a header, at its top-left position, \
766                 holding its `cell` slot, its fields written as the attributes of each entry",
767            ),
768            entry("row_span", "rowspan"),
769            entry("col_span", "colspan"),
770            entry("header", "scope"),
771            entry_data("align", "align"),
772            entry_data("rules", "rules"),
773            entry_data("styles", "style-"),
774        ],
775        style: Some(crate::stdlib::features::cells::STYLE),
776    },
777    Convention {
778        element: pres::LINES,
779        tag: TagRule::Fixed("div"),
780        fields: &[],
781        style: Some(STYLE_LISTS),
782    },
783    Convention {
784        element: pres::LINE,
785        tag: TagRule::Fixed("div"),
786        fields: &[style("indent_left"), style("indent_right"), data("align")],
787        style: Some(STYLE_LISTS),
788    },
789    Convention {
790        element: pres::VERBATIM,
791        tag: TagRule::VerbatimKindAndDisplay,
792        fields: &[data("kind"), data("display"), data("lang")],
793        style: Some(STYLE_VERBATIM),
794    },
795    Convention {
796        element: pres::MATH_PASSTHROUGH,
797        // One tag for both displays: a displayed formula can stand inside a
798        // paragraph, where HTML allows no block element.
799        tag: TagRule::Fixed("span"),
800        fields: &[role("role"), data("display"), data("env")],
801        style: Some(STYLE_MATH_PASSTHROUGH),
802    },
803    Convention {
804        element: pres::MATH_TEXT,
805        tag: TagRule::Fixed("span"),
806        fields: &[
807            own("anchor", "id"),
808            data("command"),
809            dropped(
810                "at_tag",
811                "the content is written at the position of an equation line's tag; no attribute: a \
812                 pair of dollar signs is written around the element instead, inside the \
813                 formula",
814            ),
815        ],
816        style: Some(STYLE_MATH_PASSTHROUGH),
817    },
818    Convention {
819        element: pres::LINK,
820        tag: TagRule::Fixed("a"),
821        fields: &[
822            own("href", "href"),
823            own("doc_role", "role"),
824            own("label", "aria-label"),
825            data("kind"),
826        ],
827        style: Some(STYLE_CORE),
828    },
829    Convention {
830        element: pres::IMAGE,
831        tag: TagRule::Fixed("img"),
832        fields: &[
833            own("anchor", "id"),
834            own("src", "src"),
835            block_class("display"),
836            own("alt", "alt"),
837            own("srcset", "srcset"),
838            style("width"),
839            style("height"),
840            // CSS cannot divide one length by another, so the image's proportions
841            // reach the stylesheet as a ratio of their own, which keeps them on a
842            // page narrower than the image.
843            ratio("aspect_ratio", "width", "height"),
844        ],
845        style: Some(STYLE_CORE),
846    },
847    Convention {
848        element: pres::UNSUPPORTED,
849        tag: TagRule::Fixed("span"),
850        fields: &[
851            data("element"),
852            dropped("message", "the reason is reported as a diagnostic, not shown in the page"),
853        ],
854        style: Some(STYLE_ERRORS),
855    },
856    Convention {
857        element: pres::DROPPED,
858        tag: TagRule::Fixed("span"),
859        fields: &[
860            data("condition"),
861            dropped(
862                "detail",
863                "written as the element's content, after `dropped: `, so that it shows without a \
864                 stylesheet",
865            ),
866        ],
867        style: Some(STYLE_ERRORS),
868    },
869    Convention {
870        element: pres::UNKNOWN,
871        tag: TagRule::Display { inline: "span", block: "div" },
872        fields: &[
873            data("kind"),
874            data("name"),
875            dropped(
876                "spelling",
877                "what the author typed, written as the element's content: a macro's spelling, an \
878                 environment's `\\begin` and `\\end` lines",
879            ),
880        ],
881        style: Some(STYLE_ERRORS),
882    },
883    Convention {
884        element: pres::DECO_RUNIN,
885        tag: TagRule::Fixed("span"),
886        fields: &[],
887        style: Some(STYLE_CORE),
888    },
889    Convention {
890        element: pres::DECO_FINAL,
891        tag: TagRule::Fixed("span"),
892        fields: &[],
893        style: Some(STYLE_CORE),
894    },
895    Convention {
896        element: pres::DECO_MARGIN,
897        tag: TagRule::Fixed("span"),
898        fields: &[],
899        style: Some(STYLE_CORE),
900    },
901    Convention {
902        element: pres::DECO_MARK,
903        tag: TagRule::None,
904        fields: &[dropped("slot", "identifies the decoration written in the mark's place")],
905        style: None,
906    },
907    Convention {
908        element: pres::SUBTREE,
909        tag: TagRule::None,
910        fields: &[dropped("tree", "identifies the document tree written in the node's place")],
911        style: None,
912    },
913];
914
915/// Returns the value of the `role` attribute written for the document role `role`:
916/// `doc-` followed by the role's stable name ([`DocRole::as_str`]) —
917/// `doc-endnotes`, `doc-footnote`, `doc-noteref`, `doc-backlink`,
918/// `doc-bibliography`, `doc-biblioref` and `doc-toc`, the roles the
919/// digital-publishing accessibility vocabulary defines for notes, cited works
920/// and a table of contents.
921///
922/// # Examples
923///
924/// ```
925/// use flm_core::stdlib::backends::html::conventions::doc_role_value;
926/// use flm_core::stdlib::backends::pres::DocRole;
927///
928/// assert_eq!(doc_role_value(DocRole::NoteRef), "doc-noteref");
929/// assert_eq!(doc_role_value(DocRole::Toc), "doc-toc");
930/// ```
931pub fn doc_role_value(role: DocRole) -> String {
932    format!("doc-{}", role.as_str())
933}
934
935/// Returns the row of the presentation element `element`, or `None` when the
936/// name is not one of the vocabulary's. The emitter looks each node's row up
937/// with it.
938///
939/// # Examples
940///
941/// ```
942/// use flm_core::stdlib::backends::html::conventions::row;
943/// use flm_core::stdlib::backends::pres;
944///
945/// let heading = row(pres::BLOCK_HEADING).expect("a row for every element");
946/// assert_eq!(heading.field("level").and_then(|f| f.attribute()).as_deref(),
947///            Some("data-flm-level"));
948/// assert!(row("flm.pres.nothing").is_none());
949/// ```
950pub fn row(element: &str) -> Option<&'static Convention> {
951    CONVENTIONS.iter().find(|convention| convention.element == element)
952}
953
954/// Returns the HTML contract as a Markdown table: one line per element, with
955/// the element's name, the tag, the classes, the attributes, what is dropped
956/// and the style definition.
957///
958/// The [rendering guide](crate::guide::rendering#the-html-contract) holds this
959/// table, and a test compares it with this function's result, so that the
960/// guide cannot fall behind the code.
961///
962/// # Examples
963///
964/// ```
965/// use flm_core::stdlib::backends::html::conventions::markdown_table;
966///
967/// let table = markdown_table();
968/// assert!(table.starts_with("| element | tag |"));
969/// assert!(table.contains("`flm.pres.par`"));
970/// ```
971pub fn markdown_table() -> String {
972    let mut out = String::from(
973        "| element | tag | classes | attributes | dropped | style definition |\n\
974         |---|---|---|---|---|---|\n",
975    );
976    for convention in CONVENTIONS {
977        let writes_an_element = convention.tag != TagRule::None;
978        let mut classes = if writes_an_element {
979            vec![format!("`{}`", convention.class())]
980        } else {
981            Vec::new()
982        };
983        let mut attributes: Vec<String> = Vec::new();
984        let mut dropped: Vec<String> = Vec::new();
985        let properties: Vec<String> = convention
986            .fields
987            .iter()
988            .filter_map(|field| {
989                field.style_property().map(|property| match field.written {
990                    Written::Ratio(first, second) => {
991                        format!("`{first}` ÷ `{second}` as `{property}`")
992                    }
993                    _ => format!("`{}` as `{property}`", field.field),
994                })
995            })
996            .collect();
997        let mut style_written = false;
998        for field in convention.fields {
999            match field.written {
1000                Written::Style | Written::Ratio(..) => {
1001                    // The row's length fields share one attribute, printed
1002                    // where the first of them stands.
1003                    if !style_written {
1004                        attributes.push(format!(
1005                            "`{STYLE_ATTRIBUTE}` ← {} (custom properties, none for a zero length)",
1006                            properties.join(", ")
1007                        ));
1008                        style_written = true;
1009                    }
1010                }
1011                Written::Own(name) => {
1012                    attributes.push(format!("`{name}` ← `{}`", field.field));
1013                }
1014                Written::Data(stem) => {
1015                    attributes.push(format!("`{}` ← `{}`", data_attribute(stem), field.field));
1016                }
1017                Written::Entry(_) | Written::EntryData(_) => {
1018                    if let Some(name) = field.entry_attribute() {
1019                        // A family is spelled with the place of the value's name.
1020                        let place = if name.ends_with('-') { "<name>" } else { "" };
1021                        attributes.push(format!("each entry's `{name}{place}` ← `{}`", field.field));
1022                    }
1023                }
1024                Written::RoleClass => classes.push(String::from("the role's own class")),
1025                Written::BlockClass => classes.push(format!(
1026                    "`{}` before it where `{}` is `block`",
1027                    class_of_element(pres::BLOCK),
1028                    field.field
1029                )),
1030                Written::Dropped(why) => dropped.push(format!("`{}` ({why})", field.field)),
1031            }
1032        }
1033        let join = |parts: Vec<String>| {
1034            if parts.is_empty() { String::from("—") } else { parts.join(", ") }
1035        };
1036        out.push_str(&format!(
1037            "| `{}` | {} | {} | {} | {} | {} |\n",
1038            convention.element,
1039            convention.tag.describe(),
1040            join(classes),
1041            join(attributes),
1042            join(dropped),
1043            convention.style.map_or_else(|| String::from("—"), |style| format!("`{style}`")),
1044        ));
1045    }
1046    out
1047}
1048
1049#[cfg(test)]
1050mod tests {
1051    use super::*;
1052
1053    #[test]
1054    fn every_element_of_the_vocabulary_has_exactly_one_row() {
1055        assert_eq!(CONVENTIONS.len(), pres::ALL.len());
1056        for element in pres::ALL {
1057            assert!(row(element).is_some(), "no row for `{element}`");
1058        }
1059        for convention in CONVENTIONS {
1060            assert!(
1061                pres::ALL.contains(&convention.element),
1062                "`{}` is not an element of the vocabulary",
1063                convention.element
1064            );
1065        }
1066    }
1067
1068    #[test]
1069    fn a_rows_attribute_names_are_writable_and_occur_once() {
1070        for convention in CONVENTIONS {
1071            let mut names: Vec<String> =
1072                convention.fields.iter().filter_map(|field| field.attribute()).collect();
1073            let count = names.len();
1074            names.sort();
1075            names.dedup();
1076            assert_eq!(names.len(), count, "`{}` writes one attribute twice", convention.element);
1077            // What an entry carries stands on another element than the
1078            // row's own, so it is held to the same checks apart.
1079            let mut entry: Vec<String> = convention
1080                .fields
1081                .iter()
1082                .filter_map(|field| field.entry_attribute())
1083                .collect();
1084            let count = entry.len();
1085            entry.sort();
1086            entry.dedup();
1087            assert_eq!(entry.len(), count, "`{}` writes one attribute twice", convention.element);
1088            for name in names.into_iter().chain(entry) {
1089                assert!(
1090                    super::super::names::is_valid_attribute_name(&name),
1091                    "`{name}` is not writable"
1092                );
1093            }
1094        }
1095    }
1096
1097    #[test]
1098    fn a_length_is_spelled_as_a_css_length_in_every_unit() {
1099        let spelled = |text: &str| css_length(&Length::parse(text).expect("a length"));
1100        assert_eq!(css_length(&Length::tabs(1)), "calc(1 * var(--flm-tab))");
1101        assert_eq!(css_length(&Length::tabs(2)), "calc(2 * var(--flm-tab))");
1102        assert_eq!(spelled("1.5tab"), "calc(1.5 * var(--flm-tab))");
1103        assert_eq!(spelled("-1tab"), "calc(-1 * var(--flm-tab))");
1104        assert_eq!(spelled("1.5em"), "1.5em");
1105        assert_eq!(spelled("10pt"), "10pt");
1106        assert_eq!(spelled("3mm"), "3mm");
1107        assert_eq!(spelled("2cm"), "2cm");
1108        assert_eq!(spelled("0.25in"), "0.25in");
1109        assert_eq!(spelled(".5in"), "0.5in");
1110        // Every unit has its spelling, the tab alone going through the
1111        // custom property.
1112        for unit in LengthUnit::ALL {
1113            let css = css_length(&Length::new(Length::tabs(3).amount, unit));
1114            if unit == LengthUnit::Tabs {
1115                assert_eq!(css, format!("calc(3 * var({TAB_PROPERTY}))"));
1116            } else {
1117                assert_eq!(css, format!("3{}", unit.as_str()));
1118            }
1119        }
1120    }
1121
1122    #[test]
1123    fn a_length_field_is_a_custom_property_of_the_style_attribute_and_nothing_else() {
1124        let line = row(pres::LINE).expect("a row");
1125        let properties: Vec<String> =
1126            line.fields.iter().filter_map(|field| field.style_property()).collect();
1127        assert_eq!(properties, ["--flm-element-indent-left", "--flm-element-indent-right"]);
1128        // Written once: no `data-flm-…` attribute beside the property.
1129        let attributes: Vec<String> = line.fields.iter().filter_map(|field| field.attribute()).collect();
1130        assert_eq!(attributes, ["data-flm-align"]);
1131        // No row writes a length field any other way, and no two fields of a
1132        // row share a property.
1133        for convention in CONVENTIONS {
1134            let mut names: Vec<String> =
1135                convention.fields.iter().filter_map(|field| field.style_property()).collect();
1136            let count = names.len();
1137            names.sort();
1138            names.dedup();
1139            assert_eq!(names.len(), count, "`{}` writes one property twice", convention.element);
1140        }
1141    }
1142
1143    #[test]
1144    fn the_printed_row_of_a_line_reads_the_two_properties() {
1145        let table = markdown_table();
1146        let line = table
1147            .lines()
1148            .find(|line| line.starts_with("| `flm.pres.line` |"))
1149            .expect("the row");
1150        assert!(
1151            line.contains(
1152                "`style` ← `indent_left` as `--flm-element-indent-left`, `indent_right` as \
1153                 `--flm-element-indent-right`"
1154            ),
1155            "{line}"
1156        );
1157        assert!(!line.contains("data-flm-indent"), "{line}");
1158    }
1159
1160    #[test]
1161    fn every_document_role_is_written_as_a_digital_publishing_role() {
1162        let values: Vec<String> = DocRole::ALL.into_iter().map(doc_role_value).collect();
1163        assert_eq!(
1164            values,
1165            [
1166                "doc-endnotes",
1167                "doc-footnote",
1168                "doc-noteref",
1169                "doc-backlink",
1170                "doc-bibliography",
1171                "doc-biblioref",
1172                "doc-toc"
1173            ]
1174        );
1175    }
1176
1177    #[test]
1178    fn the_printed_table_holds_one_line_per_element() {
1179        let table = markdown_table();
1180        // The header and its separator, then one line per element.
1181        assert_eq!(table.lines().count(), pres::ALL.len() + 2);
1182        for element in pres::ALL {
1183            assert!(table.contains(&format!("| `{element}` |")), "`{element}` is not in the table");
1184        }
1185    }
1186}