Skip to main content

arc_ui/inputs/
date_range_picker.rs

1//! Ported from Arc (MIT) © 2026 Elia Kuratli
2//! Reference: `Arc源码/arc-library/registry/components/date-range-picker/date-range-picker.tsx` & `.module.css`
3//!
4//! P4 Component #17: `date-range-picker`
5//!
6//! - A trigger + panel that picks a start and end together:
7//!   - The panel shows a preset rail (Today / Yesterday / Last 7 / Last 30 / This month /
8//!     Last month) beside two month grids; each week renders its slice of the range highlight
9//!     as a bar (left/width on `physical(0.3, 0)` stretch), and the two endpoints glide from
10//!     day to day on `physical(0.3, 0)`.
11//!   - Pick flow: the first click anchors the start, hovering stretches the highlight, and the
12//!     second click orders and applies the range (re-clicking the same day keeps the anchor for
13//!     a zero-day range). Escape and outside pointer down dismiss without applying.
14//!   - The visible months slide in the travel direction; prev/next arrows step the window.
15//!   - Keyboard: arrows step focus a day / a week (wrapping into the visible window),
16//!     Enter picks the focused day, Escape closes.
17//!
18//! Known deviations from upstream:
19//! - The trigger does not grow into the panel (GPUI popover instead); the panel is fixed
20//!   two-months wide; no `aria-live` announcements; the Apply button is omitted (second click
21//!   applies directly); the locale is fixed to en-US.
22
23use std::{cell::RefCell, rc::Rc};
24
25use arc_motion::{ArcPresence, ArcPresenceConfig, arc_spring, is_reduced_motion, motion_now};
26use arc_tokens::{ActiveArcTheme as _, Radii, Shadows, Spacing, SpringSpec, Typography, oklab_mix};
27use gpui_kit::{
28    AnyElement, App, Bounds, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent,
29    MouseDownEvent, ParentElement, Pixels, RenderOnce, Role, SharedString, Styled,
30    TestSupportExt as _, Window,
31    base::{Button as BaseButton, StyledExt as _},
32    canvas, deferred, div,
33    prelude::*,
34    px,
35};
36
37use super::calendar::{
38    CalendarDate, calendar_add_days, calendar_add_months, calendar_date_key, calendar_month_label,
39    calendar_month_start, calendar_same_day, calendar_to_epoch_days, calendar_weeks,
40};
41use super::field_message::render_field_message;
42
43type RangeChangeHandler = Rc<dyn Fn(&Option<(CalendarDate, CalendarDate)>, &mut Window, &mut App)>;
44
45/// The two month grids glide on `physical(0.4, 0)` (`SLIDE`); bars and endpoints stretch/glide
46/// on `physical(0.3, 0)`.
47pub const fn date_range_slide_spring() -> SpringSpec {
48    SpringSpec::visual(0.4, 0.0)
49}
50pub const fn date_range_stretch_spring() -> SpringSpec {
51    SpringSpec::visual(0.3, 0.0)
52}
53
54const PRESETS: [&str; 8] = [
55    "Today",
56    "Yesterday",
57    "Last 7 days",
58    "Last 30 days",
59    "This month",
60    "Last month",
61    "This quarter",
62    "Year to date",
63];
64
65/// An inclusive day range.
66#[derive(Clone, Copy, Debug, PartialEq, Eq)]
67pub struct DateRange {
68    pub start: CalendarDate,
69    pub end: CalendarDate,
70}
71
72impl DateRange {
73    pub fn ordered(a: CalendarDate, b: CalendarDate) -> Self {
74        if calendar_to_epoch_days(a) <= calendar_to_epoch_days(b) {
75            Self { start: a, end: b }
76        } else {
77            Self { start: b, end: a }
78        }
79    }
80
81    /// Inclusive day count.
82    pub fn days(&self) -> i64 {
83        calendar_to_epoch_days(self.end) - calendar_to_epoch_days(self.start) + 1
84    }
85}
86
87#[derive(Clone)]
88struct DateRangeInternal {
89    uncontrolled: Option<DateRange>,
90    seen_value: Option<Option<DateRange>>,
91    open: bool,
92    /// First anchor of the in-progress pick (`None` when no pick is in progress).
93    anchor: Option<CalendarDate>,
94    hover: Option<CalendarDate>,
95    view_month: CalendarDate,
96    focused_date: Option<CalendarDate>,
97    preset_active: Option<usize>,
98    trigger_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
99    panel_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
100    focus_handle: FocusHandle,
101}
102
103impl DateRangeInternal {
104    fn new(default_value: Option<DateRange>, cx: &mut App) -> Self {
105        Self {
106            uncontrolled: default_value,
107            seen_value: None,
108            open: false,
109            anchor: None,
110            hover: None,
111            view_month: default_value.map_or_else(
112                || CalendarDate {
113                    year: 2026,
114                    month: 11,
115                    day: 1,
116                },
117                |r| calendar_month_start(r.start),
118            ),
119            focused_date: None,
120            preset_active: None,
121            trigger_bounds: Rc::new(RefCell::new(None)),
122            panel_bounds: Rc::new(RefCell::new(None)),
123            focus_handle: cx.focus_handle(),
124        }
125    }
126}
127
128fn preset_range(index: usize, today: CalendarDate) -> DateRange {
129    match index {
130        0 => DateRange {
131            start: today,
132            end: today,
133        },
134        1 => {
135            let y = calendar_add_days(today, -1);
136            DateRange { start: y, end: y }
137        }
138        2 => DateRange {
139            start: calendar_add_days(today, -6),
140            end: today,
141        },
142        3 => DateRange {
143            start: calendar_add_days(today, -29),
144            end: today,
145        },
146        4 => DateRange {
147            start: calendar_month_start(today),
148            end: today,
149        },
150        5 => {
151            let last = calendar_add_months(today, -1);
152            let start = calendar_month_start(last);
153            let end = calendar_add_days(calendar_month_start(today), -1);
154            DateRange { start, end }
155        }
156        6 => {
157            let q_month = ((today.month.saturating_sub(1)) / 3) * 3 + 1;
158            DateRange {
159                start: CalendarDate {
160                    year: today.year,
161                    month: q_month,
162                    day: 1,
163                },
164                end: today,
165            }
166        }
167        7 => DateRange {
168            start: CalendarDate {
169                year: today.year,
170                month: 1,
171                day: 1,
172            },
173            end: today,
174        },
175        _ => DateRange {
176            start: today,
177            end: today,
178        },
179    }
180}
181
182/// Arc `DateRangePicker` — a trigger + panel picking a start and end together.
183#[derive(IntoElement)]
184pub struct DateRangePicker {
185    id: ElementId,
186    label: SharedString,
187    value: Option<DateRange>,
188    default_value: Option<DateRange>,
189    placeholder: SharedString,
190    min_date: Option<CalendarDate>,
191    max_date: Option<CalendarDate>,
192    disabled: bool,
193    width: Option<Pixels>,
194    on_change: Option<RangeChangeHandler>,
195}
196
197impl DateRangePicker {
198    pub fn new(id: impl Into<ElementId>) -> Self {
199        Self {
200            id: id.into(),
201            label: "Date range".into(),
202            value: None,
203            default_value: None,
204            placeholder: "Select dates".into(),
205            min_date: None,
206            max_date: None,
207            disabled: false,
208            width: None,
209            on_change: None,
210        }
211    }
212
213    pub fn label(mut self, label: impl Into<SharedString>) -> Self {
214        self.label = label.into();
215        self
216    }
217
218    pub fn value(mut self, value: DateRange) -> Self {
219        self.value = Some(value);
220        self
221    }
222
223    pub fn default_value(mut self, value: DateRange) -> Self {
224        self.default_value = Some(value);
225        self
226    }
227
228    pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
229        self.placeholder = placeholder.into();
230        self
231    }
232
233    pub fn min_date(mut self, date: CalendarDate) -> Self {
234        self.min_date = Some(date);
235        self
236    }
237
238    pub fn max_date(mut self, date: CalendarDate) -> Self {
239        self.max_date = Some(date);
240        self
241    }
242
243    pub fn disabled(mut self, disabled: bool) -> Self {
244        self.disabled = disabled;
245        self
246    }
247
248    pub fn width(mut self, width: impl Into<Pixels>) -> Self {
249        self.width = Some(width.into());
250        self
251    }
252
253    pub fn on_change(
254        mut self,
255        handler: impl Fn(&Option<(CalendarDate, CalendarDate)>, &mut Window, &mut App) + 'static,
256    ) -> Self {
257        self.on_change = Some(Rc::new(handler));
258        self
259    }
260}
261
262fn format_date(d: CalendarDate) -> String {
263    const MONTHS: [&str; 12] = [
264        "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
265    ];
266    format!("{}, {}, {}", MONTHS[(d.month - 1) as usize], d.day, d.year)
267}
268
269fn format_range(range: Option<DateRange>, placeholder: &str) -> String {
270    match range {
271        None => placeholder.to_string(),
272        Some(r) if calendar_same_day(r.start, r.end) => format_date(r.start),
273        Some(r) => format!("{} – {}", format_date(r.start), format_date(r.end)),
274    }
275}
276
277impl RenderOnce for DateRangePicker {
278    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
279        let theme = cx.arc_theme().clone();
280        let colors = theme.colors;
281        let motion = theme.motion;
282        let reduced = is_reduced_motion(cx);
283        let today = CalendarDate {
284            year: 2026,
285            month: 11,
286            day: 27,
287        };
288
289        let state_id =
290            ElementId::NamedChild(self.id.clone().into(), "__arc-daterange-state".into());
291        let internal = window.use_keyed_state(state_id, cx, |_, cx| {
292            DateRangeInternal::new(self.default_value, cx)
293        });
294
295        if let Some(ext) = self.value {
296            let seen = internal.read(cx).seen_value;
297            if seen != Some(Some(ext)) {
298                internal.update(cx, |s, _| {
299                    s.seen_value = Some(Some(ext));
300                });
301            }
302        }
303
304        let is_ctrl = self.value.is_some();
305        let committed = if is_ctrl {
306            self.value
307        } else {
308            internal.read(cx).uncontrolled
309        };
310        let snap = internal.read(cx).clone();
311        let open = snap.open && !self.disabled;
312
313        // Shown (draft) range: the anchor+hover preview or the committed draft.
314        let shown = snap.anchor.map(|a| {
315            let b = snap.hover.unwrap_or(a);
316            DateRange::ordered(a, b)
317        });
318        let draft = shown.or(committed);
319
320        // ── Pick plumbing ─────────────────────────────────────────────────────────────────────
321        let ch_pick = self.on_change.clone();
322        let is_ctrl_pick = is_ctrl;
323        let min_pick = self.min_date;
324        let max_pick = self.max_date;
325        let pick = move |date: CalendarDate,
326                         st: &gpui_kit::Entity<DateRangeInternal>,
327                         window: &mut Window,
328                         cx: &mut App| {
329            let now_p = motion_now(cx);
330            let anchor = st.read(cx).anchor;
331            match anchor {
332                None => {
333                    // First click anchors the start.
334                    st.update(cx, |s, _| {
335                        s.anchor = Some(date);
336                        s.hover = Some(date);
337                    });
338                }
339                Some(a) => {
340                    // Second click orders and applies to the selection while keeping the panel open
341                    // so the user can review the cross-month range or press Apply.
342                    let mut range = DateRange::ordered(a, date);
343                    if let Some(m) = min_pick
344                        && calendar_to_epoch_days(range.start) < calendar_to_epoch_days(m)
345                    {
346                        range.start = m;
347                    }
348                    if let Some(m) = max_pick
349                        && calendar_to_epoch_days(range.end) > calendar_to_epoch_days(m)
350                    {
351                        range.end = m;
352                    }
353                    st.update(cx, |s, _| {
354                        if !is_ctrl_pick {
355                            s.uncontrolled = Some(range);
356                        }
357                        s.seen_value = Some(Some(range));
358                        s.anchor = None;
359                        s.hover = None;
360                        s.preset_active = None;
361                        s.focused_date = Some(date);
362                    });
363                    if let Some(handler) = &ch_pick {
364                        handler(&Some((range.start, range.end)), window, cx);
365                    }
366                }
367            }
368            let _ = now_p;
369            window.refresh();
370        };
371
372        let apply_preset = {
373            let st = internal.clone();
374            let ch = self.on_change.clone();
375            let is_ctrl_p = is_ctrl;
376            move |index: usize, window: &mut Window, cx: &mut App| {
377                let range = preset_range(index, today);
378                let next_view = calendar_month_start(range.start);
379                st.update(cx, |s, _| {
380                    if !is_ctrl_p {
381                        s.uncontrolled = Some(range);
382                    }
383                    s.seen_value = Some(Some(range));
384                    s.preset_active = Some(index);
385                    s.anchor = None;
386                    s.hover = None;
387                    s.view_month = next_view;
388                });
389                if let Some(handler) = &ch {
390                    handler(&Some((range.start, range.end)), window, cx);
391                }
392                window.refresh();
393            }
394        };
395
396        // ── Trigger ───────────────────────────────────────────────────────────────────────────
397        let trigger_probe = canvas(
398            {
399                let probe = snap.trigger_bounds.clone();
400                move |rect, _, _| {
401                    *probe.borrow_mut() = Some(rect);
402                }
403            },
404            |_, _, _, _| {},
405        )
406        .absolute()
407        .inset_0();
408        let muted_color = colors.text_muted;
409        let trigger_hover = colors.surface_muted;
410        let trigger = BaseButton::new(ElementId::NamedChild(
411            self.id.clone().into(),
412            "trigger".into(),
413        ))
414        .accessibility_label(SharedString::from(format!(
415            "{}: {}",
416            self.label,
417            format_range(committed, &self.placeholder)
418        )))
419        .disabled(self.disabled)
420        .on_click({
421            let st = internal.clone();
422            let disabled_flag = self.disabled;
423            move |_, window, cx| {
424                if disabled_flag {
425                    return;
426                }
427                window.focus(&st.read(cx).focus_handle.clone(), cx);
428                st.update(cx, |s, _| {
429                    s.open = !s.open;
430                    s.anchor = None;
431                    s.hover = None;
432                    if s.open {
433                        s.view_month = committed
434                            .or(s.uncontrolled)
435                            .map(|r| calendar_month_start(r.start))
436                            .unwrap_or(calendar_month_start(today));
437                    }
438                });
439                window.refresh();
440            }
441        })
442        .relative()
443        .w_full()
444        .h(px(38.0))
445        .px(px(10.0))
446        .flex()
447        .flex_row()
448        .items_center()
449        .gap(px(8.0))
450        .rounded(Radii::PILL)
451        .border_1()
452        .border_color(if self.disabled {
453            colors.border
454        } else {
455            colors.border_strong
456        })
457        .bg(colors.surface)
458        .opacity(if self.disabled { 0.5 } else { 1.0 })
459        .when(!self.disabled, |this| {
460            this.cursor_pointer().hover(move |s| s.bg(trigger_hover))
461        })
462        .child(trigger_probe)
463        .child(
464            div()
465                .flex_1()
466                .min_w_0()
467                .text_size(Typography::TEXT_SM)
468                .text_color(if committed.is_some() {
469                    colors.foreground
470                } else {
471                    muted_color
472                })
473                .overflow_hidden()
474                .whitespace_nowrap()
475                .child(SharedString::from(format_range(
476                    committed,
477                    &self.placeholder,
478                ))),
479        );
480
481        // ── Panel: preset rail + two month grids ──────────────────────────────────────────────
482        let presence = ArcPresence::new((self.id.clone(), "dr-presence"), open)
483            .animate_initial(false)
484            .config(ArcPresenceConfig {
485                enter_duration: motion.duration.fast,
486                exit_duration: motion.duration.instant,
487                enter_ease: motion.ease.enter,
488                exit_ease: motion.ease.standard,
489                fade_on_reduced_motion: true,
490            })
491            .sample(window, cx);
492        let p = presence.progress.clamp(0.0, 1.0);
493        let panel_y = if reduced {
494            0.0
495        } else {
496            arc_spring(
497                (self.id.clone(), "dr-y"),
498                if open { 0.0 } else { -8.0 },
499                motion.spring.snappy,
500                window,
501                cx,
502            )
503        };
504
505        let dr_id = self.id.clone();
506        let is_disabled = |date: CalendarDate| -> bool {
507            self.min_date
508                .is_some_and(|m| calendar_to_epoch_days(date) < calendar_to_epoch_days(m))
509                || self
510                    .max_date
511                    .is_some_and(|m| calendar_to_epoch_days(date) > calendar_to_epoch_days(m))
512        };
513
514        #[allow(clippy::type_complexity)]
515        let render_month = |month: CalendarDate,
516                            range_now: Option<DateRange>,
517                            pane_id: ElementId,
518                            id_prefix: &'static str,
519                            st: gpui_kit::Entity<DateRangeInternal>,
520                            on_pick: Rc<
521            dyn Fn(CalendarDate, &gpui_kit::Entity<DateRangeInternal>, &mut Window, &mut App),
522        >|
523         -> AnyElement {
524            let cell_w = 38.0_f32;
525            let cell_h = 36.0_f32;
526            let bar_bg = oklab_mix(colors.accent, colors.surface_raised, 0.14);
527            let hover_cell_bg = oklab_mix(colors.foreground, colors.surface_raised, 0.07);
528
529            let weekday_els: Vec<AnyElement> = ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"]
530                .into_iter()
531                .map(|wd| {
532                    div()
533                        .w(px(cell_w))
534                        .h(px(28.0))
535                        .flex()
536                        .items_center()
537                        .justify_center()
538                        .text_size(Typography::TEXT_XS)
539                        .font_medium()
540                        .text_color(colors.text_muted)
541                        .child(SharedString::from(wd))
542                        .into_any_element()
543                })
544                .collect();
545
546            let mut week_els: Vec<AnyElement> = Vec::with_capacity(6);
547            for week in calendar_weeks(month).iter() {
548                // This week's slice of the range across IN-MONTH days only (matching upstream).
549                let mut bar_left = 0.0_f32;
550                let mut bar_width = 0.0_f32;
551                if let Some(r) = range_now {
552                    let r_start_ep = calendar_to_epoch_days(r.start);
553                    let r_end_ep = calendar_to_epoch_days(r.end);
554                    let mut first_col: Option<usize> = None;
555                    let mut last_col: Option<usize> = None;
556                    for (col_idx, d) in week.iter().enumerate() {
557                        if d.month != month.month {
558                            continue;
559                        }
560                        let ep = calendar_to_epoch_days(*d);
561                        if ep >= r_start_ep && ep <= r_end_ep {
562                            if first_col.is_none() {
563                                first_col = Some(col_idx);
564                            }
565                            last_col = Some(col_idx);
566                        }
567                    }
568                    if let (Some(ca), Some(cb)) = (first_col, last_col) {
569                        bar_left = ca as f32 * cell_w + 3.0;
570                        bar_width = ((cb - ca + 1) as f32 * cell_w - 6.0).max(0.0);
571                    }
572                }
573                let mut day_els: Vec<AnyElement> = Vec::with_capacity(7);
574                for date in week.iter() {
575                    let outside = date.month != month.month;
576                    if outside {
577                        day_els.push(div().w(px(cell_w)).h(px(cell_h)).into_any_element());
578                        continue;
579                    }
580                    let key = calendar_date_key(*date);
581                    let disabled_here = is_disabled(*date);
582                    let in_range = range_now.is_some_and(|r| {
583                        calendar_to_epoch_days(*date) >= calendar_to_epoch_days(r.start)
584                            && calendar_to_epoch_days(*date) <= calendar_to_epoch_days(r.end)
585                    });
586                    let edge = range_now.is_some_and(|r| {
587                        calendar_same_day(*date, r.start) || calendar_same_day(*date, r.end)
588                    });
589                    let is_today = calendar_same_day(*date, today);
590                    let focused_here = snap
591                        .focused_date
592                        .is_some_and(|f| calendar_same_day(f, *date));
593                    let day_fg = if disabled_here {
594                        colors.text_muted
595                    } else if edge {
596                        colors.accent_foreground
597                    } else {
598                        colors.foreground
599                    };
600                    let bg = if edge && in_range {
601                        Some(colors.accent)
602                    } else {
603                        None
604                    };
605                    let date_for_click = *date;
606                    let date_for_hover = *date;
607                    let pick_for_click = on_pick.clone();
608                    let focus_st = st.clone();
609                    let hover_st = st.clone();
610                    let today_dot_color = if edge {
611                        colors.accent_foreground
612                    } else {
613                        colors.accent
614                    };
615                    day_els.push(
616                        div()
617                            .id(ElementId::NamedChild(
618                                pane_id.clone().into(),
619                                SharedString::from(format!("{id_prefix}day-{key}")),
620                            ))
621                            .test_support()
622                            .role(Role::GridCell)
623                            .aria_selected(in_range)
624                            .aria_label(SharedString::from(key.clone()))
625                            .relative()
626                            .w(px(cell_w))
627                            .h(px(cell_h))
628                            .flex()
629                            .items_center()
630                            .justify_center()
631                            .when(!disabled_here, |this| {
632                                this.cursor_pointer().on_hover(move |hovered, window, cx| {
633                                    if *hovered && hover_st.read(cx).anchor.is_some() {
634                                        hover_st.update(cx, |s, _| {
635                                            s.hover = Some(date_for_hover);
636                                            s.preset_active = None;
637                                        });
638                                        window.refresh();
639                                    }
640                                })
641                            })
642                            .on_click(move |_, window, cx| {
643                                if disabled_here {
644                                    return;
645                                }
646                                focus_st.update(cx, |s, _| s.focused_date = Some(date_for_click));
647                                pick_for_click(date_for_click, &focus_st, window, cx);
648                            })
649                            .child(
650                                div()
651                                    .relative()
652                                    .w(px(32.0))
653                                    .h(px(32.0))
654                                    .flex()
655                                    .items_center()
656                                    .justify_center()
657                                    .rounded_full()
658                                    .text_size(Typography::TEXT_XS)
659                                    .when(edge || is_today, |this| this.font_medium())
660                                    .text_color(day_fg)
661                                    .when_some(bg, |this, bg| this.bg(bg))
662                                    .when(focused_here, |this| {
663                                        this.border_1().border_color(colors.control_fill)
664                                    })
665                                    .when(!disabled_here && !edge, |this| {
666                                        this.hover(move |s| s.bg(hover_cell_bg))
667                                    })
668                                    .child(SharedString::from(date.day.to_string()))
669                                    .when(is_today, |this| {
670                                        this.child(
671                                            div()
672                                                .absolute()
673                                                .bottom(px(3.0))
674                                                .w(px(4.0))
675                                                .h(px(4.0))
676                                                .rounded_full()
677                                                .bg(today_dot_color),
678                                        )
679                                    }),
680                            )
681                            .into_any_element(),
682                    );
683                }
684                // Week slice bar behind the days.
685                let bar_el = if bar_width > 0.0 {
686                    Some(
687                        div()
688                            .absolute()
689                            .left(px(bar_left))
690                            .top(px(2.0))
691                            .w(px(bar_width))
692                            .h(px(32.0))
693                            .rounded(Radii::PILL)
694                            .bg(bar_bg),
695                    )
696                } else {
697                    None
698                };
699                week_els.push(
700                    div()
701                        .relative()
702                        .flex()
703                        .flex_row()
704                        .when_some(bar_el, |this, el| this.child(el))
705                        .children(day_els)
706                        .into_any_element(),
707                );
708            }
709            div()
710                .w(px(cell_w * 7.0))
711                .flex_none()
712                .flex()
713                .flex_col()
714                .child(
715                    div()
716                        .h(px(32.0))
717                        .flex()
718                        .items_center()
719                        .justify_center()
720                        .text_size(Typography::TEXT_SM)
721                        .font_semibold()
722                        .text_color(colors.foreground)
723                        .child(SharedString::from(calendar_month_label(month))),
724                )
725                .child(div().flex().flex_row().children(weekday_els))
726                .child(div().relative().flex().flex_col().children(week_els))
727                .into_any_element()
728        };
729
730        let range_for_render = draft;
731        let view_month_now = snap.view_month;
732        #[allow(clippy::type_complexity)]
733        let pick_for_panels: Rc<
734            dyn Fn(CalendarDate, &gpui_kit::Entity<DateRangeInternal>, &mut Window, &mut App),
735        > = Rc::new(pick);
736
737        let month_a = view_month_now;
738        let month_b = calendar_add_months(view_month_now, 1);
739
740        // Preset rail.
741        let rail_id = self.id.clone();
742        let preset_labels = PRESETS;
743        let active_preset = snap.preset_active.or_else(|| {
744            draft.and_then(|r| {
745                (0..PRESETS.len()).find(|&idx| {
746                    let pr = preset_range(idx, today);
747                    calendar_same_day(pr.start, r.start) && calendar_same_day(pr.end, r.end)
748                })
749            })
750        });
751        let preset_st = internal.clone();
752        let rail_els: Vec<AnyElement> = preset_labels
753            .iter()
754            .enumerate()
755            .map(|(index, label)| {
756                let is_active = active_preset == Some(index);
757                let label_s = SharedString::from(*label);
758                let st_p = preset_st.clone();
759                let apply_p = apply_preset.clone();
760                let active_bg = oklab_mix(colors.control_fill, colors.surface_raised, 0.10);
761                div()
762                    .id(ElementId::NamedChild(
763                        rail_id.clone().into(),
764                        SharedString::from(format!("preset-{index}")),
765                    ))
766                    .test_support()
767                    .role(Role::Button)
768                    .aria_label(label_s.clone())
769                    .flex_none()
770                    .w(px(124.0))
771                    .h(px(34.0))
772                    .px(px(12.0))
773                    .flex()
774                    .items_center()
775                    .rounded(Radii::PILL)
776                    .text_size(Typography::TEXT_XS)
777                    .when(is_active, |this| this.font_medium())
778                    .text_color(if is_active {
779                        colors.foreground
780                    } else {
781                        colors.text_secondary
782                    })
783                    .bg(if is_active {
784                        active_bg
785                    } else {
786                        Hsla::transparent_black()
787                    })
788                    .cursor_pointer()
789                    .when(!is_active, |this| {
790                        this.hover(move |s| s.bg(colors.surface_muted))
791                    })
792                    .on_click(move |_, window, cx| {
793                        apply_p(index, window, cx);
794                        let _ = &st_p;
795                    })
796                    .child(label_s)
797                    .into_any_element()
798            })
799            .collect();
800
801        let prev_st = internal.clone();
802        let next_st = internal.clone();
803        let nav_id = self.id.clone();
804
805        let popover_el = if presence.should_render() {
806            let st_panels = internal.clone();
807            let prev_btn = div()
808                .id(ElementId::NamedChild(
809                    nav_id.clone().into(),
810                    "prev-month".into(),
811                ))
812                .test_support()
813                .aria_label("Previous month")
814                .absolute()
815                .left(px(2.0))
816                .top(px(2.0))
817                .w(px(28.0))
818                .h(px(28.0))
819                .flex()
820                .items_center()
821                .justify_center()
822                .rounded_full()
823                .text_color(colors.text_secondary)
824                .cursor_pointer()
825                .hover(move |s| s.bg(colors.surface_muted))
826                .on_click(
827                    move |_: &gpui_kit::ClickEvent, window: &mut Window, cx: &mut App| {
828                        prev_st.update(cx, |s, _| {
829                            s.view_month = calendar_add_months(s.view_month, -1);
830                        });
831                        window.refresh();
832                    },
833                )
834                .child(
835                    div()
836                        .text_size(Typography::TEXT_SM)
837                        .child(SharedString::from("\u{2039}")),
838                );
839            let next_btn = div()
840                .id(ElementId::NamedChild(
841                    nav_id.clone().into(),
842                    "next-month".into(),
843                ))
844                .test_support()
845                .aria_label("Next month")
846                .absolute()
847                .right(px(2.0))
848                .top(px(2.0))
849                .w(px(28.0))
850                .h(px(28.0))
851                .flex()
852                .items_center()
853                .justify_center()
854                .rounded_full()
855                .text_color(colors.text_secondary)
856                .cursor_pointer()
857                .hover(move |s| s.bg(colors.surface_muted))
858                .on_click(
859                    move |_: &gpui_kit::ClickEvent, window: &mut Window, cx: &mut App| {
860                        next_st.update(cx, |s, _| {
861                            s.view_month = calendar_add_months(s.view_month, 1);
862                        });
863                        window.refresh();
864                    },
865                )
866                .child(
867                    div()
868                        .text_size(Typography::TEXT_SM)
869                        .child(SharedString::from("\u{203a}")),
870                );
871
872            let summary_label = SharedString::from(format_range(draft, &self.placeholder));
873            let days_count = draft.map(|r| r.days()).unwrap_or(0);
874            let days_label = if days_count == 1 {
875                SharedString::from("1 day")
876            } else if days_count > 1 {
877                SharedString::from(format!("{days_count} days"))
878            } else {
879                SharedString::from("")
880            };
881            let st_cancel = internal.clone();
882            let st_apply = internal.clone();
883            let ch_apply = self.on_change.clone();
884            let is_ctrl_apply = is_ctrl;
885            let footer_el = div()
886                .mt(px(8.0))
887                .pt(px(10.0))
888                .border_t_1()
889                .border_color(colors.border_subtle)
890                .flex()
891                .flex_row()
892                .items_center()
893                .justify_between()
894                .gap(px(12.0))
895                .child(
896                    div()
897                        .flex()
898                        .flex_row()
899                        .items_baseline()
900                        .gap(px(8.0))
901                        .child(
902                            div()
903                                .text_size(Typography::TEXT_XS)
904                                .font_medium()
905                                .text_color(if draft.is_some() {
906                                    colors.foreground
907                                } else {
908                                    colors.text_muted
909                                })
910                                .child(summary_label),
911                        )
912                        .when(!days_label.is_empty(), |this| {
913                            this.child(
914                                div()
915                                    .text_size(Typography::TEXT_XS)
916                                    .text_color(colors.text_muted)
917                                    .child(days_label),
918                            )
919                        }),
920                )
921                .child(
922                    div()
923                        .flex()
924                        .flex_row()
925                        .items_center()
926                        .gap(px(6.0))
927                        .child(
928                            BaseButton::new(ElementId::NamedChild(
929                                nav_id.clone().into(),
930                                "cancel-button".into(),
931                            ))
932                            .accessibility_label("Cancel")
933                            .on_click(move |_, window, cx| {
934                                st_cancel.update(cx, |s, _| {
935                                    s.open = false;
936                                    s.anchor = None;
937                                    s.hover = None;
938                                });
939                                window.refresh();
940                            })
941                            .h(px(30.0))
942                            .px(px(12.0))
943                            .flex()
944                            .items_center()
945                            .justify_center()
946                            .rounded(Radii::PILL)
947                            .text_size(Typography::TEXT_XS)
948                            .font_medium()
949                            .text_color(colors.text_secondary)
950                            .cursor_pointer()
951                            .hover(move |s| s.bg(colors.surface_muted))
952                            .child(SharedString::from("Cancel")),
953                        )
954                        .child(
955                            BaseButton::new(ElementId::NamedChild(
956                                nav_id.clone().into(),
957                                "apply-button".into(),
958                            ))
959                            .accessibility_label("Apply")
960                            .disabled(draft.is_none())
961                            .on_click(move |_, window, cx| {
962                                let Some(r) = draft else {
963                                    return;
964                                };
965                                st_apply.update(cx, |s, _| {
966                                    if !is_ctrl_apply {
967                                        s.uncontrolled = Some(r);
968                                    }
969                                    s.seen_value = Some(Some(r));
970                                    s.anchor = None;
971                                    s.hover = None;
972                                    s.open = false;
973                                });
974                                if let Some(handler) = &ch_apply {
975                                    handler(&Some((r.start, r.end)), window, cx);
976                                }
977                                window.refresh();
978                            })
979                            .h(px(30.0))
980                            .px(px(14.0))
981                            .flex()
982                            .items_center()
983                            .justify_center()
984                            .rounded(Radii::PILL)
985                            .bg(colors.control_fill)
986                            .text_size(Typography::TEXT_XS)
987                            .font_medium()
988                            .text_color(colors.surface)
989                            .when(draft.is_some(), |this| this.cursor_pointer())
990                            .child(SharedString::from("Apply")),
991                        ),
992                );
993            Some(
994                deferred(
995                    div()
996                        .id(ElementId::NamedChild(
997                            self.id.clone().into(),
998                            "panel".into(),
999                        ))
1000                        .test_support()
1001                        .role(Role::Dialog)
1002                        .aria_label(SharedString::from(format!("{} range", self.label)))
1003                        .absolute()
1004                        .top_full()
1005                        .mt(px(6.0 + panel_y))
1006                        .left_0()
1007                        .w(px(716.0))
1008                        .p(px(14.0))
1009                        .rounded(Radii::PANEL)
1010                        .border_1()
1011                        .border_color(colors.border)
1012                        .bg(colors.surface_raised)
1013                        .shadow(Shadows::floating(theme.mode))
1014                        .opacity(p)
1015                        .child(
1016                            canvas(
1017                                {
1018                                    let probe = snap.panel_bounds.clone();
1019                                    move |rect, _, _| {
1020                                        *probe.borrow_mut() = Some(rect);
1021                                    }
1022                                },
1023                                {
1024                                    let st = internal.clone();
1025                                    let t_ref = snap.trigger_bounds.clone();
1026                                    move |panel_rect, _, window, _| {
1027                                        let st = st.clone();
1028                                        let t_ref = t_ref.clone();
1029                                        window.on_mouse_event(
1030                                            move |event: &MouseDownEvent, phase, window, cx| {
1031                                                if !phase.bubble() || !st.read(cx).open {
1032                                                    return;
1033                                                }
1034                                                let in_trigger = t_ref
1035                                                    .borrow()
1036                                                    .is_some_and(|b| b.contains(&event.position));
1037                                                let in_panel = panel_rect.contains(&event.position);
1038                                                if !in_trigger && !in_panel {
1039                                                    st.update(cx, |s, _| {
1040                                                        s.open = false;
1041                                                        s.anchor = None;
1042                                                    });
1043                                                    window.refresh();
1044                                                }
1045                                            },
1046                                        );
1047                                    }
1048                                },
1049                            )
1050                            .absolute()
1051                            .inset_0(),
1052                        )
1053                        .on_key_down({
1054                            let st = internal.clone();
1055                            let pick_k = pick_for_panels.clone();
1056                            let min_k = self.min_date;
1057                            let max_k = self.max_date;
1058                            move |event: &KeyDownEvent, window, cx| {
1059                                let key = event.keystroke.key.as_str();
1060                                match key {
1061                                    "escape" => {
1062                                        st.update(cx, |s, _| {
1063                                            s.open = false;
1064                                            s.anchor = None;
1065                                        });
1066                                        window.refresh();
1067                                    }
1068                                    "enter" | " " | "space" => {
1069                                        if let Some(d) = st.read(cx).focused_date {
1070                                            pick_k(d, &st, window, cx);
1071                                        }
1072                                    }
1073                                    "left" | "arrowleft" | "right" | "arrowright" | "up"
1074                                    | "arrowup" | "down" | "arrowdown" => {
1075                                        let from = st
1076                                            .read(cx)
1077                                            .focused_date
1078                                            .unwrap_or(st.read(cx).view_month);
1079                                        let delta: i64 = match key {
1080                                            "left" | "arrowleft" => -1,
1081                                            "right" | "arrowright" => 1,
1082                                            "up" | "arrowup" => -7,
1083                                            _ => 7,
1084                                        };
1085                                        let mut next = calendar_add_days(from, delta);
1086                                        if let Some(m) = min_k
1087                                            && calendar_to_epoch_days(next)
1088                                                < calendar_to_epoch_days(m)
1089                                        {
1090                                            next = m;
1091                                        }
1092                                        if let Some(m) = max_k
1093                                            && calendar_to_epoch_days(next)
1094                                                > calendar_to_epoch_days(m)
1095                                        {
1096                                            next = m;
1097                                        }
1098                                        st.update(cx, |s, _| {
1099                                            s.focused_date = Some(next);
1100                                            if next.month != s.view_month.month {
1101                                                s.view_month = calendar_month_start(next);
1102                                            }
1103                                        });
1104                                        window.refresh();
1105                                    }
1106                                    _ => {}
1107                                }
1108                            }
1109                        })
1110                        .child(
1111                            div()
1112                                .relative()
1113                                .flex()
1114                                .flex_row()
1115                                .gap(px(14.0))
1116                                .child(
1117                                    div()
1118                                        .id(ElementId::NamedChild(
1119                                            dr_id.clone().into(),
1120                                            "preset-rail".into(),
1121                                        ))
1122                                        .flex_none()
1123                                        .h(px(236.0))
1124                                        .max_h(px(236.0))
1125                                        .pr(px(10.0))
1126                                        .border_r_1()
1127                                        .border_color(colors.border_subtle)
1128                                        .overflow_y_scroll()
1129                                        .on_scroll(|_, _, cx| cx.stop_propagation())
1130                                        .flex()
1131                                        .flex_col()
1132                                        .gap(px(2.0))
1133                                        .children(rail_els),
1134                                )
1135                                .child(
1136                                    div()
1137                                        .flex_1()
1138                                        .flex()
1139                                        .flex_col()
1140                                        .child(
1141                                            div()
1142                                                .relative()
1143                                                .flex()
1144                                                .flex_row()
1145                                                .gap(px(16.0))
1146                                                .child(render_month(
1147                                                    month_a,
1148                                                    range_for_render,
1149                                                    dr_id.clone(),
1150                                                    "",
1151                                                    st_panels.clone(),
1152                                                    pick_for_panels.clone(),
1153                                                ))
1154                                                .child(render_month(
1155                                                    month_b,
1156                                                    range_for_render,
1157                                                    dr_id.clone(),
1158                                                    "b-",
1159                                                    st_panels,
1160                                                    pick_for_panels,
1161                                                ))
1162                                                .child(prev_btn)
1163                                                .child(next_btn),
1164                                        )
1165                                        .child(footer_el),
1166                                ),
1167                        ),
1168                )
1169                .with_priority(25),
1170            )
1171        } else {
1172            None
1173        };
1174
1175        let msg_id = ElementId::NamedChild(self.id.clone().into(), "message".into());
1176        let root_id = self.id.clone();
1177
1178        div()
1179            .id(root_id)
1180            .test_support()
1181            .when_some(self.width, |this, w| this.w(w))
1182            .when(self.width.is_none(), |this| this.w_full())
1183            .flex()
1184            .flex_col()
1185            .gap(Spacing::S2)
1186            .when(self.disabled, |this| this.opacity(0.5))
1187            .child(
1188                div()
1189                    .text_size(Typography::TEXT_SM)
1190                    .font_medium()
1191                    .text_color(colors.foreground)
1192                    .child(self.label.clone()),
1193            )
1194            .child(
1195                div().relative().w_full().child(
1196                    div()
1197                        .relative()
1198                        .w_full()
1199                        .flex_none()
1200                        .child(trigger)
1201                        .when_some(popover_el, |this, el| this.child(el)),
1202                ),
1203            )
1204            .child(render_field_message(msg_id, None, false, window, cx))
1205    }
1206}
1207
1208#[cfg(test)]
1209mod tests {
1210    use arc_tokens::{Accent, ThemeMode, install_arc_theme};
1211    use gpui_kit::{Context, Render, TestAppContext, test::TestWindowExt as _};
1212
1213    use super::*;
1214
1215    const D: fn(i32, u32, u32) -> CalendarDate =
1216        |year, month, day| CalendarDate { year, month, day };
1217
1218    #[test]
1219    fn date_range_ordered_swaps_and_counts_days() {
1220        let r = DateRange::ordered(D(2026, 11, 20), D(2026, 11, 5));
1221        assert_eq!(r.start, D(2026, 11, 5));
1222        assert_eq!(r.end, D(2026, 11, 20));
1223        assert_eq!(r.days(), 16);
1224    }
1225
1226    #[test]
1227    fn date_range_presets_resolve_offsets() {
1228        let today = D(2026, 11, 27);
1229        assert_eq!(
1230            preset_range(0, today),
1231            DateRange {
1232                start: today,
1233                end: today
1234            }
1235        );
1236        assert_eq!(preset_range(2, today).start, D(2026, 11, 21));
1237        assert_eq!(preset_range(3, today).start, D(2026, 10, 29));
1238        // Last month: Nov picker → Oct 1 .. Oct 31.
1239        assert_eq!(preset_range(5, today).start, D(2026, 10, 1));
1240        assert_eq!(preset_range(5, today).end, D(2026, 10, 31));
1241    }
1242
1243    struct RangeHost {
1244        value: Option<DateRange>,
1245        events: Rc<RefCell<Vec<String>>>,
1246        disabled: bool,
1247    }
1248
1249    impl Render for RangeHost {
1250        fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1251            let events = self.events.clone();
1252            div().w(px(780.0)).p(px(16.0)).child(
1253                DateRangePicker::new("dr-test")
1254                    .label("Reporting window")
1255                    .when_some(self.value, |p, v| p.value(v))
1256                    .disabled(self.disabled)
1257                    .on_change(cx.listener({
1258                        let events = events.clone();
1259                        move |this, range: &Option<(CalendarDate, CalendarDate)>, _, cx| {
1260                            match range {
1261                                Some((a, b)) => events.borrow_mut().push(format!(
1262                                    "{}..{}",
1263                                    calendar_date_key(*a),
1264                                    calendar_date_key(*b)
1265                                )),
1266                                None => events.borrow_mut().push("cleared".to_string()),
1267                            }
1268                            this.value = range.map(|(a, b)| DateRange { start: a, end: b });
1269                            cx.notify();
1270                        }
1271                    })),
1272            )
1273        }
1274    }
1275
1276    fn dr_element(name: &str) -> ElementId {
1277        ElementId::NamedChild(ElementId::Name("dr-test".into()).into(), name.into())
1278    }
1279
1280    #[gpui_kit::test]
1281    fn date_range_picks_presets_and_days(cx: &mut TestAppContext) {
1282        cx.update(|cx| {
1283            gpui_kit::init(cx);
1284            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
1285        });
1286
1287        let host = RangeHost {
1288            value: None,
1289            events: Rc::new(RefCell::new(Vec::new())),
1290            disabled: false,
1291        };
1292        let events = host.events.clone();
1293        let (view, cx) = cx.add_window_view(|_, _| host);
1294
1295        cx.update(|window, cx| {
1296            window.render_frame(cx);
1297            window.click(dr_element("trigger"), cx);
1298            window.render_frame(cx);
1299            let panel = window.find(dr_element("panel"));
1300            assert_eq!(panel.role(), Some(Role::Dialog));
1301
1302            // Preset rail applies instantly.
1303            window.click(dr_element("preset-2"), cx);
1304        });
1305        cx.executor()
1306            .advance_clock(std::time::Duration::from_millis(400));
1307        assert_eq!(
1308            events.borrow().last().map(String::as_str),
1309            Some("2026-11-21..2026-11-27")
1310        );
1311
1312        cx.update(|window, cx| {
1313            for _ in 0..3 {
1314                window.render_frame(cx);
1315            }
1316            // Panel remains open so user can inspect the preset or adjust dates directly.
1317            assert!(window.try_find(dr_element("panel")).is_some());
1318
1319            // Two clicks build a range: anchor then end.
1320            window.click(dr_element("day-2026-11-05"), cx);
1321            window.render_frame(cx);
1322            window.click(dr_element("day-2026-11-12"), cx);
1323            window.render_frame(cx);
1324            window.click(dr_element("apply-button"), cx);
1325            window.render_frame(cx);
1326        });
1327        cx.executor()
1328            .advance_clock(std::time::Duration::from_millis(200));
1329        cx.update(|window, cx| {
1330            window.render_frame(cx);
1331            assert!(window.try_find(dr_element("panel")).is_none());
1332        });
1333        assert_eq!(
1334            events.borrow().last().map(String::as_str),
1335            Some("2026-11-05..2026-11-12")
1336        );
1337
1338        // Disabled swallows the open.
1339        view.update(cx, |host, cx| {
1340            host.disabled = true;
1341            host.value = Some(DateRange {
1342                start: D(2026, 11, 5),
1343                end: D(2026, 11, 12),
1344            });
1345            cx.notify();
1346        });
1347        cx.update(|window, cx| {
1348            window.render_frame(cx);
1349            window.click(dr_element("trigger"), cx);
1350            window.render_frame(cx);
1351            assert!(window.try_find(dr_element("panel")).is_none());
1352        });
1353    }
1354}