mostr/src/task.rs

310 lines
9.6 KiB
Rust
Raw Normal View History

2024-07-30 17:13:29 +03:00
use fmt::Display;
use std::cmp::Ordering;
2024-07-24 16:03:34 +03:00
use std::collections::{BTreeSet, HashSet};
2024-07-19 21:06:03 +03:00
use std::fmt;
2024-08-09 20:53:30 +03:00
use std::string::ToString;
use colored::{ColoredString, Colorize};
2024-07-29 16:13:40 +03:00
use itertools::Either::{Left, Right};
use itertools::Itertools;
2024-07-29 21:06:23 +03:00
use log::{debug, error, info, trace, warn};
use nostr_sdk::{Event, EventId, Kind, Tag, TagStandard, Timestamp};
use crate::helpers::{format_timestamp_local, some_non_empty};
use crate::kinds::{is_hashtag, PROCEDURE_KIND, PROCEDURE_KIND_ID, TASK_KIND};
2024-07-24 16:03:34 +03:00
2024-08-09 20:53:30 +03:00
pub static MARKER_PARENT: &str = "parent";
pub static MARKER_DEPENDS: &str = "depends";
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Task {
/// Event that defines this task
pub(crate) event: Event,
/// Cached sorted tags of the event with references remove - do not modify!
2024-07-25 22:50:57 +03:00
pub(crate) tags: Option<BTreeSet<Tag>>,
2024-08-09 20:53:30 +03:00
/// Task references derived from the event tags
refs: Vec<(String, EventId)>,
/// Events belonging to this task, such as state updates and notes
pub(crate) props: BTreeSet<Event>,
}
impl PartialOrd<Self> for Task {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
self.event.partial_cmp(&other.event)
}
}
impl Ord for Task {
fn cmp(&self, other: &Self) -> Ordering {
self.event.cmp(&other.event)
}
}
impl Task {
pub(crate) fn new(event: Event) -> Task {
let (refs, tags) = event.tags.iter().partition_map(|tag| match tag.as_standardized() {
2024-08-25 14:46:07 +03:00
Some(TagStandard::Event { event_id, marker, .. }) =>
Left((marker.as_ref().map_or(MARKER_PARENT.to_string(), |m| m.to_string()), *event_id)),
2024-07-30 09:02:56 +03:00
_ => Right(tag.clone()),
2024-07-29 16:13:40 +03:00
});
// Separate refs for dependencies
Task {
2024-07-24 16:03:34 +03:00
props: Default::default(),
2024-07-29 16:13:40 +03:00
tags: Some(tags).filter(|t: &BTreeSet<Tag>| !t.is_empty()),
2024-08-09 20:53:30 +03:00
refs,
2024-07-25 22:40:35 +03:00
event,
}
}
pub(crate) fn get_id(&self) -> &EventId {
&self.event.id
}
pub(crate) fn find_refs<'a>(&'a self, marker: &'a str) -> impl Iterator<Item=&'a EventId> {
2024-08-09 20:53:30 +03:00
self.refs.iter().filter_map(move |(str, id)| Some(id).filter(|_| str == marker))
}
2024-08-01 14:07:40 +03:00
pub(crate) fn parent_id(&self) -> Option<&EventId> {
2024-08-09 20:53:30 +03:00
self.find_refs(MARKER_PARENT).next()
}
pub(crate) fn get_dependendees(&self) -> Vec<&EventId> {
self.find_refs(MARKER_DEPENDS).collect()
}
2024-08-29 22:15:30 +03:00
/// Trimmed event content or stringified id
pub(crate) fn get_title(&self) -> String {
some_non_empty(self.event.content.trim())
.unwrap_or_else(|| self.get_id().to_string())
}
pub(crate) fn get_filter_title(&self) -> String {
self.event.content.trim().trim_start_matches('#').to_string()
}
pub(crate) fn description_events(&self) -> impl Iterator<Item=&Event> + '_ {
2024-08-25 14:46:07 +03:00
self.props.iter().filter(|event| event.kind == Kind::TextNote)
}
2024-08-08 13:52:02 +03:00
pub(crate) fn descriptions(&self) -> impl Iterator<Item=&String> + '_ {
self.description_events().map(|e| &e.content)
}
pub(crate) fn is_task_kind(&self) -> bool {
self.event.kind == TASK_KIND
}
2024-08-18 22:24:14 +03:00
pub(crate) fn is_task(&self) -> bool {
self.is_task_kind() ||
2024-08-18 22:24:14 +03:00
self.states().next().is_some()
}
fn states(&self) -> impl DoubleEndedIterator<Item=TaskState> + '_ {
self.props.iter().filter_map(|event| {
2024-07-26 11:07:47 +03:00
event.kind.try_into().ok().map(|s| TaskState {
name: some_non_empty(&event.content),
2024-07-19 21:06:03 +03:00
state: s,
2024-08-25 14:46:07 +03:00
time: event.created_at,
2024-07-19 21:06:03 +03:00
})
})
}
pub(crate) fn last_state_update(&self) -> Timestamp {
self.state().map(|s| s.time).unwrap_or(self.event.created_at)
}
2024-07-26 11:07:47 +03:00
pub(crate) fn state(&self) -> Option<TaskState> {
let now = Timestamp::now();
// TODO do not iterate constructed state objects
let state = self.states().rev().take_while_inclusive(|ts| ts.time > now);
state.last().map(|ts| {
if ts.time <= now {
ts
} else {
self.default_state()
}
})
}
pub(crate) fn pure_state(&self) -> State {
self.state().map_or(State::Open, |s| s.state)
}
2024-08-01 14:07:40 +03:00
pub(crate) fn state_or_default(&self) -> TaskState {
self.state().unwrap_or_else(|| self.default_state())
}
/// Returns None for a stateless task.
pub(crate) fn state_label(&self) -> Option<ColoredString> {
self.state()
.or_else(|| Some(self.default_state()).filter(|_| self.is_task()))
.map(|state| state.get_colored_label())
}
fn default_state(&self) -> TaskState {
TaskState {
name: None,
state: State::Open,
time: self.event.created_at,
}
}
2024-07-29 16:13:40 +03:00
fn filter_tags<P>(&self, predicate: P) -> Option<String>
2024-07-30 09:02:56 +03:00
where
P: FnMut(&&Tag) -> bool,
{
self.tags.as_ref().map(|tags| {
2024-08-25 14:46:07 +03:00
tags.iter()
.filter(predicate)
2024-08-25 14:46:07 +03:00
.map(|t| t.content().unwrap().to_string())
.join(" ")
})
}
pub(crate) fn get(&self, property: &str) -> Option<String> {
match property {
// Static
"id" => Some(self.event.id.to_string()),
"parentid" => self.parent_id().map(|i| i.to_string()),
"name" => Some(self.event.content.clone()),
"pubkey" => Some(self.event.pubkey.to_string()),
"created" => Some(format_timestamp_local(&self.event.created_at)),
2024-08-20 13:49:53 +03:00
"kind" => Some(self.event.kind.to_string()),
// Dynamic
"status" => self.state_label().map(|c| c.to_string()),
2024-07-30 09:09:54 +03:00
"desc" => self.descriptions().last().cloned(),
"description" => Some(self.descriptions().join(" ")),
2024-08-02 14:31:00 +03:00
"hashtags" => self.filter_tags(|tag| { is_hashtag(tag) }),
2024-07-29 16:13:40 +03:00
"tags" => self.filter_tags(|_| true),
"alltags" => Some(format!("{:?}", self.tags)),
"refs" => Some(format!("{:?}", self.refs.iter().map(|re| format!("{}: {}", re.0, re.1)).collect_vec())),
2024-07-25 10:55:29 +03:00
"props" => Some(format!(
"{:?}",
self.props
.iter()
.map(|e| format!("{} kind {} \"{}\"", e.created_at, e.kind, e.content))
.collect_vec()
2024-07-25 10:55:29 +03:00
)),
2024-07-30 09:02:56 +03:00
"descriptions" => Some(format!(
"{:?}",
self.descriptions().collect_vec()
2024-07-30 09:02:56 +03:00
)),
_ => {
2024-07-29 21:06:23 +03:00
warn!("Unknown task property {}", property);
None
}
}
}
}
2024-07-26 11:07:47 +03:00
pub(crate) struct TaskState {
pub(crate) state: State,
2024-07-26 21:45:29 +03:00
name: Option<String>,
pub(crate) time: Timestamp,
}
2024-07-26 11:07:47 +03:00
impl TaskState {
pub(crate) fn get_label_for(state: &State, comment: &str) -> String {
some_non_empty(comment).unwrap_or_else(|| state.to_string())
}
2024-07-26 11:07:47 +03:00
pub(crate) fn get_label(&self) -> String {
self.name.clone().unwrap_or_else(|| self.state.to_string())
}
pub(crate) fn get_colored_label(&self) -> ColoredString {
self.state.colorize(&self.get_label())
}
pub(crate) fn matches_label(&self, label: &str) -> bool {
self.name.as_ref().is_some_and(|n| n.eq_ignore_ascii_case(label))
|| self.state.to_string().eq_ignore_ascii_case(label)
}
2024-07-26 11:07:47 +03:00
}
2024-07-30 17:13:29 +03:00
impl Display for TaskState {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2024-07-29 14:16:37 +03:00
let state_str = self.state.to_string();
write!(
f,
2024-07-29 14:16:37 +03:00
"{}",
self.name
.as_ref()
2024-07-29 14:16:37 +03:00
.map(|s| s.trim())
.filter(|s| !s.eq_ignore_ascii_case(&state_str))
.map_or(state_str, |s| format!("{}: {}", self.state, s))
)
}
}
#[derive(Debug, Copy, Clone, PartialEq, Ord, PartialOrd, Eq)]
pub(crate) enum State {
2024-08-18 21:37:39 +03:00
/// Actionable
Open = 1630,
/// Completed
Done,
2024-08-18 21:37:39 +03:00
/// Not Actionable (anymore)
2024-08-10 15:14:09 +03:00
Closed,
2024-08-18 21:37:39 +03:00
/// Temporarily not actionable
2024-08-10 15:14:09 +03:00
Pending,
2024-08-18 21:37:39 +03:00
/// Actionable ordered task list
Procedure = PROCEDURE_KIND_ID as isize,
}
impl TryFrom<&str> for State {
type Error = ();
fn try_from(value: &str) -> Result<Self, Self::Error> {
match value.to_ascii_lowercase().as_str() {
"closed" => Ok(State::Closed),
"done" => Ok(State::Done),
"pending" => Ok(State::Pending),
"proc" | "procedure" | "list" => Ok(State::Procedure),
"open" => Ok(State::Open),
_ => Err(()),
}
}
}
2024-07-26 11:07:47 +03:00
impl TryFrom<Kind> for State {
type Error = ();
fn try_from(value: Kind) -> Result<Self, Self::Error> {
match value {
Kind::GitStatusOpen => Ok(State::Open),
Kind::GitStatusApplied => Ok(State::Done),
Kind::GitStatusClosed => Ok(State::Closed),
Kind::GitStatusDraft => Ok(State::Pending),
_ => {
if value == PROCEDURE_KIND {
Ok(State::Procedure)
} else {
Err(())
}
}
2024-07-26 11:07:47 +03:00
}
}
}
impl State {
pub(crate) fn is_open(&self) -> bool {
2024-08-25 14:46:07 +03:00
matches!(self, State::Open | State::Pending | State::Procedure)
}
pub(crate) fn kind(self) -> u16 {
self as u16
}
pub(crate) fn colorize(&self, str: &str) -> ColoredString {
match self {
State::Open => str.green(),
State::Done => str.bright_black(),
State::Closed => str.magenta(),
State::Pending => str.yellow(),
State::Procedure => str.blue(),
}
}
}
2024-07-30 20:25:27 +03:00
impl From<State> for Kind {
fn from(value: State) -> Self {
Kind::from(value.kind())
}
}
2024-07-30 17:13:29 +03:00
impl Display for State {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(self, f)
}
}