ailloli_ui_widgets/controls/radio.rs
1//! Standalone radio buttons and typed single-selection radio groups.
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, TextStyle, Theme};
11use ailloli_ui_runtime::component::{Binding, IntoView, Memo, Signal, View, Widget};
12use ailloli_ui_runtime::input::{
13 ActivationPolicy, ClickAction, EventCtx, FocusPolicy, IntoClickAction,
14};
15use ailloli_ui_runtime::layout::{LayoutChild, LayoutCtx, LayoutResult};
16use ailloli_ui_runtime::scene::PaintCtx;
17use ailloli_ui_runtime::{DrawBorder, DrawCmd, DrawRRect, DrawText};
18use ailloli_ui_text::{TextLayoutParams, TextSystem, WrapMode};
19
20#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
21/// Built-in radio geometry sizes.
22///
23/// # Examples
24///
25/// ```
26/// use ailloli_ui_widgets::controls::RadioSize;
27/// let sizes = [RadioSize::Compact, RadioSize::Default];
28/// assert_eq!(sizes.len(), 2);
29/// assert_eq!(RadioSize::default(), RadioSize::Default);
30/// ```
31pub enum RadioSize {
32 /// 14-pixel outer circle in a 24-pixel option row.
33 Compact,
34 /// 16-pixel outer circle in a 28-pixel option row; the default.
35 #[default]
36 Default,
37}
38
39#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
40/// Layout direction for a [`RadioGroup`].
41///
42/// Keyboard arrows are direction-independent: Down/Right move forward and
43/// Up/Left move backward.
44///
45/// # Examples
46///
47/// ```
48/// use ailloli_ui_widgets::controls::RadioDirection;
49/// let directions = [RadioDirection::Vertical, RadioDirection::Horizontal];
50/// assert_eq!(directions.len(), 2);
51/// assert_eq!(RadioDirection::default(), RadioDirection::Vertical);
52/// ```
53pub enum RadioDirection {
54 /// Stack full-width option rows top-to-bottom; the default.
55 #[default]
56 Vertical,
57 /// Place content-width option rows left-to-right.
58 Horizontal,
59}
60
61#[derive(Clone, Debug, PartialEq)]
62/// Resolved radio colors, typography, and logical-pixel geometry.
63///
64/// Custom geometry is not validated; non-finite values can propagate into
65/// layout/paint calculations.
66///
67/// # Examples
68///
69/// ```
70/// use ailloli_ui_core::Theme;
71/// use ailloli_ui_widgets::controls::{RadioSize, RadioStyle};
72/// let style = RadioStyle::from_theme(Theme::dark(), RadioSize::Compact);
73/// assert_eq!((style.outer_size, style.dot_size, style.option_height), (14.0, 7.0, 24.0));
74/// ```
75pub struct RadioStyle {
76 /// Resting unchecked outer-circle fill.
77 pub outer_fill: Color,
78 /// Hovered unchecked outer-circle fill.
79 pub outer_fill_hovered: Color,
80 /// Pressed unchecked outer-circle fill.
81 pub outer_fill_pressed: Color,
82 /// Checked outer-circle fill.
83 pub selected_fill: Color,
84 /// Checked inner-dot fill.
85 pub dot_fill: Color,
86 /// Disabled outer-circle fill.
87 pub disabled_fill: Color,
88 /// Unchecked outer-circle border.
89 pub border: Border,
90 /// Checked outer-circle border.
91 pub selected_border: Border,
92 /// Focus border around the outer circle.
93 pub focus_ring: Border,
94 /// Enabled label style.
95 pub text: TextStyle,
96 /// Disabled label style.
97 pub disabled_text: TextStyle,
98 /// Outer-circle diameter in logical pixels.
99 pub outer_size: f32,
100 /// Inner-dot diameter in logical pixels.
101 pub dot_size: f32,
102 /// Per-option row height in logical pixels.
103 pub option_height: f32,
104 /// Space between circle and label in logical pixels.
105 pub label_gap: f32,
106 /// Space between group options in logical pixels.
107 pub option_gap: f32,
108 /// Horizontal inset before circle and after label in logical pixels.
109 pub option_padding_x: f32,
110 /// Focus-ring inflation beyond the outer circle in logical pixels.
111 pub focus_ring_offset: f32,
112 /// Alpha multiplier applied to disabled visuals.
113 pub disabled_opacity: f32,
114}
115
116impl Default for RadioStyle {
117 fn default() -> Self {
118 Self::from_theme(Theme::default(), RadioSize::Default)
119 }
120}
121
122impl RadioStyle {
123 /// Resolves radio styling from a theme and built-in size.
124 ///
125 /// # Examples
126 ///
127 /// ```
128 /// use ailloli_ui_core::Theme;
129 /// use ailloli_ui_widgets::controls::{RadioSize, RadioStyle};
130 /// let style = RadioStyle::from_theme(Theme::default(), RadioSize::Default);
131 /// assert_eq!((style.outer_size, style.dot_size), (16.0, 8.0));
132 /// assert_eq!((style.label_gap, style.option_gap), (8.0, 6.0));
133 /// ```
134 pub fn from_theme(theme: Theme, size: RadioSize) -> Self {
135 let palette = theme.palette();
136 let (outer_size, dot_size, option_height, text_size) = match size {
137 RadioSize::Compact => (14.0, 7.0, 24.0, 12),
138 RadioSize::Default => (16.0, 8.0, 28.0, 13),
139 };
140 Self {
141 outer_fill: palette.surface_elevated,
142 outer_fill_hovered: Color::hex_rgb(0x20252A),
143 outer_fill_pressed: Color::hex_rgb(0x15191D),
144 selected_fill: palette.surface_elevated,
145 dot_fill: palette.accent,
146 disabled_fill: palette.surface.with_alpha(0.58),
147 border: Border::new(1.0, palette.border),
148 selected_border: Border::new(1.0, palette.accent),
149 focus_ring: Border::new(2.0, palette.focus),
150 text: TextStyle::new(FontId::Ui, text_size, palette.text),
151 disabled_text: TextStyle::new(
152 FontId::Ui,
153 text_size,
154 palette.text_muted.with_alpha(0.72),
155 ),
156 outer_size,
157 dot_size,
158 option_height,
159 label_gap: 8.0,
160 option_gap: 6.0,
161 option_padding_x: 0.0,
162 focus_ring_offset: 3.0,
163 disabled_opacity: 0.45,
164 }
165 }
166
167 /// Inflates layout visual bounds for a visible focus ring.
168 fn visual_bounds(&self, rect: Rect) -> Rect {
169 if self.focus_ring.is_visible() {
170 let inflate = self.focus_ring_offset + max_border_width(self.focus_ring);
171 rect.inflate(inflate, inflate)
172 } else {
173 rect
174 }
175 }
176}
177
178#[derive(Clone)]
179/// One typed value, label, and live disabled state in a radio group.
180///
181/// Duplicate equal values are ambiguous: every equal option paints checked,
182/// while selection lookup/navigation uses the first equal option.
183///
184/// # Examples
185///
186/// ```
187/// use ailloli_ui_widgets::controls::RadioOption;
188/// let option = RadioOption::new("daily", "Daily");
189/// let _ = option;
190/// ```
191pub struct RadioOption<T> {
192 /// Selection identity and emitted value.
193 value: T,
194 /// Unwrapped visible label.
195 label: String,
196 /// Live per-option disabled state.
197 disabled: Binding<bool>,
198}
199
200impl<T> RadioOption<T> {
201 /// Creates an enabled typed option.
202 ///
203 /// # Examples
204 ///
205 /// ```
206 /// use ailloli_ui_widgets::controls::RadioOption;
207 /// let option = RadioOption::new(1, "One");
208 /// let _ = option;
209 /// ```
210 pub fn new(value: T, label: impl Into<String>) -> Self {
211 Self {
212 value,
213 label: label.into(),
214 disabled: Binding::Static(false),
215 }
216 }
217
218 /// Sets static or reactive per-option disabled state.
219 ///
220 /// Disabled options remain visible and may paint checked but are skipped by
221 /// navigation and cannot activate.
222 ///
223 /// # Examples
224 ///
225 /// ```
226 /// use ailloli_ui_widgets::controls::RadioOption;
227 /// let option = RadioOption::new(1, "One").disabled(true);
228 /// let _ = option;
229 /// ```
230 pub fn disabled(mut self, disabled: impl Into<Binding<bool>>) -> Self {
231 self.disabled = disabled.into();
232 self
233 }
234
235 /// Sets per-option disabled state from a derived memo.
236 ///
237 /// # Examples
238 ///
239 /// ```
240 /// use ailloli_ui_runtime::component::Memo;
241 /// use ailloli_ui_widgets::controls::RadioOption;
242 /// let option = RadioOption::new(1, "One").disabled_signal(Memo::new(|| false));
243 /// let _ = option;
244 /// ```
245 pub fn disabled_signal(self, disabled: Memo<bool>) -> Self {
246 self.disabled(disabled)
247 }
248}
249
250/// A standalone boolean radio button.
251///
252/// `checked` is controlled and `bind` is two-way. Activating an unchecked button
253/// writes `true` when bound and/or runs the action; activating a checked button
254/// is a no-op, so this widget never writes `false`.
255///
256/// # Examples
257///
258/// ```
259/// use ailloli_ui_widgets::controls::RadioButton;
260/// let radio: RadioButton<()> = RadioButton::new("Enable feature").checked(true);
261/// let _ = radio;
262/// ```
263pub struct RadioButton<A = ()> {
264 /// Layout configuration applied to intrinsic row geometry.
265 pub(crate) layout: LayoutStyle,
266 /// Flex behavior used by the parent layout.
267 pub(crate) flex_item: FlexItemStyle,
268 /// Unwrapped visible label.
269 label: String,
270 /// Static or reactive controlled checked state.
271 checked: Binding<bool>,
272 /// Writable checked signal in bound mode.
273 bound: Option<Signal<bool>>,
274 /// Live disabled state.
275 disabled: Binding<bool>,
276 /// Optional action run when selecting an unchecked button.
277 on_select: Option<ClickAction<A>>,
278 /// Resolved paint and geometry.
279 style: RadioStyle,
280}
281
282crate::impl_layout_builders!(RadioButton);
283
284impl<A: 'static> RadioButton<A> {
285 /// Creates an enabled unchecked button with no action.
286 ///
287 /// # Examples
288 ///
289 /// ```
290 /// use ailloli_ui_widgets::controls::RadioButton;
291 /// let radio: RadioButton<()> = RadioButton::new("Choice");
292 /// let _ = radio;
293 /// ```
294 pub fn new(label: impl Into<String>) -> Self {
295 Self {
296 layout: LayoutStyle::default(),
297 flex_item: FlexItemStyle::default(),
298 label: label.into(),
299 checked: Binding::Static(false),
300 bound: None,
301 disabled: Binding::Static(false),
302 on_select: None,
303 style: RadioStyle::default(),
304 }
305 }
306
307 /// Sets controlled static/reactive checked state and clears bound mode.
308 ///
309 /// The widget cannot mutate this source; use an action to notify the owner.
310 ///
311 /// # Examples
312 ///
313 /// ```
314 /// use ailloli_ui_widgets::controls::RadioButton;
315 /// let radio: RadioButton<()> = RadioButton::new("Choice").checked(true);
316 /// let _ = radio;
317 /// ```
318 pub fn checked(mut self, checked: impl Into<Binding<bool>>) -> Self {
319 self.checked = checked.into();
320 self.bound = None;
321 self
322 }
323
324 /// Installs a writable boolean signal for two-way selection.
325 ///
326 /// Activation only writes `true`; it never toggles off.
327 ///
328 /// # Examples
329 ///
330 /// ```
331 /// use std::{cell::RefCell, rc::Rc};
332 /// use ailloli_ui_runtime::component::Signal;
333 /// use ailloli_ui_widgets::controls::RadioButton;
334 /// let checked = Signal::new(Rc::new(RefCell::new(false)), Rc::new(|| {}));
335 /// let radio: RadioButton<()> = RadioButton::new("Choice").bind(checked);
336 /// let _ = radio;
337 /// ```
338 pub fn bind(mut self, checked: impl Into<Signal<bool>>) -> Self {
339 let signal = checked.into();
340 self.checked = Binding::Signal(signal.clone());
341 self.bound = Some(signal);
342 self
343 }
344
345 /// Sets static or reactive disabled state.
346 ///
347 /// Disabled buttons are not focusable and ignore activation.
348 ///
349 /// # Examples
350 ///
351 /// ```
352 /// use ailloli_ui_widgets::controls::RadioButton;
353 /// let radio: RadioButton<()> = RadioButton::new("Unavailable").disabled(true);
354 /// let _ = radio;
355 /// ```
356 pub fn disabled(mut self, disabled: impl Into<Binding<bool>>) -> Self {
357 self.disabled = disabled.into();
358 self
359 }
360
361 /// Sets disabled state from a derived memo.
362 ///
363 /// # Examples
364 ///
365 /// ```
366 /// use ailloli_ui_runtime::component::Memo;
367 /// use ailloli_ui_widgets::controls::RadioButton;
368 /// let radio: RadioButton<()> = RadioButton::new("Choice").disabled_signal(Memo::new(|| false));
369 /// let _ = radio;
370 /// ```
371 pub fn disabled_signal(self, disabled: Memo<bool>) -> Self {
372 self.disabled(disabled)
373 }
374
375 /// Replaces complete colors and intrinsic geometry.
376 ///
377 /// # Examples
378 ///
379 /// ```
380 /// use ailloli_ui_widgets::controls::{RadioButton, RadioStyle};
381 /// let radio: RadioButton<()> = RadioButton::new("Choice").radio_style(RadioStyle::default());
382 /// let _ = radio;
383 /// ```
384 pub fn radio_style(mut self, style: RadioStyle) -> Self {
385 self.style = style;
386 self
387 }
388
389 /// Replaces style with a default-theme built-in size.
390 ///
391 /// # Examples
392 ///
393 /// ```
394 /// use ailloli_ui_widgets::controls::{RadioButton, RadioSize};
395 /// let radio: RadioButton<()> = RadioButton::new("Choice").radio_size(RadioSize::Compact);
396 /// let _ = radio;
397 /// ```
398 pub fn radio_size(mut self, size: RadioSize) -> Self {
399 self.style = RadioStyle::from_theme(Theme::default(), size);
400 self
401 }
402
403 /// Installs the action run when an unchecked button is selected.
404 ///
405 /// A later call replaces it. Checked activation remains a no-op.
406 ///
407 /// # Examples
408 ///
409 /// ```
410 /// use ailloli_ui_widgets::controls::RadioButton;
411 /// #[derive(Clone)]
412 /// enum Action { Select }
413 /// let radio = RadioButton::new("Choice").on_select(Action::Select);
414 /// let _ = radio;
415 /// ```
416 pub fn on_select(mut self, action: impl IntoClickAction<A>) -> Self {
417 self.on_select = Some(action.into_click_action());
418 self
419 }
420
421 /// Installs a context-aware selection handler.
422 ///
423 /// # Examples
424 ///
425 /// ```
426 /// use ailloli_ui_widgets::controls::RadioButton;
427 /// let radio = RadioButton::<()>::new("Choice").on_select_ctx(|_ctx| {});
428 /// let _ = radio;
429 /// ```
430 pub fn on_select_ctx(mut self, f: impl Fn(&mut EventCtx<A>) + 'static) -> Self {
431 self.on_select = Some(ClickAction::handler(f));
432 self
433 }
434}
435
436impl<A: 'static> Default for RadioButton<A> {
437 fn default() -> Self {
438 Self::new("")
439 }
440}
441
442/// Shared typed group-selection callback.
443type ChangeHandler<T, A> = Rc<dyn Fn(&mut EventCtx<A>, T)>;
444
445/// A typed single-selection set of radio options.
446///
447/// Selection can be controlled or two-way bound. Without a writable signal or
448/// callback the group is read-only. Arrows wrap and skip disabled options;
449/// Home/End select first/last. With no matching value, forward movement and
450/// Enter/Space choose first while backward movement chooses last.
451///
452/// # Examples
453///
454/// ```
455/// use ailloli_ui_widgets::controls::RadioGroup;
456/// let group: RadioGroup<&str, ()> = RadioGroup::new()
457/// .option("daily", "Daily")
458/// .option("weekly", "Weekly")
459/// .selected("daily");
460/// let _ = group;
461/// ```
462pub struct RadioGroup<T, A = ()> {
463 /// Layout configuration applied to group geometry.
464 pub(crate) layout: LayoutStyle,
465 /// Flex behavior used by the parent layout.
466 pub(crate) flex_item: FlexItemStyle,
467 /// Options in display/navigation order.
468 options: Vec<RadioOption<T>>,
469 /// Optional controlled or bound selection.
470 selected: Option<Binding<T>>,
471 /// Writable selected-value signal in bound mode.
472 bound: Option<Signal<T>>,
473 /// Live global disabled state.
474 disabled: Binding<bool>,
475 /// Vertical or horizontal option flow.
476 direction: RadioDirection,
477 /// Optional change notification.
478 on_change: Option<ChangeHandler<T, A>>,
479 /// Resolved paint and option geometry.
480 style: RadioStyle,
481}
482
483impl<T: Clone + PartialEq + 'static, A: 'static> Default for RadioGroup<T, A> {
484 fn default() -> Self {
485 Self::new()
486 }
487}
488
489impl<T: Clone + PartialEq + 'static, A: 'static> LayoutExt for RadioGroup<T, A> {
490 fn layout_mut(&mut self) -> &mut LayoutStyle {
491 &mut self.layout
492 }
493}
494
495impl<T: Clone + PartialEq + 'static, A: 'static> RadioGroup<T, A> {
496 /// Creates an enabled empty vertical group with no selection/callback.
497 ///
498 /// Empty groups measure zero by zero and are not focusable.
499 ///
500 /// # Examples
501 ///
502 /// ```
503 /// use ailloli_ui_widgets::controls::RadioGroup;
504 /// let group: RadioGroup<i32, ()> = RadioGroup::new();
505 /// let _ = group;
506 /// ```
507 pub fn new() -> Self {
508 Self {
509 layout: LayoutStyle::default(),
510 flex_item: FlexItemStyle::default(),
511 options: Vec::new(),
512 selected: None,
513 bound: None,
514 disabled: Binding::Static(false),
515 direction: RadioDirection::Vertical,
516 on_change: None,
517 style: RadioStyle::default(),
518 }
519 }
520
521 /// Appends an enabled typed option.
522 ///
523 /// # Examples
524 ///
525 /// ```
526 /// use ailloli_ui_widgets::controls::RadioGroup;
527 /// let group: RadioGroup<i32, ()> = RadioGroup::new().option(1, "One");
528 /// let _ = group;
529 /// ```
530 pub fn option(mut self, value: T, label: impl Into<String>) -> Self {
531 self.options.push(RadioOption::new(value, label));
532 self
533 }
534
535 /// Appends a fully configured option.
536 ///
537 /// # Examples
538 ///
539 /// ```
540 /// use ailloli_ui_widgets::controls::{RadioGroup, RadioOption};
541 /// let group: RadioGroup<i32, ()> = RadioGroup::new()
542 /// .radio_option(RadioOption::new(1, "One").disabled(true));
543 /// let _ = group;
544 /// ```
545 pub fn radio_option(mut self, option: RadioOption<T>) -> Self {
546 self.options.push(option);
547 self
548 }
549
550 /// Sets controlled static/reactive selection and clears bound mode.
551 ///
552 /// A value absent from options paints no selection. Equal duplicate values
553 /// may paint multiple checked options.
554 ///
555 /// # Examples
556 ///
557 /// ```
558 /// use ailloli_ui_widgets::controls::RadioGroup;
559 /// let group: RadioGroup<i32, ()> = RadioGroup::new().option(1, "One").selected(1);
560 /// let _ = group;
561 /// ```
562 pub fn selected(mut self, selected: impl Into<Binding<T>>) -> Self {
563 self.selected = Some(selected.into());
564 self.bound = None;
565 self
566 }
567
568 /// Installs a writable signal for two-way group selection.
569 ///
570 /// # Examples
571 ///
572 /// ```
573 /// use std::{cell::RefCell, rc::Rc};
574 /// use ailloli_ui_runtime::component::Signal;
575 /// use ailloli_ui_widgets::controls::RadioGroup;
576 /// let selected = Signal::new(Rc::new(RefCell::new(1)), Rc::new(|| {}));
577 /// let group: RadioGroup<i32, ()> = RadioGroup::new().option(1, "One").bind(selected);
578 /// let _ = group;
579 /// ```
580 pub fn bind(mut self, selected: impl Into<Signal<T>>) -> Self {
581 let signal = selected.into();
582 self.selected = Some(Binding::Signal(signal.clone()));
583 self.bound = Some(signal);
584 self
585 }
586
587 /// Sets static or reactive global disabled state.
588 ///
589 /// Disabled groups are not focusable and ignore interaction.
590 ///
591 /// # Examples
592 ///
593 /// ```
594 /// use ailloli_ui_widgets::controls::RadioGroup;
595 /// let group: RadioGroup<i32, ()> = RadioGroup::new().disabled(true);
596 /// let _ = group;
597 /// ```
598 pub fn disabled(mut self, disabled: impl Into<Binding<bool>>) -> Self {
599 self.disabled = disabled.into();
600 self
601 }
602
603 /// Sets global disabled state from a derived memo.
604 ///
605 /// # Examples
606 ///
607 /// ```
608 /// use ailloli_ui_runtime::component::Memo;
609 /// use ailloli_ui_widgets::controls::RadioGroup;
610 /// let group: RadioGroup<i32, ()> = RadioGroup::new().disabled_signal(Memo::new(|| false));
611 /// let _ = group;
612 /// ```
613 pub fn disabled_signal(self, disabled: Memo<bool>) -> Self {
614 self.disabled(disabled)
615 }
616
617 /// Sets vertical or horizontal option flow.
618 ///
619 /// # Examples
620 ///
621 /// ```
622 /// use ailloli_ui_widgets::controls::{RadioDirection, RadioGroup};
623 /// let group: RadioGroup<i32, ()> = RadioGroup::new().direction(RadioDirection::Horizontal);
624 /// let _ = group;
625 /// ```
626 pub fn direction(mut self, direction: RadioDirection) -> Self {
627 self.direction = direction;
628 self
629 }
630
631 /// Selects vertical top-to-bottom option flow.
632 ///
633 /// # Examples
634 ///
635 /// ```
636 /// use ailloli_ui_widgets::controls::RadioGroup;
637 /// let group: RadioGroup<i32, ()> = RadioGroup::new().vertical();
638 /// let _ = group;
639 /// ```
640 pub fn vertical(mut self) -> Self {
641 self.direction = RadioDirection::Vertical;
642 self
643 }
644
645 /// Selects horizontal left-to-right option flow.
646 ///
647 /// # Examples
648 ///
649 /// ```
650 /// use ailloli_ui_widgets::controls::RadioGroup;
651 /// let group: RadioGroup<i32, ()> = RadioGroup::new().horizontal();
652 /// let _ = group;
653 /// ```
654 pub fn horizontal(mut self) -> Self {
655 self.direction = RadioDirection::Horizontal;
656 self
657 }
658
659 /// Replaces complete colors and option geometry.
660 ///
661 /// # Examples
662 ///
663 /// ```
664 /// use ailloli_ui_widgets::controls::{RadioGroup, RadioStyle};
665 /// let group: RadioGroup<i32, ()> = RadioGroup::new().radio_style(RadioStyle::default());
666 /// let _ = group;
667 /// ```
668 pub fn radio_style(mut self, style: RadioStyle) -> Self {
669 self.style = style;
670 self
671 }
672
673 /// Replaces style with a default-theme built-in size.
674 ///
675 /// # Examples
676 ///
677 /// ```
678 /// use ailloli_ui_widgets::controls::{RadioGroup, RadioSize};
679 /// let group: RadioGroup<i32, ()> = RadioGroup::new().radio_size(RadioSize::Compact);
680 /// let _ = group;
681 /// ```
682 pub fn radio_size(mut self, size: RadioSize) -> Self {
683 self.style = RadioStyle::from_theme(Theme::default(), size);
684 self
685 }
686
687 /// Maps each distinct enabled selection to an application action.
688 ///
689 /// The callback does not make a controlled source writable; use [`Self::bind`]
690 /// for two-way state.
691 ///
692 /// # Examples
693 ///
694 /// ```
695 /// use ailloli_ui_widgets::controls::RadioGroup;
696 /// #[derive(Clone)]
697 /// enum Action { Selected(i32) }
698 /// let group = RadioGroup::new().option(1, "One").on_change(Action::Selected);
699 /// let _ = group;
700 /// ```
701 pub fn on_change(mut self, f: impl Fn(T) -> A + 'static) -> Self {
702 self.on_change = Some(Rc::new(move |ctx, next| ctx.dispatch(f(next))));
703 self
704 }
705
706 /// Installs a context-aware selection handler.
707 ///
708 /// # Examples
709 ///
710 /// ```
711 /// use ailloli_ui_widgets::controls::RadioGroup;
712 /// let group = RadioGroup::<i32, ()>::new()
713 /// .option(1, "One")
714 /// .on_change_ctx(|_ctx, value| assert_eq!(value, 1));
715 /// let _ = group;
716 /// ```
717 pub fn on_change_ctx(mut self, f: impl Fn(&mut EventCtx<A>, T) + 'static) -> Self {
718 self.on_change = Some(Rc::new(f));
719 self
720 }
721
722 /// Sets preferred width from logical pixels or an explicit `Length`.
723 ///
724 /// # Examples
725 ///
726 /// ```
727 /// use ailloli_ui_widgets::controls::RadioGroup;
728 /// let _ = RadioGroup::<i32, ()>::new().width(240.0);
729 /// ```
730 pub fn width(mut self, value: impl Into<ailloli_ui_core::style::Length>) -> Self {
731 self.layout.width = value.into();
732 self
733 }
734
735 /// Sets preferred height from logical pixels or an explicit `Length`.
736 ///
737 /// # Examples
738 ///
739 /// ```
740 /// use ailloli_ui_widgets::controls::RadioGroup;
741 /// let _ = RadioGroup::<i32, ()>::new().height(120.0);
742 /// ```
743 pub fn height(mut self, value: impl Into<ailloli_ui_core::style::Length>) -> Self {
744 self.layout.height = value.into();
745 self
746 }
747
748 /// Sets the minimum resolved width.
749 ///
750 /// # Examples
751 ///
752 /// ```
753 /// use ailloli_ui_widgets::controls::RadioGroup;
754 /// let _ = RadioGroup::<i32, ()>::new().min_width(120.0);
755 /// ```
756 pub fn min_width(mut self, value: impl Into<ailloli_ui_core::style::Length>) -> Self {
757 self.layout.min_width = value.into();
758 self
759 }
760
761 /// Sets the maximum resolved width.
762 ///
763 /// # Examples
764 ///
765 /// ```
766 /// use ailloli_ui_widgets::controls::RadioGroup;
767 /// let _ = RadioGroup::<i32, ()>::new().max_width(400.0);
768 /// ```
769 pub fn max_width(mut self, value: impl Into<ailloli_ui_core::style::Length>) -> Self {
770 self.layout.max_width = value.into();
771 self
772 }
773
774 /// Sets the minimum resolved height.
775 ///
776 /// # Examples
777 ///
778 /// ```
779 /// use ailloli_ui_widgets::controls::RadioGroup;
780 /// let _ = RadioGroup::<i32, ()>::new().min_height(28.0);
781 /// ```
782 pub fn min_height(mut self, value: impl Into<ailloli_ui_core::style::Length>) -> Self {
783 self.layout.min_height = value.into();
784 self
785 }
786
787 /// Sets the maximum resolved height.
788 ///
789 /// # Examples
790 ///
791 /// ```
792 /// use ailloli_ui_widgets::controls::RadioGroup;
793 /// let _ = RadioGroup::<i32, ()>::new().max_height(300.0);
794 /// ```
795 pub fn max_height(mut self, value: impl Into<ailloli_ui_core::style::Length>) -> Self {
796 self.layout.max_height = value.into();
797 self
798 }
799
800 /// Marks both axes as parent-fill.
801 ///
802 /// # Examples
803 ///
804 /// ```
805 /// use ailloli_ui_widgets::controls::RadioGroup;
806 /// let _ = RadioGroup::<i32, ()>::new().fill();
807 /// ```
808 pub fn fill(mut self) -> Self {
809 self.layout.width = ailloli_ui_core::style::Length::Fill;
810 self.layout.height = ailloli_ui_core::style::Length::Fill;
811 self
812 }
813
814 /// Marks width as parent-fill while preserving height.
815 ///
816 /// # Examples
817 ///
818 /// ```
819 /// use ailloli_ui_widgets::controls::RadioGroup;
820 /// let _ = RadioGroup::<i32, ()>::new().fill_width();
821 /// ```
822 pub fn fill_width(mut self) -> Self {
823 self.layout.width = ailloli_ui_core::style::Length::Fill;
824 self
825 }
826
827 /// Marks height as parent-fill while preserving width.
828 ///
829 /// # Examples
830 ///
831 /// ```
832 /// use ailloli_ui_widgets::controls::RadioGroup;
833 /// let _ = RadioGroup::<i32, ()>::new().fill_height();
834 /// ```
835 pub fn fill_height(mut self) -> Self {
836 self.layout.height = ailloli_ui_core::style::Length::Fill;
837 self
838 }
839
840 /// Sets the same logical-pixel margin on every side.
841 ///
842 /// # Examples
843 ///
844 /// ```
845 /// use ailloli_ui_widgets::controls::RadioGroup;
846 /// let _ = RadioGroup::<i32, ()>::new().margin(8.0);
847 /// ```
848 pub fn margin(mut self, value: f32) -> Self {
849 self.layout = self.layout.margin(value);
850 self
851 }
852
853 /// Sets the same logical-pixel layout padding on every side.
854 ///
855 /// This is separate from `RadioStyle::option_padding_x`.
856 ///
857 /// # Examples
858 ///
859 /// ```
860 /// use ailloli_ui_widgets::controls::RadioGroup;
861 /// let _ = RadioGroup::<i32, ()>::new().padding(4.0);
862 /// ```
863 pub fn padding(mut self, value: f32) -> Self {
864 self.layout = self.layout.padding(value);
865 self
866 }
867
868 /// Sets the dimensionless parent flex-grow weight to one.
869 ///
870 /// # Examples
871 ///
872 /// ```
873 /// use ailloli_ui_widgets::controls::RadioGroup;
874 /// let _ = RadioGroup::<i32, ()>::new().flex_grow();
875 /// ```
876 pub fn flex_grow(mut self) -> Self {
877 self.flex_item = self.flex_item.flex_grow(1.0);
878 self
879 }
880
881 /// Sets the dimensionless parent flex-grow weight.
882 ///
883 /// # Examples
884 ///
885 /// ```
886 /// use ailloli_ui_widgets::controls::RadioGroup;
887 /// let _ = RadioGroup::<i32, ()>::new().flex_grow_by(2.0);
888 /// ```
889 pub fn flex_grow_by(mut self, value: f32) -> Self {
890 self.flex_item = self.flex_item.flex_grow(value);
891 self
892 }
893
894 /// Sets the dimensionless parent flex-shrink weight.
895 ///
896 /// # Examples
897 ///
898 /// ```
899 /// use ailloli_ui_widgets::controls::RadioGroup;
900 /// let _ = RadioGroup::<i32, ()>::new().flex_shrink(0.5);
901 /// ```
902 pub fn flex_shrink(mut self, value: f32) -> Self {
903 self.flex_item = self.flex_item.flex_shrink(value);
904 self
905 }
906
907 /// Sets the preferred parent main-axis flex basis.
908 ///
909 /// # Examples
910 ///
911 /// ```
912 /// use ailloli_ui_widgets::controls::RadioGroup;
913 /// let _ = RadioGroup::<i32, ()>::new().flex_basis(160.0);
914 /// ```
915 pub fn flex_basis(mut self, value: impl Into<ailloli_ui_core::style::Length>) -> Self {
916 self.flex_item = self.flex_item.flex_basis(value);
917 self
918 }
919
920 /// Overrides this item's parent cross-axis alignment.
921 ///
922 /// # Examples
923 ///
924 /// ```
925 /// use ailloli_ui_core::style::AlignItems;
926 /// use ailloli_ui_widgets::controls::RadioGroup;
927 /// let _ = RadioGroup::<i32, ()>::new().align_self(AlignItems::End);
928 /// ```
929 pub fn align_self(mut self, value: ailloli_ui_core::style::AlignItems) -> Self {
930 self.flex_item = self.flex_item.align_self(value);
931 self
932 }
933}
934
935/// Retained standalone radio widget.
936struct RadioButtonWidget<A> {
937 /// Outer logical sizing policy.
938 layout: LayoutStyle,
939 /// User-visible option label.
940 label: String,
941 /// Readable checked-state source.
942 checked: Binding<bool>,
943 /// Optional writable checked state for controlled interaction.
944 bound: Option<Signal<bool>>,
945 /// Reactive interaction-disable flag.
946 disabled: Binding<bool>,
947 /// Optional action invoked when an enabled unchecked option is selected.
948 on_select: Option<ClickAction<A>>,
949 /// Indicator and label colors plus logical-pixel geometry.
950 style: RadioStyle,
951}
952
953/// Retained typed group widget implementing navigation and painting.
954struct RadioGroupWidget<T, A> {
955 /// Outer logical sizing policy.
956 layout: LayoutStyle,
957 /// Ordered value/label options.
958 options: Vec<RadioOption<T>>,
959 /// Optional readable selected value.
960 selected: Option<Binding<T>>,
961 /// Optional writable selected value.
962 bound: Option<Signal<T>>,
963 /// Reactive interaction-disable flag for the whole group.
964 disabled: Binding<bool>,
965 /// Row or column option arrangement.
966 direction: RadioDirection,
967 /// Optional callback receiving a changed value.
968 on_change: Option<ChangeHandler<T, A>>,
969 /// Indicator and label colors plus logical-pixel geometry.
970 style: RadioStyle,
971}
972
973#[derive(Debug, Clone, Copy)]
974/// Complete interaction flags for painting one radio option.
975struct RadioPaintState {
976 /// Whether its value is selected.
977 checked: bool,
978 /// Whether the button/group option is disabled.
979 disabled: bool,
980 /// Whether to paint focus around its circle.
981 focused: bool,
982 /// Whether the standalone button is hovered.
983 hovered: bool,
984 /// Whether the standalone button is pressed.
985 pressed: bool,
986}
987
988impl<A: 'static> Widget<A> for RadioButtonWidget<A> {
989 fn debug_name(&self) -> &'static str {
990 "RadioButton"
991 }
992
993 fn layout(
994 &self,
995 _engine: &mut ailloli_ui_runtime::layout::LayoutEngine<'_, A>,
996 ctx: &mut LayoutCtx<'_>,
997 _children: &mut [LayoutChild],
998 constraints: Constraints,
999 ) -> LayoutResult {
1000 let label = measure_text(ctx.text_system.as_deref_mut(), &self.label, self.style.text);
1001 let intrinsic = Size::new(
1002 self.style.option_padding_x * 2.0
1003 + self.style.outer_size
1004 + self.style.label_gap
1005 + label.w,
1006 self.style.option_height.max(label.h),
1007 );
1008 let size = apply_layout_size(intrinsic, self.layout, constraints);
1009 let paint_bounds = Rect::new(0.0, 0.0, size.w, size.h);
1010 LayoutResult {
1011 size,
1012 children: Vec::new(),
1013 paint_bounds,
1014 visual_bounds: self.style.visual_bounds(paint_bounds),
1015 overlay_hit_bounds: Vec::new(),
1016 clip: None,
1017 is_window_root_clip: false,
1018 artifact: None,
1019 }
1020 }
1021
1022 fn paint(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, _layout_result: &LayoutResult) {
1023 paint_radio_option(
1024 ctx,
1025 bounds,
1026 &self.label,
1027 RadioPaintState {
1028 checked: self.checked.read(),
1029 disabled: self.disabled.read(),
1030 focused: ctx.interaction().focused,
1031 hovered: ctx.interaction().hovered,
1032 pressed: ctx.interaction().pressed,
1033 },
1034 &self.style,
1035 );
1036 }
1037
1038 fn event(&self, ctx: &mut EventCtx<A>, event: &Event, bounds: Rect, _layout: &LayoutResult) {
1039 if self.disabled.read() {
1040 return;
1041 }
1042
1043 match event {
1044 Event::Pointer(PointerEvent::Button {
1045 pos,
1046 button: MouseButton::Left,
1047 pressed: false,
1048 ..
1049 }) if bounds.contains(pos.x, pos.y) => self.select(ctx),
1050 Event::Keyboard(key) if key.state == KeyState::Pressed => {
1051 if matches!(
1052 &key.key,
1053 Key::Named(NamedKey::Enter) | Key::Named(NamedKey::Space)
1054 ) {
1055 self.select(ctx);
1056 }
1057 }
1058 _ => {}
1059 }
1060 }
1061
1062 fn focus_policy(&self) -> FocusPolicy {
1063 if self.disabled.read() {
1064 FocusPolicy::NotFocusable
1065 } else {
1066 FocusPolicy::Focusable
1067 }
1068 }
1069
1070 fn activation_policy(&self) -> ActivationPolicy {
1071 ActivationPolicy::SuppressOnFocusOnly
1072 }
1073}
1074
1075impl<A: 'static> RadioButtonWidget<A> {
1076 /// Writes `true`/runs the action for a writable unchecked button.
1077 fn select(&self, ctx: &mut EventCtx<A>) {
1078 if self.checked.read() || (self.bound.is_none() && self.on_select.is_none()) {
1079 return;
1080 }
1081 if let Some(bound) = &self.bound {
1082 bound.set(true);
1083 }
1084 if let Some(on_select) = &self.on_select {
1085 on_select.run(ctx);
1086 }
1087 ctx.request_repaint();
1088 ctx.stop_propagation();
1089 }
1090}
1091
1092impl<T: Clone + PartialEq + 'static, A: 'static> Widget<A> for RadioGroupWidget<T, A> {
1093 fn debug_name(&self) -> &'static str {
1094 "RadioGroup"
1095 }
1096
1097 fn layout(
1098 &self,
1099 _engine: &mut ailloli_ui_runtime::layout::LayoutEngine<'_, A>,
1100 ctx: &mut LayoutCtx<'_>,
1101 _children: &mut [LayoutChild],
1102 constraints: Constraints,
1103 ) -> LayoutResult {
1104 let intrinsic = group_intrinsic_size(
1105 &self.options,
1106 &self.style,
1107 self.direction,
1108 ctx.text_system.as_deref_mut(),
1109 );
1110 let size = apply_layout_size(intrinsic, self.layout, constraints);
1111 let paint_bounds = Rect::new(0.0, 0.0, size.w, size.h);
1112 LayoutResult {
1113 size,
1114 children: Vec::new(),
1115 paint_bounds,
1116 visual_bounds: self.style.visual_bounds(paint_bounds),
1117 overlay_hit_bounds: Vec::new(),
1118 clip: None,
1119 is_window_root_clip: false,
1120 artifact: None,
1121 }
1122 }
1123
1124 fn paint(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, _layout_result: &LayoutResult) {
1125 let selected = self.selected_value();
1126 let disabled = self.disabled.read();
1127 let focus_index = self.focus_index(selected.as_ref(), disabled);
1128 let rects = option_rects(bounds, &self.options, &self.style, self.direction);
1129
1130 for (idx, option) in self.options.iter().enumerate() {
1131 let option_disabled = disabled || option.disabled.read();
1132 let checked = selected
1133 .as_ref()
1134 .is_some_and(|value| value == &option.value);
1135 paint_radio_option(
1136 ctx,
1137 rects[idx],
1138 &option.label,
1139 RadioPaintState {
1140 checked,
1141 disabled: option_disabled,
1142 focused: ctx.interaction().focused && focus_index == Some(idx),
1143 hovered: false,
1144 pressed: false,
1145 },
1146 &self.style,
1147 );
1148 }
1149 }
1150
1151 fn event(&self, ctx: &mut EventCtx<A>, event: &Event, bounds: Rect, _layout: &LayoutResult) {
1152 if self.disabled.read() {
1153 return;
1154 }
1155
1156 match event {
1157 Event::Pointer(PointerEvent::Button {
1158 pos,
1159 button: MouseButton::Left,
1160 pressed: false,
1161 ..
1162 }) => {
1163 if let Some(index) = self.option_at(bounds, pos.x, pos.y) {
1164 self.select_index(ctx, index);
1165 }
1166 }
1167 Event::Keyboard(key) if key.state == KeyState::Pressed => {
1168 let selected = self.selected_value();
1169 let target = match &key.key {
1170 Key::Named(NamedKey::Enter) | Key::Named(NamedKey::Space) => {
1171 self.activation_index(selected.as_ref())
1172 }
1173 Key::Named(NamedKey::ArrowDown) | Key::Named(NamedKey::ArrowRight) => {
1174 self.next_enabled_index(selected.as_ref())
1175 }
1176 Key::Named(NamedKey::ArrowUp) | Key::Named(NamedKey::ArrowLeft) => {
1177 self.previous_enabled_index(selected.as_ref())
1178 }
1179 Key::Named(NamedKey::Home) => self.first_enabled_index(),
1180 Key::Named(NamedKey::End) => self.last_enabled_index(),
1181 _ => None,
1182 };
1183 if let Some(index) = target {
1184 self.select_index(ctx, index);
1185 }
1186 }
1187 _ => {}
1188 }
1189 }
1190
1191 fn focus_policy(&self) -> FocusPolicy {
1192 if self.disabled.read() || self.first_enabled_index().is_none() {
1193 FocusPolicy::NotFocusable
1194 } else {
1195 FocusPolicy::Focusable
1196 }
1197 }
1198
1199 fn activation_policy(&self) -> ActivationPolicy {
1200 ActivationPolicy::SuppressOnFocusOnly
1201 }
1202}
1203
1204impl<T: Clone + PartialEq + 'static, A: 'static> RadioGroupWidget<T, A> {
1205 /// Reads optional controlled or bound selection.
1206 fn selected_value(&self) -> Option<T> {
1207 self.selected.as_ref().map(Binding::read)
1208 }
1209
1210 /// Finds the first option equal to a selected value.
1211 fn selected_index(&self, selected: Option<&T>) -> Option<usize> {
1212 let selected = selected?;
1213 self.options
1214 .iter()
1215 .position(|option| &option.value == selected)
1216 }
1217
1218 /// Chooses the enabled selection or first enabled option for focus painting.
1219 fn focus_index(&self, selected: Option<&T>, disabled: bool) -> Option<usize> {
1220 if disabled {
1221 None
1222 } else {
1223 self.activation_index(selected)
1224 }
1225 }
1226
1227 /// Hit-tests current direction-specific option rectangles.
1228 fn option_at(&self, bounds: Rect, x: f32, y: f32) -> Option<usize> {
1229 option_rects(bounds, &self.options, &self.style, self.direction)
1230 .into_iter()
1231 .position(|rect| rect.contains(x, y))
1232 }
1233
1234 /// Writes/notifies a distinct enabled option when an output path exists.
1235 fn select_index(&self, ctx: &mut EventCtx<A>, index: usize) {
1236 let Some(option) = self.options.get(index) else {
1237 return;
1238 };
1239 if option.disabled.read() {
1240 return;
1241 }
1242 if self
1243 .selected_value()
1244 .as_ref()
1245 .is_some_and(|value| value == &option.value)
1246 {
1247 return;
1248 }
1249 if self.bound.is_none() && self.on_change.is_none() {
1250 return;
1251 }
1252
1253 let next = option.value.clone();
1254 if let Some(bound) = &self.bound {
1255 bound.set(next.clone());
1256 }
1257 if let Some(on_change) = &self.on_change {
1258 on_change(ctx, next);
1259 }
1260 ctx.request_repaint();
1261 ctx.stop_propagation();
1262 }
1263
1264 /// Activates the enabled selection or falls back to first enabled.
1265 fn activation_index(&self, selected: Option<&T>) -> Option<usize> {
1266 self.selected_index(selected)
1267 .filter(|idx| self.option_enabled(*idx))
1268 .or_else(|| self.first_enabled_index())
1269 }
1270
1271 /// Wraps forward through enabled options.
1272 fn next_enabled_index(&self, selected: Option<&T>) -> Option<usize> {
1273 let len = self.options.len();
1274 if len == 0 {
1275 return None;
1276 }
1277 let start = self.selected_index(selected).unwrap_or(len - 1);
1278 (1..=len)
1279 .map(|offset| (start + offset) % len)
1280 .find(|idx| self.option_enabled(*idx))
1281 }
1282
1283 /// Wraps backward through enabled options.
1284 fn previous_enabled_index(&self, selected: Option<&T>) -> Option<usize> {
1285 let len = self.options.len();
1286 if len == 0 {
1287 return None;
1288 }
1289 let start = self.selected_index(selected).unwrap_or(0);
1290 (1..=len)
1291 .map(|offset| (start + len - offset) % len)
1292 .find(|idx| self.option_enabled(*idx))
1293 }
1294
1295 /// Returns the first enabled option index.
1296 fn first_enabled_index(&self) -> Option<usize> {
1297 self.options
1298 .iter()
1299 .enumerate()
1300 .find_map(|(idx, _)| self.option_enabled(idx).then_some(idx))
1301 }
1302
1303 /// Returns the last enabled option index.
1304 fn last_enabled_index(&self) -> Option<usize> {
1305 self.options
1306 .iter()
1307 .enumerate()
1308 .rev()
1309 .find_map(|(idx, _)| self.option_enabled(idx).then_some(idx))
1310 }
1311
1312 /// Reads whether an indexed option exists and is enabled.
1313 fn option_enabled(&self, index: usize) -> bool {
1314 self.options
1315 .get(index)
1316 .is_some_and(|option| !option.disabled.read())
1317 }
1318}
1319
1320impl<A: 'static> IntoView<A> for RadioButton<A> {
1321 fn into_view(self) -> View<A> {
1322 finish_view_sized(
1323 View::leaf(RadioButtonWidget {
1324 layout: self.layout,
1325 label: self.label,
1326 checked: self.checked,
1327 bound: self.bound,
1328 disabled: self.disabled,
1329 on_select: self.on_select,
1330 style: self.style,
1331 }),
1332 self.flex_item,
1333 LayoutSizeHint::from_layout(self.layout),
1334 )
1335 }
1336}
1337
1338impl<T: Clone + PartialEq + 'static, A: 'static> IntoView<A> for RadioGroup<T, A> {
1339 fn into_view(self) -> View<A> {
1340 finish_view_sized(
1341 View::leaf(RadioGroupWidget {
1342 layout: self.layout,
1343 options: self.options,
1344 selected: self.selected,
1345 bound: self.bound,
1346 disabled: self.disabled,
1347 direction: self.direction,
1348 on_change: self.on_change,
1349 style: self.style,
1350 }),
1351 self.flex_item,
1352 LayoutSizeHint::from_layout(self.layout),
1353 )
1354 }
1355}
1356
1357/// Measures vertical max-width/summed-height or horizontal summed-width layout.
1358fn group_intrinsic_size<T>(
1359 options: &[RadioOption<T>],
1360 style: &RadioStyle,
1361 direction: RadioDirection,
1362 mut text_system: Option<&mut TextSystem>,
1363) -> Size {
1364 if options.is_empty() {
1365 return Size::new(0.0, 0.0);
1366 }
1367 let mut widths = Vec::with_capacity(options.len());
1368 for option in options {
1369 let label = measure_text(text_system.as_deref_mut(), &option.label, style.text);
1370 widths.push(option_width(label.w, style));
1371 }
1372
1373 match direction {
1374 RadioDirection::Vertical => {
1375 let width = widths.into_iter().fold(0.0_f32, f32::max);
1376 let height = options.len() as f32 * style.option_height
1377 + (options.len().saturating_sub(1)) as f32 * style.option_gap;
1378 Size::new(width.ceil(), height.ceil())
1379 }
1380 RadioDirection::Horizontal => {
1381 let width = widths.iter().sum::<f32>()
1382 + (options.len().saturating_sub(1)) as f32 * style.option_gap;
1383 Size::new(width.ceil(), style.option_height.ceil())
1384 }
1385 }
1386}
1387
1388/// Generates full-width vertical or content-width horizontal option rectangles.
1389fn option_rects<T>(
1390 bounds: Rect,
1391 options: &[RadioOption<T>],
1392 style: &RadioStyle,
1393 direction: RadioDirection,
1394) -> Vec<Rect> {
1395 let mut rects = Vec::with_capacity(options.len());
1396 match direction {
1397 RadioDirection::Vertical => {
1398 let mut y = bounds.y;
1399 for _ in options {
1400 rects.push(Rect::new(bounds.x, y, bounds.w, style.option_height));
1401 y += style.option_height + style.option_gap;
1402 }
1403 }
1404 RadioDirection::Horizontal => {
1405 let mut x = bounds.x;
1406 for option in options {
1407 let width = option_width(estimate_text_width(&option.label, style.text), style);
1408 rects.push(Rect::new(x, bounds.y, width, style.option_height));
1409 x += width + style.option_gap;
1410 }
1411 }
1412 }
1413 rects
1414}
1415
1416/// Adds horizontal insets, circle, label gap, and measured label width.
1417fn option_width(label_width: f32, style: &RadioStyle) -> f32 {
1418 style.option_padding_x * 2.0 + style.outer_size + style.label_gap + label_width
1419}
1420
1421/// Paints one radio circle, border, dot, focus ring, and label.
1422fn paint_radio_option(
1423 ctx: &mut PaintCtx<'_>,
1424 bounds: Rect,
1425 label: &str,
1426 state: RadioPaintState,
1427 style: &RadioStyle,
1428) {
1429 let opacity = if state.disabled {
1430 style.disabled_opacity
1431 } else {
1432 1.0
1433 };
1434 let outer = radio_outer_rect(bounds, style);
1435 let radius = Radius::uniform(style.outer_size * 0.5);
1436 let fill = if state.disabled {
1437 style.disabled_fill
1438 } else if state.checked {
1439 style.selected_fill
1440 } else if state.pressed {
1441 style.outer_fill_pressed
1442 } else if state.hovered {
1443 style.outer_fill_hovered
1444 } else {
1445 style.outer_fill
1446 };
1447
1448 ctx.push(DrawCmd::RRect(DrawRRect {
1449 rect: outer,
1450 radius: style.outer_size * 0.5,
1451 color: apply_opacity(fill, opacity),
1452 }));
1453
1454 let border = apply_border_opacity(
1455 if state.checked {
1456 style.selected_border
1457 } else {
1458 style.border
1459 },
1460 opacity,
1461 );
1462 if border.is_visible() {
1463 ctx.push(DrawCmd::Border(DrawBorder {
1464 rect: outer,
1465 radius,
1466 border,
1467 }));
1468 }
1469
1470 if state.checked {
1471 let dot = centered_square(outer, style.dot_size);
1472 ctx.push(DrawCmd::RRect(DrawRRect {
1473 rect: dot,
1474 radius: style.dot_size * 0.5,
1475 color: apply_opacity(style.dot_fill, opacity),
1476 }));
1477 }
1478
1479 if state.focused && !state.disabled && style.focus_ring.is_visible() {
1480 ctx.push(DrawCmd::Border(DrawBorder {
1481 rect: outer.inflate(style.focus_ring_offset, style.focus_ring_offset),
1482 radius: Radius::uniform(style.outer_size * 0.5 + style.focus_ring_offset),
1483 border: style.focus_ring,
1484 }));
1485 }
1486
1487 paint_label(ctx, label, bounds, style, state.disabled, opacity);
1488}
1489
1490/// Centers the outer circle vertically at the leading option inset.
1491fn radio_outer_rect(bounds: Rect, style: &RadioStyle) -> Rect {
1492 Rect::new(
1493 bounds.x + style.option_padding_x,
1494 bounds.y + (bounds.h - style.outer_size) * 0.5,
1495 style.outer_size,
1496 style.outer_size,
1497 )
1498}
1499
1500/// Centers a square of `size` within bounds.
1501fn centered_square(bounds: Rect, size: f32) -> Rect {
1502 Rect::new(
1503 bounds.x + (bounds.w - size) * 0.5,
1504 bounds.y + (bounds.h - size) * 0.5,
1505 size,
1506 size,
1507 )
1508}
1509
1510/// Shapes and vertically centers one unwrapped enabled/disabled label.
1511fn paint_label(
1512 ctx: &mut PaintCtx<'_>,
1513 label: &str,
1514 bounds: Rect,
1515 style: &RadioStyle,
1516 disabled: bool,
1517 opacity: f32,
1518) {
1519 let text_style = if disabled {
1520 style.disabled_text
1521 } else {
1522 style.text
1523 };
1524 let x = bounds.x + style.option_padding_x + style.outer_size + style.label_gap;
1525 let Some(text_system) = ctx.text_system.as_deref_mut() else {
1526 return;
1527 };
1528 let layout = text_system.layout_cached(TextLayoutParams {
1529 text: label,
1530 style: text_style,
1531 max_width: None,
1532 wrap_mode: WrapMode::NoWrap,
1533 });
1534 let baseline = layout
1535 .lines
1536 .first()
1537 .map(|line| line.baseline_y)
1538 .unwrap_or(0.0);
1539 let y = bounds.y + (bounds.h - layout.metrics.height) * 0.5 + baseline;
1540 ctx.push(DrawCmd::Text(DrawText {
1541 pos: [x, y],
1542 color: apply_opacity(text_style.color, opacity),
1543 decoration: ailloli_ui_core::TextDecoration::None,
1544 layout: layout.clone(),
1545 }));
1546}
1547
1548/// Measures unwrapped text through the text system or fallback estimate.
1549fn measure_text(text_system: Option<&mut TextSystem>, text: &str, style: TextStyle) -> Size {
1550 if let Some(text_system) = text_system {
1551 let layout = text_system.layout_cached(TextLayoutParams {
1552 text,
1553 style,
1554 max_width: None,
1555 wrap_mode: WrapMode::NoWrap,
1556 });
1557 Size::new(layout.metrics.width, layout.metrics.height)
1558 } else {
1559 Size::new(estimate_text_width(text, style), style.px_size as f32 * 1.2)
1560 }
1561}
1562
1563/// Estimates width as 0.58 em per Unicode scalar value.
1564fn estimate_text_width(text: &str, style: TextStyle) -> f32 {
1565 text.chars().count() as f32 * style.px_size as f32 * 0.58
1566}
1567
1568/// Multiplies alpha by `opacity` and clamps to `[0, 1]`.
1569fn apply_opacity(mut color: Color, opacity: f32) -> Color {
1570 color.a = (color.a * opacity).clamp(0.0, 1.0);
1571 color
1572}
1573
1574/// Applies opacity independently to each border-edge color.
1575fn apply_border_opacity(mut border: Border, opacity: f32) -> Border {
1576 border.colors.left = apply_opacity(border.colors.left, opacity);
1577 border.colors.top = apply_opacity(border.colors.top, opacity);
1578 border.colors.right = apply_opacity(border.colors.right, opacity);
1579 border.colors.bottom = apply_opacity(border.colors.bottom, opacity);
1580 border
1581}
1582
1583/// Returns the maximum per-edge border width.
1584fn max_border_width(border: Border) -> f32 {
1585 border
1586 .widths
1587 .left
1588 .max(border.widths.top)
1589 .max(border.widths.right)
1590 .max(border.widths.bottom)
1591}