Let a date range be stated, and draw the axis at the scale it deserves

"Limit to range" did nothing, and the reason was not visible from the button.
It took its span from the timeline's zoom, which is zero until someone zooms —
so `zoomed_span` returned the whole library and the filter narrowed to
everything. The chip lit up and the grid did not change.

The range has ends now, shown and typed as `YYYY-MM-DD`. Seeding them from the
timeline is kept, because zooming to a fortnight and pressing the chip is the
fast path; the fields say which fortnight it landed on and let it be corrected.
Ends given backwards are swapped rather than refused — there is exactly one
range between two days — and the closing day is included, since "to the 5th"
means the whole of the 5th and a range ending at its midnight contains none of
it. `parse_date` refuses anything that is not a date rather than guessing at an
order, because the alternative is a library silently filtered to a span nobody
asked for.

The axis then follows the range. It used to keep drawing the full extent while
a range was on, because it was the only way back out; the typed ends are the
way back out now, so it is free to show what was asked about.

And bucket size is chosen by how many bars it makes rather than by fixed
cut-offs. Each zoom step halves the span, so under thresholds the bar count
halved with it until a boundary was crossed: fifteen years went 15 bars, 8,
then 46, 23, 11, and finally 6. Zooming in made the picture coarser, which is
the opposite of what zooming is for. Aiming at forty bars keeps the count in
the same neighbourhood at every level, and the test asserts the property
directly — halving a span never coarsens the bucket.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-08-23 12:40:14 +02:00
co-authored by Claude Opus 5
parent fbf286d504
commit 4b7648082e
6 changed files with 391 additions and 8 deletions
+96 -7
View File
@@ -114,13 +114,78 @@ impl Granularity {
}
/// A sensible bucket size for a span of seconds, so the UI need not guess.
///
/// # Chosen by how many bars it produces, not by fixed cut-offs
///
/// This used to be four thresholds on the span, which reads sensibly and
/// behaves badly under zoom. Each zoom step halves the span, so the bar
/// count halves with it until a threshold is crossed — a fifteen-year
/// library went 15 bars, 8, then 46, 23, 11, and finally *6*. Zooming in
/// made the picture coarser, which is the opposite of what zooming is for.
///
/// So the choice is made on the axis's terms: of the four bucket sizes,
/// take the one whose bar count comes nearest [`Self::TARGET_BARS`]. The
/// count then stays in the same neighbourhood at every zoom level, and
/// each step in genuinely shows finer structure rather than the same
/// structure drawn wider.
///
/// Nearest in *ratio*, not in difference: the counts available for a given
/// span are orders of magnitude apart — a span is either about 4 years or
/// about 48 months — and on a linear measure the larger count always looks
/// further away, which would bias every choice towards too few bars.
pub fn for_span(seconds: i64) -> Self {
let seconds = seconds.max(1) as f64;
// Finest first, so that when two options are equally far from the
// target the finer one wins: `min_by` keeps the first minimum it saw,
// and more detail is the better failure.
[
Granularity::Hour,
Granularity::Day,
Granularity::Month,
Granularity::Year,
]
.into_iter()
.min_by(|a, b| {
let cost = |g: Granularity| {
let bars = seconds / g.approx_seconds() as f64;
// How far off the target, measured multiplicatively: twice as
// many and half as many are equally wrong.
//
// Deliberately not clamped to at least one bar. A span shorter
// than a bucket scores *worse* the coarser the bucket, which is
// what makes an hour of photographs pick hourly bars instead of
// every option tying at "one bar" and the coarsest winning.
(bars / Self::TARGET_BARS as f64).ln().abs()
};
cost(*a)
.partial_cmp(&cost(*b))
// Ties cannot arise from real spans, but a NaN would; falling
// back to the coarser option keeps the axis drawable.
.unwrap_or(std::cmp::Ordering::Equal)
})
.unwrap_or(Granularity::Day)
}
/// How many bars the timeline wants across its axis.
///
/// Not a hard count — the bucket sizes are calendar units, so the actual
/// number lands where the calendar puts it. It is the figure the choice
/// aims at: enough bars that a busy fortnight is visibly busier than a
/// quiet one, few enough that each is wide enough to hit with a finger.
const TARGET_BARS: i64 = 40;
/// Nominal length of one bucket, for choosing between them.
///
/// Approximate on purpose: months and years vary and it does not matter
/// here, because this only ranks four options that are a factor of ~12 or
/// ~30 apart. The exact boundaries come from `strftime` on the real dates.
fn approx_seconds(self) -> i64 {
const DAY: i64 = 86_400;
match seconds {
s if s > 5 * 365 * DAY => Granularity::Year,
s if s > 90 * DAY => Granularity::Month,
s if s > 2 * DAY => Granularity::Day,
_ => Granularity::Hour,
match self {
Granularity::Year => 365 * DAY,
Granularity::Month => 30 * DAY,
Granularity::Day => DAY,
Granularity::Hour => 3600,
}
}
}
@@ -422,10 +487,34 @@ mod tests {
#[test]
fn timeline_granularity_follows_the_span() {
const DAY: i64 = 86_400;
assert_eq!(Granularity::for_span(10 * 365 * DAY), Granularity::Year);
assert_eq!(Granularity::for_span(120 * DAY), Granularity::Month);
// Chosen by how many bars it makes, not by fixed cut-offs — see
// `for_span`. Ten years of yearly bars is ten bars, which says almost
// nothing about a library; monthly is 122, which is a shape.
assert_eq!(Granularity::for_span(10 * 365 * DAY), Granularity::Month);
assert_eq!(Granularity::for_span(120 * DAY), Granularity::Day);
assert_eq!(Granularity::for_span(10 * DAY), Granularity::Day);
assert_eq!(Granularity::for_span(3600), Granularity::Hour);
// The property the target exists for: zooming in never coarsens the
// axis. Under the old thresholds a fifteen-year library went 15 bars,
// then 8, then 46, 23, 11 — finer spans drawn with wider bars.
let mut span = 15 * 365 * DAY;
let mut previous = Granularity::for_span(span).approx_seconds();
for _ in 0..10 {
span /= 2;
let bucket = Granularity::for_span(span).approx_seconds();
assert!(
bucket <= previous,
"halving the span to {span}s coarsened the bucket \
from {previous}s to {bucket}s"
);
previous = bucket;
}
// And a span shorter than any bucket still picks the finest, rather
// than every option tying at one bar and the coarsest winning.
assert_eq!(Granularity::for_span(60), Granularity::Hour);
assert_eq!(Granularity::for_span(1), Granularity::Hour);
}
#[test]
+3 -1
View File
@@ -19,7 +19,9 @@ pub use settings::{
CacheSettings, CollisionPolicy, ColourSpace, DevelopSettings, ExportFormat, ExportSettings,
ExportTarget, ImportSettings, OutputSharpening, Settings, SizingMode,
};
pub use time::{civil_from_unix, civil_from_unix_at, format_date, Civil};
pub use time::{
civil_from_unix, civil_from_unix_at, format_date, parse_date, unix_from_civil, Civil,
};
/// Identifies a granted library location — a directory on Linux, a persisted
/// document tree on Android.
+107
View File
@@ -64,6 +64,68 @@ pub fn civil_from_unix_at(t: i64, offset: Option<i32>) -> Civil {
civil_from_unix(t + offset.unwrap_or(0) as i64 * 60)
}
/// TRACES: FR-CAT-6
/// A civil date back to Unix seconds — midnight UTC on that day.
///
/// The exact inverse of [`civil_from_unix`]'s date part, by the companion
/// era-based algorithm, so a date formatted by [`format_date`] and read back
/// here lands on the same day it named. Hand-rolled for the same reason the
/// forward direction is: four fields do not justify a date library, and two
/// implementations that disagree would put a photograph on a day the timeline
/// does not show it.
///
/// Midnight rather than noon because a range is half-open in spirit: "from the
/// 3rd" means from the first instant of the 3rd, and the caller decides what
/// "to the 5th" means by adding a day if it wants the 5th included.
pub fn unix_from_civil(year: i64, month: i64, day: i64) -> i64 {
let y = if month <= 2 { year - 1 } else { year };
let era = if y >= 0 { y } else { y - 399 } / 400;
let yoe = y - era * 400;
let mp = if month > 2 { month - 3 } else { month + 9 };
let doy = (153 * mp + 2) / 5 + day - 1;
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
(era * 146_097 + doe - 719_468) * 86_400
}
/// TRACES: FR-CAT-6
/// `YYYY-MM-DD` to Unix seconds, or `None` if that is not what it is.
///
/// Strict on purpose. This reads what a person typed into a date field, and
/// the useful answer to "13/2026/08" is that it is not a date — guessing at an
/// order would silently filter a library to a span nobody asked for, and the
/// grid going empty is a poor way to learn your input was misread.
///
/// The day is checked against the month it is in, so `2026-02-30` is refused
/// rather than quietly becoming the 2nd of March.
pub fn parse_date(text: &str) -> Option<i64> {
let text = text.trim();
let mut parts = text.split('-');
let year: i64 = parts.next()?.parse().ok()?;
let month: i64 = parts.next()?.parse().ok()?;
let day: i64 = parts.next()?.parse().ok()?;
if parts.next().is_some() {
return None;
}
if !(1..=12).contains(&month) || day < 1 {
return None;
}
if day > days_in_month(year, month) {
return None;
}
Some(unix_from_civil(year, month, day))
}
/// Length of a month, with the full Gregorian leap rule.
fn days_in_month(year: i64, month: i64) -> i64 {
match month {
1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
4 | 6 | 9 | 11 => 30,
2 if year % 4 == 0 && (year % 100 != 0 || year % 400 == 0) => 29,
2 => 28,
_ => 0,
}
}
/// A capture instant as `YYYY-MM-DD`.
pub fn format_date(t: i64) -> String {
let c = civil_from_unix(t);
@@ -74,6 +136,51 @@ pub fn format_date(t: i64) -> String {
mod tests {
use super::*;
/// The two directions must agree, or a photograph is filed on a day the
/// timeline does not show it on — the failure this module exists to stop.
#[test]
fn a_date_survives_the_round_trip() {
for t in [
0, // the epoch
1_760_000_000, // an ordinary recent instant
951_782_400, // 2000-02-29, the leap day the 100/400 rule keeps
-86_400, // the day before the epoch
] {
let c = civil_from_unix(t);
let back = unix_from_civil(c.year, c.month, c.day);
assert_eq!(
civil_from_unix(back),
Civil { hour: 0, ..c },
"{t} -> {c:?} -> {back} disagreed"
);
}
}
#[test]
fn parsing_accepts_a_date_and_refuses_everything_else() {
assert_eq!(parse_date("1970-01-01"), Some(0));
assert_eq!(parse_date(" 2026-08-23 "), parse_date("2026-08-23"));
assert_eq!(format_date(parse_date("2026-08-23").unwrap()), "2026-08-23");
// A leap day is real in 2024 and not in 2026.
assert!(parse_date("2024-02-29").is_some());
assert_eq!(parse_date("2026-02-29"), None);
// Refused rather than guessed at: silently reordering these would
// filter the library to a span nobody asked for.
assert_eq!(
parse_date("23-08-2026"),
None,
"day-first is not a format here"
);
assert_eq!(parse_date("2026-13-01"), None, "there is no month 13");
assert_eq!(parse_date("2026-08-32"), None);
assert_eq!(parse_date("2026-08"), None, "a month is not a date");
assert_eq!(parse_date("2026-08-23-01"), None);
assert_eq!(parse_date(""), None);
assert_eq!(parse_date("yesterday"), None);
}
#[test]
fn the_epoch_is_the_first_of_january_1970() {
let c = civil_from_unix(0);