use crate::icons::Glyph;
use crate::text;
use crate::widget::Align;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ColumnWidth {
Fixed(u16),
Fit,
Fill(u16),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SortDirection {
Ascending,
Descending,
}
impl SortDirection {
#[must_use]
pub fn reversed(self) -> Self {
match self {
Self::Ascending => Self::Descending,
Self::Descending => Self::Ascending,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Column {
pub(super) title: String,
pub(super) width: ColumnWidth,
pub(super) min: Option<u16>,
pub(super) align: Align,
pub(super) sortable: bool,
}
impl Column {
#[must_use]
pub fn new(title: impl Into<String>) -> Self {
Self { title: title.into(), width: ColumnWidth::Fill(1), min: None, align: Align::Start, sortable: false }
}
#[must_use]
pub fn width(mut self, width: ColumnWidth) -> Self {
self.width = width;
self
}
#[must_use]
pub fn min(mut self, cells: u16) -> Self {
self.min = Some(cells);
self
}
#[must_use]
pub fn align(mut self, align: Align) -> Self {
self.align = align;
self
}
#[must_use]
pub fn sortable(mut self, sortable: bool) -> Self {
self.sortable = sortable;
self
}
pub(super) fn title_width(&self) -> u16 {
text::width(&self.title).saturating_add(if self.sortable { 2 } else { 0 })
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct TableCell {
pub(super) text: String,
pub(super) icon: Option<Glyph>,
pub(super) icon_color: Option<String>,
pub(super) color: Option<String>,
}
impl TableCell {
#[must_use]
pub fn new(text: impl Into<String>) -> Self {
Self { text: text.into(), ..Self::default() }
}
#[must_use]
pub fn icon(mut self, glyph: impl Into<Glyph>, color: Option<&str>) -> Self {
self.icon = Some(glyph.into());
self.icon_color = color.map(str::to_owned);
self
}
#[must_use]
pub fn color(mut self, token: impl Into<String>) -> Self {
self.color = Some(token.into());
self
}
pub(super) fn width(&self) -> u16 {
let glyph = match &self.icon {
None => 0,
Some(Glyph::Key(_)) => 2,
Some(Glyph::Literal(glyph)) => text::width(glyph).saturating_add(1),
};
text::width(&self.text).saturating_add(glyph)
}
}
impl From<&str> for TableCell {
fn from(text: &str) -> Self {
Self::new(text)
}
}
impl From<String> for TableCell {
fn from(text: String) -> Self {
Self::new(text)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct TableRow {
pub(super) cells: Vec<TableCell>,
pub(super) faint: bool,
}
impl TableRow {
#[must_use]
pub fn new(cells: impl IntoIterator<Item = impl Into<TableCell>>) -> Self {
Self { cells: cells.into_iter().map(Into::into).collect(), faint: false }
}
#[must_use]
pub fn faint(mut self, faint: bool) -> Self {
self.faint = faint;
self
}
}