mod date;
mod number;
mod recognise;
mod scripts;
mod special;
mod tokens;
mod write;
pub use scripts::{FormScript, ScriptLocation, ScriptState};
pub use write::MAX_WRITTEN_SCRIPT;
pub(crate) use recognise::recognise;
use super::{FieldValue, Form};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum FieldTrigger {
Keystroke,
Format,
Validate,
Calculate,
}
impl FieldTrigger {
pub(crate) const ALL: [Self; 4] = [Self::Keystroke, Self::Format, Self::Validate, Self::Calculate];
#[must_use]
pub const fn key(self) -> &'static str {
match self {
Self::Keystroke => "K",
Self::Format => "F",
Self::Validate => "V",
Self::Calculate => "C",
}
}
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum FieldBehaviour {
NumberFormat(NumberFormat),
PercentFormat(PercentFormat),
DateFormat(DatePattern),
TimeFormat(DatePattern),
SpecialFormat(SpecialFormat),
RangeValidate(RangeValidate),
SimpleCalculate(SimpleCalculate),
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct NumberFormat {
pub decimals: u8,
pub separator: SeparatorStyle,
pub negative: NegativeStyle,
pub currency: String,
pub prepend: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum SeparatorStyle {
CommaDot,
Dot,
DotComma,
Comma,
ApostropheDot,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum NegativeStyle {
Minus,
Red,
Parentheses,
RedParentheses,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct PercentFormat {
pub decimals: u8,
pub separator: SeparatorStyle,
pub prepend: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct DatePattern {
pub pattern: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum SpecialFormat {
Zip,
ZipPlus4,
Phone,
Ssn,
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct RangeValidate {
pub min: Option<f64>,
pub max: Option<f64>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct SimpleCalculate {
pub function: CalculateFunction,
pub fields: Vec<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum CalculateFunction {
Sum,
Average,
Product,
Minimum,
Maximum,
}
#[derive(Debug, Clone, Default, PartialEq)]
#[non_exhaustive]
pub struct Behaviour {
pub keystroke: Option<FieldBehaviour>,
pub format: Option<FieldBehaviour>,
pub validate: Option<FieldBehaviour>,
pub calculate: Option<SimpleCalculate>,
pub not_handled: Vec<FieldTrigger>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ShownValue {
pub text: String,
pub red: bool,
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum InvalidValue {
NotANumber,
NotADate {
pattern: String,
},
NotSpecial(SpecialFormat),
OutOfRange(RangeValidate),
}
impl InvalidValue {
#[must_use]
pub const fn reason(&self) -> &'static str {
match self {
Self::OutOfRange(_) => "range",
_ => "format",
}
}
}
impl ShownValue {
#[must_use]
pub const fn plain(text: String) -> Self {
Self { text, red: false }
}
}
impl NumberFormat {
#[must_use]
pub fn new(
decimals: u8,
separator: SeparatorStyle,
negative: NegativeStyle,
currency: impl Into<String>,
prepend: bool,
) -> Self {
Self {
decimals,
separator,
negative,
currency: currency.into(),
prepend,
}
}
}
impl PercentFormat {
#[must_use]
pub const fn new(decimals: u8, separator: SeparatorStyle, prepend: bool) -> Self {
Self {
decimals,
separator,
prepend,
}
}
}
impl DatePattern {
#[must_use]
pub fn new(pattern: impl Into<String>) -> Self {
Self {
pattern: pattern.into(),
}
}
}
impl RangeValidate {
#[must_use]
pub const fn new(min: Option<f64>, max: Option<f64>) -> Self {
Self { min, max }
}
}
impl SimpleCalculate {
#[must_use]
pub fn new(function: CalculateFunction, fields: impl IntoIterator<Item = impl Into<String>>) -> Self {
Self {
function,
fields: fields.into_iter().map(Into::into).collect(),
}
}
}
impl FieldBehaviour {
#[must_use]
pub fn show(&self, value: &str) -> Option<ShownValue> {
let plain = ShownValue::plain;
Some(match self {
Self::NumberFormat(f) => match f.show(value) {
Some((text, red)) => ShownValue { text, red },
None => plain(String::new()),
},
Self::PercentFormat(f) => plain(match f.show(value) {
Some(text) => text,
None if value.is_empty() => String::new(),
None => "%".to_owned(),
}),
Self::DateFormat(f) | Self::TimeFormat(f) => plain(if value.is_empty() {
String::new()
} else {
date::parse(&f.pattern, value).map_or_else(|| value.to_owned(), |d| date::printd(&f.pattern, d))
}),
Self::SpecialFormat(f) => plain(f.show(value)),
Self::RangeValidate(_) | Self::SimpleCalculate(_) => return None,
})
}
#[must_use]
pub fn accepts(&self, text: &str) -> bool {
match self {
Self::NumberFormat(NumberFormat { separator, .. })
| Self::PercentFormat(PercentFormat { separator, .. }) => {
number::keystroke_accepts(*separator, text, false)
}
Self::SpecialFormat(f) => f.accepts(text, false),
_ => true,
}
}
pub fn commit(&self, text: &str) -> Result<String, InvalidValue> {
match self {
Self::NumberFormat(NumberFormat { separator, .. })
| Self::PercentFormat(PercentFormat { separator, .. }) => {
if number::keystroke_accepts(*separator, text, true) {
Ok(number::committed(*separator, text))
} else {
Err(InvalidValue::NotANumber)
}
}
Self::DateFormat(f) | Self::TimeFormat(f) => {
if text.is_empty() || date::parse(&f.pattern, text).is_some() {
Ok(text.to_owned())
} else {
Err(InvalidValue::NotADate {
pattern: f.pattern.clone(),
})
}
}
Self::SpecialFormat(f) => {
if f.accepts(text, true) {
Ok(text.to_owned())
} else {
Err(InvalidValue::NotSpecial(*f))
}
}
Self::RangeValidate(r) => {
let inside = number::make_number(text)
.is_none_or(|v| r.min.is_none_or(|min| v >= min) && r.max.is_none_or(|max| v <= max));
if text.is_empty() || inside {
Ok(text.to_owned())
} else {
Err(InvalidValue::OutOfRange(*r))
}
}
Self::SimpleCalculate(_) => Ok(text.to_owned()),
}
}
}
impl Behaviour {
#[must_use]
pub fn show(&self, value: &str) -> ShownValue {
self.format
.as_ref()
.and_then(|f| f.show(value))
.unwrap_or_else(|| ShownValue {
text: value.to_owned(),
red: false,
})
}
pub fn commit(&self, text: &str) -> Result<String, InvalidValue> {
let mut value = text.to_owned();
for behaviour in [&self.keystroke, &self.validate].into_iter().flatten() {
value = behaviour.commit(&value)?;
}
Ok(value)
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct FormValues(std::collections::BTreeMap<String, String>);
impl FormValues {
#[must_use]
pub fn of(form: &Form) -> Self {
Self(
form.fields
.iter()
.map(|f| {
let text = match &f.value {
Some(FieldValue::Text(t)) => t.clone(),
Some(FieldValue::Button(Some(s))) => s.clone(),
Some(FieldValue::Choice(c)) => c.first().cloned().unwrap_or_default(),
_ => String::new(),
};
(f.name.clone(), text)
})
.collect(),
)
}
pub fn set(&mut self, name: &str, text: String) {
self.0.insert(name.to_owned(), text);
}
#[must_use]
pub fn get(&self, name: &str) -> Option<&str> {
self.0.get(name).map(String::as_str)
}
fn under<'a>(&'a self, name: &'a str) -> impl Iterator<Item = &'a str> + 'a {
let own = self.0.get(name).map(String::as_str);
let prefix = format!("{name}.");
let below = self
.0
.range(prefix.clone()..)
.take_while(move |(k, _)| k.starts_with(&prefix))
.map(|(_, v)| v.as_str());
own.into_iter().chain(below)
}
}
impl SimpleCalculate {
#[must_use]
pub fn compute(&self, values: &FormValues) -> String {
let mut numbers = Vec::new();
for name in &self.fields {
numbers.extend(values.under(name).map(|t| number::make_number(t).unwrap_or(0.0)));
}
if numbers.is_empty() {
return "0".to_owned();
}
let sum = || {
let (mut total, mut carry) = (0.0_f64, 0.0_f64);
for v in &numbers {
let t = total + v;
carry += if total.abs() >= v.abs() {
(total - t) + v
} else {
(v - t) + total
};
total = t;
}
total + carry
};
let result = match self.function {
CalculateFunction::Sum => sum(),
#[expect(clippy::cast_precision_loss, reason = "a count of fields")]
CalculateFunction::Average => sum() / numbers.len() as f64,
CalculateFunction::Product => numbers.iter().product(),
CalculateFunction::Minimum => numbers.iter().copied().fold(f64::INFINITY, f64::min),
CalculateFunction::Maximum => numbers.iter().copied().fold(f64::NEG_INFINITY, f64::max),
};
let scaled = 1e6 * result;
let rounded = if scaled - scaled.floor() >= 0.5 {
scaled.floor() + 1.0
} else {
scaled.floor()
};
number::js_string(rounded / 1e6)
}
}