use std::sync::Arc;
use techy::core::node::NodeRef;
use crate::core::registry::{BuildError, FeatureBuilder};
use crate::lang::Flm;
use crate::lang::mint::parsers::code_span;
use crate::lang::mint::{
ArgDef, ArgStdKind, BodyDef, ElementDef, ScopedPackageDef, SyntaxDef, field_element,
};
use crate::model::aspects::{
AcceptedRefTypes, AnchorPolicy, BlockRole, BlockRoleAspect, FixedBlockRole, NumberSource,
PointId, RefPoint, Referenceable,
};
use crate::model::addr::NodeAddr;
use crate::model::element::ElementSpec;
use crate::model::names::{FeatureName, Name, RefKind};
use crate::stdlib::features::numbering::{
COUNTERS_SLOT, CounterDecl, CounterStyleDecl, JoinDecl, STYLES_SLOT,
};
use crate::stdlib::features::refs;
use super::body::{float_fields, label_uses};
use super::config::FloatType;
use super::{
CAPTION_FIELD, CAPTION_OPTIONS_ARG, CAPTION_TEXT_ARG, FIELDS_PACKAGE, FLOAT,
NONUMBER_FIELD, TYPES_SLOT, counter_name, style_name,
};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FloatElement {
pub float_type: Arc<FloatType>,
}
pub fn float_point(addr: NodeAddr) -> PointId {
PointId { addr, index: 0 }
}
impl Referenceable for FloatElement {
fn points(&self, node: &NodeRef<'_, Flm>) -> Vec<RefPoint> {
let Some(fields) = float_fields(node) else { return Vec::new() };
let (labels, malformed) = refs::point_labels(&label_uses(&fields));
let name = self.float_type.name.as_str();
let number = fields.numbered.then(|| NumberSource {
counter: counter_name(name),
instances: Vec::new(),
style: style_name(name),
advance: vec![0],
number_format: None,
});
let content = fields.caption.as_ref().and_then(|caption| caption.shown_content(node));
vec![RefPoint {
kind: RefKind::from(name),
labels,
computed: 0,
malformed,
anchor: AnchorPolicy::FromValue { prefix: name.to_string() },
number,
content,
accepts: AcceptedRefTypes::these(self.float_type.label_types.iter().map(String::as_str)),
}]
}
}
fn float_element(float_type: Arc<FloatType>) -> Arc<ElementSpec> {
let docs = format!("A float of the type `{}`.", float_type.name);
let value = Arc::new(FloatElement { float_type });
Arc::new(
ElementSpec::new(FLOAT)
.docs(docs)
.with::<dyn BlockRoleAspect>(Arc::new(FixedBlockRole(BlockRole::Block)))
.with::<dyn Referenceable>(Arc::clone(&value) as Arc<dyn Referenceable>)
.with_value(value),
)
}
pub(super) fn float_type_def(owner: &FeatureName) -> ElementDef {
let element = Arc::new(
ElementSpec::new(FLOAT)
.docs(
"A float: one element value per float type, each written as the environment of \
the type's name.",
)
.with::<dyn BlockRoleAspect>(Arc::new(FixedBlockRole(BlockRole::Block))),
);
ElementDef::new(owner.clone(), Vec::<&str>::new(), SyntaxDef::Synthesized, element)
.docs("The element of every float, with one element value per float type.")
}
fn environment_def(owner: &FeatureName, float_type: &Arc<FloatType>) -> ElementDef {
let name = float_type.name.as_str();
let mut body = BodyDef::new().blocks().scoped(FIELDS_PACKAGE);
for package in &float_type.scoped_packages {
body = body.scoped(package.clone());
}
ElementDef::new(
owner.clone(),
[name],
SyntaxDef::Environment { args: Vec::new(), body },
float_element(Arc::clone(float_type)),
)
.docs(format!(
"Writes a float of the type `{name}`: its content, shown with the line under it that \
holds its number and its caption. The body may hold `\\caption`, `\\label` and \
`\\nonumber`{}.",
label_types_clause(&float_type.label_types)
))
}
fn label_types_clause(label_types: &[String]) -> String {
let spans: Vec<String> = label_types.iter().map(|label_type| code_span(label_type)).collect();
match spans.as_slice() {
[] => String::new(),
[one] => format!("; a label of the float has the label type {one}"),
several => format!("; a label of the float has one of the label types {}", several.join(", ")),
}
}
pub(super) fn fields_package(owner: &FeatureName) -> ScopedPackageDef {
let caption = ElementDef::new(
owner.clone(),
[CAPTION_FIELD],
SyntaxDef::Macro {
args: vec![
ArgDef::named(CAPTION_OPTIONS_ARG, ArgStdKind::KeyVals)
.docs(
"`alt=…`: the caption's alternative text, which a reference to an \
unnumbered float shows.",
),
ArgDef::named(CAPTION_TEXT_ARG, ArgStdKind::Mandatory)
.docs("The caption, shown under the float's content."),
],
},
field_element(
"A `\\caption[alt=…]{…}` in a float's body: the float's caption.",
),
)
.docs("Gives the float its caption, shown under its content.");
let nonumber = ElementDef::new(
owner.clone(),
[NONUMBER_FIELD],
SyntaxDef::Macro { args: Vec::new() },
field_element("A `\\nonumber` in a float's body: the float is not numbered."),
)
.docs("Marks the float as not numbered.");
let mut elements = vec![caption, nonumber];
elements.extend(refs::label_package(owner.clone()).elements);
ScopedPackageDef {
owner: owner.clone(),
name: Name::from(FIELDS_PACKAGE),
elements,
docs: String::from(
"The commands of a float's body, which the float reads: `\\caption[alt=…]{…}`, \
`\\label{…}` and `\\nonumber`.",
),
}
}
fn counter(float_type: &FloatType) -> CounterDecl {
let name = float_type.name.as_str();
CounterDecl::new(counter_name(name), style_name(name))
.docs(format!("The numbered floats of the type `{name}`, in document order."))
}
fn style(float_type: &FloatType) -> CounterStyleDecl {
let mut style = CounterStyleDecl::new(style_name(float_type.name.as_str()));
style.number_format = float_type.number_format.clone();
style.prefix_words = float_type.words.clone();
style.join = JoinDecl::compact();
style
}
pub fn contribute_type(b: &mut FeatureBuilder<'_>, float_type: Arc<FloatType>) -> Result<(), BuildError> {
let owner = b.feature().clone();
float_type.validate().map_err(|detail| BuildError::Feature { feature: owner.clone(), detail })?;
b.peer_slot::<FloatType>(TYPES_SLOT, Arc::clone(&float_type))?;
b.peer_slot::<CounterStyleDecl>(STYLES_SLOT, Arc::new(style(&float_type)))?;
b.peer_slot::<CounterDecl>(COUNTERS_SLOT, Arc::new(counter(&float_type)))?;
b.peer_scoped_package(
FIELDS_PACKAGE,
"the scoped package of the commands of a float's body, which the `floats` feature declares",
)?;
for package in &float_type.scoped_packages {
b.peer_scoped_package(
package.clone(),
format!(
"a scoped package the float type `{}` makes available in its body",
float_type.name
),
)?;
}
b.peer_element_value(environment_def(&owner, &float_type))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::stdlib::features::numbering::{NumberTemplate, PrefixWords};
#[test]
fn a_type_declares_its_counter_and_its_style() {
let figure = FloatType::figure();
let counter = counter(&figure);
assert_eq!(counter.name.as_str(), "flm.floats.figure");
assert_eq!(counter.default_style.as_str(), "flm.floats.style.figure");
assert!(counter.within.is_none());
let style = style(&figure);
assert_eq!(style.name.as_str(), "flm.floats.style.figure");
assert_eq!(style.prefix_words, figure.words);
assert_eq!(style.number_format, NumberTemplate::formats("#{arabic}"));
assert_eq!(style.delimiters.open, "");
assert_eq!(style.join, JoinDecl::compact());
assert_ne!(style.prefix_words, PrefixWords::default());
}
#[test]
fn the_fields_package_holds_the_three_fields() {
let package = fields_package(&FeatureName::from("floats"));
assert_eq!(package.name.as_str(), FIELDS_PACKAGE);
let names: Vec<Vec<String>> = package
.elements
.iter()
.map(|element| element.names.iter().map(|name| name.to_string()).collect())
.collect();
assert_eq!(names, [["caption"], ["nonumber"], ["label"]]);
}
}