flm_core/stdlib/features/graphics/handler.rs
1//! The content handler that the [`graphics`](super) feature contributes to the
2//! `floats` feature: `includegraphics`, which accepts exactly one image.
3//!
4//! A float type lists by name the **content handlers** it accepts. A content
5//! handler ([`FloatContentHandler`]) is a value that accepts a float's content
6//! or refuses it, contributed to the service slot
7//! [`CONTENT_SLOT`](crate::stdlib::features::floats::CONTENT_SLOT)
8//! (`flm.floats.content`) by the feature that owns that kind of content. This
9//! feature owns images, so it contributes [`HANDLER`] (`includegraphics`,
10//! [`IncludeGraphicsContent`]): it accepts a float's content where the content
11//! is exactly one node of the image element [`IMAGE_ELEMENT`] (the body of a
12//! `figure` holding `\includegraphics{plot.png}` beside its caption and
13//! labels), and refuses it otherwise with the words `exactly one image`, which
14//! complete the float's Error ("a ‘figure’ must hold exactly one image").
15//!
16//! The contribution is a peer contribution: in a registry without the
17//! `floats` feature, no feature declares the slot, the registry build drops
18//! the contribution with one Note, and the `graphics` feature builds and works
19//! as it does on its own.
20
21use techy::core::node::NodeRef;
22
23use crate::lang::Flm;
24use crate::model::element::element_of;
25use crate::stdlib::features::floats::FloatContentHandler;
26
27use super::IMAGE_ELEMENT;
28
29/// The name of the feature's content handler, `includegraphics`: the name a
30/// float type lists among its handlers to accept one image
31/// ([`FloatType::handlers`](crate::stdlib::features::floats::FloatType::handlers)).
32pub const HANDLER: &str = "includegraphics";
33
34/// The content handler [`HANDLER`] (`includegraphics`): it accepts exactly one
35/// image, a node of [`IMAGE_ELEMENT`], and refuses anything else: two images,
36/// text, an image beside a paragraph, or no content at all. See the [module
37/// documentation](self).
38#[derive(Debug, Default, Clone, Copy)]
39pub struct IncludeGraphicsContent;
40
41impl FloatContentHandler for IncludeGraphicsContent {
42 fn name(&self) -> &str {
43 HANDLER
44 }
45
46 fn admit(&self, content: &[NodeRef<'_, Flm>]) -> Result<(), String> {
47 match content {
48 [one] if element_of(one).name.as_str() == IMAGE_ELEMENT => Ok(()),
49 _ => Err(String::from("exactly one image")),
50 }
51 }
52}
53
54#[cfg(test)]
55mod tests {
56 use super::*;
57 use crate::stdlib::features::floats::INCLUDEGRAPHICS_HANDLER;
58
59 #[test]
60 fn the_handler_is_the_one_the_default_float_types_name() {
61 assert_eq!(IncludeGraphicsContent.name(), HANDLER);
62 assert_eq!(HANDLER, INCLUDEGRAPHICS_HANDLER);
63 }
64
65 #[test]
66 fn no_content_is_refused() {
67 assert_eq!(IncludeGraphicsContent.admit(&[]), Err(String::from("exactly one image")));
68 }
69}