arc-ui 0.4.0

Physics-first native Rust desktop UI component library & charts for GPUI (120+ interactive components ported from Arc).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
//! Ported from Arc (MIT) © 2026 Elia Kuratli
//! Source: `Arc源码/arc-library/registry/components/usage-meter/usage-meter.tsx` & `usage-meter.module.css`
//!
//! A multi-segment allowance meter (`usage-meter`) for storage, seats, or quota breakdowns:
//! - Monochromatic accent step palette (`100%`, `62%`, `36%`, `22%` accent mixed with `surface`) so
//!   the bar reads as a single allowance rather than a rainbow.
//! - Spring-interpolated segment amounts and plan limit (`usage_meter_bar_geometry`) with `2px`
//!   inter-segment gaps (`USAGE_METER_SEGMENT_GAP_PX`); when total usage exceeds the limit, the bar
//!   span expands smoothly (`span = max(limit, used)`), drawing a `2px` vertical limit marker line
//!   at `limit_x` and diagonal `45°` hatch stripes across the overage region.
//! - Status badge (`Ok` / `Near` / `Over` via `usage_meter_status`) with warning/error alert icon.
//! - Interactive legend and track hover/click pinning: hovering or pinning any category or the
//!   `Free / Over limit` item updates the large display readout (`AnimatedCounter`) and caption to
//!   show that category's value and plan share percentage, while dimming non-selected segments to
//!   `0.28` opacity.

use std::{cell::RefCell, rc::Rc};

use arc_motion::{arc_spring, is_reduced_motion};
use arc_tokens::{ActiveArcTheme as _, Radii, Spacing, Typography, oklab_mix};
use gpui_kit::{
    AnyElement, App, Bounds, ContentMask, Corners, Edges, ElementId, FocusHandle, Hsla,
    IntoElement, KeyDownEvent, MouseButton, MouseMoveEvent, ParentElement, PathBuilder, RenderOnce,
    Role, SharedString, Styled, Window, assets::IconName, base::StyledExt as _, canvas, div, point,
    prelude::*, px, quad, svg,
};

use crate::text::animated_counter::AnimatedCounter;

/// Inter-segment gap in pixels (`2px`).
pub const USAGE_METER_SEGMENT_GAP_PX: f32 = 2.0;

/// Track height in pixels (`14px`).
pub const USAGE_METER_TRACK_HEIGHT_PX: f32 = 14.0;

/// Single category segment in [`UsageMeter`].
#[derive(Clone, Debug, PartialEq)]
pub struct UsageMeterSegment {
    pub id: SharedString,
    pub label: SharedString,
    pub value: f64,
}

impl UsageMeterSegment {
    pub fn new(id: impl Into<SharedString>, label: impl Into<SharedString>, value: f64) -> Self {
        Self {
            id: id.into(),
            label: label.into(),
            value: value.max(0.0),
        }
    }
}

/// Overall quota status of [`UsageMeter`].
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
pub enum UsageMeterStatus {
    Ok,
    Near,
    Over,
}

/// Geometry of a single segment and the overall bar computed by [`usage_meter_bar_geometry`].
#[derive(Clone, Debug, PartialEq)]
pub struct UsageMeterBarGeometry {
    /// `(x_px, width_px)` for each segment inside `track_width`.
    pub segments: Vec<(f32, f32)>,
    /// Total used amount (`sum(amounts)`).
    pub used: f64,
    /// Effective span of the bar (`max(limit, used, 1e-6)`).
    pub span: f64,
    /// Horizontal position (`px`) of the plan limit marker inside `track_width`.
    pub limit_x: f32,
    /// Whether `used > limit`.
    pub is_over: bool,
}

/// Resolves the [`UsageMeterStatus`] for `total_used` against `limit` and `warn_at` (`0.0..=1.0`).
#[inline]
pub fn usage_meter_status(total_used: f64, limit: f64, warn_at: f64) -> UsageMeterStatus {
    if total_used > limit {
        UsageMeterStatus::Over
    } else if total_used >= limit * warn_at.clamp(0.0, 1.0) {
        UsageMeterStatus::Near
    } else {
        UsageMeterStatus::Ok
    }
}

/// Computes the pixel start and width of each segment, the `limit_x` marker position, and whether
/// the bar is over the plan limit.
pub fn usage_meter_bar_geometry(
    amounts: &[f64],
    shown_limit: f64,
    track_width: f32,
) -> UsageMeterBarGeometry {
    let w = track_width.max(0.0);
    let used: f64 = amounts.iter().copied().map(|v| v.max(0.0)).sum();
    let limit = shown_limit.max(1e-6);
    let span = limit.max(used).max(1e-6);
    let limit_x = ((limit / span) as f32 * w).round();
    let is_over = used > limit + 1e-6;

    let mut cursor_val = 0.0_f64;
    let mut segments = Vec::with_capacity(amounts.len());
    for &amt in amounts {
        let amt = amt.max(0.0);
        let x = (cursor_val / span) as f32 * w;
        let raw_size = (amt / span) as f32 * w;
        let rest = (w - x - raw_size).max(0.0);
        let gap = USAGE_METER_SEGMENT_GAP_PX.min(raw_size).min(rest);
        let seg_w = (raw_size - gap).max(0.0);
        segments.push((x, seg_w));
        cursor_val += amt;
    }

    UsageMeterBarGeometry {
        segments,
        used,
        span,
        limit_x,
        is_over,
    }
}

/// Hit-tests a normalized horizontal ratio (`0.0..=1.0`) along the track and returns either the
/// matching segment `id` or `"free"` (which represents free space or overage when past `limit`).
pub fn usage_meter_hit_segment_id(
    ratio_x: f32,
    segments: &[UsageMeterSegment],
    limit: f64,
) -> SharedString {
    let total: f64 = segments.iter().map(|s| s.value.max(0.0)).sum();
    let span = limit.max(total).max(1e-6);
    let at = (ratio_x.clamp(0.0, 1.0) as f64) * span;
    if at > limit {
        return SharedString::from("free");
    }
    let mut end = 0.0;
    for seg in segments {
        end += seg.value.max(0.0);
        if at <= end {
            return seg.id.clone();
        }
    }
    SharedString::from("free")
}

#[inline]
fn round_to_decimals(value: f64, decimals: usize) -> f64 {
    let factor = 10_f64.powi(decimals as i32);
    (value * factor).round() / factor
}

#[inline]
fn format_amount(value: f64, decimals: usize, unit: &str) -> String {
    let num = format!("{:.prec$}", value, prec = decimals);
    if unit.is_empty() {
        num
    } else {
        format!("{num} {unit}")
    }
}

#[inline]
fn segment_swatch_color(index: usize, accent: Hsla, surface: Hsla) -> Hsla {
    match index {
        0 => accent,
        1 => oklab_mix(accent, surface, 0.62),
        2 => oklab_mix(accent, surface, 0.36),
        _ => oklab_mix(accent, surface, 0.22),
    }
}

#[derive(Clone)]
struct UsageMeterInternalState {
    hovered_id: Option<SharedString>,
    pinned_id: Option<SharedString>,
    roving_index: usize,
    track_bounds: Option<Bounds<gpui_kit::Pixels>>,
    focus_handle: FocusHandle,
}

/// Multi-segment allowance usage meter (`usage-meter`).
#[derive(IntoElement)]
pub struct UsageMeter {
    id: ElementId,
    label: SharedString,
    segments: Vec<UsageMeterSegment>,
    limit: f64,
    unit: SharedString,
    decimals: usize,
    free_label: SharedString,
    over_label: SharedString,
    warn_at: f64,
}

impl UsageMeter {
    pub fn new(
        id: impl Into<ElementId>,
        label: impl Into<SharedString>,
        segments: impl IntoIterator<Item = UsageMeterSegment>,
        limit: f64,
    ) -> Self {
        Self {
            id: id.into(),
            label: label.into(),
            segments: segments.into_iter().collect(),
            limit: limit.max(0.001),
            unit: SharedString::from(""),
            decimals: 1,
            free_label: SharedString::from("Free"),
            over_label: SharedString::from("Over limit"),
            warn_at: 0.9,
        }
    }

    pub fn unit(mut self, unit: impl Into<SharedString>) -> Self {
        self.unit = unit.into();
        self
    }

    pub fn decimals(mut self, decimals: usize) -> Self {
        self.decimals = decimals.min(4);
        self
    }

    pub fn free_label(mut self, label: impl Into<SharedString>) -> Self {
        self.free_label = label.into();
        self
    }

    pub fn over_label(mut self, label: impl Into<SharedString>) -> Self {
        self.over_label = label.into();
        self
    }

    pub fn warn_at(mut self, warn_at: f64) -> Self {
        self.warn_at = warn_at.clamp(0.05, 1.0);
        self
    }
}

impl RenderOnce for UsageMeter {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let theme = cx.arc_theme();
        let colors = theme.colors;
        let motion = theme.motion;
        let reduced = is_reduced_motion(cx);

        let state_cell = window
            .use_keyed_state(
                ElementId::NamedChild(
                    self.id.clone().into(),
                    SharedString::from("usage-meter-state"),
                ),
                cx,
                |_, cx| {
                    Rc::new(RefCell::new(UsageMeterInternalState {
                        hovered_id: None,
                        pinned_id: None,
                        roving_index: 0,
                        track_bounds: None,
                        focus_handle: cx.focus_handle(),
                    }))
                },
            )
            .read(cx)
            .clone();

        let total_raw: f64 = self.segments.iter().map(|s| s.value).sum();
        let total = round_to_decimals(total_raw, self.decimals);
        let free = round_to_decimals((self.limit - total).max(0.0), self.decimals);
        let over = round_to_decimals((total - self.limit).max(0.0), self.decimals);
        let status = usage_meter_status(total, self.limit, self.warn_at);

        let mut needs_anim_frame = false;

        // Spring-animated segment amounts and limit
        let mut animated_amounts: Vec<f64> = Vec::with_capacity(self.segments.len());
        for seg in &self.segments {
            let target = seg.value as f32;
            let val = if reduced {
                target
            } else {
                let s = arc_spring(
                    ElementId::NamedChild(
                        self.id.clone().into(),
                        SharedString::from(format!("seg-amt-{}", seg.id)),
                    ),
                    target,
                    motion.spring.smooth,
                    window,
                    cx,
                );
                if (s - target).abs() > 0.002 {
                    needs_anim_frame = true;
                }
                s
            };
            animated_amounts.push(val.max(0.0) as f64);
        }

        let shown_limit = if reduced {
            self.limit
        } else {
            let target = self.limit as f32;
            let s = arc_spring(
                ElementId::NamedChild(self.id.clone().into(), SharedString::from("shown-limit")),
                target,
                motion.spring.smooth,
                window,
                cx,
            );
            if (s - target).abs() > 0.002 {
                needs_anim_frame = true;
            }
            s.max(0.001) as f64
        };

        let over_marker_target = if status == UsageMeterStatus::Over {
            1.0_f32
        } else {
            0.0_f32
        };
        let marker_opacity = if reduced {
            over_marker_target
        } else {
            let s = arc_spring(
                ElementId::NamedChild(self.id.clone().into(), SharedString::from("over-marker-op")),
                over_marker_target,
                motion.spring.snappy,
                window,
                cx,
            );
            if (s - over_marker_target).abs() > 0.005 {
                needs_anim_frame = true;
            }
            s.clamp(0.0, 1.0)
        };

        if needs_anim_frame {
            window.request_animation_frame();
        }

        // Build legend items (segments + trailing Free/Over item)
        let mut legend_items: Vec<(SharedString, SharedString, f64)> = self
            .segments
            .iter()
            .map(|s| {
                (
                    s.id.clone(),
                    s.label.clone(),
                    round_to_decimals(s.value, self.decimals),
                )
            })
            .collect();
        let trailing_id = SharedString::from("free");
        let trailing_label = if status == UsageMeterStatus::Over {
            self.over_label.clone()
        } else {
            self.free_label.clone()
        };
        let trailing_val = if status == UsageMeterStatus::Over {
            over
        } else {
            free
        };
        legend_items.push((trailing_id.clone(), trailing_label, trailing_val));

        let (active_id, pinned_id, focus_handle) = {
            let st = state_cell.borrow();
            let active = st.hovered_id.clone().or_else(|| st.pinned_id.clone());
            (active, st.pinned_id.clone(), st.focus_handle.clone())
        };

        let active_item = active_id
            .as_ref()
            .and_then(|aid| legend_items.iter().find(|(id, _, _)| id == aid));

        let headline_val = active_item.map(|(_, _, v)| *v).unwrap_or(total);
        let limit_clean = {
            let s = format_amount(self.limit, self.decimals, self.unit.as_ref());
            s.replace(".0 ", " ").trim_end_matches(".0").to_string()
        };

        let caption_text = match active_item {
            None => {
                if self.unit.is_empty() {
                    SharedString::from(format!("of {limit_clean} used"))
                } else {
                    SharedString::from(format!("{} of {limit_clean} used", self.unit))
                }
            }
            Some((id, lbl, val)) if id.as_ref() == "free" => {
                let suffix = if status == UsageMeterStatus::Over {
                    "over the limit"
                } else {
                    "free"
                };
                if self.unit.is_empty() {
                    SharedString::from(format!("{lbl} ({suffix})"))
                } else {
                    SharedString::from(format!("{} {suffix}", self.unit))
                }
            }
            Some((_, lbl, val)) => {
                let share = ((val / self.limit) * 100.0).round() as i64;
                if self.unit.is_empty() {
                    SharedString::from(format!("in {lbl} · {share}% of plan"))
                } else {
                    SharedString::from(format!("{} in {lbl} · {share}% of plan", self.unit))
                }
            }
        };

        let badge_text = match status {
            UsageMeterStatus::Over => SharedString::from(format!(
                "{} over",
                format_amount(over, self.decimals, self.unit.as_ref())
            )),
            UsageMeterStatus::Near => SharedString::from("Almost full"),
            UsageMeterStatus::Ok => SharedString::from(format!(
                "{} free",
                format_amount(free, self.decimals, self.unit.as_ref())
            )),
        };

        let (badge_bg, badge_fg, badge_icon_color) = match status {
            UsageMeterStatus::Ok => (
                colors.surface_muted,
                colors.text_secondary,
                colors.text_secondary,
            ),
            UsageMeterStatus::Near => (
                oklab_mix(colors.warning, colors.surface, 0.14),
                colors.foreground,
                colors.warning,
            ),
            UsageMeterStatus::Over => (
                oklab_mix(colors.danger, colors.surface, 0.12),
                colors.foreground,
                colors.danger,
            ),
        };

        // Track canvas painting segments, diagonal overage hatch, and limit marker line
        let seg_ids: Vec<SharedString> = self.segments.iter().map(|s| s.id.clone()).collect();
        let active_for_canvas = active_id.clone();
        let track_bg = oklab_mix(colors.foreground, colors.surface, 0.07);
        let accent_c = colors.accent;
        let surface_c = colors.surface;
        let danger_c = colors.danger;
        let fg_c = colors.foreground;
        let bounds_state = state_cell.clone();

        let track_canvas = canvas(
            move |bounds, _window, _cx| {
                bounds_state.borrow_mut().track_bounds = Some(bounds);
                bounds
            },
            move |bounds: Bounds<gpui_kit::Pixels>, _, window, _cx| {
                let bar_y = bounds.origin.y + px(5.0);
                let bar_h = USAGE_METER_TRACK_HEIGHT_PX;
                let bar_w: f32 = bounds.size.width.into();
                let track_bounds = Bounds::new(
                    point(bounds.origin.x, bar_y),
                    gpui_kit::size(bounds.size.width, px(bar_h)),
                );

                // 1. Pill track background + clip mask
                window.paint_quad(quad(
                    track_bounds,
                    Corners::all(px(bar_h)),
                    track_bg,
                    Edges::all(px(0.0)),
                    gpui_kit::transparent_black(),
                    gpui_kit::BorderStyle::default(),
                ));

                let geom = usage_meter_bar_geometry(&animated_amounts, shown_limit, bar_w);

                window.with_content_mask(
                    Some(ContentMask {
                        bounds: track_bounds,
                    }),
                    |window| {
                        // 2. Segments
                        for (idx, (seg_x, seg_w)) in geom.segments.iter().copied().enumerate() {
                            if seg_w <= 0.1 {
                                continue;
                            }
                            let mut c = segment_swatch_color(idx, accent_c, surface_c);
                            if let Some(active) = &active_for_canvas
                                && seg_ids.get(idx) != Some(active)
                            {
                                c.a *= 0.28;
                            }
                            window.paint_quad(quad(
                                Bounds::new(
                                    point(bounds.origin.x + px(seg_x), bar_y),
                                    gpui_kit::size(px(seg_w), px(bar_h)),
                                ),
                                Corners::all(px(2.0)),
                                c,
                                Edges::all(px(0.0)),
                                gpui_kit::transparent_black(),
                                gpui_kit::BorderStyle::default(),
                            ));
                        }

                        // 3. Overflow diagonal hatch + optional danger highlight past `limit_x`
                        if marker_opacity > 0.01 && geom.limit_x < bar_w {
                            let over_x = (geom.limit_x + USAGE_METER_SEGMENT_GAP_PX).min(bar_w);
                            let over_w = (bar_w - over_x).max(0.0);
                            if over_w > 0.5 {
                                let over_bounds = Bounds::new(
                                    point(bounds.origin.x + px(over_x), bar_y),
                                    gpui_kit::size(px(over_w), px(bar_h)),
                                );

                                if active_for_canvas.as_deref() == Some("free") {
                                    let mut tint = danger_c;
                                    tint.a *= marker_opacity;
                                    window.paint_quad(quad(
                                        over_bounds,
                                        Corners::all(px(0.0)),
                                        tint,
                                        Edges::all(px(0.0)),
                                        gpui_kit::transparent_black(),
                                        gpui_kit::BorderStyle::default(),
                                    ));
                                }

                                window.with_content_mask(
                                    Some(ContentMask {
                                        bounds: over_bounds,
                                    }),
                                    |window| {
                                        let mut hatch_c = surface_c;
                                        hatch_c.a *= 0.72 * marker_opacity;
                                        let mut step = -bar_h;
                                        while step < over_w + bar_h {
                                            let x0 = bounds.origin.x + px(over_x + step);
                                            let y0 = bar_y + px(bar_h);
                                            let x1 = bounds.origin.x + px(over_x + step + bar_h);
                                            let y1 = bar_y;
                                            let mut builder = PathBuilder::stroke(px(2.2));
                                            builder.move_to(point(x0, y0));
                                            builder.line_to(point(x1, y1));
                                            if let Ok(path) = builder.build() {
                                                window.paint_path(path, hatch_c);
                                            }
                                            step += 6.0;
                                        }
                                    },
                                );
                            }
                        }
                    },
                );

                // 4. Vertical 2px limit marker extending 5px above and below the track
                if marker_opacity > 0.01 {
                    let mut line_c = fg_c;
                    line_c.a *= marker_opacity;
                    let lx = (geom.limit_x - 1.0).clamp(0.0, (bar_w - 2.0).max(0.0));
                    window.paint_quad(quad(
                        Bounds::new(
                            point(bounds.origin.x + px(lx), bounds.origin.y),
                            gpui_kit::size(px(2.0), bounds.size.height),
                        ),
                        Corners::all(px(1.0)),
                        line_c,
                        Edges::all(px(0.0)),
                        gpui_kit::transparent_black(),
                        gpui_kit::BorderStyle::default(),
                    ));
                }
            },
        )
        .size_full();

        let move_state = state_cell.clone();
        let move_segs = self.segments.clone();
        let move_limit = self.limit;
        let leave_state = state_cell.clone();
        let click_state = state_cell.clone();
        let click_segs = self.segments.clone();

        let bar_container = div()
            .id(ElementId::NamedChild(
                self.id.clone().into(),
                SharedString::from("track"),
            ))
            .w_full()
            .h(px(USAGE_METER_TRACK_HEIGHT_PX + 10.0))
            .cursor_pointer()
            .on_mouse_move(move |event: &MouseMoveEvent, window, _cx| {
                let mut st = move_state.borrow_mut();
                if let Some(b) = st.track_bounds {
                    let w: f32 = b.size.width.into();
                    if w > 1.0 {
                        let rx: f32 = (event.position.x - b.origin.x).into();
                        let hit = usage_meter_hit_segment_id(rx / w, &move_segs, move_limit);
                        if st.hovered_id.as_ref() != Some(&hit) {
                            st.hovered_id = Some(hit);
                            drop(st);
                            window.refresh();
                        }
                    }
                }
            })
            .on_hover(move |hovered: &bool, window, _cx| {
                if !*hovered {
                    let mut st = leave_state.borrow_mut();
                    if st.hovered_id.take().is_some() {
                        drop(st);
                        window.refresh();
                    }
                }
            })
            .on_mouse_down(MouseButton::Left, move |event, window, _cx| {
                let mut st = click_state.borrow_mut();
                if let Some(b) = st.track_bounds {
                    let w: f32 = b.size.width.into();
                    if w > 1.0 {
                        let rx: f32 = (event.position.x - b.origin.x).into();
                        let hit = usage_meter_hit_segment_id(rx / w, &click_segs, move_limit);
                        if st.pinned_id.as_ref() == Some(&hit) {
                            st.pinned_id = None;
                        } else {
                            st.pinned_id = Some(hit);
                        }
                        drop(st);
                        window.refresh();
                    }
                }
            })
            .child(track_canvas);

        // Legend buttons
        let mut legend_els: Vec<AnyElement> = Vec::with_capacity(legend_items.len());
        for (idx, (item_id, item_label, item_val)) in legend_items.iter().enumerate() {
            let is_free_item = item_id.as_ref() == "free";
            let is_over_warning = is_free_item && status == UsageMeterStatus::Over;
            let is_pinned = pinned_id.as_ref() == Some(item_id);
            let is_dimmed = active_id
                .as_ref()
                .map(|aid| aid != item_id)
                .unwrap_or(false);

            let swatch_el: AnyElement = if is_over_warning {
                svg()
                    .path(IconName::Info.path())
                    .size(px(12.0))
                    .text_color(colors.danger)
                    .into_any_element()
            } else if is_free_item {
                div()
                    .size(px(10.0))
                    .rounded(px(3.0))
                    .bg(track_bg)
                    .border_1()
                    .border_color(colors.border_strong)
                    .into_any_element()
            } else {
                div()
                    .size(px(10.0))
                    .rounded(px(3.0))
                    .bg(segment_swatch_color(idx, colors.accent, colors.surface))
                    .into_any_element()
            };

            let hover_state = state_cell.clone();
            let click_item_state = state_cell.clone();
            let id_for_hover = item_id.clone();
            let id_for_click = item_id.clone();
            let hover_bg = colors.surface_muted;

            let btn = div()
                .id(ElementId::NamedChild(
                    self.id.clone().into(),
                    SharedString::from(format!("legend-{item_id}")),
                ))
                .flex_1()
                .min_w(px(110.0))
                .p(Spacing::S2)
                .rounded(Radii::CONTROL)
                .cursor_pointer()
                .when(is_pinned, |this| this.bg(hover_bg))
                .hover(move |s| s.bg(hover_bg))
                .when(is_dimmed, |this| this.opacity(0.45))
                .flex()
                .flex_col()
                .gap(px(2.0))
                .on_hover(move |hovered: &bool, window, _cx| {
                    let mut st = hover_state.borrow_mut();
                    if *hovered {
                        st.hovered_id = Some(id_for_hover.clone());
                    } else if st.hovered_id.as_ref() == Some(&id_for_hover) {
                        st.hovered_id = None;
                    }
                    drop(st);
                    window.refresh();
                })
                .on_mouse_up(MouseButton::Left, move |_, window, _cx| {
                    let mut st = click_item_state.borrow_mut();
                    st.roving_index = idx;
                    if st.pinned_id.as_ref() == Some(&id_for_click) {
                        st.pinned_id = None;
                    } else {
                        st.pinned_id = Some(id_for_click.clone());
                    }
                    drop(st);
                    window.refresh();
                })
                .child(
                    div()
                        .flex()
                        .flex_row()
                        .items_center()
                        .gap(Spacing::S2)
                        .child(
                            div()
                                .size(px(12.0))
                                .flex_none()
                                .flex()
                                .items_center()
                                .justify_center()
                                .child(swatch_el),
                        )
                        .child(
                            div()
                                .text_size(Typography::TEXT_SM)
                                .text_color(colors.text_secondary)
                                .child(item_label.clone()),
                        ),
                )
                .child(
                    div()
                        .pl(px(20.0))
                        .flex()
                        .flex_row()
                        .items_baseline()
                        .gap(px(4.0))
                        .child(
                            div().text_color(colors.foreground).child(
                                AnimatedCounter::new(
                                    ElementId::NamedChild(
                                        self.id.clone().into(),
                                        SharedString::from(format!("legend-val-{item_id}")),
                                    ),
                                    *item_val,
                                )
                                .decimals(self.decimals)
                                .text_size(Typography::TEXT_BASE),
                            ),
                        )
                        .when(!self.unit.is_empty(), |this| {
                            this.child(
                                div()
                                    .text_size(Typography::TEXT_SM)
                                    .text_color(colors.text_secondary)
                                    .child(self.unit.clone()),
                            )
                        }),
                )
                .into_any_element();

            legend_els.push(btn);
        }

        let key_state = state_cell.clone();
        let legend_ids: Vec<SharedString> =
            legend_items.iter().map(|(id, _, _)| id.clone()).collect();

        div()
            .id(self.id.clone())
            .role(Role::Group)
            .track_focus(&focus_handle)
            .w_full()
            .flex()
            .flex_col()
            .gap(Spacing::S3)
            .on_key_down(move |event: &KeyDownEvent, window, _cx| {
                if legend_ids.is_empty() {
                    return;
                }
                let key = event.keystroke.key.as_str();
                let mut st = key_state.borrow_mut();
                let len = legend_ids.len();
                match key {
                    "escape" => {
                        st.pinned_id = None;
                        st.hovered_id = None;
                    }
                    "right" | "arrowright" | "down" | "arrowdown" => {
                        st.roving_index = (st.roving_index + 1) % len;
                        st.pinned_id = Some(legend_ids[st.roving_index].clone());
                    }
                    "left" | "arrowleft" | "up" | "arrowup" => {
                        st.roving_index = (st.roving_index + len - 1) % len;
                        st.pinned_id = Some(legend_ids[st.roving_index].clone());
                    }
                    "home" => {
                        st.roving_index = 0;
                        st.pinned_id = Some(legend_ids[0].clone());
                    }
                    "end" => {
                        st.roving_index = len - 1;
                        st.pinned_id = Some(legend_ids[len - 1].clone());
                    }
                    _ => return,
                }
                drop(st);
                window.refresh();
            })
            // Top header row: Title + StatusBadge
            .child(
                div()
                    .w_full()
                    .min_h(px(28.0))
                    .flex()
                    .flex_row()
                    .items_center()
                    .justify_between()
                    .gap(Spacing::S3)
                    .child(
                        div()
                            .text_size(Typography::TEXT_BASE)
                            .font_medium()
                            .text_color(colors.foreground)
                            .child(self.label),
                    )
                    .child(
                        div()
                            .h(px(28.0))
                            .px(Spacing::S3)
                            .rounded(Radii::PILL)
                            .bg(badge_bg)
                            .text_size(Typography::TEXT_XS)
                            .font_medium()
                            .text_color(badge_fg)
                            .flex()
                            .flex_row()
                            .items_center()
                            .gap(px(6.0))
                            .when(status != UsageMeterStatus::Ok, |this| {
                                this.child(
                                    svg()
                                        .path(IconName::Info.path())
                                        .size(px(14.0))
                                        .text_color(badge_icon_color),
                                )
                            })
                            .child(badge_text),
                    ),
            )
            // Headline amount + caption
            .child(
                div()
                    .w_full()
                    .flex()
                    .flex_row()
                    .items_baseline()
                    .gap(Spacing::S2)
                    .child(
                        div().text_color(colors.foreground).child(
                            AnimatedCounter::new(
                                ElementId::NamedChild(
                                    self.id.into(),
                                    SharedString::from("headline-ticker"),
                                ),
                                headline_val,
                            )
                            .decimals(self.decimals)
                            .text_size(px(30.0)),
                        ),
                    )
                    .child(
                        div()
                            .text_size(Typography::TEXT_SM)
                            .text_color(colors.text_secondary)
                            .child(caption_text),
                    ),
            )
            // Segmented track bar
            .child(bar_container)
            // Interactive legend
            .child(
                div()
                    .w_full()
                    .flex()
                    .flex_row()
                    .flex_wrap()
                    .gap(px(4.0))
                    .children(legend_els),
            )
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn usage_meter_status_and_bar_geometry_handle_under_near_and_over_limit() {
        assert_eq!(usage_meter_status(40.0, 100.0, 0.9), UsageMeterStatus::Ok);
        assert_eq!(usage_meter_status(92.0, 100.0, 0.9), UsageMeterStatus::Near);
        assert_eq!(
            usage_meter_status(115.0, 100.0, 0.9),
            UsageMeterStatus::Over
        );

        // Under limit: span == 100, limit_x == 200
        let g_under = usage_meter_bar_geometry(&[30.0, 20.0], 100.0, 200.0);
        assert!(!g_under.is_over);
        assert_eq!(g_under.span, 100.0);
        assert_eq!(g_under.limit_x, 200.0);
        assert_eq!(g_under.segments.len(), 2);
        assert!((g_under.segments[0].0 - 0.0).abs() < 1e-4);
        assert!((g_under.segments[0].1 - 58.0).abs() < 1e-4); // 60px minus 2px gap

        // Over limit: total = 125, limit = 100 -> span == 125, limit_x == 160
        let g_over = usage_meter_bar_geometry(&[75.0, 50.0], 100.0, 200.0);
        assert!(g_over.is_over);
        assert_eq!(g_over.span, 125.0);
        assert_eq!(g_over.limit_x, 160.0);
    }

    #[test]
    fn usage_meter_hit_segment_id_identifies_categories_and_overage() {
        let segs = vec![
            UsageMeterSegment::new("db", "Database", 40.0),
            UsageMeterSegment::new("media", "Media", 30.0),
        ];
        assert_eq!(
            usage_meter_hit_segment_id(0.20, &segs, 100.0),
            SharedString::from("db")
        );
        assert_eq!(
            usage_meter_hit_segment_id(0.55, &segs, 100.0),
            SharedString::from("media")
        );
        assert_eq!(
            usage_meter_hit_segment_id(0.85, &segs, 100.0),
            SharedString::from("free")
        );
    }
}