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