ailloli_ui_widgets/controls/
segmented.rs

1//! Equal-width, single-selection segmented controls.
2
3use std::rc::Rc;
4
5use crate::layout::layout_ext::{apply_layout_size, finish_view_sized, LayoutExt};
6use ailloli_ui_core::event::pointer::{MouseButton, PointerEvent};
7use ailloli_ui_core::event::{Event, Key, KeyState, NamedKey};
8use ailloli_ui_core::geometry::{Constraints, Rect, Size};
9use ailloli_ui_core::style::{Border, FlexItemStyle, LayoutSizeHint, LayoutStyle, Radius};
10use ailloli_ui_core::{Color, FontId, IconId, TextStyle, Theme};
11use ailloli_ui_runtime::component::{Binding, IntoView, Memo, Signal, View, Widget};
12use ailloli_ui_runtime::input::{EventCtx, FocusPolicy};
13use ailloli_ui_runtime::layout::{LayoutChild, LayoutCtx, LayoutResult};
14use ailloli_ui_runtime::scene::PaintCtx;
15use ailloli_ui_runtime::{DrawBorder, DrawCmd, DrawImage, DrawRRect, DrawRect, DrawText};
16use ailloli_ui_text::{TextLayoutParams, TextSystem, WrapMode};
17
18#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
19/// Built-in segmented-control density choices.
20///
21/// # Examples
22///
23/// ```
24/// use ailloli_ui_widgets::controls::SegmentedSize;
25/// let sizes = [SegmentedSize::Compact, SegmentedSize::Default];
26/// assert_eq!(sizes.len(), 2);
27/// assert_eq!(SegmentedSize::default(), SegmentedSize::Default);
28/// ```
29pub enum SegmentedSize {
30    /// 28-pixel height and 56-pixel minimum segment width.
31    Compact,
32    /// 34-pixel height and 72-pixel minimum segment width; the default.
33    #[default]
34    Default,
35}
36
37#[derive(Clone, Debug, PartialEq)]
38/// Resolved colors, typography, and logical-pixel geometry.
39///
40/// `selected_background_hovered` and `selected_background_pressed` are retained
41/// for compatibility but the current painter always uses `selected_background`.
42/// Other geometry is not validated.
43///
44/// # Examples
45///
46/// ```
47/// use ailloli_ui_core::Theme;
48/// use ailloli_ui_widgets::controls::{SegmentedSize, SegmentedStyle};
49/// let style = SegmentedStyle::from_theme(Theme::dark(), SegmentedSize::Compact);
50/// assert_eq!((style.height, style.min_segment_width), (28.0, 56.0));
51/// ```
52pub struct SegmentedStyle {
53    /// Resting outer background.
54    pub background: Color,
55    /// Background while the widget is hovered.
56    pub background_hovered: Color,
57    /// Background while the widget is pressed.
58    pub background_pressed: Color,
59    /// Selected-segment fill.
60    pub selected_background: Color,
61    /// Reserved selected-hover fill; currently not read.
62    pub selected_background_hovered: Color,
63    /// Reserved selected-pressed fill; currently not read.
64    pub selected_background_pressed: Color,
65    /// Outer border.
66    pub border: Border,
67    /// Focus border outside widget bounds.
68    pub focus_ring: Border,
69    /// Divider color between adjacent segments.
70    pub divider_color: Color,
71    /// Unselected label style.
72    pub text: TextStyle,
73    /// Selected label style.
74    pub selected_text: TextStyle,
75    /// Disabled label style.
76    pub disabled_text: TextStyle,
77    /// Unselected icon tint.
78    pub icon_tint: Color,
79    /// Selected icon tint.
80    pub selected_icon_tint: Color,
81    /// Disabled icon tint.
82    pub disabled_icon_tint: Color,
83    /// Intrinsic control height in logical pixels.
84    pub height: f32,
85    /// Outer control corner radii.
86    pub radius: Radius,
87    /// Horizontal label/icon inset per segment in logical pixels.
88    pub segment_padding_x: f32,
89    /// Minimum equal segment width in logical pixels.
90    pub min_segment_width: f32,
91    /// Optional leading icon width/height in logical pixels.
92    pub icon_size: f32,
93    /// Space between icon and label in logical pixels.
94    pub icon_gap: f32,
95    /// Focus-ring inflation beyond widget bounds in logical pixels.
96    pub focus_ring_offset: f32,
97    /// Alpha multiplier for globally/individually disabled visuals.
98    pub disabled_opacity: f32,
99}
100
101impl Default for SegmentedStyle {
102    fn default() -> Self {
103        Self::from_theme(Theme::default(), SegmentedSize::Default)
104    }
105}
106
107impl SegmentedStyle {
108    /// Resolves control colors and geometry from a theme and built-in size.
109    ///
110    /// # Examples
111    ///
112    /// ```
113    /// use ailloli_ui_core::Theme;
114    /// use ailloli_ui_widgets::controls::{SegmentedSize, SegmentedStyle};
115    /// let style = SegmentedStyle::from_theme(Theme::default(), SegmentedSize::Default);
116    /// assert_eq!((style.height, style.segment_padding_x), (34.0, 12.0));
117    /// assert_eq!((style.icon_size, style.icon_gap), (14.0, 6.0));
118    /// ```
119    pub fn from_theme(theme: Theme, size: SegmentedSize) -> Self {
120        let palette = theme.palette();
121        let (height, padding, min_width, icon_size, text_size) = match size {
122            SegmentedSize::Compact => (28.0, 10.0, 56.0, 14.0, 12),
123            SegmentedSize::Default => (34.0, 12.0, 72.0, 14.0, 13),
124        };
125        let text = TextStyle::new(FontId::Ui, text_size, palette.text);
126        let disabled = TextStyle::new(FontId::Ui, text_size, palette.text_muted.with_alpha(0.70));
127        Self {
128            background: palette.surface_elevated,
129            background_hovered: Color::hex_rgb(0x20252A),
130            background_pressed: Color::hex_rgb(0x15191D),
131            selected_background: palette.accent,
132            selected_background_hovered: theme.button_bg_hover,
133            selected_background_pressed: theme.button_bg_pressed,
134            border: Border::new(1.0, palette.border),
135            focus_ring: Border::new(2.0, palette.focus),
136            divider_color: palette.border,
137            text,
138            selected_text: text,
139            disabled_text: disabled,
140            icon_tint: palette.text_muted,
141            selected_icon_tint: palette.text,
142            disabled_icon_tint: palette.text_muted.with_alpha(0.62),
143            height,
144            radius: Radius::uniform(theme.radius().md),
145            segment_padding_x: padding,
146            min_segment_width: min_width,
147            icon_size,
148            icon_gap: 6.0,
149            focus_ring_offset: 3.0,
150            disabled_opacity: 0.45,
151        }
152    }
153
154    /// Inflates layout visual bounds for a visible focus ring.
155    fn visual_bounds(&self, rect: Rect) -> Rect {
156        if self.focus_ring.is_visible() {
157            let inflate = self.focus_ring_offset + max_border_width(self.focus_ring);
158            rect.inflate(inflate, inflate)
159        } else {
160            rect
161        }
162    }
163}
164
165#[derive(Clone)]
166/// One typed value, label, and optional leading icon in a segmented control.
167///
168/// Values are identity: duplicate values cannot represent distinct selections
169/// because the first equal option is painted selected and selecting another equal
170/// option is treated as unchanged.
171///
172/// # Examples
173///
174/// ```
175/// use ailloli_ui_widgets::controls::SegmentedOption;
176/// let option = SegmentedOption::new("grid", "Grid");
177/// let _ = option;
178/// ```
179pub struct SegmentedOption<T> {
180    /// Selection identity and emitted value.
181    value: T,
182    /// Unwrapped visible label.
183    label: String,
184    /// Optional leading icon.
185    icon: Option<IconId>,
186    /// Live per-option disabled state.
187    disabled: Binding<bool>,
188}
189
190impl<T> SegmentedOption<T> {
191    /// Creates an enabled text-only option.
192    ///
193    /// # Examples
194    ///
195    /// ```
196    /// use ailloli_ui_widgets::controls::SegmentedOption;
197    /// let option = SegmentedOption::new(1, "One");
198    /// let _ = option;
199    /// ```
200    pub fn new(value: T, label: impl Into<String>) -> Self {
201        Self {
202            value,
203            label: label.into(),
204            icon: None,
205            disabled: Binding::Static(false),
206        }
207    }
208
209    /// Sets the leading icon, replacing any previous icon.
210    ///
211    /// # Examples
212    ///
213    /// ```
214    /// use ailloli_ui_core::IconId;
215    /// use ailloli_ui_widgets::controls::SegmentedOption;
216    /// let option = SegmentedOption::new("history", "History").leading_icon(IconId::History);
217    /// let _ = option;
218    /// ```
219    pub fn leading_icon(mut self, icon: IconId) -> Self {
220        self.icon = Some(icon);
221        self
222    }
223
224    /// Sets static or reactive per-option disabled state.
225    ///
226    /// Disabled options remain visible and can remain selected but are skipped by
227    /// navigation and cannot activate.
228    ///
229    /// # Examples
230    ///
231    /// ```
232    /// use ailloli_ui_widgets::controls::SegmentedOption;
233    /// let option = SegmentedOption::new(1, "One").disabled(true);
234    /// let _ = option;
235    /// ```
236    pub fn disabled(mut self, disabled: impl Into<Binding<bool>>) -> Self {
237        self.disabled = disabled.into();
238        self
239    }
240
241    /// Sets per-option disabled state from a derived memo.
242    ///
243    /// # Examples
244    ///
245    /// ```
246    /// use ailloli_ui_runtime::component::Memo;
247    /// use ailloli_ui_widgets::controls::SegmentedOption;
248    /// let option = SegmentedOption::new(1, "One").disabled_signal(Memo::new(|| false));
249    /// let _ = option;
250    /// ```
251    pub fn disabled_signal(self, disabled: Memo<bool>) -> Self {
252        self.disabled(disabled)
253    }
254}
255
256/// Shared typed selection-change callback.
257type ChangeHandler<T, A> = Rc<dyn Fn(&mut EventCtx<A>, T)>;
258
259/// An equal-width, typed single-selection control.
260///
261/// Selection can be controlled or two-way bound. Without either a writable
262/// signal or callback, interaction is read-only. Arrow keys wrap and skip
263/// disabled options; Home/End choose first/last. With no matching selection,
264/// Right chooses first, Left chooses last, and Enter/Space chooses first.
265///
266/// # Examples
267///
268/// ```
269/// use ailloli_ui_widgets::controls::SegmentedControl;
270/// let control: SegmentedControl<&str, ()> = SegmentedControl::new()
271///     .option("grid", "Grid")
272///     .option("list", "List")
273///     .selected("grid");
274/// let _ = control;
275/// ```
276pub struct SegmentedControl<T, A = ()> {
277    /// Layout configuration applied to intrinsic equal-width geometry.
278    pub(crate) layout: LayoutStyle,
279    /// Flex behavior used by the parent layout.
280    pub(crate) flex_item: FlexItemStyle,
281    /// Options in display/navigation order.
282    options: Vec<SegmentedOption<T>>,
283    /// Optional controlled or bound selection.
284    selected: Option<Binding<T>>,
285    /// Writable selection signal in bound mode.
286    bound: Option<Signal<T>>,
287    /// Live global disabled state.
288    disabled: Binding<bool>,
289    /// Optional selection-change notification.
290    on_change: Option<ChangeHandler<T, A>>,
291    /// Resolved paint and geometry.
292    style: SegmentedStyle,
293}
294
295impl<T: Clone + PartialEq + 'static, A: 'static> Default for SegmentedControl<T, A> {
296    fn default() -> Self {
297        Self::new()
298    }
299}
300
301impl<T: Clone + PartialEq + 'static, A: 'static> LayoutExt for SegmentedControl<T, A> {
302    fn layout_mut(&mut self) -> &mut LayoutStyle {
303        &mut self.layout
304    }
305}
306
307impl<T: Clone + PartialEq + 'static, A: 'static> SegmentedControl<T, A> {
308    /// Creates an enabled empty control with no selection or callback.
309    ///
310    /// Empty controls measure zero width, retain style height, and are not
311    /// focusable.
312    ///
313    /// # Examples
314    ///
315    /// ```
316    /// use ailloli_ui_widgets::controls::SegmentedControl;
317    /// let control: SegmentedControl<i32, ()> = SegmentedControl::new();
318    /// let _ = control;
319    /// ```
320    pub fn new() -> Self {
321        Self {
322            layout: LayoutStyle::default(),
323            flex_item: FlexItemStyle::default(),
324            options: Vec::new(),
325            selected: None,
326            bound: None,
327            disabled: Binding::Static(false),
328            on_change: None,
329            style: SegmentedStyle::default(),
330        }
331    }
332
333    /// Appends an enabled text-only option.
334    ///
335    /// # Examples
336    ///
337    /// ```
338    /// use ailloli_ui_widgets::controls::SegmentedControl;
339    /// let control: SegmentedControl<i32, ()> = SegmentedControl::new().option(1, "One");
340    /// let _ = control;
341    /// ```
342    pub fn option(mut self, value: T, label: impl Into<String>) -> Self {
343        self.options.push(SegmentedOption::new(value, label));
344        self
345    }
346
347    /// Appends a fully configured option.
348    ///
349    /// # Examples
350    ///
351    /// ```
352    /// use ailloli_ui_widgets::controls::{SegmentedControl, SegmentedOption};
353    /// let option = SegmentedOption::new(1, "One").disabled(true);
354    /// let control: SegmentedControl<i32, ()> = SegmentedControl::new().segmented_option(option);
355    /// let _ = control;
356    /// ```
357    pub fn segmented_option(mut self, option: SegmentedOption<T>) -> Self {
358        self.options.push(option);
359        self
360    }
361
362    /// Sets controlled static/reactive selection and clears bound mode.
363    ///
364    /// A value absent from options paints no selection. Change callbacks still
365    /// emit interaction results, but cannot mutate this source.
366    ///
367    /// # Examples
368    ///
369    /// ```
370    /// use ailloli_ui_widgets::controls::SegmentedControl;
371    /// let control: SegmentedControl<i32, ()> = SegmentedControl::new().option(1, "One").selected(1);
372    /// let _ = control;
373    /// ```
374    pub fn selected(mut self, selected: impl Into<Binding<T>>) -> Self {
375        self.selected = Some(selected.into());
376        self.bound = None;
377        self
378    }
379
380    /// Installs a writable signal for two-way selection.
381    ///
382    /// # Examples
383    ///
384    /// ```
385    /// use std::{cell::RefCell, rc::Rc};
386    /// use ailloli_ui_runtime::component::Signal;
387    /// use ailloli_ui_widgets::controls::SegmentedControl;
388    /// let selected = Signal::new(Rc::new(RefCell::new(1)), Rc::new(|| {}));
389    /// let control: SegmentedControl<i32, ()> = SegmentedControl::new().option(1, "One").bind(selected);
390    /// let _ = control;
391    /// ```
392    pub fn bind(mut self, selected: impl Into<Signal<T>>) -> Self {
393        let signal = selected.into();
394        self.selected = Some(Binding::Signal(signal.clone()));
395        self.bound = Some(signal);
396        self
397    }
398
399    /// Sets static or reactive global disabled state.
400    ///
401    /// Disabled controls are not focusable and ignore pointer/keyboard input.
402    ///
403    /// # Examples
404    ///
405    /// ```
406    /// use ailloli_ui_widgets::controls::SegmentedControl;
407    /// let control: SegmentedControl<i32, ()> = SegmentedControl::new().disabled(true);
408    /// let _ = control;
409    /// ```
410    pub fn disabled(mut self, disabled: impl Into<Binding<bool>>) -> Self {
411        self.disabled = disabled.into();
412        self
413    }
414
415    /// Sets global disabled state from a derived memo.
416    ///
417    /// # Examples
418    ///
419    /// ```
420    /// use ailloli_ui_runtime::component::Memo;
421    /// use ailloli_ui_widgets::controls::SegmentedControl;
422    /// let control: SegmentedControl<i32, ()> = SegmentedControl::new().disabled_signal(Memo::new(|| false));
423    /// let _ = control;
424    /// ```
425    pub fn disabled_signal(self, disabled: Memo<bool>) -> Self {
426        self.disabled(disabled)
427    }
428
429    /// Replaces complete colors and intrinsic geometry.
430    ///
431    /// # Examples
432    ///
433    /// ```
434    /// use ailloli_ui_widgets::controls::{SegmentedControl, SegmentedStyle};
435    /// let control: SegmentedControl<i32, ()> = SegmentedControl::new().segmented_style(SegmentedStyle::default());
436    /// let _ = control;
437    /// ```
438    pub fn segmented_style(mut self, style: SegmentedStyle) -> Self {
439        self.style = style;
440        self
441    }
442
443    /// Replaces style with a default-theme built-in size.
444    ///
445    /// # Examples
446    ///
447    /// ```
448    /// use ailloli_ui_widgets::controls::{SegmentedControl, SegmentedSize};
449    /// let control: SegmentedControl<i32, ()> = SegmentedControl::new().segmented_size(SegmentedSize::Compact);
450    /// let _ = control;
451    /// ```
452    pub fn segmented_size(mut self, size: SegmentedSize) -> Self {
453        self.style = SegmentedStyle::from_theme(Theme::default(), size);
454        self
455    }
456
457    /// Maps each distinct enabled option selection to an application action.
458    ///
459    /// The callback does not make a controlled source writable; use [`Self::bind`]
460    /// for two-way state.
461    ///
462    /// # Examples
463    ///
464    /// ```
465    /// use ailloli_ui_widgets::controls::SegmentedControl;
466    /// #[derive(Clone)]
467    /// enum Action { Selected(i32) }
468    /// let control = SegmentedControl::new().option(1, "One").on_change(Action::Selected);
469    /// let _ = control;
470    /// ```
471    pub fn on_change(mut self, f: impl Fn(T) -> A + 'static) -> Self {
472        self.on_change = Some(Rc::new(move |ctx, next| ctx.dispatch(f(next))));
473        self
474    }
475
476    /// Installs a context-aware selection handler.
477    ///
478    /// # Examples
479    ///
480    /// ```
481    /// use ailloli_ui_widgets::controls::SegmentedControl;
482    /// let control = SegmentedControl::<i32, ()>::new()
483    ///     .option(1, "One")
484    ///     .on_change_ctx(|_ctx, value| assert_eq!(value, 1));
485    /// let _ = control;
486    /// ```
487    pub fn on_change_ctx(mut self, f: impl Fn(&mut EventCtx<A>, T) + 'static) -> Self {
488        self.on_change = Some(Rc::new(f));
489        self
490    }
491
492    /// Sets preferred width from logical pixels or an explicit `Length`.
493    ///
494    /// # Examples
495    ///
496    /// ```
497    /// use ailloli_ui_widgets::controls::SegmentedControl;
498    /// let _ = SegmentedControl::<i32, ()>::new().width(240.0);
499    /// ```
500    pub fn width(mut self, value: impl Into<ailloli_ui_core::style::Length>) -> Self {
501        self.layout.width = value.into();
502        self
503    }
504
505    /// Sets preferred height from logical pixels or an explicit `Length`.
506    ///
507    /// # Examples
508    ///
509    /// ```
510    /// use ailloli_ui_widgets::controls::SegmentedControl;
511    /// let _ = SegmentedControl::<i32, ()>::new().height(40.0);
512    /// ```
513    pub fn height(mut self, value: impl Into<ailloli_ui_core::style::Length>) -> Self {
514        self.layout.height = value.into();
515        self
516    }
517
518    /// Sets the minimum resolved width.
519    ///
520    /// # Examples
521    ///
522    /// ```
523    /// use ailloli_ui_widgets::controls::SegmentedControl;
524    /// let _ = SegmentedControl::<i32, ()>::new().min_width(120.0);
525    /// ```
526    pub fn min_width(mut self, value: impl Into<ailloli_ui_core::style::Length>) -> Self {
527        self.layout.min_width = value.into();
528        self
529    }
530
531    /// Sets the maximum resolved width.
532    ///
533    /// # Examples
534    ///
535    /// ```
536    /// use ailloli_ui_widgets::controls::SegmentedControl;
537    /// let _ = SegmentedControl::<i32, ()>::new().max_width(400.0);
538    /// ```
539    pub fn max_width(mut self, value: impl Into<ailloli_ui_core::style::Length>) -> Self {
540        self.layout.max_width = value.into();
541        self
542    }
543
544    /// Sets the minimum resolved height.
545    ///
546    /// # Examples
547    ///
548    /// ```
549    /// use ailloli_ui_widgets::controls::SegmentedControl;
550    /// let _ = SegmentedControl::<i32, ()>::new().min_height(28.0);
551    /// ```
552    pub fn min_height(mut self, value: impl Into<ailloli_ui_core::style::Length>) -> Self {
553        self.layout.min_height = value.into();
554        self
555    }
556
557    /// Sets the maximum resolved height.
558    ///
559    /// # Examples
560    ///
561    /// ```
562    /// use ailloli_ui_widgets::controls::SegmentedControl;
563    /// let _ = SegmentedControl::<i32, ()>::new().max_height(48.0);
564    /// ```
565    pub fn max_height(mut self, value: impl Into<ailloli_ui_core::style::Length>) -> Self {
566        self.layout.max_height = value.into();
567        self
568    }
569
570    /// Marks both axes as parent-fill.
571    ///
572    /// # Examples
573    ///
574    /// ```
575    /// use ailloli_ui_widgets::controls::SegmentedControl;
576    /// let _ = SegmentedControl::<i32, ()>::new().fill();
577    /// ```
578    pub fn fill(mut self) -> Self {
579        self.layout.width = ailloli_ui_core::style::Length::Fill;
580        self.layout.height = ailloli_ui_core::style::Length::Fill;
581        self
582    }
583
584    /// Marks width as parent-fill while preserving height.
585    ///
586    /// # Examples
587    ///
588    /// ```
589    /// use ailloli_ui_widgets::controls::SegmentedControl;
590    /// let _ = SegmentedControl::<i32, ()>::new().fill_width();
591    /// ```
592    pub fn fill_width(mut self) -> Self {
593        self.layout.width = ailloli_ui_core::style::Length::Fill;
594        self
595    }
596
597    /// Marks height as parent-fill while preserving width.
598    ///
599    /// # Examples
600    ///
601    /// ```
602    /// use ailloli_ui_widgets::controls::SegmentedControl;
603    /// let _ = SegmentedControl::<i32, ()>::new().fill_height();
604    /// ```
605    pub fn fill_height(mut self) -> Self {
606        self.layout.height = ailloli_ui_core::style::Length::Fill;
607        self
608    }
609
610    /// Sets the same logical-pixel margin on every side.
611    ///
612    /// # Examples
613    ///
614    /// ```
615    /// use ailloli_ui_widgets::controls::SegmentedControl;
616    /// let _ = SegmentedControl::<i32, ()>::new().margin(8.0);
617    /// ```
618    pub fn margin(mut self, value: f32) -> Self {
619        self.layout = self.layout.margin(value);
620        self
621    }
622
623    /// Sets the same logical-pixel layout padding on every side.
624    ///
625    /// This is layout metadata and is separate from per-segment content padding.
626    ///
627    /// # Examples
628    ///
629    /// ```
630    /// use ailloli_ui_widgets::controls::SegmentedControl;
631    /// let _ = SegmentedControl::<i32, ()>::new().padding(4.0);
632    /// ```
633    pub fn padding(mut self, value: f32) -> Self {
634        self.layout = self.layout.padding(value);
635        self
636    }
637
638    /// Sets the dimensionless parent flex-grow weight to one.
639    ///
640    /// # Examples
641    ///
642    /// ```
643    /// use ailloli_ui_widgets::controls::SegmentedControl;
644    /// let _ = SegmentedControl::<i32, ()>::new().flex_grow();
645    /// ```
646    pub fn flex_grow(mut self) -> Self {
647        self.flex_item = self.flex_item.flex_grow(1.0);
648        self
649    }
650
651    /// Sets the dimensionless parent flex-grow weight.
652    ///
653    /// # Examples
654    ///
655    /// ```
656    /// use ailloli_ui_widgets::controls::SegmentedControl;
657    /// let _ = SegmentedControl::<i32, ()>::new().flex_grow_by(2.0);
658    /// ```
659    pub fn flex_grow_by(mut self, value: f32) -> Self {
660        self.flex_item = self.flex_item.flex_grow(value);
661        self
662    }
663
664    /// Sets the dimensionless parent flex-shrink weight.
665    ///
666    /// # Examples
667    ///
668    /// ```
669    /// use ailloli_ui_widgets::controls::SegmentedControl;
670    /// let _ = SegmentedControl::<i32, ()>::new().flex_shrink(0.5);
671    /// ```
672    pub fn flex_shrink(mut self, value: f32) -> Self {
673        self.flex_item = self.flex_item.flex_shrink(value);
674        self
675    }
676
677    /// Sets the preferred parent main-axis flex basis.
678    ///
679    /// # Examples
680    ///
681    /// ```
682    /// use ailloli_ui_widgets::controls::SegmentedControl;
683    /// let _ = SegmentedControl::<i32, ()>::new().flex_basis(160.0);
684    /// ```
685    pub fn flex_basis(mut self, value: impl Into<ailloli_ui_core::style::Length>) -> Self {
686        self.flex_item = self.flex_item.flex_basis(value);
687        self
688    }
689
690    /// Overrides this item's parent cross-axis alignment.
691    ///
692    /// # Examples
693    ///
694    /// ```
695    /// use ailloli_ui_core::style::AlignItems;
696    /// use ailloli_ui_widgets::controls::SegmentedControl;
697    /// let _ = SegmentedControl::<i32, ()>::new().align_self(AlignItems::End);
698    /// ```
699    pub fn align_self(mut self, value: ailloli_ui_core::style::AlignItems) -> Self {
700        self.flex_item = self.flex_item.align_self(value);
701        self
702    }
703}
704
705/// Retained widget implementing equal-width measurement, paint, and selection.
706struct SegmentedWidget<T, A> {
707    /// Outer logical sizing policy.
708    layout: LayoutStyle,
709    /// Ordered value, label, and icon choices.
710    options: Vec<SegmentedOption<T>>,
711    /// Optional readable external selected value.
712    selected: Option<Binding<T>>,
713    /// Optional writable external selected value.
714    bound: Option<Signal<T>>,
715    /// Reactive interaction-disable flag for the entire control.
716    disabled: Binding<bool>,
717    /// Optional callback receiving changed values.
718    on_change: Option<ChangeHandler<T, A>>,
719    /// Segment colors and logical-pixel geometry.
720    style: SegmentedStyle,
721}
722
723#[derive(Debug, Clone, Copy)]
724/// Selected/disabled flags used to resolve one segment's content colors.
725struct SegmentPaintState {
726    /// Whether this is the first option equal to the selected value.
727    selected: bool,
728    /// Whether the control or this option is disabled.
729    disabled: bool,
730}
731
732impl<T: Clone + PartialEq + 'static, A: 'static> Widget<A> for SegmentedWidget<T, A> {
733    fn debug_name(&self) -> &'static str {
734        "SegmentedControl"
735    }
736
737    fn layout(
738        &self,
739        _engine: &mut ailloli_ui_runtime::layout::LayoutEngine<'_, A>,
740        ctx: &mut LayoutCtx<'_>,
741        _children: &mut [LayoutChild],
742        constraints: Constraints,
743    ) -> LayoutResult {
744        let intrinsic =
745            segmented_intrinsic_size(&self.options, &self.style, ctx.text_system.as_deref_mut());
746        let size = apply_layout_size(intrinsic, self.layout, constraints);
747        let paint_bounds = Rect::new(0.0, 0.0, size.w, size.h);
748        LayoutResult {
749            size,
750            children: Vec::new(),
751            paint_bounds,
752            visual_bounds: self.style.visual_bounds(paint_bounds),
753            overlay_hit_bounds: Vec::new(),
754            clip: None,
755            is_window_root_clip: false,
756            artifact: None,
757        }
758    }
759
760    fn paint(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, _layout_result: &LayoutResult) {
761        let disabled = self.disabled.read();
762        let selected = self.selected_value();
763        let selected_index = self.selected_index(selected.as_ref());
764        let segment_rects = segment_rects(bounds, self.options.len());
765        let interaction = ctx.interaction();
766
767        paint_background(
768            ctx,
769            bounds,
770            disabled,
771            interaction.hovered,
772            interaction.pressed,
773            &self.style,
774        );
775
776        if let Some(index) = selected_index {
777            if let Some(rect) = segment_rects.get(index).copied() {
778                paint_selected_segment(
779                    ctx,
780                    rect,
781                    disabled || self.options[index].disabled.read(),
782                    &self.style,
783                );
784            }
785        }
786
787        paint_dividers(ctx, bounds, self.options.len(), &self.style);
788
789        for (idx, option) in self.options.iter().enumerate() {
790            let option_disabled = disabled || option.disabled.read();
791            let option_selected = selected_index == Some(idx);
792            paint_segment_content(
793                ctx,
794                segment_rects[idx],
795                option,
796                SegmentPaintState {
797                    selected: option_selected,
798                    disabled: option_disabled,
799                },
800                &self.style,
801            );
802        }
803
804        if self.style.border.is_visible() {
805            ctx.push(DrawCmd::Border(DrawBorder {
806                rect: bounds,
807                radius: self.style.radius,
808                border: apply_border_opacity(
809                    self.style.border,
810                    if disabled {
811                        self.style.disabled_opacity
812                    } else {
813                        1.0
814                    },
815                ),
816            }));
817        }
818
819        if interaction.focused && !disabled && self.style.focus_ring.is_visible() {
820            ctx.push(DrawCmd::Border(DrawBorder {
821                rect: bounds.inflate(self.style.focus_ring_offset, self.style.focus_ring_offset),
822                radius: Radius::uniform(self.style.radius.tl + self.style.focus_ring_offset),
823                border: self.style.focus_ring,
824            }));
825        }
826    }
827
828    fn event(&self, ctx: &mut EventCtx<A>, event: &Event, bounds: Rect, _layout: &LayoutResult) {
829        if self.disabled.read() {
830            return;
831        }
832
833        match event {
834            Event::Pointer(PointerEvent::Button {
835                pos,
836                button: MouseButton::Left,
837                pressed: false,
838                ..
839            }) => {
840                if let Some(index) = self.segment_at(bounds, pos.x, pos.y) {
841                    self.select_index(ctx, index);
842                }
843            }
844            Event::Keyboard(key) if key.state == KeyState::Pressed => {
845                let selected = self.selected_value();
846                let target = match &key.key {
847                    Key::Named(NamedKey::Enter) | Key::Named(NamedKey::Space) => {
848                        self.activation_index(selected.as_ref())
849                    }
850                    Key::Named(NamedKey::ArrowRight) => self.next_enabled_index(selected.as_ref()),
851                    Key::Named(NamedKey::ArrowLeft) => {
852                        self.previous_enabled_index(selected.as_ref())
853                    }
854                    Key::Named(NamedKey::Home) => self.first_enabled_index(),
855                    Key::Named(NamedKey::End) => self.last_enabled_index(),
856                    _ => None,
857                };
858                if let Some(index) = target {
859                    self.select_index(ctx, index);
860                }
861            }
862            _ => {}
863        }
864    }
865
866    fn focus_policy(&self) -> FocusPolicy {
867        if self.disabled.read() || self.first_enabled_index().is_none() {
868            FocusPolicy::NotFocusable
869        } else {
870            FocusPolicy::Focusable
871        }
872    }
873}
874
875impl<T: Clone + PartialEq + 'static, A: 'static> SegmentedWidget<T, A> {
876    /// Reads the optional controlled or bound selection.
877    fn selected_value(&self) -> Option<T> {
878        self.selected.as_ref().map(Binding::read)
879    }
880
881    /// Finds the first option equal to a selected value.
882    fn selected_index(&self, selected: Option<&T>) -> Option<usize> {
883        let selected = selected?;
884        self.options
885            .iter()
886            .position(|option| &option.value == selected)
887    }
888
889    /// Hit-tests equal-width segments inside widget bounds.
890    fn segment_at(&self, bounds: Rect, x: f32, y: f32) -> Option<usize> {
891        if self.options.is_empty() || !bounds.contains(x, y) {
892            return None;
893        }
894        let segment_width = bounds.w / self.options.len() as f32;
895        if segment_width <= 0.0 {
896            return None;
897        }
898        let index = ((x - bounds.x) / segment_width).floor() as usize;
899        (index < self.options.len()).then_some(index)
900    }
901
902    /// Writes/notifies a distinct enabled option when an output path exists.
903    fn select_index(&self, ctx: &mut EventCtx<A>, index: usize) {
904        let Some(option) = self.options.get(index) else {
905            return;
906        };
907        if option.disabled.read() {
908            return;
909        }
910        if self
911            .selected_value()
912            .as_ref()
913            .is_some_and(|value| value == &option.value)
914        {
915            return;
916        }
917        if self.bound.is_none() && self.on_change.is_none() {
918            return;
919        }
920
921        let next = option.value.clone();
922        if let Some(bound) = &self.bound {
923            bound.set(next.clone());
924        }
925        if let Some(on_change) = &self.on_change {
926            on_change(ctx, next);
927        }
928        ctx.request_repaint();
929        ctx.stop_propagation();
930    }
931
932    /// Activates the enabled selection or falls back to the first enabled option.
933    fn activation_index(&self, selected: Option<&T>) -> Option<usize> {
934        self.selected_index(selected)
935            .filter(|idx| self.option_enabled(*idx))
936            .or_else(|| self.first_enabled_index())
937    }
938
939    /// Wraps forward through enabled options.
940    fn next_enabled_index(&self, selected: Option<&T>) -> Option<usize> {
941        let len = self.options.len();
942        if len == 0 {
943            return None;
944        }
945        let start = self.selected_index(selected).unwrap_or(len - 1);
946        (1..=len)
947            .map(|offset| (start + offset) % len)
948            .find(|idx| self.option_enabled(*idx))
949    }
950
951    /// Wraps backward through enabled options.
952    fn previous_enabled_index(&self, selected: Option<&T>) -> Option<usize> {
953        let len = self.options.len();
954        if len == 0 {
955            return None;
956        }
957        let start = self.selected_index(selected).unwrap_or(0);
958        (1..=len)
959            .map(|offset| (start + len - offset) % len)
960            .find(|idx| self.option_enabled(*idx))
961    }
962
963    /// Returns the first enabled option index.
964    fn first_enabled_index(&self) -> Option<usize> {
965        self.options
966            .iter()
967            .enumerate()
968            .find_map(|(idx, _)| self.option_enabled(idx).then_some(idx))
969    }
970
971    /// Returns the last enabled option index.
972    fn last_enabled_index(&self) -> Option<usize> {
973        self.options
974            .iter()
975            .enumerate()
976            .rev()
977            .find_map(|(idx, _)| self.option_enabled(idx).then_some(idx))
978    }
979
980    /// Reads whether an indexed option exists and is enabled.
981    fn option_enabled(&self, index: usize) -> bool {
982        self.options
983            .get(index)
984            .is_some_and(|option| !option.disabled.read())
985    }
986}
987
988impl<T: Clone + PartialEq + 'static, A: 'static> IntoView<A> for SegmentedControl<T, A> {
989    fn into_view(self) -> View<A> {
990        finish_view_sized(
991            View::leaf(SegmentedWidget {
992                layout: self.layout,
993                options: self.options,
994                selected: self.selected,
995                bound: self.bound,
996                disabled: self.disabled,
997                on_change: self.on_change,
998                style: self.style,
999            }),
1000            self.flex_item,
1001            LayoutSizeHint::from_layout(self.layout),
1002        )
1003    }
1004}
1005
1006/// Measures every label and gives all segments the longest required width.
1007fn segmented_intrinsic_size<T>(
1008    options: &[SegmentedOption<T>],
1009    style: &SegmentedStyle,
1010    mut text_system: Option<&mut TextSystem>,
1011) -> Size {
1012    if options.is_empty() {
1013        return Size::new(0.0, style.height);
1014    }
1015    let segment_width = options
1016        .iter()
1017        .map(|option| {
1018            let label = measure_text(text_system.as_deref_mut(), &option.label, style.text);
1019            segment_content_width(option, label.w, style)
1020        })
1021        .fold(style.min_segment_width, f32::max);
1022    Size::new(
1023        (segment_width * options.len() as f32).ceil(),
1024        style.height.ceil(),
1025    )
1026}
1027
1028/// Computes label/icon/padding width subject to the minimum segment width.
1029fn segment_content_width<T>(
1030    option: &SegmentedOption<T>,
1031    label_width: f32,
1032    style: &SegmentedStyle,
1033) -> f32 {
1034    let icon_width = if option.icon.is_some() {
1035        style.icon_size + style.icon_gap
1036    } else {
1037        0.0
1038    };
1039    (label_width + icon_width + style.segment_padding_x * 2.0).max(style.min_segment_width)
1040}
1041
1042/// Divides bounds equally, assigning rounding remainder to the last segment.
1043fn segment_rects(bounds: Rect, count: usize) -> Vec<Rect> {
1044    if count == 0 {
1045        return Vec::new();
1046    }
1047    let segment_width = bounds.w / count as f32;
1048    (0..count)
1049        .map(|idx| {
1050            let x = bounds.x + segment_width * idx as f32;
1051            let w = if idx + 1 == count {
1052                bounds.right() - x
1053            } else {
1054                segment_width
1055            };
1056            Rect::new(x, bounds.y, w, bounds.h)
1057        })
1058        .collect()
1059}
1060
1061/// Paints the interaction-state outer background with disabled opacity.
1062fn paint_background(
1063    ctx: &mut PaintCtx<'_>,
1064    bounds: Rect,
1065    disabled: bool,
1066    hovered: bool,
1067    pressed: bool,
1068    style: &SegmentedStyle,
1069) {
1070    let color = if pressed {
1071        style.background_pressed
1072    } else if hovered {
1073        style.background_hovered
1074    } else {
1075        style.background
1076    };
1077    ctx.push(DrawCmd::RRect(DrawRRect {
1078        rect: bounds,
1079        radius: style.radius.tl,
1080        color: apply_opacity(
1081            color,
1082            if disabled {
1083                style.disabled_opacity
1084            } else {
1085                1.0
1086            },
1087        ),
1088    }));
1089}
1090
1091/// Paints an inset selected segment, dimmed when disabled.
1092fn paint_selected_segment(
1093    ctx: &mut PaintCtx<'_>,
1094    rect: Rect,
1095    disabled: bool,
1096    style: &SegmentedStyle,
1097) {
1098    let inset = 3.0_f32.min(rect.h * 0.25);
1099    let selected_rect = rect.inflate(-inset, -inset);
1100    ctx.push(DrawCmd::RRect(DrawRRect {
1101        rect: selected_rect,
1102        radius: (style.radius.tl - 2.0).max(0.0),
1103        color: apply_opacity(
1104            style.selected_background,
1105            if disabled {
1106                style.disabled_opacity
1107            } else {
1108                1.0
1109            },
1110        ),
1111    }));
1112}
1113
1114/// Paints one-pixel dividers between adjacent equal-width segments.
1115fn paint_dividers(ctx: &mut PaintCtx<'_>, bounds: Rect, count: usize, style: &SegmentedStyle) {
1116    if count <= 1 {
1117        return;
1118    }
1119    let segment_width = bounds.w / count as f32;
1120    for idx in 1..count {
1121        let x = bounds.x + segment_width * idx as f32;
1122        ctx.push(DrawCmd::Rect(DrawRect {
1123            rect: Rect::new(x, bounds.y + 6.0, 1.0, (bounds.h - 12.0).max(0.0)),
1124            color: style.divider_color.with_alpha(0.72),
1125        }));
1126    }
1127}
1128
1129/// Centers and paints one option's optional icon and unwrapped label.
1130fn paint_segment_content<T>(
1131    ctx: &mut PaintCtx<'_>,
1132    rect: Rect,
1133    option: &SegmentedOption<T>,
1134    state: SegmentPaintState,
1135    style: &SegmentedStyle,
1136) {
1137    let opacity = if state.disabled {
1138        style.disabled_opacity
1139    } else {
1140        1.0
1141    };
1142    let text_style = if state.disabled {
1143        style.disabled_text
1144    } else if state.selected {
1145        style.selected_text
1146    } else {
1147        style.text
1148    };
1149    let label_width = estimate_text_width(&option.label, text_style);
1150    let content_width = label_width
1151        + option
1152            .icon
1153            .as_ref()
1154            .map(|_| style.icon_size + style.icon_gap)
1155            .unwrap_or(0.0);
1156    let mut x = rect.x + (rect.w - content_width).max(0.0) * 0.5;
1157
1158    if let Some(icon) = &option.icon {
1159        let tint = if state.disabled {
1160            style.disabled_icon_tint
1161        } else if state.selected {
1162            style.selected_icon_tint
1163        } else {
1164            style.icon_tint
1165        };
1166        ctx.push(DrawCmd::Image(DrawImage {
1167            rect: Rect::new(
1168                x,
1169                rect.y + (rect.h - style.icon_size) * 0.5,
1170                style.icon_size,
1171                style.icon_size,
1172            ),
1173            icon: icon.clone(),
1174            tint: apply_opacity(tint, opacity),
1175            rotation_rad: 0.0,
1176        }));
1177        x += style.icon_size + style.icon_gap;
1178    }
1179
1180    paint_label(ctx, &option.label, text_style, x, rect, opacity);
1181}
1182
1183/// Shapes and vertically centers one unwrapped label.
1184fn paint_label(
1185    ctx: &mut PaintCtx<'_>,
1186    label: &str,
1187    style: TextStyle,
1188    x: f32,
1189    bounds: Rect,
1190    opacity: f32,
1191) {
1192    let Some(text_system) = ctx.text_system.as_deref_mut() else {
1193        return;
1194    };
1195    let layout = text_system.layout_cached(TextLayoutParams {
1196        text: label,
1197        style,
1198        max_width: None,
1199        wrap_mode: WrapMode::NoWrap,
1200    });
1201    let baseline = layout
1202        .lines
1203        .first()
1204        .map(|line| line.baseline_y)
1205        .unwrap_or(0.0);
1206    let y = bounds.y + (bounds.h - layout.metrics.height) * 0.5 + baseline;
1207    ctx.push(DrawCmd::Text(DrawText {
1208        pos: [x, y],
1209        color: apply_opacity(style.color, opacity),
1210        decoration: ailloli_ui_core::TextDecoration::None,
1211        layout: layout.clone(),
1212    }));
1213}
1214
1215/// Measures unwrapped text through the text system or fallback estimate.
1216fn measure_text(text_system: Option<&mut TextSystem>, text: &str, style: TextStyle) -> Size {
1217    if let Some(text_system) = text_system {
1218        let layout = text_system.layout_cached(TextLayoutParams {
1219            text,
1220            style,
1221            max_width: None,
1222            wrap_mode: WrapMode::NoWrap,
1223        });
1224        Size::new(layout.metrics.width, layout.metrics.height)
1225    } else {
1226        Size::new(estimate_text_width(text, style), style.px_size as f32 * 1.2)
1227    }
1228}
1229
1230/// Estimates width as 0.58 em per Unicode scalar value.
1231fn estimate_text_width(text: &str, style: TextStyle) -> f32 {
1232    text.chars().count() as f32 * style.px_size as f32 * 0.58
1233}
1234
1235/// Multiplies alpha by `opacity` and clamps to `[0, 1]`.
1236fn apply_opacity(mut color: Color, opacity: f32) -> Color {
1237    color.a = (color.a * opacity).clamp(0.0, 1.0);
1238    color
1239}
1240
1241/// Applies an opacity multiplier independently to all border-edge colors.
1242fn apply_border_opacity(mut border: Border, opacity: f32) -> Border {
1243    border.colors.left = apply_opacity(border.colors.left, opacity);
1244    border.colors.top = apply_opacity(border.colors.top, opacity);
1245    border.colors.right = apply_opacity(border.colors.right, opacity);
1246    border.colors.bottom = apply_opacity(border.colors.bottom, opacity);
1247    border
1248}
1249
1250/// Returns the maximum per-edge border width.
1251fn max_border_width(border: Border) -> f32 {
1252    border
1253        .widths
1254        .left
1255        .max(border.widths.top)
1256        .max(border.widths.right)
1257        .max(border.widths.bottom)
1258}