use std::rc::Rc;
use arc_motion::{is_reduced_motion, motion_now};
use arc_tokens::{ActiveArcTheme as _, Radii, Spacing, Typography, oklab_mix};
use gpui_kit::{
App, Bounds, Context, ElementId, FocusHandle, Hsla, InteractiveElement as _, IntoElement,
KeyDownEvent, MouseButton, MouseDownEvent, MouseMoveEvent, ParentElement, Pixels, RenderOnce,
Role, SharedString, Styled, Window, base::StyledExt as _, canvas, div, point, prelude::*, px,
};
use super::common::{
ChartSpring, build_area_fill, build_band_fill, build_circle_fill, build_polyline_stroke,
format_compact, format_grouped, nice_scale,
};
const DAY_MS: f64 = 86_400_000.0;
const PLOT_TOP: f32 = 24.0;
const GRIP_HIT: f32 = 12.0;
#[derive(Clone, Debug)]
pub struct BrushChartDatum {
pub timestamp_ms: f64,
pub value: f64,
}
impl BrushChartDatum {
pub fn new(timestamp_ms: f64, value: f64) -> Self {
Self {
timestamp_ms,
value,
}
}
}
#[derive(Clone, Debug)]
pub struct BrushChartAnnotation {
pub timestamp_ms: f64,
pub label: SharedString,
pub description: Option<SharedString>,
}
impl BrushChartAnnotation {
pub fn new(timestamp_ms: f64, label: impl Into<SharedString>) -> Self {
Self {
timestamp_ms,
label: label.into(),
description: None,
}
}
pub fn description(mut self, desc: impl Into<SharedString>) -> Self {
self.description = Some(desc.into());
self
}
}
#[derive(Clone, Debug)]
pub struct SmoothedPoint {
pub t: f64,
pub value: f64,
pub low: f64,
pub high: f64,
}
pub fn format_utc_date(ms: f64, include_year: bool) -> String {
let days = (ms / DAY_MS).floor() as i64;
let (y, m, d) = civil_from_days(days);
const MONTHS: [&str; 12] = [
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
];
let mon = MONTHS[(m.clamp(1, 12) - 1) as usize];
if include_year {
format!("{mon} {d}, {y}")
} else {
format!("{mon} {d}")
}
}
pub(crate) fn civil_from_days(z: i64) -> (i32, u32, u32) {
let z = z + 719_468;
let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
let doe = (z - era * 146_097) as u64;
let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
let y = (yoe as i64) + era * 400;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = doy - (153 * mp + 2) / 5 + 1;
let m = if mp < 10 { mp + 3 } else { mp - 9 };
let year = (y + if m <= 2 { 1 } else { 0 }) as i32;
(year, m as u32, d as u32)
}
#[cfg(test)]
pub(crate) fn days_from_civil(y: i32, m: u32, d: u32) -> i64 {
let y = y as i64 - if m <= 2 { 1 } else { 0 };
let era = if y >= 0 { y } else { y - 399 } / 400;
let yoe = (y - era * 400) as u64;
let m = m as u64;
let d = d as u64;
let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + d - 1;
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
era * 146_097 + doe as i64 - 719_468
}
pub fn brush_smooth_series(data: &[BrushChartDatum]) -> Vec<SmoothedPoint> {
if data.is_empty() {
return Vec::new();
}
let n = data.len();
let mut raw = Vec::with_capacity(n);
for i in 0..n {
let lo_i = i.saturating_sub(3);
let hi_i = (i + 3).min(n - 1);
let mut sum = 0.0;
let mut low = f64::INFINITY;
let mut high = f64::NEG_INFINITY;
let mut cnt = 0.0;
for item in &data[lo_i..=hi_i] {
sum += item.value;
low = low.min(item.value);
high = high.max(item.value);
cnt += 1.0;
}
raw.push((sum / cnt, low, high));
}
let mut out = Vec::with_capacity(n);
for i in 0..n {
let lo_i = i.saturating_sub(3);
let hi_i = (i + 3).min(n - 1);
let mut sum_lo = 0.0;
let mut sum_hi = 0.0;
let mut cnt = 0.0;
for &(_, l, h) in &raw[lo_i..=hi_i] {
sum_lo += l;
sum_hi += h;
cnt += 1.0;
}
out.push(SmoothedPoint {
t: data[i].timestamp_ms,
value: raw[i].0,
low: sum_lo / cnt,
high: sum_hi / cnt,
});
}
out
}
pub fn brush_lower_bound(data: &[BrushChartDatum], t: f64) -> usize {
let mut lo = 0usize;
let mut hi = data.len();
while lo < hi {
let mid = (lo + hi) / 2;
if data[mid].timestamp_ms < t {
lo = mid + 1;
} else {
hi = mid;
}
}
lo
}
pub fn brush_time_ticks(start: f64, end: f64, width: f32) -> Vec<(f64, String)> {
let span = (end - start).max(1.0);
let room = ((width / 82.0).floor() as usize).max(2);
for days in [1.0, 2.0, 7.0, 14.0, 30.0, 60.0, 90.0, 180.0] {
if span / (days * DAY_MS) <= room as f64 {
let step = days * DAY_MS;
let mut t = (start / DAY_MS).ceil() * DAY_MS;
let mut ticks = Vec::new();
while t <= end + 1.0 {
ticks.push((t, format_utc_date(t, days >= 90.0)));
t += step;
}
if !ticks.is_empty() {
return ticks;
}
}
}
vec![
(start, format_utc_date(start, true)),
(end, format_utc_date(end, true)),
]
}
pub fn brush_fit_range(range: (f64, f64), whole: (f64, f64), min_span: f64) -> (f64, f64) {
let total = (whole.1 - whole.0).max(1.0);
let least = min_span.min(total).max(1.0);
let span = (range.1 - range.0).clamp(least, total);
let max_start = (whole.1 - span).max(whole.0);
let s = range.0.clamp(whole.0, max_start);
(s, s + span)
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum DragMode {
Start,
End,
Pan,
New,
}
#[derive(Clone, Copy, Debug)]
struct StripDrag {
mode: DragMode,
anchor_t: f64,
from: (f64, f64),
moved: bool,
start_x: f32,
}
type OnRangeChangeFn = Rc<dyn Fn((f64, f64), &mut Window, &mut App)>;
struct BrushChartState {
focus_handle: FocusHandle,
view: (f64, f64),
target_view: (f64, f64),
initialized: bool,
top_spring: ChartSpring,
reveal_spring: ChartSpring,
active_index: Option<usize>,
drag: Option<StripDrag>,
plot_bounds: Option<Bounds<Pixels>>,
strip_bounds: Option<Bounds<Pixels>>,
last_frame_secs: Option<f64>,
last_whole: (f64, f64),
}
impl BrushChartState {
fn new(cx: &mut Context<Self>) -> Self {
Self {
focus_handle: cx.focus_handle(),
view: (0.0, 1.0),
target_view: (0.0, 1.0),
initialized: false,
top_spring: ChartSpring::new(1.0),
reveal_spring: ChartSpring::new(0.0),
active_index: None,
drag: None,
plot_bounds: None,
strip_bounds: None,
last_frame_secs: None,
last_whole: (0.0, 1.0),
}
}
}
#[derive(IntoElement)]
pub struct BrushChart {
id: ElementId,
label: SharedString,
data: Vec<BrushChartDatum>,
unit: SharedString,
annotations: Vec<BrushChartAnnotation>,
default_range: Option<(f64, f64)>,
min_span_ms: f64,
height: f32,
overview_height: f32,
empty_label: SharedString,
on_range_change: Option<OnRangeChangeFn>,
}
impl BrushChart {
pub fn new(
id: impl Into<ElementId>,
label: impl Into<SharedString>,
data: Vec<BrushChartDatum>,
) -> Self {
Self {
id: id.into(),
label: label.into(),
data,
unit: SharedString::from(""),
annotations: Vec::new(),
default_range: None,
min_span_ms: 7.0 * DAY_MS,
height: 224.0,
overview_height: 52.0,
empty_label: SharedString::from("No data yet"),
on_range_change: None,
}
}
pub fn unit(mut self, unit: impl Into<SharedString>) -> Self {
self.unit = unit.into();
self
}
pub fn annotations(mut self, annotations: Vec<BrushChartAnnotation>) -> Self {
self.annotations = annotations;
self
}
pub fn default_range(mut self, start_ms: f64, end_ms: f64) -> Self {
self.default_range = Some((start_ms, end_ms));
self
}
pub fn min_span_ms(mut self, min_span_ms: f64) -> Self {
self.min_span_ms = min_span_ms.max(DAY_MS);
self
}
pub fn height(mut self, height: f32) -> Self {
self.height = height.max(120.0);
self
}
pub fn overview_height(mut self, height: f32) -> Self {
self.overview_height = height.max(36.0);
self
}
pub fn empty_label(mut self, label: impl Into<SharedString>) -> Self {
self.empty_label = label.into();
self
}
pub fn on_range_change(
mut self,
f: impl Fn((f64, f64), &mut Window, &mut App) + 'static,
) -> Self {
self.on_range_change = Some(Rc::new(f));
self
}
fn format_val(&self, v: f64) -> String {
let base = format_grouped(v, 1);
if self.unit.is_empty() {
base
} else {
format!("{base} {}", self.unit)
}
}
}
impl RenderOnce for BrushChart {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let colors = cx.arc_theme().colors;
let reduced = is_reduced_motion(cx);
let now = motion_now(cx);
let state = window.use_keyed_state(
ElementId::NamedChild(self.id.clone().into(), "state".into()),
cx,
|_, cx| BrushChartState::new(cx),
);
let empty = self.data.len() < 2;
let whole = if empty {
(0.0, 1.0)
} else {
(
self.data.first().unwrap().timestamp_ms,
self.data.last().unwrap().timestamp_ms,
)
};
let smooth = brush_smooth_series(&self.data);
let mut animating = false;
let (view, top_now, reveal_val, active_idx, plot_w, strip_w) = state.update(cx, |st, _| {
let dt = st
.last_frame_secs
.map(|prev| (now - prev).clamp(0.0, 0.05) as f32)
.unwrap_or(0.016);
st.last_frame_secs = Some(now);
if !st.initialized || st.last_whole != whole {
let init_r = self.default_range.unwrap_or(whole);
let fitted = brush_fit_range(init_r, whole, self.min_span_ms);
st.view = fitted;
st.target_view = fitted;
st.last_whole = whole;
st.initialized = true;
}
if st.drag.is_none() {
if reduced {
st.view = st.target_view;
} else {
let alpha = (1.0 - (-12.0 * dt as f64).exp()).clamp(0.0, 1.0);
let ds = st.target_view.0 - st.view.0;
let de = st.target_view.1 - st.view.1;
if ds.abs() + de.abs() > (whole.1 - whole.0) * 1e-4 {
st.view.0 += ds * alpha;
st.view.1 += de * alpha;
animating = true;
} else {
st.view = st.target_view;
}
}
}
let from = brush_lower_bound(&self.data, st.view.0).saturating_sub(1);
let to = (brush_lower_bound(&self.data, st.view.1) + 1).min(self.data.len());
let mut peak = 1.0f64;
for d in &self.data[from..to] {
peak = peak.max(d.value);
}
let sc = nice_scale(0.0, peak * 1.06, 4);
let target_top = sc.max as f32;
if reduced || st.top_spring.value <= 1.01 {
st.top_spring.snap(target_top);
} else if !st.top_spring.is_settled_at(target_top, 0.05) {
st.top_spring.step_to(target_top, 0.36, 0.0, dt);
animating = true;
}
if empty || reduced {
st.reveal_spring.snap(1.0);
} else if !st.reveal_spring.is_settled_at(1.0, 0.002) {
st.reveal_spring.step_to(1.0, 0.85, 0.0, dt);
animating = true;
}
let pw = st
.plot_bounds
.map(|b| f32::from(b.size.width))
.unwrap_or(520.0)
.max(120.0);
let sw = st
.strip_bounds
.map(|b| f32::from(b.size.width))
.unwrap_or(520.0)
.max(120.0);
let idx = st.active_index.filter(|&i| i >= from && i < to);
(
st.view,
st.top_spring.value.max(1.0),
st.reveal_spring.value.clamp(0.0, 1.0),
idx,
pw,
sw,
)
});
if animating {
window.request_animation_frame();
}
let (start, end) = view;
let span = (end - start).max(1.0);
let from = brush_lower_bound(&self.data, start).saturating_sub(1);
let to = (brush_lower_bound(&self.data, end) + 1).min(self.data.len());
let mut peak = 1.0f64;
for d in &self.data[from..to] {
peak = peak.max(d.value);
}
let scale = nice_scale(0.0, peak * 1.06, 4);
let px_per_point = if empty {
plot_w
} else {
(plot_w * ((whole.1 - whole.0) / span) as f32) / (self.data.len() - 1).max(1) as f32
};
let detail = ((px_per_point - 2.75) / 1.5).clamp(0.0, 1.0);
let accent = colors.series.series_1;
let grid_color = colors.border_subtle;
let baseline_color = colors.border;
let crosshair_color = oklab_mix(colors.foreground, colors.surface, 0.35);
let paint_data = self.data.clone();
let paint_smooth = smooth.clone();
let paint_ticks = scale.ticks.clone();
let paint_annotations = self.annotations.clone();
let state_plot_bounds = state.clone();
let paint_h = self.height;
let main_canvas = canvas(
move |bounds, _, cx| {
state_plot_bounds.update(cx, |st, _| st.plot_bounds = Some(bounds));
bounds
},
move |bounds, _, window, _cx| {
let w = f32::from(bounds.size.width).max(1.0);
let h = f32::from(bounds.size.height).max(1.0);
let ox = f32::from(bounds.origin.x);
let oy = f32::from(bounds.origin.y);
let to_x = |t: f64| ox + (((t - start) / span) as f32) * w;
let to_y = |v: f64| oy + PLOT_TOP + (1.0 - (v as f32 / top_now)) * (h - PLOT_TOP);
for &tick in &paint_ticks {
let y = to_y(tick);
let col = if tick.abs() < 1e-6 {
baseline_color
} else {
grid_color
};
if let Some(p) = build_polyline_stroke(
&[point(px(ox), px(y)), point(px(ox + w), px(y))],
1.0,
) {
window.paint_path(p, col);
}
}
for ev in &paint_annotations {
if ev.timestamp_ms >= start && ev.timestamp_ms <= end {
let ex = to_x(ev.timestamp_ms);
if let Some(p) = build_polyline_stroke(
&[
point(px(ex), px(oy + PLOT_TOP - 8.0)),
point(px(ex), px(oy + h)),
],
1.0,
) {
window
.paint_path(p, oklab_mix(colors.foreground, colors.surface, 0.25));
}
if let Some(dot) = build_circle_fill(ex, oy + PLOT_TOP - 8.0, 3.0, 12) {
window.paint_path(dot, accent);
}
}
}
if paint_data.len() >= 2 && to > from {
let reveal_x = ox + w * reveal_val;
let mut raw_pts = Vec::new();
let mut trend_pts = Vec::new();
let mut upper_pts = Vec::new();
let mut lower_pts = Vec::new();
for i in from..to {
let px_x = to_x(paint_data[i].timestamp_ms);
if px_x > reveal_x + 4.0 {
break;
}
raw_pts.push(point(px(px_x), px(to_y(paint_data[i].value))));
trend_pts.push(point(px(px_x), px(to_y(paint_smooth[i].value))));
upper_pts.push(point(px(px_x), px(to_y(paint_smooth[i].high))));
lower_pts.push(point(px(px_x), px(to_y(paint_smooth[i].low))));
}
if (1.0 - detail) > 0.02 {
let band_a = (1.0 - detail) * 0.16;
if let Some(band_p) = build_band_fill(&upper_pts, &lower_pts) {
window.paint_path(
band_p,
Hsla {
a: accent.a * band_a,
..accent
},
);
}
if let Some(tr_p) = build_polyline_stroke(&trend_pts, 2.0) {
window.paint_path(
tr_p,
Hsla {
a: accent.a * (1.0 - detail),
..accent
},
);
}
}
if detail > 0.02 {
if let Some(area_p) = build_area_fill(&raw_pts, px(oy + h)) {
window.paint_path(
area_p,
Hsla {
a: accent.a * 0.14 * detail,
..accent
},
);
}
if let Some(line_p) = build_polyline_stroke(&raw_pts, 2.0) {
window.paint_path(
line_p,
Hsla {
a: accent.a * detail,
..accent
},
);
}
}
}
if let Some(idx) = active_idx
&& let Some(d) = paint_data.get(idx)
{
let s_val = paint_smooth.get(idx).map(|p| p.value).unwrap_or(d.value);
let blend_v = s_val + (d.value - s_val) * detail as f64;
let cx_px = to_x(d.timestamp_ms);
let cy_px = to_y(blend_v);
if let Some(ch) = build_polyline_stroke(
&[
point(px(cx_px), px(oy + PLOT_TOP - 8.0)),
point(px(cx_px), px(oy + h)),
],
1.0,
) {
window.paint_path(ch, crosshair_color);
}
if let Some(outer) = build_circle_fill(cx_px, cy_px, 5.0, 16) {
window.paint_path(outer, colors.surface);
}
if let Some(inner) = build_circle_fill(cx_px, cy_px, 3.5, 16) {
window.paint_path(inner, accent);
}
}
},
)
.size_full();
let state_plot_move = state.clone();
let state_plot_hover = state.clone();
let state_plot_key = state.clone();
let move_data = self.data.clone();
let key_data_len = self.data.len();
let key_min_span = self.min_span_ms;
let key_on_range = self.on_range_change.clone();
let focus_handle = state.read(cx).focus_handle.clone();
let mut annotation_labels = Vec::new();
let mut last_label_right = -100.0f32;
for ev in &self.annotations {
if ev.timestamp_ms >= start && ev.timestamp_ms <= end {
let x_px = (((ev.timestamp_ms - start) / span) as f32) * plot_w;
let w_est = (ev.label.len() as f32 * 6.4 + 10.0).max(40.0);
if x_px + 6.0 >= last_label_right && x_px + 6.0 + w_est <= plot_w {
annotation_labels.push((x_px + 6.0, ev.label.clone()));
last_label_right = x_px + 6.0 + w_est + 6.0;
}
}
}
let tooltip_el = active_idx
.and_then(|idx| self.data.get(idx).map(|d| (idx, d)))
.map(|(idx, d)| {
let x_px = (((d.timestamp_ms - start) / span) as f32) * plot_w;
let tip_w = 184.0f32;
let left = if x_px + 14.0 + tip_w <= plot_w {
x_px + 14.0
} else {
(x_px - 14.0 - tip_w).max(4.0)
};
let prev = idx.checked_sub(7).and_then(|pi| self.data.get(pi));
let pct_change = prev.and_then(|p| {
if p.value.abs() > 1e-6 {
Some((d.value - p.value) / p.value * 100.0)
} else {
None
}
});
let ev_at = self
.annotations
.iter()
.find(|ev| (ev.timestamp_ms - d.timestamp_ms).abs() < DAY_MS * 0.5);
div()
.absolute()
.left(px(left))
.top(px(PLOT_TOP + 6.0))
.w(px(tip_w))
.p(Spacing::S2)
.rounded(Radii::CONTROL)
.bg(colors.surface_raised)
.border_1()
.border_color(colors.border)
.flex()
.flex_col()
.gap(px(2.0))
.child(
div()
.text_size(Typography::TEXT_XS)
.text_color(colors.text_muted)
.child(format_utc_date(d.timestamp_ms, true)),
)
.child(
div()
.text_size(Typography::TEXT_SM)
.font_semibold()
.text_color(colors.foreground)
.child(self.format_val(d.value)),
)
.when_some(pct_change, |this, pct| {
let sign = if pct >= 0.0 { "+" } else { "−" };
this.child(
div()
.text_size(Typography::TEXT_XS)
.text_color(colors.text_secondary)
.child(format!("{sign}{:.1}% vs 7d ago", pct.abs())),
)
})
.when_some(ev_at, |this, ev| {
this.child(
div()
.pt(px(2.0))
.flex()
.items_center()
.gap(px(5.0))
.child(div().size(px(6.0)).rounded(Radii::PILL).bg(accent))
.child(
div()
.text_size(Typography::TEXT_XS)
.font_medium()
.text_color(colors.foreground)
.child(ev.label.clone()),
),
)
})
});
let mut main_plot = div()
.id(ElementId::NamedChild(self.id.clone().into(), "plot".into()))
.role(Role::Group)
.track_focus(&focus_handle)
.relative()
.flex_1()
.h(px(self.height))
.overflow_hidden()
.cursor_crosshair()
.on_mouse_move(move |event: &MouseMoveEvent, window, cx| {
if empty {
return;
}
state_plot_move.update(cx, |st, _| {
if let Some(bounds) = st.plot_bounds {
let w = f32::from(bounds.size.width).max(1.0);
let local_x = (f32::from(event.position.x) - f32::from(bounds.origin.x))
.clamp(0.0, w);
let t = st.view.0 + (local_x / w) as f64 * (st.view.1 - st.view.0);
let nearest = if move_data.len() <= 1 {
0
} else {
let at = brush_lower_bound(&move_data, t)
.clamp(1, move_data.len().saturating_sub(1));
if (t - move_data[at - 1].timestamp_ms).abs()
< (move_data[at].timestamp_ms - t).abs()
{
at - 1
} else {
at
}
};
st.active_index = Some(nearest);
}
});
window.refresh();
})
.on_hover(move |hovered, window, cx| {
if !*hovered {
state_plot_hover.update(cx, |st, _| st.active_index = None);
window.refresh();
}
})
.on_key_down(move |event: &KeyDownEvent, window, cx| {
if empty || key_data_len == 0 {
return;
}
let key = event.keystroke.key.as_str();
let mut range_changed = None;
let mut handled = true;
state_plot_key.update(cx, |st, _| {
let cur = st.active_index.unwrap_or(to.saturating_sub(1));
let page = ((to.saturating_sub(from)) / 8).max(1);
let win = st.target_view.1 - st.target_view.0;
match key {
"escape" => {
if st.active_index.is_some() {
st.active_index = None;
} else {
st.target_view = whole;
range_changed = Some(whole);
}
}
"0" => {
st.target_view = whole;
range_changed = Some(whole);
}
"+" | "=" => {
let next = brush_fit_range(
(st.target_view.0 + win * 0.2, st.target_view.1 - win * 0.2),
whole,
key_min_span,
);
st.target_view = next;
range_changed = Some(next);
}
"-" | "_" => {
let next = brush_fit_range(
(st.target_view.0 - win * 0.35, st.target_view.1 + win * 0.35),
whole,
key_min_span,
);
st.target_view = next;
range_changed = Some(next);
}
"left" => {
st.active_index = Some(cur.saturating_sub(1).max(from));
}
"right" => {
st.active_index = Some((cur + 1).min(to.saturating_sub(1)));
}
"pageup" => {
st.active_index = Some((cur + page).min(to.saturating_sub(1)));
}
"pagedown" => {
st.active_index = Some(cur.saturating_sub(page).max(from));
}
"home" => {
st.active_index = Some(from);
}
"end" => {
st.active_index = Some(to.saturating_sub(1));
}
_ => handled = false,
}
});
if handled {
if let (Some(cb), Some(r)) = (&key_on_range, range_changed) {
cb(r, window, cx);
}
cx.stop_propagation();
window.refresh();
}
})
.child(main_canvas);
for (lx, lbl) in annotation_labels {
main_plot = main_plot.child(
div()
.absolute()
.left(px(lx))
.top(px(4.0))
.text_size(Typography::TEXT_XS)
.font_medium()
.text_color(colors.text_secondary)
.child(lbl),
);
}
if let Some(tip) = tooltip_el {
main_plot = main_plot.child(tip);
}
if empty {
main_plot = main_plot.child(
div()
.absolute()
.inset_0()
.flex()
.items_center()
.justify_center()
.text_size(Typography::TEXT_SM)
.text_color(colors.text_muted)
.child(self.empty_label.clone()),
);
}
let y_gutter = div()
.relative()
.w(px(44.0))
.h(px(self.height))
.flex_none()
.children(scale.ticks.iter().map(|&tick| {
let y = PLOT_TOP + (1.0 - (tick as f32 / top_now)) * (paint_h - PLOT_TOP);
div()
.absolute()
.right(px(0.0))
.top(px((y - 7.0).clamp(0.0, (paint_h - 14.0).max(0.0))))
.text_size(Typography::TEXT_XS)
.text_color(colors.text_muted)
.child(format_compact(tick))
}));
let x_ticks = if empty {
Vec::new()
} else {
brush_time_ticks(start, end, plot_w)
};
let x_axis = div()
.relative()
.w(px(plot_w))
.h(px(18.0))
.children(x_ticks.into_iter().map(|(t, lbl)| {
let x = (((t - start) / span) as f32 * plot_w - 28.0)
.clamp(0.0, (plot_w - 56.0).max(0.0));
div()
.absolute()
.left(px(x))
.top(px(0.0))
.w(px(56.0))
.flex()
.justify_center()
.text_size(Typography::TEXT_XS)
.text_color(colors.text_muted)
.child(lbl)
}));
let whole_span = (whole.1 - whole.0).max(1.0);
let wx0 = (((start - whole.0) / whole_span) as f32 * strip_w).clamp(0.0, strip_w);
let wx1 = (((end - whole.0) / whole_span) as f32 * strip_w).clamp(wx0, strip_w);
let ov_smooth = smooth.clone();
let ov_annotations = self.annotations.clone();
let ov_h = self.overview_height;
let state_strip_bounds = state.clone();
let muted_line = oklab_mix(colors.foreground, colors.surface, 0.35);
let overview_canvas = canvas(
move |bounds, _, cx| {
state_strip_bounds.update(cx, |st, _| st.strip_bounds = Some(bounds));
bounds
},
move |bounds, _, window, _cx| {
let w = f32::from(bounds.size.width).max(1.0);
let h = f32::from(bounds.size.height).max(1.0);
let ox = f32::from(bounds.origin.x);
let oy = f32::from(bounds.origin.y);
if ov_smooth.len() < 2 {
return;
}
let max_v = ov_smooth.iter().map(|p| p.value).fold(1.0f64, f64::max);
let to_ox = |t: f64| ox + (((t - whole.0) / whole_span) as f32) * w;
let to_oy = |v: f64| oy + 4.0 + (1.0 - (v / max_v) as f32) * (h - 6.0);
let all_pts: Vec<_> = ov_smooth
.iter()
.map(|p| point(px(to_ox(p.t)), px(to_oy(p.value))))
.collect();
if let Some(area) = build_area_fill(&all_pts, px(oy + h)) {
window.paint_path(
area,
Hsla {
a: muted_line.a * 0.25,
..muted_line
},
);
}
if let Some(line) = build_polyline_stroke(&all_pts, 1.25) {
window.paint_path(line, muted_line);
}
let in_pts: Vec<_> = ov_smooth
.iter()
.filter(|p| p.t >= start && p.t <= end)
.map(|p| point(px(to_ox(p.t)), px(to_oy(p.value))))
.collect();
if let Some(area) = build_area_fill(&in_pts, px(oy + h)) {
window.paint_path(
area,
Hsla {
a: accent.a * 0.22,
..accent
},
);
}
if let Some(line) = build_polyline_stroke(&in_pts, 1.5) {
window.paint_path(line, accent);
}
for ev in &ov_annotations {
let ex = to_ox(ev.timestamp_ms);
if let Some(dot) = build_circle_fill(ex, oy + h * 0.5, 2.5, 10) {
window.paint_path(dot, accent);
}
}
},
)
.size_full();
let state_s_down = state.clone();
let state_s_move = state.clone();
let state_s_up = state.clone();
let min_span_drag = self.min_span_ms;
let move_on_range = self.on_range_change.clone();
let up_on_range = self.on_range_change.clone();
let shade_col = Hsla {
a: 0.45,
..colors.surface_muted
};
let strip_box = div()
.id(ElementId::NamedChild(
self.id.clone().into(),
"strip".into(),
))
.relative()
.w_full()
.h(px(ov_h))
.rounded(Radii::CONTROL)
.border_1()
.border_color(colors.border)
.bg(colors.surface_muted)
.overflow_hidden()
.cursor_grab()
.on_mouse_down(
MouseButton::Left,
move |event: &MouseDownEvent, window, cx| {
if empty {
return;
}
if event.click_count >= 2 {
state_s_down.update(cx, |st, _| {
st.drag = None;
st.target_view = whole;
});
window.refresh();
return;
}
let fh = state_s_down.read(cx).focus_handle.clone();
window.focus(&fh, cx);
state_s_down.update(cx, |st, _| {
if let Some(bounds) = st.strip_bounds {
let w = f32::from(bounds.size.width).max(1.0);
let local_x = (f32::from(event.position.x)
- f32::from(bounds.origin.x))
.clamp(0.0, w);
let cur_wx0 = (((st.view.0 - whole.0) / whole_span) as f32) * w;
let cur_wx1 = (((st.view.1 - whole.0) / whole_span) as f32) * w;
let mode = if (local_x - cur_wx0).abs() <= GRIP_HIT
&& local_x <= (cur_wx0 + cur_wx1) * 0.5
{
DragMode::Start
} else if (local_x - cur_wx1).abs() <= GRIP_HIT {
DragMode::End
} else if local_x > cur_wx0 && local_x < cur_wx1 {
DragMode::Pan
} else {
DragMode::New
};
let anchor_t = whole.0 + (local_x / w) as f64 * whole_span;
st.drag = Some(StripDrag {
mode,
anchor_t,
from: st.view,
moved: false,
start_x: f32::from(event.position.x),
});
}
});
window.refresh();
},
)
.on_mouse_move(move |event: &MouseMoveEvent, window, cx| {
let mut emitted = None;
state_s_move.update(cx, |st, _| {
let Some(mut drag) = st.drag else {
return;
};
if !drag.moved && (f32::from(event.position.x) - drag.start_x).abs() < 2.5 {
return;
}
drag.moved = true;
st.drag = Some(drag);
let Some(bounds) = st.strip_bounds else {
return;
};
let w = f32::from(bounds.size.width).max(1.0);
let local_x =
(f32::from(event.position.x) - f32::from(bounds.origin.x)).clamp(0.0, w);
let t = whole.0 + (local_x / w) as f64 * whole_span;
let shift = t - drag.anchor_t;
let least = min_span_drag.min(whole_span);
let raw = match drag.mode {
DragMode::Pan => (drag.from.0 + shift, drag.from.1 + shift),
DragMode::Start => {
let hi = (drag.from.1 - least).max(whole.0);
(t.clamp(whole.0, hi), drag.from.1)
}
DragMode::End => {
let lo = (drag.from.0 + least).min(whole.1);
(drag.from.0, t.clamp(lo, whole.1))
}
DragMode::New => {
let lo = drag.anchor_t.min(t);
let hi = drag.anchor_t.max(t);
if hi - lo < least {
if t >= drag.anchor_t {
(lo, lo + least)
} else {
(hi - least, hi)
}
} else {
(lo, hi)
}
}
};
let fitted = brush_fit_range(raw, whole, min_span_drag);
st.view = fitted;
st.target_view = fitted;
emitted = Some(fitted);
});
if let (Some(cb), Some(r)) = (&move_on_range, emitted) {
cb(r, window, cx);
}
if emitted.is_some() {
window.refresh();
}
})
.on_mouse_up(MouseButton::Left, move |_, window, cx| {
let mut recentered = None;
state_s_up.update(cx, |st, _| {
if let Some(drag) = st.drag.take()
&& !drag.moved
&& drag.mode == DragMode::New
{
let half = (st.view.1 - st.view.0) * 0.5;
let next = brush_fit_range(
(drag.anchor_t - half, drag.anchor_t + half),
whole,
min_span_drag,
);
st.target_view = next;
recentered = Some(next);
}
});
if let (Some(cb), Some(r)) = (&up_on_range, recentered) {
cb(r, window, cx);
}
window.refresh();
})
.child(overview_canvas)
.child(
div()
.absolute()
.left(px(0.0))
.top(px(0.0))
.bottom(px(0.0))
.w(px(wx0.max(0.0)))
.bg(shade_col),
)
.child(
div()
.absolute()
.left(px(wx1))
.right(px(0.0))
.top(px(0.0))
.bottom(px(0.0))
.bg(shade_col),
)
.child(
div()
.absolute()
.left(px(wx0))
.w(px((wx1 - wx0).max(2.0)))
.top(px(0.0))
.bottom(px(0.0))
.border_1()
.border_color(accent)
.child(
div()
.absolute()
.left(px(-3.0))
.top(px((ov_h - 18.0) * 0.5))
.w(px(6.0))
.h(px(18.0))
.rounded(Radii::PILL)
.bg(colors.surface_raised)
.border_1()
.border_color(accent),
)
.child(
div()
.absolute()
.right(px(-3.0))
.top(px((ov_h - 18.0) * 0.5))
.w(px(6.0))
.h(px(18.0))
.rounded(Radii::PILL)
.bg(colors.surface_raised)
.border_1()
.border_color(accent),
),
);
let window_text = format!(
"{} – {}",
format_utc_date(start, true),
format_utc_date(end, true)
);
div()
.id(self.id)
.w_full()
.flex()
.flex_col()
.gap(Spacing::S2)
.p(Spacing::S4)
.rounded(Radii::PANEL)
.bg(colors.surface)
.border_1()
.border_color(colors.border_subtle)
.child(
div()
.flex()
.items_center()
.justify_between()
.gap(Spacing::S2)
.child(
div()
.text_size(Typography::TEXT_SM)
.font_semibold()
.text_color(colors.foreground)
.child(self.label),
)
.child(
div()
.text_size(Typography::TEXT_XS)
.text_color(colors.text_muted)
.child(window_text),
),
)
.child(
div()
.w_full()
.flex()
.items_stretch()
.gap(Spacing::S2)
.child(main_plot)
.child(y_gutter),
)
.child(x_axis)
.child(strip_box)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn brush_chart_smoothing_window_clamping_and_ticks() {
let base = days_from_civil(2026, 1, 1) as f64 * DAY_MS;
let data: Vec<BrushChartDatum> = (0..60)
.map(|i| BrushChartDatum::new(base + i as f64 * DAY_MS, 100.0 + (i % 7) as f64 * 12.0))
.collect();
let smoothed = brush_smooth_series(&data);
assert_eq!(smoothed.len(), 60);
for p in &smoothed {
assert!(p.low <= p.value + 1e-6);
assert!(p.high >= p.value - 1e-6);
}
let whole = (base, base + 59.0 * DAY_MS);
let fitted = brush_fit_range(
(base - 10.0 * DAY_MS, base - 8.0 * DAY_MS),
whole,
7.0 * DAY_MS,
);
assert!((fitted.0 - whole.0).abs() < 1e-6);
assert!((fitted.1 - fitted.0 - 7.0 * DAY_MS).abs() < 1e-6);
let preserved = brush_fit_range(
(base - 10.0 * DAY_MS, base + 2.0 * DAY_MS),
whole,
7.0 * DAY_MS,
);
assert!((preserved.0 - whole.0).abs() < 1e-6);
assert!((preserved.1 - preserved.0 - 12.0 * DAY_MS).abs() < 1e-6);
let ticks = brush_time_ticks(whole.0, whole.1, 480.0);
assert!(ticks.len() >= 2);
assert_eq!(format_utc_date(base, true), "Jan 1, 2026");
}
}