use crate::coordinate::Range;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum FilterOperator {
#[default]
Equal,
NotEqual,
GreaterThan,
GreaterThanOrEqual,
LessThan,
LessThanOrEqual,
}
impl FilterOperator {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Equal => "equal",
Self::NotEqual => "notEqual",
Self::GreaterThan => "greaterThan",
Self::GreaterThanOrEqual => "greaterThanOrEqual",
Self::LessThan => "lessThan",
Self::LessThanOrEqual => "lessThanOrEqual",
}
}
#[must_use]
pub fn parse(value: &str) -> Self {
match value {
"notEqual" => Self::NotEqual,
"greaterThan" => Self::GreaterThan,
"greaterThanOrEqual" => Self::GreaterThanOrEqual,
"lessThan" => Self::LessThan,
"lessThanOrEqual" => Self::LessThanOrEqual,
_ => Self::Equal,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct CustomFilter {
pub operator: FilterOperator,
pub value: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct DateGroup {
pub year: Option<u32>,
pub month: Option<u32>,
pub day: Option<u32>,
pub hour: Option<u32>,
pub minute: Option<u32>,
pub second: Option<u32>,
pub grouping: String,
}
impl DateGroup {
#[must_use]
#[cfg(feature = "write")]
pub(crate) fn parts(&self) -> Vec<(&'static str, u32)> {
[
("year", self.year),
("month", self.month),
("day", self.day),
("hour", self.hour),
("minute", self.minute),
("second", self.second),
]
.into_iter()
.filter_map(|(name, value)| value.map(|v| (name, v)))
.collect()
}
pub(crate) fn slots(&mut self) -> [(&'static str, &mut Option<u32>); 6] {
[
("year", &mut self.year),
("month", &mut self.month),
("day", &mut self.day),
("hour", &mut self.hour),
("minute", &mut self.minute),
("second", &mut self.second),
]
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ColumnFilter {
Values {
blank: bool,
values: Vec<String>,
date_groups: Vec<DateGroup>,
},
Custom {
and: bool,
rules: Vec<CustomFilter>,
},
Dynamic {
kind: String,
value: Option<String>,
max_value: Option<String>,
},
Top10 {
value: Option<String>,
percent: bool,
top: bool,
filter_value: Option<String>,
},
Color {
dxf: Option<u32>,
cell_color: bool,
},
Icon {
icon_set: String,
icon_id: Option<u32>,
},
}
impl ColumnFilter {
#[must_use]
pub const fn tag(&self) -> &'static str {
match self {
Self::Values { .. } => "filters",
Self::Custom { .. } => "customFilters",
Self::Dynamic { .. } => "dynamicFilter",
Self::Top10 { .. } => "top10",
Self::Color { .. } => "colorFilter",
Self::Icon { .. } => "iconFilter",
}
}
#[must_use]
pub(crate) fn empty(tag: &str) -> Option<Self> {
Some(match tag {
"filters" => Self::Values {
blank: false,
values: Vec::new(),
date_groups: Vec::new(),
},
"customFilters" => Self::Custom {
and: false,
rules: Vec::new(),
},
"dynamicFilter" => Self::Dynamic {
kind: String::new(),
value: None,
max_value: None,
},
"top10" => Self::Top10 {
value: None,
percent: false,
top: true,
filter_value: None,
},
"colorFilter" => Self::Color {
dxf: None,
cell_color: true,
},
"iconFilter" => Self::Icon {
icon_set: String::new(),
icon_id: None,
},
_ => return None,
})
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FilterColumn {
pub col_id: u32,
pub hidden_button: bool,
pub filter: Option<ColumnFilter>,
}
impl FilterColumn {
#[must_use]
pub const fn new(col_id: u32) -> Self {
Self {
col_id,
hidden_button: false,
filter: None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SortCondition {
pub range: Range,
pub descending: bool,
pub sort_by: Option<String>,
pub custom_list: Option<String>,
pub dxf: Option<u32>,
pub icon_set: Option<String>,
pub icon_id: Option<u32>,
}
impl SortCondition {
#[must_use]
pub const fn new(range: Range) -> Self {
Self {
range,
descending: false,
sort_by: None,
custom_list: None,
dxf: None,
icon_set: None,
icon_id: None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SortState {
pub range: Range,
pub column_sort: bool,
pub case_sensitive: bool,
pub sort_method: Option<String>,
pub conditions: Vec<SortCondition>,
}
impl SortState {
#[must_use]
pub const fn new(range: Range) -> Self {
Self {
range,
column_sort: false,
case_sensitive: false,
sort_method: None,
conditions: Vec::new(),
}
}
#[must_use]
pub(crate) fn moved(mut self, shift: impl Fn(Range) -> Option<Range>) -> Option<Self> {
self.range = shift(self.range)?;
self.conditions.retain_mut(|c| match shift(c.range) {
Some(range) => {
c.range = range;
true
}
None => false,
});
Some(self)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AutoFilter {
pub range: Range,
pub columns: Vec<FilterColumn>,
pub sort_state: Option<SortState>,
}
impl AutoFilter {
#[must_use]
pub const fn new(range: Range) -> Self {
Self {
range,
columns: Vec::new(),
sort_state: None,
}
}
pub fn column_at(&mut self, col_id: u32) -> &mut FilterColumn {
if let Some(i) = self.columns.iter().position(|c| c.col_id == col_id) {
return &mut self.columns[i];
}
self.columns.push(FilterColumn::new(col_id));
self.columns.last_mut().unwrap_or_else(|| unreachable!())
}
}
#[cfg(test)]
mod tests {
use super::{AutoFilter, ColumnFilter, DateGroup, FilterOperator};
use crate::coordinate::Range;
fn range(s: &str) -> Range {
Range::parse(s).unwrap_or_else(|e| unreachable!("{e}"))
}
#[test]
fn a_column_is_created_once_and_then_found() {
let mut filter = AutoFilter::new(range("A1:C9"));
filter.column_at(2).hidden_button = true;
filter.column_at(0).hidden_button = true;
assert!(filter.column_at(2).hidden_button);
assert_eq!(filter.columns.len(), 2);
assert_eq!(
filter.columns.iter().map(|c| c.col_id).collect::<Vec<_>>(),
vec![2, 0]
);
}
#[test]
fn an_unknown_operator_is_equal() {
assert_eq!(FilterOperator::parse("lessThan"), FilterOperator::LessThan);
assert_eq!(FilterOperator::parse(""), FilterOperator::Equal);
assert_eq!(FilterOperator::parse("nonsense"), FilterOperator::Equal);
}
#[test]
fn each_element_name_builds_its_own_variant() {
for tag in [
"filters",
"customFilters",
"dynamicFilter",
"top10",
"colorFilter",
"iconFilter",
] {
let filter = ColumnFilter::empty(tag).unwrap_or_else(|| unreachable!());
assert_eq!(filter.tag(), tag);
}
assert!(ColumnFilter::empty("mystery").is_none());
}
#[test]
fn a_top_ten_filter_defaults_to_the_top() {
let filter = ColumnFilter::empty("top10").unwrap_or_else(|| unreachable!());
assert!(matches!(
filter,
ColumnFilter::Top10 {
top: true,
percent: false,
..
}
));
}
#[cfg(feature = "write")]
#[test]
fn a_date_group_lists_only_the_parts_it_has() {
let group = DateGroup {
year: Some(2026),
month: Some(8),
grouping: "month".into(),
..DateGroup::default()
};
assert_eq!(group.parts(), vec![("year", 2026), ("month", 8)]);
}
}