use std::sync::Arc;
use techy::core::node::NodeRef;
use crate::core::lowering::{
DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
};
use crate::core::registry::{BuildError, FeatureBuilder};
use crate::lang::Flm;
use crate::model::names::{ElementName, Name};
use crate::stdlib::backends::pres::{self, I48F16, Length, LengthUnit, ParPayload, SpanPayload, SpanStyle};
use crate::stdlib::backends::text::construct::{RULED, RuledPayload};
use crate::stdlib::backends::text::BACKEND;
use super::rules::{block, entry_lines, inline_content};
use super::{AUTHOR_ENTRY, AUTHOR_NAME, STYLE, TITLE};
pub fn text_rule_name(element: &str) -> String {
format!("{element}.lower.text")
}
#[derive(Debug, Default)]
pub struct TitleTextRule;
impl Lower for TitleTextRule {
fn lower(
&self,
node: NodeRef<'_, Flm>,
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
) -> Result<Lowering, LowerError> {
lw.require(&Name::from(STYLE));
let content = inline_content(&node, cx, lw)?;
let bold = SpanPayload { style: Some(SpanStyle::Bold), ..SpanPayload::default() };
let span = lw.pres_with(cx, &ElementName::from(pres::SPAN), bold, content)?;
let par = lw.pres_with(cx, &ElementName::from(pres::PAR), ParPayload::default(), vec![span])?;
let ruled = lw.pres_with(cx, &ElementName::from(RULED), RuledPayload { above: true, below: true }, vec![par])?;
Ok(Lowering::Emit(vec![lw.pres_with(cx, &ElementName::from(pres::BLOCK), block(TITLE), vec![ruled])?]))
}
}
#[derive(Debug, Default)]
pub struct EntryTextRule;
impl Lower for EntryTextRule {
fn lower(
&self,
node: NodeRef<'_, Flm>,
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
) -> Result<Lowering, LowerError> {
let indent = |element: &str| {
if element == AUTHOR_NAME { Length::default() } else { Length::new(I48F16::ONE, LengthUnit::Ems) }
};
Ok(Lowering::Emit(vec![entry_lines(&node, cx, lw, indent)?]))
}
}
pub(super) fn register(b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
b.peer_backend(BACKEND, "the text backend, on which the metadata's text rules are the default")?;
b.peer_element::<RuledPayload>(RULED, "the text backend's ruled construct, which the title's rule stages")?;
let on_backend = || DefaultMark::OnBackends(vec![BACKEND.into()]);
b.lowering_rule(
LoweringRule::new(
text_rule_name(TITLE),
TITLE,
LoweringDecl::new().produces(pres::BLOCK).produces(RULED).produces(pres::PAR).produces(pres::SPAN),
Arc::new(TitleTextRule),
on_backend(),
)
.docs(
"on the text output, the title is a `flm.pres.block` holding a `flm.pres.text.ruled` with a rule \
above and under, over one paragraph whose content is the title in a bold span",
),
)?;
b.lowering_rule(
LoweringRule::new(
text_rule_name(AUTHOR_ENTRY),
AUTHOR_ENTRY,
LoweringDecl::new().produces(pres::LINES).produces(pres::LINE),
Arc::new(EntryTextRule),
on_backend(),
)
.docs(
"on the text output, an author is a `flm.pres.lines`, the name at the margin and each other part \
on a `flm.pres.line` indented by `1em`",
),
)?;
Ok(())
}