Skip to main content

ferrochart_core/
time_scale.rs

1//! The global time scale (bar spacing, right offset, index <-> x) and the
2//! weight-based time tick algorithm, with pure-algorithm calendar math.
3//!
4
5use core::fmt::{self, Write};
6
7use crate::data::{LogicalIndex, TimeIndex, Timestamp};
8use crate::error::{Error, Result};
9use crate::geom::Px;
10
11const DAY_MS: i64 = 86_400_000;
12
13/// UTC offset provider for label formatting. Full IANA time zones are injected by
14/// the binding layer (JS `Intl`, Python `zoneinfo`); the core only ships [`Utc`]
15/// and [`FixedOffset`].
16///
17/// # Examples
18///
19/// ```
20/// use ferrochart_core::time_scale::{FixedOffset, TimeZoneProvider, Utc};
21///
22/// assert_eq!(Utc.offset_ms(0), 0);
23/// assert_eq!(FixedOffset(8 * 3_600_000).offset_ms(0), 28_800_000);
24/// ```
25pub trait TimeZoneProvider: Send {
26    /// Offset of local time from UTC at instant `utc`, in milliseconds.
27    fn offset_ms(&self, utc: Timestamp) -> i64;
28}
29
30/// UTC.
31#[derive(Clone, Copy, Debug, Default)]
32pub struct Utc;
33
34impl TimeZoneProvider for Utc {
35    fn offset_ms(&self, _: Timestamp) -> i64 {
36        0
37    }
38}
39
40/// A fixed offset from UTC in milliseconds.
41#[derive(Clone, Copy, Debug, Default)]
42pub struct FixedOffset(pub i64);
43
44impl TimeZoneProvider for FixedOffset {
45    fn offset_ms(&self, _: Timestamp) -> i64 {
46        self.0
47    }
48}
49
50/// Civil date `(year, month 1..=12, day 1..=31)` of a day count since
51/// 1970-01-01 (Howard Hinnant's `civil_from_days`).
52///
53/// # Examples
54///
55/// ```
56/// use ferrochart_core::time_scale::civil_from_days;
57///
58/// assert_eq!(civil_from_days(0), (1970, 1, 1));
59/// assert_eq!(civil_from_days(19_723), (2024, 1, 1));
60/// assert_eq!(civil_from_days(-1), (1969, 12, 31));
61/// ```
62pub fn civil_from_days(days: i64) -> (i64, u32, u32) {
63    let z = days + 719_468;
64    let era = z.div_euclid(146_097);
65    let doe = z.rem_euclid(146_097); // [0, 146096]
66    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; // [0, 399]
67    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); // [0, 365]
68    let mp = (5 * doy + 2) / 153; // [0, 11]
69    let d = doy - (153 * mp + 2) / 5 + 1; // [1, 31]
70    let m = if mp < 10 { mp + 3 } else { mp - 9 }; // [1, 12]
71    let y = yoe + era * 400 + i64::from(m <= 2);
72    (y, m as u32, d as u32)
73}
74
75/// How big a calendar boundary a time label marks. Higher is more important.
76///
77/// # Examples
78///
79/// ```
80/// use ferrochart_core::time_scale::TickWeight;
81///
82/// assert!(TickWeight::Year > TickWeight::Month);
83/// ```
84#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
85pub enum TickWeight {
86    /// A new second.
87    Second,
88    /// A new minute.
89    Minute,
90    /// A new 5-minute slot.
91    Min5,
92    /// A new 15-minute slot.
93    Min15,
94    /// A new 30-minute slot.
95    Min30,
96    /// A new hour.
97    Hour,
98    /// A new day.
99    Day,
100    /// A new month.
101    Month,
102    /// A new year.
103    Year,
104}
105
106const WEIGHTS_DESC: [TickWeight; 9] = [
107    TickWeight::Year,
108    TickWeight::Month,
109    TickWeight::Day,
110    TickWeight::Hour,
111    TickWeight::Min30,
112    TickWeight::Min15,
113    TickWeight::Min5,
114    TickWeight::Minute,
115    TickWeight::Second,
116];
117
118/// A number identifying the calendar unit of `weight` that local time `t` lies in.
119fn unit(t: i64, weight: TickWeight) -> i64 {
120    let slot = |ms: i64| t.div_euclid(ms);
121    match weight {
122        TickWeight::Year => civil_from_days(t.div_euclid(DAY_MS)).0,
123        TickWeight::Month => {
124            let (y, m, _) = civil_from_days(t.div_euclid(DAY_MS));
125            y * 12 + i64::from(m)
126        }
127        TickWeight::Day => slot(DAY_MS),
128        TickWeight::Hour => slot(3_600_000),
129        TickWeight::Min30 => slot(1_800_000),
130        TickWeight::Min15 => slot(900_000),
131        TickWeight::Min5 => slot(300_000),
132        TickWeight::Minute => slot(60_000),
133        TickWeight::Second => slot(1000),
134    }
135}
136
137/// The largest calendar boundary crossed going from local time `a` to `b`.
138///
139/// # Examples
140///
141/// ```
142/// use ferrochart_core::time_scale::{weight_between, TickWeight};
143///
144/// let jan1_2024 = 1_704_067_200_000;
145/// assert_eq!(weight_between(jan1_2024 - 60_000, jan1_2024), TickWeight::Year);
146/// assert_eq!(weight_between(jan1_2024, jan1_2024 + 60_000), TickWeight::Minute);
147/// ```
148pub fn weight_between(a: i64, b: i64) -> TickWeight {
149    WEIGHTS_DESC
150        .into_iter()
151        .find(|&w| unit(a, w) != unit(b, w))
152        .unwrap_or(TickWeight::Second)
153}
154
155const MONTHS: [&str; 12] = [
156    "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
157];
158
159/// Writes the label of a tick of `weight` at local time `t`: `2024`, `Mar`, `15`,
160/// `14:30` or `14:30:05`.
161///
162/// # Errors
163///
164/// Only if `out` fails.
165///
166/// # Examples
167///
168/// ```
169/// use ferrochart_core::text::StackStr;
170/// use ferrochart_core::time_scale::{format_tick, TickWeight};
171///
172/// let t = 1_710_513_000_000; // 2024-03-15T14:30:00Z
173/// let mut s = StackStr::<16>::new();
174/// format_tick(t, TickWeight::Hour, &mut s).unwrap();
175/// assert_eq!(s.as_str(), "14:30");
176/// ```
177pub fn format_tick(t: i64, weight: TickWeight, out: &mut impl Write) -> fmt::Result {
178    let (y, m, d) = civil_from_days(t.div_euclid(DAY_MS));
179    let ms = t.rem_euclid(DAY_MS);
180    let (hh, mm, ss) = (ms / 3_600_000, ms / 60_000 % 60, ms / 1000 % 60);
181    match weight {
182        TickWeight::Year => write!(out, "{y}"),
183        TickWeight::Month => out.write_str(MONTHS[(m as usize).saturating_sub(1) % 12]),
184        TickWeight::Day => write!(out, "{d}"),
185        TickWeight::Second => write!(out, "{hh:02}:{mm:02}:{ss:02}"),
186        _ => write!(out, "{hh:02}:{mm:02}"),
187    }
188}
189
190/// Writes the crosshair label of local time `t`: `2024-03-15 14:30`, or only the
191/// date for bars that start at midnight.
192///
193/// # Errors
194///
195/// Only if `out` fails.
196///
197/// # Examples
198///
199/// ```
200/// use ferrochart_core::text::StackStr;
201/// use ferrochart_core::time_scale::format_crosshair_time;
202///
203/// let mut s = StackStr::<32>::new();
204/// format_crosshair_time(1_710_513_000_000, &mut s).unwrap();
205/// assert_eq!(s.as_str(), "2024-03-15 14:30");
206/// ```
207pub fn format_crosshair_time(t: i64, out: &mut impl Write) -> fmt::Result {
208    let (y, m, d) = civil_from_days(t.div_euclid(DAY_MS));
209    let ms = t.rem_euclid(DAY_MS);
210    write!(out, "{y:04}-{m:02}-{d:02}")?;
211    if ms != 0 {
212        write!(out, " {:02}:{:02}", ms / 3_600_000, ms / 60_000 % 60)?;
213    }
214    Ok(())
215}
216
217/// Days since 1970-01-01 of a proleptic Gregorian date (inverse of
218/// [`civil_from_days`]).
219fn days_from_civil(y: i64, m: u32, d: u32) -> i64 {
220    let y = if m <= 2 { y - 1 } else { y };
221    let era = y.div_euclid(400);
222    let yoe = y.rem_euclid(400);
223    let m = i64::from(m);
224    let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + i64::from(d) - 1;
225    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
226    era * 146_097 + doe - 719_468
227}
228
229/// Steps of [`time_ticks`]: milliseconds, or months when negative.
230const TIME_STEPS: [i64; 31] = [
231    1000,
232    2000,
233    5000,
234    10_000,
235    15_000,
236    30_000, // seconds
237    60_000,
238    120_000,
239    300_000,
240    600_000,
241    900_000,
242    1_800_000, // minutes
243    3_600_000,
244    7_200_000,
245    10_800_000,
246    21_600_000,
247    43_200_000, // hours
248    DAY_MS,
249    2 * DAY_MS,
250    7 * DAY_MS,
251    14 * DAY_MS, // days
252    -1,
253    -2,
254    -3,
255    -6, // months
256    -12,
257    -24,
258    -60,
259    -120,
260    -240,
261    -600, // years
262];
263
264/// Ticks for a numeric axis whose values are local times in milliseconds
265/// (`ferrochart-plot`'s date axes): times `lo..=hi` on an axis `length`
266/// px long, at least `min_spacing` px apart, aligned to whole seconds,
267/// minutes, hours, days, months or years, each with the weight of the
268/// calendar boundary it falls on (for [`format_tick`]). Written to `out`
269/// (cleared first, ascending); at most 1000 ticks; no allocation once `out`
270/// has capacity.
271///
272/// ```
273/// use ferrochart_core::time_scale::{time_ticks, TickWeight};
274///
275/// let jan1_2024 = 1_704_067_200_000;
276/// let year = 366 * 86_400_000;
277/// let mut out = Vec::new();
278/// time_ticks(jan1_2024, jan1_2024 + year, 800.0, 60.0, &mut out);
279/// assert_eq!(out[0], (jan1_2024, TickWeight::Year));
280/// assert_eq!(out[1].1, TickWeight::Month);
281/// ```
282pub fn time_ticks(
283    lo: i64,
284    hi: i64,
285    length: f64,
286    min_spacing: f64,
287    out: &mut Vec<(i64, TickWeight)>,
288) {
289    out.clear();
290    if lo >= hi || length <= 0.0 || min_spacing <= 0.0 {
291        return;
292    }
293    let max_ticks = (length / min_spacing).floor().max(1.0);
294    let span = (hi - lo) as f64;
295    let step = TIME_STEPS
296        .into_iter()
297        .find(|&s| {
298            let ms = if s > 0 {
299                s as f64
300            } else {
301                -s as f64 * 30.44 * DAY_MS as f64
302            };
303            span / ms <= max_ticks
304        })
305        .unwrap_or(-1200);
306    let mut push = |t: i64| {
307        if out.len() < 1000 && (out.len() < out.capacity() || out.try_reserve(1).is_ok()) {
308            out.push((t, weight_between(t - 1, t)));
309        }
310    };
311    if step > 0 {
312        let mut t = lo.div_euclid(step) * step;
313        if t < lo {
314            t += step;
315        }
316        while t <= hi {
317            push(t);
318            t += step;
319        }
320    } else {
321        let months = -step;
322        let (y, m, _) = civil_from_days(lo.div_euclid(DAY_MS));
323        let mut k = (y * 12 + i64::from(m) - 1).div_euclid(months) * months;
324        loop {
325            let t = days_from_civil(k.div_euclid(12), (k.rem_euclid(12) + 1) as u32, 1) * DAY_MS;
326            if t > hi {
327                break;
328            }
329            if t >= lo {
330                push(t);
331            }
332            k += months;
333        }
334    }
335}
336
337/// A time tick candidate: the first bar (logical index) of a calendar unit.
338#[derive(Clone, Copy, Debug, PartialEq)]
339pub(crate) struct TimeTick {
340    pub index: i64,
341    pub weight: TickWeight,
342}
343
344/// Collects tick candidates for logical indices `from..=to` into `out` (cleared
345/// first). Bars are sampled every `2^shift` indices, aligned to the fixed origin
346/// so that candidates do not flicker while panning; for every sampled interval
347/// that crosses a calendar boundary, a binary search finds the exact first bar of
348/// the new unit. Work is O(samples · log stride), independent of the data size.
349pub(crate) fn collect_ticks(
350    index: &TimeIndex,
351    tz: &dyn TimeZoneProvider,
352    from: i64,
353    to: i64,
354    shift: u32,
355    out: &mut Vec<TimeTick>,
356) {
357    out.clear();
358    let first = index.first_index();
359    let last = index.end_index() - 1;
360    let local = |i: i64| index.time_at(i).map(|t| t + tz.offset_ms(t));
361    let stride = 1_i64 << shift;
362    let lo = from.max(first + 1);
363    let hi = to.min(last);
364    if lo > hi {
365        return;
366    }
367    let anchor = crate::data::ANCHOR;
368    let mut j = anchor + (((lo - anchor) + stride - 1) >> shift << shift);
369    while j <= hi {
370        let prev = (j - stride).max(first);
371        if let (Some(tp), Some(tj)) = (local(prev), local(j)) {
372            let w = weight_between(tp, tj);
373            let up = unit(tp, w);
374            // First index in (prev, j] whose unit differs from prev's.
375            let (mut a, mut b) = (prev + 1, j);
376            while a < b {
377                let mid = a + (b - a) / 2;
378                if local(mid).is_some_and(|t| unit(t, w) != up) {
379                    b = mid;
380                } else {
381                    a = mid + 1;
382                }
383            }
384            if out.len() < out.capacity() || out.try_reserve(1).is_ok() {
385                out.push(TimeTick {
386                    index: a,
387                    weight: w,
388                });
389            }
390        }
391        j += stride;
392    }
393}
394
395/// The global time scale.
396///
397/// `x(i) = width - (last_index + right_offset - i + 0.5) * bar_spacing` is the
398/// center of bar `i` in physical pixels relative to the plot's left edge.
399///
400/// # Examples
401///
402/// ```
403/// use ferrochart_core::{Chart, ChartOptions};
404/// use ferrochart_core::geom::Px;
405///
406/// let mut chart = Chart::new(ChartOptions::default());
407/// let ts = chart.time_scale();
408/// ts.set_bar_spacing(8.0);
409/// ts.scroll_by(Px(16.0)); // drag right by two bars
410/// assert_eq!(ts.bar_spacing(), 8.0);
411/// ```
412#[derive(Clone, Debug)]
413pub struct TimeScale {
414    bar_spacing: f64,
415    right_offset: f64,
416    min_spacing: f64,
417    max_spacing: f64,
418    width: f64,
419    first: i64,
420    last: i64,
421    bars: usize,
422    pending: Option<Pending>,
423    pub(crate) changed: bool,
424}
425
426/// A view that depends on the plot width. It is applied at once and again
427/// whenever the width or the data extent changes, until the layout of the
428/// next frame has settled (the price axis width, and so the plot width, is
429/// only known then), or until the user pans or zooms.
430#[derive(Clone, Copy, Debug)]
431enum Pending {
432    /// All bars.
433    Fit,
434    /// Logical indices at the left and the right plot edge.
435    Span { from: f64, to: f64 },
436}
437
438impl TimeScale {
439    pub(crate) fn new(bar_spacing: f64, right_offset: f64, min: f64, max: f64) -> Self {
440        Self {
441            bar_spacing,
442            right_offset,
443            min_spacing: min,
444            max_spacing: max,
445            width: 0.0,
446            first: 0,
447            last: -1,
448            bars: 0,
449            pending: None,
450            changed: true,
451        }
452    }
453
454    /// Width of one bar in physical pixels.
455    pub fn bar_spacing(&self) -> f64 {
456        self.bar_spacing
457    }
458
459    /// Empty space right of the last bar, in bars (may be negative).
460    pub fn right_offset(&self) -> f64 {
461        self.right_offset
462    }
463
464    /// Smallest allowed bar spacing: `min(min_bar_spacing, 0.9 · width / bars)`, so
465    /// that all data can always be shown at once.
466    pub fn effective_min_spacing(&self) -> f64 {
467        if self.bars == 0 || self.width <= 0.0 {
468            return self.min_spacing;
469        }
470        self.min_spacing.min(0.9 * self.width / self.bars as f64)
471    }
472
473    /// Sets the bar spacing (physical pixels), clamped to the allowed range;
474    /// non-finite values are ignored.
475    pub fn set_bar_spacing(&mut self, px: f64) {
476        if px.is_finite() && px > 0.0 {
477            self.bar_spacing = px;
478            self.pending = None;
479            self.clamp();
480            self.changed = true;
481        }
482    }
483
484    /// Sets the right offset in bars; non-finite values are ignored.
485    pub fn set_right_offset(&mut self, bars: f64) {
486        if bars.is_finite() {
487            self.right_offset = bars;
488            self.pending = None;
489            self.clamp();
490            self.changed = true;
491        }
492    }
493
494    /// Pans by `dx` (positive = content moves right, showing earlier bars).
495    pub fn scroll_by(&mut self, dx: Px) {
496        let d = f64::from(dx.0) / self.bar_spacing;
497        if d.is_finite() {
498            self.right_offset -= d;
499            self.pending = None;
500            self.clamp();
501            self.changed = true;
502        }
503    }
504
505    /// Zooms by `factor` (> 1 zooms in) keeping the bar under `anchor_x` fixed.
506    pub fn zoom(&mut self, anchor_x: Px, factor: f64) {
507        if !(factor.is_finite() && factor > 0.0) {
508            return;
509        }
510        let x = f64::from(anchor_x.0);
511        let at = self.x_to_index(anchor_x);
512        let spacing = (self.bar_spacing * factor)
513            .clamp(self.effective_min_spacing(), self.max_spacing.max(1e-9));
514        self.bar_spacing = spacing;
515        self.right_offset = at - self.last as f64 - 0.5 + (self.width - x) / spacing;
516        self.pending = None;
517        self.clamp();
518        self.changed = true;
519    }
520
521    /// Shows all bars.
522    pub fn fit_content(&mut self) {
523        self.pending = Some(Pending::Fit);
524        self.apply_pending();
525        self.changed = true;
526    }
527
528    /// Shows logical indices `from..to` across the plot (the left and right
529    /// edges), as far as the spacing limits allow (the right edge is kept).
530    /// Like [`fit_content`](Self::fit_content) it waits for the plot width,
531    /// so it may be called before the first frame or
532    /// together with a resize; panning or zooming drops it.
533    ///
534    /// # Errors
535    ///
536    /// [`Error::InvalidArgument`] unless `from` and `to` are finite and
537    /// `from < to`; the view is unchanged.
538    ///
539    /// # Examples
540    ///
541    /// ```
542    /// use ferrochart_core::{Chart, ChartOptions};
543    /// use ferrochart_core::chart::{SeriesData, SeriesOptions};
544    /// use ferrochart_core::frame::SeriesKind;
545    /// use ferrochart_core::geom::SizeCss;
546    /// use ferrochart_core::testing::{random_walk, MonoMeasurer};
547    ///
548    /// let mut chart = Chart::new(ChartOptions::default());
549    /// chart.resize(SizeCss { w: 800.0, h: 450.0 }, 1.0);
550    /// let pane = chart.main_pane();
551    /// let candles = chart.add_series(pane, SeriesKind::Candlestick, SeriesOptions::default())?;
552    /// chart.set_data(candles, SeriesData::Ohlc(random_walk(1, 500, 0, 60_000)?))?;
553    /// // Before the first frame: applied once the layout is known.
554    /// chart.time_scale().set_visible_range(100.0, 200.0)?;
555    /// chart.build_frame(0.0, &MonoMeasurer);
556    /// let (from, to) = chart.time_scale().visible_range();
557    /// assert!((from - 100.0).abs() < 1e-6 && (to - 200.0).abs() < 1e-6);
558    /// assert!(chart.time_scale().set_visible_range(5.0, 5.0).is_err());
559    /// # Ok::<(), ferrochart_core::Error>(())
560    /// ```
561    pub fn set_visible_range(&mut self, from: LogicalIndex, to: LogicalIndex) -> Result<()> {
562        if !(from.is_finite() && to.is_finite() && from < to) {
563            return Err(Error::InvalidArgument(
564                "the visible range must be finite with from < to",
565            ));
566        }
567        self.show_span(from, to);
568        Ok(())
569    }
570
571    /// Shows logical indices `from..to` across the plot (`from < to`), as far
572    /// as the spacing limits allow (the right edge is kept).
573    pub(crate) fn show_span(&mut self, from: f64, to: f64) {
574        self.pending = Some(Pending::Span { from, to });
575        self.apply_pending();
576        self.changed = true;
577    }
578
579    /// Applies the pending view; `false` while it cannot be applied yet (no
580    /// width or no bars).
581    fn apply_pending(&mut self) -> bool {
582        let Some(pending) = self.pending else {
583            return false;
584        };
585        if self.width <= 0.0 || self.bars == 0 {
586            return false;
587        }
588        match pending {
589            Pending::Fit => {
590                self.bar_spacing = self.width / self.bars as f64;
591                self.right_offset = 0.0;
592            }
593            Pending::Span { from, to } => {
594                self.bar_spacing = self.width / (to - from);
595                self.right_offset = to - self.last as f64 - 0.5;
596            }
597        }
598        self.clamp();
599        true
600    }
601
602    /// End of the layout: the plot width is final, so a pending view that
603    /// could be applied is done.
604    pub(crate) fn settle(&mut self) {
605        if self.apply_pending() {
606            self.pending = None;
607        }
608    }
609
610    /// Visible logical range `(from, to)` (left and right plot edges).
611    pub fn visible_range(&self) -> (LogicalIndex, LogicalIndex) {
612        let to = self.last as f64 + self.right_offset + 0.5;
613        (to - self.width / self.bar_spacing, to)
614    }
615
616    /// x of the center of logical index `i`, relative to the plot's left edge.
617    ///
618    /// # Examples
619    ///
620    /// ```
621    /// use ferrochart_core::{Chart, ChartOptions};
622    ///
623    /// let mut chart = Chart::new(ChartOptions::default());
624    /// let ts = chart.time_scale();
625    /// let x = ts.index_to_x(3.0);
626    /// assert!((ts.x_to_index(x) - 3.0).abs() < 1e-3);
627    /// ```
628    pub fn index_to_x(&self, i: LogicalIndex) -> Px {
629        Px(self.index_to_x_f64(i) as f32)
630    }
631
632    pub(crate) fn index_to_x_f64(&self, i: f64) -> f64 {
633        self.width - (self.last as f64 + self.right_offset - i + 0.5) * self.bar_spacing
634    }
635
636    /// Logical index at x (relative to the plot's left edge).
637    pub fn x_to_index(&self, x: Px) -> LogicalIndex {
638        self.last as f64 + self.right_offset + 0.5
639            - (self.width - f64::from(x.0)) / self.bar_spacing
640    }
641
642    /// Scrolls so that the first bar sits at the left edge.
643    pub(crate) fn scroll_to_first(&mut self) {
644        if self.bars == 0 || self.bar_spacing <= 0.0 {
645            return;
646        }
647        let to = self.first as f64 - 0.5 + self.width / self.bar_spacing;
648        self.set_right_offset(to - self.last as f64 - 0.5);
649    }
650
651    /// Updates the data extent; called by the chart after data changes.
652    pub(crate) fn set_extent(&mut self, first: i64, end: i64) {
653        self.first = first;
654        self.last = end - 1;
655        self.bars = usize::try_from(end - first).unwrap_or(0);
656        self.apply_pending();
657        self.clamp();
658    }
659
660    /// Updates the plot width (physical pixels).
661    pub(crate) fn set_width(&mut self, width: f64) {
662        if (width - self.width).abs() > f64::EPSILON {
663            self.width = width.max(0.0);
664            self.apply_pending();
665            self.clamp();
666        }
667    }
668
669    /// Rescales the spacing when the device pixel ratio changes.
670    pub(crate) fn rescale(&mut self, ratio: f64) {
671        self.bar_spacing *= ratio;
672        self.min_spacing *= ratio;
673        self.max_spacing *= ratio;
674        self.clamp();
675        self.changed = true;
676    }
677
678    /// Keeps the spacing in range and at least one bar on screen.
679    fn clamp(&mut self) {
680        self.bar_spacing = self
681            .bar_spacing
682            .clamp(self.effective_min_spacing(), self.max_spacing.max(1e-9));
683        if self.bars == 0 || self.width <= 0.0 {
684            return;
685        }
686        let lo = (self.first - self.last) as f64 + 0.5;
687        let hi = (self.width / self.bar_spacing - 1.0).max(lo);
688        self.right_offset = self.right_offset.clamp(lo, hi);
689    }
690}
691
692#[cfg(test)]
693mod tests {
694    use super::*;
695
696    #[test]
697    fn days_from_civil_inverts_civil_from_days() {
698        for d in [-800_000_i64, -1, 0, 59, 60, 11_016, 19_723, 2_000_000] {
699            let (y, m, dd) = civil_from_days(d);
700            assert_eq!(days_from_civil(y, m, dd), d);
701        }
702    }
703
704    #[test]
705    fn time_ticks_are_aligned_and_spaced() {
706        let t0 = 1_710_513_000_000; // 2024-03-15T14:30:00Z
707        let mut out = Vec::new();
708        // Six hours over 600 px, 60 px apart: at most 10 ticks of 1 h.
709        time_ticks(t0, t0 + 6 * 3_600_000, 600.0, 60.0, &mut out);
710        assert_eq!(out.len(), 6);
711        assert!(
712            out.iter()
713                .all(|&(t, w)| t % 3_600_000 == 0 && w == TickWeight::Hour)
714        );
715        // Ten years: whole years.
716        time_ticks(t0, t0 + 3650 * DAY_MS, 600.0, 60.0, &mut out);
717        assert!(out.iter().all(|&(_, w)| w == TickWeight::Year), "{out:?}");
718        assert!(out.windows(2).all(|w| w[0].0 < w[1].0));
719        // Empty or degenerate ranges.
720        time_ticks(t0, t0, 600.0, 60.0, &mut out);
721        assert!(out.is_empty());
722    }
723    use proptest::prelude::*;
724
725    #[test]
726    fn pending_view_follows_width_until_settled() {
727        let mut ts = TimeScale::new(6.0, 0.0, 0.5, 50.0);
728        ts.set_extent(0, 100);
729        ts.set_width(600.0);
730        // Fit with a stale width; the layout then narrows the plot.
731        ts.fit_content();
732        ts.set_width(540.0);
733        ts.settle();
734        let (from, to) = ts.visible_range();
735        assert!(
736            (from + 0.5).abs() < 1e-9 && (to - 99.5).abs() < 1e-9,
737            "{from} {to}"
738        );
739        // Settled: a later width change keeps the spacing.
740        ts.set_width(600.0);
741        assert!((ts.bar_spacing() - 5.4).abs() < 1e-9);
742
743        ts.show_span(20.0, 60.0);
744        ts.set_width(400.0);
745        ts.settle();
746        let (from, to) = ts.visible_range();
747        assert!(
748            (from - 20.0).abs() < 1e-9 && (to - 60.0).abs() < 1e-9,
749            "{from} {to}"
750        );
751        // A user zoom drops a pending view.
752        ts.show_span(0.0, 50.0);
753        ts.set_bar_spacing(4.0);
754        ts.set_width(500.0);
755        ts.settle();
756        assert!((ts.bar_spacing() - 4.0).abs() < 1e-9);
757    }
758
759    #[test]
760    fn known_dates() {
761        assert_eq!(civil_from_days(11_016), (2000, 2, 29));
762        assert_eq!(civil_from_days(-719_468), (0, 3, 1));
763        assert_eq!(civil_from_days(2_932_896), (9999, 12, 31));
764    }
765
766    #[test]
767    fn labels() {
768        let mut s = crate::text::StackStr::<16>::new();
769        let t = 1_704_067_200_000; // 2024-01-01
770        for (w, want) in [
771            (TickWeight::Year, "2024"),
772            (TickWeight::Month, "Jan"),
773            (TickWeight::Day, "1"),
774            (TickWeight::Minute, "00:00"),
775            (TickWeight::Second, "00:00:00"),
776        ] {
777            s.clear();
778            format_tick(t, w, &mut s).unwrap();
779            assert_eq!(s.as_str(), want);
780        }
781    }
782
783    #[test]
784    fn ticks_find_exact_boundaries() {
785        // Daily bars from 2023-12-20 for 40 days, sampled every 8 bars.
786        let start = 1_703_030_400_000;
787        let index = TimeIndex::from_times((0..40).map(|d| start + d * DAY_MS).collect()).unwrap();
788        let mut out = Vec::new();
789        collect_ticks(&index, &Utc, 0, 39, 3, &mut out);
790        let year = out.iter().find(|t| t.weight == TickWeight::Year).unwrap();
791        assert_eq!(index.time_at(year.index), Some(1_704_067_200_000));
792    }
793
794    proptest! {
795        /// civil_from_days is consistent with stepping one day at a time.
796        #[test]
797        fn civil_steps_by_one_day(days in -1_000_000i64..1_000_000) {
798            let (y0, m0, d0) = civil_from_days(days);
799            let (y1, m1, d1) = civil_from_days(days + 1);
800            let next_day = d1 == d0 + 1 && m1 == m0 && y1 == y0;
801            let next_month = d1 == 1 && ((m1 == m0 + 1 && y1 == y0) || (m0 == 12 && m1 == 1 && y1 == y0 + 1));
802            prop_assert!(next_day || next_month);
803            prop_assert!((28..=31).contains(&d0) || next_day);
804        }
805
806        /// Zooming keeps the anchor's logical index fixed (when not clamped).
807        #[test]
808        fn zoom_keeps_anchor(x in 0.0f32..800.0, factor in 0.5f64..2.0) {
809            let mut ts = TimeScale::new(6.0, 3.0, 0.5, 50.0);
810            ts.set_extent(0, 1000);
811            ts.set_width(800.0);
812            let before = ts.x_to_index(Px(x));
813            ts.zoom(Px(x), factor);
814            prop_assert!((ts.x_to_index(Px(x)) - before).abs() < 1e-6);
815        }
816    }
817}