1use 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
41type DateChangeHandler<A> = Rc<dyn Fn(&mut EventCtx<A>, DateValue)>;
43type TimeChangeHandler<A> = Rc<dyn Fn(&mut EventCtx<A>, TimeValue)>;
45type ColorChangeHandler<A> = Rc<dyn Fn(&mut EventCtx<A>, Color)>;
47
48#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
49pub enum DatePickerSize {
59 Compact,
61 #[default]
62 Default,
64}
65
66#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
67pub enum TimePickerSize {
77 Compact,
79 #[default]
80 Default,
82}
83
84#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
85pub enum ColorPickerSize {
95 Compact,
97 #[default]
98 Default,
100}
101
102#[derive(Clone, Debug, PartialEq)]
103pub struct PickerBaseStyle {
117 pub trigger_background: Color,
119 pub trigger_hovered: Color,
121 pub popup_background: Color,
123 pub active: Color,
125 pub selected: Color,
127 pub disabled_fill: Color,
129 pub border: Border,
131 pub popup_border: Border,
133 pub focus_ring: Border,
135 pub shadows: Vec<BoxShadow>,
137 pub text: TextStyle,
139 pub muted_text: TextStyle,
141 pub disabled_text: TextStyle,
143 pub accent_text: TextStyle,
145 pub width: f32,
147 pub height: f32,
149 pub popup_gap: f32,
151 pub radius: Radius,
153 pub padding_x: f32,
155 pub icon_size: f32,
157 pub disabled_opacity: f32,
159}
160
161#[derive(Clone, Debug, PartialEq)]
162pub struct DatePickerStyle {
173 pub base: PickerBaseStyle,
175 pub popup_width: f32,
177 pub header_height: f32,
179 pub week_height: f32,
181 pub cell_height: f32,
183}
184
185#[derive(Clone, Debug, PartialEq)]
186pub struct TimePickerStyle {
196 pub base: PickerBaseStyle,
198 pub popup_width: f32,
200 pub popup_height: f32,
202 pub row_height: f32,
204}
205
206#[derive(Clone, Debug, PartialEq)]
207pub struct ColorPickerStyle {
217 pub base: PickerBaseStyle,
219 pub popup_width: f32,
221 pub popup_height: f32,
223 pub swatch_size: f32,
225}
226
227impl PickerBaseStyle {
228 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 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 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 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
356pub struct DatePicker<A = ()> {
371 pub(crate) layout: LayoutStyle,
373 pub(crate) flex_item: FlexItemStyle,
375 value: Option<Binding<Option<DateValue>>>,
377 bound: Option<Signal<Option<DateValue>>>,
379 min: Option<DateValue>,
381 max: Option<DateValue>,
383 placeholder: Binding<String>,
385 disabled: Binding<bool>,
387 default_month: Option<MonthValue>,
389 default_open: bool,
391 style: DatePickerStyle,
393 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 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 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 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 pub fn min(mut self, value: DateValue) -> Self {
490 self.min = Some(value);
491 self
492 }
493
494 pub fn max(mut self, value: DateValue) -> Self {
507 self.max = Some(value);
508 self
509 }
510
511 pub fn placeholder(mut self, value: impl Into<Binding<String>>) -> Self {
521 self.placeholder = value.into();
522 self
523 }
524
525 pub fn disabled(mut self, value: impl Into<Binding<bool>>) -> Self {
538 self.disabled = value.into();
539 self
540 }
541
542 pub fn default_month(mut self, value: MonthValue) -> Self {
555 self.default_month = Some(value);
556 self
557 }
558
559 pub fn default_open(mut self, open: bool) -> Self {
569 self.default_open = open;
570 self
571 }
572
573 pub fn date_style(mut self, style: DatePickerStyle) -> Self {
583 self.style = style;
584 self
585 }
586
587 pub fn date_size(mut self, size: DatePickerSize) -> Self {
599 self.style = DatePickerStyle::from_theme(Theme::default(), size);
600 self
601 }
602
603 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 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
635struct DatePickerComponent<A> {
637 props: DatePicker<A>,
639}
640
641impl<A: 'static> ComponentNode<A> for DatePickerComponent<A> {
642 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 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
681struct DatePickerWidget<A> {
683 layout: LayoutStyle,
685 value: Option<Binding<Option<DateValue>>>,
687 bound: Option<Signal<Option<DateValue>>>,
689 min: Option<DateValue>,
691 max: Option<DateValue>,
693 placeholder: Binding<String>,
695 disabled: Binding<bool>,
697 style: DatePickerStyle,
699 on_change: Option<DateChangeHandler<A>>,
701 open: Signal<bool>,
703 month: Signal<MonthValue>,
705 active: Signal<DateValue>,
707}
708
709impl<A: 'static> Widget<A> for DatePickerWidget<A> {
710 fn debug_name(&self) -> &'static str {
712 "DatePicker"
713 }
714
715 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 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 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 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 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 fn current_value(&self) -> Option<DateValue> {
811 self.value.as_ref().and_then(Binding::read)
812 }
813
814 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 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 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 fn move_active(&self, ctx: &mut EventCtx<A>, delta: i32) {
893 self.set_active(ctx, next_day(self.active.read(), delta));
894 }
895
896 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 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 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 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
1034pub struct TimePicker<A = ()> {
1049 pub(crate) layout: LayoutStyle,
1051 pub(crate) flex_item: FlexItemStyle,
1053 value: Option<Binding<Option<TimeValue>>>,
1055 bound: Option<Signal<Option<TimeValue>>>,
1057 placeholder: Binding<String>,
1059 disabled: Binding<bool>,
1061 step_minutes: u8,
1063 format: TimeFormat,
1065 default_open: bool,
1067 style: TimePickerStyle,
1069 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 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 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 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 pub fn placeholder(mut self, value: impl Into<Binding<String>>) -> Self {
1161 self.placeholder = value.into();
1162 self
1163 }
1164
1165 pub fn disabled(mut self, value: impl Into<Binding<bool>>) -> Self {
1178 self.disabled = value.into();
1179 self
1180 }
1181
1182 pub fn step_minutes(mut self, value: u8) -> Self {
1196 self.step_minutes = sanitize_step_minutes(value);
1197 self
1198 }
1199
1200 pub fn format(mut self, value: TimeFormat) -> Self {
1213 self.format = value;
1214 self
1215 }
1216
1217 pub fn default_open(mut self, open: bool) -> Self {
1227 self.default_open = open;
1228 self
1229 }
1230
1231 pub fn time_style(mut self, style: TimePickerStyle) -> Self {
1241 self.style = style;
1242 self
1243 }
1244
1245 pub fn time_size(mut self, size: TimePickerSize) -> Self {
1257 self.style = TimePickerStyle::from_theme(Theme::default(), size);
1258 self
1259 }
1260
1261 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 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
1293struct TimePickerComponent<A> {
1295 props: TimePicker<A>,
1297}
1298
1299impl<A: 'static> ComponentNode<A> for TimePickerComponent<A> {
1300 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 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)]
1339enum TimeColumn {
1341 Hour,
1343 Minute,
1345}
1346
1347struct TimePickerWidget<A> {
1349 layout: LayoutStyle,
1351 value: Option<Binding<Option<TimeValue>>>,
1353 bound: Option<Signal<Option<TimeValue>>>,
1355 placeholder: Binding<String>,
1357 disabled: Binding<bool>,
1359 step_minutes: u8,
1361 format: TimeFormat,
1363 style: TimePickerStyle,
1365 on_change: Option<TimeChangeHandler<A>>,
1367 open: Signal<bool>,
1369 active: Signal<TimeValue>,
1371 active_column: Signal<TimeColumn>,
1373}
1374
1375impl<A: 'static> Widget<A> for TimePickerWidget<A> {
1376 fn debug_name(&self) -> &'static str {
1378 "TimePicker"
1379 }
1380
1381 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 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 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 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 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 fn current_value(&self) -> Option<TimeValue> {
1481 self.value.as_ref().and_then(Binding::read)
1482 }
1483
1484 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 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 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 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 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 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 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 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
1698pub struct ColorPicker<A = ()> {
1713 pub(crate) layout: LayoutStyle,
1715 pub(crate) flex_item: FlexItemStyle,
1717 value: Binding<Color>,
1719 bound: Option<Signal<Color>>,
1721 disabled: Binding<bool>,
1723 hex_input: bool,
1725 default_open: bool,
1727 style: ColorPickerStyle,
1729 swatches: Vec<Color>,
1731 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 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 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 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 pub fn disabled(mut self, value: impl Into<Binding<bool>>) -> Self {
1823 self.disabled = value.into();
1824 self
1825 }
1826
1827 pub fn swatch(mut self, value: Color) -> Self {
1841 self.swatches.push(value);
1842 self
1843 }
1844
1845 pub fn hex_input(mut self, value: bool) -> Self {
1858 self.hex_input = value;
1859 self
1860 }
1861
1862 pub fn default_open(mut self, open: bool) -> Self {
1872 self.default_open = open;
1873 self
1874 }
1875
1876 pub fn color_style(mut self, style: ColorPickerStyle) -> Self {
1886 self.style = style;
1887 self
1888 }
1889
1890 pub fn color_size(mut self, size: ColorPickerSize) -> Self {
1902 self.style = ColorPickerStyle::from_theme(Theme::default(), size);
1903 self
1904 }
1905
1906 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 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
1938struct ColorPickerComponent<A> {
1940 props: ColorPicker<A>,
1942}
1943
1944impl<A: 'static> ComponentNode<A> for ColorPickerComponent<A> {
1945 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 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)]
1980enum ColorDragPart {
1982 Sv,
1984 Hue,
1986}
1987
1988struct ColorPickerWidget<A> {
1990 layout: LayoutStyle,
1992 value: Binding<Color>,
1994 bound: Option<Signal<Color>>,
1996 disabled: Binding<bool>,
1998 hex_input: bool,
2000 style: ColorPickerStyle,
2002 swatches: Vec<Color>,
2004 on_change: Option<ColorChangeHandler<A>>,
2006 open: Signal<bool>,
2008 drag: Signal<Option<ColorDragPart>>,
2010 hex_value: Signal<String>,
2012 hex_buffer: Signal<TextBuffer>,
2014 hex_edit: Signal<TextEditState>,
2016}
2017
2018impl<A: 'static> Widget<A> for ColorPickerWidget<A> {
2019 fn debug_name(&self) -> &'static str {
2021 "ColorPicker"
2022 }
2023
2024 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 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 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 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 fn focus_policy(&self) -> FocusPolicy {
2166 if self.disabled.read() {
2167 FocusPolicy::NotFocusable
2168 } else {
2169 FocusPolicy::Focusable
2170 }
2171 }
2172
2173 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 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 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 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 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 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 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 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 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 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 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 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
2418fn 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
2485fn 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
2506fn 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
2521fn 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
2541fn 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
2567fn 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
2579fn 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
2585fn 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}