initial commit
This commit is contained in:
commit
d6990ac8f7
9 changed files with 2784 additions and 0 deletions
22
.gitignore
vendored
Normal file
22
.gitignore
vendored
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
# ---> Rust
|
||||
# Generated by Cargo
|
||||
# will have compiled files and executables
|
||||
debug/
|
||||
target/
|
||||
|
||||
# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries
|
||||
# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html
|
||||
Cargo.lock
|
||||
|
||||
# These are backup files generated by rustfmt
|
||||
**/*.rs.bk
|
||||
|
||||
# MSVC Windows builds of rustc generate these, which store debugging information
|
||||
*.pdb
|
||||
|
||||
# RustRover
|
||||
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
||||
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
||||
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
||||
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
||||
#.idea/
|
||||
2350
Cargo.lock
generated
Normal file
2350
Cargo.lock
generated
Normal file
File diff suppressed because it is too large
Load diff
15
Cargo.toml
Normal file
15
Cargo.toml
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
[package]
|
||||
name = "ttz"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
chrono = "0.4.44"
|
||||
chrono-tz = { version = "0.10.4", features = ["case-insensitive"] }
|
||||
clap = { version = "4.6.1", features = ["derive", "env"] }
|
||||
color-eyre = "0.6.5"
|
||||
crossterm = "0.29.0"
|
||||
kdl = "6.7.0"
|
||||
ratatui = "0.30.0"
|
||||
ratatui-textarea = "0.9.1"
|
||||
unidecode = "0.3.0"
|
||||
9
LICENSE
Normal file
9
LICENSE
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
MIT License
|
||||
|
||||
Copyright (c) 2026 Brent Schroeter (https://brentsch.com)
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
1
README.md
Normal file
1
README.md
Normal file
|
|
@ -0,0 +1 @@
|
|||
# Team Time Zones
|
||||
2
mise.toml
Normal file
2
mise.toml
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
[tools]
|
||||
rust = { version = "nightly", components = "rust-analyzer,rust-docs,rustfmt,clippy" }
|
||||
92
src/config.rs
Normal file
92
src/config.rs
Normal file
|
|
@ -0,0 +1,92 @@
|
|||
use std::{
|
||||
env,
|
||||
ffi::{OsStr, OsString},
|
||||
fs,
|
||||
path::PathBuf,
|
||||
};
|
||||
|
||||
use chrono_tz::Tz;
|
||||
use color_eyre::{
|
||||
Result,
|
||||
eyre::{Context as _, eyre},
|
||||
};
|
||||
use kdl::KdlDocument;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct Config {
|
||||
pub(crate) locations: Vec<Location>,
|
||||
}
|
||||
|
||||
impl Config {
|
||||
/// Reads ttz.kdl config from a file.
|
||||
///
|
||||
/// Uses the provided path if `Some`; otherwise defaults to `ttz.kdl` within
|
||||
/// `$XDG_CONFIG_HOME` if set or `~/.config` if not.
|
||||
pub(crate) fn load_from_file(file_path: Option<&OsStr>) -> Result<Self> {
|
||||
let default_file_path: Result<OsString> = env::var("XDG_CONFIG_HOME")
|
||||
.ok()
|
||||
.map(Into::<PathBuf>::into)
|
||||
.or(env::home_dir().map(|mut buf| {
|
||||
buf.push(".config");
|
||||
buf
|
||||
}))
|
||||
.map(|mut buf| {
|
||||
buf.push("ttz.kdl");
|
||||
buf.into()
|
||||
})
|
||||
.ok_or(eyre!("Unable to determine config home"));
|
||||
let file_path = if let Some(file_path) = file_path {
|
||||
file_path
|
||||
} else {
|
||||
&default_file_path?
|
||||
};
|
||||
if !fs::exists(file_path)? {
|
||||
return Err(eyre!("Unable to find config file"));
|
||||
}
|
||||
let config_raw = fs::read_to_string(file_path)?;
|
||||
|
||||
let doc: KdlDocument = config_raw
|
||||
.parse()
|
||||
.wrap_err(eyre!("Unable to parse config file"))?;
|
||||
|
||||
let mut locations: Vec<Location> = Vec::with_capacity(doc.nodes().len());
|
||||
for node in doc.nodes() {
|
||||
if node.name().value() != "location" {
|
||||
return Err(eyre!(
|
||||
"Config parse error: only `location` nodes are allowed"
|
||||
));
|
||||
}
|
||||
let name = node
|
||||
.entry(0)
|
||||
.and_then(|entry| entry.value().as_string())
|
||||
.ok_or(eyre!(
|
||||
"Config parse error: each node must have an argument for its name"
|
||||
))?
|
||||
.to_owned();
|
||||
let tz_raw: &str = node
|
||||
.entry("tz")
|
||||
.ok_or(eyre!(
|
||||
"Config parse error: each node must have a `tz` property"
|
||||
))?
|
||||
.value()
|
||||
.as_string()
|
||||
.ok_or(eyre!("Config parse error: tz must be a string"))?;
|
||||
let tz: Tz = tz_raw.parse().wrap_err(eyre!(
|
||||
"Config parse error: not a chrono-tz time zone: {tz_raw}",
|
||||
))?;
|
||||
locations.push(Location { name, tz })
|
||||
}
|
||||
if locations.is_empty() {
|
||||
return Err(eyre!(
|
||||
"Config parse error: must have at least one `location`"
|
||||
));
|
||||
}
|
||||
Ok(Self { locations })
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct Location {
|
||||
pub(crate) name: String,
|
||||
pub(crate) tz: Tz,
|
||||
}
|
||||
289
src/main.rs
Normal file
289
src/main.rs
Normal file
|
|
@ -0,0 +1,289 @@
|
|||
//! A simple CLI app for displaying rich 24 hour time information for multiple
|
||||
//! people and/or time zones.
|
||||
|
||||
mod config;
|
||||
|
||||
use std::{ffi::OsString, io, time::Duration};
|
||||
|
||||
use chrono::{NaiveTime, TimeDelta, Timelike, Utc, offset::LocalResult};
|
||||
use chrono_tz::Tz;
|
||||
use clap::Parser;
|
||||
use crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
|
||||
use ratatui::{
|
||||
DefaultTerminal,
|
||||
prelude::*,
|
||||
symbols::border,
|
||||
widgets::{Block, BorderType::Rounded, Cell, Padding, Row, Table, TableState},
|
||||
};
|
||||
use ratatui_textarea::{Input, TextArea};
|
||||
use unidecode::unidecode;
|
||||
|
||||
use crate::config::{Config, Location};
|
||||
|
||||
/// A simple CLI app for displaying rich 24 hour time information for multiple
|
||||
/// people and/or time zones.
|
||||
#[derive(Debug, Parser)]
|
||||
#[command(version, about, long_about = None)]
|
||||
struct Args {
|
||||
/// Path to config; defaults to $XDG_CONFIG/ttz.kdl or ~/.config/ttz.kdl
|
||||
#[arg(short, long, env = "TTZ_CONFIG")]
|
||||
config_file: Option<OsString>,
|
||||
}
|
||||
|
||||
fn main() -> color_eyre::Result<()> {
|
||||
color_eyre::install()?;
|
||||
let args = Args::parse();
|
||||
let config = Config::load_from_file(args.config_file.as_deref())?;
|
||||
ratatui::run(|term| run(term, config))
|
||||
}
|
||||
|
||||
/// TUI render loop.
|
||||
fn run(terminal: &mut DefaultTerminal, config: Config) -> color_eyre::Result<()> {
|
||||
let mut model = Model::from_config(config);
|
||||
|
||||
while model.running_state != RunningState::Done {
|
||||
terminal.draw(|f| view(&mut model, f))?;
|
||||
|
||||
// Handle events and map to a Message
|
||||
let mut current_msg = handle_event(&model)?;
|
||||
|
||||
// Process updates as long as they return a non-None message
|
||||
while current_msg.is_some() {
|
||||
current_msg = update(&mut model, current_msg.unwrap());
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// App-wide Elm model.
|
||||
#[derive(Debug)]
|
||||
struct Model<'a> {
|
||||
config: Config,
|
||||
table_state: TableState,
|
||||
running_state: RunningState,
|
||||
focus_state: FocusState,
|
||||
filter_textarea: TextArea<'a>,
|
||||
}
|
||||
|
||||
impl<'a> Model<'a> {
|
||||
fn from_config(config: Config) -> Self {
|
||||
Self {
|
||||
config,
|
||||
table_state: Default::default(),
|
||||
running_state: Default::default(),
|
||||
focus_state: Default::default(),
|
||||
filter_textarea: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Eq, PartialEq)]
|
||||
enum RunningState {
|
||||
#[default]
|
||||
Running,
|
||||
Done,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Eq, PartialEq)]
|
||||
enum FocusState {
|
||||
#[default]
|
||||
Table,
|
||||
Filter,
|
||||
}
|
||||
|
||||
enum Message {
|
||||
Quit,
|
||||
FilterOpened,
|
||||
FilterCancelled,
|
||||
FilterUpdated(Input),
|
||||
}
|
||||
|
||||
fn handle_event(model: &Model) -> io::Result<Option<Message>> {
|
||||
Ok(if event::poll(Duration::from_secs(5))? {
|
||||
match event::read()? {
|
||||
Event::Key(key_event) if key_event.kind == KeyEventKind::Press => {
|
||||
handle_key_event(model, key_event)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
} else {
|
||||
// Skip event handling and proceed to render so that the current time
|
||||
// highlight stays up to date.
|
||||
None
|
||||
})
|
||||
}
|
||||
|
||||
fn handle_key_event(model: &Model, key_event: KeyEvent) -> Option<Message> {
|
||||
match (&model.focus_state, key_event.code) {
|
||||
(_, KeyCode::Char('c')) if key_event.modifiers.contains(KeyModifiers::CONTROL) => {
|
||||
Some(Message::Quit)
|
||||
}
|
||||
(FocusState::Table, KeyCode::Char('q')) => Some(Message::Quit),
|
||||
(FocusState::Table, KeyCode::Char('/')) => Some(Message::FilterOpened),
|
||||
(FocusState::Filter, KeyCode::Esc) | (FocusState::Filter, KeyCode::Enter) => {
|
||||
Some(Message::FilterCancelled)
|
||||
}
|
||||
// Ignore input that creates newlines.
|
||||
(FocusState::Filter, KeyCode::Char('m'))
|
||||
if key_event.modifiers.contains(KeyModifiers::CONTROL)
|
||||
&& !key_event.modifiers.contains(KeyModifiers::ALT) =>
|
||||
{
|
||||
None
|
||||
}
|
||||
(FocusState::Filter, _) => Some(Message::FilterUpdated(key_event.into())),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Elm update function.
|
||||
fn update(model: &mut Model, msg: Message) -> Option<Message> {
|
||||
match msg {
|
||||
Message::Quit => model.running_state = RunningState::Done,
|
||||
Message::FilterOpened => model.focus_state = FocusState::Filter,
|
||||
Message::FilterCancelled => {
|
||||
model.focus_state = FocusState::Table;
|
||||
model.filter_textarea.clear();
|
||||
}
|
||||
Message::FilterUpdated(input) => {
|
||||
model.filter_textarea.input(input);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Elm render function.
|
||||
fn view(model: &mut Model, frame: &mut Frame) {
|
||||
let title = Line::from(" Team Time Zones ".bold());
|
||||
let instructions = Line::from(vec![
|
||||
" Filter ".into(),
|
||||
"/".blue().bold(),
|
||||
" Quit ".into(),
|
||||
"Q ".blue().bold(),
|
||||
]);
|
||||
let block = Block::bordered()
|
||||
.title(title.centered().fg(Color::Reset))
|
||||
.title_bottom(instructions.centered().fg(Color::Reset))
|
||||
.border_set(border::PLAIN)
|
||||
.border_style(Style::new().fg(Color::DarkGray))
|
||||
.border_type(Rounded)
|
||||
.padding(Padding::horizontal(2));
|
||||
|
||||
let visible_locations: Vec<&Location> = if model.focus_state == FocusState::Filter {
|
||||
let filter_terms: Vec<String> = model
|
||||
.filter_textarea
|
||||
.clone()
|
||||
.into_lines()
|
||||
.into_iter()
|
||||
.next()
|
||||
.unwrap_or_default()
|
||||
.split('|')
|
||||
.map(|value| value.trim().to_owned())
|
||||
.collect();
|
||||
model
|
||||
.config
|
||||
.locations
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(i, location)| {
|
||||
*i == 0
|
||||
|| filter_terms.iter().any(|filter_term| {
|
||||
unidecode(&location.name.to_ascii_lowercase())
|
||||
.contains(&unidecode(&filter_term.to_ascii_lowercase()))
|
||||
})
|
||||
})
|
||||
.map(|(_, value)| value)
|
||||
.collect()
|
||||
} else {
|
||||
model.config.locations.iter().collect()
|
||||
};
|
||||
|
||||
let header = Row::new(
|
||||
visible_locations
|
||||
.iter()
|
||||
.map(|location| location.name.as_str())
|
||||
.collect::<Vec<&str>>(),
|
||||
)
|
||||
.cyan()
|
||||
.bold();
|
||||
let col_widths: Vec<Constraint> = visible_locations
|
||||
.iter()
|
||||
.map(|location| Constraint::Length(clamp_u16(location.name.len(), 5, 32)))
|
||||
.collect();
|
||||
|
||||
let mut rows: Vec<Row> = Vec::with_capacity(24);
|
||||
let home_tz = visible_locations
|
||||
.first()
|
||||
.expect("should always be at least one location loaded and visible")
|
||||
.tz;
|
||||
let now = Utc::now();
|
||||
let mut home_datetime = match now
|
||||
.with_timezone(&home_tz)
|
||||
.with_time(NaiveTime::from_hms_opt(0, 0, 0).expect("00:00:00 is a valid time"))
|
||||
{
|
||||
LocalResult::Single(datetime) | LocalResult::Ambiguous(datetime, _) => datetime,
|
||||
LocalResult::None => {
|
||||
// TODO: display error
|
||||
return;
|
||||
}
|
||||
};
|
||||
for _ in 0..24 {
|
||||
let is_current_time = now.with_timezone(&Tz::UTC) - home_datetime > TimeDelta::zero()
|
||||
&& now.with_timezone(&Tz::UTC) - home_datetime < TimeDelta::minutes(60);
|
||||
rows.push(
|
||||
Row::new(visible_locations.iter().map(|Location { tz, .. }| {
|
||||
let col_datetime = home_datetime.with_timezone(tz);
|
||||
let is_daylight = col_datetime.hour() >= 9 && col_datetime.hour() <= 16;
|
||||
Cell::new(col_datetime.format("%H:%M").to_string()).style(
|
||||
if is_current_time || is_daylight {
|
||||
Style::new()
|
||||
} else {
|
||||
Style::new().fg(Color::DarkGray)
|
||||
},
|
||||
)
|
||||
}))
|
||||
.style(if is_current_time {
|
||||
Style::new().red()
|
||||
} else {
|
||||
Style::new()
|
||||
}),
|
||||
);
|
||||
home_datetime += TimeDelta::hours(1);
|
||||
}
|
||||
|
||||
let table = Table::new(rows, col_widths)
|
||||
.header(header)
|
||||
.block(block)
|
||||
.column_spacing(4);
|
||||
|
||||
let layout = Layout::vertical([
|
||||
Constraint::Fill(1),
|
||||
Constraint::Length(if model.focus_state == FocusState::Filter {
|
||||
1
|
||||
} else {
|
||||
0
|
||||
}),
|
||||
]);
|
||||
let [table_area, filter_area] = layout.areas(frame.area());
|
||||
if model.focus_state == FocusState::Filter {
|
||||
frame.render_widget(&model.filter_textarea, filter_area);
|
||||
}
|
||||
frame.render_stateful_widget(table, table_area, &mut model.table_state);
|
||||
}
|
||||
|
||||
/// Clip a [`usize`]-like value to between two [`u16`]s (inclusive).
|
||||
fn clamp_u16<T>(value: T, min: u16, max: u16) -> u16
|
||||
where
|
||||
T: Into<usize>,
|
||||
{
|
||||
let value: usize = value.into();
|
||||
if value <= min.into() {
|
||||
min
|
||||
} else if value >= max.into() {
|
||||
max
|
||||
} else {
|
||||
value
|
||||
.try_into()
|
||||
.expect("value is known to be unsigned and less than some valid u16")
|
||||
}
|
||||
}
|
||||
4
ttz.example.kdl
Normal file
4
ttz.example.kdl
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
location Oakland tz="America/Los_Angeles"
|
||||
location UTC tz="UTC"
|
||||
// Unclear why this is +8 and not -8.
|
||||
location "Pacific Standard Time" tz="Etc/GMT+8"
|
||||
Loading…
Add table
Reference in a new issue