Skip to main content

flm_core/core/
region.rs

1//! Output regions: the named parts an output's entry artifact is made of, the
2//! table in which a backend writes them, and a backend's statement that its
3//! output is made of them.
4//!
5//! An output region is one named part of an output's entry artifact (the
6//! document's content, each [piece](crate::core::piece) placed beside it, and
7//! on HTML the stylesheets, the scripts, the title and the language), which
8//! the backend writes once into the table `flm.output.<backend>.regions`
9//! ([`Regions`]). The entry artifact is the artifact that represents the
10//! output as a whole: the HTML page, the printed text, the recomposed LaTeX
11//! document ([`ArtifactSet`]).
12//!
13//! The backend's final stage assembles the entry artifact from those regions,
14//! in a layout of the backend's own, and publishes the result as the output's
15//! artifact set. A host may instead assemble the same regions through a
16//! template of its own, with a stage that the plan schedules in place of the
17//! backend's final stage ([output regions and the final
18//! stage](crate::guide::concepts_overview#output-regions-and-the-final-stage)).
19//! Either way the regions are computed once. The [`Regions`] table also states
20//! what the entry artifact is (its identity, its media type and the artifacts
21//! it refers to), so that every assembler makes the same artifact from one
22//! statement.
23//!
24//! This module holds the region names (below), one region ([`Region`]), the
25//! regions of one output ([`Regions`]), the function that computes a piece's
26//! plain words ([`piece_words`]), and a backend's statement that an output is
27//! made of regions ([`RegionsOutput`]).
28//!
29//! # The region names
30//!
31//! | Name | What the region holds | Backends |
32//! |---|---|---|
33//! | [`CONTENT`] | the document's content: every tree in document order; a tree placed inside another tree is written where it is placed | every backend (the text backend writes its pieces inside this region too) |
34//! | a piece's name | that piece, as the backend writes it | HTML, recomposed LaTeX |
35//! | [`STYLES`] | the stylesheets the document requires, one part per HTML element (`<style>` or `<link>`) | HTML |
36//! | [`SCRIPTS`] | the scripts the document requires, one part per `<script>` element | HTML |
37//! | [`TITLE`] | the words of the page's title: the document's title, else the title the HTML render options ([`HtmlRenderOptions`](crate::stdlib::backends::html::HtmlRenderOptions)) give | HTML |
38//! | [`LANG`] | the page's language tag, when the HTML render options give a language; absent otherwise | HTML |
39//! | [`STYLE_PACKAGE`] | the package name of the style file, when the output has a style file | recomposed LaTeX |
40//!
41//! # Which outputs are made of regions
42//!
43//! A backend whose output is made of regions states it by contributing a
44//! [`RegionsOutput`] to the service slot
45//! [`flm.output.regions`](crate::stdlib::backends::lowering::REGIONS_SLOT):
46//! the output, its backend, the table of its regions, the tables of the files
47//! written beside its entry artifact, and the capability its final stage
48//! provides. A stage that assembles the regions another way, such as a
49//! host's template stage, reads that service slot to learn which outputs it can
50//! serve. It
51//! therefore serves exactly the outputs of the backends the registry holds.
52//!
53//! # Parts
54//!
55//! A region is a list of **parts**, each a text the backend wrote in its
56//! output format (HTML, LaTeX or plain text). The HTML backend's final stage places each part of a
57//! region on a line of its own, at the indentation of the place where the
58//! region goes. A template places the region's [`text`](Region::text): its
59//! parts joined by line breaks. A region that is one text has one part.
60
61use techy::core::node::NodeTree;
62use techy::serialize::SerialValue;
63
64use crate::core::artifact::{ArtifactId, ArtifactSet};
65use crate::core::data::table::{PieceClass, ProjectCx, Table, TableHandle};
66use crate::core::piece::PiecePlace;
67use crate::lang::Flm;
68use crate::model::names::{BackendName, CapName, Name, OutputName};
69
70/// The name of the output region holding the document's content, `content`.
71pub const CONTENT: &str = "content";
72/// The name of the output region holding the stylesheets an HTML page loads,
73/// `styles`.
74pub const STYLES: &str = "styles";
75/// The name of the output region holding the scripts an HTML page loads,
76/// `scripts`.
77pub const SCRIPTS: &str = "scripts";
78/// The name of the output region holding the words of an HTML page's title,
79/// `title`.
80///
81/// The words are those of the document's title piece when the render places
82/// that piece and its words are not empty, else the title the HTML render
83/// options give
84/// ([`HtmlRenderOptions`](crate::stdlib::backends::html::HtmlRenderOptions)).
85/// The region's [`words`](Region::words) are the plain text, and its one part
86/// is that text escaped as HTML text.
87pub const TITLE: &str = "title";
88/// The name of the output region holding an HTML page's language tag, `lang`.
89///
90/// The region is present only when the HTML render options
91/// ([`HtmlRenderOptions`](crate::stdlib::backends::html::HtmlRenderOptions))
92/// give a language. Its [`words`](Region::words) are the tag, and its one
93/// part is the tag escaped as the value of an HTML attribute.
94pub const LANG: &str = "lang";
95/// The name of the output region holding the package name of the recomposed
96/// LaTeX's style file, `style-package`: the name with which a LaTeX document
97/// loads the style file through `\usepackage`.
98pub const STYLE_PACKAGE: &str = "style-package";
99
100/// One output region: its name, whether it is a piece, its parts, and the
101/// plain words of a piece or of the HTML title and language.
102///
103/// Build one with [`Region::new`], [`Region::with_words`] or
104/// [`Region::piece`]. A backend's regions stage pushes the regions of its
105/// output into a [`Regions`] table.
106#[derive(Debug, Clone, PartialEq, Eq)]
107pub struct Region {
108    /// The region's name: one of the names in the [module
109    /// documentation](self#the-region-names), or a piece's name.
110    pub name: Name,
111    /// Where the piece is placed, when the region is a piece; `None` for every
112    /// other region.
113    pub piece: Option<PiecePlace>,
114    /// The region's parts, in order, each written by the backend in its
115    /// output format (see the [module documentation](self#parts)).
116    pub parts: Vec<String>,
117    /// The region's **words**: its displayed characters as plain text, for a
118    /// place in the entry artifact where no markup is allowed, such as the
119    /// title of an HTML page or the value of an attribute. Set for a piece and
120    /// for the HTML regions [`TITLE`] and [`LANG`]; `None` for every other
121    /// region.
122    pub words: Option<String>,
123}
124
125impl Region {
126    /// Returns a region named `name` holding `parts`, which is not a piece
127    /// and has no words.
128    pub fn new(name: impl Into<Name>, parts: Vec<String>) -> Region {
129        Region { name: name.into(), piece: None, parts, words: None }
130    }
131
132    /// Returns a region named `name`, not a piece, holding the one part
133    /// `part`, with the words `words`: the form of the HTML regions [`TITLE`]
134    /// and [`LANG`].
135    pub fn with_words(name: impl Into<Name>, part: String, words: String) -> Region {
136        Region { name: name.into(), piece: None, parts: vec![part], words: Some(words) }
137    }
138
139    /// Returns the region of the piece `name`, placed at `place`, holding
140    /// `parts`, with the words `words` (computed by [`piece_words`]).
141    pub fn piece(
142        name: impl Into<Name>,
143        place: PiecePlace,
144        parts: Vec<String>,
145        words: String,
146    ) -> Region {
147        Region { name: name.into(), piece: Some(place), parts, words: Some(words) }
148    }
149
150    /// Returns the region as one text: its parts joined by line breaks.
151    ///
152    /// # Examples
153    ///
154    /// ```
155    /// use flm_core::core::region::Region;
156    ///
157    /// let region = Region::new("styles", vec![String::from("<style>a</style>"), String::from("<style>b</style>")]);
158    /// assert_eq!(region.text(), "<style>a</style>\n<style>b</style>");
159    /// ```
160    pub fn text(&self) -> String {
161        self.parts.join("\n")
162    }
163}
164
165/// Returns the words of a piece whose lowered tree is `tree`, as its region
166/// carries them ([`Region::words`]): the tree's plain text
167/// ([`plain_text`](crate::lang::text::plain_text)), with every run of white
168/// space replaced by one space and none at either end.
169///
170/// The HTML and recomposed LaTeX backends compute a piece's words with this
171/// function, so that both give the same words for the same piece.
172pub fn piece_words(tree: &NodeTree<Flm>) -> String {
173    crate::lang::text::plain_text(tree).split_whitespace().collect::<Vec<_>>().join(" ")
174}
175
176/// The output regions of one output, and what the entry artifact assembled
177/// from them is: the value of the table `flm.output.<backend>.regions`, which
178/// a backend's regions stage writes once per run.
179///
180/// The backend's final stage, or a host's template stage, reads it to make
181/// the entry artifact; see the [module documentation](self).
182#[derive(Debug, Clone, PartialEq, Eq)]
183pub struct Regions {
184    /// The identity of the entry artifact.
185    pub entry: ArtifactId,
186    /// The entry artifact's media type. Every assembler, the backend's final
187    /// stage and a host's template stage alike, takes it from here.
188    pub media_type: String,
189    /// The artifacts the entry artifact refers to, among those the backend
190    /// writes beside it, such as the style file of the recomposed LaTeX. The
191    /// final stage copies them into the entry artifact's
192    /// [`refs`](crate::core::artifact::Artifact::refs).
193    pub refs: Vec<ArtifactId>,
194    /// The regions, in the order the backend wrote them; no name occurs
195    /// twice.
196    pub regions: Vec<Region>,
197}
198
199impl Regions {
200    /// Returns a table with no region yet, for an entry artifact of identity
201    /// `entry` and media type `media_type`.
202    pub fn new(entry: ArtifactId, media_type: impl Into<String>) -> Regions {
203        Regions { entry, media_type: media_type.into(), refs: Vec::new(), regions: Vec::new() }
204    }
205
206    /// Returns the region named `name`, or `None` when there is none.
207    pub fn get(&self, name: &str) -> Option<&Region> {
208        self.regions.iter().find(|region| region.name.as_str() == name)
209    }
210
211    /// Returns the regions that are pieces placed at `place`, in order.
212    pub fn pieces_at(&self, place: PiecePlace) -> impl Iterator<Item = &Region> + '_ {
213        self.regions.iter().filter(move |region| region.piece == Some(place))
214    }
215
216    /// Returns the regions that are pieces, in order.
217    pub fn pieces(&self) -> impl Iterator<Item = &Region> + '_ {
218        self.regions.iter().filter(|region| region.piece.is_some())
219    }
220}
221
222impl Default for Regions {
223    /// Returns an empty table: no region, and an entry artifact whose identity
224    /// and media type are empty, which the backend's regions stage replaces.
225    fn default() -> Regions {
226        Regions::new(ArtifactId::new("", ""), "")
227    }
228}
229
230impl Table for Regions {
231    /// Replaces the table's value: one stage per run writes the table, the
232    /// backend's regions stage, so a second table piece replaces the first.
233    fn absorb(&mut self, piece: Regions) {
234        *self = piece;
235    }
236
237    /// `{entry, media_type, refs: [id], regions: [{name, piece?, parts: [text], words?}]}`.
238    fn project(&self, _cx: &dyn ProjectCx) -> SerialValue {
239        let regions = self
240            .regions
241            .iter()
242            .map(|region| {
243                let mut entries =
244                    vec![(String::from("name"), SerialValue::Str(region.name.to_string()))];
245                if let Some(place) = region.piece {
246                    entries.push((String::from("piece"), SerialValue::Str(place.as_str().into())));
247                }
248                entries.push((
249                    String::from("parts"),
250                    SerialValue::List(
251                        region.parts.iter().map(|part| SerialValue::Str(part.clone())).collect(),
252                    ),
253                ));
254                if let Some(words) = &region.words {
255                    entries.push((String::from("words"), SerialValue::Str(words.clone())));
256                }
257                SerialValue::Map(entries)
258            })
259            .collect();
260        SerialValue::Map(vec![
261            (String::from("entry"), SerialValue::Str(self.entry.to_string())),
262            (String::from("media_type"), SerialValue::Str(self.media_type.clone())),
263            (
264                String::from("refs"),
265                SerialValue::List(
266                    self.refs.iter().map(|id| SerialValue::Str(id.to_string())).collect(),
267                ),
268            ),
269            (String::from("regions"), SerialValue::List(regions)),
270        ])
271    }
272
273    fn piece_class(&self) -> PieceClass {
274        PieceClass::DocumentFact
275    }
276}
277
278/// A regions output: a backend's statement that its output is made of output
279/// regions (which table holds them and which capability its final stage
280/// provides), contributed to the service slot `flm.output.regions` so that a
281/// host's own assembler can read it.
282///
283/// A backend contributes one per such output to the service slot
284/// [`flm.output.regions`](crate::stdlib::backends::lowering::REGIONS_SLOT);
285/// see the [module documentation](self#which-outputs-are-made-of-regions).
286#[derive(Debug, Clone)]
287pub struct RegionsOutput {
288    /// The output's name, with which a caller asks for it.
289    pub output: OutputName,
290    /// The backend that writes the output's regions.
291    pub backend: BackendName,
292    /// The name of the output's table that holds its artifact set, which its
293    /// final stage writes.
294    pub document: CapName,
295    /// The capability a request for the output demands: the capability of the
296    /// [`document`](RegionsOutput::document) table, or a refinement of it that
297    /// the final stage provides. A host's template stage provides this
298    /// capability to take the final stage's place.
299    pub capability: CapName,
300    /// The table of the output's regions, `flm.output.<backend>.regions`.
301    pub regions: TableHandle<Regions>,
302    /// The tables of the files that the output's stages write beside its
303    /// entry artifact, in the order in which they are added to the output's
304    /// artifact set ([`ArtifactSet::insert_entry_with`]): the backend's own
305    /// files (the recomposed LaTeX's style file), then the output's artifact
306    /// table `flm.output.<backend>.artifacts`, which only the `graphics`
307    /// feature's publish stage writes (its copies of images). Empty for an
308    /// output of one file. An assembler reads each table when a stage of the
309    /// plan writes it.
310    pub artifacts: Vec<TableHandle<ArtifactSet>>,
311}