use comemo::Track;
use ecow::eco_format;
use crate::diag::{bail, At, Hint, SourceResult};
use crate::engine::Engine;
use crate::foundations::{
cast, elem, Content, Context, Func, IntoValue, Label, NativeElement, Packed, Show,
Smart, StyleChain, Synthesize,
};
use crate::introspection::{Counter, Locatable};
use crate::math::EquationElem;
use crate::model::{
BibliographyElem, CiteElem, Destination, Figurable, FootnoteElem, Numbering,
};
use crate::text::TextElem;
#[elem(title = "Reference", Synthesize, Locatable, Show)]
pub struct RefElem {
#[required]
pub target: Label,
#[borrowed]
pub supplement: Smart<Option<Supplement>>,
#[synthesized]
pub citation: Option<Packed<CiteElem>>,
#[synthesized]
pub element: Option<Content>,
}
impl Synthesize for Packed<RefElem> {
fn synthesize(
&mut self,
engine: &mut Engine,
styles: StyleChain,
) -> SourceResult<()> {
let citation = to_citation(self, engine, styles)?;
let elem = self.as_mut();
elem.push_citation(Some(citation));
elem.push_element(None);
let target = *elem.target();
if !BibliographyElem::has(engine, target) {
if let Ok(found) = engine.introspector.query_label(target).cloned() {
elem.push_element(Some(found));
return Ok(());
}
}
Ok(())
}
}
impl Show for Packed<RefElem> {
#[typst_macros::time(name = "ref", span = self.span())]
fn show(&self, engine: &mut Engine, styles: StyleChain) -> SourceResult<Content> {
let target = *self.target();
let elem = engine.introspector.query_label(target);
let span = self.span();
if BibliographyElem::has(engine, target) {
if elem.is_ok() {
bail!(span, "label occurs in the document and its bibliography");
}
return Ok(to_citation(self, engine, styles)?.pack().spanned(span));
}
let elem = elem.at(span)?;
if let Some(footnote) = elem.to_packed::<FootnoteElem>() {
return Ok(footnote.into_ref(target).pack().spanned(span));
}
let elem = elem.clone();
let refable = elem
.with::<dyn Refable>()
.ok_or_else(|| {
if elem.can::<dyn Figurable>() {
eco_format!(
"cannot reference {} directly, try putting it into a figure",
elem.func().name()
)
} else {
eco_format!("cannot reference {}", elem.func().name())
}
})
.at(span)?;
let numbering = refable
.numbering()
.ok_or_else(|| {
eco_format!("cannot reference {} without numbering", elem.func().name())
})
.hint(eco_format!(
"you can enable {} numbering with `#set {}(numbering: \"1.\")`",
elem.func().name(),
if elem.func() == EquationElem::elem() {
"math.equation"
} else {
elem.func().name()
}
))
.at(span)?;
let loc = elem.location().unwrap();
let numbers = refable.counter().display_at_loc(
engine,
loc,
styles,
&numbering.clone().trimmed(),
)?;
let supplement = match self.supplement(styles).as_ref() {
Smart::Auto => refable.supplement(),
Smart::Custom(None) => Content::empty(),
Smart::Custom(Some(supplement)) => {
supplement.resolve(engine, styles, [elem])?
}
};
let mut content = numbers;
if !supplement.is_empty() {
content = supplement + TextElem::packed("\u{a0}") + content;
}
Ok(content.linked(Destination::Location(loc)))
}
}
fn to_citation(
reference: &Packed<RefElem>,
engine: &mut Engine,
styles: StyleChain,
) -> SourceResult<Packed<CiteElem>> {
let mut elem = Packed::new(CiteElem::new(*reference.target()).with_supplement(
match reference.supplement(styles).clone() {
Smart::Custom(Some(Supplement::Content(content))) => Some(content),
_ => None,
},
));
if let Some(loc) = reference.location() {
elem.set_location(loc);
}
elem.synthesize(engine, styles)?;
Ok(elem)
}
#[derive(Debug, Clone, PartialEq, Hash)]
pub enum Supplement {
Content(Content),
Func(Func),
}
impl Supplement {
pub fn resolve<T: IntoValue>(
&self,
engine: &mut Engine,
styles: StyleChain,
args: impl IntoIterator<Item = T>,
) -> SourceResult<Content> {
Ok(match self {
Supplement::Content(content) => content.clone(),
Supplement::Func(func) => func
.call(engine, Context::new(None, Some(styles)).track(), args)?
.display(),
})
}
}
cast! {
Supplement,
self => match self {
Self::Content(v) => v.into_value(),
Self::Func(v) => v.into_value(),
},
v: Content => Self::Content(v),
v: Func => Self::Func(v),
}
pub trait Refable {
fn supplement(&self) -> Content;
fn counter(&self) -> Counter;
fn numbering(&self) -> Option<&Numbering>;
}