ailloli_ui_widgets/controls/
list_view.rs

1//! Retained stacked lists and actionable list rows.
2
3use crate::layout::layout_ext::{apply_layout_size, finish_view_sized};
4use crate::layout::{Column, Container};
5use ailloli_ui_core::event::pointer::{MouseButton, PointerEvent};
6use ailloli_ui_core::event::{Event, Key, KeyState, NamedKey};
7use ailloli_ui_core::geometry::{Constraints, Rect, Size};
8use ailloli_ui_core::style::{
9    AlignItems, Border, FlexItemStyle, LayoutSizeHint, LayoutStyle, Radius,
10};
11use ailloli_ui_core::{Color, FontId, IconId, TextStyle, Theme};
12use ailloli_ui_runtime::component::{Binding, IntoView, View, Widget};
13use ailloli_ui_runtime::input::{
14    ActivationPolicy, ClickAction, EventCtx, FocusPolicy, IntoClickAction,
15};
16use ailloli_ui_runtime::layout::{LayoutChild, LayoutCtx, LayoutResult};
17use ailloli_ui_runtime::scene::PaintCtx;
18use ailloli_ui_runtime::{DrawBorder, DrawCmd, DrawImage, DrawRRect, DrawText};
19use ailloli_ui_text::{PreparedTextLayout, TextLayoutParams, WrapMode};
20use std::sync::Arc;
21
22#[derive(Clone, Debug, PartialEq)]
23/// Resolved container style and intrinsic width for a [`ListView`].
24///
25/// The backing container currently forwards only the top border width/color and
26/// top-left radius as uniform values; use uniform borders and radii.
27///
28/// # Examples
29///
30/// ```
31/// use ailloli_ui_core::Theme;
32/// use ailloli_ui_widgets::controls::ListViewStyle;
33/// let style = ListViewStyle::from_theme(Theme::dark());
34/// assert_eq!(style.width, 260.0);
35/// assert_eq!(style.gap, 2.0);
36/// ```
37pub struct ListViewStyle {
38    /// List container fill.
39    pub background: Color,
40    /// Container border; use uniform widths and colors.
41    pub border: Border,
42    /// Container radii; use a uniform value for current rendering.
43    pub radius: Radius,
44    /// Inner padding on every edge in logical pixels.
45    pub padding: f32,
46    /// Vertical gap between items in logical pixels.
47    pub gap: f32,
48    /// Intrinsic list width in logical pixels.
49    pub width: f32,
50}
51
52impl Default for ListViewStyle {
53    fn default() -> Self {
54        Self::from_theme(Theme::default())
55    }
56}
57
58impl ListViewStyle {
59    /// Resolves list container colors and metrics from `theme`.
60    ///
61    /// # Examples
62    ///
63    /// ```
64    /// use ailloli_ui_core::Theme;
65    /// use ailloli_ui_widgets::controls::ListViewStyle;
66    /// let style = ListViewStyle::from_theme(Theme::dark());
67    /// assert!(style.padding >= 0.0);
68    /// assert_eq!(style.width, 260.0);
69    /// ```
70    pub fn from_theme(theme: Theme) -> Self {
71        let palette = theme.palette();
72        Self {
73            background: palette.surface,
74            border: Border::new(1.0, palette.border),
75            radius: theme.radius().button(),
76            padding: theme.spacing().xs,
77            gap: 2.0,
78            width: 260.0,
79        }
80    }
81}
82
83/// A non-virtualized vertical stack of [`ListItem`] views.
84///
85/// Items are retained in insertion order, forced to fill the list width, and
86/// all laid out. The control supplies no scrolling or item reuse; large data
87/// sets should use a virtualized model-backed control instead.
88///
89/// # Examples
90///
91/// ```
92/// use ailloli_ui_widgets::controls::{ListItem, ListView};
93/// let list = ListView::<()>::new().item(ListItem::new("Profile"));
94/// let _ = list;
95/// ```
96pub struct ListView<A = ()> {
97    /// Layout applied to the backing container.
98    pub(crate) layout: LayoutStyle,
99    /// Flex-item behavior used by the parent layout.
100    pub(crate) flex_item: FlexItemStyle,
101    /// Resolved container paint and spacing.
102    style: ListViewStyle,
103    /// Item views in insertion order; no capacity bound or virtualization.
104    items: Vec<View<A>>,
105}
106
107crate::impl_layout_builders!(ListView);
108
109impl<A: 'static> Default for ListView<A> {
110    fn default() -> Self {
111        Self::new()
112    }
113}
114
115impl<A: 'static> ListView<A> {
116    /// Creates an empty list with default-theme style and a 260-pixel width.
117    ///
118    /// # Examples
119    ///
120    /// ```
121    /// use ailloli_ui_widgets::controls::ListView;
122    /// let list: ListView<()> = ListView::new();
123    /// let _ = list;
124    /// ```
125    pub fn new() -> Self {
126        let style = ListViewStyle::default();
127        Self {
128            layout: LayoutStyle::default().width(style.width),
129            flex_item: FlexItemStyle::default(),
130            style,
131            items: Vec::new(),
132        }
133    }
134
135    /// Replaces the complete container style and synchronizes layout width.
136    ///
137    /// A later explicit width layout builder may override the style width.
138    /// Values, including negative spacing, are accepted as-is.
139    ///
140    /// # Examples
141    ///
142    /// ```
143    /// use ailloli_ui_core::Theme;
144    /// use ailloli_ui_widgets::controls::{ListView, ListViewStyle};
145    /// let style = ListViewStyle::from_theme(Theme::dark());
146    /// let list: ListView<()> = ListView::new().list_view_style(style);
147    /// let _ = list;
148    /// ```
149    pub fn list_view_style(mut self, style: ListViewStyle) -> Self {
150        self.layout = self.layout.width(style.width);
151        self.style = style;
152        self
153    }
154
155    /// Appends one item and forces that item to fill the list width.
156    ///
157    /// Repeated calls preserve insertion order and grow an unbounded vector.
158    ///
159    /// # Examples
160    ///
161    /// ```
162    /// use ailloli_ui_widgets::controls::{ListItem, ListView};
163    /// let list = ListView::<()>::new()
164    ///     .item(ListItem::new("One"))
165    ///     .item(ListItem::new("Two"));
166    /// let _ = list;
167    /// ```
168    pub fn item(mut self, item: ListItem<A>) -> Self {
169        self.items.push(item.fill_width().into_view());
170        self
171    }
172}
173
174impl<A: 'static> IntoView<A> for ListView<A> {
175    fn into_view(self) -> View<A> {
176        let mut content = Column::new()
177            .gap(self.style.gap)
178            .align_items(AlignItems::Stretch);
179        for item in self.items {
180            content = content.child(item);
181        }
182
183        let mut container = Container::<A>::new()
184            .background(self.style.background)
185            .radius(self.style.radius.tl)
186            .border(self.style.border.widths.top, self.style.border.colors.top)
187            .padding(self.style.padding)
188            .child(content);
189        container.layout = self.layout;
190        container.flex_item = self.flex_item;
191        container.into_view()
192    }
193}
194
195#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
196/// Semantic title treatment for a [`ListItem`].
197///
198/// # Examples
199///
200/// ```
201/// use ailloli_ui_widgets::controls::ListItemVariant;
202/// assert_eq!(ListItemVariant::default(), ListItemVariant::Default);
203/// ```
204pub enum ListItemVariant {
205    /// Normal or selected title color.
206    #[default]
207    Default,
208    /// Danger title color; behavior and other paint remain unchanged.
209    Danger,
210}
211
212#[derive(Clone, Debug, PartialEq)]
213/// Resolved colors, typography, and logical-pixel metrics for a [`ListItem`].
214///
215/// # Examples
216///
217/// ```
218/// use ailloli_ui_core::Theme;
219/// use ailloli_ui_widgets::controls::ListItemStyle;
220/// let style = ListItemStyle::from_theme(Theme::dark());
221/// assert_eq!(style.height, 36.0);
222/// assert_eq!(style.subtitle_height, 52.0);
223/// ```
224pub struct ListItemStyle {
225    /// Intrinsic height without a subtitle.
226    pub height: f32,
227    /// Intrinsic height whenever `subtitle` is `Some`, even if empty.
228    pub subtitle_height: f32,
229    /// Horizontal content inset.
230    pub padding_x: f32,
231    /// Gap between content regions.
232    pub gap: f32,
233    /// Width and height of an optional leading icon.
234    pub icon_size: f32,
235    /// Background and focus-ring corner radii.
236    pub radius: Radius,
237    /// Idle background.
238    pub background: Color,
239    /// Actionable enabled hover background.
240    pub hover_background: Color,
241    /// Actionable enabled pressed background.
242    pub pressed_background: Color,
243    /// Background used whenever selected.
244    pub selected_background: Color,
245    /// Normal title style.
246    pub title_text: TextStyle,
247    /// Subtitle style.
248    pub subtitle_text: TextStyle,
249    /// Right-aligned trailing text style.
250    pub trailing_text: TextStyle,
251    /// Title style for [`ListItemVariant::Danger`].
252    pub danger_text: TextStyle,
253    /// Unselected leading-icon tint.
254    pub icon_tint: Color,
255    /// Selected leading-icon tint and default selected-title color.
256    pub selected_icon_tint: Color,
257    /// Numeric badge background.
258    pub badge_background: Color,
259    /// Numeric badge text style.
260    pub badge_text: TextStyle,
261    /// Border painted for focused, enabled, actionable items.
262    pub focus_ring: Border,
263    /// Alpha multiplier for disabled backgrounds, icons, and text.
264    pub disabled_opacity: f32,
265}
266
267impl Default for ListItemStyle {
268    fn default() -> Self {
269        Self::from_theme(Theme::default())
270    }
271}
272
273impl ListItemStyle {
274    /// Resolves row colors, typography, and geometry from `theme`.
275    ///
276    /// # Examples
277    ///
278    /// ```
279    /// use ailloli_ui_core::Theme;
280    /// use ailloli_ui_widgets::controls::ListItemStyle;
281    /// let style = ListItemStyle::from_theme(Theme::dark());
282    /// assert_eq!(style.icon_size, 16.0);
283    /// assert_eq!(style.disabled_opacity, 0.42);
284    /// ```
285    pub fn from_theme(theme: Theme) -> Self {
286        let palette = theme.palette();
287        Self {
288            height: 36.0,
289            subtitle_height: 52.0,
290            padding_x: 10.0,
291            gap: 8.0,
292            icon_size: 16.0,
293            radius: Radius::uniform(theme.radius().md),
294            background: Color::TRANSPARENT,
295            hover_background: palette.surface_elevated,
296            pressed_background: Color::hex_rgb(0x20252A),
297            selected_background: palette.accent.with_alpha(0.18),
298            title_text: TextStyle::new(FontId::Ui, 13, palette.text),
299            subtitle_text: TextStyle::new(FontId::Ui, 12, palette.text_muted),
300            trailing_text: TextStyle::new(FontId::Ui, 12, palette.text_muted),
301            danger_text: TextStyle::new(FontId::Ui, 13, palette.danger),
302            icon_tint: palette.text_muted,
303            selected_icon_tint: palette.accent,
304            badge_background: palette.surface_elevated,
305            badge_text: TextStyle::new(FontId::Ui, 11, palette.text),
306            focus_ring: Border::new(1.0, palette.focus),
307            disabled_opacity: 0.42,
308        }
309    }
310}
311
312/// One optional-action row for a [`ListView`].
313///
314/// Activation occurs on left-button release inside or a pressed Enter/Space
315/// key while focused. Only an enabled item with an action is focusable.
316/// Selection affects paint but does not suppress activation. No text is clipped
317/// or truncated by the row itself.
318///
319/// # Examples
320///
321/// ```
322/// use ailloli_ui_widgets::controls::ListItem;
323/// let item: ListItem<()> = ListItem::new("Downloads");
324/// let _ = item;
325/// ```
326pub struct ListItem<A = ()> {
327    /// Layout configuration used to resolve intrinsic geometry.
328    pub(crate) layout: LayoutStyle,
329    /// Flex-item behavior used by the parent layout.
330    pub(crate) flex_item: FlexItemStyle,
331    /// Owned primary text; empty is valid.
332    title: String,
333    /// Optional second line; `Some("")` still selects subtitle height.
334    subtitle: Option<String>,
335    /// Optional leading icon.
336    leading_icon: Option<IconId>,
337    /// Optional right-aligned text.
338    trailing_text: Option<String>,
339    /// Optional decimal badge count; zero is displayed as `0`.
340    badge: Option<u32>,
341    /// Live selected state.
342    selected: Binding<bool>,
343    /// Live disabled state.
344    disabled: Binding<bool>,
345    /// Semantic title treatment.
346    variant: ListItemVariant,
347    /// Resolved paint and metrics.
348    style: ListItemStyle,
349    /// Optional activation action.
350    on_select: Option<ClickAction<A>>,
351}
352
353crate::impl_layout_builders!(ListItem);
354
355impl<A: 'static> ListItem<A> {
356    /// Creates an enabled, unselected item with no optional content or action.
357    ///
358    /// # Examples
359    ///
360    /// ```
361    /// use ailloli_ui_widgets::controls::ListItem;
362    /// let item: ListItem<()> = ListItem::new("Settings");
363    /// let _ = item;
364    /// ```
365    pub fn new(title: impl Into<String>) -> Self {
366        Self {
367            layout: LayoutStyle::default(),
368            flex_item: FlexItemStyle::default(),
369            title: title.into(),
370            subtitle: None,
371            leading_icon: None,
372            trailing_text: None,
373            badge: None,
374            selected: Binding::Static(false),
375            disabled: Binding::Static(false),
376            variant: ListItemVariant::Default,
377            style: ListItemStyle::default(),
378            on_select: None,
379        }
380    }
381
382    /// Sets a second line, replacing any previous subtitle.
383    ///
384    /// An empty string still changes intrinsic height to `subtitle_height`.
385    ///
386    /// # Examples
387    ///
388    /// ```
389    /// use ailloli_ui_widgets::controls::ListItem;
390    /// let item: ListItem<()> = ListItem::new("Account").subtitle("Signed in");
391    /// let _ = item;
392    /// ```
393    pub fn subtitle(mut self, subtitle: impl Into<String>) -> Self {
394        self.subtitle = Some(subtitle.into());
395        self
396    }
397
398    /// Sets the leading icon, replacing any prior icon.
399    ///
400    /// # Examples
401    ///
402    /// ```
403    /// use ailloli_ui_core::IconId;
404    /// use ailloli_ui_widgets::controls::ListItem;
405    /// let item: ListItem<()> = ListItem::new("History").leading_icon(IconId::History);
406    /// let _ = item;
407    /// ```
408    pub fn leading_icon(mut self, icon: IconId) -> Self {
409        self.leading_icon = Some(icon);
410        self
411    }
412
413    /// Sets right-aligned trailing text, replacing any previous value.
414    ///
415    /// # Examples
416    ///
417    /// ```
418    /// use ailloli_ui_widgets::controls::ListItem;
419    /// let item: ListItem<()> = ListItem::new("Version").trailing_text("1.0");
420    /// let _ = item;
421    /// ```
422    pub fn trailing_text(mut self, text: impl Into<String>) -> Self {
423        self.trailing_text = Some(text.into());
424        self
425    }
426
427    /// Sets a decimal numeric badge, replacing any previous count.
428    ///
429    /// Every `u32` value is accepted, including zero; no compact `99+` sentinel
430    /// is applied.
431    ///
432    /// # Examples
433    ///
434    /// ```
435    /// use ailloli_ui_widgets::controls::ListItem;
436    /// let item: ListItem<()> = ListItem::new("Inbox").badge(12);
437    /// let _ = item;
438    /// ```
439    pub fn badge(mut self, count: u32) -> Self {
440        self.badge = Some(count);
441        self
442    }
443
444    /// Sets static or reactive selected state.
445    ///
446    /// Selected background takes precedence over pressed/hover state. A danger
447    /// item keeps danger title color while its icon uses selected tint.
448    ///
449    /// # Examples
450    ///
451    /// ```
452    /// use ailloli_ui_widgets::controls::ListItem;
453    /// let item: ListItem<()> = ListItem::new("Current").selected(true);
454    /// let _ = item;
455    /// ```
456    pub fn selected(mut self, selected: impl Into<Binding<bool>>) -> Self {
457        self.selected = selected.into();
458        self
459    }
460
461    /// Sets static or reactive disabled state.
462    ///
463    /// Disabled items ignore events, are not focusable, and multiply paint
464    /// alpha by [`ListItemStyle::disabled_opacity`].
465    ///
466    /// # Examples
467    ///
468    /// ```
469    /// use ailloli_ui_widgets::controls::ListItem;
470    /// let item: ListItem<()> = ListItem::new("Unavailable").disabled(true);
471    /// let _ = item;
472    /// ```
473    pub fn disabled(mut self, disabled: impl Into<Binding<bool>>) -> Self {
474        self.disabled = disabled.into();
475        self
476    }
477
478    /// Selects normal or danger title treatment.
479    ///
480    /// # Examples
481    ///
482    /// ```
483    /// use ailloli_ui_widgets::controls::{ListItem, ListItemVariant};
484    /// let item: ListItem<()> = ListItem::new("Delete").variant(ListItemVariant::Danger);
485    /// let _ = item;
486    /// ```
487    pub fn variant(mut self, variant: ListItemVariant) -> Self {
488        self.variant = variant;
489        self
490    }
491
492    /// Replaces complete resolved row style and intrinsic metrics.
493    ///
494    /// Values are accepted as-is; layout builders may override intrinsic size.
495    ///
496    /// # Examples
497    ///
498    /// ```
499    /// use ailloli_ui_core::Theme;
500    /// use ailloli_ui_widgets::controls::{ListItem, ListItemStyle};
501    /// let style = ListItemStyle::from_theme(Theme::dark());
502    /// let item: ListItem<()> = ListItem::new("Styled").list_item_style(style);
503    /// let _ = item;
504    /// ```
505    pub fn list_item_style(mut self, style: ListItemStyle) -> Self {
506        self.style = style;
507        self
508    }
509
510    /// Installs an action value emitted on activation.
511    ///
512    /// A later action builder replaces it. The item stops propagation after
513    /// running the action.
514    ///
515    /// # Examples
516    ///
517    /// ```
518    /// use ailloli_ui_widgets::controls::ListItem;
519    /// #[derive(Clone)]
520    /// enum Action { Open }
521    /// let item = ListItem::new("Project").on_select(Action::Open);
522    /// let _ = item;
523    /// ```
524    pub fn on_select(mut self, action: impl IntoClickAction<A>) -> Self
525    where
526        A: Clone,
527    {
528        self.on_select = Some(action.into_click_action());
529        self
530    }
531
532    /// Installs a context-aware activation handler.
533    ///
534    /// A later action builder replaces it.
535    ///
536    /// # Examples
537    ///
538    /// ```
539    /// use ailloli_ui_widgets::controls::ListItem;
540    /// let item = ListItem::<()>::new("Refresh").on_select_ctx(|ctx| ctx.request_repaint());
541    /// let _ = item;
542    /// ```
543    pub fn on_select_ctx(mut self, f: impl Fn(&mut EventCtx<A>) + 'static) -> Self {
544        self.on_select = Some(ClickAction::handler(f));
545        self
546    }
547}
548
549/// Retained leaf resolving item bindings, paint state, and activation.
550struct ListItemWidget<A> {
551    /// Outer logical sizing policy.
552    layout: LayoutStyle,
553    /// Primary user-visible item title.
554    title: String,
555    /// Optional secondary line below the title.
556    subtitle: Option<String>,
557    /// Optional icon painted before the text stack.
558    leading_icon: Option<IconId>,
559    /// Optional trailing text.
560    trailing_text: Option<String>,
561    /// Optional numeric trailing badge.
562    badge: Option<u32>,
563    /// Reactive selected-state source.
564    selected: Binding<bool>,
565    /// Reactive interaction-disable flag.
566    disabled: Binding<bool>,
567    /// Compact or standard row presentation.
568    variant: ListItemVariant,
569    /// Row colors and logical-pixel geometry.
570    style: ListItemStyle,
571    /// Optional click action invoked for an enabled item.
572    on_select: Option<ClickAction<A>>,
573}
574
575impl<A: 'static> Widget<A> for ListItemWidget<A> {
576    fn debug_name(&self) -> &'static str {
577        "ListItem"
578    }
579
580    fn layout(
581        &self,
582        _engine: &mut ailloli_ui_runtime::layout::LayoutEngine<'_, A>,
583        ctx: &mut LayoutCtx<'_>,
584        _children: &mut [LayoutChild],
585        constraints: Constraints,
586    ) -> LayoutResult {
587        let title_w = measure_text(ctx, &self.title, self.title_style(false)).unwrap_or(80.0);
588        let subtitle_w = self
589            .subtitle
590            .as_deref()
591            .and_then(|text| measure_text(ctx, text, self.style.subtitle_text))
592            .unwrap_or(0.0);
593        let icon_w = self
594            .leading_icon
595            .as_ref()
596            .map(|_| self.style.icon_size + self.style.gap)
597            .unwrap_or(0.0);
598        let trailing_w = self
599            .trailing_text
600            .as_deref()
601            .and_then(|text| measure_text(ctx, text, self.style.trailing_text))
602            .unwrap_or(0.0);
603        let badge_w = self
604            .badge
605            .map(|count| measure_badge(ctx, count, &self.style))
606            .unwrap_or(0.0);
607        let height = if self.subtitle.is_some() {
608            self.style.subtitle_height
609        } else {
610            self.style.height
611        };
612        let intrinsic = Size::new(
613            self.style.padding_x * 2.0
614                + icon_w
615                + title_w.max(subtitle_w)
616                + trailing_w
617                + badge_w
618                + self.style.gap,
619            height,
620        );
621        let size = apply_layout_size(intrinsic, self.layout, constraints);
622        LayoutResult {
623            size,
624            children: Vec::new(),
625            paint_bounds: Rect::new(0.0, 0.0, size.w, size.h),
626            visual_bounds: Rect::new(0.0, 0.0, size.w, size.h),
627            overlay_hit_bounds: Vec::new(),
628            clip: None,
629            is_window_root_clip: false,
630            artifact: None,
631        }
632    }
633
634    fn paint(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, _layout: &LayoutResult) {
635        let selected = self.selected.read();
636        let disabled = self.disabled.read();
637        let interaction = ctx.interaction();
638        let mut bg = self.style.background;
639        if selected {
640            bg = self.style.selected_background;
641        } else if interaction.pressed && self.on_select.is_some() && !disabled {
642            bg = self.style.pressed_background;
643        } else if interaction.hovered && self.on_select.is_some() && !disabled {
644            bg = self.style.hover_background;
645        }
646
647        let opacity = if disabled {
648            self.style.disabled_opacity
649        } else {
650            1.0
651        };
652        if bg.a > 0.0 {
653            ctx.push(DrawCmd::RRect(DrawRRect {
654                rect: bounds,
655                radius: self.style.radius.tl,
656                color: bg.with_alpha(bg.a * opacity),
657            }));
658        }
659
660        let mut x = bounds.x + self.style.padding_x;
661        if let Some(icon) = &self.leading_icon {
662            let rect = Rect::new(
663                x,
664                bounds.y + (bounds.h - self.style.icon_size) * 0.5,
665                self.style.icon_size,
666                self.style.icon_size,
667            );
668            let tint = if selected {
669                self.style.selected_icon_tint
670            } else {
671                self.style.icon_tint
672            };
673            ctx.push(DrawCmd::Image(DrawImage {
674                rect,
675                icon: icon.clone(),
676                tint: tint.with_alpha(tint.a * opacity),
677                rotation_rad: 0.0,
678            }));
679            x += self.style.icon_size + self.style.gap;
680        }
681
682        if let Some(subtitle) = &self.subtitle {
683            paint_text_at(
684                ctx,
685                &self.title,
686                self.title_style(selected),
687                x,
688                bounds.y + 19.0,
689                opacity,
690            );
691            paint_text_at(
692                ctx,
693                subtitle,
694                self.style.subtitle_text,
695                x,
696                bounds.y + 37.0,
697                opacity,
698            );
699        } else {
700            paint_text_centered(
701                ctx,
702                &self.title,
703                self.title_style(selected),
704                bounds,
705                x,
706                opacity,
707            );
708        }
709
710        let mut right = bounds.right() - self.style.padding_x;
711        if let Some(count) = self.badge {
712            right = paint_badge(ctx, count, bounds, right, &self.style, opacity) - self.style.gap;
713        }
714        if let Some(trailing) = &self.trailing_text {
715            paint_trailing_text(
716                ctx,
717                trailing,
718                self.style.trailing_text,
719                bounds,
720                right,
721                opacity,
722            );
723        }
724
725        if interaction.focused && self.on_select.is_some() && !disabled {
726            ctx.push(DrawCmd::Border(DrawBorder {
727                rect: bounds,
728                radius: self.style.radius,
729                border: self.style.focus_ring,
730            }));
731        }
732    }
733
734    fn event(&self, ctx: &mut EventCtx<A>, event: &Event, bounds: Rect, _layout: &LayoutResult) {
735        if self.disabled.read() {
736            return;
737        }
738        match event {
739            Event::Pointer(PointerEvent::Button {
740                pos,
741                button: MouseButton::Left,
742                pressed: false,
743                ..
744            }) if bounds.contains(pos.x, pos.y) => self.run_action(ctx),
745            Event::Keyboard(key) if key.state == KeyState::Pressed => {
746                if matches!(
747                    &key.key,
748                    Key::Named(NamedKey::Enter) | Key::Named(NamedKey::Space)
749                ) {
750                    self.run_action(ctx);
751                }
752            }
753            _ => {}
754        }
755    }
756
757    fn focus_policy(&self) -> FocusPolicy {
758        if self.on_select.is_some() && !self.disabled.read() {
759            FocusPolicy::Focusable
760        } else {
761            FocusPolicy::NotFocusable
762        }
763    }
764
765    fn activation_policy(&self) -> ActivationPolicy {
766        ActivationPolicy::SuppressOnFocusOnly
767    }
768}
769
770impl<A> ListItemWidget<A> {
771    /// Runs the optional action and consumes input; otherwise does nothing.
772    fn run_action(&self, ctx: &mut EventCtx<A>) {
773        if let Some(on_select) = &self.on_select {
774            on_select.run(ctx);
775            ctx.stop_propagation();
776        }
777    }
778
779    /// Resolves danger first, then selected, then normal title paint.
780    fn title_style(&self, selected: bool) -> TextStyle {
781        if self.variant == ListItemVariant::Danger {
782            self.style.danger_text
783        } else if selected {
784            TextStyle {
785                color: self.style.selected_icon_tint,
786                ..self.style.title_text
787            }
788        } else {
789            self.style.title_text
790        }
791    }
792}
793
794impl<A: 'static> IntoView<A> for ListItem<A> {
795    fn into_view(self) -> View<A> {
796        finish_view_sized(
797            View::leaf(ListItemWidget {
798                layout: self.layout,
799                title: self.title,
800                subtitle: self.subtitle,
801                leading_icon: self.leading_icon,
802                trailing_text: self.trailing_text,
803                badge: self.badge,
804                selected: self.selected,
805                disabled: self.disabled,
806                variant: self.variant,
807                style: self.style,
808                on_select: self.on_select,
809            }),
810            self.flex_item,
811            LayoutSizeHint::from_layout(self.layout),
812        )
813    }
814}
815
816/// Measures one unwrapped line, returning `None` without a text system.
817fn measure_text(ctx: &mut LayoutCtx<'_>, text: &str, style: TextStyle) -> Option<f32> {
818    ctx.text_system.as_deref_mut().map(|text_system| {
819        text_system
820            .layout_cached(TextLayoutParams {
821                text,
822                style,
823                max_width: None,
824                wrap_mode: WrapMode::NoWrap,
825            })
826            .metrics
827            .width
828    })
829}
830
831/// Prepares one unwrapped line, returning `None` without a text system.
832fn layout_text(
833    ctx: &mut PaintCtx<'_>,
834    text: &str,
835    style: TextStyle,
836) -> Option<Arc<PreparedTextLayout>> {
837    ctx.text_system.as_deref_mut().map(|text_system| {
838        text_system.layout_cached(TextLayoutParams {
839            text,
840            style,
841            max_width: None,
842            wrap_mode: WrapMode::NoWrap,
843        })
844    })
845}
846
847/// Paints text at an explicit baseline with alpha multiplication.
848fn paint_text_at(
849    ctx: &mut PaintCtx<'_>,
850    text: &str,
851    style: TextStyle,
852    x: f32,
853    baseline_y: f32,
854    opacity: f32,
855) {
856    let Some(layout) = layout_text(ctx, text, style) else {
857        return;
858    };
859    ctx.push(DrawCmd::Text(DrawText {
860        pos: [x, baseline_y],
861        color: style.color.with_alpha(style.color.a * opacity),
862        decoration: ailloli_ui_core::TextDecoration::None,
863        layout,
864    }));
865}
866
867/// Paints left-anchored text vertically centered within row bounds.
868fn paint_text_centered(
869    ctx: &mut PaintCtx<'_>,
870    text: &str,
871    style: TextStyle,
872    bounds: Rect,
873    x: f32,
874    opacity: f32,
875) {
876    let Some(layout) = layout_text(ctx, text, style) else {
877        return;
878    };
879    let baseline = layout
880        .lines
881        .first()
882        .map(|line| line.baseline_y)
883        .unwrap_or(0.0);
884    let y = bounds.y + (bounds.h - layout.metrics.height) * 0.5 + baseline;
885    ctx.push(DrawCmd::Text(DrawText {
886        pos: [x, y],
887        color: style.color.with_alpha(style.color.a * opacity),
888        decoration: ailloli_ui_core::TextDecoration::None,
889        layout,
890    }));
891}
892
893/// Paints text right-aligned to `right` and vertically centered.
894fn paint_trailing_text(
895    ctx: &mut PaintCtx<'_>,
896    text: &str,
897    style: TextStyle,
898    bounds: Rect,
899    right: f32,
900    opacity: f32,
901) {
902    let Some(layout) = layout_text(ctx, text, style) else {
903        return;
904    };
905    let baseline = layout
906        .lines
907        .first()
908        .map(|line| line.baseline_y)
909        .unwrap_or(0.0);
910    let x = right - layout.metrics.width;
911    let y = bounds.y + (bounds.h - layout.metrics.height) * 0.5 + baseline;
912    ctx.push(DrawCmd::Text(DrawText {
913        pos: [x, y],
914        color: style.color.with_alpha(style.color.a * opacity),
915        decoration: ailloli_ui_core::TextDecoration::None,
916        layout,
917    }));
918}
919
920/// Estimates numeric badge width with eight-pixel glyph and padding floors.
921fn measure_badge(ctx: &mut LayoutCtx<'_>, count: u32, style: &ListItemStyle) -> f32 {
922    let label = count.to_string();
923    let text_w = measure_text(ctx, &label, style.badge_text).unwrap_or(8.0);
924    text_w.max(8.0) + 16.0
925}
926
927/// Paints a numeric pill and returns its left edge, or `right` without text support.
928fn paint_badge(
929    ctx: &mut PaintCtx<'_>,
930    count: u32,
931    bounds: Rect,
932    right: f32,
933    style: &ListItemStyle,
934    opacity: f32,
935) -> f32 {
936    let label = count.to_string();
937    let Some(layout) = layout_text(ctx, &label, style.badge_text) else {
938        return right;
939    };
940    let w = (layout.metrics.width + 12.0).max(20.0);
941    let h = 18.0;
942    let rect = Rect::new(right - w, bounds.y + (bounds.h - h) * 0.5, w, h);
943    ctx.push(DrawCmd::RRect(DrawRRect {
944        rect,
945        radius: h * 0.5,
946        color: style
947            .badge_background
948            .with_alpha(style.badge_background.a * opacity),
949    }));
950    let baseline = layout
951        .lines
952        .first()
953        .map(|line| line.baseline_y)
954        .unwrap_or(0.0);
955    let x = rect.x + (rect.w - layout.metrics.width) * 0.5;
956    let y = rect.y + (rect.h - layout.metrics.height) * 0.5 + baseline;
957    ctx.push(DrawCmd::Text(DrawText {
958        pos: [x, y],
959        color: style
960            .badge_text
961            .color
962            .with_alpha(style.badge_text.color.a * opacity),
963        decoration: ailloli_ui_core::TextDecoration::None,
964        layout,
965    }));
966    rect.x
967}