feat: add ScoreListWidget with execution confirmation

Implement ScoreListWidget to manage score list rendering and execution confirmation flow. This includes methods for scrolling through scores, launching an execution, confirming/denying the execution, and rendering a popup for user confirmation.
This commit is contained in:
2025-01-27 23:24:21 -05:00
parent 651266d71c
commit 3410751463
21 changed files with 369 additions and 23 deletions

View File

@@ -9,5 +9,6 @@ log = { workspace = true }
env_logger = { workspace = true }
tokio = { workspace = true }
ratatui = "0.29.0"
crossterm = "0.28.1"
crossterm = { version = "0.28.1", features = [ "event-stream" ] }
color-eyre = "0.6.3"
tokio-stream = "0.1.17"

View File

@@ -1,7 +1,18 @@
use crossterm::event::{self, Event};
use harmony::maestro::Maestro;
use ratatui::{self, layout::Position, prelude::CrosstermBackend, Frame, Terminal};
use std::io;
mod widget;
use tokio_stream::StreamExt;
use widget::score::ScoreListWidget;
use std::time::Duration;
use crossterm::event::{Event, EventStream, KeyCode, KeyEventKind};
use harmony::{maestro::Maestro, score::Score};
use ratatui::{
self,
layout::{Constraint, Layout, Position},
widgets::{Block, Borders, ListItem},
Frame,
};
pub mod tui {
// Export any necessary modules or types from the internal tui module
@@ -34,21 +45,35 @@ pub async fn init(maestro: Maestro) -> Result<(), Box<dyn std::error::Error>> {
pub struct HarmonyTUI {
maestro: Maestro,
score: ScoreListWidget,
should_quit: bool,
}
impl HarmonyTUI {
pub fn new(maestro: Maestro) -> Self {
HarmonyTUI { maestro }
let score = ScoreListWidget::new(Self::scores_list(&maestro));
HarmonyTUI {
maestro,
should_quit: false,
score,
}
}
pub async fn init(self) -> Result<(), Box<dyn std::error::Error>> {
pub async fn init(mut self) -> Result<(), Box<dyn std::error::Error>> {
color_eyre::install()?;
let mut terminal = ratatui::init();
loop {
terminal.draw(|f| self.render(f))?;
if matches!(event::read()?, Event::Key(_)) {
break;
// TODO improve performance here
// Refreshing the entire terminal 10 times a second does not seem very smart
let period = Duration::from_secs_f32(1.0 / 10.0);
let mut interval = tokio::time::interval(period);
let mut events = EventStream::new();
while !self.should_quit {
tokio::select! {
_ = interval.tick() => { terminal.draw(|frame| self.render(frame))?; },
Some(Ok(event)) = events.next() => self.handle_event(&event),
}
}
@@ -60,9 +85,53 @@ impl HarmonyTUI {
fn render(&self, frame: &mut Frame) {
let size = frame.area();
frame.set_cursor_position(Position::new(size.x / 2, size.y / 2));
frame.render_widget(
ratatui::widgets::Paragraph::new("Hello World"),
frame.area(),
);
let [list_area, output_area] =
Layout::horizontal([Constraint::Min(30), Constraint::Percentage(100)])
.areas(frame.area());
let block = Block::default().borders(Borders::RIGHT);
frame.render_widget(&block, list_area);
self.score.render(list_area, frame);
}
fn scores_list(maestro: &Maestro) -> Vec<ScoreItem> {
let scores = maestro.scores();
let scores_read = scores.read().expect("Should be able to read scores");
scores_read
.iter()
.map(|s| ScoreItem(s.clone_box()))
.collect()
}
fn handle_event(&mut self, event: &Event) {
if let Event::Key(key) = event {
if key.kind == KeyEventKind::Press {
match key.code {
KeyCode::Char('q') | KeyCode::Esc => self.should_quit = true,
KeyCode::Char('j') | KeyCode::Down => self.score.scroll_down(),
KeyCode::Char('k') | KeyCode::Up => self.score.scroll_up(),
KeyCode::Enter => self.score.launch_execution(),
KeyCode::Char('y') => self.score.confirm(true),
KeyCode::Char('n') => self.score.confirm(false),
_ => {}
}
}
}
}
}
#[derive(Debug)]
struct ScoreItem(Box<dyn Score>);
impl ScoreItem {
pub fn clone(&self) -> Self {
Self(self.0.clone_box())
}
}
impl Into<ListItem<'_>> for &ScoreItem {
fn into(self) -> ListItem<'static> {
ListItem::new(self.0.name())
}
}

View File

@@ -0,0 +1,2 @@
pub mod score;
pub mod ratatui_utils;

View File

@@ -0,0 +1,22 @@
use ratatui::layout::{Constraint, Flex, Layout, Rect};
/// Centers a [`Rect`] within another [`Rect`] using the provided [`Constraint`]s.
///
/// # Examples
///
/// ```rust
/// use ratatui::layout::{Constraint, Rect};
///
/// let area = Rect::new(0, 0, 100, 100);
/// let horizontal = Constraint::Percentage(20);
/// let vertical = Constraint::Percentage(30);
///
/// let centered = center(area, horizontal, vertical);
/// ```
pub(crate) fn center(area: Rect, horizontal: Constraint, vertical: Constraint) -> Rect {
let [area] = Layout::horizontal([horizontal])
.flex(Flex::Center)
.areas(area);
let [area] = Layout::vertical([vertical]).flex(Flex::Center).areas(area);
area
}

View File

@@ -0,0 +1,143 @@
use std::sync::{Arc, RwLock};
use log::warn;
use ratatui::{
layout::{Constraint, Rect},
style::{Style, Stylize},
widgets::{Block, Clear, List, ListState, Paragraph, StatefulWidget, Widget},
Frame,
};
use crate::ScoreItem;
use super::ratatui_utils::center;
#[derive(Debug)]
enum ExecutionState {
INITIATED,
CONFIRMED,
CANCELED,
RUNNING,
COMPLETED,
}
#[derive(Debug)]
struct Execution {
state: ExecutionState,
score: ScoreItem,
}
#[derive(Debug)]
pub(crate) struct ScoreListWidget {
list_state: Arc<RwLock<ListState>>,
scores: Vec<ScoreItem>,
execution: Option<Execution>,
execution_history: Vec<Execution>,
}
impl ScoreListWidget {
pub(crate) fn new(scores: Vec<ScoreItem>) -> Self {
let mut list_state = ListState::default();
list_state.select_first();
let list_state = Arc::new(RwLock::new(list_state));
Self {
scores,
list_state,
execution: None,
execution_history: vec![],
}
}
pub(crate) fn launch_execution(&mut self) {
let list_read = self.list_state.read().unwrap();
if let Some(index) = list_read.selected() {
let score = self
.scores
.get(index)
.expect("List state should always match with internal Vec");
self.execution = Some(Execution {
state: ExecutionState::INITIATED,
score: score.clone(),
});
}
}
pub(crate) fn scroll_down(&self) {
self.list_state.write().unwrap().scroll_down_by(1);
}
pub(crate) fn scroll_up(&self) {
self.list_state.write().unwrap().scroll_up_by(1);
}
pub(crate) fn render(&self, area: Rect, frame: &mut Frame) {
frame.render_widget(self, area);
self.render_execution(frame);
}
pub(crate) fn render_execution(&self, frame: &mut Frame) {
if let None = self.execution {
return;
}
let execution = self.execution.as_ref().unwrap();
// let confirm = Paragraph::new(format!("{:#?}", execution.score.0)).block(
// Block::default()
// .borders(Borders::ALL)
// .title("Confirm Execution")
// .border_type(BorderType::Rounded),
// );
// let rect = frame.area().inner(Margin::new(5, 5));
// frame.render_widget(confirm, rect);
let area = center(
frame.area(),
Constraint::Percentage(80),
Constraint::Percentage(80), // top and bottom border + content
);
let popup = Paragraph::new(format!("{:#?}", execution.score.0))
.block(Block::bordered().title("Confirm Execution (Press y/n)"));
frame.render_widget(Clear, area);
frame.render_widget(popup, area);
}
fn clear_execution(&mut self) {
match self.execution.take() {
Some(execution) => {
self.execution_history.push(execution);
}
None => warn!("Should never clear execution when no execution exists"),
}
}
pub(crate) fn confirm(&mut self, confirm: bool) {
if let Some(execution) = &mut self.execution {
match confirm {
true => {
execution.state = ExecutionState::CONFIRMED;
todo!("launch execution {:#?}", execution);
},
false => {
execution.state = ExecutionState::CANCELED;
self.clear_execution();
}
}
}
}
}
impl Widget for &ScoreListWidget {
fn render(self, area: ratatui::prelude::Rect, buf: &mut ratatui::prelude::Buffer)
where
Self: Sized,
{
let mut list_state = self.list_state.write().unwrap();
let list = List::new(&self.scores)
.highlight_style(Style::new().bold().italic())
.highlight_symbol("🠊 ");
StatefulWidget::render(list, area, buf, &mut list_state)
}
}