ailloli_ui_widgets/controls/
disclosure_row.rs

1//! Single-line disclosure rows with optional leading and trailing content.
2
3use crate::layout::layout_ext::{apply_layout_size, finish_view_sized};
4use ailloli_ui_core::event::pointer::{MouseButton, PointerEvent};
5use ailloli_ui_core::event::{Event, Key, KeyState, NamedKey};
6use ailloli_ui_core::geometry::{Constraints, Rect, Size};
7use ailloli_ui_core::style::{Border, FlexItemStyle, LayoutSizeHint, LayoutStyle, Radius};
8use ailloli_ui_core::{Color, FontId, IconId, TextStyle, Theme};
9use ailloli_ui_runtime::component::{Binding, IntoView, View, Widget};
10use ailloli_ui_runtime::input::{ClickAction, EventCtx, FocusPolicy, IntoClickAction};
11use ailloli_ui_runtime::layout::{LayoutChild, LayoutCtx, LayoutResult};
12use ailloli_ui_runtime::scene::PaintCtx;
13use ailloli_ui_runtime::{DrawBorder, DrawCmd, DrawImage, DrawRRect, DrawText};
14use ailloli_ui_text::{PreparedTextLayout, TextLayoutParams, WrapMode};
15use lucide_icons::Icon as LucideIcon;
16use std::sync::Arc;
17
18#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
19/// Semantic text treatment for a [`DisclosureRow`].
20///
21/// # Examples
22///
23/// ```
24/// use ailloli_ui_widgets::controls::DisclosureRowVariant;
25/// assert_eq!(DisclosureRowVariant::default(), DisclosureRowVariant::Default);
26/// ```
27pub enum DisclosureRowVariant {
28    /// Normal theme text color.
29    #[default]
30    Default,
31    /// Danger-colored label; interaction behavior is unchanged.
32    Danger,
33}
34
35#[derive(Clone, Debug, PartialEq)]
36/// Resolved colors, typography, and logical-pixel metrics for a disclosure row.
37///
38/// # Examples
39///
40/// ```
41/// use ailloli_ui_core::Theme;
42/// use ailloli_ui_widgets::controls::DisclosureRowStyle;
43/// let style = DisclosureRowStyle::from_theme(Theme::dark());
44/// assert_eq!(style.height, 38.0);
45/// assert_eq!(style.disabled_opacity, 0.42);
46/// ```
47pub struct DisclosureRowStyle {
48    /// Intrinsic row height in logical pixels.
49    pub height: f32,
50    /// Leading and trailing inset in logical pixels.
51    pub padding_x: f32,
52    /// Gap between content regions in logical pixels.
53    pub gap: f32,
54    /// Width and height of the optional leading icon in logical pixels.
55    pub icon_size: f32,
56    /// Width and height of the disclosure chevron in logical pixels.
57    pub chevron_size: f32,
58    /// Background and focus-ring corner radii.
59    pub radius: Radius,
60    /// Idle background color.
61    pub background: Color,
62    /// Background used while an actionable row is hovered.
63    pub hover_background: Color,
64    /// Background used while an actionable row is pressed.
65    pub pressed_background: Color,
66    /// Background used whenever the selected binding is true.
67    pub selected_background: Color,
68    /// Default label style.
69    pub text: TextStyle,
70    /// Optional trailing-label style.
71    pub trailing_text: TextStyle,
72    /// Label style for [`DisclosureRowVariant::Danger`].
73    pub danger_text: TextStyle,
74    /// Leading-icon tint.
75    pub icon_tint: Color,
76    /// Chevron tint.
77    pub chevron_tint: Color,
78    /// Border painted for a focused, enabled, actionable row.
79    pub focus_ring: Border,
80    /// Alpha multiplier for disabled backgrounds, icons, and text.
81    pub disabled_opacity: f32,
82}
83
84impl Default for DisclosureRowStyle {
85    fn default() -> Self {
86        Self::from_theme(Theme::default())
87    }
88}
89
90impl DisclosureRowStyle {
91    /// Resolves row colors and metrics from `theme`.
92    ///
93    /// The returned opacity is `0.42`; values are not clamped if the caller
94    /// later mutates the public fields.
95    ///
96    /// # Examples
97    ///
98    /// ```
99    /// use ailloli_ui_core::Theme;
100    /// use ailloli_ui_widgets::controls::DisclosureRowStyle;
101    /// let style = DisclosureRowStyle::from_theme(Theme::dark());
102    /// assert_eq!(style.padding_x, 12.0);
103    /// assert_eq!(style.icon_size, 16.0);
104    /// ```
105    pub fn from_theme(theme: Theme) -> Self {
106        let palette = theme.palette();
107        Self {
108            height: 38.0,
109            padding_x: 12.0,
110            gap: 8.0,
111            icon_size: 16.0,
112            chevron_size: 16.0,
113            radius: Radius::uniform(theme.radius().md),
114            background: Color::TRANSPARENT,
115            hover_background: palette.surface_elevated,
116            pressed_background: Color::hex_rgb(0x20252A),
117            selected_background: palette.accent.with_alpha(0.18),
118            text: TextStyle::new(FontId::Ui, 13, palette.text),
119            trailing_text: TextStyle::new(FontId::Ui, 12, palette.text_muted),
120            danger_text: TextStyle::new(FontId::Ui, 13, palette.danger),
121            icon_tint: palette.text_muted,
122            chevron_tint: palette.text_muted,
123            focus_ring: Border::new(1.0, palette.focus),
124            disabled_opacity: 0.42,
125        }
126    }
127}
128
129/// An optional-action row used to disclose a destination or secondary pane.
130///
131/// The row activates on a left-button release inside its bounds, or on a
132/// pressed Enter/Space key while focused. It is focusable only when enabled and
133/// an action is installed. Selection changes appearance but does not suppress
134/// activation. Bindings are read during layout, painting, and event handling.
135///
136/// # Examples
137///
138/// ```
139/// use ailloli_ui_widgets::controls::DisclosureRow;
140/// let row: DisclosureRow<()> = DisclosureRow::new("Advanced");
141/// let _ = row;
142/// ```
143pub struct DisclosureRow<A = ()> {
144    /// Layout configuration used to resolve intrinsic geometry.
145    pub(crate) layout: LayoutStyle,
146    /// Flex-item behavior used by the parent layout.
147    pub(crate) flex_item: FlexItemStyle,
148    /// Primary row label; empty text is valid.
149    label: String,
150    /// Optional icon shown before the label.
151    leading_icon: Option<IconId>,
152    /// Optional right-aligned text before the chevron.
153    trailing_text: Option<String>,
154    /// Live selected state.
155    selected: Binding<bool>,
156    /// Live disabled state.
157    disabled: Binding<bool>,
158    /// Semantic label treatment.
159    variant: DisclosureRowVariant,
160    /// Resolved paint and geometry configuration.
161    style: DisclosureRowStyle,
162    /// Whether to reserve and paint the trailing chevron.
163    show_chevron: bool,
164    /// Optional activation action.
165    on_select: Option<ClickAction<A>>,
166}
167
168crate::impl_layout_builders!(DisclosureRow);
169
170impl<A: 'static> DisclosureRow<A> {
171    /// Creates an enabled, unselected row with a chevron and no action.
172    ///
173    /// A row without an action is decorative and not focusable.
174    ///
175    /// # Examples
176    ///
177    /// ```
178    /// use ailloli_ui_widgets::controls::DisclosureRow;
179    /// let row: DisclosureRow<()> = DisclosureRow::new("Details");
180    /// let _ = row;
181    /// ```
182    pub fn new(label: impl Into<String>) -> Self {
183        Self {
184            layout: LayoutStyle::default(),
185            flex_item: FlexItemStyle::default(),
186            label: label.into(),
187            leading_icon: None,
188            trailing_text: None,
189            selected: Binding::Static(false),
190            disabled: Binding::Static(false),
191            variant: DisclosureRowVariant::Default,
192            style: DisclosureRowStyle::default(),
193            show_chevron: true,
194            on_select: None,
195        }
196    }
197
198    /// Sets the leading icon, replacing any previous icon.
199    ///
200    /// # Examples
201    ///
202    /// ```
203    /// use ailloli_ui_core::IconId;
204    /// use ailloli_ui_widgets::controls::DisclosureRow;
205    /// let row: DisclosureRow<()> = DisclosureRow::new("History").leading_icon(IconId::History);
206    /// let _ = row;
207    /// ```
208    pub fn leading_icon(mut self, icon: IconId) -> Self {
209        self.leading_icon = Some(icon);
210        self
211    }
212
213    /// Sets right-aligned secondary text, replacing any previous value.
214    ///
215    /// An empty string remains present and reserves only its leading gap when
216    /// a text system is available.
217    ///
218    /// # Examples
219    ///
220    /// ```
221    /// use ailloli_ui_widgets::controls::DisclosureRow;
222    /// let row: DisclosureRow<()> = DisclosureRow::new("Version").trailing_text("1.0");
223    /// let _ = row;
224    /// ```
225    pub fn trailing_text(mut self, text: impl Into<String>) -> Self {
226        self.trailing_text = Some(text.into());
227        self
228    }
229
230    /// Sets a static or reactive selected binding.
231    ///
232    /// Selection takes paint precedence over pressed and hovered backgrounds.
233    /// It does not alter focusability or action dispatch.
234    ///
235    /// # Examples
236    ///
237    /// ```
238    /// use ailloli_ui_widgets::controls::DisclosureRow;
239    /// let row: DisclosureRow<()> = DisclosureRow::new("Current").selected(true);
240    /// let _ = row;
241    /// ```
242    pub fn selected(mut self, selected: impl Into<Binding<bool>>) -> Self {
243        self.selected = selected.into();
244        self
245    }
246
247    /// Sets a static or reactive disabled binding.
248    ///
249    /// Disabled rows ignore events, cannot receive focus, and multiply painted
250    /// alpha by [`DisclosureRowStyle::disabled_opacity`].
251    ///
252    /// # Examples
253    ///
254    /// ```
255    /// use ailloli_ui_widgets::controls::DisclosureRow;
256    /// let row: DisclosureRow<()> = DisclosureRow::new("Unavailable").disabled(true);
257    /// let _ = row;
258    /// ```
259    pub fn disabled(mut self, disabled: impl Into<Binding<bool>>) -> Self {
260        self.disabled = disabled.into();
261        self
262    }
263
264    /// Selects the normal or danger label style.
265    ///
266    /// # Examples
267    ///
268    /// ```
269    /// use ailloli_ui_widgets::controls::{DisclosureRow, DisclosureRowVariant};
270    /// let row: DisclosureRow<()> =
271    ///     DisclosureRow::new("Delete").variant(DisclosureRowVariant::Danger);
272    /// let _ = row;
273    /// ```
274    pub fn variant(mut self, variant: DisclosureRowVariant) -> Self {
275        self.variant = variant;
276        self
277    }
278
279    /// Replaces all resolved style and intrinsic geometry values.
280    ///
281    /// Values are accepted as-is; explicit layout builders may override the
282    /// style's intrinsic height or measured width.
283    ///
284    /// # Examples
285    ///
286    /// ```
287    /// use ailloli_ui_core::Theme;
288    /// use ailloli_ui_widgets::controls::{DisclosureRow, DisclosureRowStyle};
289    /// let style = DisclosureRowStyle::from_theme(Theme::dark());
290    /// let row: DisclosureRow<()> = DisclosureRow::new("Details").disclosure_row_style(style);
291    /// let _ = row;
292    /// ```
293    pub fn disclosure_row_style(mut self, style: DisclosureRowStyle) -> Self {
294        self.style = style;
295        self
296    }
297
298    /// Controls whether a right-pointing chevron is reserved and painted.
299    ///
300    /// # Examples
301    ///
302    /// ```
303    /// use ailloli_ui_widgets::controls::DisclosureRow;
304    /// let row: DisclosureRow<()> = DisclosureRow::new("Static").show_chevron(false);
305    /// let _ = row;
306    /// ```
307    pub fn show_chevron(mut self, show: bool) -> Self {
308        self.show_chevron = show;
309        self
310    }
311
312    /// Installs an action value to emit on pointer or keyboard activation.
313    ///
314    /// A later action builder replaces the previous action. The row stops event
315    /// propagation after running it.
316    ///
317    /// # Examples
318    ///
319    /// ```
320    /// use ailloli_ui_widgets::controls::DisclosureRow;
321    /// #[derive(Clone)]
322    /// enum Action { Open }
323    /// let row = DisclosureRow::new("Advanced").on_select(Action::Open);
324    /// let _ = row;
325    /// ```
326    pub fn on_select(mut self, action: impl IntoClickAction<A>) -> Self
327    where
328        A: Clone,
329    {
330        self.on_select = Some(action.into_click_action());
331        self
332    }
333
334    /// Installs a context-aware activation handler.
335    ///
336    /// The handler may emit actions or request runtime effects through
337    /// [`EventCtx`]. A later action builder replaces it.
338    ///
339    /// # Examples
340    ///
341    /// ```
342    /// use ailloli_ui_widgets::controls::DisclosureRow;
343    /// let row = DisclosureRow::<()>::new("Advanced").on_select_ctx(|ctx| ctx.stop_propagation());
344    /// let _ = row;
345    /// ```
346    pub fn on_select_ctx(mut self, f: impl Fn(&mut EventCtx<A>) + 'static) -> Self {
347        self.on_select = Some(ClickAction::handler(f));
348        self
349    }
350}
351
352/// Retained leaf widget that reads bindings and handles activation.
353struct DisclosureRowWidget<A> {
354    /// Outer logical sizing policy.
355    layout: LayoutStyle,
356    /// Primary user-visible row label.
357    label: String,
358    /// Optional icon painted before the label.
359    leading_icon: Option<IconId>,
360    /// Optional secondary text painted at the trailing edge.
361    trailing_text: Option<String>,
362    /// Reactive selected-state source.
363    selected: Binding<bool>,
364    /// Reactive interaction-disable flag.
365    disabled: Binding<bool>,
366    /// Visual variant controlling row emphasis.
367    variant: DisclosureRowVariant,
368    /// Row colors and logical-pixel geometry.
369    style: DisclosureRowStyle,
370    /// Whether the trailing disclosure chevron is painted.
371    show_chevron: bool,
372    /// Optional click action invoked for an enabled row.
373    on_select: Option<ClickAction<A>>,
374}
375
376impl<A: 'static> Widget<A> for DisclosureRowWidget<A> {
377    fn debug_name(&self) -> &'static str {
378        "DisclosureRow"
379    }
380
381    fn layout(
382        &self,
383        _engine: &mut ailloli_ui_runtime::layout::LayoutEngine<'_, A>,
384        ctx: &mut LayoutCtx<'_>,
385        _children: &mut [LayoutChild],
386        constraints: Constraints,
387    ) -> LayoutResult {
388        let label_w = measure_text(ctx, &self.label, self.label_style()).unwrap_or(96.0);
389        let icon_w = self
390            .leading_icon
391            .as_ref()
392            .map(|_| self.style.icon_size + self.style.gap)
393            .unwrap_or(0.0);
394        let trailing_w = self
395            .trailing_text
396            .as_deref()
397            .and_then(|text| measure_text(ctx, text, self.style.trailing_text))
398            .map(|w| w + self.style.gap)
399            .unwrap_or(0.0);
400        let chevron_w = if self.show_chevron {
401            self.style.chevron_size
402        } else {
403            0.0
404        };
405        let intrinsic = Size::new(
406            self.style.padding_x * 2.0 + icon_w + label_w + trailing_w + chevron_w,
407            self.style.height,
408        );
409        let size = apply_layout_size(intrinsic, self.layout, constraints);
410        LayoutResult {
411            size,
412            children: Vec::new(),
413            paint_bounds: Rect::new(0.0, 0.0, size.w, size.h),
414            visual_bounds: Rect::new(0.0, 0.0, size.w, size.h),
415            overlay_hit_bounds: Vec::new(),
416            clip: None,
417            is_window_root_clip: false,
418            artifact: None,
419        }
420    }
421
422    fn paint(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, _layout: &LayoutResult) {
423        let selected = self.selected.read();
424        let disabled = self.disabled.read();
425        let interaction = ctx.interaction();
426        let mut bg = self.style.background;
427        if selected {
428            bg = self.style.selected_background;
429        } else if interaction.pressed && self.on_select.is_some() && !disabled {
430            bg = self.style.pressed_background;
431        } else if interaction.hovered && self.on_select.is_some() && !disabled {
432            bg = self.style.hover_background;
433        }
434
435        let opacity = if disabled {
436            self.style.disabled_opacity
437        } else {
438            1.0
439        };
440        if bg.a > 0.0 {
441            ctx.push(DrawCmd::RRect(DrawRRect {
442                rect: bounds,
443                radius: self.style.radius.tl,
444                color: bg.with_alpha(bg.a * opacity),
445            }));
446        }
447
448        let mut x = bounds.x + self.style.padding_x;
449        if let Some(icon) = &self.leading_icon {
450            let icon_rect = Rect::new(
451                x,
452                bounds.y + (bounds.h - self.style.icon_size) * 0.5,
453                self.style.icon_size,
454                self.style.icon_size,
455            );
456            ctx.push(DrawCmd::Image(DrawImage {
457                rect: icon_rect,
458                icon: icon.clone(),
459                tint: self
460                    .style
461                    .icon_tint
462                    .with_alpha(self.style.icon_tint.a * opacity),
463                rotation_rad: 0.0,
464            }));
465            x += self.style.icon_size + self.style.gap;
466        }
467
468        paint_text_centered(ctx, &self.label, self.label_style(), bounds, x, opacity);
469
470        let mut right = bounds.right() - self.style.padding_x;
471        if self.show_chevron {
472            let chevron_rect = Rect::new(
473                right - self.style.chevron_size,
474                bounds.y + (bounds.h - self.style.chevron_size) * 0.5,
475                self.style.chevron_size,
476                self.style.chevron_size,
477            );
478            ctx.push(DrawCmd::Image(DrawImage {
479                rect: chevron_rect,
480                icon: IconId::Lucide(LucideIcon::ChevronRight),
481                tint: self
482                    .style
483                    .chevron_tint
484                    .with_alpha(self.style.chevron_tint.a * opacity),
485                rotation_rad: 0.0,
486            }));
487            right = chevron_rect.x - self.style.gap;
488        }
489
490        if let Some(trailing) = &self.trailing_text {
491            paint_trailing_text(
492                ctx,
493                trailing,
494                self.style.trailing_text,
495                bounds,
496                right,
497                opacity,
498            );
499        }
500
501        if interaction.focused && self.on_select.is_some() && !disabled {
502            ctx.push(DrawCmd::Border(DrawBorder {
503                rect: bounds,
504                radius: self.style.radius,
505                border: self.style.focus_ring,
506            }));
507        }
508    }
509
510    fn event(&self, ctx: &mut EventCtx<A>, event: &Event, bounds: Rect, _layout: &LayoutResult) {
511        if self.disabled.read() {
512            return;
513        }
514        match event {
515            Event::Pointer(PointerEvent::Button {
516                pos,
517                button: MouseButton::Left,
518                pressed: false,
519                ..
520            }) if bounds.contains(pos.x, pos.y) => self.run_action(ctx),
521            Event::Keyboard(key) if key.state == KeyState::Pressed => {
522                if matches!(
523                    &key.key,
524                    Key::Named(NamedKey::Enter) | Key::Named(NamedKey::Space)
525                ) {
526                    self.run_action(ctx);
527                }
528            }
529            _ => {}
530        }
531    }
532
533    fn focus_policy(&self) -> FocusPolicy {
534        if self.on_select.is_some() && !self.disabled.read() {
535            FocusPolicy::Focusable
536        } else {
537            FocusPolicy::NotFocusable
538        }
539    }
540}
541
542impl<A> DisclosureRowWidget<A> {
543    /// Runs the installed action, then stops propagation; does nothing without one.
544    fn run_action(&self, ctx: &mut EventCtx<A>) {
545        if let Some(on_select) = &self.on_select {
546            on_select.run(ctx);
547            ctx.stop_propagation();
548        }
549    }
550
551    /// Resolves the label style from the semantic variant.
552    fn label_style(&self) -> TextStyle {
553        if self.variant == DisclosureRowVariant::Danger {
554            self.style.danger_text
555        } else {
556            self.style.text
557        }
558    }
559}
560
561impl<A: 'static> IntoView<A> for DisclosureRow<A> {
562    fn into_view(self) -> View<A> {
563        finish_view_sized(
564            View::leaf(DisclosureRowWidget {
565                layout: self.layout,
566                label: self.label,
567                leading_icon: self.leading_icon,
568                trailing_text: self.trailing_text,
569                selected: self.selected,
570                disabled: self.disabled,
571                variant: self.variant,
572                style: self.style,
573                show_chevron: self.show_chevron,
574                on_select: self.on_select,
575            }),
576            self.flex_item,
577            LayoutSizeHint::from_layout(self.layout),
578        )
579    }
580}
581
582/// Measures one unwrapped line, returning `None` when no text system is available.
583fn measure_text(ctx: &mut LayoutCtx<'_>, text: &str, style: TextStyle) -> Option<f32> {
584    ctx.text_system.as_deref_mut().map(|text_system| {
585        text_system
586            .layout_cached(TextLayoutParams {
587                text,
588                style,
589                max_width: None,
590                wrap_mode: WrapMode::NoWrap,
591            })
592            .metrics
593            .width
594    })
595}
596
597/// Creates one unwrapped prepared layout, or `None` without a text system.
598fn layout_text(
599    ctx: &mut PaintCtx<'_>,
600    text: &str,
601    style: TextStyle,
602) -> Option<Arc<PreparedTextLayout>> {
603    ctx.text_system.as_deref_mut().map(|text_system| {
604        text_system.layout_cached(TextLayoutParams {
605            text,
606            style,
607            max_width: None,
608            wrap_mode: WrapMode::NoWrap,
609        })
610    })
611}
612
613/// Paints left-anchored text vertically centered in `bounds`.
614fn paint_text_centered(
615    ctx: &mut PaintCtx<'_>,
616    text: &str,
617    style: TextStyle,
618    bounds: Rect,
619    x: f32,
620    opacity: f32,
621) {
622    let Some(layout) = layout_text(ctx, text, style) else {
623        return;
624    };
625    let baseline = layout
626        .lines
627        .first()
628        .map(|line| line.baseline_y)
629        .unwrap_or(0.0);
630    let y = bounds.y + (bounds.h - layout.metrics.height) * 0.5 + baseline;
631    ctx.push(DrawCmd::Text(DrawText {
632        pos: [x, y],
633        color: style.color.with_alpha(style.color.a * opacity),
634        decoration: ailloli_ui_core::TextDecoration::None,
635        layout,
636    }));
637}
638
639/// Paints text right-aligned to `right` and vertically centered in `bounds`.
640fn paint_trailing_text(
641    ctx: &mut PaintCtx<'_>,
642    text: &str,
643    style: TextStyle,
644    bounds: Rect,
645    right: f32,
646    opacity: f32,
647) {
648    let Some(layout) = layout_text(ctx, text, style) else {
649        return;
650    };
651    let baseline = layout
652        .lines
653        .first()
654        .map(|line| line.baseline_y)
655        .unwrap_or(0.0);
656    let x = right - layout.metrics.width;
657    let y = bounds.y + (bounds.h - layout.metrics.height) * 0.5 + baseline;
658    ctx.push(DrawCmd::Text(DrawText {
659        pos: [x, y],
660        color: style.color.with_alpha(style.color.a * opacity),
661        decoration: ailloli_ui_core::TextDecoration::None,
662        layout,
663    }));
664}