use std::cmp::Ordering;
use dioxus::prelude::*;
use crate::data::table::{TableRecordSlot, resolve_table_record_slots};
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct DataTableCell {
pub text: String,
pub sort_value: Option<String>,
}
impl DataTableCell {
pub fn new(text: impl Into<String>) -> Self {
Self {
text: text.into(),
sort_value: None,
}
}
#[must_use]
pub fn with_sort_value(mut self, value: impl Into<String>) -> Self {
self.sort_value = Some(value.into());
self
}
pub fn sort_text(&self) -> &str {
self.sort_value.as_deref().unwrap_or(&self.text)
}
}
pub(crate) fn js_number(value: f64) -> String {
if value.is_nan() {
"NaN".to_string()
} else if value.is_infinite() {
if value > 0.0 { "Infinity" } else { "-Infinity" }.to_string()
} else if value == 0.0 {
"0".to_string()
} else {
format!("{value}")
}
}
impl From<&str> for DataTableCell {
fn from(value: &str) -> Self {
Self::new(value)
}
}
impl From<String> for DataTableCell {
fn from(value: String) -> Self {
Self::new(value)
}
}
impl From<f64> for DataTableCell {
fn from(value: f64) -> Self {
Self::new(js_number(value))
}
}
impl From<i64> for DataTableCell {
fn from(value: i64) -> Self {
Self::new(value.to_string())
}
}
impl From<i32> for DataTableCell {
fn from(value: i32) -> Self {
Self::new(value.to_string())
}
}
impl From<u32> for DataTableCell {
fn from(value: u32) -> Self {
Self::new(value.to_string())
}
}
impl From<bool> for DataTableCell {
fn from(value: bool) -> Self {
Self::new(value.to_string())
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct DataTableRow {
pub id: Option<String>,
pub cells: Vec<(String, DataTableCell)>,
}
impl DataTableRow {
pub fn new(id: impl Into<String>) -> Self {
Self {
id: Some(id.into()),
cells: Vec::new(),
}
}
#[must_use]
pub fn cell(mut self, key: impl Into<String>, cell: impl Into<DataTableCell>) -> Self {
let key = key.into();
let cell = cell.into();
if let Some(entry) = self.cells.iter_mut().find(|(existing, _)| *existing == key) {
entry.1 = cell;
} else {
self.cells.push((key, cell));
}
self
}
pub fn get(&self, key: &str) -> Option<&DataTableCell> {
self.cells
.iter()
.find(|(existing, _)| existing == key)
.map(|(_, cell)| cell)
}
pub fn text(&self, key: &str) -> &str {
self.get(key).map_or("", |cell| cell.text.as_str())
}
pub fn value(&self, index: usize) -> String {
self.id.clone().unwrap_or_else(|| index.to_string())
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum DataTableSortType {
#[default]
String,
Number,
}
impl DataTableSortType {
pub fn as_str(self) -> &'static str {
match self {
Self::String => "string",
Self::Number => "number",
}
}
}
#[derive(Clone, PartialEq)]
pub struct DataTableColumn {
pub key: String,
pub header: Option<String>,
pub label: Option<String>,
pub sort: Option<DataTableSortType>,
pub sortable: bool,
pub numeric: Option<bool>,
pub wide: bool,
pub record: Option<TableRecordSlot>,
pub secondary: bool,
pub render: Option<Callback<(DataTableCell, DataTableRow), Element>>,
}
impl DataTableColumn {
pub fn new(key: impl Into<String>, header: impl Into<String>) -> Self {
Self {
key: key.into(),
header: Some(header.into()),
label: None,
sort: None,
sortable: false,
numeric: None,
wide: false,
record: None,
secondary: false,
render: None,
}
}
#[must_use]
pub fn numeric(mut self, numeric: bool) -> Self {
self.numeric = Some(numeric);
self
}
pub fn is_numeric(&self) -> bool {
self.numeric
.unwrap_or(self.sort == Some(DataTableSortType::Number))
}
#[must_use]
pub fn sortable(mut self, sort: DataTableSortType) -> Self {
self.sortable = true;
self.sort = Some(sort);
self
}
#[must_use]
pub fn sortable_text(mut self) -> Self {
self.sortable = true;
self
}
#[must_use]
pub fn wide(mut self) -> Self {
self.wide = true;
self
}
#[must_use]
pub fn record(mut self, slot: TableRecordSlot) -> Self {
self.record = Some(slot);
self
}
#[must_use]
pub fn secondary(mut self) -> Self {
self.secondary = true;
self
}
pub fn record_slot(&self) -> Option<TableRecordSlot> {
self.record
.or_else(|| self.wide.then_some(TableRecordSlot::Wide))
}
#[must_use]
pub fn with_render(mut self, render: Callback<(DataTableCell, DataTableRow), Element>) -> Self {
self.render = Some(render);
self
}
pub fn title(&self) -> &str {
self.header
.as_deref()
.or(self.label.as_deref())
.unwrap_or(&self.key)
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum DataTableSortDirection {
#[default]
Ascending,
Descending,
}
impl DataTableSortDirection {
pub fn as_str(self) -> &'static str {
match self {
Self::Ascending => "ascending",
Self::Descending => "descending",
}
}
#[must_use]
pub fn reversed(self) -> Self {
match self {
Self::Ascending => Self::Descending,
Self::Descending => Self::Ascending,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DataTableSort {
pub key: String,
pub direction: DataTableSortDirection,
}
impl DataTableSort {
pub fn ascending(key: impl Into<String>) -> Self {
Self {
key: key.into(),
direction: DataTableSortDirection::Ascending,
}
}
pub fn descending(key: impl Into<String>) -> Self {
Self {
key: key.into(),
direction: DataTableSortDirection::Descending,
}
}
}
pub fn data_table_record_slots(columns: &[DataTableColumn]) -> Vec<Option<TableRecordSlot>> {
let first_title = columns
.iter()
.position(|column| column.record == Some(TableRecordSlot::Title));
let slots: Vec<(Option<TableRecordSlot>, bool)> = columns
.iter()
.enumerate()
.map(|(index, column)| {
let slot =
if column.record == Some(TableRecordSlot::Title) && Some(index) != first_title {
column.wide.then_some(TableRecordSlot::Wide)
} else {
column.record_slot()
};
(slot, column.secondary)
})
.collect();
resolve_table_record_slots(&slots)
}
pub fn valid_data_table_columns(columns: &[DataTableColumn]) -> &[DataTableColumn] {
let mut keys: Vec<&str> = Vec::with_capacity(columns.len());
for column in columns {
if column.key.is_empty() || keys.contains(&column.key.as_str()) {
return &[];
}
keys.push(&column.key);
}
columns
}
pub fn valid_data_table_rows(rows: &[DataTableRow]) -> bool {
let mut ids = std::collections::HashSet::with_capacity(rows.len());
rows.iter().enumerate().all(|(index, row)| {
let id = row.value(index);
!id.is_empty() && ids.insert(id)
})
}
pub fn valid_data_table_sorting(sorting: &[DataTableSort]) -> Vec<DataTableSort> {
let mut criteria: Vec<DataTableSort> = Vec::with_capacity(sorting.len());
for sort in sorting {
if !criteria.iter().any(|existing| existing.key == sort.key) {
criteria.push(sort.clone());
}
}
criteria
}
pub fn next_data_table_sorting(
current: &[DataTableSort],
key: &str,
additive: bool,
) -> Vec<DataTableSort> {
if !additive {
return match current.first() {
Some(primary) if primary.key == key => vec![DataTableSort {
key: key.to_string(),
direction: primary.direction.reversed(),
}],
_ => vec![DataTableSort::ascending(key)],
};
}
if current.iter().any(|sort| sort.key == key) {
current
.iter()
.map(|sort| {
if sort.key == key {
DataTableSort {
key: sort.key.clone(),
direction: sort.direction.reversed(),
}
} else {
sort.clone()
}
})
.collect()
} else {
let mut next = current.to_vec();
next.push(DataTableSort::ascending(key));
next
}
}
pub fn cycle_data_table_sorting(current: &[DataTableSort], key: &str) -> Vec<DataTableSort> {
match current.first() {
Some(primary) if primary.key == key => match primary.direction {
DataTableSortDirection::Ascending => vec![DataTableSort::descending(key)],
DataTableSortDirection::Descending => Vec::new(),
},
_ => vec![DataTableSort::ascending(key)],
}
}
pub fn toggle_data_table_id(ids: &[String], id: &str) -> Vec<String> {
if ids.iter().any(|existing| existing == id) {
ids.iter()
.filter(|existing| *existing != id)
.cloned()
.collect()
} else {
let mut next = ids.to_vec();
next.push(id.to_string());
next
}
}
pub fn toggle_data_table_ids(ids: &[String], rendered: &[String]) -> Vec<String> {
let all = !rendered.is_empty() && rendered.iter().all(|id| ids.contains(id));
if all {
ids.iter()
.filter(|id| !rendered.contains(id))
.cloned()
.collect()
} else {
let mut next = ids.to_vec();
next.extend(rendered.iter().filter(|id| !ids.contains(id)).cloned());
next
}
}
pub(crate) fn js_to_number(text: &str) -> Option<f64> {
let trimmed = text.trim();
if trimmed.is_empty() {
return Some(0.0);
}
let radix = |prefix: &str, radix: u32| {
trimmed
.strip_prefix(prefix)
.or_else(|| trimmed.strip_prefix(&prefix.to_ascii_uppercase()))
.map(|digits| {
if digits.is_empty() {
return None;
}
digits.chars().try_fold(0.0_f64, |total, digit| {
digit
.to_digit(radix)
.map(|value| total * f64::from(radix) + f64::from(value))
})
})
};
if let Some(value) = radix("0x", 16)
.or_else(|| radix("0o", 8))
.or_else(|| radix("0b", 2))
{
return value;
}
match trimmed {
"Infinity" | "+Infinity" => return Some(f64::INFINITY),
"-Infinity" => return Some(f64::NEG_INFINITY),
_ => {}
}
if trimmed
.bytes()
.any(|byte| byte.is_ascii_alphabetic() && byte != b'e' && byte != b'E')
{
return None;
}
trimmed.parse::<f64>().ok()
}
fn chunk_rank(character: char) -> u8 {
if character.is_ascii_digit() {
1
} else if character.is_alphanumeric() {
2
} else {
0
}
}
pub fn compare_data_table_text(left: &str, right: &str) -> Ordering {
let mut a = left.chars().peekable();
let mut b = right.chars().peekable();
loop {
match (a.peek().copied(), b.peek().copied()) {
(None, None) => return Ordering::Equal,
(None, Some(_)) => return Ordering::Less,
(Some(_), None) => return Ordering::Greater,
(Some(x), Some(y)) if x.is_ascii_digit() && y.is_ascii_digit() => {
let mut left_digits = String::new();
let mut right_digits = String::new();
while let Some(digit) = a.next_if(char::is_ascii_digit) {
left_digits.push(digit);
}
while let Some(digit) = b.next_if(char::is_ascii_digit) {
right_digits.push(digit);
}
let left_trimmed = left_digits.trim_start_matches('0');
let right_trimmed = right_digits.trim_start_matches('0');
let order = left_trimmed
.len()
.cmp(&right_trimmed.len())
.then_with(|| left_trimmed.cmp(right_trimmed));
if order != Ordering::Equal {
return order;
}
}
(Some(x), Some(y)) => {
let order = chunk_rank(x)
.cmp(&chunk_rank(y))
.then_with(|| x.to_lowercase().cmp(y.to_lowercase()));
if order != Ordering::Equal {
return order;
}
a.next();
b.next();
}
}
}
}
pub fn compare_data_table_cells(
left: Option<&DataTableCell>,
right: Option<&DataTableCell>,
sort: Option<DataTableSortType>,
) -> Option<Ordering> {
let left = left.map_or("", DataTableCell::sort_text);
let right = right.map_or("", DataTableCell::sort_text);
if sort == Some(DataTableSortType::Number) {
let left = js_to_number(&left.replace(',', ""))?;
let right = js_to_number(&right.replace(',', ""))?;
return left.partial_cmp(&right);
}
Some(compare_data_table_text(left, right))
}
enum DataTableSortKey<'a> {
Text(&'a str),
Number(Option<f64>),
}
impl<'a> DataTableSortKey<'a> {
fn new(cell: Option<&'a DataTableCell>, sort: Option<DataTableSortType>) -> Self {
let text = cell.map_or("", DataTableCell::sort_text);
if sort != Some(DataTableSortType::Number) {
return Self::Text(text);
}
Self::Number(
js_to_number(&text.replace(',', ""))
.filter(|number| !number.is_nan())
.map(|number| if number == 0.0 { 0.0 } else { number }),
)
}
fn compare(&self, other: &Self, direction: DataTableSortDirection) -> Ordering {
let directed = |order: Ordering| match direction {
DataTableSortDirection::Ascending => order,
DataTableSortDirection::Descending => order.reverse(),
};
match (self, other) {
(Self::Text(left), Self::Text(right)) => directed(compare_data_table_text(left, right)),
(Self::Number(Some(left)), Self::Number(Some(right))) => {
directed(left.total_cmp(right))
}
(Self::Number(Some(_)), Self::Number(None)) => Ordering::Less,
(Self::Number(None), Self::Number(Some(_))) => Ordering::Greater,
_ => Ordering::Equal,
}
}
}
pub fn sort_data_table_rows(
rows: &[DataTableRow],
columns: &[DataTableColumn],
criteria: &[DataTableSort],
manual: bool,
) -> Vec<usize> {
let mut order: Vec<usize> = (0..rows.len()).collect();
if manual {
return order;
}
let active: Vec<(&DataTableColumn, DataTableSortDirection)> = criteria
.iter()
.filter_map(|sort| {
columns
.iter()
.find(|column| column.sortable && column.key == sort.key)
.map(|column| (column, sort.direction))
})
.collect();
if active.is_empty() {
return order;
}
let keys: Vec<Vec<DataTableSortKey>> = rows
.iter()
.map(|row| {
active
.iter()
.map(|(column, _)| DataTableSortKey::new(row.get(&column.key), column.sort))
.collect()
})
.collect();
order.sort_by(|left, right| {
keys[*left]
.iter()
.zip(&keys[*right])
.zip(&active)
.map(|((left, right), (_, direction))| left.compare(right, *direction))
.find(|order| order.is_ne())
.unwrap_or_else(|| left.cmp(right))
});
order
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct DataTablePagination {
pub page_index: usize,
pub page_size: usize,
}
impl Default for DataTablePagination {
fn default() -> Self {
Self {
page_index: 0,
page_size: 25,
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum DataTableDensity {
#[default]
Comfortable,
Compact,
}
impl DataTableDensity {
pub fn as_str(self) -> &'static str {
match self {
Self::Comfortable => "comfortable",
Self::Compact => "compact",
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DataTableFilter {
pub id: String,
pub value: String,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct DataTableViewState {
pub search: String,
pub filters: Vec<DataTableFilter>,
pub visibility: Vec<(String, bool)>,
pub pagination: DataTablePagination,
pub sorting: Vec<DataTableSort>,
pub density: DataTableDensity,
}
impl DataTableViewState {
pub fn filter_value(&self, key: &str) -> &str {
self.filters
.iter()
.find(|filter| filter.id == key)
.map_or("", |filter| filter.value.as_str())
}
#[must_use]
pub fn with_filter(&self, key: &str, value: &str) -> Self {
let mut next = self.clone();
next.filters.retain(|filter| filter.id != key);
if !value.is_empty() {
next.filters.push(DataTableFilter {
id: key.to_string(),
value: value.to_string(),
});
}
next
}
#[must_use]
pub fn with_visibility(&self, key: &str, visible: bool) -> Self {
let mut next = self.clone();
if let Some(entry) = next
.visibility
.iter_mut()
.find(|(existing, _)| existing == key)
{
entry.1 = visible;
} else {
next.visibility.push((key.to_string(), visible));
}
next
}
#[must_use]
pub fn first_page(mut self) -> Self {
self.pagination.page_index = 0;
self
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct DataTableViewColumn {
pub key: String,
pub label: String,
pub can_hide: bool,
pub sortable: bool,
pub searchable: bool,
pub filter_options: Vec<(String, String)>,
}
impl DataTableViewColumn {
pub fn new(key: impl Into<String>, label: impl Into<String>) -> Self {
Self {
key: key.into(),
label: label.into(),
can_hide: true,
sortable: false,
searchable: true,
filter_options: Vec::new(),
}
}
#[must_use]
pub fn sortable(mut self) -> Self {
self.sortable = true;
self
}
#[must_use]
pub fn always_visible(mut self) -> Self {
self.can_hide = false;
self
}
#[must_use]
pub fn with_filter_options(mut self, options: Vec<(String, String)>) -> Self {
self.filter_options = options;
self
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DataTableViewPage {
pub rows: Vec<usize>,
pub matching: usize,
pub pages: usize,
pub page_index: usize,
}
pub fn data_table_column_visible(
columns: &[DataTableViewColumn],
state: &DataTableViewState,
key: &str,
) -> bool {
columns.iter().any(|column| {
column.key == key
&& (!column.can_hide
|| !state
.visibility
.iter()
.any(|(hidden, visible)| hidden == key && !visible))
})
}
pub fn data_table_view_page(
rows: &[DataTableRow],
columns: &[DataTableViewColumn],
state: &DataTableViewState,
server: Option<usize>,
) -> DataTableViewPage {
let size = state.pagination.page_size.max(1);
if let Some(total) = server {
let pages = total.div_ceil(size).max(1);
return DataTableViewPage {
rows: (0..rows.len()).collect(),
matching: total,
pages,
page_index: state.pagination.page_index.min(pages - 1),
};
}
let search = state.search.to_lowercase();
let mut matching: Vec<usize> = (0..rows.len())
.filter(|index| {
let row = &rows[*index];
let searched = search.is_empty()
|| columns
.iter()
.filter(|column| column.searchable)
.any(|column| row.text(&column.key).to_lowercase().contains(&search));
let filtered = state.filters.iter().all(|filter| {
!columns.iter().any(|column| column.key == filter.id)
|| row.text(&filter.id) == filter.value
});
searched && filtered
})
.collect();
let sortable: Vec<&DataTableSort> = state
.sorting
.iter()
.filter(|sort| {
columns
.iter()
.any(|column| column.key == sort.key && column.sortable)
})
.collect();
if !sortable.is_empty() {
matching.sort_by(|left, right| {
for sort in &sortable {
let order = compare_data_table_text(
rows[*left].text(&sort.key),
rows[*right].text(&sort.key),
);
let order = match sort.direction {
DataTableSortDirection::Ascending => order,
DataTableSortDirection::Descending => order.reverse(),
};
if order != Ordering::Equal {
return order;
}
}
left.cmp(right)
});
}
let total = matching.len();
let pages = total.div_ceil(size).max(1);
let page_index = state.pagination.page_index.min(pages - 1);
let rows = matching
.into_iter()
.skip(page_index * size)
.take(size)
.collect();
DataTableViewPage {
rows,
matching: total,
pages,
page_index,
}
}
pub fn toggle_data_table_view_sort(
sorting: &[DataTableSort],
key: &str,
multiple: bool,
) -> Vec<DataTableSort> {
let active = sorting.iter().find(|sort| sort.key == key);
let direction = active.map_or(DataTableSortDirection::Ascending, |sort| {
sort.direction.reversed()
});
let mut next: Vec<DataTableSort> = if multiple {
sorting
.iter()
.filter(|sort| sort.key != key)
.cloned()
.collect()
} else {
Vec::new()
};
next.push(DataTableSort {
key: key.to_string(),
direction,
});
next
}
#[cfg(test)]
mod tests {
use std::cmp::Ordering;
use super::*;
fn rows() -> Vec<DataTableRow> {
vec![
DataTableRow::new("ada")
.cell("name", "Ada")
.cell("seats", 12),
DataTableRow::new("grace")
.cell("name", "grace")
.cell("seats", DataTableCell::new("1,200").with_sort_value("1200")),
DataTableRow::new("linus")
.cell("name", "Linus")
.cell("seats", 3),
]
}
fn columns() -> Vec<DataTableColumn> {
vec![
DataTableColumn::new("name", "Name").sortable_text(),
DataTableColumn::new("seats", "Seats").sortable(DataTableSortType::Number),
]
}
#[test]
fn header_activation_replaces_or_extends_criteria() {
let one = next_data_table_sorting(&[], "name", false);
assert_eq!(one, [DataTableSort::ascending("name")]);
assert_eq!(
next_data_table_sorting(&one, "name", false),
[DataTableSort::descending("name")]
);
assert_eq!(
next_data_table_sorting(&one, "seats", false),
[DataTableSort::ascending("seats")]
);
let two = next_data_table_sorting(&one, "seats", true);
assert_eq!(
two,
[
DataTableSort::ascending("name"),
DataTableSort::ascending("seats")
]
);
assert_eq!(
next_data_table_sorting(&two, "name", true),
[
DataTableSort::descending("name"),
DataTableSort::ascending("seats")
]
);
}
#[test]
fn single_sort_headers_cycle_ascending_descending_and_unsorted() {
let ascending = cycle_data_table_sorting(&[], "name");
assert_eq!(ascending, [DataTableSort::ascending("name")]);
let descending = cycle_data_table_sorting(&ascending, "name");
assert_eq!(descending, [DataTableSort::descending("name")]);
assert_eq!(
cycle_data_table_sorting(&descending, "name"),
[] as [DataTableSort; 0]
);
assert_eq!(
cycle_data_table_sorting(&descending, "seats"),
[DataTableSort::ascending("seats")]
);
let both = [
DataTableSort::descending("name"),
DataTableSort::descending("seats"),
];
assert_eq!(
cycle_data_table_sorting(&both, "seats"),
[DataTableSort::ascending("seats")]
);
assert_eq!(
cycle_data_table_sorting(&both, "name"),
[] as [DataTableSort; 0]
);
}
#[test]
fn record_slots_alias_wide_and_default_the_title() {
let columns = vec![
DataTableColumn::new("name", "Name").wide(),
DataTableColumn::new("email", "Email").secondary(),
DataTableColumn::new("status", "Status").record(TableRecordSlot::Trailing),
DataTableColumn::new("notes", "Notes")
.wide()
.record(TableRecordSlot::Meta),
];
assert_eq!(columns[0].record_slot(), Some(TableRecordSlot::Wide));
assert_eq!(columns[3].record_slot(), Some(TableRecordSlot::Meta));
assert!(columns[1].secondary);
assert_eq!(
data_table_record_slots(&columns),
[
Some(TableRecordSlot::Wide),
None,
Some(TableRecordSlot::Trailing),
Some(TableRecordSlot::Meta),
]
);
let titled = vec![
DataTableColumn::new("name", "Name"),
DataTableColumn::new("team", "Team").record(TableRecordSlot::Title),
];
assert_eq!(
data_table_record_slots(&titled),
[None, Some(TableRecordSlot::Title)]
);
let duplicated = vec![
DataTableColumn::new("name", "Name").record(TableRecordSlot::Title),
DataTableColumn::new("team", "Team")
.wide()
.record(TableRecordSlot::Title),
DataTableColumn::new("role", "Role").record(TableRecordSlot::Title),
];
assert_eq!(
data_table_record_slots(&duplicated),
[
Some(TableRecordSlot::Title),
Some(TableRecordSlot::Wide),
None
]
);
}
#[test]
fn rows_sort_by_type_and_priority_and_stay_stable() {
let rows = rows();
let columns = columns();
assert_eq!(
sort_data_table_rows(
&rows,
&columns,
&[DataTableSort::descending("seats")],
false
),
[1, 0, 2]
);
assert_eq!(
sort_data_table_rows(&rows, &columns, &[DataTableSort::ascending("name")], false),
[0, 1, 2]
);
assert_eq!(
sort_data_table_rows(&rows, &columns, &[DataTableSort::descending("seats")], true),
[0, 1, 2]
);
assert_eq!(
sort_data_table_rows(&rows, &columns, &[DataTableSort::ascending("role")], false),
[0, 1, 2]
);
}
#[test]
fn natural_text_order_compares_numbers_and_ignores_case() {
assert_eq!(compare_data_table_text("item 2", "item 10"), Ordering::Less);
assert_eq!(compare_data_table_text("Apple", "apple"), Ordering::Equal);
assert_eq!(compare_data_table_text("b", "A"), Ordering::Greater);
assert_eq!(compare_data_table_text("007", "7"), Ordering::Equal);
assert_eq!(compare_data_table_text("-x", "1"), Ordering::Less);
assert_eq!(compare_data_table_text("1", "a"), Ordering::Less);
let long = "9".repeat(100_000);
assert_eq!(compare_data_table_text(&long, &long), Ordering::Equal);
}
#[test]
fn numbers_parse_like_javascript() {
assert_eq!(js_to_number(" 12 "), Some(12.0));
assert_eq!(js_to_number(""), Some(0.0));
assert_eq!(js_to_number("0x10"), Some(16.0));
assert_eq!(js_to_number("1e3"), Some(1000.0));
assert_eq!(js_to_number("Infinity"), Some(f64::INFINITY));
assert_eq!(js_to_number("inf"), None);
assert_eq!(js_to_number("12px"), None);
assert_eq!(
compare_data_table_cells(
Some(&"abc".into()),
Some(&"1".into()),
Some(DataTableSortType::Number)
),
None
);
}
#[test]
fn ids_toggle_and_select_all_keeps_other_pages() {
let ids = vec!["a".to_string()];
assert_eq!(toggle_data_table_id(&ids, "b"), ["a", "b"]);
assert_eq!(toggle_data_table_id(&ids, "a"), Vec::<String>::new());
let rendered = vec!["b".to_string(), "c".to_string()];
assert_eq!(toggle_data_table_ids(&ids, &rendered), ["a", "b", "c"]);
let all = vec!["a".to_string(), "b".to_string(), "c".to_string()];
assert_eq!(toggle_data_table_ids(&all, &rendered), ["a"]);
}
#[test]
fn invalid_columns_and_rows_are_rejected() {
let duplicate = vec![
DataTableColumn::new("a", "A"),
DataTableColumn::new("a", "B"),
];
assert!(valid_data_table_columns(&duplicate).is_empty());
assert_eq!(valid_data_table_columns(&columns()).len(), 2);
assert!(!valid_data_table_rows(&[
DataTableRow::new("x"),
DataTableRow::new("x")
]));
assert!(!valid_data_table_rows(&[DataTableRow::new("")]));
assert!(valid_data_table_rows(&rows()));
}
#[test]
fn views_search_filter_sort_and_paginate() {
let rows: Vec<DataTableRow> = (0..30)
.map(|index| {
DataTableRow::new(format!("r{index}"))
.cell("name", format!("Item {index}"))
.cell("status", if index % 3 == 0 { "Open" } else { "Closed" })
})
.collect();
let columns = vec![
DataTableViewColumn::new("name", "Name").sortable(),
DataTableViewColumn::new("status", "Status"),
];
let mut state = DataTableViewState {
pagination: DataTablePagination {
page_index: 0,
page_size: 4,
},
..DataTableViewState::default()
};
let page = data_table_view_page(&rows, &columns, &state, None);
assert_eq!((page.matching, page.pages, page.rows.len()), (30, 8, 4));
state = state.with_filter("status", "Open");
let page = data_table_view_page(&rows, &columns, &state, None);
assert_eq!((page.matching, page.pages), (10, 3));
state.search = "item 2".into();
let page = data_table_view_page(&rows, &columns, &state, None);
assert_eq!(page.rows, [21, 24, 27]);
state.sorting = toggle_data_table_view_sort(&state.sorting, "name", false);
state.sorting = toggle_data_table_view_sort(&state.sorting, "name", false);
let page = data_table_view_page(&rows, &columns, &state, None);
assert_eq!(page.rows, [27, 24, 21]);
state.pagination.page_index = 99;
assert_eq!(
data_table_view_page(&rows, &columns, &state, None).page_index,
0
);
assert_eq!(
data_table_view_page(&rows, &columns, &state, Some(0)).pages,
1
);
}
#[test]
fn visibility_respects_columns_that_cannot_hide() {
let columns = vec![
DataTableViewColumn::new("name", "Name").always_visible(),
DataTableViewColumn::new("status", "Status"),
];
let state = DataTableViewState::default()
.with_visibility("name", false)
.with_visibility("status", false);
assert!(data_table_column_visible(&columns, &state, "name"));
assert!(!data_table_column_visible(&columns, &state, "status"));
assert!(!data_table_column_visible(&columns, &state, "missing"));
}
}