Skip to main content

flm_core/stdlib/features/cells/
styles.rs

1//! The cell styles of the tables of cells: what a style token written in
2//! the angle brackets of `\cell<…>` or `\celldata<…>` states about a cell.
3//!
4//! Every style token an author writes refers by name to a **cell style**, a
5//! declaration ([`CellStyle`]) contributed to the feature's service slot
6//! [`STYLES_SLOT`]. A service slot is the declaration, by the feature that
7//! owns an interaction, of a dotted name, the type of the values the slot
8//! takes and its arity; any feature, and the program embedding the library,
9//! may contribute values to it (see [services](crate::core::services)). A
10//! cell style says what the
11//! token states about the cell, one of four [`Effect`]s, each a fact that
12//! holds regardless of the output format, and lists the definitions a
13//! backend needs where a cell uses the style ([`CellStyle::requires`]): for
14//! example a style definition on HTML and a definition piece on the
15//! recomposed LaTeX. A
16//! cell style carries no code, so no cell style can change a cell's content
17//! or the table's model.
18//!
19//! A token is a name, optionally followed by a value in braces: `r`,
20//! `align{right}`. A cell style of the fixed form ([`StyleForm::Fixed`])
21//! takes no value; one of the structural form ([`StyleForm::Structural`])
22//! takes exactly one, which its [`Parameter`] reads. The feature ships
23//! ([`shipped`]):
24//!
25//! - three structural styles: `align{left|center|right}`, `head{column|row}`
26//!   and `rule{above|below|left|right}` (a rule: a line drawn along an edge
27//!   of the cell);
28//! - their short forms: `l`, `c`, `r`, `H` (a column header), `rH` (a row
29//!   header), `lvert` and `rvert` (a rule at the left or the right edge);
30//! - four custom styles, `green`, `blue`, `yellow` and `red`, to which the
31//!   feature's HTML style definition and its LaTeX definition piece give a
32//!   background.
33//!
34//! The [guide on extending FLM](crate::guide::extending#a-cell-style-of-your-own)
35//! shows how a feature declares a cell style of its own.
36
37use std::collections::BTreeMap;
38use std::fmt;
39use std::sync::{Arc, OnceLock};
40
41use crate::core::registry::{BuildError, FeatureBuilder, Finalizer};
42use crate::model::names::{BackendName, Name};
43use crate::stdlib::backends::pres::{CellAlign, CellEdge, CellHeader};
44use crate::stdlib::backends::{html, latex_recomposed, latex_rendered};
45
46use super::{LATEX_PIECE, STYLE, STYLES_SLOT};
47
48/// What a style token states about a cell: a fact that holds regardless of
49/// the output format, which each backend renders in its own way or
50/// ignores.
51#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
52pub enum Effect {
53    /// The cell's alignment. Of the tokens of one cell that give an
54    /// alignment, the first decides.
55    Align(CellAlign),
56    /// The cell is a header of its column or of its row. Of the tokens of one
57    /// cell that give a header kind, the first decides.
58    Header(CellHeader),
59    /// A rule is drawn at this edge of the cell. Every edge that a token lists is drawn.
60    Rule(CellEdge),
61    /// The cell carries the style by its name. Each backend writes the name
62    /// in a form of its own (the attribute `data-flm-style-<name>` on HTML,
63    /// the table command `\flmCellsSet{<name>}` at the start of the cell's
64    /// text on the recomposed LaTeX), and the definitions that the style
65    /// requires on that backend give the name its meaning; the text backend
66    /// shows nothing. Every custom style a cell's tokens refer to is carried,
67    /// in the order of the tokens.
68    Custom,
69}
70
71/// The parameter of a structural style: which values its token takes, and the
72/// effect of each.
73#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
74pub enum Parameter {
75    /// `left`, `center` or `right`: the cell's alignment.
76    Align,
77    /// `column` or `row`: the cell heads its column or its row.
78    Head,
79    /// `above`, `below`, `left` or `right`: a rule at that edge.
80    Rule,
81}
82
83impl Parameter {
84    /// The values the parameter takes, in order.
85    pub fn values(self) -> &'static [&'static str] {
86        match self {
87            Parameter::Align => &["left", "center", "right"],
88            Parameter::Head => &["column", "row"],
89            Parameter::Rule => &["above", "below", "left", "right"],
90        }
91    }
92
93    /// The effect of the value `value`, when the parameter takes it.
94    pub fn effect(self, value: &str) -> Option<Effect> {
95        match self {
96            Parameter::Align => CellAlign::parse(value).map(Effect::Align),
97            Parameter::Head => CellHeader::parse(value).map(Effect::Header),
98            Parameter::Rule => CellEdge::parse(value).map(Effect::Rule),
99        }
100    }
101}
102
103/// How a style token is written: with no value, or with one value in braces.
104#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
105pub enum StyleForm {
106    /// A token with no value, stating one effect: `l`, `H`, `green`.
107    Fixed(Effect),
108    /// A token with one value in braces, which the parameter reads:
109    /// `align{left}`. The feature's own three styles have this form.
110    Structural(Parameter),
111}
112
113/// One definition that a backend needs where a cell carries a cell style:
114/// the backend, and the identifier of the definition it requires there (a
115/// style or script definition on HTML, a definition piece or a package
116/// request on the recomposed LaTeX).
117#[derive(Debug, Clone, PartialEq, Eq, Hash)]
118pub struct StyleRequirement {
119    /// The backend the definition belongs to (`html`, `latex-recomposed`).
120    pub backend: BackendName,
121    /// The definition's identifier.
122    pub id: Name,
123}
124
125/// A cell style: the name an author writes in a cell's angle brackets, what
126/// it states about the cell, and the definitions a backend needs where a cell
127/// carries it.
128///
129/// A feature contributes one to the service slot [`STYLES_SLOT`] with
130/// `b.peer_slot::<CellStyle>(STYLES_SLOT, Arc::new(style))`: a peer
131/// contribution, a contribution to a service slot another feature owns,
132/// which the registry build drops with one Note when that feature is not
133/// registered, so that the contributing feature still builds in a registry
134/// without the `cells` feature. Two cell styles of one name are a registry
135/// build error, whoever contributes them, so a cell style the feature ships
136/// cannot be declared again. What a shipped custom style shows is changed
137/// through its definitions instead: on HTML, the custom properties of the
138/// feature's stylesheet (`--flm-cells-green` and the three others); on the
139/// recomposed LaTeX, the command `\flmCellsKeys<name>` (see the
140/// [rendering guide](crate::guide::rendering#tables-of-cells-in-the-recomposed-latex)).
141///
142/// # Examples
143///
144/// A custom style `orange`, which a style definition `host.orange` colors
145/// on HTML and a definition piece `host.latex.orange` on the recomposed
146/// LaTeX:
147///
148/// ```
149/// use flm_core::stdlib::backends::{html, latex_recomposed};
150/// use flm_core::stdlib::features::cells::{CellStyle, Effect, StyleForm};
151///
152/// let orange = CellStyle::custom("orange", "an orange background")
153///     .requires(html::BACKEND, ["host.orange"])
154///     .requires(latex_recomposed::BACKEND, ["host.latex.orange"]);
155/// assert_eq!(orange.form, StyleForm::Fixed(Effect::Custom));
156/// assert_eq!(orange.requirements_on(html::BACKEND).count(), 1);
157/// ```
158#[derive(Debug, Clone, PartialEq, Eq)]
159pub struct CellStyle {
160    /// The token's name: ASCII letters and digits, beginning with a letter.
161    /// A custom style's name is lowercase, since it becomes part of the name
162    /// of an HTML attribute, which HTML reads without regard to case.
163    pub name: Name,
164    /// What the style does, as a sentence, for generated reference
165    /// documentation. The constructors ([`fixed`](CellStyle::fixed),
166    /// [`custom`](CellStyle::custom), [`structural`](CellStyle::structural))
167    /// leave it empty when the crate is built without its cargo feature `docs`.
168    pub docs: String,
169    /// How the token is written and what it states.
170    pub form: StyleForm,
171    /// The definitions each backend needs where a cell carries the style.
172    /// The rule that lowers a table requires those of the backend it runs on,
173    /// and none of any other backend.
174    pub requires: Vec<StyleRequirement>,
175}
176
177impl CellStyle {
178    /// A cell style of the fixed form, stating `effect` and requiring
179    /// nothing.
180    pub fn fixed(name: impl Into<Name>, docs: impl Into<String>, effect: Effect) -> CellStyle {
181        CellStyle {
182            name: name.into(),
183            docs: crate::kept_docs(docs),
184            form: StyleForm::Fixed(effect),
185            requires: Vec::new(),
186        }
187    }
188
189    /// A custom style: a cell style of the fixed form that the cell carries
190    /// by its name ([`Effect::Custom`]), requiring nothing yet; add its
191    /// definitions with [`requires`](CellStyle::requires).
192    pub fn custom(name: impl Into<Name>, docs: impl Into<String>) -> CellStyle {
193        CellStyle::fixed(name, docs, Effect::Custom)
194    }
195
196    /// A cell style of the structural form, which reads its value through
197    /// `parameter`.
198    pub fn structural(name: impl Into<Name>, docs: impl Into<String>, parameter: Parameter) -> CellStyle {
199        CellStyle {
200            name: name.into(),
201            docs: crate::kept_docs(docs),
202            form: StyleForm::Structural(parameter),
203            requires: Vec::new(),
204        }
205    }
206
207    /// Builder: adds the definitions `ids`, which `backend` needs where a
208    /// cell carries the style.
209    pub fn requires(
210        mut self,
211        backend: impl Into<BackendName>,
212        ids: impl IntoIterator<Item = impl Into<Name>>,
213    ) -> CellStyle {
214        let backend = backend.into();
215        self.requires
216            .extend(ids.into_iter().map(|id| StyleRequirement { backend: backend.clone(), id: id.into() }));
217        self
218    }
219
220    /// The identifiers of the definitions `backend` needs where a cell
221    /// carries the style, in order.
222    pub fn requirements_on<'s>(&'s self, backend: &'s str) -> impl Iterator<Item = &'s Name> + 's {
223        self.requires.iter().filter(move |r| r.backend.as_str() == backend).map(|r| &r.id)
224    }
225}
226
227/// Whether `name` is a style's name: an ASCII letter, then ASCII letters and
228/// digits.
229pub(super) fn is_style_name(name: &str) -> bool {
230    let mut chars = name.chars();
231    chars.next().is_some_and(|first| first.is_ascii_alphabetic())
232        && chars.all(|ch| ch.is_ascii_alphanumeric())
233}
234
235/// The cell styles the feature ships, in the order it contributes them:
236/// `align`, `head`, `rule`; `l`, `c`, `r`, `H`, `rH`, `lvert`, `rvert`; and the
237/// four custom styles `green`, `blue`, `yellow`, `red`, each requiring the
238/// feature's style definition [`STYLE`] on HTML and on the rendered LaTeX
239/// (where the feature's piece delivers it) and its definition piece
240/// [`LATEX_PIECE`] on the recomposed LaTeX.
241pub fn shipped() -> Vec<CellStyle> {
242    let mut styles = vec![
243        CellStyle::structural("align", "the cell's alignment: `align{left}`, `align{center}`, `align{right}`", Parameter::Align),
244        CellStyle::structural("head", "the cell heads its column or its row: `head{column}`, `head{row}`", Parameter::Head),
245        CellStyle::structural(
246            "rule",
247            "a line drawn along an edge of the cell: `rule{above}`, `rule{below}`, `rule{left}`, \
248             `rule{right}`",
249            Parameter::Rule,
250        ),
251        CellStyle::fixed("l", "the cell aligned left, as `align{left}`", Effect::Align(CellAlign::Left)),
252        CellStyle::fixed("c", "the cell centered, as `align{center}`", Effect::Align(CellAlign::Center)),
253        CellStyle::fixed("r", "the cell aligned right, as `align{right}`", Effect::Align(CellAlign::Right)),
254        CellStyle::fixed("H", "the cell heads its column, as `head{column}`", Effect::Header(CellHeader::Column)),
255        CellStyle::fixed("rH", "the cell heads its row, as `head{row}`", Effect::Header(CellHeader::Row)),
256        CellStyle::fixed(
257            "lvert",
258            "a line drawn along the cell's left edge, as `rule{left}`",
259            Effect::Rule(CellEdge::Left),
260        ),
261        CellStyle::fixed(
262            "rvert",
263            "a line drawn along the cell's right edge, as `rule{right}`",
264            Effect::Rule(CellEdge::Right),
265        ),
266    ];
267    for color in ["green", "blue", "yellow", "red"] {
268        styles.push(
269            CellStyle::custom(color, format!("a {color} background, which sets the cell apart"))
270                .requires(html::BACKEND, [STYLE])
271                .requires(latex_recomposed::BACKEND, [LATEX_PIECE])
272                .requires(latex_rendered::BACKEND, [STYLE]),
273        );
274    }
275    styles
276}
277
278/// The cell styles of a registry, by name: every contribution to the service
279/// slot [`STYLES_SLOT`], collected by the feature's build hook
280/// ([`Finalizer`]) once the slot holds them all. The feature's rules hold
281/// this collection, because a rule has no access to the registry's services
282/// while it runs.
283#[derive(Default)]
284pub struct Styles {
285    by_name: OnceLock<BTreeMap<Name, Arc<CellStyle>>>,
286}
287
288impl Styles {
289    /// A collection filled from `styles` directly, for a caller that reads a
290    /// table of cells outside a registry, such as a test of the reader
291    /// ([`read_grid`](super::read_grid)).
292    pub fn of(styles: impl IntoIterator<Item = CellStyle>) -> Styles {
293        let by_name = styles.into_iter().map(|style| (style.name.clone(), Arc::new(style))).collect();
294        let collected = Styles::default();
295        let _ = collected.by_name.set(by_name);
296        collected
297    }
298
299    /// The cell style of the name `name`, if the registry holds one.
300    pub fn get(&self, name: &str) -> Option<&CellStyle> {
301        self.by_name.get()?.get(name).map(|style| style.as_ref())
302    }
303
304    /// Every cell style, in the order of their names.
305    pub fn iter(&self) -> impl Iterator<Item = &CellStyle> + '_ {
306        self.by_name.get().into_iter().flat_map(|by_name| by_name.values().map(|style| style.as_ref()))
307    }
308}
309
310impl fmt::Debug for Styles {
311    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
312        let names: Vec<&str> = self.iter().map(|style| style.name.as_str()).collect();
313        f.debug_struct("Styles").field("names", &names).finish()
314    }
315}
316
317/// The feature's build hook ([`Finalizer`]): it reads every contribution to
318/// the service slot [`STYLES_SLOT`] into the feature's [`Styles`], and fails
319/// the registry build on a name that is not a valid style name, on a custom
320/// style's name that is not lowercase, and on two cell styles of one name.
321pub(super) struct CollectStyles {
322    pub(super) styles: Arc<Styles>,
323}
324
325impl Finalizer for CollectStyles {
326    fn finalize(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
327        let refuse = |b: &FeatureBuilder<'_>, detail: String| BuildError::Feature {
328            feature: b.feature().clone(),
329            detail,
330        };
331        let Some(services) = b.services() else {
332            return Err(refuse(b, "the styles slot must be assembled before the finalizer runs".into()));
333        };
334        let mut by_name: BTreeMap<Name, Arc<CellStyle>> = BTreeMap::new();
335        for style in services.shared_named::<CellStyle>(STYLES_SLOT) {
336            let name = style.name.as_str();
337            if !is_style_name(name) {
338                return Err(refuse(
339                    b,
340                    format!(
341                        "the cell style name `{name}` must begin with an ASCII letter and hold only \
342                         ASCII letters and digits"
343                    ),
344                ));
345            }
346            if style.form == StyleForm::Fixed(Effect::Custom) && name.chars().any(|ch| ch.is_ascii_uppercase()) {
347                return Err(refuse(b, format!("the custom cell style name `{name}` must be lowercase")));
348            }
349            if by_name.insert(style.name.clone(), Arc::clone(style)).is_some() {
350                return Err(refuse(b, format!("the cell style `{name}` may not be declared twice")));
351            }
352        }
353        if self.styles.by_name.set(by_name).is_err() {
354            return Err(refuse(b, "the feature may be registered at most once in a registry".into()));
355        }
356        Ok(())
357    }
358}
359
360#[cfg(test)]
361mod tests {
362    use super::*;
363
364    #[test]
365    fn the_shipped_styles_are_the_python_tokens_and_the_three_structural_ones() {
366        let names: Vec<String> = shipped().iter().map(|style| style.name.to_string()).collect();
367        assert_eq!(
368            names,
369            ["align", "head", "rule", "l", "c", "r", "H", "rH", "lvert", "rvert", "green", "blue", "yellow", "red"]
370        );
371        assert!(shipped().iter().all(|style| is_style_name(style.name.as_str())));
372    }
373
374    #[test]
375    fn a_custom_shipped_style_requires_the_chunk_on_html_and_the_piece_on_latex() {
376        let green = shipped().into_iter().find(|style| style.name.as_str() == "green").expect("green");
377        assert_eq!(green.requirements_on(html::BACKEND).map(Name::as_str).collect::<Vec<_>>(), [STYLE]);
378        assert_eq!(
379            green.requirements_on(latex_recomposed::BACKEND).map(Name::as_str).collect::<Vec<_>>(),
380            [LATEX_PIECE]
381        );
382        assert_eq!(
383            green.requirements_on(latex_rendered::BACKEND).map(Name::as_str).collect::<Vec<_>>(),
384            [STYLE]
385        );
386        assert_eq!(green.requirements_on("text").count(), 0);
387    }
388
389    #[test]
390    fn a_parameter_reads_its_values() {
391        assert_eq!(Parameter::Align.effect("right"), Some(Effect::Align(CellAlign::Right)));
392        assert_eq!(Parameter::Head.effect("row"), Some(Effect::Header(CellHeader::Row)));
393        assert_eq!(Parameter::Rule.effect("above"), Some(Effect::Rule(CellEdge::Above)));
394        assert_eq!(Parameter::Align.effect("middle"), None);
395    }
396}