ailloli_ui_widgets/controls/
badge.rs

1//! Compact informational badges, taxonomy tags, and dismissible chips.
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::{
8    Background, Border, BoxShadow, FlexItemStyle, LayoutSizeHint, LayoutStyle, Radius,
9};
10use ailloli_ui_core::{Color, FontId, IconId, TextStyle, Theme};
11use ailloli_ui_runtime::component::{Binding, IntoView, Memo, View, Widget};
12use ailloli_ui_runtime::input::{ClickAction, EventCtx, FocusPolicy, IntoClickAction};
13use ailloli_ui_runtime::layout::{LayoutChild, LayoutCtx, LayoutResult};
14use ailloli_ui_runtime::scene::PaintCtx;
15use ailloli_ui_runtime::{DrawBorder, DrawBoxShadow, DrawCmd, DrawImage, DrawRRect, DrawText};
16use ailloli_ui_text::{TextLayoutParams, TextSystem, WrapMode};
17
18#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
19/// Semantic color applied to a [`Badge`], [`Tag`], or [`Chip`].
20///
21/// # Examples
22///
23/// ```
24/// use ailloli_ui_widgets::controls::BadgeTone;
25/// let tones = [
26///     BadgeTone::Neutral,
27///     BadgeTone::Accent,
28///     BadgeTone::Danger,
29///     BadgeTone::Success,
30///     BadgeTone::Warning,
31///     BadgeTone::Info,
32///     BadgeTone::Muted,
33/// ];
34/// assert_eq!(tones.len(), 7);
35/// assert_eq!(BadgeTone::default(), BadgeTone::Neutral);
36/// ```
37pub enum BadgeTone {
38    /// Neutral surface emphasis; this is the default tone.
39    #[default]
40    Neutral,
41    /// Accent-brand emphasis.
42    Accent,
43    /// Destructive or error emphasis.
44    Danger,
45    /// Successful-state emphasis.
46    Success,
47    /// Warning-state emphasis.
48    Warning,
49    /// Informational-state emphasis.
50    Info,
51    /// Low-emphasis muted presentation.
52    Muted,
53}
54
55#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
56/// Container treatment applied around pill content.
57///
58/// # Examples
59///
60/// ```
61/// use ailloli_ui_widgets::controls::BadgeVariant;
62/// let variants = [
63///     BadgeVariant::Soft,
64///     BadgeVariant::Filled,
65///     BadgeVariant::Outline,
66///     BadgeVariant::Ghost,
67/// ];
68/// assert_eq!(variants.len(), 4);
69/// assert_eq!(BadgeVariant::default(), BadgeVariant::Soft);
70/// ```
71pub enum BadgeVariant {
72    /// Translucent or elevated fill with a subtle border; the default.
73    #[default]
74    Soft,
75    /// Solid tone-colored fill with no border.
76    Filled,
77    /// Transparent fill with a tone-colored border.
78    Outline,
79    /// Transparent fill with no border.
80    Ghost,
81}
82
83#[derive(Clone, Debug, PartialEq)]
84/// Resolved visual and logical-pixel geometry for pill controls.
85///
86/// Colors are derived from the selected tone and variant. Geometry is not
87/// validated: negative or non-finite custom values propagate into layout and
88/// paint calculations.
89///
90/// # Examples
91///
92/// ```
93/// use ailloli_ui_core::Theme;
94/// use ailloli_ui_widgets::controls::{BadgeStyle, BadgeTone, BadgeVariant};
95/// let style = BadgeStyle::from_theme(Theme::dark(), BadgeTone::Info, BadgeVariant::Soft);
96/// assert_eq!((style.height, style.padding_x, style.icon_size), (26.0, 9.0, 14.0));
97/// ```
98pub struct BadgeStyle {
99    /// Pill fill; the painter currently supports color backgrounds.
100    pub background: Background,
101    /// Per-edge border widths and colors.
102    pub border: Border,
103    /// Corner radii used by the fill, border, and shadows.
104    pub radius: Radius,
105    /// Painted shadows; unlike popup helpers, inset shadows are not filtered.
106    pub shadows: Vec<BoxShadow>,
107    /// Label text style.
108    pub text: TextStyle,
109    /// Numeric count text style.
110    pub count_text: TextStyle,
111    /// Tint for an optional leading icon.
112    pub icon_tint: Color,
113    /// Fill for an optional leading dot.
114    pub dot_color: Color,
115    /// Tint for a chip's close icon.
116    pub close_tint: Color,
117    /// Preferred pill height in logical pixels; text can make it taller.
118    pub height: f32,
119    /// Horizontal inset on each side in logical pixels.
120    pub padding_x: f32,
121    /// Horizontal spacing between content segments in logical pixels.
122    pub gap: f32,
123    /// Leading icon width and height in logical pixels.
124    pub icon_size: f32,
125    /// Leading dot diameter in logical pixels.
126    pub dot_size: f32,
127    /// Close icon width and height in logical pixels.
128    pub close_size: f32,
129    /// Reserved baseline offset; the current painter does not read this field.
130    pub baseline_shift: f32,
131    /// Alpha multiplier applied when a chip is disabled.
132    pub disabled_opacity: f32,
133}
134
135impl Default for BadgeStyle {
136    fn default() -> Self {
137        Self::from_theme(Theme::default(), BadgeTone::Neutral, BadgeVariant::Soft)
138    }
139}
140
141impl BadgeStyle {
142    /// Resolves badge/chip colors and default geometry from a theme.
143    ///
144    /// The result is 26 logical pixels high with 9-pixel horizontal padding.
145    ///
146    /// # Examples
147    ///
148    /// ```
149    /// use ailloli_ui_core::Theme;
150    /// use ailloli_ui_widgets::controls::{BadgeStyle, BadgeTone, BadgeVariant};
151    /// let style = BadgeStyle::from_theme(
152    ///     Theme::default(),
153    ///     BadgeTone::Success,
154    ///     BadgeVariant::Filled,
155    /// );
156    /// assert_eq!(style.height, 26.0);
157    /// assert_eq!(style.disabled_opacity, 0.45);
158    /// ```
159    pub fn from_theme(theme: Theme, tone: BadgeTone, variant: BadgeVariant) -> Self {
160        let palette = theme.palette();
161        let tone_color = tone_color(theme, tone);
162        let text_color = match (tone, variant) {
163            (BadgeTone::Neutral, BadgeVariant::Filled) => palette.text,
164            (BadgeTone::Muted, _) => palette.text_muted,
165            (_, BadgeVariant::Filled) => contrast_text_for(tone_color),
166            _ => tone_color,
167        };
168        let (background, border) = match variant {
169            BadgeVariant::Soft => (
170                Background::color(match tone {
171                    BadgeTone::Neutral => palette.surface_elevated,
172                    BadgeTone::Muted => palette.surface,
173                    _ => tone_color.with_alpha(0.16),
174                }),
175                Border::new(
176                    1.0,
177                    match tone {
178                        BadgeTone::Neutral | BadgeTone::Muted => palette.border,
179                        _ => tone_color.with_alpha(0.34),
180                    },
181                ),
182            ),
183            BadgeVariant::Filled => (Background::color(tone_color), Border::none()),
184            BadgeVariant::Outline => (Background::color(Color::TRANSPARENT), {
185                let color = if tone == BadgeTone::Neutral {
186                    palette.border
187                } else {
188                    tone_color.with_alpha(0.72)
189                };
190                Border::new(1.0, color)
191            }),
192            BadgeVariant::Ghost => (Background::color(Color::TRANSPARENT), Border::none()),
193        };
194
195        let text = TextStyle::new(FontId::Ui, 12, text_color);
196        Self {
197            background,
198            border,
199            radius: Radius::uniform(theme.radius().sm + 2.0),
200            shadows: Vec::new(),
201            text,
202            count_text: text,
203            icon_tint: text_color,
204            dot_color: tone_color,
205            close_tint: text_color.with_alpha(0.82),
206            height: 26.0,
207            padding_x: 9.0,
208            gap: 6.0,
209            icon_size: 14.0,
210            dot_size: 7.0,
211            close_size: 14.0,
212            baseline_shift: 0.0,
213            disabled_opacity: 0.45,
214        }
215    }
216
217    /// Resolves the shorter tag geometry from a theme.
218    ///
219    /// This starts from [`Self::from_theme`] and changes the height to 24
220    /// logical pixels and horizontal padding to 8 logical pixels.
221    ///
222    /// # Examples
223    ///
224    /// ```
225    /// use ailloli_ui_core::Theme;
226    /// use ailloli_ui_widgets::controls::{BadgeStyle, BadgeTone, BadgeVariant};
227    /// let style = BadgeStyle::tag_from_theme(
228    ///     Theme::default(),
229    ///     BadgeTone::Neutral,
230    ///     BadgeVariant::Outline,
231    /// );
232    /// assert_eq!((style.height, style.padding_x), (24.0, 8.0));
233    /// ```
234    pub fn tag_from_theme(theme: Theme, tone: BadgeTone, variant: BadgeVariant) -> Self {
235        let mut style = Self::from_theme(theme, tone, variant);
236        style.height = 24.0;
237        style.padding_x = 8.0;
238        style.text.px_size = 12;
239        style.count_text.px_size = 12;
240        style
241    }
242
243    /// Extends layout bounds to include every configured shadow.
244    fn visual_bounds(&self, rect: Rect) -> Rect {
245        self.shadows.iter().fold(rect, |bounds, shadow| {
246            union_rect(bounds, shadow.paint_bounds(rect))
247        })
248    }
249}
250
251#[derive(Debug, Clone, PartialEq, Eq)]
252/// Optional content painted before a pill label.
253enum Leading {
254    /// No leading content.
255    None,
256    /// A tinted icon.
257    Icon(IconId),
258    /// A tone-colored circular dot.
259    Dot,
260}
261
262#[derive(Debug, Clone, Copy, PartialEq, Eq)]
263/// Behavioral role of the shared pill widget.
264enum PillKind {
265    /// Informational badge.
266    Badge,
267    /// Informational taxonomy tag.
268    Tag,
269    /// Interactive dismissible chip.
270    Chip,
271}
272
273#[derive(Debug, Clone, PartialEq, Eq)]
274/// Shared visible content for badge-like controls.
275struct PillContent {
276    /// Unwrapped label text.
277    label: String,
278    /// Optional decimal count rendered after the label.
279    count: Option<u32>,
280    /// Optional leading icon or dot.
281    leading: Leading,
282    /// Whether to reserve and paint a close icon.
283    close: bool,
284}
285
286impl PillContent {
287    /// Creates label-only content with no count, leading mark, or close icon.
288    fn new(label: impl Into<String>) -> Self {
289        Self {
290            label: label.into(),
291            count: None,
292            leading: Leading::None,
293            close: false,
294        }
295    }
296}
297
298/// A non-interactive status label with optional count and leading mark.
299///
300/// It defaults to accent/soft styling. Empty labels and a count of zero remain
301/// visible values; repeated leading builder calls replace the prior mark.
302///
303/// # Examples
304///
305/// ```
306/// use ailloli_ui_widgets::controls::{Badge, BadgeTone};
307/// let badge = Badge::new("Inbox").tone(BadgeTone::Info).count(3);
308/// let _ = badge;
309/// ```
310pub struct Badge {
311    /// Layout constraints applied to the intrinsic pill size.
312    pub(crate) layout: LayoutStyle,
313    /// Flex behavior used by the parent layout.
314    pub(crate) flex_item: FlexItemStyle,
315    /// Semantic tone used when regenerating a themed style.
316    tone: BadgeTone,
317    /// Container variant used when regenerating a themed style.
318    variant: BadgeVariant,
319    /// Resolved visual style.
320    style: BadgeStyle,
321    /// Label, count, and leading content.
322    content: PillContent,
323}
324
325crate::impl_layout_builders_unit!(Badge);
326
327impl Badge {
328    /// Creates an accent/soft label with no count or leading mark.
329    ///
330    /// # Examples
331    ///
332    /// ```
333    /// use ailloli_ui_widgets::controls::Badge;
334    /// let badge = Badge::new("Beta");
335    /// let _ = badge;
336    /// ```
337    pub fn new(label: impl Into<String>) -> Self {
338        let tone = BadgeTone::Accent;
339        let variant = BadgeVariant::Soft;
340        Self {
341            layout: LayoutStyle::default(),
342            flex_item: FlexItemStyle::default(),
343            tone,
344            variant,
345            style: BadgeStyle::from_theme(Theme::default(), tone, variant),
346            content: PillContent::new(label),
347        }
348    }
349
350    /// Creates a badge with a leading tone-colored dot.
351    ///
352    /// # Examples
353    ///
354    /// ```
355    /// use ailloli_ui_widgets::controls::Badge;
356    /// let badge = Badge::dot("Online");
357    /// let _ = badge;
358    /// ```
359    pub fn dot(label: impl Into<String>) -> Self {
360        Self::new(label).leading_dot()
361    }
362
363    /// Selects a tone and regenerates style from the default theme.
364    ///
365    /// This replaces any custom style previously supplied with
366    /// [`Self::badge_style`].
367    ///
368    /// # Examples
369    ///
370    /// ```
371    /// use ailloli_ui_widgets::controls::{Badge, BadgeTone};
372    /// let badge = Badge::new("Failed").tone(BadgeTone::Danger);
373    /// let _ = badge;
374    /// ```
375    pub fn tone(mut self, tone: BadgeTone) -> Self {
376        self.tone = tone;
377        self.style = BadgeStyle::from_theme(Theme::default(), self.tone, self.variant);
378        self
379    }
380
381    /// Selects a variant and regenerates style from the default theme.
382    ///
383    /// # Examples
384    ///
385    /// ```
386    /// use ailloli_ui_widgets::controls::{Badge, BadgeVariant};
387    /// let badge = Badge::new("Stable").variant(BadgeVariant::Filled);
388    /// let _ = badge;
389    /// ```
390    pub fn variant(mut self, variant: BadgeVariant) -> Self {
391        self.variant = variant;
392        self.style = BadgeStyle::from_theme(Theme::default(), self.tone, self.variant);
393        self
394    }
395
396    /// Replaces the resolved style without changing stored tone/variant.
397    ///
398    /// A later [`Self::tone`] or [`Self::variant`] call regenerates the style.
399    ///
400    /// # Examples
401    ///
402    /// ```
403    /// use ailloli_ui_widgets::controls::{Badge, BadgeStyle};
404    /// let badge = Badge::new("Custom").badge_style(BadgeStyle::default());
405    /// let _ = badge;
406    /// ```
407    pub fn badge_style(mut self, style: BadgeStyle) -> Self {
408        self.style = style;
409        self
410    }
411
412    /// Sets the unsigned decimal count rendered after the label.
413    ///
414    /// Zero is rendered as `0`; a later call replaces the previous count.
415    ///
416    /// # Examples
417    ///
418    /// ```
419    /// use ailloli_ui_widgets::controls::Badge;
420    /// let badge = Badge::new("Alerts").count(0);
421    /// let _ = badge;
422    /// ```
423    pub fn count(mut self, count: u32) -> Self {
424        self.content.count = Some(count);
425        self
426    }
427
428    /// Sets a leading icon, replacing any dot or previous icon.
429    ///
430    /// # Examples
431    ///
432    /// ```
433    /// use ailloli_ui_core::IconId;
434    /// use ailloli_ui_widgets::controls::Badge;
435    /// let badge = Badge::new("History").leading_icon(IconId::History);
436    /// let _ = badge;
437    /// ```
438    pub fn leading_icon(mut self, icon: IconId) -> Self {
439        self.content.leading = Leading::Icon(icon);
440        self
441    }
442
443    /// Sets a leading dot, replacing any icon.
444    ///
445    /// # Examples
446    ///
447    /// ```
448    /// use ailloli_ui_widgets::controls::Badge;
449    /// let badge = Badge::new("Live").leading_dot();
450    /// let _ = badge;
451    /// ```
452    pub fn leading_dot(mut self) -> Self {
453        self.content.leading = Leading::Dot;
454        self
455    }
456}
457
458/// A compact non-interactive taxonomy label.
459///
460/// Tags default to neutral/outline styling and use the shorter tag geometry.
461///
462/// # Examples
463///
464/// ```
465/// use ailloli_ui_widgets::controls::{BadgeTone, Tag};
466/// let tag = Tag::new("Rust").tone(BadgeTone::Accent);
467/// let _ = tag;
468/// ```
469pub struct Tag {
470    /// Layout constraints applied to the intrinsic pill size.
471    pub(crate) layout: LayoutStyle,
472    /// Flex behavior used by the parent layout.
473    pub(crate) flex_item: FlexItemStyle,
474    /// Semantic tone used when regenerating a themed style.
475    tone: BadgeTone,
476    /// Container variant used when regenerating a themed style.
477    variant: BadgeVariant,
478    /// Resolved visual style.
479    style: BadgeStyle,
480    /// Label-only pill content.
481    content: PillContent,
482}
483
484crate::impl_layout_builders_unit!(Tag);
485
486impl Tag {
487    /// Creates a neutral/outline tag with no leading or trailing content.
488    ///
489    /// # Examples
490    ///
491    /// ```
492    /// use ailloli_ui_widgets::controls::Tag;
493    /// let tag = Tag::new("Desktop");
494    /// let _ = tag;
495    /// ```
496    pub fn new(label: impl Into<String>) -> Self {
497        let tone = BadgeTone::Neutral;
498        let variant = BadgeVariant::Outline;
499        Self {
500            layout: LayoutStyle::default(),
501            flex_item: FlexItemStyle::default(),
502            tone,
503            variant,
504            style: BadgeStyle::tag_from_theme(Theme::default(), tone, variant),
505            content: PillContent::new(label),
506        }
507    }
508
509    /// Selects a tone and regenerates tag style from the default theme.
510    ///
511    /// # Examples
512    ///
513    /// ```
514    /// use ailloli_ui_widgets::controls::{BadgeTone, Tag};
515    /// let tag = Tag::new("Blocked").tone(BadgeTone::Danger);
516    /// let _ = tag;
517    /// ```
518    pub fn tone(mut self, tone: BadgeTone) -> Self {
519        self.tone = tone;
520        self.style = BadgeStyle::tag_from_theme(Theme::default(), self.tone, self.variant);
521        self
522    }
523
524    /// Selects a variant and regenerates tag style from the default theme.
525    ///
526    /// # Examples
527    ///
528    /// ```
529    /// use ailloli_ui_widgets::controls::{BadgeVariant, Tag};
530    /// let tag = Tag::new("Pinned").variant(BadgeVariant::Ghost);
531    /// let _ = tag;
532    /// ```
533    pub fn variant(mut self, variant: BadgeVariant) -> Self {
534        self.variant = variant;
535        self.style = BadgeStyle::tag_from_theme(Theme::default(), self.tone, self.variant);
536        self
537    }
538
539    /// Replaces the resolved style without changing stored tone/variant.
540    ///
541    /// A later [`Self::tone`] or [`Self::variant`] call regenerates the style.
542    ///
543    /// # Examples
544    ///
545    /// ```
546    /// use ailloli_ui_widgets::controls::{BadgeStyle, Tag};
547    /// let tag = Tag::new("Custom").badge_style(BadgeStyle::default());
548    /// let _ = tag;
549    /// ```
550    pub fn badge_style(mut self, style: BadgeStyle) -> Self {
551        self.style = style;
552        self
553    }
554}
555
556/// A pill with an optional close action.
557///
558/// Calling a close builder displays the close icon and makes the whole widget
559/// keyboard-focusable. Enter or Space activates the action; pointer activation
560/// is restricted to the close-icon rectangle. Disabled chips remain visible at
561/// reduced opacity but do not activate.
562///
563/// # Examples
564///
565/// ```
566/// use ailloli_ui_widgets::controls::Chip;
567/// #[derive(Clone)]
568/// enum Action { Remove }
569/// let chip = Chip::new("Filter").on_close(Action::Remove);
570/// let _ = chip;
571/// ```
572pub struct Chip<A = ()> {
573    /// Layout constraints applied to the intrinsic pill size.
574    pub(crate) layout: LayoutStyle,
575    /// Flex behavior used by the parent layout.
576    pub(crate) flex_item: FlexItemStyle,
577    /// Semantic tone used when regenerating a themed style.
578    tone: BadgeTone,
579    /// Container variant used when regenerating a themed style.
580    variant: BadgeVariant,
581    /// Resolved visual style.
582    style: BadgeStyle,
583    /// Label, leading mark, and close-icon presence.
584    content: PillContent,
585    /// Live disabled state.
586    disabled: Binding<bool>,
587    /// Optional close action.
588    on_close: Option<ClickAction<A>>,
589}
590
591crate::impl_layout_builders!(Chip);
592
593impl<A: 'static> Chip<A> {
594    /// Creates an enabled neutral/soft chip without a close action.
595    ///
596    /// # Examples
597    ///
598    /// ```
599    /// use ailloli_ui_widgets::controls::Chip;
600    /// let chip: Chip<()> = Chip::new("Filter");
601    /// let _ = chip;
602    /// ```
603    pub fn new(label: impl Into<String>) -> Self {
604        let tone = BadgeTone::Neutral;
605        let variant = BadgeVariant::Soft;
606        Self {
607            layout: LayoutStyle::default(),
608            flex_item: FlexItemStyle::default(),
609            tone,
610            variant,
611            style: BadgeStyle::from_theme(Theme::default(), tone, variant),
612            content: PillContent::new(label),
613            disabled: Binding::Static(false),
614            on_close: None,
615        }
616    }
617
618    /// Selects a tone and regenerates style from the default theme.
619    ///
620    /// # Examples
621    ///
622    /// ```
623    /// use ailloli_ui_widgets::controls::{BadgeTone, Chip};
624    /// let chip: Chip<()> = Chip::new("Urgent").tone(BadgeTone::Danger);
625    /// let _ = chip;
626    /// ```
627    pub fn tone(mut self, tone: BadgeTone) -> Self {
628        self.tone = tone;
629        self.style = BadgeStyle::from_theme(Theme::default(), self.tone, self.variant);
630        self
631    }
632
633    /// Selects a variant and regenerates style from the default theme.
634    ///
635    /// # Examples
636    ///
637    /// ```
638    /// use ailloli_ui_widgets::controls::{BadgeVariant, Chip};
639    /// let chip: Chip<()> = Chip::new("Active").variant(BadgeVariant::Outline);
640    /// let _ = chip;
641    /// ```
642    pub fn variant(mut self, variant: BadgeVariant) -> Self {
643        self.variant = variant;
644        self.style = BadgeStyle::from_theme(Theme::default(), self.tone, self.variant);
645        self
646    }
647
648    /// Replaces the resolved style without changing stored tone/variant.
649    ///
650    /// A later [`Self::tone`] or [`Self::variant`] call regenerates the style.
651    ///
652    /// # Examples
653    ///
654    /// ```
655    /// use ailloli_ui_widgets::controls::{BadgeStyle, Chip};
656    /// let chip: Chip<()> = Chip::new("Custom").badge_style(BadgeStyle::default());
657    /// let _ = chip;
658    /// ```
659    pub fn badge_style(mut self, style: BadgeStyle) -> Self {
660        self.style = style;
661        self
662    }
663
664    /// Sets a leading icon, replacing any previous leading mark.
665    ///
666    /// # Examples
667    ///
668    /// ```
669    /// use ailloli_ui_core::IconId;
670    /// use ailloli_ui_widgets::controls::Chip;
671    /// let chip: Chip<()> = Chip::new("Recent").leading_icon(IconId::History);
672    /// let _ = chip;
673    /// ```
674    pub fn leading_icon(mut self, icon: IconId) -> Self {
675        self.content.leading = Leading::Icon(icon);
676        self
677    }
678
679    /// Sets static or reactive disabled state.
680    ///
681    /// # Examples
682    ///
683    /// ```
684    /// use ailloli_ui_widgets::controls::Chip;
685    /// let chip: Chip<()> = Chip::new("Locked").disabled(true);
686    /// let _ = chip;
687    /// ```
688    pub fn disabled(mut self, disabled: impl Into<Binding<bool>>) -> Self {
689        self.disabled = disabled.into();
690        self
691    }
692
693    /// Sets disabled state from a derived memo.
694    ///
695    /// # Examples
696    ///
697    /// ```
698    /// use ailloli_ui_runtime::component::Memo;
699    /// use ailloli_ui_widgets::controls::Chip;
700    /// let chip: Chip<()> = Chip::new("Dynamic").disabled_signal(Memo::new(|| false));
701    /// let _ = chip;
702    /// ```
703    pub fn disabled_signal(self, disabled: Memo<bool>) -> Self {
704        self.disabled(disabled)
705    }
706
707    /// Displays the close icon and installs an action value.
708    ///
709    /// A later call replaces the action. The action type must be cloneable
710    /// because input dispatch may enqueue it.
711    ///
712    /// # Examples
713    ///
714    /// ```
715    /// use ailloli_ui_widgets::controls::Chip;
716    /// #[derive(Clone)]
717    /// enum Action { Remove }
718    /// let chip = Chip::new("Filter").on_close(Action::Remove);
719    /// let _ = chip;
720    /// ```
721    pub fn on_close(mut self, action: impl IntoClickAction<A>) -> Self
722    where
723        A: Clone,
724    {
725        self.content.close = true;
726        self.on_close = Some(action.into_click_action());
727        self
728    }
729
730    /// Displays the close icon and installs a context-aware handler.
731    ///
732    /// # Examples
733    ///
734    /// ```
735    /// use ailloli_ui_widgets::controls::Chip;
736    /// let chip = Chip::<()>::new("Filter").on_close_ctx(|_ctx| {});
737    /// let _ = chip;
738    /// ```
739    pub fn on_close_ctx(mut self, f: impl Fn(&mut EventCtx<A>) + 'static) -> Self {
740        self.content.close = true;
741        self.on_close = Some(ClickAction::handler(f));
742        self
743    }
744}
745
746/// Shared retained widget for badge, tag, and chip behavior.
747struct PillWidget<A> {
748    /// Layout constraints applied to the intrinsic pill size.
749    layout: LayoutStyle,
750    /// Role controlling interactivity and debug identity.
751    kind: PillKind,
752    /// Resolved paint and geometry.
753    style: BadgeStyle,
754    /// Visible pill content.
755    content: PillContent,
756    /// Live disabled state; static false for badges and tags.
757    disabled: Binding<bool>,
758    /// Optional chip-only close action.
759    on_close: Option<ClickAction<A>>,
760}
761
762impl<A: 'static> Widget<A> for PillWidget<A> {
763    fn debug_name(&self) -> &'static str {
764        match self.kind {
765            PillKind::Badge => "Badge",
766            PillKind::Tag => "Tag",
767            PillKind::Chip => "Chip",
768        }
769    }
770
771    fn layout(
772        &self,
773        _engine: &mut ailloli_ui_runtime::layout::LayoutEngine<'_, A>,
774        ctx: &mut LayoutCtx<'_>,
775        _children: &mut [LayoutChild],
776        constraints: Constraints,
777    ) -> LayoutResult {
778        let intrinsic =
779            pill_intrinsic_size(&self.content, &self.style, ctx.text_system.as_deref_mut());
780        let size = apply_layout_size(intrinsic, self.layout, constraints);
781        let paint_bounds = Rect::new(0.0, 0.0, size.w, size.h);
782        LayoutResult {
783            size,
784            children: Vec::new(),
785            paint_bounds,
786            visual_bounds: self.style.visual_bounds(paint_bounds),
787            overlay_hit_bounds: Vec::new(),
788            clip: None,
789            is_window_root_clip: false,
790            artifact: None,
791        }
792    }
793
794    fn paint(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, _layout_result: &LayoutResult) {
795        let disabled = self.disabled.read();
796        paint_pill(ctx, bounds, &self.content, &self.style, disabled);
797    }
798
799    fn event(&self, ctx: &mut EventCtx<A>, event: &Event, bounds: Rect, _layout: &LayoutResult) {
800        if self.kind != PillKind::Chip || self.disabled.read() {
801            return;
802        }
803
804        match event {
805            Event::Pointer(PointerEvent::Button {
806                pos,
807                button: MouseButton::Left,
808                pressed: false,
809                ..
810            }) if self.on_close.is_some()
811                && close_rect(bounds, &self.style).contains(pos.x, pos.y) =>
812            {
813                if let Some(on_close) = &self.on_close {
814                    on_close.run(ctx);
815                    ctx.stop_propagation();
816                }
817            }
818            Event::Keyboard(key) if key.state == KeyState::Pressed && self.on_close.is_some() => {
819                if matches!(
820                    &key.key,
821                    Key::Named(NamedKey::Enter) | Key::Named(NamedKey::Space)
822                ) {
823                    if let Some(on_close) = &self.on_close {
824                        on_close.run(ctx);
825                        ctx.stop_propagation();
826                    }
827                }
828            }
829            _ => {}
830        }
831    }
832
833    fn focus_policy(&self) -> FocusPolicy {
834        if self.kind == PillKind::Chip && self.on_close.is_some() {
835            FocusPolicy::Focusable
836        } else {
837            FocusPolicy::NotFocusable
838        }
839    }
840}
841
842impl<A: 'static> IntoView<A> for Badge {
843    fn into_view(self) -> View<A> {
844        finish_view_sized(
845            View::leaf(PillWidget {
846                layout: self.layout,
847                kind: PillKind::Badge,
848                style: self.style,
849                content: self.content,
850                disabled: Binding::Static(false),
851                on_close: None,
852            }),
853            self.flex_item,
854            LayoutSizeHint::from_layout(self.layout),
855        )
856    }
857}
858
859impl<A: 'static> IntoView<A> for Tag {
860    fn into_view(self) -> View<A> {
861        finish_view_sized(
862            View::leaf(PillWidget {
863                layout: self.layout,
864                kind: PillKind::Tag,
865                style: self.style,
866                content: self.content,
867                disabled: Binding::Static(false),
868                on_close: None,
869            }),
870            self.flex_item,
871            LayoutSizeHint::from_layout(self.layout),
872        )
873    }
874}
875
876impl<A: 'static> IntoView<A> for Chip<A> {
877    fn into_view(self) -> View<A> {
878        finish_view_sized(
879            View::leaf(PillWidget {
880                layout: self.layout,
881                kind: PillKind::Chip,
882                style: self.style,
883                content: self.content,
884                disabled: self.disabled,
885                on_close: self.on_close,
886            }),
887            self.flex_item,
888            LayoutSizeHint::from_layout(self.layout),
889        )
890    }
891}
892
893/// Measures the unwrapped pill contents plus padding and inter-segment gaps.
894fn pill_intrinsic_size(
895    content: &PillContent,
896    style: &BadgeStyle,
897    mut text_system: Option<&mut TextSystem>,
898) -> Size {
899    let (label, count) = if let Some(text_system) = text_system.as_mut() {
900        (
901            measure_text(Some(&mut **text_system), &content.label, style.text),
902            content
903                .count
904                .map(|count| {
905                    measure_text(
906                        Some(&mut **text_system),
907                        &count.to_string(),
908                        style.count_text,
909                    )
910                })
911                .unwrap_or_default(),
912        )
913    } else {
914        (
915            measure_text(None, &content.label, style.text),
916            content
917                .count
918                .map(|count| measure_text(None, &count.to_string(), style.count_text))
919                .unwrap_or_default(),
920        )
921    };
922    let mut width = style.padding_x * 2.0 + label.w;
923
924    if leading_width(content, style) > 0.0 {
925        width += leading_width(content, style) + style.gap;
926    }
927    if content.count.is_some() {
928        width += style.gap + count.w;
929    }
930    if content.close {
931        width += style.gap + style.close_size;
932    }
933
934    Size::new(width.ceil(), style.height.max(label.h).ceil())
935}
936
937/// Paints the pill shell, content segments, close icon, and border.
938fn paint_pill(
939    ctx: &mut PaintCtx<'_>,
940    bounds: Rect,
941    content: &PillContent,
942    style: &BadgeStyle,
943    disabled: bool,
944) {
945    let opacity = if disabled {
946        style.disabled_opacity
947    } else {
948        1.0
949    };
950    for shadow in style.shadows.iter().copied() {
951        let mut shadow = shadow;
952        shadow.color = apply_opacity(shadow.color, opacity);
953        if shadow.color.a > 0.0 {
954            ctx.push(DrawCmd::BoxShadow(DrawBoxShadow {
955                rect: bounds,
956                radius: style.radius,
957                shadow,
958            }));
959        }
960    }
961
962    if let Background::Color(bg) = style.background {
963        let bg = apply_opacity(bg, opacity);
964        if bg.a > 0.0 {
965            ctx.push(DrawCmd::RRect(DrawRRect {
966                rect: bounds,
967                radius: style.radius.tl,
968                color: bg,
969            }));
970        }
971    }
972
973    let mut cursor = bounds.x + style.padding_x;
974    if matches!(content.leading, Leading::Icon(_) | Leading::Dot) {
975        paint_leading(ctx, bounds, cursor, content, style, opacity);
976        cursor += leading_width(content, style) + style.gap;
977    }
978
979    cursor += paint_text(ctx, &content.label, style.text, cursor, bounds, opacity);
980
981    if let Some(count) = content.count {
982        cursor += style.gap;
983        let _ = paint_text(
984            ctx,
985            &count.to_string(),
986            style.count_text,
987            cursor,
988            bounds,
989            opacity,
990        );
991    }
992
993    if content.close {
994        let rect = close_rect(bounds, style);
995        ctx.push(DrawCmd::Image(DrawImage {
996            rect,
997            icon: IconId::Close,
998            tint: apply_opacity(style.close_tint, opacity),
999            rotation_rad: 0.0,
1000        }));
1001    }
1002
1003    let border = apply_border_opacity(style.border, opacity);
1004    if border.is_visible() {
1005        ctx.push(DrawCmd::Border(DrawBorder {
1006            rect: bounds,
1007            radius: style.radius,
1008            border,
1009        }));
1010    }
1011}
1012
1013/// Paints the optional leading icon or centered circular dot.
1014fn paint_leading(
1015    ctx: &mut PaintCtx<'_>,
1016    bounds: Rect,
1017    x: f32,
1018    content: &PillContent,
1019    style: &BadgeStyle,
1020    opacity: f32,
1021) {
1022    match &content.leading {
1023        Leading::Icon(icon) => {
1024            let y = bounds.y + (bounds.h - style.icon_size) * 0.5;
1025            ctx.push(DrawCmd::Image(DrawImage {
1026                rect: Rect::new(x, y, style.icon_size, style.icon_size),
1027                icon: icon.clone(),
1028                tint: apply_opacity(style.icon_tint, opacity),
1029                rotation_rad: 0.0,
1030            }));
1031        }
1032        Leading::Dot => {
1033            let y = bounds.y + (bounds.h - style.dot_size) * 0.5;
1034            ctx.push(DrawCmd::RRect(DrawRRect {
1035                rect: Rect::new(x, y, style.dot_size, style.dot_size),
1036                radius: style.dot_size * 0.5,
1037                color: apply_opacity(style.dot_color, opacity),
1038            }));
1039        }
1040        Leading::None => {}
1041    }
1042}
1043
1044/// Paints one unwrapped text segment and returns its width.
1045fn paint_text(
1046    ctx: &mut PaintCtx<'_>,
1047    text: &str,
1048    style: TextStyle,
1049    x: f32,
1050    bounds: Rect,
1051    opacity: f32,
1052) -> f32 {
1053    let Some(text_system) = ctx.text_system.as_deref_mut() else {
1054        return estimate_text_width(text, style);
1055    };
1056    let layout = text_system.layout_cached(TextLayoutParams {
1057        text,
1058        style,
1059        max_width: None,
1060        wrap_mode: WrapMode::NoWrap,
1061    });
1062    let baseline = layout
1063        .lines
1064        .first()
1065        .map(|line| line.baseline_y)
1066        .unwrap_or(0.0);
1067    let y = bounds.y + (bounds.h - layout.metrics.height) * 0.5 + baseline;
1068    ctx.push(DrawCmd::Text(DrawText {
1069        pos: [x, y],
1070        color: apply_opacity(style.color, opacity),
1071        decoration: ailloli_ui_core::TextDecoration::None,
1072        layout: layout.clone(),
1073    }));
1074    layout.metrics.width
1075}
1076
1077/// Measures text through the text system or a deterministic fallback estimate.
1078fn measure_text(text_system: Option<&mut TextSystem>, text: &str, style: TextStyle) -> Size {
1079    if let Some(text_system) = text_system {
1080        let layout = text_system.layout_cached(TextLayoutParams {
1081            text,
1082            style,
1083            max_width: None,
1084            wrap_mode: WrapMode::NoWrap,
1085        });
1086        Size::new(layout.metrics.width, layout.metrics.height)
1087    } else {
1088        Size::new(estimate_text_width(text, style), style.px_size as f32 * 1.2)
1089    }
1090}
1091
1092/// Estimates unwrapped text width as 0.58 em per Unicode scalar value.
1093fn estimate_text_width(text: &str, style: TextStyle) -> f32 {
1094    text.chars().count() as f32 * style.px_size as f32 * 0.58
1095}
1096
1097/// Returns the width of the current leading mark in logical pixels.
1098fn leading_width(content: &PillContent, style: &BadgeStyle) -> f32 {
1099    match content.leading {
1100        Leading::None => 0.0,
1101        Leading::Icon(_) => style.icon_size,
1102        Leading::Dot => style.dot_size,
1103    }
1104}
1105
1106/// Returns the centered close-icon rectangle at the pill's trailing inset.
1107fn close_rect(bounds: Rect, style: &BadgeStyle) -> Rect {
1108    Rect::new(
1109        bounds.right() - style.padding_x - style.close_size,
1110        bounds.y + (bounds.h - style.close_size) * 0.5,
1111        style.close_size,
1112        style.close_size,
1113    )
1114}
1115
1116/// Resolves a semantic tone to its theme palette color.
1117fn tone_color(theme: Theme, tone: BadgeTone) -> Color {
1118    let palette = theme.palette();
1119    match tone {
1120        BadgeTone::Neutral => palette.surface_elevated,
1121        BadgeTone::Accent => palette.accent,
1122        BadgeTone::Danger => palette.danger,
1123        BadgeTone::Success => palette.success,
1124        BadgeTone::Warning => palette.warning,
1125        BadgeTone::Info => palette.info,
1126        BadgeTone::Muted => palette.text_muted,
1127    }
1128}
1129
1130/// Chooses dark or light foreground using a weighted RGB luminance threshold.
1131fn contrast_text_for(color: Color) -> Color {
1132    let luminance = 0.2126 * color.r + 0.7152 * color.g + 0.0722 * color.b;
1133    if luminance > 0.62 {
1134        Color::hex_rgb(0x090B0C)
1135    } else {
1136        Color::hex_rgb(0xF4F7F8)
1137    }
1138}
1139
1140/// Multiplies alpha by `opacity` and clamps the result to `[0, 1]`.
1141fn apply_opacity(mut color: Color, opacity: f32) -> Color {
1142    color.a = (color.a * opacity).clamp(0.0, 1.0);
1143    color
1144}
1145
1146/// Applies the same opacity multiplier independently to every border edge.
1147fn apply_border_opacity(mut border: Border, opacity: f32) -> Border {
1148    border.colors.left = apply_opacity(border.colors.left, opacity);
1149    border.colors.top = apply_opacity(border.colors.top, opacity);
1150    border.colors.right = apply_opacity(border.colors.right, opacity);
1151    border.colors.bottom = apply_opacity(border.colors.bottom, opacity);
1152    border
1153}
1154
1155/// Returns the smallest axis-aligned rectangle containing both inputs.
1156fn union_rect(a: Rect, b: Rect) -> Rect {
1157    let x0 = a.x.min(b.x);
1158    let y0 = a.y.min(b.y);
1159    let x1 = a.right().max(b.right());
1160    let y1 = a.bottom().max(b.bottom());
1161    Rect::new(x0, y0, x1 - x0, y1 - y0)
1162}