7 Commits

Author SHA1 Message Date
jk
4a20587947 cargo build 2025-09-02 10:58:55 +02:00
jk
e25eb6ef89 Prepare v1.4.0 2025-09-02 10:53:41 +02:00
Jens Krause
60392b40ed demo: local time (#91) 2025-08-30 22:06:51 +02:00
Jens Krause
901cf69472 feat(screen): LocalTime (#90) 2025-08-30 21:48:56 +02:00
Jens Krause
c494f0e829 refactor(footer): AppTimeFormat data handling (#89)
- Extract local state of `app_time_format` from `footer` to have it globally available
- Add a deserialization fallback for deprecated `AppTimeFormat::Hidden`
- Persist `footer_app_time` toggle state
2025-08-27 19:44:02 +02:00
Jens Krause
637c1da21b Rust 1.89.0 (#87) 2025-08-15 11:43:17 +02:00
Jens Krause
3439e4aa8d Prepare v1.3.1 (#86)
* bump v1.3.1

* update CHANGELOG

* start workflow by `release/*` branches only but not by tags to avoid overriding releases.
2025-07-03 11:01:51 +02:00
20 changed files with 512 additions and 138 deletions

View File

@@ -4,8 +4,6 @@ on:
push:
branches:
- "release/**"
tags:
- "v*"
jobs:
get-version:

View File

@@ -1,15 +1,25 @@
# Changelog
## [Unreleased]
## v1.4.0 - 2025-09-02
### Features
- (args) set `content` by given duration [#81](https://github.com/sectore/tick-tock-tui/pull/81)
- (screen): Local Time [#89](https://github.com/sectore/timr-tui/pull/89), [#90](https://github.com/sectore/timr-tui/pull/90), [#91](https://github.com/sectore/timr-tui/pull/91)
### Misc.
- (deps) Rust 1.89.0 [#87](https://github.com/sectore/timr-tui/pull/87)
## v1.3.1 - 2025-07-03
### Features
- (args) set `content` by given duration [#81](https://github.com/sectore/timr-tui/pull/81)
### Fixes
- (pomodoro) `ctrl+r` resets rounds AND both clocks [#83](https://github.com/sectore/tick-tock-tui/pull/83)
- (pomodoro) reset active clock only [#82](https://github.com/sectore/tick-tock-tui/pull/82)
- (pomodoro) `ctrl+r` resets rounds AND both clocks [#83](https://github.com/sectore/timr-tui/pull/83)
- (pomodoro) reset active clock only [#82](https://github.com/sectore/timr-tui/pull/82)
### Misc.

2
Cargo.lock generated
View File

@@ -2082,7 +2082,7 @@ dependencies = [
[[package]]
name = "timr-tui"
version = "1.3.0"
version = "1.4.0"
dependencies = [
"clap",
"color-eyre",

View File

@@ -1,10 +1,10 @@
[package]
name = "timr-tui"
version = "1.3.0"
version = "1.4.0"
description = "TUI to organize your time: Pomodoro, Countdown, Timer."
edition = "2024"
# Reminder: Always keep `channel` in `rust-toolchain.toml` in sync with `rust-version`.
rust-version = "1.88.0"
rust-version = "1.89.0"
homepage = "https://github.com/sectore/timr-tui"
repository = "https://github.com/sectore/timr-tui"
readme = "README.md"

View File

@@ -41,10 +41,23 @@ _(theme depends on your terminal preferences)_
<img alt="countdown" src="demo/countdown.gif" />
</a>
## Change style
## Countdown: Mission Elapsed Time ([MET](https://en.wikipedia.org/wiki/Mission_Elapsed_Time))
<a href="demo/style.gif">
<img alt="style" src="demo/style.gif" />
<a href="demo/countdown-met.gif">
<img alt="menu" src="demo/countdown-met.gif" />
</a>
## Local time
<a href="demo/local-time.gif">
<img alt="menu" src="demo/local-time.gif" />
</a>
## Local time (footer)
<a href="demo/local-time-footer.gif">
<img alt="menu" src="demo/local-time-footer.gif" />
</a>
## Toggle deciseconds
@@ -53,24 +66,18 @@ _(theme depends on your terminal preferences)_
<img alt="deciseconds" src="demo/decis.gif" />
</a>
## Change style
<a href="demo/style.gif">
<img alt="style" src="demo/style.gif" />
</a>
## Menu
<a href="demo/menu.gif">
<img alt="menu" src="demo/menu.gif" />
</a>
## Local time (footer)
<a href="demo/local-time.gif">
<img alt="menu" src="demo/local-time.gif" />
</a>
## Mission Elapsed Time ([MET](https://en.wikipedia.org/wiki/Mission_Elapsed_Time))
<a href="demo/countdown-met.gif">
<img alt="menu" src="demo/countdown-met.gif" />
</a>
# CLI
```sh
@@ -83,7 +90,7 @@ Options:
-w, --work <WORK> Work time to count down from. Formats: 'ss', 'mm:ss', or 'hh:mm:ss'
-p, --pause <PAUSE> Pause time to count down from. Formats: 'ss', 'mm:ss', or 'hh:mm:ss'
-d, --decis Show deciseconds.
-m, --mode <MODE> Mode to start with. [possible values: countdown, timer, pomodoro]
-m, --mode <MODE> Mode to start with. [possible values: countdown, timer, pomodoro, localtime]
-s, --style <STYLE> Style to display time with. [possible values: full, light, medium, dark, thick, cross, braille]
--menu Open the menu.
-r, --reset Reset stored values to default values.
@@ -115,6 +122,7 @@ Extra option (if `--features sound` is enabled by local build only):
| <kbd>p</kbd> | Pomodoro |
| <kbd>c</kbd> | Countdown |
| <kbd>t</kbd> | Timer |
| <kbd>l</kbd> | Local Time |
## Controls
@@ -135,7 +143,7 @@ Extra option (if `--features sound` is enabled by local build only):
| <kbd>↑</kbd> | edit to go up |
| <kbd>↓</kbd> | edit to go down |
**In `Pomodoro` screen only**
**In `Pomodoro` screen only:**
| Key | Description |
| --- | --- |
@@ -156,7 +164,7 @@ Extra option (if `--features sound` is enabled by local build only):
| --- | --- |
| <kbd>,</kbd> | toggle styles |
| <kbd>.</kbd> | toggle deciseconds |
| <kbd>:</kbd> | toggle local time in footer |
| <kbd>:</kbd> | toggle local time |
# Installation
@@ -220,6 +228,7 @@ Available recipes:
demo-countdown-met # build demo: countdown + met [alias: dcm]
demo-decis # build demo: deciseconds [alias: dd]
demo-local-time # build demo: local time [alias: dlt]
demo-local-time-footer # build demo: local time (footer) [alias: dltf]
demo-menu # build demo: menu [alias: dm]
demo-pomodoro # build demo: pomodoro [alias: dp]
demo-rocket-countdown # build demo: rocket countdown [alias: drc]

BIN
demo/local-time-footer.gif Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

View File

@@ -0,0 +1,20 @@
Output demo/local-time-footer.gif
# https://github.com/charmbracelet/vhs/blob/main/THEMES.md
Set Theme "AtomOneLight"
Set FontSize 14
Set Width 800
Set Height 400
Set Padding 0
Set Margin 1
# --- START ---
Set LoopOffset 4
Hide
Type "cargo run -- -m c"
Enter
Sleep 0.2
Show
# --- toggle local time ---
Type@1.5s ":::"

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

After

Width:  |  Height:  |  Size: 28 KiB

View File

@@ -1,7 +1,7 @@
Output demo/local-time.gif
# https://github.com/charmbracelet/vhs/blob/main/THEMES.md
Set Theme "AtomOneLight"
Set Theme "Atom"
Set FontSize 14
Set Width 800
@@ -12,11 +12,9 @@ Set Margin 1
# --- START ---
Set LoopOffset 4
Hide
Type "cargo run -- -m c"
Type "cargo run -- -m l"
Enter
Sleep 0.2
Show
Sleep 1
# --- toggle local time ---
Type@1.5s ":::"
Sleep 1.5

24
flake.lock generated
View File

@@ -2,11 +2,11 @@
"nodes": {
"crane": {
"locked": {
"lastModified": 1750266157,
"narHash": "sha256-tL42YoNg9y30u7zAqtoGDNdTyXTi8EALDeCB13FtbQA=",
"lastModified": 1754269165,
"narHash": "sha256-0tcS8FHd4QjbCVoxN9jI+PjHgA4vc/IjkUSp+N3zy0U=",
"owner": "ipetkov",
"repo": "crane",
"rev": "e37c943371b73ed87faf33f7583860f81f1d5a48",
"rev": "444e81206df3f7d92780680e45858e31d2f07a08",
"type": "github"
},
"original": {
@@ -23,11 +23,11 @@
"rust-analyzer-src": "rust-analyzer-src"
},
"locked": {
"lastModified": 1751092526,
"narHash": "sha256-vmbu97JXqr9/sTWR5XRh646jkp8a0J9m0o6JIQTdjE4=",
"lastModified": 1755240331,
"narHash": "sha256-wEtw76+R/TOHEIjYOnxADC91G6s422HGruAngbjzsDw=",
"owner": "nix-community",
"repo": "fenix",
"rev": "6643d56d9a78afa157b577862c220298c09b891d",
"rev": "3f076d4502001c64877099093318b2dbd8b062a1",
"type": "github"
},
"original": {
@@ -56,11 +56,11 @@
},
"nixpkgs": {
"locked": {
"lastModified": 1750776420,
"narHash": "sha256-/CG+w0o0oJ5itVklOoLbdn2dGB0wbZVOoDm4np6w09A=",
"lastModified": 1755027561,
"narHash": "sha256-IVft239Bc8p8Dtvf7UAACMG5P3ZV+3/aO28gXpGtMXI=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "30a61f056ac492e3b7cdcb69c1e6abdcf00e39cf",
"rev": "005433b926e16227259a1843015b5b2b7f7d1fc3",
"type": "github"
},
"original": {
@@ -81,11 +81,11 @@
"rust-analyzer-src": {
"flake": false,
"locked": {
"lastModified": 1750871759,
"narHash": "sha256-hMNZXMtlhfjQdu1F4Fa/UFiMoXdZag4cider2R9a648=",
"lastModified": 1755004716,
"narHash": "sha256-TbhPR5Fqw5LjAeI3/FOPhNNFQCF3cieKCJWWupeZmiA=",
"owner": "rust-lang",
"repo": "rust-analyzer",
"rev": "317542c1e4a3ec3467d21d1c25f6a43b80d83e7d",
"rev": "b2a58b8c6eff3c3a2c8b5c70dbf69ead78284194",
"type": "github"
},
"original": {

View File

@@ -24,7 +24,7 @@
{
file = ./rust-toolchain.toml;
#sha256 = nixpkgs.lib.fakeSha256;
sha256 = "sha256-Qxt8XAuaUR2OMdKbN4u8dBJOhSHxS+uS06Wl9+flVEk=";
sha256 = "sha256-+9FmLhAOezBZCOziO0Qct1NOrfpjNsXxc/8I0c7BdKE=";
};
craneLib = (crane.mkLib pkgs).overrideToolchain toolchain;

View File

@@ -121,6 +121,13 @@ alias dlt := demo-local-time
demo-local-time:
vhs demo/local-time.tape
alias dltf := demo-local-time-footer
# build demo: local time (footer)
[group('demo')]
demo-local-time-footer:
vhs demo/local-time-footer.tape
alias drc := demo-rocket-countdown
# build demo: rocket countdown

View File

@@ -1,6 +1,6 @@
[toolchain]
# Reminder: Always keep `rust-version` in `Cargo.toml` in sync with `channel`.
channel = "1.88.0"
channel = "1.89.0"
components = ["clippy", "rustfmt", "rust-src", "rust-analyzer"]
targets = ["x86_64-pc-windows-gnu", "x86_64-unknown-linux-musl"]
profile = "minimal"

View File

@@ -10,6 +10,7 @@ use crate::{
countdown::{Countdown, CountdownState, CountdownStateArgs},
footer::{Footer, FooterState},
header::Header,
local_time::{LocalTimeState, LocalTimeStateArgs, LocalTimeWidget},
pomodoro::{Mode as PomodoroMode, PomodoroState, PomodoroStateArgs, PomodoroWidget},
timer::{Timer, TimerState},
},
@@ -44,9 +45,11 @@ pub struct App {
#[allow(dead_code)] // w/ `--features sound` available only
sound_path: Option<PathBuf>,
app_time: AppTime,
app_time_format: AppTimeFormat,
countdown: CountdownState,
timer: TimerState,
pomodoro: PomodoroState,
local_time: LocalTimeState,
style: Style,
with_decis: bool,
footer: FooterState,
@@ -72,6 +75,7 @@ pub struct AppArgs {
pub current_value_timer: Duration,
pub app_tx: events::AppEventTx,
pub sound_path: Option<PathBuf>,
pub footer_toggle_app_time: Toggle,
}
pub struct FromAppArgs {
@@ -131,6 +135,7 @@ impl From<FromAppArgs> for App {
sound_path: args.sound,
#[cfg(not(feature = "sound"))]
sound_path: None,
footer_toggle_app_time: stg.footer_app_time,
})
}
}
@@ -164,6 +169,7 @@ impl App {
blink,
sound_path,
app_tx,
footer_toggle_app_time,
} = args;
let app_time = get_app_time();
@@ -174,6 +180,7 @@ impl App {
sound_path,
content,
app_time,
app_time_format,
style,
with_decis,
countdown: CountdownState::new(CountdownStateArgs {
@@ -204,7 +211,18 @@ impl App {
round: pomodoro_round,
app_tx: app_tx.clone(),
}),
footer: FooterState::new(show_menu, app_time_format),
local_time: LocalTimeState::new(LocalTimeStateArgs {
app_time,
app_time_format,
}),
footer: FooterState::new(
show_menu,
if footer_toggle_app_time == Toggle::On {
Some(app_time_format)
} else {
None
},
),
}
}
@@ -221,8 +239,39 @@ impl App {
KeyCode::Char('c') => app.content = Content::Countdown,
KeyCode::Char('t') => app.content = Content::Timer,
KeyCode::Char('p') => app.content = Content::Pomodoro,
KeyCode::Char('l') => app.content = Content::LocalTime,
// toogle app time format
KeyCode::Char(':') => app.footer.toggle_app_time_format(),
KeyCode::Char(':') => {
if app.content == Content::LocalTime {
// For LocalTime content: just cycle through formats
app.app_time_format = app.app_time_format.next();
app.local_time.set_app_time_format(app.app_time_format);
// Only update footer if it's currently showing time
if app.footer.app_time_format().is_some() {
app.footer.set_app_time_format(Some(app.app_time_format));
}
} else {
// For other content: allow footer to toggle between formats and None
let new_format = match app.footer.app_time_format() {
// footer is hidden -> show first format
None => Some(AppTimeFormat::first()),
Some(v) => {
if v != &AppTimeFormat::last() {
Some(v.next())
} else {
// reached last format -> hide footer time
None
}
}
};
if let Some(format) = new_format {
app.app_time_format = format;
app.local_time.set_app_time_format(format);
}
app.footer.set_app_time_format(new_format);
}
}
// toogle menu
KeyCode::Char('m') => app.footer.set_show_menu(!app.footer.get_show_menu()),
KeyCode::Char(',') => {
@@ -245,6 +294,7 @@ impl App {
if matches!(event, events::TuiEvent::Tick) {
app.app_time = get_app_time();
app.countdown.set_app_time(app.app_time);
app.local_time.set_app_time(app.app_time);
}
// Pipe events into subviews and handle only 'unhandled' events afterwards
@@ -252,6 +302,7 @@ impl App {
Content::Countdown => app.countdown.update(event.clone()),
Content::Timer => app.timer.update(event.clone()),
Content::Pomodoro => app.pomodoro.update(event.clone()),
Content::LocalTime => app.local_time.update(event.clone()),
} {
match unhandled {
events::TuiEvent::Render | events::TuiEvent::Resize => {
@@ -342,6 +393,7 @@ impl App {
AppEditMode::None
}
}
Content::LocalTime => AppEditMode::None,
}
}
@@ -350,6 +402,8 @@ impl App {
Content::Countdown => self.countdown.is_running(),
Content::Timer => self.timer.get_clock().is_running(),
Content::Pomodoro => self.pomodoro.get_clock().is_running(),
// `LocalTime` does not use a `Clock`
Content::LocalTime => false,
}
}
@@ -358,6 +412,7 @@ impl App {
Content::Countdown => Some(self.countdown.get_clock().get_percentage_done()),
Content::Timer => None,
Content::Pomodoro => Some(self.pomodoro.get_clock().get_percentage_done()),
Content::LocalTime => None,
}
}
@@ -374,7 +429,7 @@ impl App {
show_menu: self.footer.get_show_menu(),
notification: self.notification,
blink: self.blink,
app_time_format: *self.footer.app_time_format(),
app_time_format: self.app_time_format,
style: self.style,
with_decis: self.with_decis,
pomodoro_mode: self.pomodoro.get_mode().clone(),
@@ -393,6 +448,7 @@ impl App {
),
elapsed_value_countdown: Duration::from(*self.countdown.get_elapsed_value()),
current_value_timer: Duration::from(*self.timer.get_clock().get_current_value()),
footer_app_time: self.footer.app_time_format().is_some().into(),
}
}
}
@@ -419,6 +475,9 @@ impl AppWidget {
blink: state.blink == Toggle::On,
}
.render(area, buf, &mut state.pomodoro),
Content::LocalTime => {
LocalTimeWidget { style: state.style }.render(area, buf, &mut state.local_time);
}
};
}
}

View File

@@ -1,8 +1,8 @@
use clap::ValueEnum;
use ratatui::symbols::shade;
use serde::{Deserialize, Serialize};
use time::OffsetDateTime;
use time::format_description;
use strum::EnumString;
use time::{OffsetDateTime, format_description};
#[derive(
Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, ValueEnum, Default, Serialize, Deserialize,
@@ -15,6 +15,8 @@ pub enum Content {
Timer,
#[value(name = "pomodoro", alias = "p")]
Pomodoro,
#[value(name = "localtime", alias = "l")]
LocalTime,
}
#[derive(Clone, Debug)]
@@ -71,7 +73,7 @@ impl Style {
}
}
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize)]
#[derive(Debug, Clone, Copy, Default, PartialEq, EnumString, Serialize, Deserialize)]
pub enum AppTimeFormat {
/// `hh:mm:ss`
#[default]
@@ -80,17 +82,22 @@ pub enum AppTimeFormat {
HhMm,
/// `hh:mm AM` (or PM)
Hh12Mm,
/// `` (empty)
Hidden,
}
impl AppTimeFormat {
pub const fn first() -> Self {
Self::HhMmSs
}
pub const fn last() -> Self {
Self::Hh12Mm
}
pub fn next(&self) -> Self {
match self {
AppTimeFormat::HhMmSs => AppTimeFormat::HhMm,
AppTimeFormat::HhMm => AppTimeFormat::Hh12Mm,
AppTimeFormat::Hh12Mm => AppTimeFormat::Hidden,
AppTimeFormat::Hidden => AppTimeFormat::HhMmSs,
AppTimeFormat::Hh12Mm => AppTimeFormat::HhMmSs,
}
}
}
@@ -113,14 +120,12 @@ impl From<AppTime> for OffsetDateTime {
impl AppTime {
pub fn format(&self, app_format: &AppTimeFormat) -> String {
let parse_str = match app_format {
AppTimeFormat::HhMmSs => Some("[hour]:[minute]:[second]"),
AppTimeFormat::HhMm => Some("[hour]:[minute]"),
AppTimeFormat::Hh12Mm => Some("[hour repr:12 padding:none]:[minute] [period]"),
AppTimeFormat::Hidden => None,
AppTimeFormat::HhMmSs => "[hour]:[minute]:[second]",
AppTimeFormat::HhMm => "[hour]:[minute]",
AppTimeFormat::Hh12Mm => "[hour repr:12 padding:none]:[minute] [period]",
};
if let Some(str) = parse_str {
format_description::parse(str)
format_description::parse(parse_str)
.map_err(|_| "parse error")
.and_then(|fd| {
OffsetDateTime::from(*self)
@@ -128,9 +133,30 @@ impl AppTime {
.map_err(|_| "format error")
})
.unwrap_or_else(|e| e.to_string())
} else {
"".to_owned()
}
pub fn get_period(&self) -> String {
format_description::parse("[period]")
.map_err(|_| "parse error")
.and_then(|fd| {
OffsetDateTime::from(*self)
.format(&fd)
.map_err(|_| "format error")
})
.unwrap_or_else(|e| e.to_string())
}
/// Converts `AppTime` into a `Duration` representing elapsed time since midnight (today).
pub fn as_duration_of_today(&self) -> std::time::Duration {
let dt = OffsetDateTime::from(*self);
let time = dt.time();
let total_nanos = u64::from(time.hour()) * 3_600_000_000_000
+ u64::from(time.minute()) * 60_000_000_000
+ u64::from(time.second()) * 1_000_000_000
+ u64::from(time.nanosecond());
std::time::Duration::from_nanos(total_nanos)
}
}
@@ -150,6 +176,15 @@ pub enum Toggle {
Off,
}
impl From<bool> for Toggle {
fn from(value: bool) -> Self {
match value {
true => Toggle::On,
false => Toggle::Off,
}
}
}
#[cfg(test)]
mod tests {
@@ -196,12 +231,5 @@ mod tests {
"6:06 PM",
"local"
);
// hidden
assert_eq!(AppTime::Utc(dt).format(&AppTimeFormat::Hidden), "", "utc");
assert_eq!(
AppTime::Local(dt).format(&AppTimeFormat::Hidden),
"",
"local"
);
}
}

View File

@@ -60,10 +60,19 @@ impl DurationEx {
self.seconds() / (SECS_PER_MINUTE * MINS_PER_HOUR)
}
/// Hours as 24-hour clock
pub fn hours_mod(&self) -> u64 {
self.hours() % HOURS_PER_DAY
}
/// Hours as 12-hour clock
pub fn hours_mod_12(&self) -> u64 {
// 0 => 12,
// 1..=12 => hours,
// 13..=23 => hours - 12,
(self.hours_mod() + 11) % 12 + 1
}
pub fn minutes(&self) -> u64 {
self.seconds() / MINS_PER_HOUR
}
@@ -211,6 +220,34 @@ mod tests {
assert_eq!(format!("{ex3}"), "11");
}
#[test]
fn test_hours_mod_12() {
// 24 -> 12
let ex: DurationEx = ONE_HOUR.saturating_mul(24).into();
let result = ex.hours_mod_12();
assert_eq!(result, 12);
// 12 -> 12
let ex: DurationEx = ONE_HOUR.saturating_mul(12).into();
let result = ex.hours_mod_12();
assert_eq!(result, 12);
// 0 -> 12
let ex: DurationEx = ONE_SECOND.into();
let result = ex.hours_mod_12();
assert_eq!(result, 12);
// 13 -> 1
let ex: DurationEx = ONE_HOUR.saturating_mul(13).into();
let result = ex.hours_mod_12();
assert_eq!(result, 1);
// 1 -> 1
let ex: DurationEx = ONE_HOUR.saturating_mul(1).into();
let result = ex.hours_mod_12();
assert_eq!(result, 1);
}
#[test]
fn test_parse_duration() {
// ss

View File

@@ -3,17 +3,30 @@ use crate::{
widgets::pomodoro::Mode as PomodoroMode,
};
use color_eyre::eyre::Result;
use serde::{Deserialize, Serialize};
use serde::{Deserialize, Deserializer, Serialize};
use std::fs;
use std::path::PathBuf;
use std::time::Duration;
fn deserialize_app_time_format<'de, D>(deserializer: D) -> Result<AppTimeFormat, D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
match s.as_str() {
// Hidden is deprecated - use `default` value instead
"Hidden" => Ok(AppTimeFormat::default()),
_ => s.parse().map_err(serde::de::Error::custom),
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct AppStorage {
pub content: Content,
pub show_menu: bool,
pub notification: Toggle,
pub blink: Toggle,
#[serde(deserialize_with = "deserialize_app_time_format")]
pub app_time_format: AppTimeFormat,
pub style: Style,
pub with_decis: bool,
@@ -31,6 +44,8 @@ pub struct AppStorage {
pub elapsed_value_countdown: Duration,
// timer
pub current_value_timer: Duration,
// footer
pub footer_app_time: Toggle,
}
impl Default for AppStorage {
@@ -60,6 +75,8 @@ impl Default for AppStorage {
elapsed_value_countdown: Duration::ZERO,
// timer
current_value_timer: Duration::ZERO,
// footer
footer_app_time: Toggle::Off,
}
}
}

View File

@@ -8,6 +8,7 @@ pub mod countdown;
pub mod edit_time;
pub mod footer;
pub mod header;
pub mod local_time;
pub mod pomodoro;
pub mod progressbar;
pub mod timer;

View File

@@ -13,11 +13,11 @@ use ratatui::{
#[derive(Debug, Clone)]
pub struct FooterState {
show_menu: bool,
app_time_format: AppTimeFormat,
app_time_format: Option<AppTimeFormat>,
}
impl FooterState {
pub const fn new(show_menu: bool, app_time_format: AppTimeFormat) -> Self {
pub const fn new(show_menu: bool, app_time_format: Option<AppTimeFormat>) -> Self {
Self {
show_menu,
app_time_format,
@@ -32,12 +32,12 @@ impl FooterState {
self.show_menu
}
pub const fn app_time_format(&self) -> &AppTimeFormat {
pub const fn app_time_format(&self) -> &Option<AppTimeFormat> {
&self.app_time_format
}
pub fn toggle_app_time_format(&mut self) {
self.app_time_format = self.app_time_format.next();
pub const fn set_app_time_format(&mut self, value: Option<AppTimeFormat>) {
self.app_time_format = value;
}
}
@@ -56,6 +56,7 @@ impl StatefulWidget for Footer {
(Content::Countdown, "[c]ountdown"),
(Content::Timer, "[t]imer"),
(Content::Pomodoro, "[p]omodoro"),
(Content::LocalTime, "[l]ocal time"),
]);
let [_, area] =
@@ -71,11 +72,12 @@ impl StatefulWidget for Footer {
)
.title(
Line::from(
match state.app_time_format {
// `Hidden` -> no (empty) title
AppTimeFormat::Hidden => "".into(),
// others -> add some space around
_ => format!(" {} ", self.app_time.format(&state.app_time_format))
match (state.app_time_format, self.selected_content) {
// Show time
(Some(v), content) if content != Content::LocalTime => format!(" {} " // add some space around
, self.app_time.format(&v)),
// Hide time -> empty
_ => "".into(),
}
).right_aligned())
.border_set(border::PLAIN)
@@ -102,8 +104,7 @@ impl StatefulWidget for Footer {
const SPACE: &str = " "; // 2 empty spaces
let widths = [Constraint::Length(12), Constraint::Percentage(100)];
let table = Table::new(
[
let mut table_rows = vec![
// screens
Row::new(vec![
Cell::from(Span::styled(
@@ -132,6 +133,10 @@ impl StatefulWidget for Footer {
)),
])),
]),
];
if self.selected_content != Content::LocalTime {
table_rows.extend_from_slice(&[
// controls - 1. row
Row::new(vec![
Cell::from(Span::styled(
@@ -224,10 +229,10 @@ impl StatefulWidget for Footer {
}
})),
]),
],
widths,
)
.column_spacing(1);
])
}
let table = Table::new(table_rows, widths).column_spacing(1);
Widget::render(table, menu_area, buf);
}

185
src/widgets/local_time.rs Normal file
View File

@@ -0,0 +1,185 @@
use ratatui::{
buffer::Buffer,
layout::{Constraint, Layout, Rect},
style::{Modifier, Style},
text::{Line, Span},
widgets::{StatefulWidget, Widget},
};
use crate::{
common::{AppTime, AppTimeFormat, Style as DigitStyle},
duration::DurationEx,
events::{TuiEvent, TuiEventHandler},
utils::center,
widgets::clock_elements::{
COLON_WIDTH, Colon, DIGIT_HEIGHT, DIGIT_SPACE_WIDTH, DIGIT_WIDTH, Digit,
},
};
use std::cmp::max;
/// State for `LocalTimeWidget`
pub struct LocalTimeState {
time: AppTime,
format: AppTimeFormat,
}
pub struct LocalTimeStateArgs {
pub app_time: AppTime,
pub app_time_format: AppTimeFormat,
}
impl LocalTimeState {
pub fn new(args: LocalTimeStateArgs) -> Self {
let LocalTimeStateArgs {
app_time,
app_time_format,
} = args;
Self {
time: app_time,
format: app_time_format,
}
}
pub fn set_app_time(&mut self, app_time: AppTime) {
self.time = app_time;
}
pub fn set_app_time_format(&mut self, format: AppTimeFormat) {
self.format = format;
}
}
impl TuiEventHandler for LocalTimeState {
fn update(&mut self, event: TuiEvent) -> Option<TuiEvent> {
Some(event)
}
}
#[derive(Debug)]
pub struct LocalTimeWidget {
pub style: DigitStyle,
}
impl LocalTimeWidget {
fn get_horizontal_lengths(&self, format: &AppTimeFormat) -> Vec<u16> {
const PERIOD_WIDTH: u16 = 2; // PM or AM
match format {
AppTimeFormat::HhMmSs => vec![
DIGIT_WIDTH, // H
DIGIT_SPACE_WIDTH, // (space)
DIGIT_WIDTH, // h
COLON_WIDTH, // :
DIGIT_WIDTH, // M
DIGIT_SPACE_WIDTH, // (space)
DIGIT_WIDTH, // m
COLON_WIDTH, // :
DIGIT_WIDTH, // S
DIGIT_SPACE_WIDTH, // (space)
DIGIT_WIDTH, // s
],
AppTimeFormat::HhMm => vec![
DIGIT_WIDTH, // H
DIGIT_SPACE_WIDTH, // (space)
DIGIT_WIDTH, // h
COLON_WIDTH, // :
DIGIT_WIDTH, // M
DIGIT_SPACE_WIDTH, // (space)
DIGIT_WIDTH, // m
],
AppTimeFormat::Hh12Mm => vec![
DIGIT_SPACE_WIDTH + PERIOD_WIDTH, // (space) + (empty period) to center everything well horizontally
DIGIT_WIDTH, // H
DIGIT_SPACE_WIDTH, // (space)
DIGIT_WIDTH, // h
COLON_WIDTH, // :
DIGIT_WIDTH, // M
DIGIT_SPACE_WIDTH, // (space)
DIGIT_WIDTH, // m
DIGIT_SPACE_WIDTH, // (space)
PERIOD_WIDTH, // period
],
}
}
}
impl StatefulWidget for LocalTimeWidget {
type State = LocalTimeState;
fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
let current_value: DurationEx = state.time.as_duration_of_today().into();
let hours = current_value.hours_mod();
let hours12 = current_value.hours_mod_12();
let minutes = current_value.minutes_mod();
let seconds = current_value.seconds_mod();
let symbol = self.style.get_digit_symbol();
let label = Line::raw("Local Time".to_uppercase());
let format = state.format;
let widths = self.get_horizontal_lengths(&format);
let mut widths = widths;
// Special case for `Hh12Mm`
// It might be `h:Mm` OR `Hh:Mm` depending on `hours12`
if state.format == AppTimeFormat::Hh12Mm && hours12 < 10 {
// single digit means, no (zero) width's for `H` and `space`
widths[1] = 0; // `H`
widths[2] = 0; // `space`
}
let width = widths.iter().sum();
let area = center(
area,
Constraint::Length(max(width, label.width() as u16)),
Constraint::Length(DIGIT_HEIGHT + 1 /* height of label */),
);
let [v1, v2] = Layout::vertical(Constraint::from_lengths([DIGIT_HEIGHT, 1])).areas(area);
match state.format {
AppTimeFormat::HhMmSs => {
let [hh, _, h, c_hm, mm, _, m, c_ms, ss, _, s] =
Layout::horizontal(Constraint::from_lengths(widths)).areas(v1);
Digit::new(hours / 10, false, symbol).render(hh, buf);
Digit::new(hours % 10, false, symbol).render(h, buf);
Colon::new(symbol).render(c_hm, buf);
Digit::new(minutes / 10, false, symbol).render(mm, buf);
Digit::new(minutes % 10, false, symbol).render(m, buf);
Colon::new(symbol).render(c_ms, buf);
Digit::new(seconds / 10, false, symbol).render(ss, buf);
Digit::new(seconds % 10, false, symbol).render(s, buf);
}
AppTimeFormat::HhMm => {
let [hh, _, h, c_hm, mm, _, m] =
Layout::horizontal(Constraint::from_lengths(widths)).areas(v1);
Digit::new(hours / 10, false, symbol).render(hh, buf);
Digit::new(hours % 10, false, symbol).render(h, buf);
Colon::new(symbol).render(c_hm, buf);
Digit::new(minutes / 10, false, symbol).render(mm, buf);
Digit::new(minutes % 10, false, symbol).render(m, buf);
}
AppTimeFormat::Hh12Mm => {
let [_, hh, _, h, c_hm, mm, _, m, _, p] =
Layout::horizontal(Constraint::from_lengths(widths)).areas(v1);
// Hh
if hours12 >= 10 {
Digit::new(hours12 / 10, false, symbol).render(hh, buf);
Digit::new(hours12 % 10, false, symbol).render(h, buf);
}
// h
else {
Digit::new(hours12, false, symbol).render(h, buf);
}
Colon::new(symbol).render(c_hm, buf);
Digit::new(minutes / 10, false, symbol).render(mm, buf);
Digit::new(minutes % 10, false, symbol).render(m, buf);
Span::styled(
state.time.get_period().to_uppercase(),
Style::default().add_modifier(Modifier::BOLD),
)
.render(p, buf);
}
}
label.centered().render(v2, buf);
}
}