use std::collections::BTreeMap;
use crate::model::names::Name;
use super::decl::Within;
#[derive(Clone, PartialEq, Eq, Hash, Debug, serde::Deserialize)]
#[derive(schemars::JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum WithinOption {
Nothing,
Counter(Within),
}
#[derive(Clone, PartialEq, Eq, Hash, Debug, Default, serde::Deserialize)]
#[derive(schemars::JsonSchema)]
#[serde(default, deny_unknown_fields)]
pub struct CounterOptions {
pub within: Option<WithinOption>,
pub initial: Option<u32>,
}
impl CounterOptions {
pub fn new() -> CounterOptions {
CounterOptions::default()
}
pub fn within(mut self, within: Within) -> CounterOptions {
self.within = Some(WithinOption::Counter(within));
self
}
pub fn within_nothing(mut self) -> CounterOptions {
self.within = Some(WithinOption::Nothing);
self
}
pub fn initial(mut self, value: u32) -> CounterOptions {
self.initial = Some(value);
self
}
}
#[derive(Clone, PartialEq, Eq, Hash, Debug, Default, serde::Deserialize)]
#[derive(schemars::JsonSchema)]
#[serde(default, deny_unknown_fields)]
pub struct NumberingOptions {
pub counters: BTreeMap<Name, CounterOptions>,
}
impl NumberingOptions {
pub fn new() -> NumberingOptions {
NumberingOptions::default()
}
pub fn of(&self, counter: &str) -> Option<&CounterOptions> {
self.counters.get(&Name::new(counter))
}
pub fn counter(mut self, counter: impl Into<Name>, entry: CounterOptions) -> NumberingOptions {
self.counters.insert(counter.into(), entry);
self
}
pub fn within(mut self, counter: impl Into<Name>, within: Within) -> NumberingOptions {
self.counters.entry(counter.into()).or_default().within =
Some(WithinOption::Counter(within));
self
}
pub fn within_nothing(mut self, counter: impl Into<Name>) -> NumberingOptions {
self.counters.entry(counter.into()).or_default().within = Some(WithinOption::Nothing);
self
}
pub fn initial(mut self, counter: impl Into<Name>, value: u32) -> NumberingOptions {
self.counters.entry(counter.into()).or_default().initial = Some(value);
self
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_builders_write_into_one_entry_per_counter() {
let options = NumberingOptions::new()
.initial("section", 0)
.within("section", Within::parent("chapter"));
assert_eq!(options.counters.len(), 1);
let entry = options.of("section").expect("set");
assert_eq!(entry.initial, Some(0));
assert!(matches!(entry.within, Some(WithinOption::Counter(_))));
}
#[test]
fn a_counter_the_document_says_nothing_about_has_no_entry() {
assert!(NumberingOptions::new().of("equation").is_none());
}
}