1use std::sync::Arc;
50
51use techy::core::node::{BuildId, NodeRef, NodeSlice};
52
53use crate::core::lowering::{
54 DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
55};
56use crate::core::registry::{BuildError, FeatureBuilder};
57use crate::lang::mint::{ElementDef, SyntaxDef};
58use crate::lang::Flm;
59use crate::model::aspects::{BlockRole, BlockRoleAspect, FixedBlockRole};
60use crate::model::element::ElementSpec;
61use crate::model::names::{ElementName, Name};
62use crate::stdlib::backends::lowering::lower_blocks_with_edges;
63use crate::stdlib::backends::pres::{self, BlockPayload, LinePayload, LinesPayload, LinkPayload, SpanPayload};
64use crate::stdlib::features::href::LINK_KIND;
65
66use super::{
67 EmailPayload, AUTHOR, AUTHOR_AFFILIATION, AUTHOR_EMAIL, AUTHOR_ENTRY, AUTHOR_NAME, AUTHOR_NOTE, DATE,
68 KIND_METADATA, STYLE, TITLE,
69};
70
71const MAILTO: &str = "mailto:";
74
75pub fn rule_name(element: &str) -> String {
78 format!("{element}.lower.default")
79}
80
81fn block(role: &str) -> BlockPayload {
84 BlockPayload { role: Some(Name::from(role)), kinds: vec![Name::from(KIND_METADATA)], anchor: None, doc_role: None }
85}
86
87fn span(role: &str) -> SpanPayload {
90 SpanPayload { role: Some(Name::from(role)), ..SpanPayload::default() }
91}
92
93pub(super) fn each_child<'t>(node: &NodeRef<'t, Flm>) -> Result<Vec<NodeSlice<'t, Flm>>, LowerError> {
96 let children = node.children();
97 let start = children.range().start;
98 (0u32..)
99 .zip(children.iter())
100 .map(|(index, _)| {
101 node.tree()
102 .slice(start + index..start + index + 1)
103 .ok_or_else(|| LowerError::structure("a child outside its parent's children"))
104 })
105 .collect()
106}
107
108pub(super) fn inline_content(
111 node: &NodeRef<'_, Flm>,
112 cx: &mut LowerCx<'_>,
113 lw: &mut dyn Lowerer,
114) -> Result<Vec<BuildId>, LowerError> {
115 let paragraph = Arc::clone(&lw.lang().structural().paragraph);
116 let mut content = Vec::new();
117 for (one, child) in each_child(node)?.into_iter().zip(node.children().iter()) {
118 if child.ext().element.name == paragraph.name {
119 content.extend(lw.lower_children(cx, &child)?);
120 } else {
121 content.extend(lw.lower_nodes(cx, one)?);
122 }
123 }
124 Ok(content)
125}
126
127#[derive(Debug)]
136pub struct MetaTextRule {
137 role: &'static str,
138}
139
140impl Lower for MetaTextRule {
141 fn lower(
142 &self,
143 node: NodeRef<'_, Flm>,
144 cx: &mut LowerCx<'_>,
145 lw: &mut dyn Lowerer,
146 ) -> Result<Lowering, LowerError> {
147 lw.require(&Name::from(STYLE));
148 let content: Vec<NodeRef<'_, Flm>> = node.children().iter().collect();
149 let body = lower_blocks_with_edges(cx, lw, &content, Vec::new(), Vec::new())?;
150 Ok(Lowering::Emit(vec![lw.pres_with(cx, &ElementName::from(pres::BLOCK), block(self.role), body)?]))
151 }
152}
153
154#[derive(Debug, Default)]
159pub struct AuthorRule;
160
161impl Lower for AuthorRule {
162 fn lower(
163 &self,
164 node: NodeRef<'_, Flm>,
165 cx: &mut LowerCx<'_>,
166 lw: &mut dyn Lowerer,
167 ) -> Result<Lowering, LowerError> {
168 lw.require(&Name::from(STYLE));
169 let body = lw.lower_children(cx, &node)?;
170 Ok(Lowering::Emit(vec![lw.pres_with(cx, &ElementName::from(pres::BLOCK), block(AUTHOR), body)?]))
171 }
172}
173
174#[derive(Debug, Default)]
181pub struct EntryRule;
182
183impl Lower for EntryRule {
184 fn lower(
185 &self,
186 node: NodeRef<'_, Flm>,
187 cx: &mut LowerCx<'_>,
188 lw: &mut dyn Lowerer,
189 ) -> Result<Lowering, LowerError> {
190 let mut lines = Vec::new();
191 for one in each_child(&node)? {
192 let part = lw.lower_nodes(cx, one)?;
193 lines.push(lw.pres_with(cx, &ElementName::from(pres::LINE), LinePayload::default(), part)?);
194 }
195 Ok(Lowering::Emit(vec![lw.pres_with(cx, &ElementName::from(pres::LINES), LinesPayload, lines)?]))
196 }
197}
198
199#[derive(Debug)]
204pub struct PartRule {
205 role: &'static str,
206}
207
208impl Lower for PartRule {
209 fn lower(
210 &self,
211 node: NodeRef<'_, Flm>,
212 cx: &mut LowerCx<'_>,
213 lw: &mut dyn Lowerer,
214 ) -> Result<Lowering, LowerError> {
215 let content = inline_content(&node, cx, lw)?;
216 Ok(Lowering::Emit(vec![lw.pres_with(cx, &ElementName::from(pres::SPAN), span(self.role), content)?]))
217 }
218}
219
220#[derive(Debug, Default)]
232pub struct EmailRule;
233
234impl Lower for EmailRule {
235 fn lower(
236 &self,
237 node: NodeRef<'_, Flm>,
238 cx: &mut LowerCx<'_>,
239 lw: &mut dyn Lowerer,
240 ) -> Result<Lowering, LowerError> {
241 let address = email_of(&node)?;
242 let payload = LinkPayload {
243 href: format!("{MAILTO}{address}"),
244 kind: Name::from(LINK_KIND),
245 doc_role: None,
246 label: None,
247 shows_target: true,
248 };
249 let text = lw.text(cx, address)?;
250 let link = lw.pres_with(cx, &ElementName::from(pres::LINK), payload, vec![text])?;
251 Ok(Lowering::Emit(vec![lw.pres_with(cx, &ElementName::from(pres::SPAN), span(AUTHOR_EMAIL), vec![link])?]))
252 }
253}
254
255pub(super) fn email_of<'n>(node: &'n NodeRef<'_, Flm>) -> Result<&'n str, LowerError> {
261 EmailPayload::of(node)
262 .map(|payload| payload.address.as_str())
263 .ok_or_else(|| LowerError::structure("missing ‘EmailPayload’ on an author’s email node"))
264}
265
266pub(super) fn declare(b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
269 let owner = b.feature().clone();
270 let elements = [
271 (TITLE, "The document's title.", "The title of the document, built from its metadata."),
272 (
273 AUTHOR,
274 "The document's authors, one author per child.",
275 "The list of the document's authors, built from its metadata.",
276 ),
277 (
278 AUTHOR_ENTRY,
279 "One author of the document: the name, then each affiliation, the email address and each note.",
280 "One author of the document, in the list of its authors.",
281 ),
282 (AUTHOR_NAME, "An author's name.", "The name of one author of the document."),
283 (
284 AUTHOR_AFFILIATION,
285 "One affiliation of an author, with its number among the document's affiliations.",
286 "One affiliation of one author of the document.",
287 ),
288 (
289 AUTHOR_EMAIL,
290 "An author's email address, a plain text.",
291 "The email address of one author of the document.",
292 ),
293 (AUTHOR_NOTE, "One note about an author.", "One note about one author of the document."),
294 (DATE, "The document's date.", "The date of the document, built from its metadata."),
295 ];
296 for (name, docs, type_docs) in elements {
297 b.element_type_text(name, type_docs)?;
298 let role = Arc::new(FixedBlockRole(BlockRole::Block)) as Arc<dyn BlockRoleAspect>;
299 b.element(
300 ElementDef::new(
301 owner.clone(),
302 Vec::<&str>::new(),
303 SyntaxDef::Synthesized,
304 Arc::new(ElementSpec::new(name).docs(docs).with(role)),
305 )
306 .docs(format!("{docs} No document can write it: a stage builds it from the metadata.")),
307 )?;
308 }
309 for element in [TITLE, DATE] {
310 b.lowering_rule(
311 LoweringRule::new(
312 rule_name(element),
313 element,
314 LoweringDecl::new().produces(pres::BLOCK).produces(pres::PAR),
315 Arc::new(MetaTextRule { role: element }),
316 DefaultMark::Everywhere,
317 )
318 .docs(format!("`{element}` lowers to a `flm.pres.block` holding the text as one paragraph")),
319 )?;
320 }
321 b.lowering_rule(
322 LoweringRule::new(
323 rule_name(AUTHOR),
324 AUTHOR,
325 LoweringDecl::new().produces(pres::BLOCK),
326 Arc::new(AuthorRule),
327 DefaultMark::Everywhere,
328 )
329 .docs("the authors lower to a `flm.pres.block` holding each author in order"),
330 )?;
331 b.lowering_rule(
332 LoweringRule::new(
333 rule_name(AUTHOR_ENTRY),
334 AUTHOR_ENTRY,
335 LoweringDecl::new().produces(pres::LINES).produces(pres::LINE),
336 Arc::new(EntryRule),
337 DefaultMark::Everywhere,
338 )
339 .docs("an author lowers to a `flm.pres.lines`, each part of the author on a `flm.pres.line` of its own"),
340 )?;
341 for element in [AUTHOR_NAME, AUTHOR_AFFILIATION, AUTHOR_NOTE] {
342 b.lowering_rule(
343 LoweringRule::new(
344 rule_name(element),
345 element,
346 LoweringDecl::new().produces(pres::SPAN),
347 Arc::new(PartRule { role: element }),
348 DefaultMark::Everywhere,
349 )
350 .docs(format!("`{element}` lowers to a `flm.pres.span` of role `{element}` holding the text")),
351 )?;
352 }
353 b.lowering_rule(
354 LoweringRule::new(
355 rule_name(AUTHOR_EMAIL),
356 AUTHOR_EMAIL,
357 LoweringDecl::new().produces(pres::SPAN).produces(pres::LINK),
358 Arc::new(EmailRule),
359 DefaultMark::Everywhere,
360 )
361 .docs(
362 "an email address lowers to a `flm.pres.span` of role `flm.metadata.author.email` holding a \
363 `flm.pres.link` of kind `url` to `mailto:` followed by the address, showing the address",
364 ),
365 )?;
366 Ok(())
367}