use jiff::{Timestamp, TimestampRound, tz::TimeZone}; use smol::{LocalExecutor, channel::Sender}; use std::{cell::RefCell, rc::Rc}; use crate::bar::{component::Value, module::Data}; pub struct Clock; impl Clock { pub fn run(executor: &LocalExecutor<'static>, data: Rc>, tx: Sender<()>) { let future = async move { loop { let time = Timestamp::now().to_zoned(TimeZone::system()); let mut data = data.borrow_mut(); data.update_tick(); data.update_value("clock.yyyy", || { Value::String(format!("{:04}", time.year())) }); data.update_value("clock.mm", || Value::String(format!("{:02}", time.month()))); data.update_value("clock.dd", || Value::String(format!("{:02}", time.day()))); data.update_value("clock.hr", || Value::String(format!("{:02}", time.hour()))); data.update_value("clock.min", || { Value::String(format!("{:02}", time.minute())) }); data.update_value("clock.sec", || { Value::String(format!("{:02}", time.second())) }); data.update_value("clock.hr-12", || { let mut hour = time.hour(); if hour > 12 { hour -= 12; } else if hour == 0 { hour = 12; } Value::String(format!("{:02}", hour)) }); data.update_value("clock.am/pm", || { Value::String(String::from(if time.hour() >= 12 { "PM" } else { "AM" })) }); drop(data); tx.try_send(())?; let next = Timestamp::now().round( TimestampRound::new() .mode(jiff::RoundMode::Ceil) .smallest(jiff::Unit::Second), )?; let waiting_time = Timestamp::now().duration_until(next).try_into()?; smol::Timer::after(waiting_time).await; } #[expect(unreachable_code, reason = "type inference")] Ok::<(), Box>(()) }; executor.spawn(future).detach(); } }