Compare commits

...

195 Commits

Author SHA1 Message Date
xeruf 49d8eef29c fix(tasks): wrong position for immediate task entering 2024-10-15 15:42:17 +02:00
xeruf 74fff5a2b1 fix(main): only parse single-digit view depths 2024-10-15 03:28:40 +02:00
xeruf bdb8b6e814 fix(main): show correct relay url on relay change 2024-10-15 03:02:46 +02:00
xeruf b0c92e64fa feat(tasks): expand Bookmarks display to Quick Access
Now also including recently created tasks
2024-10-15 03:01:57 +02:00
xeruf 4e4ad7099f fix(tasks): do not find children of closed tasks globally 2024-10-15 03:00:12 +02:00
xeruf 613a8b3822 feat(tasks): display bookmarks and time summary 2024-10-14 16:44:35 +02:00
xeruf 1533676bff fix: do not show all tasks when filter has no matches 2024-10-14 16:39:44 +02:00
xeruf 52be8c53eb feat: revamp task printing through recursive sorting
Still to be fixed: Bookmarks, Time Summary
2024-10-14 16:10:56 +02:00
xeruf 5f25e116a1 feat: allow filtering tasks by author name 2024-10-13 17:15:43 +02:00
xeruf d1720f89ae fix(tasks): do not show progress for activities 2024-10-13 16:01:55 +02:00
xeruf f6082f12f2 fix(tasks): prevent crashes at zero depth 2024-10-12 21:55:32 +02:00
xeruf 3d389e8d52 feat: toggleable activity recursion 2024-10-12 14:17:46 +02:00
xeruf 28d1f4c983 fix(tasks): properly set search depth 2024-10-12 11:54:29 +02:00
xeruf 93fde86169 test(tasks): adjust view and search depth 2024-10-12 11:35:43 +02:00
xeruf 769b9578fe refactor: do not import xdg 2024-10-12 11:34:44 +02:00
xeruf c27ccb8282 refactor: rename stateless tasks to activities 2024-10-11 22:06:18 +02:00
xeruf d744fb8457 feat: separate search and view depth 2024-10-11 01:10:17 +02:00
xeruf c2f775e891 docs(tasks): expand documentation a bit 2024-10-03 13:39:52 +02:00
xeruf 617b1ea6d1 fix(tasks): do not show children of non-matching states 2024-10-03 13:29:41 +02:00
xeruf fd970b3709 fix(tasks): match task names at word boundary with regex 2024-10-01 23:20:08 +02:00
xeruf c6de8daee9 fix(main): increase notification channel size
apparently it needs to be double of the expected events,
so even this is only a temporary remedy
2024-10-01 23:19:01 +02:00
xeruf a297f61363 feat(tasks): report reprocessing issues 2024-09-23 13:59:29 +02:00
xeruf 96ca945263 feat: allow viewing tracking history for user 2024-09-23 13:51:16 +02:00
xeruf d4bca1c26f feat: deferred state updates 2024-09-23 08:50:12 +02:00
xeruf 516acadd4a fix: properly determine current task state 2024-09-23 01:20:24 +02:00
xeruf 945eb6906a feat: add ability to schedule any action 2024-09-22 20:05:05 +02:00
xeruf 34657540de refactor: remove Tasks to TasksRelay 2024-09-22 16:48:15 +02:00
xeruf afe3fa8670 fix: remove cached task children list 2024-09-22 16:47:26 +02:00
xeruf 753afad2fd fix: obtain children on the fly 2024-09-22 16:24:07 +02:00
xeruf 7755967a7a feat: requeue events with missing references 2024-09-22 14:44:20 +02:00
xeruf cb75a5749f style(tasks): some bits of documentation 2024-09-14 16:17:30 +03:00
xeruf 0744e86922 feat: properly include tasks with hashtags in filters 2024-09-14 16:13:41 +03:00
xeruf ddb68f7107 feat: recognize hashtags in task name 2024-09-14 15:53:27 +03:00
xeruf 4b59b273f5 feat(tasks): extend search depth by tags if appropriate 2024-09-07 16:26:55 +03:00
xeruf bb3bb1fd56 feat: better feedback on bookmarking 2024-09-07 16:25:44 +03:00
xeruf 593ebcddca feat(main): make empty / go to root 2024-09-07 16:06:59 +03:00
xeruf 132ea048a5 feat: greatly revamp filtering 2024-09-07 16:06:28 +03:00
xeruf ddc57dc36a fix(tasks): do not panic on missing children 2024-09-05 13:56:48 +03:00
xeruf 77bfc4cb7a fix: add weekday to relative date formatting 2024-09-05 13:50:50 +03:00
xeruf 43e7a5cd10 fix(tasks): prevent infinite loop on higher depth in ChildIterator 2024-09-03 21:15:48 +03:00
xeruf 3942105764 fix(tasks): do not show bookmarks on childrenless tasks 2024-08-29 23:28:52 +03:00
xeruf 945e29b5ed feat: enable setting persistent bookmarks 2024-08-29 23:20:31 +03:00
xeruf 1297be43bc feat(tasks): include bookmarked tasks regardless of position 2024-08-29 22:59:31 +03:00
xeruf 5a62e8f99e feat(tasks): parse own bookmarks from event 2024-08-29 22:28:25 +03:00
xeruf 018357b21e refactor(tasks): accurately rename referenced_events to singular 2024-08-29 22:17:46 +03:00
xeruf d1ae0f5458 docs(readme): enhance command documentation 2024-08-29 22:15:59 +03:00
xeruf d4f544173a style: slight reformatting 2024-08-29 22:15:30 +03:00
xeruf c2b106ea69 refactor: use static Kinds rather than their ids 2024-08-29 22:14:26 +03:00
xeruf 003d1d6120 feat: prefer immediate children search results 2024-08-29 12:11:43 +03:00
xeruf 039c390c66 fix(tasks): re-filter when reducing view depth 2024-08-29 12:02:13 +03:00
xeruf b974957bc9 fix: do not set view depth when searching 2024-08-29 11:54:53 +03:00
xeruf dd5aaf71d2 feat: enable moving back through history with & 2024-08-29 11:50:34 +03:00
xeruf c5a2872534 feat: enable setting specific state with label 2024-08-29 11:06:56 +03:00
xeruf 1a1f23007b feat: filter tasks by state change time 2024-08-28 21:56:15 +03:00
xeruf 9eaf10006b fix(tasks): avoid timestamp conflicts 2024-08-28 09:16:38 +03:00
xeruf 6492a22cc9 fix: dim path separators 2024-08-28 09:16:38 +03:00
xeruf 13dac88ded fix: more consistent time-tracking history 2024-08-28 09:16:35 +03:00
xeruf 1263e39fb3 fix: parse date without numbers as day start 2024-08-27 12:02:45 +03:00
xeruf 714d4a4d5b fix(tasks): only enter a perfect global match that is not closed 2024-08-27 12:02:45 +03:00
xeruf 1d7d3eea74 feat(main): automatic readline history 2024-08-27 12:02:45 +03:00
xeruf 3cab294122 feat(tasks): prevent accidental redundant time-tracking 2024-08-27 12:02:45 +03:00
xeruf 01305c5a78 feat: more adaptive tag filtering
Make tag exclusions more persistent
2024-08-27 12:02:45 +03:00
xeruf 14a1cbe09c refactor: code cleanup with clippy 2024-08-27 12:02:45 +03:00
xeruf 533378b24d feat(tasks): allow jumping to task anywhere by exact name match 2024-08-27 12:02:40 +03:00
xeruf a0f5d62c81 fix: more intuitive feedback when stopping timetracking 2024-08-25 14:28:23 +03:00
xeruf 84e46827ce fix(tasks): temporary improved author formatting 2024-08-25 11:17:55 +03:00
xeruf 3c93e0aae7 feat: character threshold for creating notes 2024-08-25 11:17:26 +03:00
xeruf c3d18e4494 fix(tasks): properly determine last tracking of current task 2024-08-25 10:50:24 +03:00
xeruf 75a5f27843 feat(main): allow creating multiple task at once with newlines 2024-08-24 21:01:07 +03:00
xeruf 58126ba6e7 feat(main): migrate to current rustyline version 2024-08-24 20:57:07 +03:00
xeruf 9f14a0f3f9 feat: parse plain hour when adjusting tracking 2024-08-22 11:13:35 +03:00
xeruf f240413e2a style: various small cleanups 2024-08-21 12:31:29 +03:00
xeruf 999068bdd9 fix(main): pass own username to Tasks object 2024-08-21 12:30:13 +03:00
xeruf f7f4bdc4f3 refactor(main): merge local_tasks into relays map 2024-08-21 12:22:47 +03:00
xeruf ed1f482707 feat: revamp timestamp formatting helpers 2024-08-21 11:57:28 +03:00
xeruf 3dca6a4b23 fix(main): safer key persistence 2024-08-21 11:52:07 +03:00
xeruf 17b3334aea fix: prompt via readline 2024-08-21 11:05:43 +03:00
xeruf 77ba311bab feat(main): neatly interpret plain hour in date filter 2024-08-21 10:14:01 +03:00
xeruf 9da41db427 feat(main): implement readline functionality with rustylinez
Including background log output
2024-08-20 22:40:16 +03:00
xeruf a67bd384ec fix(tasks): creation position in filter_or_create 2024-08-20 21:42:05 +03:00
xeruf ace365de38 fix(main): enhance Result warnings macro with string interpolation 2024-08-20 21:16:01 +03:00
xeruf 07bba314ec fix(main): print Result warnings via macro 2024-08-20 20:41:41 +03:00
xeruf 126bd8cf81 fix: move from std::sync fully to tokio
Fixes Relay adding

Closes https://github.com/rust-nostr/nostr/issues/533
2024-08-20 14:29:09 +03:00
xeruf b5b2ea9b71 fix(main): client communication ordering 2024-08-20 14:18:37 +03:00
xeruf f98486f012 docs: small updates 2024-08-20 13:51:23 +03:00
xeruf ada3492487 feat: upgrade to nostr sdk 0.34 2024-08-20 13:00:36 +03:00
xeruf efc0061390 feat(main): rudimentary filter by date or author 2024-08-19 22:16:19 +03:00
xeruf 1b0f7dca09 fix(main): more intuitive behavior when stopping tracking with stamp 2024-08-19 21:55:44 +03:00
xeruf f4cff3d702 feat: use author name consistently 2024-08-19 21:41:45 +03:00
xeruf f8a4777f71 feat(kinds): more accurate tag formatting 2024-08-19 21:25:59 +03:00
xeruf 0296556bcd fix(main): fetch task kinds before updates 2024-08-19 21:25:20 +03:00
xeruf c64a1fa051 feat(tasks): add task author to default columns 2024-08-19 21:21:31 +03:00
xeruf 721c200b97 fix(tasks): hide duplicates again in personal time-tracking history 2024-08-19 17:35:26 +03:00
xeruf 3b9fedd9a3 feat(tasks): display details on task without subtasks 2024-08-19 17:30:05 +03:00
xeruf 12b7c909ab feat(tasks): track depth in ChildIterator 2024-08-19 16:52:19 +03:00
xeruf 5bc3509930 refactor: provide position ref and cloned 2024-08-19 16:36:06 +03:00
xeruf 629db66018 fix(tasks): properly find current position when futures are involved 2024-08-19 13:59:37 +03:00
xeruf e0d241ec5a fix(tasks): undo tracking with history-based position 2024-08-19 13:56:28 +03:00
xeruf 506a73060a fix(tasks): properly process movement with history-based position 2024-08-19 13:47:27 +03:00
xeruf ebfe632497 feat(tasks): derive position from history 2024-08-19 13:06:20 +03:00
xeruf a4f9398846 fix: simplify tracking functions
Pruning the local history is not worth it.
2024-08-19 11:45:12 +03:00
xeruf 416a7f195d feat: format visible time tracking history 2024-08-19 11:27:12 +03:00
xeruf f8375cf879 refactor(task): state kind numbers as enum values 2024-08-18 22:47:19 +03:00
xeruf 8bf305d4d4 fix: only show default state for proper tasks 2024-08-18 22:43:14 +03:00
xeruf eaeeebca7b feat: add notes as stateless tasks 2024-08-18 22:37:02 +03:00
xeruf 2255abc1b8 docs: unify property columns documentation 2024-08-18 21:54:48 +03:00
xeruf 19d0fbb8fc feat(task): expose remaining relevant event properties 2024-08-18 21:38:20 +03:00
xeruf 903536bd3b docs: some helpful comments 2024-08-18 21:37:39 +03:00
xeruf 86654c8348 feat: show named task authors 2024-08-18 21:33:32 +03:00
xeruf d88cae4273 feat(main): enable filtering by author 2024-08-16 21:58:38 +03:00
xeruf 9ad1243078 fix(main): better messages for background thread operations 2024-08-16 17:46:04 +03:00
xeruf 2fac3fd8f8 refactor(tasks): resolve recursive tasks without intermediate collections 2024-08-16 09:45:35 +03:00
xeruf 34540370c3 refactor(main): small cleanups 2024-08-15 15:50:58 +03:00
xeruf 43278a6631 feat(tasks): interpret plain numbers as minutes and strip prefixes 2024-08-15 13:22:16 +03:00
xeruf 9c0a688297 fix(tasks): prevent tracking invalid times 2024-08-15 13:12:42 +03:00
xeruf fcd5e9c0c9 feat(tasks): employ time parsing libraries for tracking offsets 2024-08-15 12:21:32 +03:00
xeruf 3e056eb2b6 feat: feedback when filter does not match 2024-08-15 10:33:52 +03:00
xeruf 930c6b9c38 fix: improve task filtering, especially with slash
- smart case
- substring match
- less movement needed
2024-08-15 10:33:06 +03:00
xeruf c93b2f2d91 feat(main): enhance prompt formatting 2024-08-15 09:31:49 +03:00
xeruf 0253b00c61 feat(tasks): display tracking since for current task 2024-08-14 22:12:43 +03:00
xeruf 957422f767 feat: localize nostr Timestamps consistently 2024-08-14 21:49:36 +03:00
xeruf 3eefbad6d5 feat: allow setting multiple tag filters at once 2024-08-14 19:42:58 +03:00
xeruf b544616801 test(tasks): small rearrangements 2024-08-14 16:00:03 +03:00
xeruf 1e0cc319b8 docs: expand Readme and adjust code comments 2024-08-14 15:59:43 +03:00
xeruf 8588fb9a04 refactor(main): improved debug output 2024-08-14 15:57:05 +03:00
xeruf bbfbb2d8b0 fix(main): better feedback on url parse error 2024-08-14 15:40:15 +03:00
xeruf f5aca3eca8 fix(main): better feedback after adjusting timetracking 2024-08-14 15:36:54 +03:00
xeruf be582cb536 fix(main): revamp prompt formatting 2024-08-14 15:33:50 +03:00
xeruf 68d5c101e9 feat(main): enable switching to new relay while running 2024-08-14 15:32:42 +03:00
xeruf 45b8f9cf0f feat(main): define MostrMessage type for inter-thread channel 2024-08-13 21:40:23 +03:00
xeruf ae4d315d87 fix: small sorting adjustment 2024-08-13 21:40:01 +03:00
xeruf 66af6af0ab fix(main): do not superfluously move in place 2024-08-13 21:40:01 +03:00
xeruf a059ff1c3e refactor(main): define timeout delays as constants 2024-08-13 21:39:47 +03:00
xeruf 6cb2d47a8d feat(main): advanced logger instantiation 2024-08-13 21:27:26 +03:00
xeruf 6d4666c12d feat(tasks): improve visible tasks summary 2024-08-13 11:59:57 +03:00
xeruf c67ef3b119 feat(main): batch up messages for relays 2024-08-13 11:54:14 +03:00
xeruf 619bcfbbad feat(tasks): generate tree from iterator 2024-08-12 23:08:06 +03:00
xeruf 85b923edc8 feat: enable creating dependent sibling task 2024-08-12 23:06:49 +03:00
xeruf 9f84fd7ef1 refactor(tasks): find task tree as references 2024-08-12 12:17:03 +03:00
xeruf 67a19d61f2 feat(tasks): implement fallback for finding task children 2024-08-12 12:09:46 +03:00
xeruf 8f3552aeba feat: move up after setting state manually 2024-08-12 11:57:21 +03:00
xeruf b3d70ab0b7 feat(tasks): enable excluding tags from view 2024-08-11 12:28:08 +03:00
xeruf c83d8a2f55 feat(tasks): option to fully set sorting 2024-08-11 12:05:29 +03:00
xeruf a7d02e60b2 feat(tasks): make sorting by property customizable 2024-08-11 10:58:34 +03:00
xeruf 55792ca34f feat(tasks): sorting by property 2024-08-11 10:01:46 +03:00
xeruf dda969e08b feat: integrate progress and dependencies into state property 2024-08-10 21:27:47 +03:00
xeruf dcf333353b fix(tasks): ignore future stamps in time-tracking summation 2024-08-10 21:27:47 +03:00
xeruf 15bd21059d fix: show currently running timetracking for task 2024-08-10 21:27:47 +03:00
xeruf 9fbe3e27cb feat: implement task stopping shortcut 2024-08-10 21:27:41 +03:00
xeruf 06bfe8e18a fix(task): properly parse str into State 2024-08-10 18:16:29 +03:00
xeruf b74ac18e39 style: reformat and remove leftover debug print 2024-08-10 18:14:19 +03:00
xeruf ae2172c8f2 feat(main): properly apply input trimming 2024-08-10 18:11:42 +03:00
xeruf b03ad00b6a feat: quick filter for all task states 2024-08-10 15:44:52 +03:00
xeruf ff74ac216b feat(task): colorize state property 2024-08-10 15:14:09 +03:00
xeruf c48355e5da feat(task): parse dependees 2024-08-09 20:53:30 +03:00
xeruf 7a8a048d6c feat: add procedures for dependency lists 2024-08-08 21:10:17 +03:00
xeruf c492d64d9e style: align command match branches 2024-08-08 18:16:25 +03:00
xeruf b62ec6fd39 feat: summarize time tracked on visible tasks 2024-08-08 15:14:04 +03:00
xeruf 43c62bf742 feat: list existing tracked times 2024-08-08 15:09:39 +03:00
xeruf 79b42b8df0 style: reformat code 2024-08-08 13:52:02 +03:00
xeruf a3a732879f feat(tasks): don't create tasks from typos 2024-08-08 13:04:52 +03:00
xeruf 6b7b6b91a8 feat: hashtag list and quick filter override 2024-08-08 13:04:22 +03:00
xeruf 08b0ba48a3 feat: properly handle commands without argument 2024-08-08 00:18:34 +03:00
xeruf 4180533844 fix(tasks): apply state to new tasks 2024-08-07 23:59:05 +03:00
xeruf fca9b1492b fix(tasks): recursive time tracked format string 2024-08-07 15:04:57 +03:00
xeruf 50ac994d21 docs: slight additions to readme and code comments 2024-08-07 15:04:18 +03:00
xeruf 65207a1de2 feat: allow switching between initial relays 2024-08-07 15:03:29 +03:00
xeruf 6932e1f257 feat: hide Tasks attributes for feedback logs and make column interaction 1-indexed 2024-08-07 00:06:09 +03:00
xeruf b66089fc94 refactor: create helpers file 2024-08-06 23:01:59 +03:00
xeruf f4f1b56f02 feat: info feedback on what you are doing 2024-08-06 22:54:22 +03:00
xeruf b5b57b7ac9 fix: flush after backtrack 2024-08-06 17:57:01 +03:00
xeruf db4f9ee8cb fix(tasks): test time-tracking including automatic back-tracking 2024-08-06 17:52:31 +03:00
xeruf d950c13098 feat: migrate to nostr-sdk 0.33 2024-08-06 11:34:18 +03:00
xeruf a2505e94fb feat: allow timetracking with date specifier 2024-08-02 20:40:42 +03:00
xeruf 8c2c279238 refactor: put kinds and helpers in own module 2024-08-02 14:44:47 +03:00
xeruf aa468f80c5 test(tasks): separate test cases 2024-08-02 14:31:28 +03:00
xeruf 55d856c75d feat: info message on task creation 2024-08-02 14:31:00 +03:00
xeruf e16e21a477 feat(main): collapse more time tracking events through soft flushing 2024-08-02 14:30:06 +03:00
xeruf 9619435c03 fix(tasks): time display format replacements 2024-08-02 11:13:36 +03:00
xeruf bf802e3195 feat: filter with slash 2024-08-01 21:40:15 +03:00
xeruf 03f9e60c6f feat: activate perfect match and filter without dot 2024-08-01 21:11:33 +03:00
xeruf 5b05c53947 fix: task progress percentage 2024-08-01 20:40:55 +03:00
xeruf 7f34a888f3 feat: make tags sticky and allow manual removal 2024-08-01 20:12:04 +03:00
xeruf 256c86e06f fix: move text notes to comma key 2024-08-01 20:04:56 +03:00
xeruf a9509fd4f2 feat: fold repeated time tracking events 2024-08-01 20:00:45 +03:00
xeruf 36fe58d3f3 fix(tasks): time tracking within current session 2024-08-01 19:48:05 +03:00
xeruf 14dcc8f0ff fix(tasks): comment persistence 2024-08-01 19:18:46 +03:00
xeruf 486cbb1ab4 feat: undo function with @ 2024-08-01 19:10:58 +03:00
xeruf afd6f2f77a style: reformat 2024-07-31 20:08:33 +03:00
xeruf 03263840ac fix(tasks): no decimal point for progress percentage 2024-07-31 20:07:20 +03:00
xeruf 5c7793f4a3 feat: revamp time tracking with own kind 2024-07-31 20:07:16 +03:00
xeruf 484c05dbee release: 0.3.0 2024-07-31 16:34:23 +03:00
xeruf e5953c63b4 fix: list properties instead of adding blank column 2024-07-30 21:21:16 +03:00
xeruf 74464241ec docs: explain implemented and planned concepts 2024-07-30 21:18:11 +03:00
xeruf 3652f0d39f refactor: state-kind conversion 2024-07-30 20:25:27 +03:00
9 changed files with 3863 additions and 1149 deletions

3
.gitignore vendored
View File

@ -1,6 +1,7 @@
/target /target
/examples
/.idea
relays relays
keys keys
*.html *.html
/src/bin

1162
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -5,19 +5,27 @@ repository = "https://forge.ftt.gmbh/janek/mostr"
readme = "README.md" readme = "README.md"
license = "GPL 3.0" license = "GPL 3.0"
authors = ["melonion"] authors = ["melonion"]
version = "0.2.0" version = "0.5.0"
edition = "2021" edition = "2021"
default-run = "mostr" default-run = "mostr"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies] [dependencies]
xdg = "2.5.2" xdg = "2.5"
itertools = "0.12.1" itertools = "0.12"
log = "0.4.21" log = "0.4"
chrono = "0.4.38" chrono = "0.4"
colog = "1.3.0" env_logger = "0.11"
colored = "2.1.0" colog = "1.3"
nostr-sdk = "0.30" colored = "2.1"
tokio = { version = "1.0.0", features = ["rt", "rt-multi-thread", "macros"] } parse_datetime = "0.5.0"
once_cell = "1.19.0" interim = { version = "0.1", features = ["chrono"] }
nostr-sdk = "0.34" # { git = "https://github.com/rust-nostr/nostr" }
tokio = { version = "1.40", features = ["rt", "rt-multi-thread", "macros"] }
regex = "1.10.6"
rustyline = { git = "https://github.com/xeruf/rustyline", rev = "465b14d" }
[dev-dependencies]
chrono-english = "0.1"
linefeed = "0.6"

278
README.md
View File

@ -1,6 +1,6 @@
# mostr # mostr
A nested task chat, powered by nostr! An immutable nested collaborative task manager, powered by nostr!
## Quickstart ## Quickstart
@ -12,20 +12,79 @@ Run development build with:
cargo run cargo run
Creating a test task: A `relay` list and private `key` can be placed in config files
`nostril --envelope --content "test task" --kind 1621 | websocat ws://localhost:4736` under `${XDG_CONFIG_HOME:-$HOME/.config}/mostr/`.
Currently, all relays are fetched and synced to,
separation is planned -
ideally for any project with different collaborators,
an own relay will be used.
If not saved, mostr will ask for a relay url
(entering none is fine too, but your data will not be persisted between sessions)
and a private key, alternatively generating one on the fly.
Both are currently saved in plain text to the above files.
Install latest build: Install latest build:
cargo install --path . --offline cargo install --path .
## Principles Creating a test task externally:
`nostril --envelope --content "test task" --kind 1621 | websocat ws://localhost:4736`
- active task is tracked automatically To exit the application, press `Ctrl-D`.
- progress through subdivision rather than guessing
- TBI: show/hide closed/done tasks
Recommendation: Flat hierarchy, using tags for filtering (TBI) ## Basic Usage
### Navigation and Nesting
Create tasks and navigate using the shortcuts below.
Whichever task is active (selected)
will be the parent task for newly created tasks
and automatically has time-tracking running.
To track task progress,
simply subdivide the task -
checking off tasks will automatically update the progress
for all parent tasks.
Generally a flat hierarchy is recommended
with tags for filtering,
since hierarchies cannot be changed.
Filtering by a tag is just as easy
as activating a task and more flexible.
Using subtasks has two main advantages:
- ability to accumulate time tracked
- swiftly navigate between related tasks
Managing a project with subtasks makes it continuously visible,
which is helpful if you want to be able to track time on the project itself
without a specific task,
Thus subtasks can be very useful for specific contexts,
for example a project or a specific place.
On the other hand, related tasks like chores
should be grouped with a tag instead.
Similarly for projects which are only sporadically worked on
when a specific task comes up, so they do not clutter the list.
### Collaboration
Since everything in mostr is inherently immutable,
live collaboration is easily possible.
After every command,
mostr checks if new updates arrived from the relay
and updates its display accordingly.
If a relay has a lot of events,
initial population of data can take a bit -
but you can already start creating events without issues,
updates will be fetched in the background.
For that reason,
it is recommended to leave mostr running
as you work.
### Time-Tracking
The currently active task is automatically time-tracked.
To stop time-tracking completely, simply move to the root of all tasks.
## Reference ## Reference
@ -34,62 +93,177 @@ Recommendation: Flat hierarchy, using tags for filtering (TBI)
`TASK` creation syntax: `NAME: TAG1 TAG2 ...` `TASK` creation syntax: `NAME: TAG1 TAG2 ...`
- `TASK` - create task - `TASK` - create task
- `.` - clear filters and reload + prefix with space if you want a task to start with a command character
+ copy in text with newlines to create one task per line
- `.` - clear all filters
- `.TASK` - `.TASK`
+ select task by id + activate task by id
+ match by task name prefix: if one or more tasks match, filter / activate (tries case-sensitive then case-insensitive) + match by task name prefix: if one or more tasks match, filter / activate (tries case-sensitive then case-insensitive)
+ no match: create & activate task + no match: create & activate task
- `.2` - set view depth to `2`, which can be substituted for any number (how many subtask levels to show, default 1) - `.2` - set view depth to the given number (how many subtask levels to show, default is 1)
- `/[TEXT]` - activate task or filter by smart-case substring match (empty: move to root)
- `||TASK` - create and activate a new task procedure (where subtasks automatically depend on the previously created task)
- `|[TASK]` - (un)mark current task as procedure or create a sibling task depending on the current one and move up
Dots can be repeated to move to parent tasks Dot or slash can be repeated to move to parent tasks before acting.
Append `@TIME` to any task creation or change command to record the action with the given time.
- `:[IND][COL]` - add / remove property column COL to IND or end - `:[IND][PROP]` - add property column PROP at IND or end,
- `>[TEXT]` - Complete active task and move to parent, with optional state description if it already exists remove property column PROP or IND; empty: list properties
- `<[TEXT]` - Close active task and move to parent, with optional state description - `::[PROP]` - sort by property PROP (multiple space-separated values allowed)
- `|TEXT` - Set state for current task from text (also aliased to `/` for now) - `([TIME]` - list tracked times or insert timetracking with the specified offset (double to view all history)
- `-TEXT` - add text note (comment / description) such as `-1d`, `-15 minutes`, `yesterday 17:20`, `in 2 fortnights`
- `)[TIME]` - stop timetracking with optional offset - also convenience helper to move to root
- `>[TEXT]` - complete active task and move up, with optional status description
- `<[TEXT]` - close active task and move up, with optional status description
- `!TEXT` - set status for current task from text and move up; empty: Open
- `!TIME: REASON` - defer current task to date
- TBI: `*[INT]` - set priority - can also be used in task creation, with any digit
- `,[TEXT]` - list notes or add text note (stateless task / task description)
- TBI: `;[TEXT]` - list comments or comment on task
- TBI: show status history and creation with attribution
- `&` - revert
- with string argument, find first matching task in history
- with int argument, jump back X tasks in history
- undo last action (moving in place or upwards confirms pending actions)
- `wss://...` - switch or subscribe to relay (prefix with space to forcibly add a new one)
Property Filters: Property Filters:
- `#TAG` - filter by tag - `#TAG1 TAG2` - set tag filter
- `?STATE` - filter by state (type or description) - plain `?` to reset - `+TAG` - add tag filter (empty: list all used tags)
- `-TAG` - remove tag filters (by prefix)
- `?STATUS` - filter by status (type or description) - plain `?` to reset, `??` to show all
- `@[AUTHOR|TIME]` - filter by time or author (pubkey, or `@` for self, TBI: id prefix, name prefix)
- TBI: `**INT` - filter by priority
State descriptions can be used for example for Kanban columns. Status descriptions can be used for example for Kanban columns or review flows.
An active tag or state filter will also set that attribute for newly created tasks. An active tag or status filter will also set that attribute for newly created tasks.
### Available Columns ### Notes
- `id` - TBI = To Be Implemented
- `parentid` - `. TASK` - create and enter a new task even if the name matches an existing one
- `name`
- `state`
- `hashtags`
- `tags` - values of all nostr tags associated with the event, except event tags
- `desc` - last note on the task
- `description` - accumulated notes on the task
- `path` - name including parent tasks
- `rpath` - name including parent tasks up to active task
- `time` - time tracked on this task
- `rtime` - time tracked on this tasks and all recursive subtasks
- `progress` - recursive subtask completion in percent
- `subtasks` - how many direct subtasks are complete
For debugging: `props`, `alltags`, `descriptions` ## Nostr reference
TBI: Combined formatting and recursion specifiers - Mostr mainly uses the following NIPs:
for example progress count/percentage and recursive or not.
Subtask progress immediate/all/leafs. - Kind 1 for task descriptions and permanent tasks, can contain task property updates (tags, priority)
- Issue Tracking: https://github.com/nostr-protocol/nips/blob/master/34.md
+ Tasks have Kind 1621 (originally: git issue - currently no markdown support implemented)
+ TBI: Kind 1622 for task comments
+ Kind 1630-1633: Task Status (1630 Open, 1631 Done, 1632 Closed, 1633 Pending)
- Own Kind 1650 for time-tracking
Considering to use Calendar: https://github.com/nostr-protocol/nips/blob/master/52.md
- Kind 31922 for GANTT, since it has only Date
- Kind 31923 for Calendar, since it has a time
## Plans ## Plans
- Relay Selection, fetch most recent tasks first - Handle event sending rejections (e.g. permissions)
- parse Hashtag tags from task name - Local Database Cache, Negentropy Reconciliation
- Personal time tracking -> Offline Use!
- Unified Filter object - Remove status filter when moving up?
-> include sub - Task markdown support? - colored
- Time tracking: Active not as task state, ability to postpone task and add planned timestamps (calendar entry) - Calendar Events - make future time-tracking editable -> parametrised replaceable events
- TUI - Clear terminal? - Speedup: Offline caching & Expiry (no need to fetch potential years of history)
- Expiry (no need to fetch potential years of history) + Fetch most recent tasks first
- Offline caching + Relay: compress tracked time for old tasks, filter closed tasks
- Web Interface, Messenger integrations + Relay: filter out task status updates within few seconds, also on client side
- Relay: filter out task state updates within few seconds, also on client side
### Commands
- Open Command characters: `_^\=$%~'"`, `{}[]`
- Remove colon from task creation syntax
### Conceptual
The following features are not ready to be implemented
because they need conceptualization.
Suggestions welcome!
- Queueing tasks
- Allow adding new parent via description?
- Special commands: help, exit, tutorial, change log level
- Duplicate task (subtasks? timetracking?)
- What if I want to postpone a procedure, i.e. make it pending, or move it across kanban, does this make sense?
- Dependencies (change from tags to properties so they can be added later? or maybe as a status?)
- Templates
- Ownership
- Combined formatting and recursion specifiers
+ progress count/percentage and recursive or not
+ Subtask progress immediate/all/leafs
+ path full / leaf / top
### Interfaces
- TUI: Clear Terminal? Refresh on empty prompt after timeout?
- Kanban, GANTT, Calendar
- Web Interface
- Messenger Integrations (Telegram Bot)
- n8n node
- Caldav Feed: Scheduled (planning) / Tracked (events, timetracking) with args for how far back/forward
## Exemplary Workflows - User Stories
- Freelancer
- Family Chore Management
- Inter-Disciplinary Project Team -> Company with multiple projects and multiple relays
+ Permissions via status or assignment (reassignment?)
+ Tasks can be blocked while having a status (e.g. kanban column)
+ A meeting can be worked on (tracked) before it starts
+ Schedule for multiple people
- Tracking Daily Routines / Habits
### Freelancer
For a Freelancer, mostr can help structure work times
across different projects
because it can connect to multiple clients,
using their mental state effectively (Mind Management not Time Management).
It also enables transparency for clients
by sharing the tracked time -
but alternatively the freelancer
can track times on their own auxiliary relay
without problems.
### Family
With a mobile client implemented,
mostr can track shopping lists and other chores for a family,
and provide them context-dependently -
allowing you to batch shopping and activities without mental effort.
### Project Team
sharing, assigning, stand-ups, communication
### Contexts
A context is a custom set of filters such as status, tags, assignee
so that the visible tasks are always relevant
and newly created tasks are less of a hassle to type out
since they will automatically take on that context.
By automating these contexts based on triggers, scripts or time,
relevant tasks can be surfaced automatically.
#### Example
In the morning, your groggy brain is good at divergent thinking,
and you like to do sports in the morning.
So for that time, mostr can show you tasks tagged for divergent thinking,
since you are easily distracted filter out those that require the internet,
as well as anything sportsy.
After you come back from sports and had breakfast,
for example detected through a period of inactivity on your device,
you are ready for work, so the different work projects are shown and you delve into one.
After 90 minutes you reach a natural low in your focus,
so mostr surfaces break activities -
such as a short walk, a small workout, some instrument practice
or simply grabbing a snack and drink.
After lunch you like to take an extended afternoon break,
so your call list pops up -
you can give a few people a call as you make a market run,
before going for siesta.

152
src/helpers.rs Normal file
View File

@ -0,0 +1,152 @@
use std::ops::Sub;
use chrono::LocalResult::Single;
use chrono::{DateTime, Local, NaiveTime, TimeDelta, TimeZone, Utc};
use log::{debug, error, info, trace, warn};
use nostr_sdk::Timestamp;
pub const CHARACTER_THRESHOLD: usize = 3;
pub fn some_non_empty(str: &str) -> Option<String> {
if str.is_empty() { None } else { Some(str.to_string()) }
}
pub fn trim_start_count(str: &str, char: char) -> (&str, usize) {
let len = str.len();
let result = str.trim_start_matches(char);
let dots = len - result.len();
(result, dots)
}
pub trait ToTimestamp {
fn to_timestamp(&self) -> Timestamp;
}
impl<T: TimeZone> ToTimestamp for DateTime<T> {
fn to_timestamp(&self) -> Timestamp {
let stamp = self.to_utc().timestamp();
if let Some(t) = 0u64.checked_add_signed(stamp) {
Timestamp::from(t)
} else { Timestamp::zero() }
}
}
/// Parses the hour from a plain number in the String,
/// with max of max_future hours into the future.
pub fn parse_hour(str: &str, max_future: i64) -> Option<DateTime<Local>> {
str.parse::<u32>().ok().and_then(|hour| {
let now = Local::now();
#[allow(deprecated)]
now.date().and_hms_opt(hour, 0, 0).map(|time| {
if time - now > TimeDelta::hours(max_future) {
time.sub(TimeDelta::days(1))
} else {
time
}
})
})
}
pub fn parse_date(str: &str) -> Option<DateTime<Utc>> {
// Using two libraries for better exhaustiveness, see https://github.com/uutils/parse_datetime/issues/84
match interim::parse_date_string(str, Local::now(), interim::Dialect::Us) {
Ok(date) => Some(date.to_utc()),
Err(e) => {
match parse_datetime::parse_datetime_at_date(Local::now(), str) {
Ok(date) => Some(date.to_utc()),
Err(_) => {
warn!("Could not parse date from \"{str}\": {e}");
None
}
}
}
}.map(|time| {
// TODO properly map date without time to day start, also support intervals
if str.chars().any(|c| c.is_numeric()) {
time
} else {
#[allow(deprecated)]
time.date().and_time(NaiveTime::default()).unwrap()
}
})
}
/// Turn a human-readable relative timestamp into a nostr Timestamp.
/// - Plain number as hour, 18 hours back or 6 hours forward
/// - Number with prefix as minute offset
/// - Otherwise try to parse a relative date
pub fn parse_tracking_stamp(str: &str) -> Option<Timestamp> {
if let Some(num) = parse_hour(str, 6) {
return Some(num.to_timestamp());
}
let stripped = str.trim().trim_start_matches('+').trim_start_matches("in ");
if let Ok(num) = stripped.parse::<i64>() {
return Some(Timestamp::from(Timestamp::now().as_u64().saturating_add_signed(num * 60)));
}
parse_date(str).and_then(|time| {
let stamp = time.to_utc().timestamp();
if stamp > 0 {
Some(Timestamp::from(stamp as u64))
} else {
warn!("Can only track times after 1970!");
None
}
})
}
/// Format DateTime easily comprehensible for human but unambiguous.
/// Length may vary.
pub fn format_datetime_relative(time: DateTime<Local>) -> String {
let date = time.date_naive();
let prefix =
match Local::now()
.date_naive()
.signed_duration_since(date)
.num_days() {
-1 => "tomorrow ".into(),
0 => "".into(),
1 => "yesterday ".into(),
//-3..=3 => date.format("%a ").to_string(),
-10..=10 => date.format("%d. %a ").to_string(),
-100..=100 => date.format("%a %b %d ").to_string(),
_ => date.format("%y-%m-%d %a ").to_string(),
};
format!("{}{}", prefix, time.format("%H:%M"))
}
/// Format a nostr timestamp with the given formatting function.
pub fn format_as_datetime<F>(stamp: &Timestamp, formatter: F) -> String
where
F: Fn(DateTime<Local>) -> String,
{
match Local.timestamp_opt(stamp.as_u64() as i64, 0) {
Single(time) => formatter(time),
_ => stamp.to_human_datetime(),
}
}
/// Format nostr Timestamp relative to local time
/// with optional day specifier or full date depending on distance to today.
pub fn format_timestamp_relative(stamp: &Timestamp) -> String {
format_as_datetime(stamp, format_datetime_relative)
}
/// Format nostr timestamp with the given format.
pub fn format_timestamp(stamp: &Timestamp, format: &str) -> String {
format_as_datetime(stamp, |time| time.format(format).to_string())
}
/// Format nostr timestamp in a sensible comprehensive format with consistent length and consistent sorting.
///
/// Currently: 18 characters
pub fn format_timestamp_local(stamp: &Timestamp) -> String {
format_timestamp(stamp, "%y-%m-%d %a %H:%M")
}
pub fn format_timestamp_relative_to(stamp: &Timestamp, reference: &Timestamp) -> String {
// Rough difference in days
match (stamp.as_u64() as i64 - reference.as_u64() as i64) / 80_000 {
0 => format_timestamp(stamp, "%H:%M"),
-3..=3 => format_timestamp(stamp, "%a %H:%M"),
_ => format_timestamp_local(stamp),
}
}

144
src/kinds.rs Normal file
View File

@ -0,0 +1,144 @@
use itertools::Itertools;
use log::info;
use nostr_sdk::TagStandard::Hashtag;
use nostr_sdk::{Alphabet, EventBuilder, EventId, Kind, Tag, TagStandard};
use std::collections::HashSet;
use crate::task::{State, MARKER_PARENT};
pub const TASK_KIND: Kind = Kind::GitIssue;
pub const PROCEDURE_KIND_ID: u16 = 1639;
pub const PROCEDURE_KIND: Kind = Kind::Regular(PROCEDURE_KIND_ID);
pub const TRACKING_KIND: Kind = Kind::Regular(1650);
pub const BASIC_KINDS: [Kind; 4] = [
Kind::Metadata,
Kind::TextNote,
TASK_KIND,
Kind::Bookmarks,
];
pub const PROP_KINDS: [Kind; 6] = [
TRACKING_KIND,
Kind::GitStatusOpen,
Kind::GitStatusApplied,
Kind::GitStatusClosed,
Kind::GitStatusDraft,
PROCEDURE_KIND,
];
// TODO: use formatting - bold / heading / italics - and generate from code
/// Helper for available properties.
pub const PROPERTY_COLUMNS: &str =
"# Available Properties
Immutable:
- `id` - unique task id
- `parentid` - unique task id of the parent, if any
- `name` - initial name of the task
- `created` - task creation timestamp
- `author` - name or abbreviated key of the task creator
Task:
- `status` - pure task status
- `hashtags` - list of hashtags set for the task
- `tags` - values of all nostr tags associated with the event, except event tags
- `desc` - last note on the task
- `description` - accumulated notes on the task
- `time` - time tracked on this task by you
Utilities:
- `state` - indicator of current progress
- `rtime` - time tracked on this tasks and its subtree by everyone
- `progress` - recursive subtask completion in percent
- `subtasks` - how many direct subtasks are complete
- `path` - name including parent tasks
- `rpath` - name including parent tasks up to active task
- TBI `depends` - list all tasks this task depends on before it becomes actionable
Debugging: `kind`, `pubkey`, `props`, `alltags`, `descriptions`";
pub(crate) fn build_tracking<I>(id: I) -> EventBuilder
where
I: IntoIterator<Item=EventId>,
{
EventBuilder::new(
Kind::from(TRACKING_KIND),
"",
id.into_iter().map(Tag::event),
)
}
/// Build a task with informational output and optional labeled kind
pub(crate) fn build_task(name: &str, tags: Vec<Tag>, kind: Option<(&str, Kind)>) -> EventBuilder {
info!("Created {} \"{name}\" with tags [{}]",
kind.map(|k| k.0).unwrap_or("task"),
tags.iter().map(format_tag).join(", "));
EventBuilder::new(kind.map(|k| k.1).unwrap_or(TASK_KIND), name, tags)
}
pub(crate) fn build_prop(
kind: Kind,
comment: &str,
id: EventId,
) -> EventBuilder {
EventBuilder::new(
kind,
comment,
vec![Tag::event(id)],
)
}
/// Return Hashtags embedded in the string.
pub(crate) fn extract_hashtags(input: &str) -> impl Iterator<Item=Tag> + '_ {
input.split_ascii_whitespace()
.filter(|s| s.starts_with('#'))
.map(|s| s.trim_start_matches('#'))
.map(to_hashtag)
}
/// Extracts everything after a ": " as a list of tags.
///
/// Expects sanitized input.
pub(crate) fn extract_tags(input: &str) -> (&str, Vec<Tag>) {
match input.split_once(": ") {
None => (input, extract_hashtags(input).collect_vec()),
Some((name, tags)) => {
let tags = extract_hashtags(name)
.chain(tags.split_ascii_whitespace().map(to_hashtag))
.collect();
(name, tags)
}
}
}
fn to_hashtag(tag: &str) -> Tag {
Hashtag(tag.to_string()).into()
}
fn format_tag(tag: &Tag) -> String {
match tag.as_standardized() {
Some(TagStandard::Event {
event_id,
marker,
..
}) => format!("{}: {:.8}", marker.as_ref().map(|m| m.to_string()).unwrap_or(MARKER_PARENT.to_string()), event_id),
Some(TagStandard::PublicKey {
public_key,
alias,
..
}) => format!("Key{}: {:.8}", public_key, alias.as_ref().map(|s| format!(" {s}")).unwrap_or_default()),
Some(TagStandard::Hashtag(content)) =>
format!("#{content}"),
_ => tag.content().map_or_else(
|| format!("Kind {}", tag.kind()),
|content| content.to_string(),
)
}
}
pub(crate) fn is_hashtag(tag: &Tag) -> bool {
tag.single_letter_tag()
.is_some_and(|letter| letter.character == Alphabet::T)
}
#[test]
fn test_extract_tags() {
assert_eq!(extract_tags("Hello from #mars with #greetings: yeah done-it"),
("Hello from #mars with #greetings", ["mars", "greetings", "yeah", "done-it"].into_iter().map(to_hashtag).collect()))
}

File diff suppressed because it is too large Load Diff

View File

@ -1,36 +1,64 @@
use fmt::Display; use fmt::Display;
use std::cmp::Ordering;
use std::collections::{BTreeSet, HashSet}; use std::collections::{BTreeSet, HashSet};
use std::fmt; use std::fmt;
use std::ops::Div; use std::hash::{Hash, Hasher};
use std::string::ToString;
use colored::{ColoredString, Colorize};
use itertools::Either::{Left, Right}; use itertools::Either::{Left, Right};
use itertools::Itertools; use itertools::Itertools;
use log::{debug, error, info, trace, warn}; use log::{debug, error, info, trace, warn};
use nostr_sdk::{Alphabet, Event, EventBuilder, EventId, Kind, Tag, Timestamp}; use nostr_sdk::{Event, EventId, Kind, Tag, TagStandard, Timestamp};
use crate::EventSender; use crate::helpers::{format_timestamp_local, some_non_empty};
use crate::kinds::{is_hashtag, PROCEDURE_KIND, PROCEDURE_KIND_ID, TASK_KIND};
#[derive(Debug, Clone, PartialEq)] pub static MARKER_PARENT: &str = "parent";
pub static MARKER_DEPENDS: &str = "depends";
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Task { pub(crate) struct Task {
/// Event that defines this task
pub(crate) event: Event, pub(crate) event: Event,
pub(crate) children: HashSet<EventId>, /// Cached sorted tags of the event with references remove - do not modify!
pub(crate) props: BTreeSet<Event>,
/// Cached sorted tags of the event
pub(crate) tags: Option<BTreeSet<Tag>>, pub(crate) tags: Option<BTreeSet<Tag>>,
parents: Vec<EventId>, /// 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 Hash for Task {
fn hash<H: Hasher>(&self, state: &mut H) {
self.event.id.hash(state);
}
} }
impl Task { impl Task {
pub(crate) fn new(event: Event) -> Task { pub(crate) fn new(event: Event) -> Task {
let (parents, tags) = event.tags.iter().partition_map(|tag| match tag { let (refs, tags) = event.tags.iter().partition_map(|tag| match tag.as_standardized() {
Tag::Event { event_id, .. } => return Left(event_id), Some(TagStandard::Event { event_id, marker, .. }) =>
Left((marker.as_ref().map_or(MARKER_PARENT.to_string(), |m| m.to_string()), *event_id)),
_ => Right(tag.clone()), _ => Right(tag.clone()),
}); });
// Separate refs for dependencies
Task { Task {
children: Default::default(),
props: Default::default(), props: Default::default(),
tags: Some(tags).filter(|t: &BTreeSet<Tag>| !t.is_empty()), tags: Some(tags).filter(|t: &BTreeSet<Tag>| !t.is_empty()),
parents, refs,
event, event,
} }
} }
@ -39,59 +67,86 @@ impl Task {
&self.event.id &self.event.id
} }
pub(crate) fn parent_id(&self) -> Option<EventId> { pub(crate) fn find_refs<'a>(&'a self, marker: &'a str) -> impl Iterator<Item=&'a EventId> {
self.parents.first().cloned() self.refs.iter().filter_map(move |(str, id)| Some(id).filter(|_| str == marker))
} }
pub(crate) fn parent_id(&self) -> Option<&EventId> {
self.find_refs(MARKER_PARENT).next()
}
pub(crate) fn get_dependendees(&self) -> Vec<&EventId> {
self.find_refs(MARKER_DEPENDS).collect()
}
/// Trimmed event content or stringified id
pub(crate) fn get_title(&self) -> String { pub(crate) fn get_title(&self) -> String {
Some(self.event.content.trim().to_string()) some_non_empty(self.event.content.trim())
.filter(|s| !s.is_empty())
.unwrap_or_else(|| self.get_id().to_string()) .unwrap_or_else(|| self.get_id().to_string())
} }
pub(crate) fn descriptions(&self) -> impl Iterator<Item = &String> + '_ { pub(crate) fn get_filter_title(&self) -> String {
self.props.iter().filter_map(|event| { self.event.content.trim().trim_start_matches('#').to_string()
if event.kind == Kind::TextNote {
Some(&event.content)
} else {
None
}
})
} }
fn states(&self) -> impl Iterator<Item = TaskState> + '_ { pub(crate) fn description_events(&self) -> impl Iterator<Item=&Event> + '_ {
self.props.iter().filter(|event| event.kind == Kind::TextNote)
}
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
}
/// Whether this is an actionable task - false if stateless
pub(crate) fn is_task(&self) -> bool {
self.is_task_kind() ||
self.props.iter().any(|event| State::try_from(event.kind).is_ok())
}
fn states(&self) -> impl DoubleEndedIterator<Item=TaskState> + '_ {
self.props.iter().filter_map(|event| { self.props.iter().filter_map(|event| {
event.kind.try_into().ok().map(|s| TaskState { event.kind.try_into().ok().map(|s| TaskState {
name: Some(event.content.clone()).filter(|c| !c.is_empty()), name: some_non_empty(&event.content),
state: s, state: s,
time: event.created_at.clone(), time: event.created_at,
}) })
}) })
} }
pub(crate) fn last_state_update(&self) -> Timestamp {
self.state().map(|s| s.time).unwrap_or(self.event.created_at)
}
pub(crate) fn state(&self) -> Option<TaskState> { pub(crate) fn state(&self) -> Option<TaskState> {
self.states().max_by_key(|t| t.time) 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 { pub(crate) fn pure_state(&self) -> State {
self.state().map_or(State::Open, |s| s.state) self.state().map_or(State::Open, |s| s.state)
} }
pub(crate) fn set_state( pub(crate) fn state_or_default(&self) -> TaskState {
&mut self, self.state().unwrap_or_else(|| self.default_state())
sender: &EventSender, }
state: State,
comment: &str, /// Returns None for activities.
) -> Option<Event> { pub(crate) fn state_label(&self) -> Option<ColoredString> {
sender self.state()
.submit(EventBuilder::new( .or_else(|| Some(self.default_state()).filter(|_| self.is_task()))
state.kind(), .map(|state| state.get_colored_label())
comment,
vec![Tag::event(self.event.id)],
))
.inspect(|e| {
self.props.insert(e.clone());
})
} }
fn default_state(&self) -> TaskState { fn default_state(&self) -> TaskState {
@ -102,68 +157,45 @@ impl Task {
} }
} }
/// Total time this task has been active.
/// TODO: Consider caching
pub(crate) fn time_tracked(&self) -> u64 {
let mut total = 0;
let mut start: Option<Timestamp> = None;
for state in self.states() {
match state.state {
State::Active => start = start.or(Some(state.time)),
_ => {
if let Some(stamp) = start {
total += (state.time - stamp).as_u64();
start = None;
}
}
}
}
if let Some(start) = start {
total += (Timestamp::now() - start).as_u64();
}
total
}
fn filter_tags<P>(&self, predicate: P) -> Option<String> fn filter_tags<P>(&self, predicate: P) -> Option<String>
where where
P: FnMut(&&Tag) -> bool, P: FnMut(&&Tag) -> bool,
{ {
self.tags.as_ref().map(|tags| { self.tags.as_ref().map(|tags| {
tags.into_iter() tags.iter()
.filter(predicate) .filter(predicate)
.map(|t| format!("{}", t.content().unwrap())) .map(|t| t.content().unwrap().to_string())
.collect::<Vec<String>>()
.join(" ") .join(" ")
}) })
} }
pub(crate) fn get(&self, property: &str) -> Option<String> { pub(crate) fn get(&self, property: &str) -> Option<String> {
match property { match property {
// Static
"id" => Some(self.event.id.to_string()), "id" => Some(self.event.id.to_string()),
"parentid" => self.parent_id().map(|i| i.to_string()), "parentid" => self.parent_id().map(|i| i.to_string()),
"state" => self.state().map(|s| s.to_string()),
"name" => Some(self.event.content.clone()), "name" => Some(self.event.content.clone()),
"time" => Some(self.time_tracked().div(60)) "pubkey" => Some(self.event.pubkey.to_string()),
.filter(|t| t > &0) "created" => Some(format_timestamp_local(&self.event.created_at)),
.map(|t| format!("{}m", t)), "kind" => Some(self.event.kind.to_string()),
// Dynamic
"status" => self.state_label().map(|c| c.to_string()),
"desc" => self.descriptions().last().cloned(), "desc" => self.descriptions().last().cloned(),
"description" => Some(self.descriptions().join(" ")), "description" => Some(self.descriptions().join(" ")),
"hashtags" => self.filter_tags(|tag| { "hashtags" => self.filter_tags(|tag| { is_hashtag(tag) }),
tag.single_letter_tag()
.is_some_and(|sltag| sltag.character == Alphabet::T)
}),
"tags" => self.filter_tags(|_| true), "tags" => self.filter_tags(|_| true),
"alltags" => Some(format!("{:?}", self.tags)), "alltags" => Some(format!("{:?}", self.tags)),
"refs" => Some(format!("{:?}", self.refs.iter().map(|re| format!("{}: {}", re.0, re.1)).collect_vec())),
"props" => Some(format!( "props" => Some(format!(
"{:?}", "{:?}",
self.props self.props
.iter() .iter()
.map(|e| format!("{} kind {} '{}'", e.created_at, e.kind, e.content)) .map(|e| format!("{} kind {} \"{}\"", e.created_at, e.kind, e.content))
.collect::<Vec<String>>() .collect_vec()
)), )),
"descriptions" => Some(format!( "descriptions" => Some(format!(
"{:?}", "{:?}",
self.descriptions().collect::<Vec<&String>>() self.descriptions().collect_vec()
)), )),
_ => { _ => {
warn!("Unknown task property {}", property); warn!("Unknown task property {}", property);
@ -174,20 +206,22 @@ impl Task {
} }
pub(crate) struct TaskState { pub(crate) struct TaskState {
state: State, pub(crate) state: State,
name: Option<String>, name: Option<String>,
pub(crate) time: Timestamp, pub(crate) time: Timestamp,
} }
impl TaskState { impl TaskState {
pub(crate) fn get_label_for(state: &State, comment: &str) -> String {
some_non_empty(comment).unwrap_or_else(|| state.to_string())
}
pub(crate) fn get_label(&self) -> String { pub(crate) fn get_label(&self) -> String {
self.name.clone().unwrap_or_else(|| self.state.to_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 { pub(crate) fn matches_label(&self, label: &str) -> bool {
self.state == State::Active self.name.as_ref().is_some_and(|n| n.eq_ignore_ascii_case(label))
|| self
.name
.as_ref()
.is_some_and(|n| n.eq_ignore_ascii_case(label))
|| self.state.to_string().eq_ignore_ascii_case(label) || self.state.to_string().eq_ignore_ascii_case(label)
} }
} }
@ -206,43 +240,76 @@ impl Display for TaskState {
} }
} }
#[derive(Debug, Copy, Clone, PartialEq)] #[derive(Debug, Copy, Clone, PartialEq, Ord, PartialOrd, Eq)]
pub(crate) enum State { pub(crate) enum State {
Closed, /// Actionable
Open, Open = 1630,
Active, /// Completed
Done, Done,
/// Not Actionable (anymore)
Closed,
/// Temporarily not actionable
Pending,
/// 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(()),
}
}
} }
impl TryFrom<Kind> for State { impl TryFrom<Kind> for State {
type Error = (); type Error = ();
fn try_from(value: Kind) -> Result<Self, Self::Error> { fn try_from(value: Kind) -> Result<Self, Self::Error> {
match value.as_u32() { match value {
1630 => Ok(State::Open), Kind::GitStatusOpen => Ok(State::Open),
1631 => Ok(State::Done), Kind::GitStatusApplied => Ok(State::Done),
1632 => Ok(State::Closed), Kind::GitStatusClosed => Ok(State::Closed),
1633 => Ok(State::Active), Kind::GitStatusDraft => Ok(State::Pending),
_ => Err(()), _ => {
if value == PROCEDURE_KIND {
Ok(State::Procedure)
} else {
Err(())
}
}
} }
} }
} }
impl State { impl State {
pub(crate) fn is_open(&self) -> bool { pub(crate) fn is_open(&self) -> bool {
match self { matches!(self, State::Open | State::Pending | State::Procedure)
State::Open | State::Active => true,
_ => false,
}
} }
pub(crate) fn kind(&self) -> Kind { pub(crate) fn kind(self) -> u16 {
self as u16
}
pub(crate) fn colorize(&self, str: &str) -> ColoredString {
match self { match self {
State::Open => Kind::from(1630), State::Open => str.green(),
State::Done => Kind::from(1631), State::Done => str.bright_black(),
State::Closed => Kind::from(1632), State::Closed => str.magenta(),
State::Active => Kind::from(1633), State::Pending => str.yellow(),
State::Procedure => str.blue(),
} }
} }
} }
impl From<State> for Kind {
fn from(value: State) -> Self {
Kind::from(value.kind())
}
}
impl Display for State { impl Display for State {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(self, f) fmt::Debug::fmt(self, f)

File diff suppressed because it is too large Load Diff