ailloli_ui_widgets/controls/
navigation.rs

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