use std::{cell::RefCell, rc::Rc};
use arc_motion::{
ArcPresence, ArcPresenceConfig, BlurFallback, CubicBezier, arc_spring, is_reduced_motion,
motion_now,
};
use arc_tokens::{ActiveArcTheme as _, Radii, Shadows, Spacing, Typography, oklab_mix};
use gpui_kit::{
AnyElement, App, Bounds, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent,
MouseDownEvent, ParentElement, PathBuilder, Pixels, RenderOnce, Role, SharedString, Styled,
TestSupportExt as _, Window,
base::{Button as BaseButton, StyledExt as _},
canvas, deferred, div, point,
prelude::*,
px,
};
use super::field_message::render_field_message;
type TimeChangeHandler = Rc<dyn Fn(&SharedString, &mut Window, &mut App)>;
const PAD: fn(usize) -> String = |v| format!("{v:02}");
pub fn time_picker_display(raw: &str, format_24h: bool) -> String {
let minutes = time_picker_to_minutes(raw);
let hour = minutes / 60;
let minute = minutes % 60;
if format_24h {
format!("{}:{}", PAD(hour), PAD(minute))
} else {
let shown_hour = hour % 12;
let shown_hour = if shown_hour == 0 { 12 } else { shown_hour };
format!(
"{}:{} {}",
shown_hour,
PAD(minute),
if hour < 12 { "AM" } else { "PM" }
)
}
}
pub fn time_picker_to_minutes(value: &str) -> usize {
let (h, m) = value.split_once(':').unwrap_or(("x", "x"));
match (h.trim().parse::<usize>(), m.trim().parse::<usize>()) {
(Ok(h), Ok(m)) if h < 24 && m < 60 => h * 60 + m,
_ => 0,
}
}
#[derive(Clone)]
struct TimePickerInternal {
uncontrolled: SharedString,
seen_value: Option<SharedString>,
open: bool,
active_index: usize,
direction: i8,
changed_at_secs: f64,
trigger_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
menu_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
focus_handle: FocusHandle,
}
impl TimePickerInternal {
fn new(default_value: SharedString, cx: &mut App) -> Self {
Self {
uncontrolled: default_value,
seen_value: None,
open: false,
active_index: 0,
direction: 1,
changed_at_secs: f64::NEG_INFINITY,
trigger_bounds: Rc::new(RefCell::new(None)),
menu_bounds: Rc::new(RefCell::new(None)),
focus_handle: cx.focus_handle(),
}
}
}
fn paint_clock_glyph(cx: f32, cy: f32, color: Hsla, window: &mut Window) {
let segments = 20;
let radius = 7.0_f32;
let mut builder = PathBuilder::stroke(px(1.5));
for i in 0..=segments {
let angle = i as f32 / segments as f32 * std::f32::consts::TAU;
let x = cx + angle.cos() * radius;
let y = cy + angle.sin() * radius;
let p = point(px(x), px(y));
if i == 0 {
builder.move_to(p);
} else {
builder.line_to(p);
}
}
if let Ok(path) = builder.build() {
window.paint_path(path, color);
}
let mut hands = PathBuilder::stroke(px(1.5));
hands.move_to(point(px(cx), px(cy)));
hands.line_to(point(px(cx), px(cy - 4.0)));
if let Ok(path) = hands.build() {
window.paint_path(path, color);
}
let mut minute_hand = PathBuilder::stroke(px(1.5));
minute_hand.move_to(point(px(cx), px(cy)));
minute_hand.line_to(point(px(cx + 3.0), px(cy)));
if let Ok(path) = minute_hand.build() {
window.paint_path(path, color);
}
}
fn paint_chevron(cx: f32, cy: f32, color: Hsla, window: &mut Window) {
let pts = [(-3.0_f32, -2.0_f32), (0.0, 2.0), (3.0, -2.0)];
let mut builder = PathBuilder::stroke(px(1.75));
for (i, (lx, ly)) in pts.iter().enumerate() {
let p = point(px(cx + lx), px(cy + ly));
if i == 0 {
builder.move_to(p);
} else {
builder.line_to(p);
}
}
if let Ok(path) = builder.build() {
window.paint_path(path, color);
}
}
#[derive(IntoElement)]
pub struct TimePicker {
id: ElementId,
label: SharedString,
value: Option<SharedString>,
default_value: SharedString,
description: Option<SharedString>,
placeholder: SharedString,
minute_step: usize,
format_24h: bool,
disabled: bool,
width: Option<Pixels>,
on_change: Option<TimeChangeHandler>,
}
impl TimePicker {
pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
Self {
id: id.into(),
label: label.into(),
value: None,
default_value: "09:00".into(),
description: None,
placeholder: "Select a time".into(),
minute_step: 15,
format_24h: false,
disabled: false,
width: None,
on_change: None,
}
}
pub fn value(mut self, value: impl Into<SharedString>) -> Self {
self.value = Some(value.into());
self
}
pub fn default_value(mut self, value: impl Into<SharedString>) -> Self {
self.default_value = value.into();
self
}
pub fn description(mut self, description: impl Into<SharedString>) -> Self {
self.description = Some(description.into());
self
}
pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
self.placeholder = placeholder.into();
self
}
pub fn minute_step(mut self, minute_step: usize) -> Self {
self.minute_step = minute_step.clamp(1, 30);
self
}
pub fn format_24h(mut self, format_24h: bool) -> Self {
self.format_24h = format_24h;
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(&SharedString, &mut Window, &mut App) + 'static,
) -> Self {
self.on_change = Some(Rc::new(handler));
self
}
}
impl RenderOnce for TimePicker {
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 options: Vec<SharedString> = (0..(1440 / self.minute_step.clamp(1, 1440).max(1)))
.map(|index| {
let minutes = index * self.minute_step;
SharedString::from(format!("{}:{}", PAD(minutes / 60), PAD(minutes % 60)))
})
.collect();
let state_id = ElementId::NamedChild(self.id.clone().into(), "__arc-time-state".into());
let internal = window.use_keyed_state(state_id, cx, |_, cx| {
TimePickerInternal::new(self.default_value.clone(), cx)
});
if let Some(ext) = self.value.clone() {
let seen = internal.read(cx).seen_value.clone();
if seen.as_ref() != Some(&ext) {
internal.update(cx, |s, _| {
let prev = s
.seen_value
.clone()
.unwrap_or_else(|| s.uncontrolled.clone());
s.direction = if time_picker_to_minutes(&ext) >= time_picker_to_minutes(&prev) {
1
} else {
-1
};
s.seen_value = Some(ext.clone());
s.changed_at_secs = now;
});
}
}
let is_ctrl = self.value.is_some();
let selected = self
.value
.clone()
.or_else(|| internal.read(cx).seen_value.clone())
.unwrap_or_else(|| internal.read(cx).uncontrolled.clone());
let snap_state = internal.read(cx).clone();
let open = snap_state.open && !self.disabled;
let active_index = snap_state.active_index.min(options.len().saturating_sub(1));
let src_elapsed = (now - snap_state.changed_at_secs).max(0.0);
let (value_op, value_y) = if src_elapsed >= 0.24 {
(1.0_f32, 0.0_f32)
} else {
window.request_animation_frame();
let t = (src_elapsed / 0.24).clamp(0.0, 1.0) as f32;
let e = if reduced {
t
} else {
CubicBezier::new(0.16, 1.0, 0.3, 1.0).sample(t)
};
let blur = BlurFallback::evaluate(px(4.0 * (1.0 - e)), reduced);
let y = if reduced {
0.0
} else {
(snap_state.direction as f32) * 0.35 * f32::from(Typography::TEXT_SM) * (1.0 - e)
};
((e * blur.opacity_multiplier).clamp(0.0, 1.0), y)
};
let menu_presence = ArcPresence::new((self.id.clone(), "tp-presence"), open)
.animate_initial(false)
.config(ArcPresenceConfig {
enter_duration: motion.duration.fast,
exit_duration: motion.duration.instant,
enter_ease: motion.ease.enter,
exit_ease: motion.ease.standard,
fade_on_reduced_motion: true,
})
.sample(window, cx);
let p = menu_presence.progress.clamp(0.0, 1.0);
let menu_y = if reduced {
0.0
} else {
arc_spring(
(self.id.clone(), "tp-y"),
if open { 0.0 } else { -4.0 },
motion.spring.snappy,
window,
cx,
)
};
let display_fn = |raw: &str| time_picker_display(raw, self.format_24h);
let shown = display_fn(&selected);
let choose_st = internal.clone();
let choose_ch = self.on_change.clone();
let choose_is_ctrl = is_ctrl;
let choose = move |next: SharedString,
st: &gpui_kit::Entity<TimePickerInternal>,
window: &mut Window,
cx: &mut App| {
let now_c = motion_now(cx);
let prev = st.read(cx).uncontrolled.clone();
st.update(cx, |s, _| {
if !choose_is_ctrl {
s.uncontrolled = next.clone();
}
s.seen_value = Some(next.clone());
s.direction = if time_picker_to_minutes(&next) >= time_picker_to_minutes(&prev) {
1
} else {
-1
};
s.changed_at_secs = now_c;
s.open = false;
});
if let Some(handler) = &choose_ch {
handler(&next, window, cx);
}
window.refresh();
};
let muted_color = colors.text_muted;
let trigger_hover = colors.surface_muted;
let trigger = BaseButton::new(ElementId::NamedChild(
self.id.clone().into(),
"trigger".into(),
))
.accessibility_label(SharedString::from(format!("{}: {}", self.label, shown)))
.disabled(self.disabled)
.on_click({
let st = internal.clone();
let options_len = options.len();
let selected_for_open = selected.clone();
let disabled_flag = self.disabled;
move |_, window, cx| {
if disabled_flag {
return;
}
window.focus(&st.read(cx).focus_handle.clone(), cx);
st.update(cx, |s, _| {
s.open = !s.open;
let idx = options_len
.checked_sub(1)
.and_then(|max| {
(0..=max).find(|i| {
let minutes = time_picker_to_minutes(&selected_for_open);
let step = 1440_usize / options_len.max(1);
*i * step == minutes
})
})
.unwrap_or(0);
s.active_index = idx;
});
window.refresh();
}
})
.w_full()
.h(px(38.0))
.px(px(10.0))
.flex()
.flex_row()
.items_center()
.gap(px(8.0))
.rounded(px(10.0))
.border_1()
.border_color(if self.disabled {
colors.border
} else {
colors.border_strong
})
.bg(colors.surface)
.opacity(if self.disabled { 0.5 } else { 1.0 })
.when(!self.disabled, |this| {
this.cursor_pointer().hover(move |s| s.bg(trigger_hover))
})
.child(
div().w(px(16.0)).h(px(16.0)).flex_none().child(
canvas(
|_, _, _| {},
move |rect, _, window, _| {
let cx_pt = f32::from(rect.origin.x + rect.size.width * 0.5);
let cy_pt = f32::from(rect.origin.y + rect.size.height * 0.5);
paint_clock_glyph(cx_pt, cy_pt, muted_color, window);
},
)
.size_full(),
),
)
.child(
div()
.flex_1()
.min_w_0()
.mt(px(value_y))
.opacity(value_op)
.text_size(Typography::TEXT_SM)
.text_color(if !selected.is_empty() {
colors.foreground
} else {
muted_color
})
.child(SharedString::from(if selected.is_empty() {
self.placeholder.to_string()
} else {
shown
})),
)
.child(
div().w(px(16.0)).h(px(16.0)).flex_none().child(
canvas(
|_, _, _| {},
move |rect, _, window, _| {
let cx_pt = f32::from(rect.origin.x + rect.size.width * 0.5);
let cy_pt = f32::from(rect.origin.y + rect.size.height * 0.5);
paint_chevron(cx_pt, cy_pt, muted_color, window);
},
)
.size_full(),
),
);
let menu_open = menu_presence.should_render();
let menu_el = if menu_open {
let st_hover = internal.clone();
let choose_hover = choose.clone();
let rows: Vec<AnyElement> = options
.iter()
.enumerate()
.map(|(index, option)| {
let is_selected = *option == selected;
let is_active = index == active_index;
let row_fg = if is_active || is_selected {
colors.foreground
} else {
colors.text_secondary
};
let option_for_hover = option.clone();
let option_for_click = option.clone();
let hover_st = st_hover.clone();
let click_st = choose_st.clone();
let click_choose = choose_hover.clone();
div()
.id(ElementId::NamedChild(
self.id.clone().into(),
SharedString::from(format!("option-{index}")),
))
.test_support()
.role(Role::ListBoxOption)
.aria_selected(is_selected)
.aria_label(SharedString::from(display_fn(option)))
.w_full()
.flex_none()
.h(px(34.0))
.min_h(px(34.0))
.px(px(10.0))
.flex()
.flex_row()
.items_center()
.justify_between()
.rounded(px(8.0))
.text_size(Typography::TEXT_SM)
.text_color(row_fg)
.bg(if is_active {
oklab_mix(colors.foreground, colors.surface_raised, 0.065)
} else {
Hsla::transparent_black()
})
.cursor_pointer()
.on_hover(move |hovered, window, cx| {
if *hovered {
hover_st.update(cx, |s, _| s.active_index = index);
window.refresh();
}
let _ = &option_for_hover;
})
.on_click(move |_, window, cx| {
click_choose(option_for_click.clone(), &click_st, window, cx);
})
.child(SharedString::from(display_fn(option)))
.child(
div()
.size(px(6.0))
.rounded_full()
.bg(colors.control_fill)
.when(!is_selected, |this| this.opacity(0.0)),
)
.into_any_element()
})
.collect();
Some(
deferred(
div()
.id(ElementId::NamedChild(
self.id.clone().into(),
"listbox".into(),
))
.test_support()
.role(Role::ListBox)
.aria_label(SharedString::from(format!("{} options", self.label)))
.absolute()
.top_full()
.mt(px(6.0 + menu_y))
.left_0()
.w(px(180.0))
.p(px(6.0))
.rounded(Radii::CONTROL)
.border_1()
.border_color(colors.border)
.bg(colors.surface_raised)
.shadow(Shadows::floating(theme.mode))
.opacity(p)
.overflow_hidden()
.child(canvas(
{
let probe = snap_state.menu_bounds.clone();
move |rect, _, _| {
*probe.borrow_mut() = Some(rect);
}
},
|_, _, _, _| {},
))
.child(
div()
.id(ElementId::NamedChild(
self.id.clone().into(),
"option-scroll".into(),
))
.h(px(240.0))
.max_h(px(240.0))
.overflow_y_scroll()
.on_scroll(|_, _, cx| cx.stop_propagation())
.flex()
.flex_col()
.gap(px(2.0))
.children(rows),
),
)
.with_priority(25),
)
} else {
None
};
let key_st = internal.clone();
let key_choose = choose.clone();
let key_options = options.clone();
let key_disabled = self.disabled;
let dismiss_st = internal.clone();
let dismiss_trigger = snap_state.trigger_bounds.clone();
let dismiss_menu = snap_state.menu_bounds.clone();
let dismiss_canvas = canvas(
{
let probe = snap_state.trigger_bounds.clone();
move |rect, _, _| {
*probe.borrow_mut() = Some(rect);
}
},
move |_, _, window, _| {
let st = dismiss_st.clone();
let trigger_ref = dismiss_trigger.clone();
let menu_ref = dismiss_menu.clone();
window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
if !phase.bubble() || !st.read(cx).open {
return;
}
let in_trigger = trigger_ref
.borrow()
.is_some_and(|b| b.contains(&event.position));
let in_menu = menu_ref
.borrow()
.is_some_and(|b| b.contains(&event.position));
if !in_trigger && !in_menu {
st.update(cx, |s, _| s.open = false);
window.refresh();
}
});
},
)
.absolute()
.inset_0();
let msg_id = ElementId::NamedChild(self.id.clone().into(), "message".into());
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()
.gap(Spacing::S2)
.when(self.disabled, |this| this.opacity(0.5))
.child(
div()
.text_size(Typography::TEXT_SM)
.font_medium()
.text_color(colors.foreground)
.child(self.label.clone()),
)
.child(
div()
.relative()
.w_full()
.track_focus(&snap_state.focus_handle.clone())
.child(dismiss_canvas)
.on_key_down(move |event: &KeyDownEvent, window, cx| {
if key_disabled {
return;
}
let key = event.keystroke.key.as_str();
let st_open = key_st.read(cx).open;
match key {
"escape" if st_open => {
key_st.update(cx, |s, _| s.open = false);
window.refresh();
}
"enter" | " " | "space" => {
if st_open {
let idx = key_st.read(cx).active_index;
if let Some(option) = key_options.get(idx) {
key_choose(option.clone(), &key_st, window, cx);
}
} else {
key_st.update(cx, |s, _| {
s.open = true;
});
window.refresh();
}
}
"down" | "arrowdown" | "up" | "arrowup" => {
if !st_open {
key_st.update(cx, |s, _| s.open = true);
window.refresh();
return;
}
let len = key_options.len().max(1);
let delta = if key.starts_with("down") || key == "down" {
1
} else {
-1
};
key_st.update(cx, |s, _| {
s.active_index = ((s.active_index as i64 + delta)
.rem_euclid(len as i64))
as usize;
});
window.refresh();
}
_ => {}
}
})
.child(trigger)
.when_some(menu_el, |this, el| this.child(el)),
)
.child(render_field_message(
msg_id,
self.description,
false,
window,
cx,
))
}
}
#[cfg(test)]
mod tests {
use arc_tokens::{Accent, ThemeMode, install_arc_theme};
use gpui_kit::{Context, Render, TestAppContext, test::TestWindowExt as _};
use super::*;
#[test]
fn time_picker_display_formats_12h_and_24h() {
assert_eq!(time_picker_display("15:15", false), "3:15 PM");
assert_eq!(time_picker_display("09:00", false), "9:00 AM");
assert_eq!(time_picker_display("00:30", false), "12:30 AM");
assert_eq!(time_picker_display("15:15", true), "15:15");
assert_eq!(time_picker_display("garbage", true), "00:00");
}
#[test]
fn time_picker_to_minutes_parses_and_rejects() {
assert_eq!(time_picker_to_minutes("15:15"), 915);
assert_eq!(time_picker_to_minutes("00:00"), 0);
assert_eq!(time_picker_to_minutes("garbage"), 0);
assert_eq!(time_picker_to_minutes("25:00"), 0);
}
struct TimeHost {
value: Option<SharedString>,
events: Rc<RefCell<Vec<String>>>,
disabled: bool,
}
impl Render for TimeHost {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let events = self.events.clone();
div().w(px(360.0)).p(px(16.0)).child(
TimePicker::new("time-test", "Start time")
.minute_step(15)
.format_24h(true)
.disabled(self.disabled)
.when_some(self.value.clone(), |p, v| p.value(v))
.on_change(cx.listener({
let events = events.clone();
move |this, v: &SharedString, _, cx| {
events.borrow_mut().push(v.to_string());
this.value = Some(v.clone());
cx.notify();
}
})),
)
}
}
fn time_element(name: &str) -> ElementId {
ElementId::NamedChild(ElementId::Name("time-test".into()).into(), name.into())
}
#[gpui_kit::test]
fn time_picker_opens_walks_and_picks(cx: &mut TestAppContext) {
cx.update(|cx| {
gpui_kit::init(cx);
install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
});
let host = TimeHost {
value: Some("09:00".into()),
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(time_element("trigger"), cx);
window.render_frame(cx);
let menu = window.find(time_element("listbox"));
assert_eq!(menu.role(), Some(Role::ListBox));
window.press("down", cx);
window.press("down", cx);
window.press("down", cx);
window.press("down", cx);
window.press("enter", cx);
});
assert_eq!(events.borrow().last().map(String::as_str), Some("10:00"));
view.update(cx, |host, cx| {
host.disabled = true;
host.value = Some("09:00".into());
cx.notify();
});
cx.update(|window, cx| {
window.render_frame(cx);
window.click(time_element("trigger"), cx);
window.render_frame(cx);
assert!(window.try_find(time_element("listbox")).is_none());
});
}
#[gpui_kit::test]
fn time_picker_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 = TimeHost {
value: Some("12:00".into()),
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(time_element("trigger"), cx);
window.render_frame(cx);
window.press("down", cx);
window.press("enter", cx);
});
assert_eq!(events.borrow().last().map(String::as_str), Some("12:15"));
}
}