Skip to main content

flm_core/stdlib/features/toc/
mod.rs

1//! The `toc` feature: the document's table of contents, as a table of entries
2//! a program can read and as a piece a backend places before the content.
3//!
4//! # What it lists
5//!
6//! A *heading* is any node whose element carries the sectioning aspect
7//! ([`Sectioning`](crate::model::aspects::Sectioning)): the standard headings
8//! (`\section` to `\subparagraph`) and any heading kind an extension declares
9//! alike. The feature lists, in the run's document order, every heading that
10//! the aspect says is listed ([`in_toc`](crate::model::aspects::Sectioning::in_toc):
11//! not of a kind declared `skip_toc`, not written `toc=false`) and whose level
12//! ([`level`](crate::model::aspects::Sectioning::level)) is at most the
13//! setting [`depth`](TocOptions::depth) (3 by default: sections, subsections
14//! and subsubsections). A starred heading is listed like any other. A heading
15//! inside a file brought in as a heading input comes where that file is placed.
16//!
17//! Each entry shows what the aspect returns for the heading
18//! ([`toc_title`](crate::model::aspects::Sectioning::toc_title)): for a
19//! standard heading, the alternative title written with the heading key
20//! `alt=`, and the heading's title otherwise. A footnote inside the title
21//! shows its mark in the entry, and its note is listed once, where the heading
22//! stands.
23//!
24//! # The table and the piece
25//!
26//! The stage [`BUILD`] (`flm.toc.build`, [`BuildToc`]) writes two tables:
27//!
28//! - [`ENTRIES`] (`flm.toc.entries`, [`TocEntries`]): one [`TocEntry`] per
29//!   listed heading, in document order: the heading's address, its level, its
30//!   first reference point and the content its entry shows. The table holds no
31//!   number and no anchor: a reader takes both from the counters and anchors
32//!   tables at the point of use, as the heading's own lowering rule does, so
33//!   that every output and the table agree. A program demands the table by its
34//!   name and reads it without rendering anything.
35//! - [`PIECE`] (`flm.toc`, a [`Piece`]): the table of contents as content, one
36//!   synthesized value of nested lists. A *piece* is a document-level
37//!   synthesized value that a backend places beside the document's content
38//!   (see [pieces](crate::guide::concepts_overview#pieces)).
39//!
40//! The piece is declared before the content and **off by default**
41//! ([`PieceDecl::default_on`]): a render places it only when its pieces
42//! option includes it (`pieces.include: [flm.toc]`), or when the compose
43//! template of the output requires it. Among the pieces placed before the
44//! content, it comes after the metadata's.
45//!
46//! # The shape of the piece
47//!
48//! The value holds three synthesized elements, which no document can write:
49//! [`PIECE`] (`flm.toc`), the root, holding one [`LIST`] (`flm.toc.list`);
50//! a list holds [`ENTRY`] (`flm.toc.entry`) nodes, each carrying a
51//! [`TocEntryPayload`] and holding the entry's title, then, where the entry
52//! has sub-entries, one list of them. The entries are nested by relative
53//! level: an entry whose level is greater than the level of the entry before
54//! it at the same depth goes into a new list inside that entry; a level gap (a
55//! subsubsection directly under a section) nests one list deeper, not two;
56//! the first entry, at any level, is a top-level entry. A heading left out
57//! (too deep, or not listed) is skipped: its listed sub-headings are nested
58//! among the headings kept.
59//!
60//! The lowering rules ([`rules`]) stage, on every backend:
61//!
62//! ```text
63//! flm.pres.block { role: flm.toc, kinds: [toc], doc_role: Toc }
64//!   └ flm.pres.list { kinds: [unnumbered, toc], entry_levels: [<each entry's level>] }
65//!       per entry:  label ⇒ nothing
66//!                   item  ⇒ flm.pres.link { href: "#<anchor>", kind: toc }
67//!                             ├ flm.pres.span { role: flm.toc.entry.number }  the number
68//!                             ├ " "
69//!                             └ the title
70//!                           the sub-list, where there is one
71//! ```
72//!
73//! Each entry's level is its heading's level, from its [`TocEntryPayload`].
74//! The number is the heading's number alone, without the word and the
75//! delimiters a reference writes. An entry without a number has no number
76//! span and no space; an entry whose heading has no anchor has no link.
77//!
78//! On the HTML page ([`html`]), the block is a `<nav>` with the role
79//! `doc-toc`, and the page carries the feature's stylesheet [`STYLE`]
80//! (`flm.toc.style`). The plain-text backend prints the nested lists as it
81//! prints every list whose labels are all empty: one entry per paragraph, at
82//! the left margin, so the nesting shows only through the numbers. In the
83//! rendered LaTeX the block is written through the backend's contract and the
84//! requirement brings in the feature's definition piece
85//! ([`latex_rendered`]): the title, the entries linked to the headings, and
86//! each entry's page number as LaTeX gives it. In the
87//! recomposed LaTeX the three elements write nothing ([`latex`]): LaTeX builds
88//! its own table of contents, and the piece is not placed on that output
89//! unless a render names it for that backend.
90//!
91//! # Settings
92//!
93//! The option type [`TocOptions`] (`depth`), bound on the document or on the
94//! render request ([`Bind::Either`]): `flm: {features: {toc: {depth: 2}}}` in
95//! a front matter, `-O toc.depth=2` on the command line.
96//!
97//! # Interactions with other features
98//!
99//! - `index` and `refpoints`: the stage reads the element index, and the table
100//!   of reference points where the `refpoints` feature is registered; without
101//!   it, no entry has a point, and so no number and no link.
102//! - `numbering` and `refs`: the rules read the counters and anchors tables
103//!   where they are computed, under peer declarations
104//!   ([`PeerName`](crate::core::registry::PeerName)), so the feature builds in
105//!   a registry without either.
106//! - `pieces`: the piece declaration is a peer contribution to the slot
107//!   [`pieces::SLOT`]; without the `pieces` feature no backend places it.
108//!
109//! # Items
110//!
111//! - The feature: [`Toc`], [`feature`], [`FEATURE`], [`TocOptions`].
112//! - The table: [`ENTRIES`], [`TocEntries`], [`TocEntry`].
113//! - The stage: [`BUILD`], [`BuildToc`], [`TocFailed`].
114//! - The piece and its elements: [`PIECE`], [`LIST`], [`ENTRY`],
115//!   [`TocEntryPayload`], [`KIND_TOC`], [`NUMBER_ROLE`].
116//! - The rules: [`rules`], [`latex`]. The style identifier, the stylesheet
117//!   and the rendered LaTeX's definition piece: [`STYLE`], [`html`],
118//!   [`latex_rendered`].
119
120pub mod html;
121pub mod latex;
122pub mod latex_rendered;
123pub mod rules;
124pub mod stage;
125
126use std::sync::Arc;
127
128use techy::core::node::NodeRef;
129use techy::serialize::SerialValue;
130
131use crate::core::data::table::{PieceClass, ProjectCx, SingletonTable, Table, TableName};
132use crate::core::piece::{Piece, PieceDecl, PiecePlace};
133use crate::core::registry::{BuildError, FeatureBuilder, FeatureInfo, FlmFeature};
134use crate::core::settings::SettingsDecl;
135use crate::lang::{Flm, PresPayload};
136use crate::model::addr::NodeAddr;
137use crate::model::aspects::{ContentRef, PointId};
138use crate::model::options::Bind;
139use crate::stdlib::backends::pieces;
140use crate::stdlib::features::refpoints::{content_text, point_key};
141
142pub use stage::{BuildToc, TocFailed};
143
144/// The feature's registered name, `toc`; also its settings key.
145pub const FEATURE: &str = "toc";
146
147/// The typed name of the table of entries, `flm.toc.entries` ([`TocEntries`]);
148/// like every table name, it is also the capability a caller demands to have
149/// it computed.
150pub const ENTRIES: TableName<TocEntries> = TableName::new("flm.toc.entries");
151
152/// The name of the piece `flm.toc`: the name of its table (of type
153/// [`Piece`]), of its declaration, and of the synthesized element at the root
154/// of its content.
155pub const PIECE: &str = "flm.toc";
156
157/// The name of the synthesized element of a list of entries, `flm.toc.list`.
158pub const LIST: &str = "flm.toc.list";
159
160/// The name of the synthesized element of one entry, `flm.toc.entry`, which
161/// carries a [`TocEntryPayload`].
162pub const ENTRY: &str = "flm.toc.entry";
163
164/// The name of the stage that writes the table of entries and the piece,
165/// `flm.toc.build` ([`BuildToc`]).
166pub const BUILD: &str = "flm.toc.build";
167
168/// The feature's style identifier, `flm.toc.style`, which the general rule
169/// of the root ([`RootRule`](rules::RootRule)) requires: the stylesheet on the
170/// HTML page ([`html::stylesheet`]).
171pub const STYLE: &str = "flm.toc.style";
172
173/// The kind token of the block and of the lists the rules stage, `toc`: a
174/// stylesheet or a program's lowering rule can select on it.
175pub const KIND_TOC: &str = "toc";
176
177/// The role of the span holding an entry's number, `flm.toc.entry.number`.
178pub const NUMBER_ROLE: &str = "flm.toc.entry.number";
179
180/// The default of [`TocOptions::depth`], 3.
181pub const DEFAULT_DEPTH: u32 = 3;
182
183/// The options of the `toc` feature, bound on the document or on the render
184/// request ([`Bind::Either`]); in data, the settings of the feature `toc`.
185///
186/// # Examples
187///
188/// ```
189/// use flm_core::stdlib::features::toc::TocOptions;
190///
191/// assert_eq!(TocOptions::default().depth, 3);
192/// ```
193#[derive(Debug, Clone, Hash, serde::Deserialize, schemars::JsonSchema)]
194#[serde(default, deny_unknown_fields)]
195pub struct TocOptions {
196    /// The deepest heading level listed: a heading is listed when its level is at
197    /// most this number. 3 by default (sections, subsections, subsubsections).
198    pub depth: u32,
199}
200
201impl Default for TocOptions {
202    fn default() -> TocOptions {
203        TocOptions { depth: DEFAULT_DEPTH }
204    }
205}
206
207/// One entry of the table of contents: a listed heading.
208#[derive(Debug, Clone, PartialEq, Eq)]
209pub struct TocEntry {
210    /// The heading.
211    pub addr: NodeAddr,
212    /// Its level, as the sectioning aspect returns it.
213    pub level: u32,
214    /// Its first reference point, where the reference points table holds one.
215    pub point: Option<PointId>,
216    /// What an entry shows: the content the sectioning aspect returns.
217    pub title: Option<ContentRef>,
218}
219
220/// The table of entries, `flm.toc.entries` ([`ENTRIES`]): one [`TocEntry`] per
221/// listed heading, in the run's document order. See the [module
222/// documentation](self).
223///
224/// The table is a document fact ([`PieceClass::DocumentFact`]) when it holds
225/// an entry: it describes the document's own headings.
226#[derive(Debug, Clone, Default, PartialEq, Eq)]
227pub struct TocEntries {
228    /// The entries, in document order.
229    pub entries: Vec<TocEntry>,
230}
231
232impl Table for TocEntries {
233    /// Appends the piece's entries after this table's.
234    fn absorb(&mut self, piece: TocEntries) {
235        self.entries.extend(piece.entries);
236    }
237
238    /// A list, one map per entry: `node` (the heading), `level`, `point`
239    /// (where there is one, keyed `<node>#<index>` as the table of reference
240    /// points keys a point) and `title` (where there is one: the reference as
241    /// text, or the plain text of a tree the aspect built).
242    fn project(&self, cx: &dyn ProjectCx) -> SerialValue {
243        SerialValue::List(
244            self.entries
245                .iter()
246                .map(|entry| {
247                    let mut map = vec![
248                        ("node".to_string(), cx.node_ref(entry.addr)),
249                        ("level".to_string(), SerialValue::Int(i64::from(entry.level))),
250                    ];
251                    if let Some(point) = entry.point {
252                        map.push(("point".to_string(), SerialValue::Str(point_key(cx, point))));
253                    }
254                    if let Some(title) = &entry.title {
255                        map.push(("title".to_string(), SerialValue::Str(content_text(cx, entry.addr.tree, title))));
256                    }
257                    SerialValue::Map(map)
258                })
259                .collect(),
260        )
261    }
262
263    fn piece_class(&self) -> PieceClass {
264        if self.entries.is_empty() { PieceClass::Empty } else { PieceClass::DocumentFact }
265    }
266}
267
268impl SingletonTable for TocEntries {
269    const NAME: &'static str = "flm.toc.entries";
270}
271
272/// The payload of an [`ENTRY`] node: the heading's first reference point,
273/// where it has one, and its level. The entry's rule reads the number and the
274/// anchor of the point from the counters and anchors tables.
275#[derive(Debug, Clone, Copy, PartialEq, Eq)]
276pub struct TocEntryPayload {
277    /// The heading's first reference point, where the reference points table
278    /// holds one.
279    pub point: Option<PointId>,
280    /// The heading's level.
281    pub level: u32,
282}
283
284impl PresPayload for TocEntryPayload {
285    /// `{point?, level}`: the point as `<tree>/<node>#<index>`, then the level.
286    fn project(&self) -> SerialValue {
287        let mut map = Vec::with_capacity(2);
288        if let Some(point) = self.point {
289            map.push((
290                "point".to_string(),
291                SerialValue::Str(format!("{}/{}#{}", point.addr.tree, point.addr.node.index(), point.index)),
292            ));
293        }
294        map.push(("level".to_string(), SerialValue::Int(i64::from(self.level))));
295        SerialValue::Map(map)
296    }
297}
298
299impl TocEntryPayload {
300    /// The payload of the entry node `node`, or `None` for a node that carries
301    /// none.
302    pub fn of<'n>(node: &'n NodeRef<'_, Flm>) -> Option<&'n TocEntryPayload> {
303        node.ext().payload.as_deref()?.downcast_ref::<TocEntryPayload>()
304    }
305}
306
307/// The declaration of the feature's settings: the field of [`TocOptions`]
308/// (`depth`) is its settings key.
309fn settings() -> SettingsDecl {
310    SettingsDecl::new(FEATURE).options::<TocOptions>(
311        Bind::Either,
312        "The deepest heading level the table of contents lists (`depth`, 3 by default). Set on \
313         the document; a render request may set it again, and its value then replaces the \
314         document's for that render.",
315    )
316}
317
318/// The `toc` feature: the option type [`TocOptions`], the table [`ENTRIES`],
319/// the stage [`BUILD`], the piece [`PIECE`] with its elements, lowering rules
320/// and stylesheet (see the [module documentation](self)).
321///
322/// Use [`feature()`] to obtain it as a value a package entry can list.
323#[derive(Debug, Default, Clone, Copy)]
324pub struct Toc;
325
326impl FlmFeature for Toc {
327    fn info(&self) -> FeatureInfo {
328        FeatureInfo::new(FEATURE, "Table of contents").docs(
329            "The document's table of contents: the table `flm.toc.entries` of the listed \
330             headings, and the piece `flm.toc` (off by default) that shows them as nested lists \
331             before the content.",
332        )
333    }
334
335    fn settings(&self) -> Option<SettingsDecl> {
336        Some(settings())
337    }
338
339    fn register(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
340        b.table(
341            ENTRIES,
342            "The document's listed headings, in document order: each heading's address, level, \
343             first reference point and the content its entry shows.",
344        )?;
345        b.table_named::<Piece>(PIECE, "The table of contents as nested lists, or nothing to place.")?;
346        b.stage(Arc::new(BuildToc))?;
347        rules::declare(b)?;
348        html::register(b)?;
349        latex_rendered::register(b)?;
350        latex::register(b)?;
351        // The pieces feature owns the slot, and may be absent: the table of
352        // contents is then placed by no backend.
353        b.peer_slot(
354            pieces::SLOT,
355            Arc::new(
356                PieceDecl::new(PIECE, PiecePlace::BeforeContent, "the table of contents, before the content")
357                    .default_on(false),
358            ),
359        )?;
360        Ok(())
361    }
362}
363
364/// Returns the [`Toc`] feature, ready to be listed in a package entry.
365///
366/// # Examples
367///
368/// ```
369/// use flm_core::stdlib::features::toc;
370///
371/// assert_eq!(toc::feature().info().name.as_str(), toc::FEATURE);
372/// ```
373pub fn feature() -> Arc<dyn FlmFeature> {
374    Arc::new(Toc)
375}