flm_core/stdlib/features/floats/
elements.rs1use 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#[derive(Debug, Clone, PartialEq, Eq)]
47pub struct FloatElement {
48 pub float_type: Arc<FloatType>,
50}
51
52pub fn float_point(addr: NodeAddr) -> PointId {
55 PointId { addr, index: 0 }
56}
57
58impl 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
99fn 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
113pub(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
131fn 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
155fn 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
168pub(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
216fn 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
225fn 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
237pub 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}