use std::collections::BTreeMap;
use std::fmt;
use std::sync::{Arc, OnceLock};
use crate::core::registry::{BuildError, FeatureBuilder, Finalizer};
use crate::model::names::{BackendName, Name};
use crate::stdlib::backends::pres::{CellAlign, CellEdge, CellHeader};
use crate::stdlib::backends::{html, latex_recomposed, latex_rendered};
use super::{LATEX_PIECE, STYLE, STYLES_SLOT};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Effect {
Align(CellAlign),
Header(CellHeader),
Rule(CellEdge),
Custom,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Parameter {
Align,
Head,
Rule,
}
impl Parameter {
pub fn values(self) -> &'static [&'static str] {
match self {
Parameter::Align => &["left", "center", "right"],
Parameter::Head => &["column", "row"],
Parameter::Rule => &["above", "below", "left", "right"],
}
}
pub fn effect(self, value: &str) -> Option<Effect> {
match self {
Parameter::Align => CellAlign::parse(value).map(Effect::Align),
Parameter::Head => CellHeader::parse(value).map(Effect::Header),
Parameter::Rule => CellEdge::parse(value).map(Effect::Rule),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum StyleForm {
Fixed(Effect),
Structural(Parameter),
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct StyleRequirement {
pub backend: BackendName,
pub id: Name,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CellStyle {
pub name: Name,
pub docs: String,
pub form: StyleForm,
pub requires: Vec<StyleRequirement>,
}
impl CellStyle {
pub fn fixed(name: impl Into<Name>, docs: impl Into<String>, effect: Effect) -> CellStyle {
CellStyle {
name: name.into(),
docs: crate::kept_docs(docs),
form: StyleForm::Fixed(effect),
requires: Vec::new(),
}
}
pub fn custom(name: impl Into<Name>, docs: impl Into<String>) -> CellStyle {
CellStyle::fixed(name, docs, Effect::Custom)
}
pub fn structural(name: impl Into<Name>, docs: impl Into<String>, parameter: Parameter) -> CellStyle {
CellStyle {
name: name.into(),
docs: crate::kept_docs(docs),
form: StyleForm::Structural(parameter),
requires: Vec::new(),
}
}
pub fn requires(
mut self,
backend: impl Into<BackendName>,
ids: impl IntoIterator<Item = impl Into<Name>>,
) -> CellStyle {
let backend = backend.into();
self.requires
.extend(ids.into_iter().map(|id| StyleRequirement { backend: backend.clone(), id: id.into() }));
self
}
pub fn requirements_on<'s>(&'s self, backend: &'s str) -> impl Iterator<Item = &'s Name> + 's {
self.requires.iter().filter(move |r| r.backend.as_str() == backend).map(|r| &r.id)
}
}
pub(super) fn is_style_name(name: &str) -> bool {
let mut chars = name.chars();
chars.next().is_some_and(|first| first.is_ascii_alphabetic())
&& chars.all(|ch| ch.is_ascii_alphanumeric())
}
pub fn shipped() -> Vec<CellStyle> {
let mut styles = vec![
CellStyle::structural("align", "the cell's alignment: `align{left}`, `align{center}`, `align{right}`", Parameter::Align),
CellStyle::structural("head", "the cell heads its column or its row: `head{column}`, `head{row}`", Parameter::Head),
CellStyle::structural(
"rule",
"a line drawn along an edge of the cell: `rule{above}`, `rule{below}`, `rule{left}`, \
`rule{right}`",
Parameter::Rule,
),
CellStyle::fixed("l", "the cell aligned left, as `align{left}`", Effect::Align(CellAlign::Left)),
CellStyle::fixed("c", "the cell centered, as `align{center}`", Effect::Align(CellAlign::Center)),
CellStyle::fixed("r", "the cell aligned right, as `align{right}`", Effect::Align(CellAlign::Right)),
CellStyle::fixed("H", "the cell heads its column, as `head{column}`", Effect::Header(CellHeader::Column)),
CellStyle::fixed("rH", "the cell heads its row, as `head{row}`", Effect::Header(CellHeader::Row)),
CellStyle::fixed(
"lvert",
"a line drawn along the cell's left edge, as `rule{left}`",
Effect::Rule(CellEdge::Left),
),
CellStyle::fixed(
"rvert",
"a line drawn along the cell's right edge, as `rule{right}`",
Effect::Rule(CellEdge::Right),
),
];
for color in ["green", "blue", "yellow", "red"] {
styles.push(
CellStyle::custom(color, format!("a {color} background, which sets the cell apart"))
.requires(html::BACKEND, [STYLE])
.requires(latex_recomposed::BACKEND, [LATEX_PIECE])
.requires(latex_rendered::BACKEND, [STYLE]),
);
}
styles
}
#[derive(Default)]
pub struct Styles {
by_name: OnceLock<BTreeMap<Name, Arc<CellStyle>>>,
}
impl Styles {
pub fn of(styles: impl IntoIterator<Item = CellStyle>) -> Styles {
let by_name = styles.into_iter().map(|style| (style.name.clone(), Arc::new(style))).collect();
let collected = Styles::default();
let _ = collected.by_name.set(by_name);
collected
}
pub fn get(&self, name: &str) -> Option<&CellStyle> {
self.by_name.get()?.get(name).map(|style| style.as_ref())
}
pub fn iter(&self) -> impl Iterator<Item = &CellStyle> + '_ {
self.by_name.get().into_iter().flat_map(|by_name| by_name.values().map(|style| style.as_ref()))
}
}
impl fmt::Debug for Styles {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let names: Vec<&str> = self.iter().map(|style| style.name.as_str()).collect();
f.debug_struct("Styles").field("names", &names).finish()
}
}
pub(super) struct CollectStyles {
pub(super) styles: Arc<Styles>,
}
impl Finalizer for CollectStyles {
fn finalize(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
let refuse = |b: &FeatureBuilder<'_>, detail: String| BuildError::Feature {
feature: b.feature().clone(),
detail,
};
let Some(services) = b.services() else {
return Err(refuse(b, "the styles slot must be assembled before the finalizer runs".into()));
};
let mut by_name: BTreeMap<Name, Arc<CellStyle>> = BTreeMap::new();
for style in services.shared_named::<CellStyle>(STYLES_SLOT) {
let name = style.name.as_str();
if !is_style_name(name) {
return Err(refuse(
b,
format!(
"the cell style name `{name}` must begin with an ASCII letter and hold only \
ASCII letters and digits"
),
));
}
if style.form == StyleForm::Fixed(Effect::Custom) && name.chars().any(|ch| ch.is_ascii_uppercase()) {
return Err(refuse(b, format!("the custom cell style name `{name}` must be lowercase")));
}
if by_name.insert(style.name.clone(), Arc::clone(style)).is_some() {
return Err(refuse(b, format!("the cell style `{name}` may not be declared twice")));
}
}
if self.styles.by_name.set(by_name).is_err() {
return Err(refuse(b, "the feature may be registered at most once in a registry".into()));
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_shipped_styles_are_the_python_tokens_and_the_three_structural_ones() {
let names: Vec<String> = shipped().iter().map(|style| style.name.to_string()).collect();
assert_eq!(
names,
["align", "head", "rule", "l", "c", "r", "H", "rH", "lvert", "rvert", "green", "blue", "yellow", "red"]
);
assert!(shipped().iter().all(|style| is_style_name(style.name.as_str())));
}
#[test]
fn a_custom_shipped_style_requires_the_chunk_on_html_and_the_piece_on_latex() {
let green = shipped().into_iter().find(|style| style.name.as_str() == "green").expect("green");
assert_eq!(green.requirements_on(html::BACKEND).map(Name::as_str).collect::<Vec<_>>(), [STYLE]);
assert_eq!(
green.requirements_on(latex_recomposed::BACKEND).map(Name::as_str).collect::<Vec<_>>(),
[LATEX_PIECE]
);
assert_eq!(
green.requirements_on(latex_rendered::BACKEND).map(Name::as_str).collect::<Vec<_>>(),
[STYLE]
);
assert_eq!(green.requirements_on("text").count(), 0);
}
#[test]
fn a_parameter_reads_its_values() {
assert_eq!(Parameter::Align.effect("right"), Some(Effect::Align(CellAlign::Right)));
assert_eq!(Parameter::Head.effect("row"), Some(Effect::Header(CellHeader::Row)));
assert_eq!(Parameter::Rule.effect("above"), Some(Effect::Rule(CellEdge::Above)));
assert_eq!(Parameter::Align.effect("middle"), None);
}
}