refactor(cli-rs): share the activity calendar with the stats poster

The TUI /stats poster had its own activityCalendar port and time zone
lookup. Move C.3's activity_calendar and time_zone, with the TS oracle
test, to opencode-ui and use them in both. Number formatting stays
apart: TS uses formatNumber in the CLI and statsNumber in the TUI.
This commit is contained in:
Simon Klee
2026-11-05 00:47:58 +01:00
Unverified
parent c873c5c556
commit 5607de3a87
6 changed files with 245 additions and 381 deletions
+1
View File
@@ -1328,6 +1328,7 @@ dependencies = [
name = "opencode-ui"
version = "0.1.0"
dependencies = [
"chrono",
"indexmap",
"log",
"opencode-api",
@@ -8,7 +8,8 @@ use std::time::Duration;
use chrono::{DateTime, Datelike, Local, NaiveDate, TimeZone};
use opencode_api::client::{Call, RequestOptions};
use opencode_api::error::Error as ApiError;
use opencode_api::generated::types::{SessionStatsActivity, SessionStatsInfo, SessionStatsTools};
use opencode_api::generated::types::{SessionStatsInfo, SessionStatsTools};
use opencode_ui::activity_calendar::{activity_calendar, time_zone};
use serde_json::Value;
use super::Context;
@@ -135,56 +136,6 @@ fn message(error: &anyhow::Error) -> String {
}
}
/// `Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC"` as Bun resolves it: `TZ` (an empty
/// value is UTC), else the zone `/etc/localtime` links to. ICU's names for UTC become `UTC`, and a
/// zone without tz data falls back to `UTC`.
fn time_zone() -> String {
let name = match std::env::var("TZ") {
Ok(value) => value.trim_start_matches(':').to_owned(),
Err(_) => std::fs::read_link("/etc/localtime")
.ok()
.and_then(|link| {
let link = link.to_string_lossy().into_owned();
link.split_once("zoneinfo/")
.map(|(_, name)| name.to_owned())
})
.unwrap_or_default(),
};
const UTC: [&str; 14] = [
"",
"UTC",
"UCT",
"GMT",
"GMT0",
"GMT+0",
"GMT-0",
"Greenwich",
"Universal",
"Zulu",
"Etc/UTC",
"Etc/UCT",
"Etc/GMT",
"Etc/Universal",
];
if UTC.contains(&name.as_str())
|| [
"Etc/GMT0",
"Etc/GMT+0",
"Etc/GMT-0",
"Etc/Greenwich",
"Etc/Zulu",
]
.contains(&name.as_str())
|| name.starts_with('/')
|| !std::path::Path::new("/usr/share/zoneinfo")
.join(&name)
.is_file()
{
return "UTC".to_owned();
}
name
}
// `process.stdout.columns`: set only when stdout is a terminal.
fn columns() -> Option<usize> {
let stdout = std::io::stdout();
@@ -253,133 +204,6 @@ fn local_midnight<Tz: TimeZone>(zone: &Tz, date: NaiveDate) -> i64 {
.map_or(0, |time| time.timestamp_millis())
}
/// One cell of the calendar: `level` is -1 outside the range, 0 without steps, else 1 to 4.
#[derive(Debug, Clone, PartialEq)]
pub struct Day {
pub date: String,
pub steps: i64,
pub level: i64,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Month {
pub week: usize,
pub label: &'static str,
pub span: usize,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Calendar {
pub weeks: Vec<[Day; 7]>,
pub months: Vec<Month>,
pub clipped: bool,
}
const MONTHS: [&str; 12] = [
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
];
/// `activityCalendar`: Monday-first weeks covering `[from, to)` in `zone`'s local dates, the latest
/// `max_weeks` of them (at most 53), with month labels.
pub fn activity_calendar<Tz: TimeZone>(
zone: &Tz,
activity: &[SessionStatsActivity],
from: i64,
to: i64,
max_weeks: f64,
) -> Calendar {
// Local dates first, then day ordinals, so DST cannot add or drop cells.
let ordinal = |time: i64| {
DateTime::from_timestamp_millis(time).map_or(0, |time| {
i64::from(time.with_timezone(zone).date_naive().num_days_from_ce()) - EPOCH_DAYS
})
};
let first = ordinal(from);
let last = ordinal(to - 1);
let monday = first - i64::from(date(first).weekday().num_days_from_monday());
let total = if to <= from {
0
} else {
(last - monday).div_euclid(7) + 1
};
let count = total.min(53).min((max_weeks.floor() as i64).max(1));
let start = monday + (total - count).max(0) * 7;
let mut values: Vec<(&str, i64)> = Vec::new();
for day in activity {
match values.iter_mut().find(|(date, _)| *date == day.date) {
Some(entry) => entry.1 = day.steps,
None => values.push((&day.date, day.steps)),
}
}
let mut levels: Vec<i64> = values
.iter()
.map(|(_, steps)| *steps)
.filter(|steps| *steps > 0)
.collect();
levels.sort_unstable();
levels.dedup();
let weeks = (0..count)
.map(|week| {
std::array::from_fn(|day| {
let ordinal = start + week * 7 + day as i64;
let key = date(ordinal).format("%Y-%m-%d").to_string();
let steps = values
.iter()
.find(|(date, _)| *date == key)
.map_or(0, |(_, steps)| *steps);
let level = if ordinal < first || ordinal > last {
-1
} else if steps == 0 {
0
} else {
let rank = levels.iter().position(|level| *level == steps);
let rank = rank.map_or(0, |rank| rank as i64 + 1) as f64;
((rank / levels.len() as f64 * 4.0).ceil() as i64).max(1)
};
Day {
date: key,
steps,
level,
}
})
})
.collect::<Vec<[Day; 7]>>();
// Thursday names the month that owns most of a week; edge weeks stay inside the range.
let mut months: Vec<Month> = Vec::new();
for week in 0..count {
let label =
MONTHS[date((start + week * 7 + 3).clamp(first, last.max(first))).month0() as usize];
if months.last().is_none_or(|month| month.label != label) {
months.push(Month {
week: week as usize,
label,
span: 0,
});
}
}
let ends: Vec<usize> = months
.iter()
.skip(1)
.map(|month| month.week)
.chain([count as usize])
.collect();
for (month, end) in months.iter_mut().zip(ends) {
month.span = end - month.week;
}
Calendar {
weeks,
months,
clipped: count < total,
}
}
// Days from 0001-01-01 to 1970-01-01, as `num_days_from_ce` counts them.
const EPOCH_DAYS: i64 = 719_163;
fn date(ordinal: i64) -> NaiveDate {
NaiveDate::from_num_days_from_ce_opt((ordinal + EPOCH_DAYS) as i32).unwrap_or_default()
}
/// The stats palette, which `terminalPalette` picks from `COLORFGBG`'s background.
#[derive(Debug, Clone, PartialEq)]
pub struct Palette {
@@ -911,51 +735,11 @@ fn paint_activity(level: usize, palette: &Palette, color: bool) -> String {
mod tests {
use super::*;
use chrono::{FixedOffset, Utc};
use serde_json::json;
fn fixture() -> Value {
serde_json::from_str(include_str!("../../../../parity/fixtures/C.3/stats.json")).unwrap()
}
fn calendar_json(calendar: &Calendar) -> Value {
json!({
"weeks": calendar.weeks.iter().map(|week| week.iter().map(|day| json!({
"date": day.date, "steps": day.steps, "level": day.level,
})).collect::<Vec<_>>()).collect::<Vec<_>>(),
"months": calendar.months.iter().map(|month| json!({
"week": month.week, "label": month.label, "span": month.span,
})).collect::<Vec<_>>(),
"clipped": calendar.clipped,
})
}
#[test]
fn activity_calendar_matches_the_typescript_oracle() {
let fixture = fixture();
let cases = fixture["calendar"].as_array().unwrap();
assert!(cases.len() > 40);
for case in cases {
let zone = FixedOffset::east_opt(case["offset"].as_i64().unwrap() as i32).unwrap();
let input = &case["input"];
let activity: Vec<SessionStatsActivity> =
serde_json::from_value(input["activity"].clone()).unwrap();
let calendar = activity_calendar(
&zone,
&activity,
input["from"].as_i64().unwrap(),
input["to"].as_i64().unwrap(),
input["maxWeeks"].as_f64().unwrap(),
);
assert_eq!(
calendar_json(&calendar),
case["output"],
"{} in {}",
input["name"],
case["tz"]
);
}
}
#[test]
fn render_stats_matches_the_typescript_oracle() {
let fixture = fixture();
+11 -163
View File
@@ -4,7 +4,6 @@
//! a calendar of active days, the best streak, the active days, and the sessions. Escape goes back.
use std::cell::RefCell;
use std::collections::BTreeSet;
use std::rc::Rc;
use chrono::{Datelike, Local, NaiveDate, TimeZone};
@@ -14,6 +13,7 @@ use opencode_api::generated::{
};
use opencode_plugin::{Definition, Slotted};
use opencode_store::Changes;
use opencode_ui::activity_calendar::{activity_calendar, time_zone};
use opencode_ui::keymap::{Bind, GLOBAL_MODE, KeymapLayer, TuiCommand};
use opencode_ui::theme::Theme;
use opentui::keymap::Disposer;
@@ -140,7 +140,7 @@ fn load(tui: &Tui, content: &View) {
.map_or(0, |start| start.timestamp_millis());
let input = ExperimentalSessionStatsInput {
from: Some(from as f64),
timezone: Some(timezone()),
timezone: Some(time_zone()),
tools: Some(ExperimentalSessionStatsInputTools::None),
..ExperimentalSessionStatsInput::default()
};
@@ -176,21 +176,6 @@ fn load(tui: &Tui, content: &View) {
);
}
/// `Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC"`: `TZ`, else the zone `/etc/localtime` links to.
fn timezone() -> String {
std::env::var("TZ")
.ok()
.map(|zone| zone.trim_start_matches(':').to_owned())
.filter(|zone| !zone.is_empty())
.or_else(|| {
let link = std::fs::read_link("/etc/localtime").ok()?;
let link = link.to_string_lossy();
link.split_once("zoneinfo/")
.map(|(_, zone)| zone.to_owned())
})
.unwrap_or_else(|| "UTC".to_owned())
}
const DIGITS: [(char, [&str; 5]); 15] = [
('0', ["111", "101", "101", "101", "111"]),
('1', ["010", "110", "010", "010", "111"]),
@@ -321,17 +306,12 @@ fn poster(tui: &Tui, theme: &Theme, stats: &SessionStatsInfo) -> View {
}
fn calendar_view(app: &App, theme: &Theme, stats: &SessionStatsInfo, width: u32) -> View {
let days: Vec<(String, i64)> = stats
.activity
.iter()
.map(|day| (day.date.clone(), day.steps))
.collect();
let calendar = calendar(
&days,
local_ordinal(stats.range.from),
local_ordinal(stats.range.to - 1.0),
stats.range.to <= stats.range.from,
(i64::from(width) - 4) / 2,
let calendar = activity_calendar(
&Local,
&stats.activity,
stats.range.from as i64,
stats.range.to as i64,
f64::from(width.saturating_sub(4) / 2),
);
let accent = theme
.categorical()
@@ -348,12 +328,12 @@ fn calendar_view(app: &App, theme: &Theme, stats: &SessionStatsInfo, width: u32)
.months
.iter()
.map(|month| {
let label = if month.label.len() as i64 <= month.span * 2 {
let label = if month.label.len() <= month.span * 2 {
month.label
} else {
""
};
format!("{label:<width$}", width = (month.span * 2) as usize)
format!("{label:<width$}", width = month.span * 2)
})
.collect();
let root = View::new(app)
@@ -362,7 +342,7 @@ fn calendar_view(app: &App, theme: &Theme, stats: &SessionStatsInfo, width: u32)
for (index, day) in ["M", "T", "W", "T", "F", "S", "S"].into_iter().enumerate() {
let mut spans = vec![format!("{day} ").fg(theme.text.muted)];
for week in &calendar.weeks {
let level = week[index];
let level = week[index].level;
let cell = match level {
-1 => " ",
0 => "\u{b7} ",
@@ -386,111 +366,6 @@ fn calendar_view(app: &App, theme: &Theme, stats: &SessionStatsInfo, width: u32)
root
}
/// `activityCalendar`'s result: a level per day of each week (-1 outside the range), month labels with the
/// number of weeks each spans, and whether weeks before the range's end were left out.
#[derive(Debug, PartialEq)]
pub struct Calendar {
pub weeks: Vec<[i64; 7]>,
pub months: Vec<Month>,
pub clipped: bool,
}
#[derive(Debug, PartialEq)]
pub struct Month {
pub week: i64,
pub label: &'static str,
pub span: i64,
}
/// The local date of a time, as days since the epoch (`ordinal`).
fn local_ordinal(time: f64) -> i64 {
let date = Local
.timestamp_millis_opt(time as i64)
.single()
.map_or(NaiveDate::default(), |date| date.date_naive());
date.signed_duration_since(NaiveDate::default()).num_days()
}
/// `activityCalendar`, over local-date ordinals `from` to `to` (both included).
pub fn calendar(
days: &[(String, i64)],
from: i64,
to: i64,
empty: bool,
max_weeks: i64,
) -> Calendar {
let date = |ordinal: i64| NaiveDate::default() + chrono::Duration::days(ordinal);
let monday = from - i64::from(date(from).weekday().num_days_from_monday());
let total = if empty {
0
} else {
(to - monday).div_euclid(7) + 1
};
let count = total.min(53).min(max_weeks.max(1));
let start = monday + (total - count).max(0) * 7;
let levels: Vec<i64> = days
.iter()
.map(|(_, steps)| *steps)
.filter(|steps| *steps > 0)
.collect::<BTreeSet<_>>()
.into_iter()
.collect();
let steps = |key: &str| {
days.iter()
.rev()
.find(|(day, _)| day == key)
.map_or(0, |(_, steps)| *steps)
};
let weeks = (0..count)
.map(|week| {
std::array::from_fn(|day| {
let ordinal = start + week * 7 + day as i64;
let value = steps(&date(ordinal).format("%Y-%m-%d").to_string());
if ordinal < from || ordinal > to {
return -1;
}
if value == 0 {
return 0;
}
let rank = levels
.iter()
.position(|level| *level == value)
.map_or(0, |index| index + 1);
((rank as f64 / levels.len() as f64 * 4.0).ceil() as i64).max(1)
})
})
.collect();
const MONTHS: [&str; 12] = [
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
];
let mut months: Vec<Month> = Vec::new();
for week in 0..count {
// Thursday names the month that owns most of a week; edge weeks stay inside the range.
let label = MONTHS[date((start + week * 7 + 3).clamp(from, to)).month0() as usize];
if months.last().is_none_or(|month| month.label != label) {
months.push(Month {
week,
label,
span: 0,
});
}
}
let ends: Vec<i64> = months
.iter()
.skip(1)
.map(|month| month.week)
.chain([count])
.collect();
for (month, end) in months.iter_mut().zip(ends) {
month.span = end - month.week;
}
Calendar {
weeks,
months,
clipped: count < total,
}
}
/// `statsNumber`: compact notation with at most one fraction digit (`12.3K`, `1M`).
pub fn number(value: f64) -> String {
const UNITS: [(f64, &str); 5] = [(1.0, ""), (1e3, "K"), (1e6, "M"), (1e9, "B"), (1e12, "T")];
@@ -561,31 +436,4 @@ mod tests {
assert_eq!(number(value), want, "{value}");
}
}
#[test]
fn calendar_like_activity_calendar() {
// 2026-01-01 is a Thursday; the range is January 1 to 14.
let from = NaiveDate::from_ymd_opt(2026, 1, 1)
.unwrap()
.signed_duration_since(NaiveDate::default())
.num_days();
let days = [("2026-01-02".to_owned(), 3), ("2026-01-05".to_owned(), 9)];
let calendar = calendar(&days, from, from + 13, false, 53);
assert_eq!(calendar.weeks.len(), 3);
assert_eq!(calendar.weeks[0], [-1, -1, -1, 0, 2, 0, 0]);
assert_eq!(calendar.weeks[1][0], 4);
assert_eq!(calendar.weeks[2], [0, 0, 0, -1, -1, -1, -1]);
assert_eq!(
calendar.months,
[Month {
week: 0,
label: "Jan",
span: 3
}]
);
assert!(!calendar.clipped);
let clipped = super::calendar(&days, from, from + 13, false, 2);
assert_eq!(clipped.weeks.len(), 2);
assert!(clipped.clipped);
}
}
+1
View File
@@ -13,6 +13,7 @@ workspace = true
opentui.workspace = true
opencode-api.workspace = true
opencode-local.workspace = true
chrono.workspace = true
indexmap.workspace = true
log.workspace = true
serde.workspace = true
@@ -0,0 +1,229 @@
//! `@opencode/util/activity-calendar` for `stats` (C.3) and the TUI's `/stats` poster (E.14): Monday-first weeks
//! of activity levels with month labels, and the time zone both send with the stats request.
use chrono::{DateTime, Datelike, NaiveDate, TimeZone};
use opencode_api::generated::types::SessionStatsActivity;
/// `Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC"` as Bun resolves it: `TZ` (an empty
/// value is UTC), else the zone `/etc/localtime` links to. ICU's names for UTC become `UTC`, and a
/// zone without tz data falls back to `UTC`.
pub fn time_zone() -> String {
let name = match std::env::var("TZ") {
Ok(value) => value.trim_start_matches(':').to_owned(),
Err(_) => std::fs::read_link("/etc/localtime")
.ok()
.and_then(|link| {
let link = link.to_string_lossy().into_owned();
link.split_once("zoneinfo/")
.map(|(_, name)| name.to_owned())
})
.unwrap_or_default(),
};
const UTC: [&str; 14] = [
"",
"UTC",
"UCT",
"GMT",
"GMT0",
"GMT+0",
"GMT-0",
"Greenwich",
"Universal",
"Zulu",
"Etc/UTC",
"Etc/UCT",
"Etc/GMT",
"Etc/Universal",
];
if UTC.contains(&name.as_str())
|| [
"Etc/GMT0",
"Etc/GMT+0",
"Etc/GMT-0",
"Etc/Greenwich",
"Etc/Zulu",
]
.contains(&name.as_str())
|| name.starts_with('/')
|| !std::path::Path::new("/usr/share/zoneinfo")
.join(&name)
.is_file()
{
return "UTC".to_owned();
}
name
}
/// One cell of the calendar: `level` is -1 outside the range, 0 without steps, else 1 to 4.
#[derive(Debug, Clone, PartialEq)]
pub struct Day {
pub date: String,
pub steps: i64,
pub level: i64,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Month {
pub week: usize,
pub label: &'static str,
pub span: usize,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Calendar {
pub weeks: Vec<[Day; 7]>,
pub months: Vec<Month>,
pub clipped: bool,
}
const MONTHS: [&str; 12] = [
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
];
/// `activityCalendar`: Monday-first weeks covering `[from, to)` in `zone`'s local dates, the latest
/// `max_weeks` of them (at most 53), with month labels.
pub fn activity_calendar<Tz: TimeZone>(
zone: &Tz,
activity: &[SessionStatsActivity],
from: i64,
to: i64,
max_weeks: f64,
) -> Calendar {
// Local dates first, then day ordinals, so DST cannot add or drop cells.
let ordinal = |time: i64| {
DateTime::from_timestamp_millis(time).map_or(0, |time| {
i64::from(time.with_timezone(zone).date_naive().num_days_from_ce()) - EPOCH_DAYS
})
};
let first = ordinal(from);
let last = ordinal(to - 1);
let monday = first - i64::from(date(first).weekday().num_days_from_monday());
let total = if to <= from {
0
} else {
(last - monday).div_euclid(7) + 1
};
let count = total.min(53).min((max_weeks.floor() as i64).max(1));
let start = monday + (total - count).max(0) * 7;
let mut values: Vec<(&str, i64)> = Vec::new();
for day in activity {
match values.iter_mut().find(|(date, _)| *date == day.date) {
Some(entry) => entry.1 = day.steps,
None => values.push((&day.date, day.steps)),
}
}
let mut levels: Vec<i64> = values
.iter()
.map(|(_, steps)| *steps)
.filter(|steps| *steps > 0)
.collect();
levels.sort_unstable();
levels.dedup();
let weeks = (0..count)
.map(|week| {
std::array::from_fn(|day| {
let ordinal = start + week * 7 + day as i64;
let key = date(ordinal).format("%Y-%m-%d").to_string();
let steps = values
.iter()
.find(|(date, _)| *date == key)
.map_or(0, |(_, steps)| *steps);
let level = if ordinal < first || ordinal > last {
-1
} else if steps == 0 {
0
} else {
let rank = levels.iter().position(|level| *level == steps);
let rank = rank.map_or(0, |rank| rank as i64 + 1) as f64;
((rank / levels.len() as f64 * 4.0).ceil() as i64).max(1)
};
Day {
date: key,
steps,
level,
}
})
})
.collect::<Vec<[Day; 7]>>();
// Thursday names the month that owns most of a week; edge weeks stay inside the range.
let mut months: Vec<Month> = Vec::new();
for week in 0..count {
let label =
MONTHS[date((start + week * 7 + 3).clamp(first, last.max(first))).month0() as usize];
if months.last().is_none_or(|month| month.label != label) {
months.push(Month {
week: week as usize,
label,
span: 0,
});
}
}
let ends: Vec<usize> = months
.iter()
.skip(1)
.map(|month| month.week)
.chain([count as usize])
.collect();
for (month, end) in months.iter_mut().zip(ends) {
month.span = end - month.week;
}
Calendar {
weeks,
months,
clipped: count < total,
}
}
// Days from 0001-01-01 to 1970-01-01, as `num_days_from_ce` counts them.
const EPOCH_DAYS: i64 = 719_163;
fn date(ordinal: i64) -> NaiveDate {
NaiveDate::from_num_days_from_ce_opt((ordinal + EPOCH_DAYS) as i32).unwrap_or_default()
}
#[cfg(test)]
mod tests {
use super::*;
use chrono::FixedOffset;
use serde_json::{Value, json};
fn calendar_json(calendar: &Calendar) -> Value {
json!({
"weeks": calendar.weeks.iter().map(|week| week.iter().map(|day| json!({
"date": day.date, "steps": day.steps, "level": day.level,
})).collect::<Vec<_>>()).collect::<Vec<_>>(),
"months": calendar.months.iter().map(|month| json!({
"week": month.week, "label": month.label, "span": month.span,
})).collect::<Vec<_>>(),
"clipped": calendar.clipped,
})
}
#[test]
fn activity_calendar_matches_the_typescript_oracle() {
let fixture: Value =
serde_json::from_str(include_str!("../../../parity/fixtures/C.3/stats.json")).unwrap();
let cases = fixture["calendar"].as_array().unwrap();
assert!(cases.len() > 40);
for case in cases {
let zone = FixedOffset::east_opt(case["offset"].as_i64().unwrap() as i32).unwrap();
let input = &case["input"];
let activity: Vec<SessionStatsActivity> =
serde_json::from_value(input["activity"].clone()).unwrap();
let calendar = activity_calendar(
&zone,
&activity,
input["from"].as_i64().unwrap(),
input["to"].as_i64().unwrap(),
input["maxWeeks"].as_f64().unwrap(),
);
assert_eq!(
calendar_json(&calendar),
case["output"],
"{} in {}",
input["name"],
case["tz"]
);
}
}
}
+1
View File
@@ -1,5 +1,6 @@
//! UI kit on opentui: themes, keymap, dialogs, and content widgets.
pub mod activity_calendar;
pub mod alert;
pub mod code;
pub mod confirm;