flm_core/stdlib/features/xnotes/html.rs
1//! The lowering rules of the [`xnotes`](super) feature for the `html`
2//! backend, and the feature's stylesheet.
3//!
4//! On the HTML page, an xnote and a list of xnotes are written with the same
5//! presentation elements as on every other output: the rules of this module
6//! call the staging helpers of the general rules
7//! ([`stage_mark`](super::stage_mark), [`stage_in_place`](super::stage_in_place),
8//! [`ListRule`]), so that the page writes the same structure as the other
9//! outputs that use these shapes, and
10//! the HTML backend writes those elements as its HTML contract states (the
11//! classes and attributes a stylesheet may rely on; see
12//! [`CONVENTIONS`](crate::stdlib::backends::html::CONVENTIONS) and [the HTML
13//! contract](crate::guide::rendering#the-html-contract)). The rules of this
14//! module are marked default on the `html` backend and add what only the page
15//! needs:
16//!
17//! - the **link back** from each entry of a list of xnotes to its mark
18//! ([`ListHtmlRule`]);
19//! - **no bracket text** around an xnote shown in place ([`XnoteHtmlRule`]):
20//! the stylesheet draws the brackets, so that a page's own stylesheet can
21//! replace them;
22//! - the **stylesheet** [`STYLE`] (`flm.xnotes.style`). The staging helpers
23//! that the general rules and these rules share require the feature's
24//! style identifier [`STYLE`] at every xnote and every list: they record it
25//! as a requirement of the output, and on this backend it names the
26//! stylesheet, which the backend then writes or loads (see [`StyleDef`]).
27//!
28//! # The markup
29//!
30//! The worked example, `The claim holds in every case.\footnote{Except the
31//! empty one, which we exclude by convention.} The next sentence goes on.`,
32//! writes the mark as a superscript carrying the mark's anchor (its `id`),
33//! around a link to the xnote. The link carries the document role
34//! `doc-noteref` and an accessible name (the name that assistive technology
35//! reads in place of the link's text), so that a screen reader announces
36//! "Footnote 1" rather than "1":
37//!
38//! ```html
39//! <p class="flm-pres-par">The claim holds in every case.<sup class="flm-pres-span flm-xnotes-xnote-mark" id="fnref--1yuhk" data-flm-style="superscript"><a class="flm-pres-link" href="#fn-1" role="doc-noteref" aria-label="Footnote 1" data-flm-kind="xnote">1</a></sup> The next sentence goes on.</p>
40//! ```
41//!
42//! The list of the xnote kind is placed after the document's content: a block
43//! of the document role `doc-endnotes` holding the title as a heading and a
44//! labeled list whose entries carry the xnotes' anchors. The last paragraph of
45//! each entry ends with a link back to the mark, of the role `doc-backlink`,
46//! whose text is the kind's [`backlink`](super::XnoteKind::backlink) (`↩`) and
47//! whose accessible name is `Back to ` followed by the xnote's name as a
48//! reference writes it:
49//!
50//! ```html
51//! <div class="flm-pres-block flm-xnotes-footnote-list" role="doc-endnotes" data-flm-kind="xnotes footnote">
52//! <h2 class="flm-pres-block--heading" data-flm-heading="xnotes" data-flm-level="2" data-flm-toc="false">Footnotes</h2>
53//! <ol class="flm-pres-list" data-flm-kind="numbered xnotes footnote labeled">
54//! <li id="fn-1"><span class="flm-pres-list-label"><sup class="flm-pres-span flm-xnotes-entry-mark" data-flm-style="superscript">1</sup></span>
55//! <p class="flm-pres-par">Except the empty one, which we exclude by convention. <a class="flm-pres-link" href="#fnref--1yuhk" role="doc-backlink" aria-label="Back to Footnote 1" data-flm-kind="xnote-back">↩</a></p>
56//! </li>
57//! </ol>
58//! </div>
59//! ```
60//!
61//! The heading is written with the tag of its level, or with the tag to which
62//! the render option
63//! [`heading_tags`](crate::stdlib::backends::html::HtmlRenderOptions::heading_tags)
64//! maps the heading name `xnotes` ([`TITLE_HEADING`](super::TITLE_HEADING)).
65//! Where the plan computes no anchors (in a registry without the references
66//! feature), the mark has no link and the entry no link back.
67//!
68//! An xnote of a kind shown **in place** is one span where its content is
69//! inline, carrying the xnote's anchor, its kind tokens and the document role
70//! `doc-footnote`, with the mark inside it and no link:
71//!
72//! ```html
73//! …every case. <span class="flm-pres-span flm-xnotes-xnote-inplace" id="fn-1" role="doc-footnote" data-flm-kind="xnotes footnote"><sup class="flm-pres-span flm-xnotes-xnote-mark" id="fnref--1yuhk" data-flm-style="superscript">1</sup>Except the empty one, which we exclude by convention.</span> The next…
74//! ```
75//!
76//! Where its content holds paragraphs, it is a block, as a list is: the
77//! paragraph it is written in ends before it, the text after it is a new
78//! paragraph, and its mark is at the head of its first paragraph:
79//!
80//! ```html
81//! <p class="flm-pres-par">Two paragraphs.</p>
82//! <div class="flm-pres-block flm-xnotes-xnote-inplace" id="fn-1" role="doc-footnote" data-flm-kind="xnotes footnote">
83//! <p class="flm-pres-par"><sup class="flm-pres-span flm-xnotes-xnote-mark" id="fnref--1yuhk" data-flm-style="superscript">1</sup>First paragraph.</p>
84//! <p class="flm-pres-par">Second paragraph.</p>
85//! </div>
86//! <p class="flm-pres-par">And on.</p>
87//! ```
88//!
89//! The mark of an unnumbered xnote kind is its fixed mark, and an empty fixed
90//! mark gives an empty `<sup>`, so that the mark's anchor still exists.
91//!
92//! # The stylesheet
93//!
94//! The style definition [`stylesheet`] (`flm.xnotes.style`; see
95//! [`StyleDef`]) is one cascade layer holding the line above a list of xnotes,
96//! with a space between the line and the list's content, and the brackets
97//! around an xnote shown in place, and nothing more. Every
98//! value it uses is a custom property declared in it
99//! (`--flm-xnotes-list-rule`, `--flm-xnotes-list-size`,
100//! `--flm-xnotes-list-space`, `--flm-xnotes-list-padding`,
101//! `--flm-xnotes-inplace-open`, `--flm-xnotes-inplace-close`), which a page sets to change these values
102//! without writing a rule of its own. The xnote and the list require it, so a
103//! page holding no xnote does not carry it.
104//!
105//! **The feature ships no script.** An xnote shown in place is always written
106//! whole, with every anchor, role and kind token as an attribute, so that a
107//! page's own stylesheet or script can lay it out, hide it or show it; a
108//! script shipped by the feature would interfere with the page's own. A host
109//! adds a stylesheet or a script of its own by declaring a style or script
110//! definition in a feature of its own
111//! ([`FeatureBuilder::style_def`](crate::core::registry::FeatureBuilder::style_def),
112//! [`script_def`](crate::core::registry::FeatureBuilder::script_def)) and
113//! requiring it from a rule, or replaces the content of this stylesheet
114//! through the render option
115//! [`definitions`](crate::stdlib::backends::html::HtmlRenderOptions::definitions).
116//!
117//! # Registration
118//!
119//! The rules are marked default on the `html` backend only, and are
120//! registered under a peer declaration
121//! ([`PeerName`](crate::core::registry::PeerName)) of that backend, so that a
122//! registry without the backend still builds, with the rules set aside
123//! (excluded from rule selection). The `xnotes` feature registers the
124//! stylesheet and, where a configured xnote kind has a command, the xnote's
125//! rule ([`html_rule`]);
126//! [`contribute_kind`](super::contribute_kind) registers the list's rule for
127//! each xnote kind, like every rule of a kind's list.
128
129use std::sync::Arc;
130
131use techy::core::node::{BuildId, NodeRef};
132
133use crate::core::lowering::{
134 DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringRule,
135};
136use crate::core::registry::{BuildError, DefContent, FeatureBuilder, StyleDef};
137use crate::lang::Flm;
138use crate::model::names::{ElementName, Name, RuleName};
139use crate::stdlib::backends::html::BACKEND;
140use crate::stdlib::backends::pres::{self, DocRole, LinkPayload};
141use crate::stdlib::features::refs::ANCHORS;
142
143use super::config::XnoteKind;
144use super::list::{list_decl, ListRule};
145use super::lower::{accessible_name, lower_xnote, Brackets};
146use super::stages::XnoteRecord;
147use super::{list_element_name, xnote_decl, BACKLINK_KIND, STYLE, XNOTE};
148
149/// The name of the lowering rule of an xnote on the `html` backend,
150/// `flm.xnotes.xnote.lower.html` ([`XnoteHtmlRule`]).
151pub const HTML_RULE: &str = "flm.xnotes.xnote.lower.html";
152
153/// The words with which the accessible name of an entry's link back to its
154/// mark begins, before the xnote's name: `Back to`.
155pub const BACKLINK_LABEL_PREFIX: &str = "Back to";
156
157/// The name of the lowering rule of the list element of the xnote kind `kind`
158/// on the `html` backend, `flm.xnotes.<kind>.list.lower.html`
159/// ([`ListHtmlRule`]).
160pub fn list_rule_name(kind: &str) -> RuleName {
161 RuleName::from(format!("{}.lower.html", list_element_name(kind)))
162}
163
164/// The feature's style definition, `flm.xnotes.style` ([`STYLE`]): the line
165/// above a list of xnotes and the brackets around an xnote shown in place,
166/// in one cascade layer, with every value a custom property it declares. The
167/// `xnotes` feature registers it; the xnote and the list require it.
168/// See the [module documentation](self).
169pub fn stylesheet() -> StyleDef {
170 StyleDef {
171 id: Name::from(STYLE),
172 content: vec![DefContent::Inline(String::from(include_str!("css/xnotes.css")))],
173 docs: String::from(
174 "the line above a list of xnotes and the brackets around an xnote shown in place",
175 ),
176 }
177}
178
179/// The lowering rule of an xnote on the `html` backend, [`HTML_RULE`]: the
180/// xnote's mark, or the xnote in place, as the general rule writes them
181/// ([`stage_mark`](super::stage_mark),
182/// [`stage_in_place`](super::stage_in_place)), but with no bracket text,
183/// because the stylesheet draws the brackets. It requires the style
184/// identifier [`STYLE`] and reports the refused content of the optional
185/// argument as the general rule does.
186#[derive(Debug, Default, Clone, Copy)]
187pub struct XnoteHtmlRule;
188
189impl Lower for XnoteHtmlRule {
190 fn lower(
191 &self,
192 node: NodeRef<'_, Flm>,
193 cx: &mut LowerCx<'_>,
194 lw: &mut dyn Lowerer,
195 ) -> Result<Lowering, LowerError> {
196 lower_xnote(&node, cx, lw, Brackets::Drawn)
197 }
198}
199
200/// The lowering rule of an xnote kind's list element on the `html` backend
201/// ([`list_rule_name`]): the list as the general rule writes it
202/// ([`ListRule`]), with the link back to each xnote's mark at the end of the
203/// last paragraph of its entry. It requires the style identifier [`STYLE`],
204/// as the general rule does.
205///
206/// The link back is
207/// `flm.pres.link { href: "#<the mark's anchor>", kind: xnote-back,
208/// doc_role: BackLink, label: "Back to <the xnote's name>" }` holding the
209/// kind's [`backlink`](XnoteKind::backlink) text, after a space. The xnote's
210/// name is the kind's singular word, as a reference writes it in running text
211/// (with no variant), then the xnote's number as a reference writes it
212/// without the word (`Back to Footnote 1`); the word alone where there is no
213/// number. There is no link back where the mark has no anchor (in a registry
214/// without the references feature), for an entry whose pointer refers to no
215/// recorded xnote, and for a kind whose `backlink` text is empty.
216#[derive(Debug)]
217pub struct ListHtmlRule {
218 kind: Arc<XnoteKind>,
219 list: Arc<ListRule>,
220}
221
222impl Lower for ListHtmlRule {
223 fn lower(
224 &self,
225 node: NodeRef<'_, Flm>,
226 cx: &mut LowerCx<'_>,
227 lw: &mut dyn Lowerer,
228 ) -> Result<Lowering, LowerError> {
229 let kind = &self.kind;
230 self.list.lower_list(&node, cx, lw, &mut |cx, lw, record| backlink(cx, lw, kind, record))
231 }
232}
233
234/// Stages the link back from the entry of the xnote `record` of the xnote
235/// kind `kind` to its mark, after a space, as [`ListHtmlRule`] documents it;
236/// nothing where there is no link back.
237fn backlink(
238 cx: &mut LowerCx<'_>,
239 lw: &mut dyn Lowerer,
240 kind: &XnoteKind,
241 record: Option<&XnoteRecord>,
242) -> Result<Vec<BuildId>, LowerError> {
243 let Some(record) = record else { return Ok(Vec::new()) };
244 if kind.backlink.is_empty() {
245 return Ok(Vec::new());
246 }
247 let mark = match lw.get(ANCHORS)? {
248 Some(anchors) => anchors.lookup(record.mark).flatten().map(String::from),
249 None => None,
250 };
251 let Some(mark) = mark else { return Ok(Vec::new()) };
252 // The word a reference writes in running text, with no variant and never
253 // re-cased: the kind's words are the one source of its wording, and a
254 // change of case misfires on a word such as an acronym or a proper name.
255 let name = accessible_name(lw, kind, &kind.words.base.one, record.point)?;
256 let label = if name.is_empty() {
257 String::from(BACKLINK_LABEL_PREFIX)
258 } else {
259 format!("{BACKLINK_LABEL_PREFIX} {name}")
260 };
261 let link = LinkPayload {
262 href: format!("#{mark}"),
263 kind: Name::from(BACKLINK_KIND),
264 doc_role: Some(DocRole::BackLink),
265 label: Some(label),
266 shows_target: false,
267 };
268 let text = lw.text(cx, &kind.backlink)?;
269 let space = lw.text(cx, " ")?;
270 Ok(vec![space, lw.pres_with(cx, &ElementName::from(pres::LINK), link, vec![text])?])
271}
272
273/// The lowering rule of an xnote on the `html` backend, [`HTML_RULE`]
274/// ([`XnoteHtmlRule`]), marked default on that backend only.
275pub fn html_rule() -> LoweringRule {
276 LoweringRule::new(HTML_RULE, XNOTE, xnote_decl(), Arc::new(XnoteHtmlRule), on_html())
277 .docs(
278 "an xnote lowers as under the general rule, with no bracket text around an xnote \
279 shown in place: the stylesheet `flm.xnotes.style`, which the rule requires, draws \
280 the brackets",
281 )
282}
283
284/// The lowering rule of the list element of the xnote kind `kind` on the
285/// `html` backend ([`ListHtmlRule`], [`list_rule_name`]), marked default on
286/// that backend only, writing the list as `list` does, with the links back.
287fn list_html_rule(kind: &Arc<XnoteKind>, list: Arc<ListRule>) -> LoweringRule {
288 let name = kind.name.as_str();
289 LoweringRule::new(
290 list_rule_name(name),
291 list_element_name(name),
292 list_decl().produces(pres::LINK),
293 Arc::new(ListHtmlRule { kind: Arc::clone(kind), list }),
294 on_html(),
295 )
296 .docs(
297 "the list of a kind's xnotes lowers as under the general rule, each entry's last \
298 paragraph ending with a link back to the xnote's mark; it requires the stylesheet \
299 `flm.xnotes.style`",
300 )
301}
302
303/// The default mark of every rule of this module: default on the `html`
304/// backend only.
305fn on_html() -> DefaultMark {
306 DefaultMark::OnBackends(vec![BACKEND.into()])
307}
308
309/// Makes a peer declaration of the `html` backend, on behalf of the feature
310/// that `b` registers, so that a registry without the backend builds with the
311/// rules of this module set aside. Every call declares it: the registry
312/// merges an identical repeated peer declaration into the first.
313fn declare_backend(b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
314 b.peer_backend(BACKEND, "the html backend, on which the HTML rules of xnotes are the default")
315}
316
317/// Registers what the `xnotes` feature itself contributes to the page: the
318/// stylesheet ([`stylesheet`]), and, where the configuration declares an
319/// xnote kind with a command (where the element [`XNOTE`] exists), the
320/// xnote's rule ([`html_rule`]) under the peer declaration of the backend.
321///
322/// # Errors
323///
324/// The [`BuildError`] of the registry builder when a declaration is made
325/// in a [registration round](crate::core::registry::builder#the-two-registration-rounds)
326/// that does not accept it (from a finalizer, for instance).
327pub(super) fn register(b: &mut FeatureBuilder<'_>, with_element: bool) -> Result<(), BuildError> {
328 // Declared once, by this feature, never per kind: a kind another feature
329 // contributes places no list where this feature is absent, and a single
330 // declaration keeps one entry in the table of definitions.
331 b.style_def(stylesheet())?;
332 if with_element {
333 declare_backend(b)?;
334 b.lowering_rule(html_rule())?;
335 }
336 Ok(())
337}
338
339/// Declares what the xnote kind `kind` needs on the page, on behalf of the
340/// feature that `b` registers: the rule of its list element on the `html`
341/// backend, which writes the list as `list` (the kind's general rule) does,
342/// under the peer declaration of the backend.
343/// [`contribute_kind`](super::contribute_kind) calls it once per kind.
344///
345/// Only the `xnotes` feature declares the stylesheet the rule requires: where
346/// that feature is absent, no list of the kind has entries to write.
347///
348/// # Errors
349///
350/// The [`BuildError`] of the registry builder when a declaration is made
351/// in a [registration round](crate::core::registry::builder#the-two-registration-rounds)
352/// that does not accept it (from a finalizer, for instance).
353pub(super) fn declare_kind(
354 b: &mut FeatureBuilder<'_>,
355 kind: &Arc<XnoteKind>,
356 list: Arc<ListRule>,
357) -> Result<(), BuildError> {
358 declare_backend(b)?;
359 b.lowering_rule(list_html_rule(kind, list))
360}
361
362#[cfg(test)]
363mod tests {
364 use super::*;
365
366 #[test]
367 fn the_rules_are_the_defaults_on_the_html_backend_only() {
368 let rule = html_rule();
369 assert_eq!(rule.name, HTML_RULE);
370 assert_eq!(rule.element, XNOTE);
371 assert!(rule.default.is_specific_to(&BACKEND.into()));
372 assert_eq!(list_rule_name("footnote").as_str(), "flm.xnotes.footnote.list.lower.html");
373 }
374
375 #[test]
376 fn the_stylesheet_names_itself_and_is_one_layer() {
377 let style = stylesheet();
378 assert_eq!(style.id.as_str(), "flm.xnotes.style");
379 let [DefContent::Inline(css)] = style.content.as_slice() else { panic!("one inline part") };
380 assert_eq!(css.lines().next(), Some("/* flm.xnotes.style */"));
381 assert_eq!(css.matches("@layer flm {").count(), 1);
382 }
383}