This commit is contained in:
@@ -0,0 +1,130 @@
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::model::{CreateRoutine, CreateTask, RescheduleTask, Routine, Task};
|
||||
|
||||
pub struct ApiClient {
|
||||
base_url: String,
|
||||
token: Option<String>,
|
||||
}
|
||||
|
||||
impl ApiClient {
|
||||
pub fn new(base_url: String, token: Option<String>) -> Self {
|
||||
Self {
|
||||
base_url: base_url.trim_end_matches('/').to_owned(),
|
||||
token,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn list_tasks(&self, date: &str) -> Result<Vec<Task>, String> {
|
||||
self.get(&format!("/v1/tasks?date={date}"))
|
||||
}
|
||||
|
||||
pub fn list_routines(&self) -> Result<Vec<Routine>, String> {
|
||||
self.get("/v1/routines")
|
||||
}
|
||||
|
||||
pub fn create_task(&self, task: &CreateTask) -> Result<(), String> {
|
||||
self.send_json("/v1/tasks", task)
|
||||
}
|
||||
|
||||
pub fn create_routine(&self, routine: &CreateRoutine) -> Result<(), String> {
|
||||
self.send_json("/v1/routines", routine)
|
||||
}
|
||||
|
||||
pub fn complete_task(&self, id: i64) -> Result<(), String> {
|
||||
self.send_empty("POST", &format!("/v1/tasks/{id}/complete"))
|
||||
}
|
||||
|
||||
pub fn delete_task(&self, id: i64) -> Result<(), String> {
|
||||
self.send_empty("DELETE", &format!("/v1/tasks/{id}"))
|
||||
}
|
||||
|
||||
pub fn reschedule_task(&self, id: i64, date: &str) -> Result<(), String> {
|
||||
self.send_json(
|
||||
&format!("/v1/tasks/{id}/reschedule"),
|
||||
&RescheduleTask {
|
||||
scheduled_date: date.to_owned(),
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fn get<T: DeserializeOwned>(&self, path: &str) -> Result<T, String> {
|
||||
let response = self
|
||||
.authorize(minreq::get(self.url(path)))
|
||||
.send()
|
||||
.map_err(transport_error)?;
|
||||
let body = response.as_str().map_err(|error| error.to_string())?;
|
||||
if !(200..300).contains(&response.status_code) {
|
||||
return Err(api_error(response.status_code, body));
|
||||
}
|
||||
serde_json::from_str(body).map_err(|error| format!("invalid server response: {error}"))
|
||||
}
|
||||
|
||||
fn send_json<T: Serialize>(&self, path: &str, value: &T) -> Result<(), String> {
|
||||
let body = serde_json::to_string(value).map_err(|error| error.to_string())?;
|
||||
let response = self
|
||||
.authorize(minreq::post(self.url(path)))
|
||||
.with_header("Content-Type", "application/json")
|
||||
.with_body(body)
|
||||
.send()
|
||||
.map_err(transport_error)?;
|
||||
check_status(response)
|
||||
}
|
||||
|
||||
fn send_empty(&self, method: &str, path: &str) -> Result<(), String> {
|
||||
let request = match method {
|
||||
"POST" => minreq::post(self.url(path)),
|
||||
"DELETE" => minreq::delete(self.url(path)),
|
||||
_ => return Err(format!("unsupported HTTP method: {method}")),
|
||||
};
|
||||
let response = self.authorize(request).send().map_err(transport_error)?;
|
||||
check_status(response)
|
||||
}
|
||||
|
||||
fn authorize(&self, request: minreq::Request) -> minreq::Request {
|
||||
match &self.token {
|
||||
Some(token) => request.with_header("Authorization", format!("Bearer {token}")),
|
||||
None => request,
|
||||
}
|
||||
}
|
||||
|
||||
fn url(&self, path: &str) -> String {
|
||||
format!("{}{path}", self.base_url)
|
||||
}
|
||||
}
|
||||
|
||||
fn check_status(response: minreq::Response) -> Result<(), String> {
|
||||
if (200..300).contains(&response.status_code) {
|
||||
return Ok(());
|
||||
}
|
||||
let body = response.as_str().unwrap_or("");
|
||||
Err(api_error(response.status_code, body))
|
||||
}
|
||||
|
||||
fn api_error(status: i32, body: &str) -> String {
|
||||
serde_json::from_str::<serde_json::Value>(body)
|
||||
.ok()
|
||||
.and_then(|value| value["error"].as_str().map(str::to_owned))
|
||||
.unwrap_or_else(|| format!("server returned HTTP {status}"))
|
||||
}
|
||||
|
||||
fn transport_error(error: minreq::Error) -> String {
|
||||
format!("cannot reach routine-server: {error}")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn joins_base_url_and_path_once() {
|
||||
let client = ApiClient::new("http://localhost:8090/".to_owned(), None);
|
||||
assert_eq!(client.url("/health"), "http://localhost:8090/health");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_json_error_message() {
|
||||
assert_eq!(api_error(400, r#"{"error":"bad date"}"#), "bad date");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,416 @@
|
||||
use chrono::{Days, Local, NaiveDate};
|
||||
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
|
||||
|
||||
use crate::api::ApiClient;
|
||||
use crate::model::{CreateRoutine, CreateTask, Routine, Schedule, Task};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum View {
|
||||
Tasks,
|
||||
Routines,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub enum FormKind {
|
||||
Task,
|
||||
Routine,
|
||||
Reschedule { task_id: i64 },
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum FieldValue {
|
||||
Text(String),
|
||||
Choice {
|
||||
options: &'static [&'static str],
|
||||
selected: usize,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Field {
|
||||
pub label: &'static str,
|
||||
pub hint: &'static str,
|
||||
pub value: FieldValue,
|
||||
}
|
||||
|
||||
impl Field {
|
||||
pub fn display(&self) -> &str {
|
||||
match &self.value {
|
||||
FieldValue::Text(value) => value,
|
||||
FieldValue::Choice { options, selected } => options[*selected],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Form {
|
||||
pub kind: FormKind,
|
||||
pub fields: Vec<Field>,
|
||||
pub active: usize,
|
||||
}
|
||||
|
||||
pub struct App {
|
||||
pub api: ApiClient,
|
||||
pub view: View,
|
||||
pub date: NaiveDate,
|
||||
pub tasks: Vec<Task>,
|
||||
pub routines: Vec<Routine>,
|
||||
pub selected: usize,
|
||||
pub status: String,
|
||||
pub form: Option<Form>,
|
||||
pub quit: bool,
|
||||
}
|
||||
|
||||
impl App {
|
||||
pub fn new(api: ApiClient) -> Self {
|
||||
Self {
|
||||
api,
|
||||
view: View::Tasks,
|
||||
date: Local::now().date_naive(),
|
||||
tasks: Vec::new(),
|
||||
routines: Vec::new(),
|
||||
selected: 0,
|
||||
status: "connecting…".to_owned(),
|
||||
form: None,
|
||||
quit: false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn refresh(&mut self) {
|
||||
let result = match self.view {
|
||||
View::Tasks => self
|
||||
.api
|
||||
.list_tasks(&self.date.to_string())
|
||||
.map(|tasks| self.tasks = tasks),
|
||||
View::Routines => self
|
||||
.api
|
||||
.list_routines()
|
||||
.map(|routines| self.routines = routines),
|
||||
};
|
||||
self.selected = self.selected.min(self.item_count().saturating_sub(1));
|
||||
self.status = match result {
|
||||
Ok(()) => format!("{} item(s)", self.item_count()),
|
||||
Err(error) => error,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn handle_key(&mut self, key: KeyEvent) {
|
||||
if self.form.is_some() {
|
||||
self.handle_form_key(key);
|
||||
} else {
|
||||
self.handle_normal_key(key);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn item_count(&self) -> usize {
|
||||
match self.view {
|
||||
View::Tasks => self.tasks.len(),
|
||||
View::Routines => self.routines.len(),
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_normal_key(&mut self, key: KeyEvent) {
|
||||
match key.code {
|
||||
KeyCode::Char('q') => self.quit = true,
|
||||
KeyCode::Char('j') | KeyCode::Down => self.select_next(),
|
||||
KeyCode::Char('k') | KeyCode::Up => self.select_previous(),
|
||||
KeyCode::Tab => {
|
||||
self.view = match self.view {
|
||||
View::Tasks => View::Routines,
|
||||
View::Routines => View::Tasks,
|
||||
};
|
||||
self.selected = 0;
|
||||
self.refresh();
|
||||
}
|
||||
KeyCode::Char('h') | KeyCode::Left if self.view == View::Tasks => self.move_date(false),
|
||||
KeyCode::Char('l') | KeyCode::Right if self.view == View::Tasks => self.move_date(true),
|
||||
KeyCode::Char('t') if self.view == View::Tasks => {
|
||||
self.date = Local::now().date_naive();
|
||||
self.refresh();
|
||||
}
|
||||
KeyCode::Char('r') => self.refresh(),
|
||||
KeyCode::Char('a') => self.open_create_form(),
|
||||
KeyCode::Char(' ') if self.view == View::Tasks => self.complete_selected(),
|
||||
KeyCode::Char('x') if self.view == View::Tasks => self.delete_selected(),
|
||||
KeyCode::Char('s') if self.view == View::Tasks => self.open_reschedule_form(),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_form_key(&mut self, key: KeyEvent) {
|
||||
if key.code == KeyCode::Esc {
|
||||
self.form = None;
|
||||
self.status = "cancelled".to_owned();
|
||||
return;
|
||||
}
|
||||
if key.code == KeyCode::Char('s') && key.modifiers.contains(KeyModifiers::CONTROL) {
|
||||
self.submit_form();
|
||||
return;
|
||||
}
|
||||
|
||||
let form = self.form.as_mut().expect("form is present");
|
||||
match key.code {
|
||||
KeyCode::Tab | KeyCode::Down => form.active = (form.active + 1) % form.fields.len(),
|
||||
KeyCode::BackTab | KeyCode::Up => {
|
||||
form.active = form.active.checked_sub(1).unwrap_or(form.fields.len() - 1)
|
||||
}
|
||||
KeyCode::Left => cycle_choice(&mut form.fields[form.active], false),
|
||||
KeyCode::Right => cycle_choice(&mut form.fields[form.active], true),
|
||||
KeyCode::Backspace => {
|
||||
if let FieldValue::Text(value) = &mut form.fields[form.active].value {
|
||||
value.pop();
|
||||
}
|
||||
}
|
||||
KeyCode::Char(character)
|
||||
if !key.modifiers.contains(KeyModifiers::CONTROL)
|
||||
&& !key.modifiers.contains(KeyModifiers::ALT) =>
|
||||
{
|
||||
if let FieldValue::Text(value) = &mut form.fields[form.active].value {
|
||||
value.push(character);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn submit_form(&mut self) {
|
||||
let form = self.form.take().expect("form is present");
|
||||
let result = match form.kind {
|
||||
FormKind::Task => self.submit_task(&form),
|
||||
FormKind::Routine => self.submit_routine(&form),
|
||||
FormKind::Reschedule { task_id } => {
|
||||
self.api.reschedule_task(task_id, form.fields[0].display())
|
||||
}
|
||||
};
|
||||
match result {
|
||||
Ok(()) => {
|
||||
self.status = "saved".to_owned();
|
||||
self.refresh();
|
||||
}
|
||||
Err(error) => {
|
||||
self.status = error;
|
||||
self.form = Some(form);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn submit_task(&self, form: &Form) -> Result<(), String> {
|
||||
self.api.create_task(&CreateTask {
|
||||
title: required(form.fields[0].display(), "title")?,
|
||||
section: form.fields[1].display().to_owned(),
|
||||
priority: form.fields[2].display().to_owned(),
|
||||
reminder_time: optional(form.fields[3].display()),
|
||||
notes: optional(form.fields[4].display()),
|
||||
scheduled_date: self.date.to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
fn submit_routine(&self, form: &Form) -> Result<(), String> {
|
||||
let schedule = parse_schedule(form.fields[3].display(), form.fields[4].display())?;
|
||||
self.api.create_routine(&CreateRoutine {
|
||||
title: required(form.fields[0].display(), "title")?,
|
||||
section: form.fields[1].display().to_owned(),
|
||||
priority: form.fields[2].display().to_owned(),
|
||||
schedule,
|
||||
reminder_time: optional(form.fields[5].display()),
|
||||
notes: optional(form.fields[6].display()),
|
||||
})
|
||||
}
|
||||
|
||||
fn open_create_form(&mut self) {
|
||||
self.form = Some(match self.view {
|
||||
View::Tasks => task_form(),
|
||||
View::Routines => routine_form(),
|
||||
});
|
||||
}
|
||||
|
||||
fn open_reschedule_form(&mut self) {
|
||||
let Some(task) = self.tasks.get(self.selected) else {
|
||||
self.status = "no task selected".to_owned();
|
||||
return;
|
||||
};
|
||||
self.form = Some(Form {
|
||||
kind: FormKind::Reschedule { task_id: task.id },
|
||||
fields: vec![text_field("Date", "YYYY-MM-DD", self.date.to_string())],
|
||||
active: 0,
|
||||
});
|
||||
}
|
||||
|
||||
fn complete_selected(&mut self) {
|
||||
let Some(task) = self.tasks.get(self.selected) else {
|
||||
self.status = "no task selected".to_owned();
|
||||
return;
|
||||
};
|
||||
let result = self.api.complete_task(task.id);
|
||||
self.finish_action(result, "completed");
|
||||
}
|
||||
|
||||
fn delete_selected(&mut self) {
|
||||
let Some(task) = self.tasks.get(self.selected) else {
|
||||
self.status = "no task selected".to_owned();
|
||||
return;
|
||||
};
|
||||
let result = self.api.delete_task(task.id);
|
||||
self.finish_action(result, "deleted");
|
||||
}
|
||||
|
||||
fn finish_action(&mut self, result: Result<(), String>, success: &str) {
|
||||
match result {
|
||||
Ok(()) => {
|
||||
self.status = success.to_owned();
|
||||
self.refresh();
|
||||
}
|
||||
Err(error) => self.status = error,
|
||||
}
|
||||
}
|
||||
|
||||
fn move_date(&mut self, forward: bool) {
|
||||
let changed = if forward {
|
||||
self.date.checked_add_days(Days::new(1))
|
||||
} else {
|
||||
self.date.checked_sub_days(Days::new(1))
|
||||
};
|
||||
if let Some(date) = changed {
|
||||
self.date = date;
|
||||
self.selected = 0;
|
||||
self.refresh();
|
||||
}
|
||||
}
|
||||
|
||||
fn select_next(&mut self) {
|
||||
if self.selected + 1 < self.item_count() {
|
||||
self.selected += 1;
|
||||
}
|
||||
}
|
||||
|
||||
fn select_previous(&mut self) {
|
||||
self.selected = self.selected.saturating_sub(1);
|
||||
}
|
||||
}
|
||||
|
||||
fn task_form() -> Form {
|
||||
Form {
|
||||
kind: FormKind::Task,
|
||||
fields: vec![
|
||||
text_field("Title", "required", String::new()),
|
||||
choice_field("Section", &["morning", "work", "evening"]),
|
||||
choice_field("Priority", &["must", "should", "optional"]),
|
||||
text_field("Reminder", "optional HH:MM", String::new()),
|
||||
text_field("Notes", "optional", String::new()),
|
||||
],
|
||||
active: 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn routine_form() -> Form {
|
||||
Form {
|
||||
kind: FormKind::Routine,
|
||||
fields: vec![
|
||||
text_field("Title", "required", String::new()),
|
||||
choice_field("Section", &["morning", "work", "evening"]),
|
||||
choice_field("Priority", &["must", "should", "optional"]),
|
||||
choice_field("Repeat", &["daily", "weekly", "monthly"]),
|
||||
text_field("Days", "weekly 1-7; monthly 1-31", String::new()),
|
||||
text_field("Reminder", "optional HH:MM", String::new()),
|
||||
text_field("Notes", "optional", String::new()),
|
||||
],
|
||||
active: 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn text_field(label: &'static str, hint: &'static str, value: String) -> Field {
|
||||
Field {
|
||||
label,
|
||||
hint,
|
||||
value: FieldValue::Text(value),
|
||||
}
|
||||
}
|
||||
|
||||
fn choice_field(label: &'static str, options: &'static [&'static str]) -> Field {
|
||||
Field {
|
||||
label,
|
||||
hint: "←/→",
|
||||
value: FieldValue::Choice {
|
||||
options,
|
||||
selected: 0,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn cycle_choice(field: &mut Field, forward: bool) {
|
||||
if let FieldValue::Choice { options, selected } = &mut field.value {
|
||||
*selected = if forward {
|
||||
(*selected + 1) % options.len()
|
||||
} else {
|
||||
selected.checked_sub(1).unwrap_or(options.len() - 1)
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
fn required(value: &str, name: &str) -> Result<String, String> {
|
||||
let value = value.trim();
|
||||
if value.is_empty() {
|
||||
Err(format!("{name} is required"))
|
||||
} else {
|
||||
Ok(value.to_owned())
|
||||
}
|
||||
}
|
||||
|
||||
fn optional(value: &str) -> Option<String> {
|
||||
let value = value.trim();
|
||||
(!value.is_empty()).then(|| value.to_owned())
|
||||
}
|
||||
|
||||
fn parse_schedule(kind: &str, days: &str) -> Result<Schedule, String> {
|
||||
match kind {
|
||||
"daily" => Ok(Schedule::Daily),
|
||||
"weekly" => Ok(Schedule::Weekly {
|
||||
weekdays: parse_days(days, 7)?,
|
||||
}),
|
||||
"monthly" => Ok(Schedule::Monthly {
|
||||
days: parse_days(days, 31)?,
|
||||
clamp_to_last_day: true,
|
||||
}),
|
||||
_ => Err("unknown routine schedule".to_owned()),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_days(input: &str, maximum: u32) -> Result<Vec<u32>, String> {
|
||||
let mut values = input
|
||||
.split(',')
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty())
|
||||
.map(|value| {
|
||||
value
|
||||
.parse::<u32>()
|
||||
.map_err(|_| "days must be comma-separated numbers".to_owned())
|
||||
})
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
values.sort_unstable();
|
||||
values.dedup();
|
||||
if values.is_empty() || values.iter().any(|day| !(1..=maximum).contains(day)) {
|
||||
return Err(format!("days must contain values 1 through {maximum}"));
|
||||
}
|
||||
Ok(values)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parses_and_normalizes_weekdays() {
|
||||
assert!(matches!(
|
||||
parse_schedule("weekly", "5, 1,5").unwrap(),
|
||||
Schedule::Weekly { weekdays } if weekdays == vec![1, 5]
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_out_of_range_month_day() {
|
||||
assert_eq!(
|
||||
parse_schedule("monthly", "32").unwrap_err(),
|
||||
"days must contain values 1 through 31"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
mod api;
|
||||
mod app;
|
||||
mod model;
|
||||
mod ui;
|
||||
|
||||
use std::env;
|
||||
use std::io::{self, stdout};
|
||||
use std::time::Duration;
|
||||
|
||||
use crossterm::event::{self, Event, KeyEventKind};
|
||||
use crossterm::execute;
|
||||
use crossterm::terminal::{
|
||||
disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen,
|
||||
};
|
||||
use ratatui::backend::CrosstermBackend;
|
||||
use ratatui::Terminal;
|
||||
|
||||
use api::ApiClient;
|
||||
use app::App;
|
||||
|
||||
fn main() {
|
||||
if let Err(error) = run() {
|
||||
eprintln!("routine-tui: {error}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
fn run() -> Result<(), String> {
|
||||
let base_url =
|
||||
env::var("ROUTINE_API_URL").unwrap_or_else(|_| "http://127.0.0.1:8090".to_owned());
|
||||
let token = env::var("ROUTINE_API_TOKEN").ok();
|
||||
let mut app = App::new(ApiClient::new(base_url, token));
|
||||
app.refresh();
|
||||
|
||||
enable_raw_mode().map_err(io_error)?;
|
||||
let mut output = stdout();
|
||||
execute!(output, EnterAlternateScreen).map_err(io_error)?;
|
||||
let backend = CrosstermBackend::new(output);
|
||||
let mut terminal = Terminal::new(backend).map_err(io_error)?;
|
||||
|
||||
let result = event_loop(&mut terminal, &mut app);
|
||||
disable_raw_mode().map_err(io_error)?;
|
||||
execute!(terminal.backend_mut(), LeaveAlternateScreen).map_err(io_error)?;
|
||||
terminal.show_cursor().map_err(io_error)?;
|
||||
result
|
||||
}
|
||||
|
||||
fn event_loop(
|
||||
terminal: &mut Terminal<CrosstermBackend<io::Stdout>>,
|
||||
app: &mut App,
|
||||
) -> Result<(), String> {
|
||||
while !app.quit {
|
||||
terminal
|
||||
.draw(|frame| ui::render(frame, app))
|
||||
.map_err(io_error)?;
|
||||
if event::poll(Duration::from_millis(250)).map_err(io_error)? {
|
||||
if let Event::Key(key) = event::read().map_err(io_error)? {
|
||||
if key.kind == KeyEventKind::Press {
|
||||
app.handle_key(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn io_error(error: io::Error) -> String {
|
||||
error.to_string()
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct Task {
|
||||
pub id: i64,
|
||||
pub routine_id: Option<i64>,
|
||||
pub title: String,
|
||||
pub notes: Option<String>,
|
||||
pub section: String,
|
||||
pub priority: String,
|
||||
pub reminder_time: Option<String>,
|
||||
pub status: String,
|
||||
pub completed_at: Option<i64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct Routine {
|
||||
pub title: String,
|
||||
pub notes: Option<String>,
|
||||
pub section: String,
|
||||
pub priority: String,
|
||||
pub schedule: Schedule,
|
||||
pub reminder_time: Option<String>,
|
||||
pub enabled: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
#[serde(tag = "kind", rename_all = "snake_case")]
|
||||
pub enum Schedule {
|
||||
Daily,
|
||||
Weekly {
|
||||
weekdays: Vec<u32>,
|
||||
},
|
||||
Monthly {
|
||||
days: Vec<u32>,
|
||||
clamp_to_last_day: bool,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct CreateTask {
|
||||
pub title: String,
|
||||
pub notes: Option<String>,
|
||||
pub section: String,
|
||||
pub priority: String,
|
||||
pub scheduled_date: String,
|
||||
pub reminder_time: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct CreateRoutine {
|
||||
pub title: String,
|
||||
pub notes: Option<String>,
|
||||
pub section: String,
|
||||
pub priority: String,
|
||||
pub schedule: Schedule,
|
||||
pub reminder_time: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct RescheduleTask {
|
||||
pub scheduled_date: String,
|
||||
}
|
||||
|
||||
pub fn schedule_label(schedule: &Schedule) -> String {
|
||||
match schedule {
|
||||
Schedule::Daily => "daily".to_owned(),
|
||||
Schedule::Weekly { weekdays } => format!("weekly [{}]", join_numbers(weekdays)),
|
||||
Schedule::Monthly {
|
||||
days,
|
||||
clamp_to_last_day,
|
||||
} => {
|
||||
let suffix = if *clamp_to_last_day { ", clamp" } else { "" };
|
||||
format!("monthly [{}{suffix}]", join_numbers(days))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn join_numbers(numbers: &[u32]) -> String {
|
||||
numbers
|
||||
.iter()
|
||||
.map(u32::to_string)
|
||||
.collect::<Vec<_>>()
|
||||
.join(",")
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
use ratatui::layout::{Alignment, Constraint, Layout, Rect};
|
||||
use ratatui::style::{Color, Modifier, Style};
|
||||
use ratatui::text::{Line, Span};
|
||||
use ratatui::widgets::{Block, Borders, Clear, List, ListItem, ListState, Paragraph, Wrap};
|
||||
use ratatui::Frame;
|
||||
|
||||
use crate::app::{App, FormKind, View};
|
||||
use crate::model::schedule_label;
|
||||
|
||||
pub fn render(frame: &mut Frame, app: &App) {
|
||||
let rows = Layout::vertical([
|
||||
Constraint::Length(3),
|
||||
Constraint::Min(5),
|
||||
Constraint::Length(3),
|
||||
])
|
||||
.split(frame.area());
|
||||
|
||||
let active = Style::default()
|
||||
.fg(Color::Black)
|
||||
.bg(Color::Cyan)
|
||||
.add_modifier(Modifier::BOLD);
|
||||
let tasks_style = if app.view == View::Tasks {
|
||||
active
|
||||
} else {
|
||||
Style::default()
|
||||
};
|
||||
let routines_style = if app.view == View::Routines {
|
||||
active
|
||||
} else {
|
||||
Style::default()
|
||||
};
|
||||
let date = if app.view == View::Tasks {
|
||||
format!(" {} ", app.date)
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
let header = Paragraph::new(Line::from(vec![
|
||||
Span::styled(" Tasks ", tasks_style),
|
||||
Span::raw(" "),
|
||||
Span::styled(" Routines ", routines_style),
|
||||
Span::raw(date),
|
||||
]))
|
||||
.block(Block::default().borders(Borders::ALL).title("Routine"));
|
||||
frame.render_widget(header, rows[0]);
|
||||
|
||||
let items = match app.view {
|
||||
View::Tasks => app
|
||||
.tasks
|
||||
.iter()
|
||||
.map(|task| {
|
||||
let mark = if task.status == "completed" {
|
||||
"✓"
|
||||
} else {
|
||||
"○"
|
||||
};
|
||||
let reminder = task
|
||||
.reminder_time
|
||||
.as_deref()
|
||||
.map(|time| format!(" @{time}"))
|
||||
.unwrap_or_default();
|
||||
let source = task.routine_id.map(|_| " ↻").unwrap_or_default();
|
||||
let completed = task.completed_at.map(|_| " done").unwrap_or_default();
|
||||
let mut lines = vec![Line::from(format!(
|
||||
"{mark} {:<8} {:<8} {}{reminder}{source}{completed}",
|
||||
task.section, task.priority, task.title
|
||||
))];
|
||||
if let Some(notes) = task.notes.as_deref().filter(|notes| !notes.is_empty()) {
|
||||
lines.push(Line::styled(
|
||||
format!(" {notes}"),
|
||||
Style::default().fg(Color::DarkGray),
|
||||
));
|
||||
}
|
||||
ListItem::new(lines)
|
||||
})
|
||||
.collect::<Vec<_>>(),
|
||||
View::Routines => app
|
||||
.routines
|
||||
.iter()
|
||||
.map(|routine| {
|
||||
let enabled = if routine.enabled { "●" } else { "○" };
|
||||
let reminder = routine
|
||||
.reminder_time
|
||||
.as_deref()
|
||||
.map(|time| format!(" @{time}"))
|
||||
.unwrap_or_default();
|
||||
let mut lines = vec![Line::from(format!(
|
||||
"{enabled} {:<8} {:<8} {} — {}{reminder}",
|
||||
routine.section,
|
||||
routine.priority,
|
||||
routine.title,
|
||||
schedule_label(&routine.schedule)
|
||||
))];
|
||||
if let Some(notes) = routine.notes.as_deref().filter(|notes| !notes.is_empty()) {
|
||||
lines.push(Line::styled(
|
||||
format!(" {notes}"),
|
||||
Style::default().fg(Color::DarkGray),
|
||||
));
|
||||
}
|
||||
ListItem::new(lines)
|
||||
})
|
||||
.collect::<Vec<_>>(),
|
||||
};
|
||||
let title = match app.view {
|
||||
View::Tasks => "Tasks for selected day",
|
||||
View::Routines => "Daily, weekly, and monthly routines",
|
||||
};
|
||||
let list = List::new(items)
|
||||
.block(Block::default().borders(Borders::ALL).title(title))
|
||||
.highlight_style(Style::default().bg(Color::DarkGray).fg(Color::White))
|
||||
.highlight_symbol("› ");
|
||||
let mut state =
|
||||
ListState::default().with_selected((app.item_count() > 0).then_some(app.selected));
|
||||
frame.render_stateful_widget(list, rows[1], &mut state);
|
||||
|
||||
let help = match app.view {
|
||||
View::Tasks => {
|
||||
"q quit Tab routines h/l day t today j/k move a add Space complete s move x delete r refresh"
|
||||
}
|
||||
View::Routines => "q quit Tab tasks j/k move a add routine r refresh",
|
||||
};
|
||||
let footer = Paragraph::new(vec![
|
||||
Line::from(help),
|
||||
Line::styled(&app.status, Style::default().fg(Color::Yellow)),
|
||||
])
|
||||
.alignment(Alignment::Left)
|
||||
.block(Block::default().borders(Borders::TOP));
|
||||
frame.render_widget(footer, rows[2]);
|
||||
|
||||
if let Some(form) = &app.form {
|
||||
let height = (form.fields.len() as u16 * 2 + 5).min(frame.area().height);
|
||||
let area = centered_rect(72, height, frame.area());
|
||||
frame.render_widget(Clear, area);
|
||||
let title = match form.kind {
|
||||
FormKind::Task => format!("New task for {}", app.date),
|
||||
FormKind::Routine => "New routine".to_owned(),
|
||||
FormKind::Reschedule { .. } => "Reschedule task".to_owned(),
|
||||
};
|
||||
let lines = form
|
||||
.fields
|
||||
.iter()
|
||||
.enumerate()
|
||||
.flat_map(|(index, field)| {
|
||||
let style = if index == form.active {
|
||||
Style::default()
|
||||
.fg(Color::Cyan)
|
||||
.add_modifier(Modifier::BOLD)
|
||||
} else {
|
||||
Style::default()
|
||||
};
|
||||
[
|
||||
Line::styled(format!("{} ({})", field.label, field.hint), style),
|
||||
Line::from(format!(" {}", field.display())),
|
||||
]
|
||||
})
|
||||
.chain([
|
||||
Line::from(""),
|
||||
Line::from("Ctrl+S save • Esc cancel • Tab field"),
|
||||
])
|
||||
.collect::<Vec<_>>();
|
||||
let dialog = Paragraph::new(lines)
|
||||
.wrap(Wrap { trim: false })
|
||||
.block(Block::default().borders(Borders::ALL).title(title));
|
||||
frame.render_widget(dialog, area);
|
||||
}
|
||||
}
|
||||
|
||||
fn centered_rect(width_percent: u16, height: u16, area: Rect) -> Rect {
|
||||
let vertical_margin = area.height.saturating_sub(height) / 2;
|
||||
let vertical = Layout::vertical([
|
||||
Constraint::Length(vertical_margin),
|
||||
Constraint::Length(height),
|
||||
Constraint::Min(0),
|
||||
])
|
||||
.split(area);
|
||||
let horizontal_margin = (100 - width_percent) / 2;
|
||||
Layout::horizontal([
|
||||
Constraint::Percentage(horizontal_margin),
|
||||
Constraint::Percentage(width_percent),
|
||||
Constraint::Percentage(horizontal_margin),
|
||||
])
|
||||
.split(vertical[1])[1]
|
||||
}
|
||||
Reference in New Issue
Block a user