ailloli_ui_widgets/controls/
pickers.rs

1//! Overlay date, time, and RGB color picker controls.
2//!
3//! Each picker supports read-only values or writable signal binding. Picker
4//! actions update a writable binding before calling `on_change`, and equal values
5//! are not emitted again. Popup geometry is expressed in logical pixels.
6
7use std::rc::Rc;
8
9use crate::layout::layout_ext::{apply_layout_size, finish_view_sized};
10use ailloli_ui_core::date_picker::{
11    add_months, clamp_date, is_date_enabled, month_grid, next_day, DateValue, MonthValue, WeekStart,
12};
13use ailloli_ui_core::event::pointer::{MouseButton, PointerEvent};
14use ailloli_ui_core::event::{Event, Key, KeyState, NamedKey};
15use ailloli_ui_core::geometry::{Constraints, Point, Rect, Size};
16use ailloli_ui_core::style::{
17    Border, BoxShadow, FlexItemStyle, LayoutSizeHint, LayoutStyle, Radius,
18};
19use ailloli_ui_core::time_picker::{
20    nudge_time, sanitize_step_minutes, snap_time, TimeFormat, TimeValue,
21};
22use ailloli_ui_core::{
23    color_to_hsv, format_hex_rgb, hsv_to_color, parse_hex_rgb, Color, FontId, HsvColor, IconId,
24    TextStyle, Theme,
25};
26use ailloli_ui_runtime::component::{
27    Binding, ComponentNode, Context, IntoView, Signal, View, Widget,
28};
29use ailloli_ui_runtime::input::{EventCtx, FocusPolicy, InputRole};
30use ailloli_ui_runtime::layout::{LayoutChild, LayoutCtx, LayoutResult};
31use ailloli_ui_runtime::scene::PaintCtx;
32use ailloli_ui_runtime::{
33    DrawBorder, DrawBoxShadow, DrawCmd, DrawImage, DrawRRect, DrawRect, DrawText,
34};
35use ailloli_ui_text::{TextBuffer, TextEditState, TextLayoutParams, WrapMode};
36use lucide_icons::Icon as LucideIcon;
37
38use super::text_field_core::{handle_single_line_text_event, TextFieldEventOptions};
39use super::text_input::TextInputStyle;
40
41/// Shared context-aware callback for a changed date.
42type DateChangeHandler<A> = Rc<dyn Fn(&mut EventCtx<A>, DateValue)>;
43/// Shared context-aware callback for a changed time.
44type TimeChangeHandler<A> = Rc<dyn Fn(&mut EventCtx<A>, TimeValue)>;
45/// Shared context-aware callback for a changed RGB color.
46type ColorChangeHandler<A> = Rc<dyn Fn(&mut EventCtx<A>, Color)>;
47
48#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
49/// Density preset for [`DatePickerStyle`].
50///
51/// # Examples
52///
53/// ```
54/// use ailloli_ui_widgets::controls::DatePickerSize;
55/// assert_eq!(DatePickerSize::default(), DatePickerSize::Default);
56/// assert_ne!(DatePickerSize::Compact, DatePickerSize::Default);
57/// ```
58pub enum DatePickerSize {
59    /// 180-by-30 trigger with denser calendar cells.
60    Compact,
61    #[default]
62    /// 220-by-36 trigger with regular calendar cells.
63    Default,
64}
65
66#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
67/// Density preset for [`TimePickerStyle`].
68///
69/// # Examples
70///
71/// ```
72/// use ailloli_ui_widgets::controls::TimePickerSize;
73/// assert_eq!(TimePickerSize::default(), TimePickerSize::Default);
74/// assert_ne!(TimePickerSize::Compact, TimePickerSize::Default);
75/// ```
76pub enum TimePickerSize {
77    /// 180-by-30 trigger and 26-pixel popup rows.
78    Compact,
79    #[default]
80    /// 220-by-36 trigger and 30-pixel popup rows.
81    Default,
82}
83
84#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
85/// Density preset for [`ColorPickerStyle`].
86///
87/// # Examples
88///
89/// ```
90/// use ailloli_ui_widgets::controls::ColorPickerSize;
91/// assert_eq!(ColorPickerSize::default(), ColorPickerSize::Default);
92/// assert_ne!(ColorPickerSize::Compact, ColorPickerSize::Default);
93/// ```
94pub enum ColorPickerSize {
95    /// 180-by-30 trigger and a 250-by-284 popup.
96    Compact,
97    #[default]
98    /// 220-by-36 trigger and a 282-by-318 popup.
99    Default,
100}
101
102#[derive(Clone, Debug, PartialEq)]
103/// Common trigger, popup, typography, and geometry tokens for all pickers.
104///
105/// Dimensions are logical pixels and opacity is a multiplier. Fields are used as
106/// supplied without validation.
107///
108/// # Examples
109///
110/// ```
111/// use ailloli_ui_widgets::controls::DatePickerStyle;
112/// let base = DatePickerStyle::default().base;
113/// assert_eq!((base.width, base.height), (220.0, 36.0));
114/// assert_eq!(base.disabled_opacity, 0.45);
115/// ```
116pub struct PickerBaseStyle {
117    /// Resting trigger fill.
118    pub trigger_background: Color,
119    /// Hovered enabled trigger fill.
120    pub trigger_hovered: Color,
121    /// Popup surface fill.
122    pub popup_background: Color,
123    /// Keyboard-active cell or row fill.
124    pub active: Color,
125    /// Selected cell or row fill.
126    pub selected: Color,
127    /// Reserved disabled fill token.
128    pub disabled_fill: Color,
129    /// Resting trigger border.
130    pub border: Border,
131    /// Popup border.
132    pub popup_border: Border,
133    /// Focused trigger border.
134    pub focus_ring: Border,
135    /// Popup shadows, painted in order.
136    pub shadows: Vec<BoxShadow>,
137    /// Primary text style.
138    pub text: TextStyle,
139    /// Placeholder and secondary text style.
140    pub muted_text: TextStyle,
141    /// Disabled trigger/cell text style.
142    pub disabled_text: TextStyle,
143    /// Accent text style for selected dates.
144    pub accent_text: TextStyle,
145    /// Preferred trigger width in logical pixels.
146    pub width: f32,
147    /// Preferred trigger height in logical pixels.
148    pub height: f32,
149    /// Gap below the trigger before the popup, in logical pixels.
150    pub popup_gap: f32,
151    /// Trigger and popup corner radii.
152    pub radius: Radius,
153    /// Trigger horizontal padding in logical pixels.
154    pub padding_x: f32,
155    /// Trigger icon size in logical pixels.
156    pub icon_size: f32,
157    /// Disabled trigger fill alpha multiplier.
158    pub disabled_opacity: f32,
159}
160
161#[derive(Clone, Debug, PartialEq)]
162/// Calendar popup geometry layered on [`PickerBaseStyle`].
163///
164/// # Examples
165///
166/// ```
167/// use ailloli_ui_widgets::controls::DatePickerStyle;
168/// let style = DatePickerStyle::default();
169/// assert_eq!((style.popup_width, style.header_height, style.week_height, style.cell_height),
170///            (306.0, 36.0, 24.0, 34.0));
171/// ```
172pub struct DatePickerStyle {
173    /// Shared trigger and popup tokens.
174    pub base: PickerBaseStyle,
175    /// Calendar popup width in logical pixels.
176    pub popup_width: f32,
177    /// Month header height in logical pixels.
178    pub header_height: f32,
179    /// Weekday header height in logical pixels.
180    pub week_height: f32,
181    /// Six-row calendar cell height in logical pixels.
182    pub cell_height: f32,
183}
184
185#[derive(Clone, Debug, PartialEq)]
186/// Two-column time popup geometry layered on [`PickerBaseStyle`].
187///
188/// # Examples
189///
190/// ```
191/// use ailloli_ui_widgets::controls::TimePickerStyle;
192/// let style = TimePickerStyle::default();
193/// assert_eq!((style.popup_width, style.popup_height, style.row_height), (240.0, 220.0, 30.0));
194/// ```
195pub struct TimePickerStyle {
196    /// Shared trigger and popup tokens.
197    pub base: PickerBaseStyle,
198    /// Popup width in logical pixels.
199    pub popup_width: f32,
200    /// Popup height in logical pixels.
201    pub popup_height: f32,
202    /// Hour/minute row height in logical pixels.
203    pub row_height: f32,
204}
205
206#[derive(Clone, Debug, PartialEq)]
207/// HSV plane, hue rail, swatch, and hex popup geometry.
208///
209/// # Examples
210///
211/// ```
212/// use ailloli_ui_widgets::controls::ColorPickerStyle;
213/// let style = ColorPickerStyle::default();
214/// assert_eq!((style.popup_width, style.popup_height, style.swatch_size), (282.0, 318.0, 18.0));
215/// ```
216pub struct ColorPickerStyle {
217    /// Shared trigger and popup tokens.
218    pub base: PickerBaseStyle,
219    /// Popup width in logical pixels.
220    pub popup_width: f32,
221    /// Popup height in logical pixels.
222    pub popup_height: f32,
223    /// Palette swatch side length in logical pixels.
224    pub swatch_size: f32,
225}
226
227impl PickerBaseStyle {
228    /// Derives shared tokens from `theme` and the internal compact flag.
229    fn from_theme(theme: Theme, compact: bool) -> Self {
230        let palette = theme.palette();
231        let text_size = if compact { 12 } else { 13 };
232        Self {
233            trigger_background: palette.surface_elevated,
234            trigger_hovered: Color::hex_rgb(0x20252A),
235            popup_background: palette.surface_elevated,
236            active: Color::hex_rgb(0x20252A),
237            selected: palette.accent,
238            disabled_fill: palette.surface,
239            border: Border::new(1.0, palette.border),
240            popup_border: Border::new(1.0, palette.border),
241            focus_ring: Border::new(2.0, palette.focus),
242            shadows: vec![theme.shadows().md],
243            text: TextStyle::new(FontId::Ui, text_size, palette.text),
244            muted_text: TextStyle::new(FontId::Ui, text_size, palette.text_muted),
245            disabled_text: TextStyle::new(
246                FontId::Ui,
247                text_size,
248                palette.text_muted.with_alpha(0.6),
249            ),
250            accent_text: TextStyle::new(FontId::Ui, text_size, palette.accent),
251            width: if compact { 180.0 } else { 220.0 },
252            height: if compact { 30.0 } else { 36.0 },
253            popup_gap: 4.0,
254            radius: Radius::uniform(theme.radius().md),
255            padding_x: if compact { 10.0 } else { 12.0 },
256            icon_size: if compact { 14.0 } else { 16.0 },
257            disabled_opacity: 0.45,
258        }
259    }
260}
261
262impl Default for DatePickerStyle {
263    fn default() -> Self {
264        Self::from_theme(Theme::default(), DatePickerSize::Default)
265    }
266}
267
268impl DatePickerStyle {
269    /// Derives calendar style and geometry from `theme` and density.
270    ///
271    /// Compact uses popup width/cell height `270/30`; default uses `306/34`.
272    /// Header and weekday heights remain `36/24` logical pixels.
273    ///
274    /// # Examples
275    ///
276    /// ```
277    /// use ailloli_ui_core::Theme;
278    /// use ailloli_ui_widgets::controls::{DatePickerSize, DatePickerStyle};
279    /// let style = DatePickerStyle::from_theme(Theme::default(), DatePickerSize::Compact);
280    /// assert_eq!((style.base.width, style.base.height, style.popup_width), (180.0, 30.0, 270.0));
281    /// ```
282    pub fn from_theme(theme: Theme, size: DatePickerSize) -> Self {
283        let compact = size == DatePickerSize::Compact;
284        Self {
285            base: PickerBaseStyle::from_theme(theme, compact),
286            popup_width: if compact { 270.0 } else { 306.0 },
287            header_height: 36.0,
288            week_height: 24.0,
289            cell_height: if compact { 30.0 } else { 34.0 },
290        }
291    }
292}
293
294impl Default for TimePickerStyle {
295    fn default() -> Self {
296        Self::from_theme(Theme::default(), TimePickerSize::Default)
297    }
298}
299
300impl TimePickerStyle {
301    /// Derives time-list style and geometry from `theme` and density.
302    ///
303    /// Compact uses popup `210 x 188` and 26-pixel rows; default uses
304    /// `240 x 220` and 30-pixel rows.
305    ///
306    /// # Examples
307    ///
308    /// ```
309    /// use ailloli_ui_core::Theme;
310    /// use ailloli_ui_widgets::controls::{TimePickerSize, TimePickerStyle};
311    /// let style = TimePickerStyle::from_theme(Theme::default(), TimePickerSize::Compact);
312    /// assert_eq!((style.popup_width, style.popup_height, style.row_height), (210.0, 188.0, 26.0));
313    /// ```
314    pub fn from_theme(theme: Theme, size: TimePickerSize) -> Self {
315        let compact = size == TimePickerSize::Compact;
316        Self {
317            base: PickerBaseStyle::from_theme(theme, compact),
318            popup_width: if compact { 210.0 } else { 240.0 },
319            popup_height: if compact { 188.0 } else { 220.0 },
320            row_height: if compact { 26.0 } else { 30.0 },
321        }
322    }
323}
324
325impl Default for ColorPickerStyle {
326    fn default() -> Self {
327        Self::from_theme(Theme::default(), ColorPickerSize::Default)
328    }
329}
330
331impl ColorPickerStyle {
332    /// Derives color-picker style and geometry from `theme` and density.
333    ///
334    /// Compact uses popup `250 x 284` and 16-pixel swatches; default uses
335    /// `282 x 318` and 18-pixel swatches.
336    ///
337    /// # Examples
338    ///
339    /// ```
340    /// use ailloli_ui_core::Theme;
341    /// use ailloli_ui_widgets::controls::{ColorPickerSize, ColorPickerStyle};
342    /// let style = ColorPickerStyle::from_theme(Theme::default(), ColorPickerSize::Compact);
343    /// assert_eq!((style.popup_width, style.popup_height, style.swatch_size), (250.0, 284.0, 16.0));
344    /// ```
345    pub fn from_theme(theme: Theme, size: ColorPickerSize) -> Self {
346        let compact = size == ColorPickerSize::Compact;
347        Self {
348            base: PickerBaseStyle::from_theme(theme, compact),
349            popup_width: if compact { 250.0 } else { 282.0 },
350            popup_height: if compact { 284.0 } else { 318.0 },
351            swatch_size: if compact { 16.0 } else { 18.0 },
352        }
353    }
354}
355
356/// Controlled optional-date field with a six-week Monday-first calendar popup.
357///
358/// `A` is the application action returned by the non-context callback. Use
359/// [`Self::bind`] for internal writes; [`Self::value`] is read-only. Optional
360/// minimum and maximum dates are inclusive.
361///
362/// # Examples
363///
364/// ```
365/// use ailloli_ui_core::DateValue;
366/// use ailloli_ui_widgets::controls::DatePicker;
367/// let picker: DatePicker<()> = DatePicker::new().value(Some(DateValue::new(2026, 5, 1)));
368/// let _ = picker;
369/// ```
370pub struct DatePicker<A = ()> {
371    /// Trigger layout configured by generated builders.
372    pub(crate) layout: LayoutStyle,
373    /// Flex-parent participation configured by generated builders.
374    pub(crate) flex_item: FlexItemStyle,
375    /// Optional readable selected date.
376    value: Option<Binding<Option<DateValue>>>,
377    /// Optional writable selected-date signal.
378    bound: Option<Signal<Option<DateValue>>>,
379    /// Inclusive lower selection bound.
380    min: Option<DateValue>,
381    /// Inclusive upper selection bound.
382    max: Option<DateValue>,
383    /// Label shown when no date is selected.
384    placeholder: Binding<String>,
385    /// Whole-control disabled binding.
386    disabled: Binding<bool>,
387    /// Initial calendar month override.
388    default_month: Option<MonthValue>,
389    /// Initial popup visibility.
390    default_open: bool,
391    /// Trigger and calendar appearance.
392    style: DatePickerStyle,
393    /// Changed-date callback.
394    on_change: Option<DateChangeHandler<A>>,
395}
396
397crate::impl_layout_builders!(DatePicker);
398
399impl<A: 'static> Default for DatePicker<A> {
400    fn default() -> Self {
401        Self::new()
402    }
403}
404
405impl<A: 'static> DatePicker<A> {
406    /// Creates an enabled, unselected date picker with a closed popup.
407    ///
408    /// The placeholder is `Pick a date`. Without a default month or selected
409    /// value, the calendar starts at May 2026; this is a deterministic sentinel,
410    /// not the current system date.
411    ///
412    /// # Examples
413    ///
414    /// ```
415    /// use ailloli_ui_widgets::controls::DatePicker;
416    /// let picker: DatePicker<()> = DatePicker::new();
417    /// let _ = picker;
418    /// ```
419    pub fn new() -> Self {
420        Self {
421            layout: LayoutStyle::default(),
422            flex_item: FlexItemStyle::default(),
423            value: None,
424            bound: None,
425            min: None,
426            max: None,
427            placeholder: Binding::Static("Pick a date".to_string()),
428            disabled: Binding::Static(false),
429            default_month: None,
430            default_open: false,
431            style: DatePickerStyle::default(),
432            on_change: None,
433        }
434    }
435
436    /// Sets a read-only static or reactive optional date and clears writable binding.
437    ///
438    /// Selecting a different date may invoke the callback, but cannot update this
439    /// configured value.
440    ///
441    /// # Examples
442    ///
443    /// ```
444    /// use ailloli_ui_core::DateValue;
445    /// use ailloli_ui_widgets::controls::DatePicker;
446    /// let picker: DatePicker<()> = DatePicker::new().value(Some(DateValue::new(2026, 5, 9)));
447    /// let _ = picker;
448    /// ```
449    pub fn value(mut self, value: impl Into<Binding<Option<DateValue>>>) -> Self {
450        self.value = Some(value.into());
451        self.bound = None;
452        self
453    }
454
455    /// Binds a writable optional-date signal.
456    ///
457    /// Selecting a changed date writes `Some(date)` before invoking the callback;
458    /// the picker never emits or writes `None` itself.
459    ///
460    /// # Examples
461    ///
462    /// ```
463    /// use ailloli_ui_core::DateValue;
464    /// use ailloli_ui_runtime::component::State;
465    /// use ailloli_ui_widgets::controls::DatePicker;
466    /// let selected = State::new(None::<DateValue>);
467    /// let picker: DatePicker<()> = DatePicker::new().bind(selected);
468    /// let _ = picker;
469    /// ```
470    pub fn bind(mut self, value: impl Into<Signal<Option<DateValue>>>) -> Self {
471        let signal = value.into();
472        self.value = Some(Binding::Signal(signal.clone()));
473        self.bound = Some(signal);
474        self
475    }
476
477    /// Sets the inclusive earliest selectable date.
478    ///
479    /// If it exceeds `max`, no date satisfies both bounds.
480    ///
481    /// # Examples
482    ///
483    /// ```
484    /// use ailloli_ui_core::DateValue;
485    /// use ailloli_ui_widgets::controls::DatePicker;
486    /// let picker: DatePicker<()> = DatePicker::new().min(DateValue::new(2026, 1, 1));
487    /// let _ = picker;
488    /// ```
489    pub fn min(mut self, value: DateValue) -> Self {
490        self.min = Some(value);
491        self
492    }
493
494    /// Sets the inclusive latest selectable date.
495    ///
496    /// If it precedes `min`, no date satisfies both bounds.
497    ///
498    /// # Examples
499    ///
500    /// ```
501    /// use ailloli_ui_core::DateValue;
502    /// use ailloli_ui_widgets::controls::DatePicker;
503    /// let picker: DatePicker<()> = DatePicker::new().max(DateValue::new(2026, 12, 31));
504    /// let _ = picker;
505    /// ```
506    pub fn max(mut self, value: DateValue) -> Self {
507        self.max = Some(value);
508        self
509    }
510
511    /// Replaces the static or reactive no-selection label.
512    ///
513    /// # Examples
514    ///
515    /// ```
516    /// use ailloli_ui_widgets::controls::DatePicker;
517    /// let picker: DatePicker<()> = DatePicker::new().placeholder("Departure");
518    /// let _ = picker;
519    /// ```
520    pub fn placeholder(mut self, value: impl Into<Binding<String>>) -> Self {
521        self.placeholder = value.into();
522        self
523    }
524
525    /// Sets static or reactive disabled state.
526    ///
527    /// Disabled pickers are not focusable, ignore input, and do not paint or
528    /// expose popup hit bounds.
529    ///
530    /// # Examples
531    ///
532    /// ```
533    /// use ailloli_ui_widgets::controls::DatePicker;
534    /// let picker: DatePicker<()> = DatePicker::new().disabled(true);
535    /// let _ = picker;
536    /// ```
537    pub fn disabled(mut self, value: impl Into<Binding<bool>>) -> Self {
538        self.disabled = value.into();
539        self
540    }
541
542    /// Sets the initial displayed month, taking precedence over selected value.
543    ///
544    /// Month values created with `MonthValue::new` clamp month to `1..=12`.
545    ///
546    /// # Examples
547    ///
548    /// ```
549    /// use ailloli_ui_core::MonthValue;
550    /// use ailloli_ui_widgets::controls::DatePicker;
551    /// let picker: DatePicker<()> = DatePicker::new().default_month(MonthValue::new(2026, 5));
552    /// let _ = picker;
553    /// ```
554    pub fn default_month(mut self, value: MonthValue) -> Self {
555        self.default_month = Some(value);
556        self
557    }
558
559    /// Sets only the calendar popup's initial open state.
560    ///
561    /// # Examples
562    ///
563    /// ```
564    /// use ailloli_ui_widgets::controls::DatePicker;
565    /// let picker: DatePicker<()> = DatePicker::new().default_open(true);
566    /// let _ = picker;
567    /// ```
568    pub fn default_open(mut self, open: bool) -> Self {
569        self.default_open = open;
570        self
571    }
572
573    /// Replaces trigger and calendar style without altering explicit layout size.
574    ///
575    /// # Examples
576    ///
577    /// ```
578    /// use ailloli_ui_widgets::controls::{DatePicker, DatePickerStyle};
579    /// let picker: DatePicker<()> = DatePicker::new().date_style(DatePickerStyle::default());
580    /// let _ = picker;
581    /// ```
582    pub fn date_style(mut self, style: DatePickerStyle) -> Self {
583        self.style = style;
584        self
585    }
586
587    /// Re-derives style from the default theme and requested density.
588    ///
589    /// This overwrites every previous date-style customization.
590    ///
591    /// # Examples
592    ///
593    /// ```
594    /// use ailloli_ui_widgets::controls::{DatePicker, DatePickerSize};
595    /// let picker: DatePicker<()> = DatePicker::new().date_size(DatePickerSize::Compact);
596    /// let _ = picker;
597    /// ```
598    pub fn date_size(mut self, size: DatePickerSize) -> Self {
599        self.style = DatePickerStyle::from_theme(Theme::default(), size);
600        self
601    }
602
603    /// Dispatches the application action returned for a newly selected date.
604    ///
605    /// Equal selections and dates outside inclusive bounds emit nothing.
606    ///
607    /// # Examples
608    ///
609    /// ```
610    /// use ailloli_ui_core::DateValue;
611    /// use ailloli_ui_widgets::controls::DatePicker;
612    /// let picker: DatePicker<DateValue> = DatePicker::new().on_change(|date| date);
613    /// let _ = picker;
614    /// ```
615    pub fn on_change(mut self, f: impl Fn(DateValue) -> A + 'static) -> Self {
616        self.on_change = Some(Rc::new(move |ctx, next| ctx.dispatch(f(next))));
617        self
618    }
619
620    /// Handles a newly selected date with direct event-context access.
621    ///
622    /// # Examples
623    ///
624    /// ```
625    /// use ailloli_ui_widgets::controls::DatePicker;
626    /// let picker: DatePicker<()> = DatePicker::new().on_change_ctx(|_ctx, _date| {});
627    /// let _ = picker;
628    /// ```
629    pub fn on_change_ctx(mut self, f: impl Fn(&mut EventCtx<A>, DateValue) + 'static) -> Self {
630        self.on_change = Some(Rc::new(f));
631        self
632    }
633}
634
635/// Component that derives deterministic initial calendar navigation state.
636struct DatePickerComponent<A> {
637    /// Complete public picker configuration.
638    props: DatePicker<A>,
639}
640
641impl<A: 'static> ComponentNode<A> for DatePickerComponent<A> {
642    /// Allocates popup, visible-month, and active-date signals.
643    fn build(&self, context: &mut Context<A>) -> View<A> {
644        let selected = self.props.value.as_ref().and_then(Binding::read);
645        let month = self
646            .props
647            .default_month
648            .or_else(|| selected.map(DateValue::month_value))
649            .unwrap_or_else(|| MonthValue::new(2026, 5));
650        View::leaf(DatePickerWidget {
651            layout: self.props.layout,
652            value: self.props.value.clone(),
653            bound: self.props.bound.clone(),
654            min: self.props.min,
655            max: self.props.max,
656            placeholder: self.props.placeholder.clone(),
657            disabled: self.props.disabled.clone(),
658            style: self.props.style.clone(),
659            on_change: self.props.on_change.clone(),
660            open: context.signal(self.props.default_open),
661            month: context.signal(month),
662            active: context
663                .signal(selected.unwrap_or_else(|| DateValue::new(month.year, month.month, 1))),
664        })
665    }
666}
667
668impl<A: 'static> IntoView<A> for DatePicker<A> {
669    /// Converts configuration into a sized reactive component view.
670    fn into_view(self) -> View<A> {
671        let flex_item = self.flex_item;
672        let hint = LayoutSizeHint::from_layout(self.layout);
673        finish_view_sized(
674            View::component(DatePickerComponent { props: self }),
675            flex_item,
676            hint,
677        )
678    }
679}
680
681/// Retained date trigger and calendar overlay state machine.
682struct DatePickerWidget<A> {
683    /// Runtime trigger layout.
684    layout: LayoutStyle,
685    /// Readable optional date.
686    value: Option<Binding<Option<DateValue>>>,
687    /// Optional writable date signal.
688    bound: Option<Signal<Option<DateValue>>>,
689    /// Inclusive lower date bound.
690    min: Option<DateValue>,
691    /// Inclusive upper date bound.
692    max: Option<DateValue>,
693    /// No-selection label.
694    placeholder: Binding<String>,
695    /// Whole-control disabled binding.
696    disabled: Binding<bool>,
697    /// Trigger and calendar style.
698    style: DatePickerStyle,
699    /// Changed-date callback.
700    on_change: Option<DateChangeHandler<A>>,
701    /// Popup visibility.
702    open: Signal<bool>,
703    /// Currently displayed calendar month.
704    month: Signal<MonthValue>,
705    /// Keyboard-active calendar date.
706    active: Signal<DateValue>,
707}
708
709impl<A: 'static> Widget<A> for DatePickerWidget<A> {
710    /// Returns the stable diagnostic name.
711    fn debug_name(&self) -> &'static str {
712        "DatePicker"
713    }
714
715    /// Applies trigger constraints and publishes open popup hit bounds.
716    fn layout(
717        &self,
718        _engine: &mut ailloli_ui_runtime::layout::LayoutEngine<'_, A>,
719        _ctx: &mut LayoutCtx<'_>,
720        _children: &mut [LayoutChild],
721        constraints: Constraints,
722    ) -> LayoutResult {
723        let intrinsic = Size::new(self.style.base.width, self.style.base.height);
724        let size = apply_layout_size(intrinsic, self.layout, constraints);
725        let paint_bounds = Rect::new(0.0, 0.0, size.w, size.h);
726        let mut overlay_hit_bounds = Vec::new();
727        if self.open.read() && !self.disabled.read() {
728            overlay_hit_bounds.push(self.popup_rect_for(Rect::new(0.0, 0.0, size.w, size.h)));
729        }
730        LayoutResult {
731            size,
732            children: Vec::new(),
733            paint_bounds,
734            visual_bounds: paint_bounds,
735            overlay_hit_bounds,
736            clip: None,
737            is_window_root_clip: false,
738            artifact: None,
739        }
740    }
741
742    /// Paints the formatted date or configured placeholder trigger.
743    fn paint(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, _layout: &LayoutResult) {
744        let label = self.current_value().map(DateValue::format_yyyy_mm_dd);
745        paint_picker_trigger(
746            ctx,
747            bounds,
748            label.as_deref(),
749            &self.placeholder.read(),
750            IconId::Lucide(LucideIcon::Calendar),
751            self.disabled.read(),
752            &self.style.base,
753        );
754    }
755
756    /// Paints the calendar overlay only while open and enabled.
757    fn paint_overlay(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, _layout: &LayoutResult) {
758        if self.open.read() && !self.disabled.read() {
759            self.paint_popup(ctx, bounds);
760        }
761    }
762
763    /// Routes blur, trigger/calendar pointer releases, and keyboard navigation.
764    fn event(&self, ctx: &mut EventCtx<A>, event: &Event, bounds: Rect, _layout: &LayoutResult) {
765        if self.disabled.read() {
766            return;
767        }
768        match event {
769            Event::Focus(focus) if !focus.focused && self.open.read() => {
770                self.open.set(false);
771                ctx.request_repaint();
772            }
773            Event::Pointer(PointerEvent::Button {
774                pos,
775                button: MouseButton::Left,
776                pressed: false,
777                ..
778            }) if bounds.contains(pos.x, pos.y) => {
779                self.open.set(!self.open.read());
780                ctx.request_repaint();
781                ctx.stop_propagation();
782            }
783            Event::Pointer(PointerEvent::Button {
784                pos,
785                button: MouseButton::Left,
786                pressed: false,
787                ..
788            }) if self.open.read() && self.popup_rect_for(bounds).contains(pos.x, pos.y) => {
789                self.handle_popup_click(ctx, bounds, *pos);
790            }
791            Event::Keyboard(key) if key.state == KeyState::Pressed => {
792                self.handle_key(ctx, &key.key);
793            }
794            _ => {}
795        }
796    }
797
798    /// Makes only enabled pickers focusable.
799    fn focus_policy(&self) -> FocusPolicy {
800        if self.disabled.read() {
801            FocusPolicy::NotFocusable
802        } else {
803            FocusPolicy::Focusable
804        }
805    }
806}
807
808impl<A: 'static> DatePickerWidget<A> {
809    /// Reads the configured optional date or returns `None` when unconfigured.
810    fn current_value(&self) -> Option<DateValue> {
811        self.value.as_ref().and_then(Binding::read)
812    }
813
814    /// Computes calendar popup geometry immediately below the trigger.
815    fn popup_rect_for(&self, bounds: Rect) -> Rect {
816        Rect::new(
817            bounds.x,
818            bounds.bottom() + self.style.base.popup_gap,
819            self.style.popup_width,
820            self.style.header_height + self.style.week_height + self.style.cell_height * 6.0 + 16.0,
821        )
822    }
823
824    /// Commits an enabled date, closes, and synchronizes active month/date.
825    fn select(&self, ctx: &mut EventCtx<A>, value: DateValue) {
826        if !is_date_enabled(value, self.min, self.max) {
827            ctx.stop_propagation();
828            return;
829        }
830        let value = clamp_date(value, self.min, self.max);
831        if self.current_value() != Some(value) {
832            if let Some(bound) = &self.bound {
833                bound.set(Some(value));
834            }
835            if let Some(on_change) = &self.on_change {
836                on_change(ctx, value);
837            }
838        }
839        self.open.set(false);
840        self.active.set(value);
841        self.month.set(value.month_value());
842        ctx.request_repaint();
843        ctx.stop_propagation();
844    }
845
846    /// Opens on Enter/Space or routes calendar navigation and selection keys.
847    fn handle_key(&self, ctx: &mut EventCtx<A>, key: &Key) {
848        if !self.open.read() {
849            if matches!(
850                key,
851                Key::Named(NamedKey::Enter) | Key::Named(NamedKey::Space)
852            ) {
853                self.open.set(true);
854                ctx.request_repaint();
855                ctx.stop_propagation();
856            }
857            return;
858        }
859        match key {
860            Key::Named(NamedKey::Escape) => {
861                self.open.set(false);
862                ctx.request_repaint();
863                ctx.stop_propagation();
864            }
865            Key::Named(NamedKey::Enter) | Key::Named(NamedKey::Space) => {
866                self.select(ctx, self.active.read());
867            }
868            Key::Named(NamedKey::ArrowLeft) => self.move_active(ctx, -1),
869            Key::Named(NamedKey::ArrowRight) => self.move_active(ctx, 1),
870            Key::Named(NamedKey::ArrowUp) => self.move_active(ctx, -7),
871            Key::Named(NamedKey::ArrowDown) => self.move_active(ctx, 7),
872            Key::Named(NamedKey::Home) => {
873                let m = self.month.read();
874                self.set_active(ctx, DateValue::new(m.year, m.month, 1));
875            }
876            Key::Named(NamedKey::End) => {
877                let m = self.month.read();
878                self.set_active(
879                    ctx,
880                    DateValue::new(
881                        m.year,
882                        m.month,
883                        ailloli_ui_core::date_picker::days_in_month(m.year, m.month),
884                    ),
885                );
886            }
887            _ => {}
888        }
889    }
890
891    /// Moves the active date by signed calendar days.
892    fn move_active(&self, ctx: &mut EventCtx<A>, delta: i32) {
893        self.set_active(ctx, next_day(self.active.read(), delta));
894    }
895
896    /// Sets active date, switches its displayed month, and consumes the event.
897    fn set_active(&self, ctx: &mut EventCtx<A>, value: DateValue) {
898        self.active.set(value);
899        self.month.set(value.month_value());
900        ctx.request_repaint();
901        ctx.stop_propagation();
902    }
903
904    /// Handles previous/next month controls or a calendar cell release.
905    fn handle_popup_click(&self, ctx: &mut EventCtx<A>, bounds: Rect, pos: Point) {
906        let popup = self.popup_rect_for(bounds);
907        let prev = Rect::new(popup.x + 10.0, popup.y + 8.0, 28.0, 24.0);
908        let next = Rect::new(popup.right() - 38.0, popup.y + 8.0, 28.0, 24.0);
909        if prev.contains(pos.x, pos.y) {
910            self.month.set(add_months(self.month.read(), -1));
911            ctx.request_repaint();
912            ctx.stop_propagation();
913            return;
914        }
915        if next.contains(pos.x, pos.y) {
916            self.month.set(add_months(self.month.read(), 1));
917            ctx.request_repaint();
918            ctx.stop_propagation();
919            return;
920        }
921        if let Some(date) = self.date_at(popup, pos) {
922            self.select(ctx, date);
923        } else {
924            ctx.stop_propagation();
925        }
926    }
927
928    /// Maps a point in the six-by-seven grid to its calendar date.
929    fn date_at(&self, popup: Rect, pos: Point) -> Option<DateValue> {
930        let top = popup.y + self.style.header_height + self.style.week_height;
931        if pos.y < top {
932            return None;
933        }
934        let cell_w = popup.w / 7.0;
935        let col = ((pos.x - popup.x) / cell_w).floor() as usize;
936        let row = ((pos.y - top) / self.style.cell_height).floor() as usize;
937        if col >= 7 || row >= 6 {
938            return None;
939        }
940        Some(month_grid(self.month.read(), WeekStart::Monday)[row * 7 + col].date)
941    }
942
943    /// Paints month controls, weekdays, and the fixed 42-cell calendar grid.
944    fn paint_popup(&self, ctx: &mut PaintCtx<'_>, bounds: Rect) {
945        let popup = self.popup_rect_for(bounds);
946        paint_popup_shell(ctx, popup, &self.style.base);
947        let month = self.month.read();
948        push_overlay_text(
949            ctx,
950            &format!("{} {:04}", month_name(month.month), month.year),
951            popup.x + 48.0,
952            popup.y + 25.0,
953            self.style.base.text,
954        );
955        paint_icon_button(
956            ctx,
957            Rect::new(popup.x + 10.0, popup.y + 8.0, 28.0, 24.0),
958            IconId::Lucide(LucideIcon::ChevronLeft),
959            &self.style.base,
960        );
961        paint_icon_button(
962            ctx,
963            Rect::new(popup.right() - 38.0, popup.y + 8.0, 28.0, 24.0),
964            IconId::Lucide(LucideIcon::ChevronRight),
965            &self.style.base,
966        );
967
968        let weekdays = ["Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"];
969        let cell_w = popup.w / 7.0;
970        let week_y = popup.y + self.style.header_height + 17.0;
971        for (idx, label) in weekdays.iter().enumerate() {
972            push_overlay_text(
973                ctx,
974                label,
975                popup.x + idx as f32 * cell_w + 12.0,
976                week_y,
977                self.style.base.muted_text,
978            );
979        }
980
981        let grid = month_grid(month, WeekStart::Monday);
982        let selected = self.current_value();
983        let active = self.active.read();
984        let top = popup.y + self.style.header_height + self.style.week_height;
985        for row in 0..6 {
986            for col in 0..7 {
987                let day = grid[row * 7 + col];
988                let rect = Rect::new(
989                    popup.x + col as f32 * cell_w + 4.0,
990                    top + row as f32 * self.style.cell_height + 3.0,
991                    cell_w - 8.0,
992                    self.style.cell_height - 6.0,
993                );
994                let enabled = day.in_month && is_date_enabled(day.date, self.min, self.max);
995                let is_selected = selected == Some(day.date);
996                let is_active = active == day.date;
997                if is_selected {
998                    ctx.push_overlay(DrawCmd::RRect(DrawRRect {
999                        rect,
1000                        radius: 7.0,
1001                        color: self.style.base.selected,
1002                    }));
1003                } else if is_active {
1004                    ctx.push_overlay(DrawCmd::RRect(DrawRRect {
1005                        rect,
1006                        radius: 7.0,
1007                        color: self.style.base.active,
1008                    }));
1009                }
1010                let style = if !enabled {
1011                    self.style.base.disabled_text
1012                } else if is_selected {
1013                    TextStyle {
1014                        color: Color::WHITE,
1015                        ..self.style.base.text
1016                    }
1017                } else if !day.in_month {
1018                    self.style.base.muted_text
1019                } else {
1020                    self.style.base.text
1021                };
1022                push_overlay_text(
1023                    ctx,
1024                    &day.date.day.to_string(),
1025                    rect.x + 10.0,
1026                    rect.y + 20.0,
1027                    style,
1028                );
1029            }
1030        }
1031    }
1032}
1033
1034/// Controlled optional-time field with hour and stepped-minute popup columns.
1035///
1036/// `A` is the application action returned by the non-context callback. Use
1037/// [`Self::bind`] for internal writes; [`Self::value`] is read-only. Committed
1038/// times are rounded to the nearest configured step and clamped within the day.
1039///
1040/// # Examples
1041///
1042/// ```
1043/// use ailloli_ui_core::TimeValue;
1044/// use ailloli_ui_widgets::controls::TimePicker;
1045/// let picker: TimePicker<()> = TimePicker::new().value(Some(TimeValue::new(14, 30)));
1046/// let _ = picker;
1047/// ```
1048pub struct TimePicker<A = ()> {
1049    /// Trigger layout configured by generated builders.
1050    pub(crate) layout: LayoutStyle,
1051    /// Flex-parent participation configured by generated builders.
1052    pub(crate) flex_item: FlexItemStyle,
1053    /// Optional readable selected time.
1054    value: Option<Binding<Option<TimeValue>>>,
1055    /// Optional writable selected-time signal.
1056    bound: Option<Signal<Option<TimeValue>>>,
1057    /// Label shown when no time is selected.
1058    placeholder: Binding<String>,
1059    /// Whole-control disabled binding.
1060    disabled: Binding<bool>,
1061    /// Sanitized minute increment in `1..=60`.
1062    step_minutes: u8,
1063    /// Trigger text format.
1064    format: TimeFormat,
1065    /// Initial popup visibility.
1066    default_open: bool,
1067    /// Trigger and time-list appearance.
1068    style: TimePickerStyle,
1069    /// Changed-time callback.
1070    on_change: Option<TimeChangeHandler<A>>,
1071}
1072
1073crate::impl_layout_builders!(TimePicker);
1074
1075impl<A: 'static> Default for TimePicker<A> {
1076    fn default() -> Self {
1077        Self::new()
1078    }
1079}
1080
1081impl<A: 'static> TimePicker<A> {
1082    /// Creates an enabled, unselected time picker with a closed popup.
1083    ///
1084    /// Defaults are placeholder `Pick a time`, five-minute increments, 24-hour
1085    /// formatting, and noon as the initial keyboard-active sentinel.
1086    ///
1087    /// # Examples
1088    ///
1089    /// ```
1090    /// use ailloli_ui_widgets::controls::TimePicker;
1091    /// let picker: TimePicker<()> = TimePicker::new();
1092    /// let _ = picker;
1093    /// ```
1094    pub fn new() -> Self {
1095        Self {
1096            layout: LayoutStyle::default(),
1097            flex_item: FlexItemStyle::default(),
1098            value: None,
1099            bound: None,
1100            placeholder: Binding::Static("Pick a time".to_string()),
1101            disabled: Binding::Static(false),
1102            step_minutes: 5,
1103            format: TimeFormat::Hour24,
1104            default_open: false,
1105            style: TimePickerStyle::default(),
1106            on_change: None,
1107        }
1108    }
1109
1110    /// Sets a read-only static or reactive optional time and clears writable binding.
1111    ///
1112    /// Selecting a different time may invoke the callback but cannot mutate this
1113    /// configured value.
1114    ///
1115    /// # Examples
1116    ///
1117    /// ```
1118    /// use ailloli_ui_core::TimeValue;
1119    /// use ailloli_ui_widgets::controls::TimePicker;
1120    /// let picker: TimePicker<()> = TimePicker::new().value(Some(TimeValue::new(9, 30)));
1121    /// let _ = picker;
1122    /// ```
1123    pub fn value(mut self, value: impl Into<Binding<Option<TimeValue>>>) -> Self {
1124        self.value = Some(value.into());
1125        self.bound = None;
1126        self
1127    }
1128
1129    /// Binds a writable optional-time signal.
1130    ///
1131    /// Committing a changed time writes `Some(time)` before invoking the callback;
1132    /// the picker never emits or writes `None` itself.
1133    ///
1134    /// # Examples
1135    ///
1136    /// ```
1137    /// use ailloli_ui_core::TimeValue;
1138    /// use ailloli_ui_runtime::component::State;
1139    /// use ailloli_ui_widgets::controls::TimePicker;
1140    /// let selected = State::new(None::<TimeValue>);
1141    /// let picker: TimePicker<()> = TimePicker::new().bind(selected);
1142    /// let _ = picker;
1143    /// ```
1144    pub fn bind(mut self, value: impl Into<Signal<Option<TimeValue>>>) -> Self {
1145        let signal = value.into();
1146        self.value = Some(Binding::Signal(signal.clone()));
1147        self.bound = Some(signal);
1148        self
1149    }
1150
1151    /// Replaces the static or reactive no-selection label.
1152    ///
1153    /// # Examples
1154    ///
1155    /// ```
1156    /// use ailloli_ui_widgets::controls::TimePicker;
1157    /// let picker: TimePicker<()> = TimePicker::new().placeholder("Start time");
1158    /// let _ = picker;
1159    /// ```
1160    pub fn placeholder(mut self, value: impl Into<Binding<String>>) -> Self {
1161        self.placeholder = value.into();
1162        self
1163    }
1164
1165    /// Sets static or reactive disabled state.
1166    ///
1167    /// Disabled pickers are not focusable, ignore input, and do not paint or
1168    /// expose popup hit bounds.
1169    ///
1170    /// # Examples
1171    ///
1172    /// ```
1173    /// use ailloli_ui_widgets::controls::TimePicker;
1174    /// let picker: TimePicker<()> = TimePicker::new().disabled(true);
1175    /// let _ = picker;
1176    /// ```
1177    pub fn disabled(mut self, value: impl Into<Binding<bool>>) -> Self {
1178        self.disabled = value.into();
1179        self
1180    }
1181
1182    /// Sets the minute increment after clamping it to `1..=60`.
1183    ///
1184    /// Committing rounds to the nearest step with half-step ties upward and
1185    /// clamps at `23:59` rather than wrapping to the next day.
1186    ///
1187    /// # Examples
1188    ///
1189    /// ```
1190    /// use ailloli_ui_widgets::controls::TimePicker;
1191    /// let picker: TimePicker<()> = TimePicker::new().step_minutes(15);
1192    /// let clamped: TimePicker<()> = TimePicker::new().step_minutes(0);
1193    /// let _ = (picker, clamped);
1194    /// ```
1195    pub fn step_minutes(mut self, value: u8) -> Self {
1196        self.step_minutes = sanitize_step_minutes(value);
1197        self
1198    }
1199
1200    /// Sets the selected value's trigger text format.
1201    ///
1202    /// This does not change the popup's numeric 24-hour column values.
1203    ///
1204    /// # Examples
1205    ///
1206    /// ```
1207    /// use ailloli_ui_core::TimeFormat;
1208    /// use ailloli_ui_widgets::controls::TimePicker;
1209    /// let picker: TimePicker<()> = TimePicker::new().format(TimeFormat::Hour12);
1210    /// let _ = picker;
1211    /// ```
1212    pub fn format(mut self, value: TimeFormat) -> Self {
1213        self.format = value;
1214        self
1215    }
1216
1217    /// Sets only the time popup's initial open state.
1218    ///
1219    /// # Examples
1220    ///
1221    /// ```
1222    /// use ailloli_ui_widgets::controls::TimePicker;
1223    /// let picker: TimePicker<()> = TimePicker::new().default_open(true);
1224    /// let _ = picker;
1225    /// ```
1226    pub fn default_open(mut self, open: bool) -> Self {
1227        self.default_open = open;
1228        self
1229    }
1230
1231    /// Replaces trigger and popup style without altering explicit layout size.
1232    ///
1233    /// # Examples
1234    ///
1235    /// ```
1236    /// use ailloli_ui_widgets::controls::{TimePicker, TimePickerStyle};
1237    /// let picker: TimePicker<()> = TimePicker::new().time_style(TimePickerStyle::default());
1238    /// let _ = picker;
1239    /// ```
1240    pub fn time_style(mut self, style: TimePickerStyle) -> Self {
1241        self.style = style;
1242        self
1243    }
1244
1245    /// Re-derives style from the default theme and requested density.
1246    ///
1247    /// This overwrites every previous time-style customization.
1248    ///
1249    /// # Examples
1250    ///
1251    /// ```
1252    /// use ailloli_ui_widgets::controls::{TimePicker, TimePickerSize};
1253    /// let picker: TimePicker<()> = TimePicker::new().time_size(TimePickerSize::Compact);
1254    /// let _ = picker;
1255    /// ```
1256    pub fn time_size(mut self, size: TimePickerSize) -> Self {
1257        self.style = TimePickerStyle::from_theme(Theme::default(), size);
1258        self
1259    }
1260
1261    /// Dispatches the application action returned for a newly committed time.
1262    ///
1263    /// Reselecting an equal snapped value emits nothing.
1264    ///
1265    /// # Examples
1266    ///
1267    /// ```
1268    /// use ailloli_ui_core::TimeValue;
1269    /// use ailloli_ui_widgets::controls::TimePicker;
1270    /// let picker: TimePicker<TimeValue> = TimePicker::new().on_change(|time| time);
1271    /// let _ = picker;
1272    /// ```
1273    pub fn on_change(mut self, f: impl Fn(TimeValue) -> A + 'static) -> Self {
1274        self.on_change = Some(Rc::new(move |ctx, next| ctx.dispatch(f(next))));
1275        self
1276    }
1277
1278    /// Handles a newly committed time with direct event-context access.
1279    ///
1280    /// # Examples
1281    ///
1282    /// ```
1283    /// use ailloli_ui_widgets::controls::TimePicker;
1284    /// let picker: TimePicker<()> = TimePicker::new().on_change_ctx(|_ctx, _time| {});
1285    /// let _ = picker;
1286    /// ```
1287    pub fn on_change_ctx(mut self, f: impl Fn(&mut EventCtx<A>, TimeValue) + 'static) -> Self {
1288        self.on_change = Some(Rc::new(f));
1289        self
1290    }
1291}
1292
1293/// Component that derives deterministic initial time navigation state.
1294struct TimePickerComponent<A> {
1295    /// Complete public picker configuration.
1296    props: TimePicker<A>,
1297}
1298
1299impl<A: 'static> ComponentNode<A> for TimePickerComponent<A> {
1300    /// Allocates popup, active-time, and active-column signals.
1301    fn build(&self, context: &mut Context<A>) -> View<A> {
1302        let current = self
1303            .props
1304            .value
1305            .as_ref()
1306            .and_then(Binding::read)
1307            .unwrap_or_else(|| TimeValue::new(12, 0));
1308        View::leaf(TimePickerWidget {
1309            layout: self.props.layout,
1310            value: self.props.value.clone(),
1311            bound: self.props.bound.clone(),
1312            placeholder: self.props.placeholder.clone(),
1313            disabled: self.props.disabled.clone(),
1314            step_minutes: self.props.step_minutes,
1315            format: self.props.format,
1316            style: self.props.style.clone(),
1317            on_change: self.props.on_change.clone(),
1318            open: context.signal(self.props.default_open),
1319            active: context.signal(current),
1320            active_column: context.signal(TimeColumn::Hour),
1321        })
1322    }
1323}
1324
1325impl<A: 'static> IntoView<A> for TimePicker<A> {
1326    /// Converts configuration into a sized reactive component view.
1327    fn into_view(self) -> View<A> {
1328        let flex_item = self.flex_item;
1329        let hint = LayoutSizeHint::from_layout(self.layout);
1330        finish_view_sized(
1331            View::component(TimePickerComponent { props: self }),
1332            flex_item,
1333            hint,
1334        )
1335    }
1336}
1337
1338#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1339/// Keyboard-active half of the two-column time list.
1340enum TimeColumn {
1341    /// Hour values `0..=23`.
1342    Hour,
1343    /// Sanitized stepped minute values below 60.
1344    Minute,
1345}
1346
1347/// Retained time trigger and two-column overlay state machine.
1348struct TimePickerWidget<A> {
1349    /// Runtime trigger layout.
1350    layout: LayoutStyle,
1351    /// Readable optional time.
1352    value: Option<Binding<Option<TimeValue>>>,
1353    /// Optional writable time signal.
1354    bound: Option<Signal<Option<TimeValue>>>,
1355    /// No-selection label.
1356    placeholder: Binding<String>,
1357    /// Whole-control disabled binding.
1358    disabled: Binding<bool>,
1359    /// Sanitized minute increment.
1360    step_minutes: u8,
1361    /// Trigger display format.
1362    format: TimeFormat,
1363    /// Trigger and time-list style.
1364    style: TimePickerStyle,
1365    /// Changed-time callback.
1366    on_change: Option<TimeChangeHandler<A>>,
1367    /// Popup visibility.
1368    open: Signal<bool>,
1369    /// Keyboard-active time.
1370    active: Signal<TimeValue>,
1371    /// Keyboard-active hour or minute column.
1372    active_column: Signal<TimeColumn>,
1373}
1374
1375impl<A: 'static> Widget<A> for TimePickerWidget<A> {
1376    /// Returns the stable diagnostic name.
1377    fn debug_name(&self) -> &'static str {
1378        "TimePicker"
1379    }
1380
1381    /// Applies trigger constraints and publishes open popup hit bounds.
1382    fn layout(
1383        &self,
1384        _engine: &mut ailloli_ui_runtime::layout::LayoutEngine<'_, A>,
1385        _ctx: &mut LayoutCtx<'_>,
1386        _children: &mut [LayoutChild],
1387        constraints: Constraints,
1388    ) -> LayoutResult {
1389        let size = apply_layout_size(
1390            Size::new(self.style.base.width, self.style.base.height),
1391            self.layout,
1392            constraints,
1393        );
1394        let paint_bounds = Rect::new(0.0, 0.0, size.w, size.h);
1395        let overlay_hit_bounds = if self.open.read() && !self.disabled.read() {
1396            vec![self.popup_rect_for(Rect::new(0.0, 0.0, size.w, size.h))]
1397        } else {
1398            Vec::new()
1399        };
1400        LayoutResult {
1401            size,
1402            children: Vec::new(),
1403            paint_bounds,
1404            visual_bounds: paint_bounds,
1405            overlay_hit_bounds,
1406            clip: None,
1407            is_window_root_clip: false,
1408            artifact: None,
1409        }
1410    }
1411
1412    /// Paints the formatted time or configured placeholder trigger.
1413    fn paint(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, _layout: &LayoutResult) {
1414        let label = self.current_value().map(|time| time.format(self.format));
1415        paint_picker_trigger(
1416            ctx,
1417            bounds,
1418            label.as_deref(),
1419            &self.placeholder.read(),
1420            IconId::Lucide(LucideIcon::Clock),
1421            self.disabled.read(),
1422            &self.style.base,
1423        );
1424    }
1425
1426    /// Paints the time overlay only while open and enabled.
1427    fn paint_overlay(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, _layout: &LayoutResult) {
1428        if self.open.read() && !self.disabled.read() {
1429            self.paint_popup(ctx, bounds);
1430        }
1431    }
1432
1433    /// Routes blur, trigger/list pointer releases, and keyboard navigation.
1434    fn event(&self, ctx: &mut EventCtx<A>, event: &Event, bounds: Rect, _layout: &LayoutResult) {
1435        if self.disabled.read() {
1436            return;
1437        }
1438        match event {
1439            Event::Focus(focus) if !focus.focused && self.open.read() => {
1440                self.open.set(false);
1441                ctx.request_repaint();
1442            }
1443            Event::Pointer(PointerEvent::Button {
1444                pos,
1445                button: MouseButton::Left,
1446                pressed: false,
1447                ..
1448            }) if bounds.contains(pos.x, pos.y) => {
1449                self.open.set(!self.open.read());
1450                ctx.request_repaint();
1451                ctx.stop_propagation();
1452            }
1453            Event::Pointer(PointerEvent::Button {
1454                pos,
1455                button: MouseButton::Left,
1456                pressed: false,
1457                ..
1458            }) if self.open.read() && self.popup_rect_for(bounds).contains(pos.x, pos.y) => {
1459                self.handle_popup_click(ctx, bounds, *pos);
1460            }
1461            Event::Keyboard(key) if key.state == KeyState::Pressed => {
1462                self.handle_key(ctx, &key.key)
1463            }
1464            _ => {}
1465        }
1466    }
1467
1468    /// Makes only enabled pickers focusable.
1469    fn focus_policy(&self) -> FocusPolicy {
1470        if self.disabled.read() {
1471            FocusPolicy::NotFocusable
1472        } else {
1473            FocusPolicy::Focusable
1474        }
1475    }
1476}
1477
1478impl<A: 'static> TimePickerWidget<A> {
1479    /// Reads the configured optional time or returns `None` when unconfigured.
1480    fn current_value(&self) -> Option<TimeValue> {
1481        self.value.as_ref().and_then(Binding::read)
1482    }
1483
1484    /// Computes time popup geometry immediately below the trigger.
1485    fn popup_rect_for(&self, bounds: Rect) -> Rect {
1486        Rect::new(
1487            bounds.x,
1488            bounds.bottom() + self.style.base.popup_gap,
1489            self.style.popup_width,
1490            self.style.popup_height,
1491        )
1492    }
1493
1494    /// Snaps and commits a changed time, then closes the popup.
1495    fn commit(&self, ctx: &mut EventCtx<A>, value: TimeValue) {
1496        let value = snap_time(value, self.step_minutes);
1497        if self.current_value() != Some(value) {
1498            if let Some(bound) = &self.bound {
1499                bound.set(Some(value));
1500            }
1501            if let Some(on_change) = &self.on_change {
1502                on_change(ctx, value);
1503            }
1504        }
1505        self.active.set(value);
1506        self.open.set(false);
1507        ctx.request_repaint();
1508        ctx.stop_propagation();
1509    }
1510
1511    /// Opens on Enter/Space or routes column, value, and commit keys.
1512    fn handle_key(&self, ctx: &mut EventCtx<A>, key: &Key) {
1513        if !self.open.read() {
1514            if matches!(
1515                key,
1516                Key::Named(NamedKey::Enter) | Key::Named(NamedKey::Space)
1517            ) {
1518                self.open.set(true);
1519                ctx.request_repaint();
1520                ctx.stop_propagation();
1521            }
1522            return;
1523        }
1524        match key {
1525            Key::Named(NamedKey::Escape) => {
1526                self.open.set(false);
1527                ctx.request_repaint();
1528                ctx.stop_propagation();
1529            }
1530            Key::Named(NamedKey::Enter) | Key::Named(NamedKey::Space) => {
1531                self.commit(ctx, self.active.read())
1532            }
1533            Key::Named(NamedKey::ArrowLeft) | Key::Named(NamedKey::ArrowRight) => {
1534                self.active_column
1535                    .set(if self.active_column.read() == TimeColumn::Hour {
1536                        TimeColumn::Minute
1537                    } else {
1538                        TimeColumn::Hour
1539                    });
1540                ctx.request_repaint();
1541                ctx.stop_propagation();
1542            }
1543            Key::Named(NamedKey::ArrowUp) => self.nudge_active(ctx, -1),
1544            Key::Named(NamedKey::ArrowDown) => self.nudge_active(ctx, 1),
1545            Key::Named(NamedKey::Home) => self.set_active_part(ctx, 0),
1546            Key::Named(NamedKey::End) => self.set_active_part(
1547                ctx,
1548                if self.active_column.read() == TimeColumn::Hour {
1549                    23
1550                } else {
1551                    59
1552                },
1553            ),
1554            _ => {}
1555        }
1556    }
1557
1558    /// Nudges one hour or one configured minute step without day wrapping.
1559    fn nudge_active(&self, ctx: &mut EventCtx<A>, delta: i16) {
1560        let current = self.active.read();
1561        let next = if self.active_column.read() == TimeColumn::Hour {
1562            nudge_time(current, delta * 60, self.step_minutes)
1563        } else {
1564            nudge_time(current, delta * self.step_minutes as i16, self.step_minutes)
1565        };
1566        self.active.set(next);
1567        ctx.request_repaint();
1568        ctx.stop_propagation();
1569    }
1570
1571    /// Sets and clamps the active column component, snapping minutes.
1572    fn set_active_part(&self, ctx: &mut EventCtx<A>, value: u8) {
1573        let current = self.active.read();
1574        let next = if self.active_column.read() == TimeColumn::Hour {
1575            TimeValue::new(value.min(23), current.minute)
1576        } else {
1577            TimeValue::new(
1578                current.hour,
1579                snap_time(TimeValue::new(0, value.min(59)), self.step_minutes).minute,
1580            )
1581        };
1582        self.active.set(next);
1583        ctx.request_repaint();
1584        ctx.stop_propagation();
1585    }
1586
1587    /// Maps a visible row in either column to a time and commits it.
1588    fn handle_popup_click(&self, ctx: &mut EventCtx<A>, bounds: Rect, pos: Point) {
1589        let popup = self.popup_rect_for(bounds);
1590        let col_w = popup.w / 2.0;
1591        let list_top = popup.y + 10.0;
1592        let visible = (popup.h / self.style.row_height).floor().max(1.0) as usize;
1593        let active = self.active.read();
1594        let hour_start = visible_start(active.hour as usize, 24, visible);
1595        let minutes = minute_values(self.step_minutes);
1596        let minute_index = minutes
1597            .iter()
1598            .position(|m| *m == snap_time(active, self.step_minutes).minute)
1599            .unwrap_or(0);
1600        let minute_start = visible_start(minute_index, minutes.len(), visible);
1601        let row = ((pos.y - list_top) / self.style.row_height).floor() as usize;
1602        if row >= visible {
1603            ctx.stop_propagation();
1604            return;
1605        }
1606        if pos.x < popup.x + col_w {
1607            let hour = (hour_start + row).min(23) as u8;
1608            self.active.set(TimeValue::new(hour, active.minute));
1609            self.active_column.set(TimeColumn::Hour);
1610        } else if let Some(minute) = minutes.get(minute_start + row).copied() {
1611            self.active.set(TimeValue::new(active.hour, minute));
1612            self.active_column.set(TimeColumn::Minute);
1613        }
1614        self.commit(ctx, self.active.read());
1615    }
1616
1617    /// Paints centered windows of hour and stepped-minute rows.
1618    fn paint_popup(&self, ctx: &mut PaintCtx<'_>, bounds: Rect) {
1619        let popup = self.popup_rect_for(bounds);
1620        paint_popup_shell(ctx, popup, &self.style.base);
1621        let col_w = popup.w / 2.0;
1622        let list_top = popup.y + 10.0;
1623        let visible = (popup.h / self.style.row_height).floor().max(1.0) as usize;
1624        let active = self.active.read();
1625        let selected = self.current_value();
1626        let hour_start = visible_start(active.hour as usize, 24, visible);
1627        let minutes = minute_values(self.step_minutes);
1628        let minute_index = minutes
1629            .iter()
1630            .position(|m| *m == snap_time(active, self.step_minutes).minute)
1631            .unwrap_or(0);
1632        let minute_start = visible_start(minute_index, minutes.len(), visible);
1633        for row in 0..visible {
1634            let y = list_top + row as f32 * self.style.row_height;
1635            if let Some(hour) = (hour_start + row < 24).then_some((hour_start + row) as u8) {
1636                self.paint_time_row(
1637                    ctx,
1638                    Rect::new(popup.x + 8.0, y, col_w - 12.0, self.style.row_height - 3.0),
1639                    &format!("{hour:02}"),
1640                    active.hour == hour,
1641                    selected.is_some_and(|v| v.hour == hour),
1642                    self.active_column.read() == TimeColumn::Hour,
1643                );
1644            }
1645            if let Some(minute) = minutes.get(minute_start + row).copied() {
1646                self.paint_time_row(
1647                    ctx,
1648                    Rect::new(
1649                        popup.x + col_w + 4.0,
1650                        y,
1651                        col_w - 12.0,
1652                        self.style.row_height - 3.0,
1653                    ),
1654                    &format!("{minute:02}"),
1655                    active.minute == minute,
1656                    selected.is_some_and(|v| v.minute == minute),
1657                    self.active_column.read() == TimeColumn::Minute,
1658                );
1659            }
1660        }
1661    }
1662
1663    /// Paints one selected, active, or resting time row.
1664    fn paint_time_row(
1665        &self,
1666        ctx: &mut PaintCtx<'_>,
1667        rect: Rect,
1668        label: &str,
1669        active: bool,
1670        selected: bool,
1671        column_active: bool,
1672    ) {
1673        if selected {
1674            ctx.push_overlay(DrawCmd::RRect(DrawRRect {
1675                rect,
1676                radius: 7.0,
1677                color: self.style.base.selected,
1678            }));
1679        } else if active && column_active {
1680            ctx.push_overlay(DrawCmd::RRect(DrawRRect {
1681                rect,
1682                radius: 7.0,
1683                color: self.style.base.active,
1684            }));
1685        }
1686        let style = if selected {
1687            TextStyle {
1688                color: Color::WHITE,
1689                ..self.style.base.text
1690            }
1691        } else {
1692            self.style.base.text
1693        };
1694        push_overlay_text(ctx, label, rect.x + 14.0, rect.y + 20.0, style);
1695    }
1696}
1697
1698/// Controlled RGB color field with HSV controls, palette swatches, and hex input.
1699///
1700/// `A` is the application action returned by the non-context callback. Use
1701/// [`Self::bind`] for internal writes; [`Self::value`] is read-only. HSV and
1702/// parsed hex commits are opaque, while a supplied swatch is committed unchanged.
1703///
1704/// # Examples
1705///
1706/// ```
1707/// use ailloli_ui_core::Color;
1708/// use ailloli_ui_widgets::controls::ColorPicker;
1709/// let picker: ColorPicker<()> = ColorPicker::new().value(Color::hex_rgb(0xFF5A00));
1710/// let _ = picker;
1711/// ```
1712pub struct ColorPicker<A = ()> {
1713    /// Trigger layout configured by generated builders.
1714    pub(crate) layout: LayoutStyle,
1715    /// Flex-parent participation configured by generated builders.
1716    pub(crate) flex_item: FlexItemStyle,
1717    /// Readable current color.
1718    value: Binding<Color>,
1719    /// Optional writable color signal.
1720    bound: Option<Signal<Color>>,
1721    /// Whole-control disabled binding.
1722    disabled: Binding<bool>,
1723    /// Whether the popup exposes editable hexadecimal RGB text.
1724    hex_input: bool,
1725    /// Initial popup visibility.
1726    default_open: bool,
1727    /// Trigger and popup appearance.
1728    style: ColorPickerStyle,
1729    /// Palette swatches in display order.
1730    swatches: Vec<Color>,
1731    /// Changed-color callback.
1732    on_change: Option<ColorChangeHandler<A>>,
1733}
1734
1735crate::impl_layout_builders!(ColorPicker);
1736
1737impl<A: 'static> Default for ColorPicker<A> {
1738    fn default() -> Self {
1739        Self::new()
1740    }
1741}
1742
1743impl<A: 'static> ColorPicker<A> {
1744    /// Creates an enabled color picker initialized from the default accent color.
1745    ///
1746    /// Hex input is enabled, the popup starts closed, and no palette swatches or
1747    /// callback are installed.
1748    ///
1749    /// # Examples
1750    ///
1751    /// ```
1752    /// use ailloli_ui_widgets::controls::ColorPicker;
1753    /// let picker: ColorPicker<()> = ColorPicker::new();
1754    /// let _ = picker;
1755    /// ```
1756    pub fn new() -> Self {
1757        Self {
1758            layout: LayoutStyle::default(),
1759            flex_item: FlexItemStyle::default(),
1760            value: Binding::Static(Theme::default().palette().accent),
1761            bound: None,
1762            disabled: Binding::Static(false),
1763            hex_input: true,
1764            default_open: false,
1765            style: ColorPickerStyle::default(),
1766            swatches: Vec::new(),
1767            on_change: None,
1768        }
1769    }
1770
1771    /// Sets a read-only static or reactive color and clears writable binding.
1772    ///
1773    /// User interaction may invoke the callback but cannot mutate this configured
1774    /// value.
1775    ///
1776    /// # Examples
1777    ///
1778    /// ```
1779    /// use ailloli_ui_core::Color;
1780    /// use ailloli_ui_widgets::controls::ColorPicker;
1781    /// let picker: ColorPicker<()> = ColorPicker::new().value(Color::rgb(255, 0, 0));
1782    /// let _ = picker;
1783    /// ```
1784    pub fn value(mut self, value: impl Into<Binding<Color>>) -> Self {
1785        self.value = value.into();
1786        self.bound = None;
1787        self
1788    }
1789
1790    /// Binds a writable color signal.
1791    ///
1792    /// A changed commit writes the signal before invoking the callback.
1793    ///
1794    /// # Examples
1795    ///
1796    /// ```
1797    /// use ailloli_ui_core::Color;
1798    /// use ailloli_ui_runtime::component::State;
1799    /// use ailloli_ui_widgets::controls::ColorPicker;
1800    /// let picker: ColorPicker<()> = ColorPicker::new().bind(State::new(Color::BLACK));
1801    /// let _ = picker;
1802    /// ```
1803    pub fn bind(mut self, value: impl Into<Signal<Color>>) -> Self {
1804        let signal = value.into();
1805        self.value = Binding::Signal(signal.clone());
1806        self.bound = Some(signal);
1807        self
1808    }
1809
1810    /// Sets static or reactive disabled state.
1811    ///
1812    /// Disabled pickers are not focusable, ignore input, and do not paint or
1813    /// expose popup hit bounds.
1814    ///
1815    /// # Examples
1816    ///
1817    /// ```
1818    /// use ailloli_ui_widgets::controls::ColorPicker;
1819    /// let picker: ColorPicker<()> = ColorPicker::new().disabled(true);
1820    /// let _ = picker;
1821    /// ```
1822    pub fn disabled(mut self, value: impl Into<Binding<bool>>) -> Self {
1823        self.disabled = value.into();
1824        self
1825    }
1826
1827    /// Appends a palette swatch in display order.
1828    ///
1829    /// Duplicates and translucent colors are accepted; selecting one commits the
1830    /// exact stored [`Color`], although the hex field displays RGB only.
1831    ///
1832    /// # Examples
1833    ///
1834    /// ```
1835    /// use ailloli_ui_core::Color;
1836    /// use ailloli_ui_widgets::controls::ColorPicker;
1837    /// let picker: ColorPicker<()> = ColorPicker::new().swatch(Color::hex_rgb(0x22C55E));
1838    /// let _ = picker;
1839    /// ```
1840    pub fn swatch(mut self, value: Color) -> Self {
1841        self.swatches.push(value);
1842        self
1843    }
1844
1845    /// Shows or hides editable RGB hexadecimal input.
1846    ///
1847    /// When shown and the popup is open, the widget advertises single-line text
1848    /// input. Invalid text is ignored on Enter or focus loss and remains visible.
1849    ///
1850    /// # Examples
1851    ///
1852    /// ```
1853    /// use ailloli_ui_widgets::controls::ColorPicker;
1854    /// let picker: ColorPicker<()> = ColorPicker::new().hex_input(false);
1855    /// let _ = picker;
1856    /// ```
1857    pub fn hex_input(mut self, value: bool) -> Self {
1858        self.hex_input = value;
1859        self
1860    }
1861
1862    /// Sets only the color popup's initial open state.
1863    ///
1864    /// # Examples
1865    ///
1866    /// ```
1867    /// use ailloli_ui_widgets::controls::ColorPicker;
1868    /// let picker: ColorPicker<()> = ColorPicker::new().default_open(true);
1869    /// let _ = picker;
1870    /// ```
1871    pub fn default_open(mut self, open: bool) -> Self {
1872        self.default_open = open;
1873        self
1874    }
1875
1876    /// Replaces trigger and popup style without altering explicit layout size.
1877    ///
1878    /// # Examples
1879    ///
1880    /// ```
1881    /// use ailloli_ui_widgets::controls::{ColorPicker, ColorPickerStyle};
1882    /// let picker: ColorPicker<()> = ColorPicker::new().color_style(ColorPickerStyle::default());
1883    /// let _ = picker;
1884    /// ```
1885    pub fn color_style(mut self, style: ColorPickerStyle) -> Self {
1886        self.style = style;
1887        self
1888    }
1889
1890    /// Re-derives style from the default theme and requested density.
1891    ///
1892    /// This overwrites every previous color-style customization.
1893    ///
1894    /// # Examples
1895    ///
1896    /// ```
1897    /// use ailloli_ui_widgets::controls::{ColorPicker, ColorPickerSize};
1898    /// let picker: ColorPicker<()> = ColorPicker::new().color_size(ColorPickerSize::Compact);
1899    /// let _ = picker;
1900    /// ```
1901    pub fn color_size(mut self, size: ColorPickerSize) -> Self {
1902        self.style = ColorPickerStyle::from_theme(Theme::default(), size);
1903        self
1904    }
1905
1906    /// Dispatches the application action returned for a changed committed color.
1907    ///
1908    /// Recommitting an exactly equal [`Color`] emits nothing.
1909    ///
1910    /// # Examples
1911    ///
1912    /// ```
1913    /// use ailloli_ui_core::Color;
1914    /// use ailloli_ui_widgets::controls::ColorPicker;
1915    /// let picker: ColorPicker<Color> = ColorPicker::new().on_change(|color| color);
1916    /// let _ = picker;
1917    /// ```
1918    pub fn on_change(mut self, f: impl Fn(Color) -> A + 'static) -> Self {
1919        self.on_change = Some(Rc::new(move |ctx, next| ctx.dispatch(f(next))));
1920        self
1921    }
1922
1923    /// Handles a changed committed color with direct event-context access.
1924    ///
1925    /// # Examples
1926    ///
1927    /// ```
1928    /// use ailloli_ui_widgets::controls::ColorPicker;
1929    /// let picker: ColorPicker<()> = ColorPicker::new().on_change_ctx(|_ctx, _color| {});
1930    /// let _ = picker;
1931    /// ```
1932    pub fn on_change_ctx(mut self, f: impl Fn(&mut EventCtx<A>, Color) + 'static) -> Self {
1933        self.on_change = Some(Rc::new(f));
1934        self
1935    }
1936}
1937
1938/// Component that seeds hex editing from the configured color.
1939struct ColorPickerComponent<A> {
1940    /// Complete public picker configuration.
1941    props: ColorPicker<A>,
1942}
1943
1944impl<A: 'static> ComponentNode<A> for ColorPickerComponent<A> {
1945    /// Allocates popup, drag, and synchronized hex-edit signals.
1946    fn build(&self, context: &mut Context<A>) -> View<A> {
1947        let color = self.props.value.read();
1948        View::leaf(ColorPickerWidget {
1949            layout: self.props.layout,
1950            value: self.props.value.clone(),
1951            bound: self.props.bound.clone(),
1952            disabled: self.props.disabled.clone(),
1953            hex_input: self.props.hex_input,
1954            style: self.props.style.clone(),
1955            swatches: self.props.swatches.clone(),
1956            on_change: self.props.on_change.clone(),
1957            open: context.signal(self.props.default_open),
1958            drag: context.signal(None),
1959            hex_value: context.signal(format_hex_rgb(color)),
1960            hex_buffer: context.signal(TextBuffer::from_string(format_hex_rgb(color))),
1961            hex_edit: context.signal(TextEditState::new()),
1962        })
1963    }
1964}
1965
1966impl<A: 'static> IntoView<A> for ColorPicker<A> {
1967    /// Converts configuration into a sized reactive component view.
1968    fn into_view(self) -> View<A> {
1969        let flex_item = self.flex_item;
1970        let hint = LayoutSizeHint::from_layout(self.layout);
1971        finish_view_sized(
1972            View::component(ColorPickerComponent { props: self }),
1973            flex_item,
1974            hint,
1975        )
1976    }
1977}
1978
1979#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1980/// Active pointer-drag region within the color popup.
1981enum ColorDragPart {
1982    /// Saturation/value square.
1983    Sv,
1984    /// Vertical hue rail.
1985    Hue,
1986}
1987
1988/// Retained color trigger and HSV/hex overlay state machine.
1989struct ColorPickerWidget<A> {
1990    /// Runtime trigger layout.
1991    layout: LayoutStyle,
1992    /// Readable current color.
1993    value: Binding<Color>,
1994    /// Optional writable color signal.
1995    bound: Option<Signal<Color>>,
1996    /// Whole-control disabled binding.
1997    disabled: Binding<bool>,
1998    /// Whether hex editing is shown and receives text input.
1999    hex_input: bool,
2000    /// Trigger and popup style.
2001    style: ColorPickerStyle,
2002    /// Palette swatches in display order.
2003    swatches: Vec<Color>,
2004    /// Changed-color callback.
2005    on_change: Option<ColorChangeHandler<A>>,
2006    /// Popup visibility.
2007    open: Signal<bool>,
2008    /// Active HSV pointer-drag part.
2009    drag: Signal<Option<ColorDragPart>>,
2010    /// Editable hex text.
2011    hex_value: Signal<String>,
2012    /// Text-engine buffer synchronized after committed colors.
2013    hex_buffer: Signal<TextBuffer>,
2014    /// Hex caret and selection state.
2015    hex_edit: Signal<TextEditState>,
2016}
2017
2018impl<A: 'static> Widget<A> for ColorPickerWidget<A> {
2019    /// Returns the stable diagnostic name.
2020    fn debug_name(&self) -> &'static str {
2021        "ColorPicker"
2022    }
2023
2024    /// Applies trigger constraints and publishes open popup hit bounds.
2025    fn layout(
2026        &self,
2027        _engine: &mut ailloli_ui_runtime::layout::LayoutEngine<'_, A>,
2028        _ctx: &mut LayoutCtx<'_>,
2029        _children: &mut [LayoutChild],
2030        constraints: Constraints,
2031    ) -> LayoutResult {
2032        let size = apply_layout_size(
2033            Size::new(self.style.base.width, self.style.base.height),
2034            self.layout,
2035            constraints,
2036        );
2037        let paint_bounds = Rect::new(0.0, 0.0, size.w, size.h);
2038        let overlay_hit_bounds = if self.open.read() && !self.disabled.read() {
2039            vec![self.popup_rect_for(Rect::new(0.0, 0.0, size.w, size.h))]
2040        } else {
2041            Vec::new()
2042        };
2043        LayoutResult {
2044            size,
2045            children: Vec::new(),
2046            paint_bounds,
2047            visual_bounds: paint_bounds,
2048            overlay_hit_bounds,
2049            clip: None,
2050            is_window_root_clip: false,
2051            artifact: None,
2052        }
2053    }
2054
2055    /// Paints the RGB label, palette icon, and current-color swatch trigger.
2056    fn paint(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, _layout: &LayoutResult) {
2057        let color = self.value.read();
2058        paint_picker_trigger(
2059            ctx,
2060            bounds,
2061            Some(&format_hex_rgb(color)),
2062            "Pick color",
2063            IconId::Lucide(LucideIcon::Palette),
2064            self.disabled.read(),
2065            &self.style.base,
2066        );
2067        let swatch = Rect::new(
2068            bounds.x + self.style.base.padding_x,
2069            bounds.y + (bounds.h - 18.0) * 0.5,
2070            18.0,
2071            18.0,
2072        );
2073        ctx.push(DrawCmd::RRect(DrawRRect {
2074            rect: swatch,
2075            radius: 5.0,
2076            color,
2077        }));
2078        ctx.push(DrawCmd::Border(DrawBorder {
2079            rect: swatch,
2080            radius: Radius::uniform(5.0),
2081            border: Border::new(1.0, self.style.base.border.colors.top),
2082        }));
2083    }
2084
2085    /// Paints color controls only while the popup is open and enabled.
2086    fn paint_overlay(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, _layout: &LayoutResult) {
2087        if self.open.read() && !self.disabled.read() {
2088            self.paint_popup(ctx, bounds);
2089        }
2090    }
2091
2092    /// Routes popup toggling, HSV dragging, hex editing, commits, and dismissal.
2093    fn event(&self, ctx: &mut EventCtx<A>, event: &Event, bounds: Rect, layout: &LayoutResult) {
2094        if self.disabled.read() {
2095            return;
2096        }
2097        match event {
2098            Event::Focus(focus) if !focus.focused && self.open.read() => {
2099                self.commit_hex_if_valid(ctx);
2100                self.open.set(false);
2101                ctx.request_repaint();
2102            }
2103            Event::Pointer(PointerEvent::Button {
2104                pos,
2105                button: MouseButton::Left,
2106                pressed: false,
2107                ..
2108            }) if bounds.contains(pos.x, pos.y) => {
2109                self.open.set(!self.open.read());
2110                ctx.request_repaint();
2111                ctx.stop_propagation();
2112            }
2113            Event::Pointer(PointerEvent::Button {
2114                pos,
2115                button: MouseButton::Left,
2116                pressed,
2117                ..
2118            }) if self.open.read() && self.popup_rect_for(bounds).contains(pos.x, pos.y) => {
2119                if *pressed {
2120                    self.handle_popup_press(ctx, bounds, *pos);
2121                } else {
2122                    self.drag.set(None);
2123                    ctx.stop_propagation();
2124                }
2125            }
2126            Event::Pointer(PointerEvent::Moved { pos, .. })
2127                if self.open.read() && self.drag.read().is_some() =>
2128            {
2129                self.update_drag(ctx, bounds, *pos);
2130            }
2131            Event::Keyboard(key) if key.state == KeyState::Pressed && self.open.read() => {
2132                if key.key == Key::Named(NamedKey::Escape) {
2133                    self.open.set(false);
2134                    ctx.request_repaint();
2135                    ctx.stop_propagation();
2136                } else if key.key == Key::Named(NamedKey::Enter) {
2137                    self.commit_hex_if_valid(ctx);
2138                    ctx.request_repaint();
2139                    ctx.stop_propagation();
2140                } else if self.hex_input {
2141                    let hex_rect = self.hex_rect(self.popup_rect_for(bounds));
2142                    let handled = handle_single_line_text_event(
2143                        ctx,
2144                        event,
2145                        hex_rect,
2146                        layout,
2147                        &self.hex_value,
2148                        &self.hex_buffer,
2149                        &self.hex_edit,
2150                        self.hex_text_style(),
2151                        TextFieldEventOptions {
2152                            consume_handled_events: true,
2153                        },
2154                    );
2155                    if handled {
2156                        ctx.request_repaint();
2157                    }
2158                }
2159            }
2160            _ => {}
2161        }
2162    }
2163
2164    /// Makes only enabled pickers focusable.
2165    fn focus_policy(&self) -> FocusPolicy {
2166        if self.disabled.read() {
2167            FocusPolicy::NotFocusable
2168        } else {
2169            FocusPolicy::Focusable
2170        }
2171    }
2172
2173    /// Advertises single-line text only for an open, visible hex editor.
2174    fn input_role(&self) -> InputRole {
2175        if self.open.read() && self.hex_input {
2176            InputRole::TextSingleLine
2177        } else {
2178            InputRole::None
2179        }
2180    }
2181}
2182
2183impl<A: 'static> ColorPickerWidget<A> {
2184    /// Computes color popup geometry immediately below the trigger.
2185    fn popup_rect_for(&self, bounds: Rect) -> Rect {
2186        Rect::new(
2187            bounds.x,
2188            bounds.bottom() + self.style.base.popup_gap,
2189            self.style.popup_width,
2190            self.style.popup_height,
2191        )
2192    }
2193
2194    /// Computes the square saturation/value region with a 96-pixel floor.
2195    fn sv_rect(&self, popup: Rect) -> Rect {
2196        let side = (popup.w - 42.0).min((popup.h - 142.0).max(96.0));
2197        Rect::new(popup.x + 14.0, popup.y + 14.0, side, side)
2198    }
2199
2200    /// Places a 12-pixel-wide hue rail beside the saturation/value square.
2201    fn hue_rect(&self, popup: Rect) -> Rect {
2202        let sv = self.sv_rect(popup);
2203        Rect::new(sv.right() + 8.0, sv.y, 12.0, sv.h)
2204    }
2205
2206    /// Places the 104-by-32 hex field near the popup bottom.
2207    fn hex_rect(&self, popup: Rect) -> Rect {
2208        Rect::new(popup.x + 14.0, popup.bottom() - 48.0, 104.0, 32.0)
2209    }
2210
2211    /// Writes/emits a changed color and always normalizes hex display to RGB.
2212    fn commit_color(&self, ctx: &mut EventCtx<A>, color: Color) {
2213        if self.value.read() != color {
2214            if let Some(bound) = &self.bound {
2215                bound.set(color);
2216            }
2217            if let Some(on_change) = &self.on_change {
2218                on_change(ctx, color);
2219            }
2220        }
2221        self.hex_value.set(format_hex_rgb(color));
2222        self.hex_buffer
2223            .set(TextBuffer::from_string(format_hex_rgb(color)));
2224        ctx.request_repaint();
2225        ctx.stop_propagation();
2226    }
2227
2228    /// Parses and commits accepted RGB hex; invalid text is left unchanged.
2229    fn commit_hex_if_valid(&self, ctx: &mut EventCtx<A>) {
2230        if let Ok(color) = parse_hex_rgb(&self.hex_value.read()) {
2231            self.commit_color(ctx, color);
2232        }
2233    }
2234
2235    /// Starts HSV dragging or commits a palette swatch at the pressed point.
2236    fn handle_popup_press(&self, ctx: &mut EventCtx<A>, bounds: Rect, pos: Point) {
2237        let popup = self.popup_rect_for(bounds);
2238        if self.sv_rect(popup).contains(pos.x, pos.y) {
2239            self.drag.set(Some(ColorDragPart::Sv));
2240            self.update_drag(ctx, bounds, pos);
2241        } else if self.hue_rect(popup).contains(pos.x, pos.y) {
2242            self.drag.set(Some(ColorDragPart::Hue));
2243            self.update_drag(ctx, bounds, pos);
2244        } else if let Some(color) = self.swatch_at(popup, pos) {
2245            self.commit_color(ctx, color);
2246        } else {
2247            ctx.stop_propagation();
2248        }
2249    }
2250
2251    /// Maps pointer position to clamped HSV components and commits opaque RGB.
2252    fn update_drag(&self, ctx: &mut EventCtx<A>, bounds: Rect, pos: Point) {
2253        let popup = self.popup_rect_for(bounds);
2254        let mut hsv = color_to_hsv(self.value.read());
2255        match self.drag.read() {
2256            Some(ColorDragPart::Sv) => {
2257                let rect = self.sv_rect(popup);
2258                hsv.s = ((pos.x - rect.x) / rect.w).clamp(0.0, 1.0);
2259                hsv.v = (1.0 - (pos.y - rect.y) / rect.h).clamp(0.0, 1.0);
2260                self.commit_color(ctx, hsv_to_color(hsv));
2261            }
2262            Some(ColorDragPart::Hue) => {
2263                let rect = self.hue_rect(popup);
2264                hsv.h = ((pos.y - rect.y) / rect.h).clamp(0.0, 1.0) * 360.0;
2265                self.commit_color(ctx, hsv_to_color(hsv));
2266            }
2267            None => {}
2268        }
2269    }
2270
2271    /// Hit-tests a point against sequential palette swatch rectangles.
2272    fn swatch_at(&self, popup: Rect, pos: Point) -> Option<Color> {
2273        let y = popup.bottom() - 84.0;
2274        self.swatches.iter().enumerate().find_map(|(idx, color)| {
2275            let rect = Rect::new(
2276                popup.x + 14.0 + idx as f32 * (self.style.swatch_size + 6.0),
2277                y,
2278                self.style.swatch_size,
2279                self.style.swatch_size,
2280            );
2281            rect.contains(pos.x, pos.y).then_some(*color)
2282        })
2283    }
2284
2285    /// Derives hex editor style from common picker tokens.
2286    fn hex_text_style(&self) -> TextInputStyle {
2287        let base = &self.style.base;
2288        TextInputStyle {
2289            bg: base.trigger_background,
2290            border: base.border.colors.top,
2291            border_focused: base.focus_ring.colors.top,
2292            caret: base.text.color,
2293            placeholder: base.muted_text.color,
2294            selection_bg: base.selected.with_alpha(0.34),
2295            radius: base.radius.tl,
2296            pad_x: 8.0,
2297            pad_y: 6.0,
2298            text: base.text,
2299            caret_w: 1.0,
2300            caret_blink_ms: 500,
2301        }
2302    }
2303
2304    /// Paints sampled HSV controls, swatches, optional hex field, and preview.
2305    fn paint_popup(&self, ctx: &mut PaintCtx<'_>, bounds: Rect) {
2306        let popup = self.popup_rect_for(bounds);
2307        paint_popup_shell(ctx, popup, &self.style.base);
2308        let color = self.value.read();
2309        let hsv = color_to_hsv(color);
2310        let sv = self.sv_rect(popup);
2311        let steps = 12;
2312        for y in 0..steps {
2313            for x in 0..steps {
2314                let s = x as f32 / (steps - 1) as f32;
2315                let v = 1.0 - y as f32 / (steps - 1) as f32;
2316                let rect = Rect::new(
2317                    sv.x + x as f32 * sv.w / steps as f32,
2318                    sv.y + y as f32 * sv.h / steps as f32,
2319                    sv.w / steps as f32 + 1.0,
2320                    sv.h / steps as f32 + 1.0,
2321                );
2322                ctx.push_overlay(DrawCmd::Rect(DrawRect {
2323                    rect,
2324                    color: hsv_to_color(HsvColor::new(hsv.h, s, v)),
2325                }));
2326            }
2327        }
2328        ctx.push_overlay(DrawCmd::Border(DrawBorder {
2329            rect: sv,
2330            radius: Radius::uniform(8.0),
2331            border: self.style.base.popup_border,
2332        }));
2333        let marker = Rect::new(
2334            sv.x + hsv.s * sv.w - 4.0,
2335            sv.y + (1.0 - hsv.v) * sv.h - 4.0,
2336            8.0,
2337            8.0,
2338        );
2339        ctx.push_overlay(DrawCmd::Border(DrawBorder {
2340            rect: marker,
2341            radius: Radius::uniform(4.0),
2342            border: Border::new(2.0, Color::WHITE),
2343        }));
2344
2345        let hue = self.hue_rect(popup);
2346        for i in 0..24 {
2347            let rect = Rect::new(
2348                hue.x,
2349                hue.y + i as f32 * hue.h / 24.0,
2350                hue.w,
2351                hue.h / 24.0 + 1.0,
2352            );
2353            ctx.push_overlay(DrawCmd::Rect(DrawRect {
2354                rect,
2355                color: hsv_to_color(HsvColor::new(i as f32 * 15.0, 1.0, 1.0)),
2356            }));
2357        }
2358        ctx.push_overlay(DrawCmd::Border(DrawBorder {
2359            rect: hue,
2360            radius: Radius::uniform(6.0),
2361            border: self.style.base.popup_border,
2362        }));
2363
2364        let sw_y = popup.bottom() - 84.0;
2365        for (idx, swatch) in self.swatches.iter().enumerate() {
2366            let rect = Rect::new(
2367                popup.x + 14.0 + idx as f32 * (self.style.swatch_size + 6.0),
2368                sw_y,
2369                self.style.swatch_size,
2370                self.style.swatch_size,
2371            );
2372            ctx.push_overlay(DrawCmd::RRect(DrawRRect {
2373                rect,
2374                radius: 5.0,
2375                color: *swatch,
2376            }));
2377            ctx.push_overlay(DrawCmd::Border(DrawBorder {
2378                rect,
2379                radius: Radius::uniform(5.0),
2380                border: self.style.base.border,
2381            }));
2382        }
2383
2384        if self.hex_input {
2385            let hex = self.hex_rect(popup);
2386            ctx.push_overlay(DrawCmd::RRect(DrawRRect {
2387                rect: hex,
2388                radius: 7.0,
2389                color: self.style.base.trigger_background,
2390            }));
2391            ctx.push_overlay(DrawCmd::Border(DrawBorder {
2392                rect: hex,
2393                radius: Radius::uniform(7.0),
2394                border: self.style.base.border,
2395            }));
2396            push_overlay_text(
2397                ctx,
2398                &self.hex_value.read(),
2399                hex.x + 8.0,
2400                hex.y + 21.0,
2401                self.style.base.text,
2402            );
2403        }
2404        let preview = Rect::new(popup.right() - 54.0, popup.bottom() - 48.0, 40.0, 32.0);
2405        ctx.push_overlay(DrawCmd::RRect(DrawRRect {
2406            rect: preview,
2407            radius: 7.0,
2408            color,
2409        }));
2410        ctx.push_overlay(DrawCmd::Border(DrawBorder {
2411            rect: preview,
2412            radius: Radius::uniform(7.0),
2413            border: self.style.base.border,
2414        }));
2415    }
2416}
2417
2418/// Paints a common picker trigger with label/placeholder and trailing icon.
2419fn paint_picker_trigger(
2420    ctx: &mut PaintCtx<'_>,
2421    bounds: Rect,
2422    label: Option<&str>,
2423    placeholder: &str,
2424    icon: IconId,
2425    disabled: bool,
2426    style: &PickerBaseStyle,
2427) {
2428    let interaction = ctx.interaction();
2429    let bg = if interaction.hovered && !disabled {
2430        style.trigger_hovered
2431    } else {
2432        style.trigger_background
2433    };
2434    ctx.push(DrawCmd::RRect(DrawRRect {
2435        rect: bounds,
2436        radius: style.radius.tl,
2437        color: if disabled {
2438            bg.with_alpha(style.disabled_opacity)
2439        } else {
2440            bg
2441        },
2442    }));
2443    ctx.push(DrawCmd::Border(DrawBorder {
2444        rect: bounds,
2445        radius: style.radius,
2446        border: if interaction.focused && !disabled {
2447            style.focus_ring
2448        } else {
2449            style.border
2450        },
2451    }));
2452    let icon_rect = Rect::new(
2453        bounds.right() - style.padding_x - style.icon_size,
2454        bounds.y + (bounds.h - style.icon_size) * 0.5,
2455        style.icon_size,
2456        style.icon_size,
2457    );
2458    ctx.push(DrawCmd::Image(DrawImage {
2459        rect: icon_rect,
2460        icon,
2461        tint: if disabled {
2462            style.disabled_text.color
2463        } else {
2464            style.muted_text.color
2465        },
2466        rotation_rad: 0.0,
2467    }));
2468    let text = label.unwrap_or(placeholder);
2469    let text_style = if disabled {
2470        style.disabled_text
2471    } else if label.is_some() {
2472        style.text
2473    } else {
2474        style.muted_text
2475    };
2476    push_text(
2477        ctx,
2478        text,
2479        bounds.x + style.padding_x,
2480        bounds.y + bounds.h * 0.5 + text_style.px_size as f32 * 0.35,
2481        text_style,
2482    );
2483}
2484
2485/// Paints configured shadows, popup fill, and popup border in overlay layers.
2486fn paint_popup_shell(ctx: &mut PaintCtx<'_>, popup: Rect, style: &PickerBaseStyle) {
2487    for shadow in &style.shadows {
2488        ctx.push_overlay(DrawCmd::BoxShadow(DrawBoxShadow {
2489            rect: popup,
2490            radius: style.radius,
2491            shadow: *shadow,
2492        }));
2493    }
2494    ctx.push_overlay(DrawCmd::RRect(DrawRRect {
2495        rect: popup,
2496        radius: style.radius.tl,
2497        color: style.popup_background,
2498    }));
2499    ctx.push_overlay(DrawCmd::Border(DrawBorder {
2500        rect: popup,
2501        radius: style.radius,
2502        border: style.popup_border,
2503    }));
2504}
2505
2506/// Paints a fixed-inset overlay icon button using the active fill.
2507fn paint_icon_button(ctx: &mut PaintCtx<'_>, rect: Rect, icon: IconId, style: &PickerBaseStyle) {
2508    ctx.push_overlay(DrawCmd::RRect(DrawRRect {
2509        rect,
2510        radius: 6.0,
2511        color: style.active,
2512    }));
2513    ctx.push_overlay(DrawCmd::Image(DrawImage {
2514        rect: rect.inflate(-6.0, -5.0),
2515        icon,
2516        tint: style.text.color,
2517        rotation_rad: 0.0,
2518    }));
2519}
2520
2521/// Lays out unwrapped text and emits a regular draw command when text is available.
2522fn push_text(ctx: &mut PaintCtx<'_>, text: &str, x: f32, baseline_y: f32, style: TextStyle) {
2523    let layout = ctx.text_system.as_deref_mut().map(|ts| {
2524        ts.layout_cached(TextLayoutParams {
2525            text,
2526            style,
2527            max_width: None,
2528            wrap_mode: WrapMode::NoWrap,
2529        })
2530    });
2531    if let Some(layout) = layout {
2532        ctx.push(DrawCmd::Text(DrawText {
2533            pos: [x, baseline_y],
2534            color: style.color,
2535            decoration: ailloli_ui_core::TextDecoration::None,
2536            layout,
2537        }));
2538    }
2539}
2540
2541/// Lays out unwrapped text and emits an overlay draw command when text is available.
2542fn push_overlay_text(
2543    ctx: &mut PaintCtx<'_>,
2544    text: &str,
2545    x: f32,
2546    baseline_y: f32,
2547    style: TextStyle,
2548) {
2549    let layout = ctx.text_system.as_deref_mut().map(|ts| {
2550        ts.layout_cached(TextLayoutParams {
2551            text,
2552            style,
2553            max_width: None,
2554            wrap_mode: WrapMode::NoWrap,
2555        })
2556    });
2557    if let Some(layout) = layout {
2558        ctx.push_overlay(DrawCmd::Text(DrawText {
2559            pos: [x, baseline_y],
2560            color: style.color,
2561            decoration: ailloli_ui_core::TextDecoration::None,
2562            layout,
2563        }));
2564    }
2565}
2566
2567/// Centers `active` in a bounded visible window when possible.
2568///
2569/// Callers provide a nonzero `visible`; if `visible == 0` and `len > 0`, the
2570/// subtraction `len - visible` remains safe but produces an empty intended window.
2571fn visible_start(active: usize, len: usize, visible: usize) -> usize {
2572    if len <= visible {
2573        0
2574    } else {
2575        active.saturating_sub(visible / 2).min(len - visible)
2576    }
2577}
2578
2579/// Returns minute values below 60 separated by a step sanitized to `1..=60`.
2580fn minute_values(step_minutes: u8) -> Vec<u8> {
2581    let step = sanitize_step_minutes(step_minutes);
2582    (0..60).step_by(step as usize).map(|m| m as u8).collect()
2583}
2584
2585/// Returns an English month name; every value outside `1..=11` maps to December.
2586fn month_name(month: u8) -> &'static str {
2587    match month {
2588        1 => "January",
2589        2 => "February",
2590        3 => "March",
2591        4 => "April",
2592        5 => "May",
2593        6 => "June",
2594        7 => "July",
2595        8 => "August",
2596        9 => "September",
2597        10 => "October",
2598        11 => "November",
2599        _ => "December",
2600    }
2601}