From 7bceeb255eb9cd7225599a20380519e51ed8fedf Mon Sep 17 00:00:00 2001 From: yukkop Date: Wed, 14 Oct 2026 22:59:55 +0000 Subject: [PATCH] routine tui --- package/default.nix | 1 + package/routine-tui/Cargo.lock | 943 +++++++++++++++++++++++++++++++ package/routine-tui/Cargo.toml | 17 + package/routine-tui/README.md | 32 ++ package/routine-tui/default.nix | 25 + package/routine-tui/src/api.rs | 130 +++++ package/routine-tui/src/app.rs | 416 ++++++++++++++ package/routine-tui/src/main.rs | 69 +++ package/routine-tui/src/model.rs | 85 +++ package/routine-tui/src/ui.rs | 182 ++++++ 10 files changed, 1900 insertions(+) create mode 100644 package/routine-tui/Cargo.lock create mode 100644 package/routine-tui/Cargo.toml create mode 100644 package/routine-tui/README.md create mode 100644 package/routine-tui/default.nix create mode 100644 package/routine-tui/src/api.rs create mode 100644 package/routine-tui/src/app.rs create mode 100644 package/routine-tui/src/main.rs create mode 100644 package/routine-tui/src/model.rs create mode 100644 package/routine-tui/src/ui.rs diff --git a/package/default.nix b/package/default.nix index 820f3fd0..b1b4d76b 100644 --- a/package/default.nix +++ b/package/default.nix @@ -152,6 +152,7 @@ in { shellplot = pkgs.callPackage ./shellplot {}; gitea-kanban-tui = pkgs.callPackage ./gitea-kanban-tui rust.commonArgs; routine-server = pkgs.callPackage ./routine-server rust.commonArgs; + routine-tui = pkgs.callPackage ./routine-tui rust.commonArgs; which-country-rs = pkgs.callPackage ./which-country-rs {}; onlinepubs2man = pkgs.callPackage ./onlinepubs2man {}; migrator = pkgs.callPackage ./migrator { inherit self; }; diff --git a/package/routine-tui/Cargo.lock b/package/routine-tui/Cargo.lock new file mode 100644 index 00000000..eb5732af --- /dev/null +++ b/package/routine-tui/Cargo.lock @@ -0,0 +1,943 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + +[[package]] +name = "android-tzdata" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e999941b234f3131b00bc13c22d06e8c5ff726d1b6318ac7eb276997bbb4fef0" + +[[package]] +name = "android_system_properties" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" +dependencies = [ + "libc", +] + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "cassowary" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df8670b8c7b9dae1793364eafadf7239c40d669904660c5960d74cfd80b46a53" + +[[package]] +name = "castaway" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dec551ab6e7578819132c713a93c022a05d60159dc86e7a7050223577484c55a" +dependencies = [ + "rustversion", +] + +[[package]] +name = "cc" +version = "1.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6651c9ed80effdc7db0ff72512157f901af5e3549e341e24b1dd4887d836d838" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "chrono" +version = "0.4.38" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a21f936df1771bf62b77f047b726c4625ff2e8aa607c01ec06e5a05bd8463401" +dependencies = [ + "android-tzdata", + "iana-time-zone", + "num-traits", + "serde", + "windows-targets", +] + +[[package]] +name = "compact_str" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7fd622ebbb56a5b2ccb651b32b911cdeb2a9b4b11776b2473bf26a26a286244e" +dependencies = [ + "castaway", + "cfg-if", + "itoa", + "rustversion", + "ryu", + "static_assertions", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "crossterm" +version = "0.28.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "829d955a0bb380ef178a640b91779e3987da38c9aea133b20614cfed8cdea9c6" +dependencies = [ + "bitflags", + "crossterm_winapi", + "mio", + "parking_lot", + "rustix", + "signal-hook", + "signal-hook-mio", + "winapi", +] + +[[package]] +name = "crossterm_winapi" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "acdd7c62a3665c7f6830a51635d9ac9b23ed385797f70a83bb8bafe9c572ab2b" +dependencies = [ + "winapi", +] + +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484" + +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "indoc" +version = "2.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a37b2691796cffeb8a8cd305ac66e65841559f147f4e63231d0eafa4db5384d1" +dependencies = [ + "rustversion", +] + +[[package]] +name = "instability" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b23a0c8dfe501baac4adf6ebbfa6eddf8f0c07f56b058cc1288017e32397846c" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "itertools" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "js-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "libc" +version = "0.2.190" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78" + +[[package]] +name = "linux-raw-sys" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "lru" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "234cf4f4a04dc1f57e24b96cc0cd600cf2af460d4161ac5ecdd0af8e1f3b2a38" +dependencies = [ + "hashbrown", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "minreq" +version = "2.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "763d142cdff44aaadd9268bebddb156ef6c65a0e13486bb81673cf2d8739f9b0" +dependencies = [ + "log", + "once_cell", + "rustls", + "rustls-webpki", + "webpki-roots", +] + +[[package]] +name = "mio" +version = "1.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" +dependencies = [ + "libc", + "log", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "paste" +version = "1.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "ratatui" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eabd94c2f37801c20583fc49dd5cd6b0ba68c716787c2dd6ed18571e1e63117b" +dependencies = [ + "bitflags", + "cassowary", + "compact_str", + "crossterm", + "indoc", + "instability", + "itertools", + "lru", + "paste", + "strum", + "unicode-segmentation", + "unicode-truncate", + "unicode-width 0.2.0", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "routine-tui" +version = "0.1.0" +dependencies = [ + "chrono", + "crossterm", + "instability", + "minreq", + "ratatui", + "serde", + "serde_json", + "unicode-segmentation", +] + +[[package]] +name = "rustix" +version = "0.38.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.59.0", +] + +[[package]] +name = "rustls" +version = "0.21.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f56a14d1f48b391359b22f731fd4bd7e43c97f3c50eee276f3aa09c94784d3e" +dependencies = [ + "log", + "ring", + "rustls-webpki", + "sct", +] + +[[package]] +name = "rustls-webpki" +version = "0.101.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b6275d1ee7a1cd780b64aca7726599a1dbc893b1e64144529e55c3c2f745765" +dependencies = [ + "ring", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "sct" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da046153aa2352493d6cb7da4b6e5c0c057d8a1d0a9aa8560baffdd945acd414" +dependencies = [ + "ring", + "untrusted", +] + +[[package]] +name = "serde" +version = "1.0.210" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8e3592472072e6e22e0a54d5904d9febf8508f65fb8552499a1abc7d1078c3a" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.210" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "243902eda00fad750862fc144cea25caca5e20d615af0a81bee94ca738f1df1f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "serde_json" +version = "1.0.128" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ff5456707a1de34e7e37f2a6fd3d3f808c318259cbd01ab6377795054b483d8" +dependencies = [ + "itoa", + "memchr", + "ryu", + "serde", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d881a16cf4426aa584979d30bd82cb33429027e42122b169753d6ef1085ed6e2" +dependencies = [ + "libc", + "signal-hook-registry", +] + +[[package]] +name = "signal-hook-mio" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b75a19a7a740b25bc7944bdee6172368f988763b744e3d4dfe753f6b4ece40cc" +dependencies = [ + "libc", + "mio", + "signal-hook", +] + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b3dc8af474f516a851ff4bd12db780f948b9250ad37211e4eec0bccea54e01b" + +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + +[[package]] +name = "strum" +version = "0.26.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fec0f0aef304996cf250b31b5a10dee7980c85da9d759361292b8bca5a18f06" +dependencies = [ + "strum_macros", +] + +[[package]] +name = "strum_macros" +version = "0.26.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c6bee85a5a24955dc440386795aa378cd9cf82acd5f764469152d2270e581be" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "rustversion", + "syn 2.0.119", +] + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-segmentation" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6ccf251212114b54433ec949fd6a7841275f9ada20dddd2f29e9ceea4501493" + +[[package]] +name = "unicode-truncate" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b3644627a5af5fa321c95b9b235a72fd24cd29c648c2c379431e6628655627bf" +dependencies = [ + "itertools", + "unicode-segmentation", + "unicode-width 0.1.14", +] + +[[package]] +name = "unicode-width" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af" + +[[package]] +name = "unicode-width" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fc81956842c57dac11422a97c3b8195a1ff727f06e85c84ed2e8aa277c9a0fd" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasm-bindgen" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.9", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "webpki-roots" +version = "0.25.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f20c57d8d7db6d3b86154206ae5d8fba62dd39573114de97c2cb0578251f8e1" + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" diff --git a/package/routine-tui/Cargo.toml b/package/routine-tui/Cargo.toml new file mode 100644 index 00000000..fc391aab --- /dev/null +++ b/package/routine-tui/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "routine-tui" +version = "0.1.0" +edition = "2021" +description = "Ratatui client for routine-server" +license = "MIT" + +[dependencies] +chrono = { version = "=0.4.38", default-features = false, features = ["clock", "serde"] } +crossterm = "=0.28.1" +instability = "=0.3.2" +minreq = { version = "=2.12.0", default-features = false, features = ["https-rustls"] } +ratatui = "=0.29.0" +serde = { version = "=1.0.210", features = ["derive"] } +serde_json = "=1.0.128" +unicode-segmentation = "=1.12.0" + diff --git a/package/routine-tui/README.md b/package/routine-tui/README.md new file mode 100644 index 00000000..ce86b436 --- /dev/null +++ b/package/routine-tui/README.md @@ -0,0 +1,32 @@ +# routine-tui + +Ratatui client for `routine-server`. + +```sh +nix run .#routine-tui +``` + +Configuration: + +- `ROUTINE_API_URL` defaults to `http://127.0.0.1:8090`. +- `ROUTINE_API_TOKEN` is sent as a bearer token when set. + +Because the production server is loopback-only, either run the TUI on +`hectic-lab` or open a local tunnel first: + +```sh +ssh -N -L 8090:127.0.0.1:8090 hectic-lab +``` + +Keys: + +- `Tab`: switch between tasks and routines. +- `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. + +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 +last day. + diff --git a/package/routine-tui/default.nix b/package/routine-tui/default.nix new file mode 100644 index 00000000..58186e54 --- /dev/null +++ b/package/routine-tui/default.nix @@ -0,0 +1,25 @@ +{ + cargoToml, + lib, + nativeBuildInputs, + pkgs, + ... +}: let + cargo = cargoToml ./Cargo.toml; +in + pkgs.rustPlatform.buildRustPackage { + pname = cargo.package.name; + version = cargo.package.version; + src = ./.; + + inherit nativeBuildInputs; + cargoLock.lockFile = ./Cargo.lock; + doCheck = true; + + meta = { + description = cargo.package.description; + license = lib.licenses.mit; + mainProgram = "routine-tui"; + }; + } + diff --git a/package/routine-tui/src/api.rs b/package/routine-tui/src/api.rs new file mode 100644 index 00000000..21266811 --- /dev/null +++ b/package/routine-tui/src/api.rs @@ -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, +} + +impl ApiClient { + pub fn new(base_url: String, token: Option) -> Self { + Self { + base_url: base_url.trim_end_matches('/').to_owned(), + token, + } + } + + pub fn list_tasks(&self, date: &str) -> Result, String> { + self.get(&format!("/v1/tasks?date={date}")) + } + + pub fn list_routines(&self) -> Result, 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(&self, path: &str) -> Result { + 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(&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::(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"); + } +} diff --git a/package/routine-tui/src/app.rs b/package/routine-tui/src/app.rs new file mode 100644 index 00000000..7afae5fc --- /dev/null +++ b/package/routine-tui/src/app.rs @@ -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, + pub active: usize, +} + +pub struct App { + pub api: ApiClient, + pub view: View, + pub date: NaiveDate, + pub tasks: Vec, + pub routines: Vec, + pub selected: usize, + pub status: String, + pub form: Option
, + 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 { + let value = value.trim(); + if value.is_empty() { + Err(format!("{name} is required")) + } else { + Ok(value.to_owned()) + } +} + +fn optional(value: &str) -> Option { + let value = value.trim(); + (!value.is_empty()).then(|| value.to_owned()) +} + +fn parse_schedule(kind: &str, days: &str) -> Result { + 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, String> { + let mut values = input + .split(',') + .map(str::trim) + .filter(|value| !value.is_empty()) + .map(|value| { + value + .parse::() + .map_err(|_| "days must be comma-separated numbers".to_owned()) + }) + .collect::, _>>()?; + 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" + ); + } +} diff --git a/package/routine-tui/src/main.rs b/package/routine-tui/src/main.rs new file mode 100644 index 00000000..a6df2b83 --- /dev/null +++ b/package/routine-tui/src/main.rs @@ -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>, + 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() +} diff --git a/package/routine-tui/src/model.rs b/package/routine-tui/src/model.rs new file mode 100644 index 00000000..7a48e18f --- /dev/null +++ b/package/routine-tui/src/model.rs @@ -0,0 +1,85 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Deserialize)] +pub struct Task { + pub id: i64, + pub routine_id: Option, + pub title: String, + pub notes: Option, + pub section: String, + pub priority: String, + pub reminder_time: Option, + pub status: String, + pub completed_at: Option, +} + +#[derive(Debug, Clone, Deserialize)] +pub struct Routine { + pub title: String, + pub notes: Option, + pub section: String, + pub priority: String, + pub schedule: Schedule, + pub reminder_time: Option, + pub enabled: bool, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum Schedule { + Daily, + Weekly { + weekdays: Vec, + }, + Monthly { + days: Vec, + clamp_to_last_day: bool, + }, +} + +#[derive(Debug, Serialize)] +pub struct CreateTask { + pub title: String, + pub notes: Option, + pub section: String, + pub priority: String, + pub scheduled_date: String, + pub reminder_time: Option, +} + +#[derive(Debug, Serialize)] +pub struct CreateRoutine { + pub title: String, + pub notes: Option, + pub section: String, + pub priority: String, + pub schedule: Schedule, + pub reminder_time: Option, +} + +#[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::>() + .join(",") +} diff --git a/package/routine-tui/src/ui.rs b/package/routine-tui/src/ui.rs new file mode 100644 index 00000000..a95bc51f --- /dev/null +++ b/package/routine-tui/src/ui.rs @@ -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::>(), + 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::>(), + }; + 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::>(); + 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] +}