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