/// Updatable checklist widget — a pure `Block` builder. /// /// Holds a list of [`ChecklistItem`]s, each with a [`CheckState`]. Because /// it is pure (no IO), you can embed it in your component state and update it /// from any context — a `run_with_channel` message handler, a `run_animated` /// tick, or plain synchronous code — and the render loop will pick up the /// changes on the next frame. /// /// # Example /// /// ``` /// use sly::widgets::checklist::{Checklist, ChecklistItem, CheckState}; /// /// let mut list = Checklist::new(vec![ /// ChecklistItem::new("Install dependencies").state(CheckState::Done), /// ChecklistItem::new("Compile project").state(CheckState::InProgress).note("3 / 8 files"), /// ChecklistItem::new("Run tests").state(CheckState::Pending), /// ]); /// /// // Later, mark compile as done: /// list.set_state(1, CheckState::Done); /// /// let block = list.to_block(); /// ``` use crate::block::Block; use crate::color::Color; use crate::style::{Span, Style}; // --------------------------------------------------------------------------- // CheckState // --------------------------------------------------------------------------- /// The status of a single checklist item. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum CheckState { /// Not yet started. Pending, /// Currently in progress. InProgress, /// Completed successfully. Done, /// Completed with an error. Failed, /// Intentionally skipped. Skipped, } impl CheckState { /// The single-character icon used when rendering. pub fn icon(self) -> &'static str { match self { CheckState::Pending => "○", CheckState::InProgress => "◉", CheckState::Done => "✓", CheckState::Failed => "✗", CheckState::Skipped => "–", } } } // --------------------------------------------------------------------------- // ChecklistItem // --------------------------------------------------------------------------- /// A single row in a [`Checklist`]. #[derive(Debug, Clone)] pub struct ChecklistItem { /// The label displayed next to the status icon. pub label: String, /// Current status. pub state: CheckState, /// Optional short annotation shown after the label (e.g. `"3 / 8 files"`). pub note: Option, } impl ChecklistItem { pub fn new(label: impl Into) -> Self { ChecklistItem { label: label.into(), state: CheckState::Pending, note: None, } } pub fn state(self, state: CheckState) -> Self { Self { state, ..self } } pub fn note(self, note: impl Into) -> Self { Self { note: Some(note.into()), ..self } } } // --------------------------------------------------------------------------- // ChecklistStyle // --------------------------------------------------------------------------- /// Visual styling for the checklist. #[derive(Debug, Clone)] pub struct ChecklistStyle { pub pending_style: Style, pub in_progress_style: Style, pub done_style: Style, pub failed_style: Style, pub skipped_style: Style, pub note_style: Style, /// Gap between icon + label and the note (spaces). pub note_gap: usize, } impl Default for ChecklistStyle { fn default() -> Self { ChecklistStyle { pending_style: Style::new().dim(), in_progress_style: Style::new().bold().fg(Color::Cyan), done_style: Style::new().fg(Color::Green), failed_style: Style::new().bold().fg(Color::Red), skipped_style: Style::new().dim(), note_style: Style::new().dim(), note_gap: 2, } } } impl ChecklistStyle { pub fn new() -> Self { Self::default() } pub fn pending_style(self, s: Style) -> Self { Self { pending_style: s, ..self } } pub fn in_progress_style(self, s: Style) -> Self { Self { in_progress_style: s, ..self } } pub fn done_style(self, s: Style) -> Self { Self { done_style: s, ..self } } pub fn failed_style(self, s: Style) -> Self { Self { failed_style: s, ..self } } pub fn skipped_style(self, s: Style) -> Self { Self { skipped_style: s, ..self } } pub fn note_style(self, s: Style) -> Self { Self { note_style: s, ..self } } fn style_for(&self, state: CheckState) -> &Style { match state { CheckState::Pending => &self.pending_style, CheckState::InProgress => &self.in_progress_style, CheckState::Done => &self.done_style, CheckState::Failed => &self.failed_style, CheckState::Skipped => &self.skipped_style, } } } // --------------------------------------------------------------------------- // Checklist // --------------------------------------------------------------------------- /// A updatable list of status items that renders as a `Block`. /// /// This is a **pure data structure** — updating it (via [`set_state`], /// [`set_note`], etc.) produces no IO. Pass the updated checklist to /// `view.update(&checklist.to_block())` or return it from your component's /// `render` function. /// /// [`set_state`]: Checklist::set_state /// [`set_note`]: Checklist::set_note #[derive(Debug, Clone)] pub struct Checklist { items: Vec, style: ChecklistStyle, } impl Checklist { /// Create a checklist from a list of items. pub fn new(items: Vec) -> Self { Checklist { items, style: ChecklistStyle::default(), } } /// Override the visual style. pub fn style(self, style: ChecklistStyle) -> Self { Self { style, ..self } } // --- Mutation helpers --- /// Set the state of item at `index`. No-op if index is out of bounds. pub fn set_state(&mut self, index: usize, state: CheckState) { if let Some(item) = self.items.get_mut(index) { item.state = state; } } /// Set (or clear) the note of item at `index`. pub fn set_note(&mut self, index: usize, note: Option) { if let Some(item) = self.items.get_mut(index) { item.note = note; } } /// Replace the label of item at `index`. pub fn set_label(&mut self, index: usize, label: impl Into) { if let Some(item) = self.items.get_mut(index) { item.label = label.into(); } } /// Append a new item to the end of the list. pub fn push(&mut self, item: ChecklistItem) { self.items.push(item); } /// Get an immutable reference to the item at `index`. pub fn get(&self, index: usize) -> Option<&ChecklistItem> { self.items.get(index) } /// The number of items in the checklist. pub fn len(&self) -> usize { self.items.len() } pub fn is_empty(&self) -> bool { self.items.is_empty() } /// How many items have state `Done`. pub fn done_count(&self) -> usize { self.items .iter() .filter(|i| i.state == CheckState::Done) .count() } /// Whether every item is in a terminal state (Done, Failed, or Skipped). pub fn is_complete(&self) -> bool { self.items.iter().all(|i| { matches!( i.state, CheckState::Done | CheckState::Failed | CheckState::Skipped ) }) } // --- Rendering --- /// Render the checklist as a [`Block`]. pub fn to_block(&self) -> Block { if self.items.is_empty() { return Block::text(vec![]); } let lines: Vec = self .items .iter() .map(|item| self.render_item(item)) .collect(); Block::text(lines) } fn render_item(&self, item: &ChecklistItem) -> crate::style::Line { let style = self.style.style_for(item.state); let icon = item.state.icon(); let mut line = vec![ Span::styled(format!("{} ", icon), style.clone()), Span::styled(item.label.clone(), style.clone()), ]; if let Some(ref note) = item.note { let gap = " ".repeat(self.style.note_gap); line.push(Span::plain(gap)); line.push(Span::styled(note.clone(), self.style.note_style.clone())); } line } } // --------------------------------------------------------------------------- // Tests // --------------------------------------------------------------------------- #[cfg(test)] mod tests { use super::*; fn make_list() -> Checklist { Checklist::new(vec![ ChecklistItem::new("Install").state(CheckState::Done), ChecklistItem::new("Build") .state(CheckState::InProgress) .note("3/8"), ChecklistItem::new("Test").state(CheckState::Pending), ]) } // --- State icons --- #[test] fn icons_match_states() { assert_eq!(CheckState::Pending.icon(), "○"); assert_eq!(CheckState::InProgress.icon(), "◉"); assert_eq!(CheckState::Done.icon(), "✓"); assert_eq!(CheckState::Failed.icon(), "✗"); assert_eq!(CheckState::Skipped.icon(), "–"); } // --- Mutation --- #[test] fn set_state_changes_item() { let mut list = make_list(); assert_eq!(list.get(2).unwrap().state, CheckState::Pending); list.set_state(2, CheckState::Done); assert_eq!(list.get(2).unwrap().state, CheckState::Done); } #[test] fn set_state_out_of_bounds_is_noop() { let mut list = make_list(); list.set_state(99, CheckState::Done); // should not panic assert_eq!(list.len(), 3); } #[test] fn set_note_attaches_note() { let mut list = make_list(); list.set_note(0, Some("elapsed: 1.2s".into())); assert_eq!(list.get(0).unwrap().note.as_deref(), Some("elapsed: 1.2s")); } #[test] fn set_note_clears_note() { let mut list = make_list(); list.set_note(1, None); assert!(list.get(1).unwrap().note.is_none()); } #[test] fn push_adds_item() { let mut list = make_list(); list.push(ChecklistItem::new("Deploy").state(CheckState::Pending)); assert_eq!(list.len(), 4); } // --- Counters / completion --- #[test] fn done_count() { let list = make_list(); assert_eq!(list.done_count(), 1); // only "Install" is Done } #[test] fn is_complete_false_when_pending() { let list = make_list(); assert!(!list.is_complete()); } #[test] fn is_complete_true_when_all_terminal() { let mut list = make_list(); list.set_state(1, CheckState::Done); list.set_state(2, CheckState::Skipped); assert!(list.is_complete()); } // --- Rendering --- #[test] fn to_block_height_matches_item_count() { let list = make_list(); let block = list.to_block(); assert_eq!(block.height(), 3); } #[test] fn render_contains_icon_and_label() { let list = make_list(); let lines = list.to_block().render(60); assert!(lines[0].contains("✓")); assert!(lines[0].contains("Install")); } #[test] fn render_contains_note() { let list = make_list(); let lines = list.to_block().render(60); assert!(lines[1].contains("3/8")); } #[test] fn empty_checklist_renders_nothing() { let list = Checklist::new(vec![]); let block = list.to_block(); assert_eq!(block.height(), 0); } #[test] fn set_label_updates_label() { let mut list = make_list(); list.set_label(0, "Install deps"); assert_eq!(list.get(0).unwrap().label, "Install deps"); let lines = list.to_block().render(60); assert!(lines[0].contains("Install deps")); } }