flm_core/stdlib/features/metadata/mod.rs
1//! The `metadata` feature: the document's metadata (its title, its authors, its date, and
2//! any other key the author writes about the document) and the three pieces that show
3//! the title, the authors and the date before the document's content.
4//!
5//! # What an author writes, and what it produces
6//!
7//! The title, the date and each author's name, affiliations and notes are FLM text,
8//! not plain text: a title may be `The \emph{Art} of \(x^2\)`. An author may have,
9//! beside a name, affiliations, an email address (a plain text) and notes
10//! ([`MetaAuthor`]). The author of the document does not write them with commands in
11//! the document's text; the program that processes the document sets them. The `flm`
12//! program reads them from the root keys `title`, `author` and `date` of a file's
13//! front matter (the block of YAML at the top of the file). Each FLM text is parsed as
14//! inline content when the document is processed, and a problem in it is reported at
15//! its place in the file that holds it.
16//!
17//! A *piece* is a document-level synthesized value that a backend places before or
18//! after the document's content ([`Piece`]; see
19//! [pieces](crate::guide::concepts_overview#pieces)). The feature builds three pieces,
20//! each placed before the content, and placed by every render unless the render
21//! options leave it out
22//! ([`PieceDecl::default_on`](crate::core::piece::PieceDecl::default_on)): [`TITLE`]
23//! (`flm.metadata.title`), [`AUTHOR`] (`flm.metadata.author`) and [`DATE`]
24//! (`flm.metadata.date`). On each output:
25//!
26//! - on the HTML and rendered-LaTeX outputs, each piece is a block of its own whose
27//! role is its element's name and whose kind token is `metadata`
28//! ([`KIND_METADATA`]; a `<div>` on HTML). The title and the date hold one
29//! paragraph. The authors hold each author, one after the other, as a group of
30//! lines: the name, each affiliation, the email address (a link to `mailto:` and
31//! the address) and each note, each on a line of its own in a span whose role is
32//! the part's element name ([`rules`]). The HTML page also uses the words of the
33//! title piece as its `<title>`;
34//! - on the plain-text output, each piece is such a block too, with two differences
35//! ([`text`]): the title is in bold, between two rule lines as wide as its widest
36//! printed line, and each part of an author after the name is indented by `1em`
37//! (two columns). The date and the authors' block are as on the other outputs;
38//! - on the recomposed LaTeX, each piece is what a LaTeX document passes to `\title`,
39//! `\author` and `\date`: the title and the date are their content written back as
40//! LaTeX; each author is the name, `\thanks{…}` for each note, then each affiliation
41//! and the email address after `\\`, the authors joined by `\and` ([`latex`]). That
42//! backend places a piece only where the render options of the `pieces` feature
43//! list it ([pieces in the recomposed
44//! LaTeX](crate::guide::rendering#pieces-in-the-recomposed-latex)).
45//!
46//! A document without metadata places nothing: each piece holds no content. The other
47//! keys of the metadata ([`DocMeta::other`]) and of an author ([`MetaAuthor::other`]) are
48//! data the library does not show; the program may pass them to the tool it builds the
49//! final output with, such as a template.
50//!
51//! # What a program provides
52//!
53//! The metadata is an option value of the option type [`DocMeta`], bound per document:
54//! an option type is a plain Rust struct a feature declares once, whose values are set
55//! on a document or on a render request ([`crate::model::options`]). A program sets it
56//! on the document it builds
57//! ([`Doc::with_options`](crate::model::doc::Doc::with_options)). A program that holds
58//! the metadata as data (for example the root keys of a front matter) reads it with
59//! [`DocMeta::from_data`], whose form ([`data`]) is the same for every program: `title`
60//! and `date` one text each, `author` one author or a list of authors, an author being
61//! a text (the name) or a map (`name`, `affiliation`, `email`, `note`). Each text is
62//! kept as the author wrote it, with the place it was written at ([`MetaText`],
63//! [`MetaPlace`]). See
64//! [the document's metadata](crate::guide::embedding#the-documents-metadata) in the
65//! embedding guide.
66//!
67//! # What the feature registers
68//!
69//! - the option type [`DocMeta`], bound per document;
70//! - the stage [`BUILD`] (`flm.metadata.build`, [`BuildMetadata`]), which parses the
71//! title, the authors and the date, numbers the distinct affiliations of the document
72//! ([`AffiliationPayload`]), and writes the tables of the three pieces. It provides
73//! the capability [`READ`] (`flm.metadata.read`), a member of the collection
74//! [`flm.validated`](crate::stdlib::VALIDATED) that every standard workflow
75//! demands, so that checking a document reports the problems the parse of its
76//! metadata finds. A problem found only when a piece is lowered for an output, such
77//! as a footnote in the title, is reported by a render only;
78//! - the three pieces [`TITLE`], [`AUTHOR`] and [`DATE`], each a table and a piece
79//! declaration contributed to the service slot of the `pieces` feature
80//! ([`pieces::SLOT`]);
81//! - the synthesized elements of the three pieces, of one author ([`AUTHOR_ENTRY`],
82//! `flm.metadata.author.entry`) and of its parts ([`AUTHOR_NAME`],
83//! [`AUTHOR_AFFILIATION`], [`AUTHOR_EMAIL`], [`AUTHOR_NOTE`]); no document can write
84//! them. Their default lowering rules are in [`rules`], their rules on the
85//! recomposed LaTeX in [`latex`], and their rules on the plain text in [`text`];
86//! - the diagnostic `flm.metadata.failed` ([`MetadataFailed`]), for a part of the
87//! metadata that could not be built.
88//!
89//! # Interactions with other features
90//!
91//! - `pieces` ([`pieces`]): the feature contributes its three piece declarations to
92//! that feature's service slot as peer contributions (values for a service slot
93//! another feature declares; see [services and service
94//! slots](crate::guide::concepts_overview#services-and-service-slots)); without the
95//! `pieces` feature no backend places the metadata.
96//! - The LaTeX family ([`latex`](crate::stdlib::backends::latex)): the rules on the
97//! recomposed LaTeX are registered with peer declarations of the backend and of the
98//! macro construct, so that a registry without the LaTeX features still builds, with
99//! those rules set aside (excluded from rule selection; see
100//! [`PeerName`](crate::core::registry::PeerName)).
101//! - `text` ([`text`](crate::stdlib::backends::text)): the rules on the plain text are
102//! registered with peer declarations of the backend and of the construct element
103//! `flm.pres.text.ruled`, in the same way.
104//! - `check` ([`CheckWorkflow`](crate::stdlib::CheckWorkflow)): the capability
105//! [`READ`] joins the collection `flm.validated`.
106//!
107//! # Items
108//!
109//! - The feature: [`Metadata`], [`feature`], [`FEATURE`].
110//! - The metadata: [`DocMeta`], [`MetaAuthor`], [`MetaText`], [`MetaPlace`]; written as
111//! data: [`data`], [`DocMeta::from_data`], [`metadata_schema`], [`TITLE_KEY`],
112//! [`AUTHOR_KEY`], [`DATE_KEY`], [`NAME_KEY`], [`AFFILIATION_KEY`], [`EMAIL_KEY`],
113//! [`NOTE_KEY`], [`MetaPath`], [`MetaStep`], [`MetaDataError`].
114//! - The pieces and their elements: [`TITLE`], [`AUTHOR`], [`AUTHOR_ENTRY`],
115//! [`AUTHOR_NAME`], [`AUTHOR_AFFILIATION`], [`AUTHOR_EMAIL`], [`AUTHOR_NOTE`], [`DATE`],
116//! [`KIND_METADATA`]; the payloads [`AffiliationPayload`] and [`EmailPayload`].
117//! - The stage: [`BUILD`], [`READ`], [`BuildMetadata`], [`MetadataFailed`].
118//! - The lowering rules: [`rules`] ([`MetaTextRule`], [`AuthorRule`], [`EntryRule`],
119//! [`PartRule`], [`EmailRule`]), [`latex`] and [`text`] ([`TitleTextRule`],
120//! [`EntryTextRule`]).
121//! - The style identifier [`STYLE`] ([`stylesheet`]), which the general rules
122//! require at every piece they stage, and the `latex-rendered` definition
123//! piece delivering it, [`latex_rendered`].
124
125pub mod build;
126pub mod data;
127pub mod latex;
128pub mod latex_rendered;
129pub mod rules;
130pub mod text;
131
132use std::collections::BTreeMap;
133use std::hash::{Hash, Hasher};
134use std::sync::Arc;
135
136use techy::core::node::NodeRef;
137use techy::serialize::SerialValue;
138
139use crate::core::piece::{Piece, PieceDecl, PiecePlace};
140use crate::core::registry::{
141 BuildError, CapabilityDef, DefContent, FeatureBuilder, FeatureInfo, FlmFeature, StyleDef,
142};
143use crate::lang::{Flm, PresPayload};
144use crate::model::names::Name;
145use crate::model::options::Bind;
146use crate::stdlib::backends::pieces;
147use crate::stdlib::VALIDATED;
148
149pub use build::{BuildMetadata, MetadataFailed};
150pub use data::{
151 AFFILIATION_KEY, AUTHOR_KEY, DATE_KEY, EMAIL_KEY, MetaDataError, MetaPath, MetaStep, NAME_KEY, NOTE_KEY,
152 TITLE_KEY, metadata_schema,
153};
154pub use rules::{AuthorRule, EmailRule, EntryRule, MetaTextRule, PartRule};
155pub use text::{EntryTextRule, TitleTextRule};
156
157/// The feature's registered name, `metadata`.
158pub const FEATURE: &str = "metadata";
159
160/// The name of the title piece, `flm.metadata.title`. It is also the name of the
161/// piece's table and of the synthesized element at the root of the piece's
162/// content.
163pub const TITLE: &str = "flm.metadata.title";
164
165/// The name of the authors piece, `flm.metadata.author`. It is also the name of the
166/// piece's table and of the synthesized element at the root of the piece's
167/// content, which holds one [`AUTHOR_ENTRY`] node per author.
168pub const AUTHOR: &str = "flm.metadata.author";
169
170/// The name of the synthesized element of one author in the authors piece,
171/// `flm.metadata.author.entry`. It holds the author's parts, in this order: one
172/// [`AUTHOR_NAME`] node, one [`AUTHOR_AFFILIATION`] node per affiliation, one
173/// [`AUTHOR_EMAIL`] node when the author has an email address, and one
174/// [`AUTHOR_NOTE`] node per note.
175pub const AUTHOR_ENTRY: &str = "flm.metadata.author.entry";
176
177/// The name of the synthesized element of an author's name,
178/// `flm.metadata.author.name`: it holds the name as inline content.
179pub const AUTHOR_NAME: &str = "flm.metadata.author.name";
180
181/// The name of the synthesized element of one affiliation of an author,
182/// `flm.metadata.author.affiliation`: it holds the affiliation as inline content,
183/// and carries the affiliation's number ([`AffiliationPayload`]).
184pub const AUTHOR_AFFILIATION: &str = "flm.metadata.author.affiliation";
185
186/// The name of the synthesized element of an author's email address,
187/// `flm.metadata.author.email`: it holds no content, and carries the address
188/// ([`EmailPayload`]).
189pub const AUTHOR_EMAIL: &str = "flm.metadata.author.email";
190
191/// The name of the synthesized element of one note about an author,
192/// `flm.metadata.author.note`: it holds the note as inline content.
193pub const AUTHOR_NOTE: &str = "flm.metadata.author.note";
194
195/// The name of the date piece, `flm.metadata.date`. It is also the name of the
196/// piece's table and of the synthesized element at the root of the piece's
197/// content.
198pub const DATE: &str = "flm.metadata.date";
199
200/// The name of the stage that parses the metadata and builds the three pieces,
201/// `flm.metadata.build` ([`BuildMetadata`]).
202pub const BUILD: &str = "flm.metadata.build";
203
204/// The name of the capability `flm.metadata.read`: the document's metadata has
205/// been parsed, and every problem the parse found has been reported. It is a member
206/// of the collection [`flm.validated`](crate::stdlib::VALIDATED), so every
207/// standard workflow runs the stage [`BUILD`].
208pub const READ: &str = "flm.metadata.read";
209
210/// The kind token that the blocks staged by the rules of the three pieces carry,
211/// `metadata`: a stylesheet or a program's lowering rule can select on it (see
212/// [`pres::payload`](crate::stdlib::backends::pres::payload)).
213pub const KIND_METADATA: &str = "metadata";
214
215/// The feature's style identifier, `flm.metadata.style`, which the general rules
216/// ([`MetaTextRule`], [`AuthorRule`]) require at every piece they stage. On
217/// the `html` backend it names the feature's stylesheet ([`stylesheet`]);
218/// on the `latex-rendered` backend
219/// the feature's definition piece ([`latex_rendered::piece`]) delivers it.
220pub const STYLE: &str = "flm.metadata.style";
221
222/// The style definition [`STYLE`] on the `html` backend: one cascade layer that
223/// sets the title large and bold, and the authors and the date indented under the
224/// title, the authors one below the other, an author's affiliations, email
225/// address and notes smaller than the name; the sizes, the indentation and the
226/// spaces are custom properties it declares (`--flm-metadata-title-size`,
227/// `--flm-metadata-line-indent`, `--flm-metadata-author-detail-size`, …). It
228/// selects on the blocks and spans the general rules stage (their role and the
229/// kind token [`KIND_METADATA`]), so it applies whatever compose template places
230/// the pieces. It sets no rule between the pieces and the content: that belongs to
231/// the page that places them.
232pub fn stylesheet() -> StyleDef {
233 StyleDef {
234 id: Name::from(STYLE),
235 content: vec![DefContent::Inline(String::from(include_str!("css/metadata.css")))],
236 docs: String::from(
237 "the document's title large and bold, and the authors and the date indented under the title, \
238 each author's affiliations, email address and notes smaller than the name",
239 ),
240 }
241}
242
243/// The payload of an [`AUTHOR_AFFILIATION`] node: the affiliation's number.
244///
245/// The stage [`BUILD`] numbers the distinct affiliations of the document from 1,
246/// in the order in which they first appear. Two affiliations whose texts are the
247/// same once the whitespace at both ends is trimmed are the same affiliation,
248/// and carry the same number. No rule of this feature writes the number: it is
249/// there for a lowering rule that marks each author with the numbers of the
250/// author's affiliations and lists the affiliations once.
251#[derive(Debug, Clone, Copy, PartialEq, Eq)]
252pub struct AffiliationPayload {
253 /// The number, counted from 1.
254 pub number: usize,
255}
256
257impl PresPayload for AffiliationPayload {
258 /// `{number}`.
259 fn project(&self) -> SerialValue {
260 SerialValue::Map(vec![(String::from("number"), SerialValue::Int(self.number as i64))])
261 }
262}
263
264impl AffiliationPayload {
265 /// The payload of the affiliation node `node`, or `None` for a node that
266 /// carries none.
267 pub fn of<'n>(node: &'n NodeRef<'_, Flm>) -> Option<&'n AffiliationPayload> {
268 node.ext().payload.as_deref()?.downcast_ref::<AffiliationPayload>()
269 }
270}
271
272/// The payload of an [`AUTHOR_EMAIL`] node: the address, as the author wrote it.
273#[derive(Debug, Clone, PartialEq, Eq)]
274pub struct EmailPayload {
275 /// The address: `ada@example.com`.
276 pub address: String,
277}
278
279impl PresPayload for EmailPayload {
280 /// `{address}`.
281 fn project(&self) -> SerialValue {
282 SerialValue::Map(vec![(String::from("address"), SerialValue::Str(self.address.clone()))])
283 }
284}
285
286impl EmailPayload {
287 /// The payload of the email node `node`, or `None` for a node that carries
288 /// none.
289 pub fn of<'n>(node: &'n NodeRef<'_, Flm>) -> Option<&'n EmailPayload> {
290 node.ext().payload.as_deref()?.downcast_ref::<EmailPayload>()
291 }
292}
293
294/// A text of the metadata as the author wrote it, and where it was written. The
295/// stage [`BUILD`] parses it as inline FLM content, except an author's email
296/// address ([`MetaAuthor::email`]), which is a plain text.
297#[derive(Debug, Clone, PartialEq, Eq, Hash)]
298pub struct MetaText {
299 /// The text: `The \emph{Art} of \(x^2\)`.
300 pub text: String,
301 /// Where the text begins, when it was read from a file. A problem in the
302 /// text is then reported at its line and column in that file.
303 pub place: Option<MetaPlace>,
304}
305
306impl MetaText {
307 /// Returns the text `text`, with no place.
308 ///
309 /// # Examples
310 ///
311 /// ```
312 /// use flm_core::stdlib::features::metadata::{MetaPlace, MetaText};
313 ///
314 /// let title = MetaText::new(r"The \emph{Art}").at(MetaPlace::new("paper.flm", 2, 8));
315 /// assert_eq!(title.place.map(|place| place.line), Some(2));
316 /// ```
317 pub fn new(text: impl Into<String>) -> MetaText {
318 MetaText { text: text.into(), place: None }
319 }
320
321 /// Builder: the text begins at `place`.
322 pub fn at(mut self, place: MetaPlace) -> MetaText {
323 self.place = Some(place);
324 self
325 }
326}
327
328/// Where a text of the metadata begins: the file, the line and the column, the
329/// line and the column counted from 1.
330#[derive(Debug, Clone, PartialEq, Eq, Hash)]
331pub struct MetaPlace {
332 /// The name of the file, as a diagnostic's position shows it.
333 pub file: String,
334 /// The line, counted from 1 at the top of the file.
335 pub line: u32,
336 /// The column, counted from 1 at the start of the line, in bytes.
337 pub column: u32,
338}
339
340impl MetaPlace {
341 /// Returns the place at `line` and `column` of the file named `file`.
342 pub fn new(file: impl Into<String>, line: u32, column: u32) -> MetaPlace {
343 MetaPlace { file: file.into(), line, column }
344 }
345}
346
347/// One author of the document: the name, the affiliations, the email address,
348/// the notes, and every other key the author's entry holds. Each text keeps the
349/// place it was written at, so that a problem in an affiliation is reported at
350/// the affiliation.
351///
352/// The name, each affiliation and each note are FLM text, which the stage
353/// [`BUILD`] parses as inline content. The email address is a plain text: it is
354/// not parsed, and nothing checks its form.
355///
356/// # Examples
357///
358/// ```
359/// use flm_core::stdlib::features::metadata::{MetaAuthor, MetaText};
360///
361/// let ada = MetaAuthor::new(MetaText::new("Ada Lovelace"))
362/// .affiliation(MetaText::new(r"University of \emph{X}"))
363/// .email(MetaText::new("ada@example.com"))
364/// .note(MetaText::new("Corresponding author"));
365/// assert_eq!(ada.affiliations.len(), 1);
366/// ```
367#[derive(Debug, Clone, PartialEq)]
368pub struct MetaAuthor {
369 /// The author's name.
370 pub name: MetaText,
371 /// The author's affiliations, in the order written.
372 pub affiliations: Vec<MetaText>,
373 /// The author's email address, a plain text.
374 pub email: Option<MetaText>,
375 /// The notes about the author, in the order written.
376 pub notes: Vec<MetaText>,
377 /// Every other key of the author's entry, with its value as data. The
378 /// library does not show these values.
379 pub other: BTreeMap<String, serde_json::Value>,
380}
381
382impl MetaAuthor {
383 /// Returns the author named `name`, with nothing else.
384 pub fn new(name: MetaText) -> MetaAuthor {
385 MetaAuthor { name, affiliations: Vec::new(), email: None, notes: Vec::new(), other: BTreeMap::new() }
386 }
387
388 /// Builder: adds an affiliation after those already given.
389 pub fn affiliation(mut self, affiliation: MetaText) -> MetaAuthor {
390 self.affiliations.push(affiliation);
391 self
392 }
393
394 /// Builder: sets the email address.
395 pub fn email(mut self, email: MetaText) -> MetaAuthor {
396 self.email = Some(email);
397 self
398 }
399
400 /// Builder: adds a note after those already given.
401 pub fn note(mut self, note: MetaText) -> MetaAuthor {
402 self.notes.push(note);
403 self
404 }
405
406 /// Builder: sets the value of another key.
407 pub fn other(mut self, key: impl Into<String>, value: serde_json::Value) -> MetaAuthor {
408 self.other.insert(key.into(), value);
409 self
410 }
411}
412
413// A data value has no hash of its own; its written form stands for it, one
414// written form per value.
415impl Hash for MetaAuthor {
416 fn hash<H: Hasher>(&self, state: &mut H) {
417 self.name.hash(state);
418 self.affiliations.hash(state);
419 self.email.hash(state);
420 self.notes.hash(state);
421 hash_data(&self.other, state);
422 }
423}
424
425/// Feeds `other`, a map of data values, to `state`: its length, then each key
426/// and the written form of its value.
427fn hash_data<H: Hasher>(other: &BTreeMap<String, serde_json::Value>, state: &mut H) {
428 other.len().hash(state);
429 for (key, value) in other {
430 key.hash(state);
431 value.to_string().hash(state);
432 }
433}
434
435/// The document's metadata: the option type the `metadata` feature declares, bound
436/// per document (see the [module documentation](self)). A program sets its value
437/// on the document ([`Doc::with_options`](crate::model::doc::Doc::with_options)),
438/// or reads it from data with [`DocMeta::from_data`].
439///
440/// The default holds nothing, and a document whose metadata holds nothing
441/// places none of the three pieces.
442///
443/// # Examples
444///
445/// ```
446/// use flm_core::model::doc::{Doc, DocContent};
447/// use flm_core::model::options::OptionValues;
448/// use flm_core::stdlib::features::metadata::{DocMeta, MetaAuthor, MetaText};
449///
450/// let meta = DocMeta::default()
451/// .title(MetaText::new(r"On \emph{flexible} markup"))
452/// .author(MetaAuthor::new(MetaText::new("Ada")).affiliation(MetaText::new("University of X")))
453/// .author(MetaAuthor::new(MetaText::new("Grace")));
454/// let doc = Doc::with_options(DocContent::new(), OptionValues::new().with(meta));
455/// # let _ = doc;
456/// ```
457#[derive(Debug, Clone, Default, PartialEq)]
458pub struct DocMeta {
459 /// The title.
460 pub title: Option<MetaText>,
461 /// The authors, in the order written.
462 pub authors: Vec<MetaAuthor>,
463 /// The date, as the author wrote it.
464 pub date: Option<MetaText>,
465 /// Every other key of the metadata, with its value as data. The library
466 /// does not show these values.
467 pub other: BTreeMap<String, serde_json::Value>,
468}
469
470impl DocMeta {
471 /// Builder: sets the title.
472 pub fn title(mut self, title: MetaText) -> DocMeta {
473 self.title = Some(title);
474 self
475 }
476
477 /// Builder: adds an author after those already given.
478 pub fn author(mut self, author: MetaAuthor) -> DocMeta {
479 self.authors.push(author);
480 self
481 }
482
483 /// Builder: sets the date.
484 pub fn date(mut self, date: MetaText) -> DocMeta {
485 self.date = Some(date);
486 self
487 }
488
489 /// Builder: sets the value of another key.
490 pub fn other(mut self, key: impl Into<String>, value: serde_json::Value) -> DocMeta {
491 self.other.insert(key.into(), value);
492 self
493 }
494
495 /// Returns whether the metadata holds nothing.
496 pub fn is_empty(&self) -> bool {
497 self.title.is_none() && self.authors.is_empty() && self.date.is_none() && self.other.is_empty()
498 }
499}
500
501// A data value has no hash of its own; its written form stands for it, one
502// written form per value.
503impl Hash for DocMeta {
504 fn hash<H: Hasher>(&self, state: &mut H) {
505 self.title.hash(state);
506 self.authors.hash(state);
507 self.date.hash(state);
508 hash_data(&self.other, state);
509 }
510}
511
512/// The `metadata` feature: the option type [`DocMeta`], the stage [`BUILD`], the
513/// three pieces and their elements and lowering rules (see the [module
514/// documentation](self)).
515///
516/// Use [`feature()`] to obtain it as a value a package entry can list.
517#[derive(Debug, Default, Clone, Copy)]
518pub struct Metadata;
519
520impl FlmFeature for Metadata {
521 fn info(&self) -> FeatureInfo {
522 FeatureInfo::new(FEATURE, "Document metadata").docs(
523 "The document's metadata (its title, its authors, its date and any other key) as \
524 an option set per document, and the three pieces that show the title, the authors \
525 and the date before the content.",
526 )
527 }
528
529 fn register(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
530 b.options_with_docs::<DocMeta>(
531 Bind::Document,
532 "the document's metadata: its title, its authors (each a name, with affiliations, an \
533 email address and notes where given) and its date, each text with the place it was \
534 written at, and every other key as data",
535 )?;
536 rules::declare(b)?;
537 latex::register(b)?;
538 text::register(b)?;
539 b.style_def(stylesheet())?;
540 latex_rendered::register(b)?;
541 for (name, docs) in [
542 (TITLE, "The document's title, parsed: its content, or nothing to place."),
543 (AUTHOR, "The document's authors, parsed: their content, or nothing to place."),
544 (DATE, "The document's date, parsed: its content, or nothing to place."),
545 ] {
546 b.table_named::<Piece>(name, docs)?;
547 }
548 b.capability(CapabilityDef::new(READ).docs(
549 "The document's metadata has been parsed, and every problem the parse found has \
550 been reported. A member of `flm.validated`.",
551 ))?;
552 // One stage parses the three texts, read from one value at one time; it
553 // joins `flm.validated` so that checking a document reports a problem in
554 // its title as rendering it does.
555 b.stage(Arc::new(BuildMetadata))?;
556 b.collection_member(VALIDATED, READ)?;
557 // The pieces feature owns the slot, and may be absent: the metadata is
558 // then placed by no backend.
559 for (name, docs) in [
560 (TITLE, "the document's title, before the content"),
561 (AUTHOR, "the document's authors, before the content"),
562 (DATE, "the document's date, before the content"),
563 ] {
564 b.peer_slot(pieces::SLOT, Arc::new(PieceDecl::new(name, PiecePlace::BeforeContent, docs)))?;
565 }
566 Ok(())
567 }
568}
569
570/// Returns the [`Metadata`] feature, ready to be listed in a package entry.
571///
572/// # Examples
573///
574/// ```
575/// use flm_core::stdlib::features::metadata;
576///
577/// assert_eq!(metadata::feature().info().name.as_str(), metadata::FEATURE);
578/// ```
579pub fn feature() -> Arc<dyn FlmFeature> {
580 Arc::new(Metadata)
581}
582
583#[cfg(test)]
584mod tests {
585 use super::*;
586 use std::collections::hash_map::DefaultHasher;
587
588 fn digest(meta: &DocMeta) -> u64 {
589 let mut hasher = DefaultHasher::new();
590 meta.hash(&mut hasher);
591 hasher.finish()
592 }
593
594 #[test]
595 fn the_hash_follows_every_field_the_data_included() {
596 let base = DocMeta::default().title(MetaText::new("A"));
597 assert_eq!(digest(&base), digest(&base.clone()));
598 assert_ne!(digest(&base), digest(&base.clone().author(MetaAuthor::new(MetaText::new("B")))));
599 assert_ne!(
600 digest(&base.clone().other("n", serde_json::json!(1))),
601 digest(&base.clone().other("n", serde_json::json!(2)))
602 );
603 }
604
605 #[test]
606 fn the_default_holds_nothing() {
607 assert!(DocMeta::default().is_empty());
608 assert!(!DocMeta::default().date(MetaText::new("today")).is_empty());
609 }
610}