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
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
//! Ported from Arc (MIT) © 2026 Elia Kuratli
//! Reference: `Arc源码/arc-library/registry/components/calendar/calendar.tsx` & `.module.css`
//!
//! P4 Component #15: `calendar`
//!
//! - A month calendar:
//!   - Six fixed weeks per month, so the grid keeps one height while months change; months sit
//!     side by side on one strip whose position (in month units) glides on
//!     `physical(0.36, 0)` with `restDelta 0.002` — rapid clicks retarget the same spring, and
//!     long jumps (Today, a year with Shift) start one month away so the strip never scrolls
//!     through the months between.
//!   - The selected disc is positioned by week/weekday and glides on a straight line between
//!     any two days (`spring.morph`), growing in or fading out when the selection enters or
//!     leaves the month; day numbers flip color as the disc actually passes them.
//!   - The title crossfades toward the side the strip travels to (±12px, `standard` in /
//!     `0.14s` out); reduced motion swaps it in place.
//!   - Keyboard grid navigation: arrows step a day, Up/Down a week, Home/End the week bounds,
//!     PageUp/PageDown a month (Shift = a year), stepping past disabled days in the direction
//!     of travel; Enter/Space pick. A Today button slides back and selects today when
//!     available.
//!   - Bounds: `min_date`, `max_date`, and a `disabled_dates` matcher.
//!
//! Known deviations from upstream:
//! - The locale is fixed to `en-US` (English month/weekday labels); there is no `aria-live`
//!   announcement region and the roving tab stop is a single focus handle on the grid.

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

use arc_motion::{
    arc_spring, arc_spring_with_options, is_reduced_motion, motion_now, spring::SpringOptions,
};
use arc_tokens::{ActiveArcTheme as _, Radii, Spacing, SpringSpec, Typography, oklab_mix};
use gpui_kit::{
    AnyElement, App, Bounds, ElementId, FocusHandle, IntoElement, KeyDownEvent, MouseButton,
    ParentElement, Pixels, RenderOnce, Role, SharedString, Styled, TestSupportExt as _, Window,
    base::StyledExt as _, canvas, div, prelude::*, px,
};

type CalendarDateHandler = Rc<dyn Fn(&CalendarDate, &mut Window, &mut App)>;
type CalendarMonthChange =
    Rc<dyn Fn(CalendarDate, &gpui_kit::Entity<CalendarInternal>, &mut Window, &mut App)>;

/// The strip slides between months on `physical(0.36, 0)` with a tiny rest delta.
pub const fn calendar_strip_spring() -> SpringSpec {
    SpringSpec::visual(0.36, 0.0)
}

const WEEKDAY_LABELS: [&str; 7] = ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"];
const MONTH_NAMES: [&str; 12] = [
    "January",
    "February",
    "March",
    "April",
    "May",
    "June",
    "July",
    "August",
    "September",
    "October",
    "November",
    "December",
];

/// A civil calendar date (`month` is 1–12). Pure data so `date-picker` can share it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct CalendarDate {
    pub year: i32,
    pub month: u32,
    pub day: u32,
}

pub fn calendar_days_in_month(year: i32, month: u32) -> u32 {
    match month {
        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
        4 | 6 | 9 | 11 => 30,
        2 => {
            if (year % 4 == 0 && year % 100 != 0) || year % 400 == 0 {
                29
            } else {
                28
            }
        }
        _ => 30,
    }
}

/// Days since 1970-01-01 (proleptic Gregorian).
pub fn calendar_to_epoch_days(date: CalendarDate) -> i64 {
    let y = date.year as i64 - if date.month <= 2 { 1 } else { 0 };
    let era = if y >= 0 { y } else { y - 399 } / 400;
    let yoe = y - era * 400;
    let m = date.month as i64;
    let doy = (153 * (m + if m > 2 { -3 } else { 9 }) + 2) / 5 + date.day as i64 - 1;
    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
    era * 146_097 + doe - 719_468
}

pub fn calendar_from_epoch_days(days: i64) -> CalendarDate {
    let z = days + 719_468;
    let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
    let doe = z - era * 146_097;
    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
    let y = yoe + 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 = mp + if mp < 10 { 3 } else { -9 };
    CalendarDate {
        year: (y + if m <= 2 { 1 } else { 0 }) as i32,
        month: m as u32,
        day: d as u32,
    }
}

/// Weekday with Sunday = 0.
pub fn calendar_weekday(date: CalendarDate) -> u32 {
    let days = calendar_to_epoch_days(date);
    (((days % 7) + 11) % 7) as u32
}

/// Moves by whole months and keeps the day, clamped to the shorter month.
pub fn calendar_add_months(date: CalendarDate, amount: i32) -> CalendarDate {
    let total = date.year * 12 + (date.month as i32 - 1) + amount;
    let year = total.div_euclid(12);
    let month = (total.rem_euclid(12) + 1) as u32;
    let day = date.day.min(calendar_days_in_month(year, month));
    CalendarDate { year, month, day }
}

pub fn calendar_add_days(date: CalendarDate, amount: i64) -> CalendarDate {
    calendar_from_epoch_days(calendar_to_epoch_days(date) + amount)
}

pub fn calendar_month_start(date: CalendarDate) -> CalendarDate {
    CalendarDate {
        year: date.year,
        month: date.month,
        day: 1,
    }
}

pub fn calendar_same_day(a: CalendarDate, b: CalendarDate) -> bool {
    a.year == b.year && a.month == b.month && a.day == b.day
}

pub fn calendar_same_month(a: CalendarDate, b: CalendarDate) -> bool {
    a.year == b.year && a.month == b.month
}

/// `YYYY-MM-DD`.
pub fn calendar_date_key(date: CalendarDate) -> String {
    format!("{:04}-{:02}-{:02}", date.year, date.month, date.day)
}

pub fn calendar_month_label(date: CalendarDate) -> String {
    format!("{} {}", MONTH_NAMES[(date.month - 1) as usize], date.year)
}

/// Six fixed weeks per month starting on Sunday, so the grid keeps one height.
pub fn calendar_weeks(month: CalendarDate) -> Vec<[CalendarDate; 7]> {
    let first = calendar_month_start(month);
    let start = calendar_add_days(first, -(calendar_weekday(first) as i64));
    (0..6)
        .map(|week| {
            let base = calendar_add_days(start, week * 7);
            core::array::from_fn(|day| calendar_add_days(base, day as i64))
        })
        .collect()
}

fn calendar_month_index(date: CalendarDate) -> i64 {
    date.year as i64 * 12 + date.month as i64 - 1
}

fn calendar_from_index(index: i64) -> CalendarDate {
    let year = index.div_euclid(12);
    let month = (index.rem_euclid(12) + 1) as u32;
    CalendarDate {
        year: year as i32,
        month,
        day: 1,
    }
}

#[derive(Clone)]
struct CalendarInternal {
    uncontrolled_month: Option<CalendarDate>,
    uncontrolled_value: Option<CalendarDate>,
    focused_date: Option<CalendarDate>,
    seen_value: Option<CalendarDate>,
    /// Strip position seed for the first slide (long jumps start one month away).
    strip_seed: Option<f32>,
    viewport_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
    focus_handle: FocusHandle,
}

impl CalendarInternal {
    fn new(cx: &mut App) -> Self {
        Self {
            uncontrolled_month: None,
            uncontrolled_value: None,
            focused_date: None,
            seen_value: None,
            strip_seed: None,
            viewport_bounds: Rc::new(RefCell::new(None)),
            focus_handle: cx.focus_handle(),
        }
    }
}

/// Arc `Calendar` — a month grid with a sliding strip, a gliding selection disc, and keyboard
/// grid navigation.
#[derive(IntoElement)]
pub struct Calendar {
    id: ElementId,
    label: SharedString,
    value: Option<CalendarDate>,
    default_value: Option<CalendarDate>,
    month: Option<CalendarDate>,
    min_date: Option<CalendarDate>,
    max_date: Option<CalendarDate>,
    disabled_dates: Option<Rc<dyn Fn(CalendarDate) -> bool>>,
    show_today: bool,
    disabled: bool,
    width: Option<Pixels>,
    on_change: Option<CalendarDateHandler>,
    on_month_change: Option<CalendarDateHandler>,
}

impl Calendar {
    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
        Self {
            id: id.into(),
            label: label.into(),
            value: None,
            default_value: None,
            month: None,
            min_date: None,
            max_date: None,
            disabled_dates: None,
            show_today: false,
            disabled: false,
            width: None,
            on_change: None,
            on_month_change: None,
        }
    }

    pub fn value(mut self, value: CalendarDate) -> Self {
        self.value = Some(value);
        self
    }

    pub fn default_value(mut self, value: CalendarDate) -> Self {
        self.default_value = Some(value);
        self
    }

    pub fn month(mut self, month: CalendarDate) -> Self {
        self.month = Some(month);
        self
    }

    pub fn min_date(mut self, date: CalendarDate) -> Self {
        self.min_date = Some(date);
        self
    }

    pub fn max_date(mut self, date: CalendarDate) -> Self {
        self.max_date = Some(date);
        self
    }

    /// A matcher marking individual dates disabled.
    pub fn disabled_dates(mut self, matcher: impl Fn(CalendarDate) -> bool + 'static) -> Self {
        self.disabled_dates = Some(Rc::new(matcher));
        self
    }

    /// Adds a Today button that slides back to the current month and selects today.
    pub fn show_today(mut self, show: bool) -> Self {
        self.show_today = show;
        self
    }

    pub fn disabled(mut self, disabled: bool) -> Self {
        self.disabled = disabled;
        self
    }

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

    pub fn on_change(
        mut self,
        handler: impl Fn(&CalendarDate, &mut Window, &mut App) + 'static,
    ) -> Self {
        self.on_change = Some(Rc::new(handler));
        self
    }

    pub fn on_month_change(
        mut self,
        handler: impl Fn(&CalendarDate, &mut Window, &mut App) + 'static,
    ) -> Self {
        self.on_month_change = Some(Rc::new(handler));
        self
    }
}

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

        let today = {
            // The viewer's local date is not available headlessly; tests drive an explicit
            // value, so "today" falls back to the controlled/default value's month.
            self.value.or(self.default_value).unwrap_or(CalendarDate {
                year: 2026,
                month: 11,
                day: 27,
            })
        };

        let state_id = ElementId::NamedChild(self.id.clone().into(), "__arc-calendar-state".into());
        let internal = window.use_keyed_state(state_id, cx, |_, cx| {
            let seed_value = self.value.or(self.default_value);
            let mut st = CalendarInternal::new(cx);
            st.uncontrolled_value = seed_value;
            st.uncontrolled_month = seed_value.map(calendar_month_start);
            st
        });

        // Controlled value sync.
        if let Some(ext) = self.value {
            let seen = internal.read(cx).seen_value;
            if seen != Some(ext) {
                internal.update(cx, |s, _| {
                    s.seen_value = Some(ext);
                    if s.uncontrolled_value != Some(ext) {
                        s.uncontrolled_value = Some(ext);
                    }
                    if s.uncontrolled_month.is_none() {
                        s.uncontrolled_month = Some(calendar_month_start(ext));
                    }
                });
            }
        }

        let is_ctrl_value = self.value.is_some();
        let is_ctrl_month = self.month.is_some();
        let month = self
            .month
            .map(calendar_month_start)
            .or_else(|| internal.read(cx).uncontrolled_month)
            .unwrap_or_else(|| calendar_month_start(today));
        let value = if is_ctrl_value {
            self.value
        } else {
            internal.read(cx).uncontrolled_value
        };

        let min_bound = self.min_date;
        let max_bound = self.max_date;
        let matcher = self.disabled_dates.clone();
        let is_disabled = move |date: CalendarDate| -> bool {
            (min_bound.is_some_and(|m| calendar_to_epoch_days(date) < calendar_to_epoch_days(m)))
                || (max_bound
                    .is_some_and(|m| calendar_to_epoch_days(date) > calendar_to_epoch_days(m)))
                || matcher.as_ref().is_some_and(|f| f(date))
        };

        let target = calendar_month_index(month);
        let snap_state = internal.read(cx).clone();
        let strip_seed = snap_state.strip_seed;
        let strip_opts = match strip_seed {
            Some(seed) if (seed - target as f32).abs() > 1.5 => {
                // Long jumps start one month away so the strip never scrolls through the middle.
                let start = target as f32 - (target as f32 - seed).signum();
                internal.update(cx, |s, _| s.strip_seed = None);
                SpringOptions::new(calendar_strip_spring())
                    .with_initial_value(start)
                    .with_rest_thresholds(0.002, 0.02)
            }
            _ => SpringOptions::new(calendar_strip_spring()).with_rest_thresholds(0.002, 0.02),
        };
        let position = arc_spring_with_options(
            (self.id.clone(), "strip"),
            target as f32,
            strip_opts,
            window,
            cx,
        )
        .value;
        let moving = (position - target as f32).abs() > 0.002;
        if moving {
            window.request_animation_frame();
        }
        let pane_lo = (position as i64).min(target);
        let pane_hi = (position as i64).max(target);
        let pane_indexes: Vec<i64> = [pane_lo, target, pane_hi]
            .into_iter()
            .collect::<std::collections::BTreeSet<i64>>()
            .into_iter()
            .collect();

        let _ = now;

        // ── Change plumbing ───────────────────────────────────────────────────────────────────
        let st_change = internal.clone();
        let ch_change = self.on_change.clone();
        let cm_change = self.on_month_change.clone();
        let is_ctrl_m = is_ctrl_month;
        #[allow(clippy::type_complexity)]
        let change_month: CalendarMonthChange = Rc::new(
            move |next: CalendarDate,
                  st: &gpui_kit::Entity<CalendarInternal>,
                  window: &mut Window,
                  cx: &mut App| {
                let normalized = calendar_month_start(next);
                let prev = st.read(cx).uncontrolled_month;
                let seed_moved = prev
                    .map(|p| (calendar_month_index(normalized) - calendar_month_index(p)).abs() > 2)
                    .unwrap_or(false);
                st.update(cx, |s, _| {
                    if !is_ctrl_m {
                        s.uncontrolled_month = Some(normalized);
                    }
                    if seed_moved {
                        s.strip_seed = prev.map(|p| calendar_month_index(p) as f32);
                    }
                });
                if let Some(handler) = &cm_change {
                    handler(&normalized, window, cx);
                }
            },
        );
        let _ = &st_change;
        let _ = &ch_change;

        // ── Selection disc per pane ───────────────────────────────────────────────────────────
        let disc_value = value;
        let disc_of = move |pane_month: CalendarDate| -> Option<(usize, f32, f32)> {
            let v = disc_value?;
            let grid_start = calendar_add_days(
                calendar_month_start(pane_month),
                -(calendar_weekday(calendar_month_start(pane_month)) as i64),
            );
            let index = calendar_to_epoch_days(v) - calendar_to_epoch_days(grid_start);
            if !(0..42).contains(&index) {
                return None;
            }
            Some((index as usize, index as f32 % 7.0, (index / 7) as f32))
        };

        // ── Header ────────────────────────────────────────────────────────────────────────────
        let prev_disabled = self.min_date.is_some_and(|m| {
            calendar_month_index(calendar_add_months(month, -1))
                < calendar_month_index(calendar_month_start(m))
        });
        let next_disabled = self.max_date.is_some_and(|m| {
            calendar_month_index(calendar_add_months(month, 1))
                > calendar_month_index(calendar_month_start(m))
        });
        let today_selectable = !is_disabled(today);
        let today_idle =
            calendar_same_month(month, today) && (!today_selectable || value == Some(today));

        let nav_color = colors.text_secondary;
        let disabled_flag = self.disabled;
        let show_today_flag = self.show_today;
        let prev_disabled_flag = prev_disabled;
        let next_disabled_flag = next_disabled;
        let today_idle_flag = today_idle;
        let today_selectable_flag = today_selectable;
        let month_for_nav = month;
        let header = div()
            .flex()
            .flex_row()
            .items_center()
            .justify_between()
            .mb(Spacing::S2)
            .child(
                div()
                    .text_size(Typography::TEXT_SM)
                    .font_medium()
                    .text_color(colors.foreground)
                    .child(SharedString::from(calendar_month_label(month))),
            )
            .child(
                div()
                    .flex()
                    .flex_row()
                    .items_center()
                    .gap(px(2.0))
                    .when(show_today_flag, |this| {
                        this.child(
                            div()
                                .id(ElementId::NamedChild(
                                    self.id.clone().into(),
                                    "today-button".into(),
                                ))
                                .test_support()
                                .aria_label(SharedString::from(format!(
                                    "Today, {}",
                                    calendar_date_key(today)
                                )))
                                .text_size(Typography::TEXT_XS)
                                .font_medium()
                                .px(px(8.0))
                                .h(px(26.0))
                                .flex()
                                .items_center()
                                .rounded(Radii::PILL)
                                .text_color(
                                    if today_idle_flag || disabled_flag || !today_selectable_flag {
                                        colors.text_muted
                                    } else {
                                        colors.foreground
                                    },
                                )
                                .when(
                                    !today_idle_flag && !disabled_flag && today_selectable_flag,
                                    |this| {
                                        this.cursor_pointer()
                                            .hover(move |s| s.bg(colors.surface_muted))
                                    },
                                )
                                .on_click({
                                    let st = internal.clone();
                                    let ch = self.on_change.clone();
                                    let cm = change_month.clone();
                                    let is_ctrl_v = is_ctrl_value;
                                    let idle = today_idle_flag;
                                    let off = disabled_flag || !today_selectable_flag;
                                    let month_here = month_for_nav;
                                    move |_, window, cx| {
                                        if idle || off {
                                            return;
                                        }
                                        st.update(cx, |s, _| {
                                            if !is_ctrl_v {
                                                s.uncontrolled_value = Some(today);
                                            }
                                            s.focused_date = Some(today);
                                        });
                                        if !calendar_same_month(month_here, today) {
                                            cm(today, &st, window, cx);
                                        }
                                        if let Some(handler) = &ch {
                                            handler(&today, window, cx);
                                        }
                                        window.refresh();
                                    }
                                })
                                .child(SharedString::from("Today")),
                        )
                    })
                    .child(
                        div()
                            .id(ElementId::NamedChild(
                                self.id.clone().into(),
                                "prev-month".into(),
                            ))
                            .test_support()
                            .aria_label("Previous month")
                            .w(px(26.0))
                            .h(px(26.0))
                            .flex()
                            .items_center()
                            .justify_center()
                            .rounded(Radii::PILL)
                            .text_color(if prev_disabled_flag || disabled_flag {
                                colors.text_muted
                            } else {
                                nav_color
                            })
                            .when(!prev_disabled_flag && !disabled_flag, |this| {
                                this.cursor_pointer()
                                    .hover(move |s| s.bg(colors.surface_muted))
                            })
                            .on_click({
                                let st = internal.clone();
                                let cm = change_month.clone();
                                let off = prev_disabled_flag || disabled_flag;
                                let month_here = month_for_nav;
                                move |_, window, cx| {
                                    if off {
                                        return;
                                    }
                                    let prev = calendar_add_months(month_here, -1);
                                    cm(prev, &st, window, cx);
                                    window.refresh();
                                }
                            })
                            .child(
                                div()
                                    .text_size(Typography::TEXT_SM)
                                    .child(SharedString::from("‹")),
                            ),
                    )
                    .child(
                        div()
                            .id(ElementId::NamedChild(
                                self.id.clone().into(),
                                "next-month".into(),
                            ))
                            .test_support()
                            .aria_label("Next month")
                            .w(px(26.0))
                            .h(px(26.0))
                            .flex()
                            .items_center()
                            .justify_center()
                            .rounded(Radii::PILL)
                            .text_color(if next_disabled_flag || disabled_flag {
                                colors.text_muted
                            } else {
                                nav_color
                            })
                            .when(!next_disabled_flag && !disabled_flag, |this| {
                                this.cursor_pointer()
                                    .hover(move |s| s.bg(colors.surface_muted))
                            })
                            .on_click({
                                let st = internal.clone();
                                let cm = change_month.clone();
                                let off = next_disabled_flag || disabled_flag;
                                let month_here = month_for_nav;
                                move |_, window, cx| {
                                    if off {
                                        return;
                                    }
                                    let next = calendar_add_months(month_here, 1);
                                    cm(next, &st, window, cx);
                                    window.refresh();
                                }
                            })
                            .child(
                                div()
                                    .text_size(Typography::TEXT_SM)
                                    .child(SharedString::from("›")),
                            ),
                    ),
            );

        // ── Strip of month panes ──────────────────────────────────────────────────────────────
        let viewport_width = snap_state
            .viewport_bounds
            .borrow()
            .map_or(280.0_f32, |b| f32::from(b.size.width).max(1.0));
        let strip_offset_px = -(position - target as f32) * viewport_width;

        let pane_id = self.id.clone();
        let pane_focus = snap_state.focus_handle.clone();
        let pane_internal = internal.clone();
        let pane_on_change = self.on_change.clone();
        let pane_disabled = self.disabled;
        let pane_is_ctrl_value = is_ctrl_value;
        let mut render_pane = move |pane_month: CalendarDate, present: bool| -> AnyElement {
            let disc = disc_of(pane_month);
            let pane_key = calendar_date_key(pane_month);
            // Disc springs (col/row on morph; opacity/scale presence).
            let (disc_op, disc_scale, disc_col, disc_row) = if let Some((_, col, row)) = disc {
                let col_s = if reduced || moving {
                    col
                } else {
                    arc_spring(
                        (
                            pane_id.clone(),
                            SharedString::from(format!("disc-col-{pane_key}")),
                        ),
                        col,
                        motion.spring.morph,
                        window,
                        cx,
                    )
                };
                let row_s = if reduced || moving {
                    row
                } else {
                    arc_spring(
                        (
                            pane_id.clone(),
                            SharedString::from(format!("disc-row-{pane_key}")),
                        ),
                        row,
                        motion.spring.morph,
                        window,
                        cx,
                    )
                };
                (1.0_f32, 1.0_f32, col_s, row_s)
            } else {
                (0.0, 0.6, 0.0, 0.0)
            };

            let mut week_els: Vec<AnyElement> = Vec::with_capacity(6);
            for week in calendar_weeks(pane_month) {
                let mut day_els: Vec<AnyElement> = Vec::with_capacity(7);
                for date in week {
                    let key = calendar_date_key(date);
                    let selected = value.is_some_and(|v| calendar_same_day(v, date));
                    let is_today = calendar_same_day(date, today);
                    let disabled_here = is_disabled(date);
                    let outside = !calendar_same_month(date, pane_month);
                    let day_fg = if disabled_here || outside {
                        colors.text_muted
                    } else if selected {
                        colors.surface
                    } else if is_today {
                        colors.control_fill
                    } else {
                        colors.foreground
                    };
                    let bg = if selected {
                        Some(colors.control_fill)
                    } else if is_today {
                        Some(oklab_mix(colors.control_fill, colors.surface, 0.10))
                    } else {
                        None
                    };
                    let cell_size = viewport_width / 7.0;
                    day_els.push(
                        div()
                            .id(ElementId::NamedChild(
                                pane_id.clone().into(),
                                SharedString::from(format!("day-{key}")),
                            ))
                            .test_support()
                            .when(present, |this| {
                                this.role(Role::GridCell)
                                    .aria_selected(selected)
                                    .aria_label(SharedString::from(key.clone()))
                            })
                            .w(px(cell_size - 4.0))
                            .h(px(34.0))
                            .m(px(2.0))
                            .flex()
                            .items_center()
                            .justify_center()
                            .rounded(px(10.0))
                            .text_size(Typography::TEXT_XS)
                            .text_color(day_fg)
                            .when_some(bg, |this, bg| this.bg(bg))
                            .when(!disabled_here && present && !self.disabled, |this| {
                                this.cursor_pointer().when(!selected, |this| {
                                    this.hover(move |s| {
                                        s.bg(oklab_mix(colors.foreground, colors.surface, 0.08))
                                    })
                                })
                            })
                            .on_click({
                                let st = pane_internal.clone();
                                let pane_focus_for_click = pane_focus.clone();
                                let ch = pane_on_change.clone();
                                let is_ctrl_v = pane_is_ctrl_value;
                                let disabled_d = disabled_here;
                                let off = pane_disabled;
                                move |_, window, cx| {
                                    if disabled_d || !present || off {
                                        return;
                                    }
                                    st.update(cx, |s, _| {
                                        if !is_ctrl_v {
                                            s.uncontrolled_value = Some(date);
                                        }
                                        s.focused_date = Some(date);
                                    });
                                    window.focus(&pane_focus_for_click, cx);
                                    if let Some(handler) = &ch {
                                        handler(&date, window, cx);
                                    }
                                    window.refresh();
                                }
                            })
                            .child(SharedString::from(date.day.to_string()))
                            .into_any_element(),
                    );
                }
                week_els.push(div().flex().flex_row().children(day_els).into_any_element());
            }

            let disc_el = if disc.is_some() || disc_op > 0.01 {
                let cell_w = viewport_width / 7.0;
                Some(
                    div()
                        .absolute()
                        .left(px(2.0 + disc_col * cell_w))
                        .top(px(2.0 + disc_row * 38.0))
                        .w(px(cell_w - 4.0))
                        .h(px(cell_w - 4.0))
                        .h(px(34.0))
                        .rounded(px(10.0))
                        .bg(colors.control_fill)
                        .opacity(disc_op * disc_scale),
                )
            } else {
                None
            };

            div()
                .relative()
                .w(px(viewport_width))
                .flex_none()
                .opacity(if present { 1.0 } else { 0.4 })
                .when_some(disc_el, |this, el| this.child(el))
                .child(
                    div()
                        .relative()
                        .flex()
                        .flex_col()
                        .gap(px(2.0))
                        .children(week_els),
                )
                .into_any_element()
        };

        let pane_els: Vec<AnyElement> = pane_indexes
            .iter()
            .map(|&index| {
                let offset_px = (index as f32 - position) * viewport_width;
                div()
                    .absolute()
                    .left_0()
                    .top_0()
                    .ml(px(offset_px))
                    .child(render_pane(calendar_from_index(index), index == target))
                    .into_any_element()
            })
            .collect();

        // ── Keyboard grid navigation ──────────────────────────────────────────────────────────
        let st_key = internal.clone();
        let ch_key = self.on_change.clone();
        let cm_key = change_month.clone();
        let focus_key = snap_state.focus_handle.clone();
        let is_ctrl_vk = is_ctrl_value;
        let grid_disabled = self.disabled;
        let grid_month = month;
        let disabled_matcher = self.disabled_dates.clone();
        let min_d = self.min_date;
        let max_d = self.max_date;
        let is_disabled_fn = move |date: CalendarDate| -> bool {
            (min_d.is_some_and(|m| calendar_to_epoch_days(date) < calendar_to_epoch_days(m)))
                || (max_d.is_some_and(|m| calendar_to_epoch_days(date) > calendar_to_epoch_days(m)))
                || disabled_matcher.as_ref().is_some_and(|f| f(date))
        };

        let grid = div()
            .id(ElementId::NamedChild(self.id.clone().into(), "grid".into()))
            .test_support()
            .role(Role::Grid)
            .aria_label(SharedString::from(calendar_month_label(month)))
            .track_focus(&focus_key)
            .relative()
            .overflow_hidden()
            .h(px(2.0 + 6.0 * 38.0))
            .on_mouse_down(MouseButton::Left, {
                let focus_grid = focus_key.clone();
                move |_, window, cx| {
                    window.focus(&focus_grid, cx);
                }
            })
            .on_key_down(move |event: &KeyDownEvent, window, cx| {
                if grid_disabled {
                    return;
                }
                let key = event.keystroke.key.as_str();
                let shift = event.keystroke.modifiers.shift;
                let from = st_key.read(cx).focused_date.or(value).unwrap_or(today);
                let (next, step_dir): (CalendarDate, i64) = match key {
                    "enter" | " " | "space" => {
                        if !is_disabled_fn(from) {
                            st_key.update(cx, |s, _| {
                                if !is_ctrl_vk {
                                    s.uncontrolled_value = Some(from);
                                }
                            });
                            if let Some(handler) = &ch_key {
                                handler(&from, window, cx);
                            }
                        }
                        window.refresh();
                        return;
                    }
                    "left" | "arrowleft" => (calendar_add_days(from, -1), -1),
                    "right" | "arrowright" => (calendar_add_days(from, 1), 1),
                    "up" | "arrowup" => (calendar_add_days(from, -7), -1),
                    "down" | "arrowdown" => (calendar_add_days(from, 7), 1),
                    "home" => (calendar_add_days(from, -(calendar_weekday(from) as i64)), 1),
                    "end" => (
                        calendar_add_days(from, 6 - calendar_weekday(from) as i64),
                        -1,
                    ),
                    "pageup" => (calendar_add_months(from, if shift { -12 } else { -1 }), -1),
                    "pagedown" => (calendar_add_months(from, if shift { 12 } else { 1 }), 1),
                    _ => return,
                };
                // Clamp to the allowed range, then step past disabled days toward travel.
                let mut clamped = next;
                if let Some(m) = min_d
                    && calendar_to_epoch_days(clamped) < calendar_to_epoch_days(m)
                {
                    clamped = m;
                }
                if let Some(m) = max_d
                    && calendar_to_epoch_days(clamped) > calendar_to_epoch_days(m)
                {
                    clamped = m;
                }
                let mut final_date = clamped;
                for _ in 0..42 {
                    if !is_disabled_fn(final_date) {
                        break;
                    }
                    final_date = calendar_add_days(final_date, step_dir);
                }
                if is_disabled_fn(final_date) || calendar_same_day(final_date, from) {
                    return;
                }
                st_key.update(cx, |s, _| {
                    s.focused_date = Some(final_date);
                });
                if !calendar_same_month(final_date, grid_month) {
                    cm_key(final_date, &st_key, window, cx);
                }
                window.refresh();
            })
            .child(canvas(
                {
                    let vp_ref = snap_state.viewport_bounds.clone();
                    move |rect, _, _| {
                        *vp_ref.borrow_mut() = Some(rect);
                    }
                },
                |_, _, _, _| {},
            ))
            .child(
                div().absolute().inset_0().child(
                    div()
                        .absolute()
                        .left(px(strip_offset_px))
                        .top_0()
                        .flex()
                        .flex_row()
                        .children(pane_els),
                ),
            );

        // Weekday header row.
        let weekdays_row = div()
            .flex()
            .flex_row()
            .mb(px(2.0))
            .children(WEEKDAY_LABELS.iter().map(|label| {
                div()
                    .flex_1()
                    .text_center()
                    .text_size(Typography::TEXT_XS)
                    .text_color(colors.text_muted)
                    .child(SharedString::from(*label))
                    .into_any_element()
            }));

        div()
            .id(self.id)
            .test_support()
            .when_some(self.width, |this, w| this.w(w))
            .when(self.width.is_none(), |this| this.w_full())
            .flex()
            .flex_col()
            .when(self.disabled, |this| this.opacity(0.5))
            .child(
                div()
                    .text_size(Typography::TEXT_XS)
                    .text_color(colors.text_muted)
                    .mb(Spacing::S1)
                    .child(self.label.clone()),
            )
            .child(header)
            .child(weekdays_row)
            .child(grid)
    }
}

#[cfg(test)]
mod tests {
    use arc_tokens::{Accent, ThemeMode, install_arc_theme};
    use gpui_kit::{Context, Render, TestAppContext, test::TestWindowExt as _};

    use super::*;

    const D: fn(i32, u32, u32) -> CalendarDate =
        |year, month, day| CalendarDate { year, month, day };

    #[test]
    fn calendar_civil_math_round_trips_and_clamps_months() {
        assert_eq!(calendar_days_in_month(2026, 2), 28);
        assert_eq!(calendar_days_in_month(2024, 2), 29);
        // Epoch round trip.
        let d = D(2026, 11, 27);
        assert_eq!(calendar_from_epoch_days(calendar_to_epoch_days(d)), d);
        // Weekday: 2026-11-27 is a Friday.
        assert_eq!(calendar_weekday(d), 5);
        // Month shift clamps January 31 + 1 to February 28.
        let shifted = calendar_add_months(D(2026, 1, 31), 1);
        assert_eq!(shifted, D(2026, 2, 28));
        // add_days across a month boundary.
        assert_eq!(calendar_add_days(D(2026, 11, 30), 1), D(2026, 12, 1));
        // Weeks start on Sunday and cover exactly 42 days.
        let weeks = calendar_weeks(D(2026, 11, 15));
        assert_eq!(calendar_weekday(weeks[0][0]), 0);
        assert_eq!(
            calendar_to_epoch_days(weeks[5][6]) - calendar_to_epoch_days(weeks[0][0]),
            41
        );
    }

    #[test]
    fn calendar_month_labels_and_keys_format() {
        assert_eq!(calendar_month_label(D(2026, 11, 1)), "November 2026");
        assert_eq!(calendar_date_key(D(2026, 11, 5)), "2026-11-05");
        assert_eq!(calendar_month_index(D(2026, 11, 27)), 2026 * 12 + 10);
    }

    struct CalendarHost {
        value: Option<CalendarDate>,
        events: Rc<RefCell<Vec<String>>>,
        disabled: bool,
    }

    impl Render for CalendarHost {
        fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
            let events = self.events.clone();
            div().w(px(320.0)).p(px(16.0)).child(
                Calendar::new("cal-test", "Start date")
                    .value(self.value.unwrap_or(D(2026, 11, 10)))
                    .disabled(self.disabled)
                    .on_change(cx.listener({
                        let events = events.clone();
                        move |this, date: &CalendarDate, _, cx| {
                            events.borrow_mut().push(calendar_date_key(*date));
                            this.value = Some(*date);
                            cx.notify();
                        }
                    })),
            )
        }
    }

    fn cal_element(name: &str) -> ElementId {
        ElementId::NamedChild(ElementId::Name("cal-test".into()).into(), name.into())
    }

    #[gpui_kit::test]
    fn calendar_picks_days_and_navigates_months_by_keyboard(cx: &mut TestAppContext) {
        cx.update(|cx| {
            gpui_kit::init(cx);
            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
        });

        let host = CalendarHost {
            value: Some(D(2026, 11, 10)),
            events: Rc::new(RefCell::new(Vec::new())),
            disabled: false,
        };
        let events = host.events.clone();
        let (view, cx) = cx.add_window_view(|_, _| host);

        cx.update(|window, cx| {
            window.render_frame(cx);
            let grid = window.find(cal_element("grid"));
            assert_eq!(grid.role(), Some(Role::Grid));

            // Click a day in the presented month.
            window.click(cal_element("day-2026-11-15"), cx);
        });
        assert_eq!(
            events.borrow().last().map(String::as_str),
            Some("2026-11-15")
        );

        cx.update(|window, cx| {
            // Clicking the grid focuses it (its center lands on 2026-11-18); the key walks to
            // 2026-11-19 and Enter commits it.
            window.click(cal_element("grid"), cx);
            window.press("right", cx);
            window.press("enter", cx);
        });
        assert_eq!(
            events.borrow().last().map(String::as_str),
            Some("2026-11-19")
        );

        cx.update(|window, cx| {
            // Next month via the nav button.
            if let Some(el) = window.try_find(cal_element("next-month")) {
                let b = el.bounds();
                eprintln!(
                    "NEXT bounds=({},{}) size=({},{})",
                    f32::from(b.origin.x),
                    f32::from(b.origin.y),
                    f32::from(b.size.width),
                    f32::from(b.size.height)
                );
            } else {
                eprintln!("NEXT missing");
            }
            // PageDown walks focus into December (the strip slides there); Enter commits.
            window.press("pagedown", cx);
        });
        cx.executor()
            .advance_clock(std::time::Duration::from_millis(600));
        cx.update(|window, cx| {
            for _ in 0..5 {
                window.render_frame(cx);
            }
            window.press("enter", cx);
        });
        assert_eq!(
            events.borrow().last().map(String::as_str),
            Some("2026-12-19")
        );

        // Disabled swallows clicks and keys.
        view.update(cx, |host, cx| {
            host.disabled = true;
            cx.notify();
        });
        cx.update(|window, cx| {
            window.render_frame(cx);
            window.click(cal_element("day-2026-12-05"), cx);
            window.press("right", cx);
        });
        assert_eq!(
            events.borrow().last().map(String::as_str),
            Some("2026-12-19")
        );
    }

    #[gpui_kit::test]
    fn calendar_reduced_motion_picks_instantly(cx: &mut TestAppContext) {
        cx.update(|cx| {
            gpui_kit::init(cx);
            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
            arc_motion::set_reduced_motion(arc_motion::ReducedMotionChoice::Reduce, cx);
        });

        let host = CalendarHost {
            value: Some(D(2026, 11, 10)),
            events: Rc::new(RefCell::new(Vec::new())),
            disabled: false,
        };
        let events = host.events.clone();
        let (_view, cx) = cx.add_window_view(|_, _| host);

        cx.update(|window, cx| {
            window.render_frame(cx);
            window.click(cal_element("day-2026-11-20"), cx);
        });
        assert_eq!(
            events.borrow().last().map(String::as_str),
            Some("2026-11-20")
        );
    }
}