Skip to main content

flm_core/stdlib/features/floats/
elements.rs

1//! The element of the [`floats`](super) feature and its declarations: the
2//! element `flm.floats.float` with one element value per float type
3//! ([`FloatElement`]), the environment of each float type, the scoped package
4//! of `\caption`, `\label` and `\nonumber`, the counter and counter style of
5//! each float type, and the float's reference point ([`float_point`]).
6//!
7//! [`contribute_type`] makes every declaration a float type needs. The
8//! `floats` feature calls it for each float type of its configuration, and
9//! another feature calls it to declare a float type of its own, so that every
10//! float type is declared in the same way.
11
12use std::sync::Arc;
13
14use techy::core::node::NodeRef;
15
16use crate::core::registry::{BuildError, FeatureBuilder};
17use crate::lang::Flm;
18use crate::lang::mint::parsers::code_span;
19use crate::lang::mint::{
20    ArgDef, ArgStdKind, BodyDef, ElementDef, ScopedPackageDef, SyntaxDef, field_element,
21};
22use crate::model::aspects::{
23    AcceptedRefTypes, AnchorPolicy, BlockRole, BlockRoleAspect, FixedBlockRole, NumberSource,
24    PointId, RefPoint, Referenceable,
25};
26use crate::model::addr::NodeAddr;
27use crate::model::element::ElementSpec;
28use crate::model::names::{FeatureName, Name, RefKind};
29use crate::stdlib::features::numbering::{
30    COUNTERS_SLOT, CounterDecl, CounterStyleDecl, JoinDecl, STYLES_SLOT,
31};
32use crate::stdlib::features::refs;
33
34use super::body::{float_fields, label_uses};
35use super::config::FloatType;
36use super::{
37    CAPTION_FIELD, CAPTION_OPTIONS_ARG, CAPTION_TEXT_ARG, FIELDS_PACKAGE, FLOAT,
38    NONUMBER_FIELD, TYPES_SLOT, counter_name, style_name,
39};
40
41/// The data of one element value of [`FLOAT`] (`flm.floats.float`): the
42/// float type whose environment the value declares. There is one element
43/// value per float type.
44///
45/// It implements [`Referenceable`]: every float is one reference point.
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub struct FloatElement {
48    /// The float type, as configured or contributed.
49    pub float_type: Arc<FloatType>,
50}
51
52/// Returns the identity of the reference point of the float at `addr`: a
53/// float has exactly one point, the first (index 0).
54pub fn float_point(addr: NodeAddr) -> PointId {
55    PointId { addr, index: 0 }
56}
57
58/// One reference point per float ([reference points, labels and
59/// anchors](crate::guide::concepts_overview#reference-points-labels-and-anchors)):
60///
61/// - of the reference kind of the float type's name;
62/// - carrying the labels written in the float's body, which must be of the
63///   type's accepted label types;
64/// - numbered in the type's counter and counter style where the type's
65///   numbering policy numbers the float;
66/// - showing, where the float has no number and has a caption, the caption's
67///   alternative text, else the caption's full content where its argument is
68///   one group or one token
69///   ([`Caption::shown_content`](super::Caption::shown_content));
70/// - with the anchor `<type>-<number>` (`figure-1`), else the anchor of its
71///   first label (`figure-photo`), else none
72///   ([`AnchorPolicy::FromValue`]).
73impl Referenceable for FloatElement {
74    fn points(&self, node: &NodeRef<'_, Flm>) -> Vec<RefPoint> {
75        let Some(fields) = float_fields(node) else { return Vec::new() };
76        let (labels, malformed) = refs::point_labels(&label_uses(&fields));
77        let name = self.float_type.name.as_str();
78        let number = fields.numbered.then(|| NumberSource {
79            counter: counter_name(name),
80            instances: Vec::new(),
81            style: style_name(name),
82            advance: vec![0],
83            number_format: None,
84        });
85        let content = fields.caption.as_ref().and_then(|caption| caption.shown_content(node));
86        vec![RefPoint {
87            kind: RefKind::from(name),
88            labels,
89            computed: 0,
90            malformed,
91            anchor: AnchorPolicy::FromValue { prefix: name.to_string() },
92            number,
93            content,
94            accepts: AcceptedRefTypes::these(self.float_type.label_types.iter().map(String::as_str)),
95        }]
96    }
97}
98
99/// Returns the element value of the float type `float_type`: a block, whose
100/// value is a [`FloatElement`] that declares the float's reference point.
101fn float_element(float_type: Arc<FloatType>) -> Arc<ElementSpec> {
102    let docs = format!("A float of the type `{}`.", float_type.name);
103    let value = Arc::new(FloatElement { float_type });
104    Arc::new(
105        ElementSpec::new(FLOAT)
106            .docs(docs)
107            .with::<dyn BlockRoleAspect>(Arc::new(FixedBlockRole(BlockRole::Block)))
108            .with::<dyn Referenceable>(Arc::clone(&value) as Arc<dyn Referenceable>)
109            .with_value(value),
110    )
111}
112
113/// Returns the declaration of the element type [`FLOAT`] itself, owned by
114/// `owner`: an element with no value, which no command writes and no node
115/// carries. The feature declares it so that the element its rules lower
116/// exists in every registry that holds the feature, including one whose
117/// configuration declares no float type.
118pub(super) fn float_type_def(owner: &FeatureName) -> ElementDef {
119    let element = Arc::new(
120        ElementSpec::new(FLOAT)
121            .docs(
122                "A float: one element value per float type, each written as the environment of \
123                 the type's name.",
124            )
125            .with::<dyn BlockRoleAspect>(Arc::new(FixedBlockRole(BlockRole::Block))),
126    );
127    ElementDef::new(owner.clone(), Vec::<&str>::new(), SyntaxDef::Synthesized, element)
128        .docs("The element of every float, with one element value per float type.")
129}
130
131/// Returns the declaration of the environment of `float_type`, owned by
132/// `owner`: no argument, and a body laid out in paragraphs and blocks that
133/// refers to the scoped package [`FIELDS_PACKAGE`] and to the type's own
134/// scoped packages. Available in text mode only.
135fn environment_def(owner: &FeatureName, float_type: &Arc<FloatType>) -> ElementDef {
136    let name = float_type.name.as_str();
137    let mut body = BodyDef::new().blocks().scoped(FIELDS_PACKAGE);
138    for package in &float_type.scoped_packages {
139        body = body.scoped(package.clone());
140    }
141    ElementDef::new(
142        owner.clone(),
143        [name],
144        SyntaxDef::Environment { args: Vec::new(), body },
145        float_element(Arc::clone(float_type)),
146    )
147    .docs(format!(
148        "Writes a float of the type `{name}`: its content, shown with the line under it that \
149         holds its number and its caption. The body may hold `\\caption`, `\\label` and \
150         `\\nonumber`{}.",
151        label_types_clause(&float_type.label_types)
152    ))
153}
154
155/// Returns the clause of a float command's text that names the label types
156/// of the float, `label_types`, each in a code span: "; a label of the float
157/// has the label type \`figure\`" for one, "; a label of the float has one of
158/// the label types \`figure\`, \`fig\`" for several, and nothing for none.
159fn label_types_clause(label_types: &[String]) -> String {
160    let spans: Vec<String> = label_types.iter().map(|label_type| code_span(label_type)).collect();
161    match spans.as_slice() {
162        [] => String::new(),
163        [one] => format!("; a label of the float has the label type {one}"),
164        several => format!("; a label of the float has one of the label types {}", several.join(", ")),
165    }
166}
167
168/// Returns the scoped package [`FIELDS_PACKAGE`] (`flm.floats.fields`),
169/// declared by `owner`, which holds the three commands of a float's body,
170/// each available in text mode: `\caption[alt=…]{…}`, whose optional argument
171/// holds key-value pairs and whose mandatory argument is inline content;
172/// `\nonumber`, with no argument; and `\label{…}`, the references feature's
173/// own declaration ([`refs::label_package`]), declared here under `owner` so
174/// that a label can be written in a float's body whether or not the
175/// references feature is registered.
176pub(super) fn fields_package(owner: &FeatureName) -> ScopedPackageDef {
177    let caption = ElementDef::new(
178        owner.clone(),
179        [CAPTION_FIELD],
180        SyntaxDef::Macro {
181            args: vec![
182                ArgDef::named(CAPTION_OPTIONS_ARG, ArgStdKind::KeyVals)
183                    .docs(
184                        "`alt=…`: the caption's alternative text, which a reference to an \
185                         unnumbered float shows.",
186                    ),
187                ArgDef::named(CAPTION_TEXT_ARG, ArgStdKind::Mandatory)
188                    .docs("The caption, shown under the float's content."),
189            ],
190        },
191        field_element(
192            "A `\\caption[alt=…]{…}` in a float's body: the float's caption.",
193        ),
194    )
195    .docs("Gives the float its caption, shown under its content.");
196    let nonumber = ElementDef::new(
197        owner.clone(),
198        [NONUMBER_FIELD],
199        SyntaxDef::Macro { args: Vec::new() },
200        field_element("A `\\nonumber` in a float's body: the float is not numbered."),
201    )
202    .docs("Marks the float as not numbered.");
203    let mut elements = vec![caption, nonumber];
204    elements.extend(refs::label_package(owner.clone()).elements);
205    ScopedPackageDef {
206        owner: owner.clone(),
207        name: Name::from(FIELDS_PACKAGE),
208        elements,
209        docs: String::from(
210            "The commands of a float's body, which the float reads: `\\caption[alt=…]{…}`, \
211             `\\label{…}` and `\\nonumber`.",
212        ),
213    }
214}
215
216/// Returns the declaration of the counter of `float_type`, `flm.floats.<type>`:
217/// shown in the type's counter style, and not numbered within another
218/// counter.
219fn counter(float_type: &FloatType) -> CounterDecl {
220    let name = float_type.name.as_str();
221    CounterDecl::new(counter_name(name), style_name(name))
222        .docs(format!("The numbered floats of the type `{name}`, in document order."))
223}
224
225/// Returns the declaration of the counter style of `float_type`,
226/// `flm.floats.style.<type>`: the type's words and number format, no
227/// delimiters, and several numbers joined compactly
228/// ([`JoinDecl::compact`]).
229fn style(float_type: &FloatType) -> CounterStyleDecl {
230    let mut style = CounterStyleDecl::new(style_name(float_type.name.as_str()));
231    style.number_format = float_type.number_format.clone();
232    style.prefix_words = float_type.words.clone();
233    style.join = JoinDecl::compact();
234    style
235}
236
237/// Makes every declaration the float type `float_type` needs, on behalf of
238/// the feature that `b` registers. The [`Floats`](super::Floats) feature calls
239/// it for the float types of its configuration, and another feature calls it
240/// for a float type it brings with its own content (for example a `listing`
241/// float of a feature for program code), so that every float type is declared
242/// in the same way.
243///
244/// Every declaration is a peer declaration or a peer contribution. A peer
245/// declaration ([`PeerName`](crate::core::registry::PeerName)) of an element,
246/// element type, table, service slot, scoped package or backend tells the
247/// registry build that another feature owns that name; a peer contribution is
248/// dropped with one Note when the feature that owns the service slot is not
249/// registered ([`core::services`](crate::core::services)). The calling feature
250/// therefore builds, and every registry holding it renders, without the
251/// `floats` feature or the `numbering` feature. The function makes:
252///
253/// - the type's environment, one more element value of the element type
254///   [`FLOAT`] (`flm.floats.float`), which the `floats` feature declares,
255///   attributed to the calling feature
256///   ([`peer_element_value`](FeatureBuilder::peer_element_value)): no
257///   argument, and a body laid out in paragraphs and blocks that refers to the
258///   scoped package [`FIELDS_PACKAGE`] and to the type's
259///   [`scoped_packages`](FloatType::scoped_packages). The `floats` feature's
260///   rules and stage handle it as they handle the feature's own types;
261/// - the contribution of the type to the service slot [`TYPES_SLOT`]
262///   (`flm.floats.types`);
263/// - the contributions of the counter `flm.floats.<type>` ([`counter_name`])
264///   and of the counter style `flm.floats.style.<type>` ([`style_name`]),
265///   with the type's words and number format, no delimiters and several
266///   numbers joined compactly, to the numbering feature's service slots;
267/// - the peer declarations of [`FIELDS_PACKAGE`] and of the type's scoped
268///   packages, which the body refers to.
269///
270/// Without the `floats` feature, the environment is not defined: a document
271/// that writes it gets an unknown environment, as it would if no feature
272/// declared the type, and a document that does not write it is processed as
273/// usual.
274///
275/// # Errors
276///
277/// [`BuildError::Feature`] when the type fails [`FloatType::validate`]; the
278/// [`BuildError`] of the registry builder when a declaration is made outside
279/// the registration round that accepts it (see
280/// [`Finalizer`](crate::core::registry::Finalizer)).
281pub fn contribute_type(b: &mut FeatureBuilder<'_>, float_type: Arc<FloatType>) -> Result<(), BuildError> {
282    let owner = b.feature().clone();
283    float_type.validate().map_err(|detail| BuildError::Feature { feature: owner.clone(), detail })?;
284    b.peer_slot::<FloatType>(TYPES_SLOT, Arc::clone(&float_type))?;
285    b.peer_slot::<CounterStyleDecl>(STYLES_SLOT, Arc::new(style(&float_type)))?;
286    b.peer_slot::<CounterDecl>(COUNTERS_SLOT, Arc::new(counter(&float_type)))?;
287    b.peer_scoped_package(
288        FIELDS_PACKAGE,
289        "the scoped package of the commands of a float's body, which the `floats` feature declares",
290    )?;
291    for package in &float_type.scoped_packages {
292        b.peer_scoped_package(
293            package.clone(),
294            format!(
295                "a scoped package the float type `{}` makes available in its body",
296                float_type.name
297            ),
298        )?;
299    }
300    b.peer_element_value(environment_def(&owner, &float_type))
301}
302
303#[cfg(test)]
304mod tests {
305    use super::*;
306    use crate::stdlib::features::numbering::{NumberTemplate, PrefixWords};
307
308    #[test]
309    fn a_type_declares_its_counter_and_its_style() {
310        let figure = FloatType::figure();
311        let counter = counter(&figure);
312        assert_eq!(counter.name.as_str(), "flm.floats.figure");
313        assert_eq!(counter.default_style.as_str(), "flm.floats.style.figure");
314        assert!(counter.within.is_none());
315        let style = style(&figure);
316        assert_eq!(style.name.as_str(), "flm.floats.style.figure");
317        assert_eq!(style.prefix_words, figure.words);
318        assert_eq!(style.number_format, NumberTemplate::formats("#{arabic}"));
319        assert_eq!(style.delimiters.open, "");
320        assert_eq!(style.join, JoinDecl::compact());
321        assert_ne!(style.prefix_words, PrefixWords::default());
322    }
323
324    #[test]
325    fn the_fields_package_holds_the_three_fields() {
326        let package = fields_package(&FeatureName::from("floats"));
327        assert_eq!(package.name.as_str(), FIELDS_PACKAGE);
328        let names: Vec<Vec<String>> = package
329            .elements
330            .iter()
331            .map(|element| element.names.iter().map(|name| name.to_string()).collect())
332            .collect();
333        assert_eq!(names, [["caption"], ["nonumber"], ["label"]]);
334    }
335}