encryption
runner nix smoke / nix label and flake smoke (push) Canceled after 0s

This commit is contained in:
2026-10-15 00:40:41 +00:00
parent 7bceeb255e
commit 60d2e5d80f
13 changed files with 799 additions and 118 deletions
+20 -2
View File
@@ -10,6 +10,22 @@ Configuration:
- `ROUTINE_API_URL` defaults to `http://127.0.0.1:8090`.
- `ROUTINE_API_TOKEN` is sent as a bearer token when set.
- `ROUTINE_AGE_RECIPIENT` enables encryption of private titles and notes.
- `ROUTINE_AGE_IDENTITY_FILE` points to the local age identity used for
decryption. The identity is never sent to the server.
Generate an identity and configure the client:
```sh
age-keygen -o ~/.config/routine/identity.txt
export ROUTINE_AGE_RECIPIENT='age1...'
export ROUTINE_AGE_IDENTITY_FILE="$HOME/.config/routine/identity.txt"
```
Every task and routine has a required public title used by Telegram. When a
private title decrypts successfully, the TUI displays it instead. If no private
title exists—or the identity is unavailable—the TUI displays the public title.
Notes are always inside the encrypted JSON.
Because the production server is loopback-only, either run the TUI on
`hectic-lab` or open a local tunnel first:
@@ -20,11 +36,13 @@ ssh -N -L 8090:127.0.0.1:8090 hectic-lab
Keys:
- `Tab`: switch between tasks and routines.
- `Tab`: switch between tasks, routines, and the archive.
- `h`/`l`: previous/next day; `t`: today.
- `j`/`k`: move selection; `r`: refresh; `q`: quit.
- `a`: add a task or routine; `Ctrl+S`: save a form; `Esc`: cancel.
- `Space`: complete task; `s`: reschedule; `x`: delete.
- On Tasks, `Space` completes, `s` reschedules, and `x` archives after confirmation.
- On Archive, `u` restores to the original day and section; `x` permanently
deletes after confirmation.
Weekly routine days use ISO numbers (`1` Monday through `7` Sunday). Monthly
days use `1` through `31`; days beyond the end of a short month clamp to its
+9 -1
View File
@@ -1,6 +1,8 @@
{
cargoToml,
age,
lib,
makeWrapper,
nativeBuildInputs,
pkgs,
...
@@ -12,10 +14,16 @@ in
version = cargo.package.version;
src = ./.;
inherit nativeBuildInputs;
nativeBuildInputs = nativeBuildInputs ++ [ makeWrapper ];
nativeCheckInputs = [ age ];
cargoLock.lockFile = ./Cargo.lock;
doCheck = true;
postFixup = ''
wrapProgram $out/bin/routine-tui \
--prefix PATH : ${lib.makeBinPath [ age ]}
'';
meta = {
description = cargo.package.description;
license = lib.licenses.mit;
+12
View File
@@ -24,6 +24,10 @@ impl ApiClient {
self.get("/v1/routines")
}
pub fn list_archived_tasks(&self) -> Result<Vec<Task>, String> {
self.get("/v1/tasks/archived")
}
pub fn create_task(&self, task: &CreateTask) -> Result<(), String> {
self.send_json("/v1/tasks", task)
}
@@ -36,6 +40,14 @@ impl ApiClient {
self.send_empty("POST", &format!("/v1/tasks/{id}/complete"))
}
pub fn archive_task(&self, id: i64) -> Result<(), String> {
self.send_empty("POST", &format!("/v1/tasks/{id}/archive"))
}
pub fn restore_task(&self, id: i64) -> Result<(), String> {
self.send_empty("POST", &format!("/v1/tasks/{id}/restore"))
}
pub fn delete_task(&self, id: i64) -> Result<(), String> {
self.send_empty("DELETE", &format!("/v1/tasks/{id}"))
}
+192 -28
View File
@@ -2,12 +2,14 @@ use chrono::{Days, Local, NaiveDate};
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use crate::api::ApiClient;
use crate::crypto::Crypto;
use crate::model::{CreateRoutine, CreateTask, Routine, Schedule, Task};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum View {
Tasks,
Routines,
Archive,
}
#[derive(Debug, Clone, Copy)]
@@ -49,29 +51,48 @@ pub struct Form {
pub active: usize,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PendingActionKind {
Archive,
Delete,
}
#[derive(Debug, Clone)]
pub struct PendingAction {
pub task_id: i64,
pub title: String,
pub kind: PendingActionKind,
}
pub struct App {
pub api: ApiClient,
pub crypto: Crypto,
pub view: View,
pub date: NaiveDate,
pub tasks: Vec<Task>,
pub archived_tasks: Vec<Task>,
pub routines: Vec<Routine>,
pub selected: usize,
pub status: String,
pub form: Option<Form>,
pub pending_action: Option<PendingAction>,
pub quit: bool,
}
impl App {
pub fn new(api: ApiClient) -> Self {
pub fn new(api: ApiClient, crypto: Crypto) -> Self {
Self {
api,
crypto,
view: View::Tasks,
date: Local::now().date_naive(),
tasks: Vec::new(),
archived_tasks: Vec::new(),
routines: Vec::new(),
selected: 0,
status: "connecting…".to_owned(),
form: None,
pending_action: None,
quit: false,
}
}
@@ -81,11 +102,24 @@ impl App {
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),
.map(|mut tasks| {
tasks
.iter_mut()
.for_each(|task| self.crypto.decrypt_task(task));
self.tasks = tasks;
}),
View::Routines => self.api.list_routines().map(|mut routines| {
routines
.iter_mut()
.for_each(|routine| self.crypto.decrypt_routine(routine));
self.routines = routines;
}),
View::Archive => self.api.list_archived_tasks().map(|mut tasks| {
tasks
.iter_mut()
.for_each(|task| self.crypto.decrypt_task(task));
self.archived_tasks = tasks;
}),
};
self.selected = self.selected.min(self.item_count().saturating_sub(1));
self.status = match result {
@@ -95,7 +129,9 @@ impl App {
}
pub fn handle_key(&mut self, key: KeyEvent) {
if self.form.is_some() {
if self.pending_action.is_some() {
self.handle_action_confirmation(key);
} else if self.form.is_some() {
self.handle_form_key(key);
} else {
self.handle_normal_key(key);
@@ -106,6 +142,7 @@ impl App {
match self.view {
View::Tasks => self.tasks.len(),
View::Routines => self.routines.len(),
View::Archive => self.archived_tasks.len(),
}
}
@@ -117,7 +154,8 @@ impl App {
KeyCode::Tab => {
self.view = match self.view {
View::Tasks => View::Routines,
View::Routines => View::Tasks,
View::Routines => View::Archive,
View::Archive => View::Tasks,
};
self.selected = 0;
self.refresh();
@@ -129,14 +167,38 @@ impl App {
self.refresh();
}
KeyCode::Char('r') => self.refresh(),
KeyCode::Char('a') => self.open_create_form(),
KeyCode::Char('a') if self.view != View::Archive => 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('x') if self.view == View::Tasks => self.ask_archive_selected(),
KeyCode::Char('x') if self.view == View::Archive => self.ask_delete_selected(),
KeyCode::Char('u') if self.view == View::Archive => self.restore_selected(),
KeyCode::Char('s') if self.view == View::Tasks => self.open_reschedule_form(),
_ => {}
}
}
fn handle_action_confirmation(&mut self, key: KeyEvent) {
match key.code {
KeyCode::Char('y') | KeyCode::Char('Y') => {
let pending = self.pending_action.take().expect("task action is pending");
let (result, success) = match pending.kind {
PendingActionKind::Archive => {
(self.api.archive_task(pending.task_id), "archived")
}
PendingActionKind::Delete => {
(self.api.delete_task(pending.task_id), "deleted permanently")
}
};
self.finish_action(result, success);
}
KeyCode::Char('n') | KeyCode::Char('N') | KeyCode::Esc => {
self.pending_action = None;
self.status = "action cancelled".to_owned();
}
_ => {}
}
}
fn handle_form_key(&mut self, key: KeyEvent) {
if key.code == KeyCode::Esc {
self.form = None;
@@ -195,25 +257,37 @@ impl App {
}
fn submit_task(&self, form: &Form) -> Result<(), String> {
let encrypted = self.crypto.encrypt_optional(
optional(form.fields[1].display()),
optional(form.fields[2].display()),
)?;
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()),
public_title: required(form.fields[0].display(), "public title")?,
encrypted_payload: encrypted.encrypted_payload,
encryption_version: encrypted.encryption_version,
content_id: encrypted.content_id,
section: form.fields[3].display().to_owned(),
priority: form.fields[4].display().to_owned(),
reminder_time: optional(form.fields[5].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())?;
let encrypted = self.crypto.encrypt_optional(
optional(form.fields[1].display()),
optional(form.fields[2].display()),
)?;
let schedule = parse_schedule(form.fields[5].display(), form.fields[6].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(),
public_title: required(form.fields[0].display(), "public title")?,
encrypted_payload: encrypted.encrypted_payload,
encryption_version: encrypted.encryption_version,
content_id: encrypted.content_id,
section: form.fields[3].display().to_owned(),
priority: form.fields[4].display().to_owned(),
schedule,
reminder_time: optional(form.fields[5].display()),
notes: optional(form.fields[6].display()),
reminder_time: optional(form.fields[7].display()),
})
}
@@ -221,6 +295,7 @@ impl App {
self.form = Some(match self.view {
View::Tasks => task_form(),
View::Routines => routine_form(),
View::Archive => return,
});
}
@@ -245,13 +320,37 @@ impl App {
self.finish_action(result, "completed");
}
fn delete_selected(&mut self) {
fn ask_archive_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");
self.pending_action = Some(PendingAction {
task_id: task.id,
title: task.visible_title().to_owned(),
kind: PendingActionKind::Archive,
});
}
fn ask_delete_selected(&mut self) {
let Some(task) = self.archived_tasks.get(self.selected) else {
self.status = "no archived task selected".to_owned();
return;
};
self.pending_action = Some(PendingAction {
task_id: task.id,
title: task.visible_title().to_owned(),
kind: PendingActionKind::Delete,
});
}
fn restore_selected(&mut self) {
let Some(task) = self.archived_tasks.get(self.selected) else {
self.status = "no archived task selected".to_owned();
return;
};
let result = self.api.restore_task(task.id);
self.finish_action(result, "restored to its original day and section");
}
fn finish_action(&mut self, result: Result<(), String>, success: &str) {
@@ -292,11 +391,16 @@ fn task_form() -> Form {
Form {
kind: FormKind::Task,
fields: vec![
text_field("Title", "required", String::new()),
text_field(
"Public title",
"required; Telegram uses this",
String::new(),
),
text_field("Private title", "optional; encrypted", String::new()),
text_field("Notes", "optional; encrypted", 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,
}
@@ -306,13 +410,18 @@ fn routine_form() -> Form {
Form {
kind: FormKind::Routine,
fields: vec![
text_field("Title", "required", String::new()),
text_field(
"Public title",
"required; Telegram uses this",
String::new(),
),
text_field("Private title", "optional; encrypted", String::new()),
text_field("Notes", "optional; encrypted", 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,
}
@@ -398,6 +507,26 @@ fn parse_days(input: &str, maximum: u32) -> Result<Vec<u32>, String> {
mod tests {
use super::*;
fn task() -> Task {
Task {
id: 42,
routine_id: None,
public_title: "Keep me".to_owned(),
encrypted_payload: None,
encryption_version: None,
content_id: None,
section: "morning".to_owned(),
priority: "must".to_owned(),
scheduled_date: "2026-10-15".to_owned(),
reminder_time: None,
status: "pending".to_owned(),
completed_at: None,
private_title: None,
private_notes: None,
decryption_failed: false,
}
}
#[test]
fn parses_and_normalizes_weekdays() {
assert!(matches!(
@@ -413,4 +542,39 @@ mod tests {
"days must contain values 1 through 31"
);
}
#[test]
fn active_task_archives_only_after_confirmation() {
let mut app = App::new(
ApiClient::new("http://127.0.0.1:1".to_owned(), None),
Crypto::disabled(),
);
app.tasks.push(task());
app.handle_key(KeyEvent::new(KeyCode::Char('x'), KeyModifiers::NONE));
let pending = app.pending_action.as_ref().unwrap();
assert_eq!(pending.task_id, 42);
assert_eq!(pending.title, "Keep me");
assert_eq!(pending.kind, PendingActionKind::Archive);
app.handle_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
assert!(app.pending_action.is_none());
assert_eq!(app.status, "action cancelled");
}
#[test]
fn archived_task_requires_confirmation_before_permanent_delete() {
let mut app = App::new(
ApiClient::new("http://127.0.0.1:1".to_owned(), None),
Crypto::disabled(),
);
app.view = View::Archive;
app.archived_tasks.push(task());
app.handle_key(KeyEvent::new(KeyCode::Char('x'), KeyModifiers::NONE));
assert_eq!(
app.pending_action.as_ref().unwrap().kind,
PendingActionKind::Delete
);
}
}
+218
View File
@@ -0,0 +1,218 @@
use std::env;
use std::io::Write;
use std::path::PathBuf;
use std::process::{Command, Stdio};
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{SystemTime, UNIX_EPOCH};
use crate::model::{EncryptedFields, PrivatePayload, Routine, Task};
const ENCRYPTION_VERSION: i16 = 1;
static CONTENT_COUNTER: AtomicU64 = AtomicU64::new(0);
pub struct Crypto {
recipient: Option<String>,
identity_file: Option<PathBuf>,
}
impl Crypto {
pub fn from_env() -> Self {
Self {
recipient: env::var("ROUTINE_AGE_RECIPIENT").ok(),
identity_file: env::var_os("ROUTINE_AGE_IDENTITY_FILE").map(PathBuf::from),
}
}
#[cfg(test)]
pub fn disabled() -> Self {
Self {
recipient: None,
identity_file: None,
}
}
pub fn encrypt_optional(
&self,
private_title: Option<String>,
notes: Option<String>,
) -> Result<EncryptedFields, String> {
if private_title.is_none() && notes.is_none() {
return Ok(EncryptedFields::default());
}
let recipient = self
.recipient
.as_deref()
.ok_or_else(|| "ROUTINE_AGE_RECIPIENT is required for private fields".to_owned())?;
let content_id = new_content_id()?;
let plaintext = serde_json::to_vec(&PrivatePayload {
version: ENCRYPTION_VERSION as u8,
content_id: content_id.clone(),
private_title,
notes,
})
.map_err(|error| format!("cannot encode private fields: {error}"))?;
let encrypted_payload = run_age(
&["--encrypt", "--armor", "--recipient", recipient],
&plaintext,
)?;
let encrypted_payload = String::from_utf8(encrypted_payload)
.map_err(|_| "age returned non-UTF-8 armored output".to_owned())?;
Ok(EncryptedFields {
encrypted_payload: Some(encrypted_payload),
encryption_version: Some(ENCRYPTION_VERSION),
content_id: Some(content_id),
})
}
pub fn decrypt_task(&self, task: &mut Task) {
match self.decrypt_fields(
task.encrypted_payload.as_deref(),
task.encryption_version,
task.content_id.as_deref(),
) {
Ok(Some(private)) => {
task.private_title = private
.private_title
.filter(|title| !title.trim().is_empty());
task.private_notes = private.notes.filter(|notes| !notes.trim().is_empty());
}
Ok(None) => {}
Err(()) => task.decryption_failed = true,
}
}
pub fn decrypt_routine(&self, routine: &mut Routine) {
match self.decrypt_fields(
routine.encrypted_payload.as_deref(),
routine.encryption_version,
routine.content_id.as_deref(),
) {
Ok(Some(private)) => {
routine.private_title = private
.private_title
.filter(|title| !title.trim().is_empty());
routine.private_notes = private.notes.filter(|notes| !notes.trim().is_empty());
}
Ok(None) => {}
Err(()) => routine.decryption_failed = true,
}
}
fn decrypt_fields(
&self,
encrypted_payload: Option<&str>,
encryption_version: Option<i16>,
content_id: Option<&str>,
) -> Result<Option<PrivatePayload>, ()> {
let Some(encrypted_payload) = encrypted_payload else {
return Ok(None);
};
if encryption_version != Some(ENCRYPTION_VERSION) {
return Err(());
}
let identity_file = self.identity_file.as_ref().ok_or(())?;
let identity = identity_file.to_str().ok_or(())?;
let plaintext = run_age(
&["--decrypt", "--identity", identity],
encrypted_payload.as_bytes(),
)
.map_err(|_| ())?;
let private: PrivatePayload = serde_json::from_slice(&plaintext).map_err(|_| ())?;
if private.version != ENCRYPTION_VERSION as u8
|| Some(private.content_id.as_str()) != content_id
{
return Err(());
}
Ok(Some(private))
}
}
fn run_age(arguments: &[&str], input: &[u8]) -> Result<Vec<u8>, String> {
let mut child = Command::new("age")
.args(arguments)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.map_err(|error| format!("cannot start age: {error}"))?;
child
.stdin
.take()
.ok_or_else(|| "cannot open age input".to_owned())?
.write_all(input)
.map_err(|error| format!("cannot write age input: {error}"))?;
let output = child
.wait_with_output()
.map_err(|error| format!("cannot wait for age: {error}"))?;
if output.status.success() {
Ok(output.stdout)
} else {
let detail = String::from_utf8_lossy(&output.stderr);
Err(format!("age failed: {}", detail.trim()))
}
}
fn new_content_id() -> Result<String, String> {
let nanos = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_err(|_| "system clock is before Unix epoch".to_owned())?
.as_nanos();
let counter = CONTENT_COUNTER.fetch_add(1, Ordering::Relaxed) as u128;
let process = std::process::id() as u128;
Ok(format!("{:032x}", nanos ^ (process << 64) ^ counter))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn age_round_trip_preserves_private_json_and_content_id() {
let test_dir =
env::temp_dir().join(format!("routine-age-test-{}", new_content_id().unwrap()));
std::fs::create_dir(&test_dir).unwrap();
let identity_file = test_dir.join("identity.txt");
let generated = Command::new("age-keygen")
.args(["-o", identity_file.to_str().unwrap()])
.output()
.unwrap();
assert!(generated.status.success());
let recipient = Command::new("age-keygen")
.args(["-y", identity_file.to_str().unwrap()])
.output()
.unwrap();
assert!(recipient.status.success());
let crypto = Crypto {
recipient: Some(
String::from_utf8(recipient.stdout)
.unwrap()
.trim()
.to_owned(),
),
identity_file: Some(identity_file),
};
let encrypted = crypto
.encrypt_optional(
Some("Private appointment".to_owned()),
Some("Private notes".to_owned()),
)
.unwrap();
let decrypted = crypto
.decrypt_fields(
encrypted.encrypted_payload.as_deref(),
encrypted.encryption_version,
encrypted.content_id.as_deref(),
)
.unwrap()
.unwrap();
assert_eq!(decrypted.content_id, encrypted.content_id.unwrap());
assert_eq!(
decrypted.private_title.as_deref(),
Some("Private appointment")
);
assert_eq!(decrypted.notes.as_deref(), Some("Private notes"));
std::fs::remove_dir_all(test_dir).unwrap();
}
}
+3 -1
View File
@@ -1,5 +1,6 @@
mod api;
mod app;
mod crypto;
mod model;
mod ui;
@@ -17,6 +18,7 @@ use ratatui::Terminal;
use api::ApiClient;
use app::App;
use crypto::Crypto;
fn main() {
if let Err(error) = run() {
@@ -29,7 +31,7 @@ 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));
let mut app = App::new(ApiClient::new(base_url, token), Crypto::from_env());
app.refresh();
enable_raw_mode().map_err(io_error)?;
+66 -8
View File
@@ -4,24 +4,41 @@ use serde::{Deserialize, Serialize};
pub struct Task {
pub id: i64,
pub routine_id: Option<i64>,
pub title: String,
pub notes: Option<String>,
pub public_title: String,
pub encrypted_payload: Option<String>,
pub encryption_version: Option<i16>,
pub content_id: Option<String>,
pub section: String,
pub priority: String,
pub scheduled_date: String,
pub reminder_time: Option<String>,
pub status: String,
pub completed_at: Option<i64>,
#[serde(skip)]
pub private_title: Option<String>,
#[serde(skip)]
pub private_notes: Option<String>,
#[serde(skip)]
pub decryption_failed: bool,
}
#[derive(Debug, Clone, Deserialize)]
pub struct Routine {
pub title: String,
pub notes: Option<String>,
pub public_title: String,
pub encrypted_payload: Option<String>,
pub encryption_version: Option<i16>,
pub content_id: Option<String>,
pub section: String,
pub priority: String,
pub schedule: Schedule,
pub reminder_time: Option<String>,
pub enabled: bool,
#[serde(skip)]
pub private_title: Option<String>,
#[serde(skip)]
pub private_notes: Option<String>,
#[serde(skip)]
pub decryption_failed: bool,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
@@ -39,8 +56,10 @@ pub enum Schedule {
#[derive(Debug, Serialize)]
pub struct CreateTask {
pub title: String,
pub notes: Option<String>,
pub public_title: String,
pub encrypted_payload: Option<String>,
pub encryption_version: Option<i16>,
pub content_id: Option<String>,
pub section: String,
pub priority: String,
pub scheduled_date: String,
@@ -49,8 +68,10 @@ pub struct CreateTask {
#[derive(Debug, Serialize)]
pub struct CreateRoutine {
pub title: String,
pub notes: Option<String>,
pub public_title: String,
pub encrypted_payload: Option<String>,
pub encryption_version: Option<i16>,
pub content_id: Option<String>,
pub section: String,
pub priority: String,
pub schedule: Schedule,
@@ -62,6 +83,43 @@ pub struct RescheduleTask {
pub scheduled_date: String,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct PrivatePayload {
pub version: u8,
pub content_id: String,
#[serde(default)]
pub private_title: Option<String>,
#[serde(default)]
pub notes: Option<String>,
}
#[derive(Debug, Default)]
pub struct EncryptedFields {
pub encrypted_payload: Option<String>,
pub encryption_version: Option<i16>,
pub content_id: Option<String>,
}
impl Task {
pub fn visible_title(&self) -> &str {
self.private_title.as_deref().unwrap_or(&self.public_title)
}
pub fn visible_notes(&self) -> Option<&str> {
self.private_notes.as_deref()
}
}
impl Routine {
pub fn visible_title(&self) -> &str {
self.private_title.as_deref().unwrap_or(&self.public_title)
}
pub fn visible_notes(&self) -> Option<&str> {
self.private_notes.as_deref()
}
}
pub fn schedule_label(schedule: &Schedule) -> String {
match schedule {
Schedule::Daily => "daily".to_owned(),
+72 -7
View File
@@ -4,7 +4,7 @@ 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::app::{App, FormKind, PendingActionKind, View};
use crate::model::schedule_label;
pub fn render(frame: &mut Frame, app: &App) {
@@ -29,6 +29,11 @@ pub fn render(frame: &mut Frame, app: &App) {
} else {
Style::default()
};
let archive_style = if app.view == View::Archive {
active
} else {
Style::default()
};
let date = if app.view == View::Tasks {
format!(" {} ", app.date)
} else {
@@ -38,6 +43,8 @@ pub fn render(frame: &mut Frame, app: &App) {
Span::styled(" Tasks ", tasks_style),
Span::raw(" "),
Span::styled(" Routines ", routines_style),
Span::raw(" "),
Span::styled(" Archive ", archive_style),
Span::raw(date),
]))
.block(Block::default().borders(Borders::ALL).title("Routine"));
@@ -60,11 +67,14 @@ pub fn render(frame: &mut Frame, app: &App) {
.unwrap_or_default();
let source = task.routine_id.map(|_| " ↻").unwrap_or_default();
let completed = task.completed_at.map(|_| " done").unwrap_or_default();
let lock = if task.decryption_failed { " 🔒" } else { "" };
let mut lines = vec![Line::from(format!(
"{mark} {:<8} {:<8} {}{reminder}{source}{completed}",
task.section, task.priority, task.title
"{mark} {:<8} {:<8} {}{reminder}{source}{completed}{lock}",
task.section,
task.priority,
task.visible_title()
))];
if let Some(notes) = task.notes.as_deref().filter(|notes| !notes.is_empty()) {
if let Some(notes) = task.visible_notes() {
lines.push(Line::styled(
format!(" {notes}"),
Style::default().fg(Color::DarkGray),
@@ -83,14 +93,46 @@ pub fn render(frame: &mut Frame, app: &App) {
.as_deref()
.map(|time| format!(" @{time}"))
.unwrap_or_default();
let lock = if routine.decryption_failed {
" 🔒"
} else {
""
};
let mut lines = vec![Line::from(format!(
"{enabled} {:<8} {:<8} {} — {}{reminder}",
"{enabled} {:<8} {:<8} {} — {}{reminder}{lock}",
routine.section,
routine.priority,
routine.title,
routine.visible_title(),
schedule_label(&routine.schedule)
))];
if let Some(notes) = routine.notes.as_deref().filter(|notes| !notes.is_empty()) {
if let Some(notes) = routine.visible_notes() {
lines.push(Line::styled(
format!(" {notes}"),
Style::default().fg(Color::DarkGray),
));
}
ListItem::new(lines)
})
.collect::<Vec<_>>(),
View::Archive => app
.archived_tasks
.iter()
.map(|task| {
let reminder = task
.reminder_time
.as_deref()
.map(|time| format!(" @{time}"))
.unwrap_or_default();
let source = task.routine_id.map(|_| " ↻").unwrap_or_default();
let lock = if task.decryption_failed { " 🔒" } else { "" };
let mut lines = vec![Line::from(format!(
"▣ {} {:<8} {:<8} {}{reminder}{source}{lock}",
task.scheduled_date,
task.section,
task.priority,
task.visible_title()
))];
if let Some(notes) = task.visible_notes() {
lines.push(Line::styled(
format!(" {notes}"),
Style::default().fg(Color::DarkGray),
@@ -103,6 +145,7 @@ pub fn render(frame: &mut Frame, app: &App) {
let title = match app.view {
View::Tasks => "Tasks for selected day",
View::Routines => "Daily, weekly, and monthly routines",
View::Archive => "Archived tasks",
};
let list = List::new(items)
.block(Block::default().borders(Borders::ALL).title(title))
@@ -117,6 +160,7 @@ pub fn render(frame: &mut Frame, app: &App) {
"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",
View::Archive => "q quit Tab tasks j/k move u restore x delete permanently r refresh",
};
let footer = Paragraph::new(vec![
Line::from(help),
@@ -162,6 +206,27 @@ pub fn render(frame: &mut Frame, app: &App) {
.block(Block::default().borders(Borders::ALL).title(title));
frame.render_widget(dialog, area);
}
if let Some(pending) = &app.pending_action {
let area = centered_rect(60, 7, frame.area());
frame.render_widget(Clear, area);
let (verb, title) = match pending.kind {
PendingActionKind::Archive => ("Archive", "Confirm archive"),
PendingActionKind::Delete => ("Permanently delete", "Confirm permanent deletion"),
};
let dialog = Paragraph::new(vec![
Line::from(format!("{verb} task “{}”?", pending.title)),
Line::from(""),
Line::styled(
"y: confirm • n/Esc: cancel",
Style::default().fg(Color::Yellow),
),
])
.alignment(Alignment::Center)
.wrap(Wrap { trim: true })
.block(Block::default().borders(Borders::ALL).title(title));
frame.render_widget(dialog, area);
}
}
fn centered_rect(width_percent: u16, height: u16, area: Rect) -> Rect {