ailloli_ui_widgets/controls/
status_indicator.rs

1//! Compact, non-interactive indicators for status and activity.
2
3use crate::layout::layout_ext::{apply_layout_size, finish_view_sized};
4use ailloli_ui_core::event::Event;
5use ailloli_ui_core::geometry::{Constraints, Rect, Size};
6use ailloli_ui_core::style::{Border, FlexItemStyle, LayoutSizeHint, LayoutStyle, Radius};
7use ailloli_ui_core::{Color, Theme};
8use ailloli_ui_runtime::component::{IntoView, View, Widget};
9use ailloli_ui_runtime::input::{EventCtx, FocusPolicy};
10use ailloli_ui_runtime::layout::{LayoutChild, LayoutCtx, LayoutResult};
11use ailloli_ui_runtime::scene::PaintCtx;
12use ailloli_ui_runtime::{DrawBorder, DrawCmd, DrawRRect};
13
14#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
15/// Semantic color choices for a [`StatusIndicator`].
16///
17/// # Examples
18///
19/// ```
20/// use ailloli_ui_widgets::controls::StatusTone;
21/// assert_eq!(StatusTone::default(), StatusTone::Success);
22/// ```
23pub enum StatusTone {
24    /// Primary text color.
25    Neutral,
26    /// Theme accent color.
27    Accent,
28    /// Destructive or failed state.
29    Danger,
30    /// Successful or healthy state.
31    #[default]
32    Success,
33    /// Warning state.
34    Warning,
35    /// Informational state.
36    Info,
37    /// De-emphasized text color.
38    Muted,
39}
40
41#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
42/// Shape used to represent status.
43///
44/// # Examples
45///
46/// ```
47/// use ailloli_ui_widgets::controls::StatusVariant;
48/// assert_eq!(StatusVariant::default(), StatusVariant::Dot);
49/// ```
50pub enum StatusVariant {
51    /// Filled circle.
52    #[default]
53    Dot,
54    /// Circular outline with a translucent inner fill when space permits.
55    Ring,
56    /// Three ascending vertical bars.
57    Bars,
58}
59
60#[derive(Clone, Debug, PartialEq)]
61/// Resolved colors and logical-pixel metrics for a [`StatusIndicator`].
62///
63/// `muted_color` is retained for style compatibility but is not currently
64/// painted by any variant.
65///
66/// # Examples
67///
68/// ```
69/// use ailloli_ui_core::Theme;
70/// use ailloli_ui_widgets::controls::{StatusStyle, StatusTone};
71/// let style = StatusStyle::from_theme(Theme::dark(), StatusTone::Info);
72/// assert_eq!(style.size, 10.0);
73/// assert_eq!(style.ring_width, 2.0);
74/// ```
75pub struct StatusStyle {
76    /// Primary dot, ring, or bars color.
77    pub color: Color,
78    /// Reserved secondary color; currently not painted.
79    pub muted_color: Color,
80    /// Preferred height, and width for dot/ring, in logical pixels.
81    pub size: f32,
82    /// Ring border width in logical pixels.
83    pub ring_width: f32,
84    /// Horizontal gap between bars in logical pixels.
85    pub bar_gap: f32,
86}
87
88impl Default for StatusStyle {
89    fn default() -> Self {
90        Self::from_theme(Theme::default(), StatusTone::Success)
91    }
92}
93
94impl StatusStyle {
95    /// Resolves `tone` through `theme` with the default indicator metrics.
96    ///
97    /// # Examples
98    ///
99    /// ```
100    /// use ailloli_ui_core::Theme;
101    /// use ailloli_ui_widgets::controls::{StatusStyle, StatusTone};
102    /// let style = StatusStyle::from_theme(Theme::dark(), StatusTone::Warning);
103    /// assert_eq!(style.bar_gap, 3.0);
104    /// ```
105    pub fn from_theme(theme: Theme, tone: StatusTone) -> Self {
106        Self {
107            color: status_tone_color(theme, tone),
108            muted_color: theme.palette().border,
109            size: 10.0,
110            ring_width: 2.0,
111            bar_gap: 3.0,
112        }
113    }
114}
115
116/// A decorative status marker that does not receive focus or events.
117///
118/// The dot and ring prefer a square of `style.size`; bars prefer a width of
119/// `1.5 × style.size`. Layout constraints and explicit layout builders may
120/// override those intrinsic dimensions.
121///
122/// # Examples
123///
124/// ```
125/// use ailloli_ui_widgets::controls::{StatusIndicator, StatusTone};
126/// let indicator = StatusIndicator::new(StatusTone::Success);
127/// let _ = indicator;
128/// ```
129pub struct StatusIndicator {
130    /// Layout configuration used to resolve the intrinsic size.
131    pub(crate) layout: LayoutStyle,
132    /// Flex-item behavior used by the parent layout.
133    pub(crate) flex_item: FlexItemStyle,
134    /// Semantic tone last selected through the public builder API.
135    tone: StatusTone,
136    /// Shape to paint.
137    variant: StatusVariant,
138    /// Resolved colors and metrics.
139    style: StatusStyle,
140}
141
142crate::impl_layout_builders_unit!(StatusIndicator);
143
144impl StatusIndicator {
145    /// Creates a dot indicator for `tone` using the default theme.
146    ///
147    /// # Examples
148    ///
149    /// ```
150    /// use ailloli_ui_widgets::controls::{StatusIndicator, StatusTone};
151    /// let indicator = StatusIndicator::new(StatusTone::Danger);
152    /// let _ = indicator;
153    /// ```
154    pub fn new(tone: StatusTone) -> Self {
155        Self {
156            layout: LayoutStyle::default(),
157            flex_item: FlexItemStyle::default(),
158            tone,
159            variant: StatusVariant::Dot,
160            style: StatusStyle::from_theme(Theme::default(), tone),
161        }
162    }
163
164    /// Selects the painted shape without changing colors or size.
165    ///
166    /// # Examples
167    ///
168    /// ```
169    /// use ailloli_ui_widgets::controls::{StatusIndicator, StatusTone, StatusVariant};
170    /// let indicator = StatusIndicator::new(StatusTone::Info).variant(StatusVariant::Ring);
171    /// let _ = indicator;
172    /// ```
173    pub fn variant(mut self, variant: StatusVariant) -> Self {
174        self.variant = variant;
175        self
176    }
177
178    /// Sets the preferred logical-pixel size, clamped to at least `0.0`.
179    ///
180    /// `NaN` is treated as zero by the floating-point `max` operation.
181    ///
182    /// # Examples
183    ///
184    /// ```
185    /// use ailloli_ui_widgets::controls::{StatusIndicator, StatusTone};
186    /// let indicator = StatusIndicator::new(StatusTone::Success).size(-4.0);
187    /// let _ = indicator; // preferred size is clamped to zero
188    /// ```
189    pub fn size(mut self, value: f32) -> Self {
190        self.style.size = value.max(0.0);
191        self
192    }
193
194    /// Replaces all resolved style values without changing the stored tone.
195    ///
196    /// Unlike [`Self::size`], this method does not clamp `style.size`.
197    /// A later [`Self::tone`] call replaces the custom style entirely.
198    ///
199    /// # Examples
200    ///
201    /// ```
202    /// use ailloli_ui_core::Theme;
203    /// use ailloli_ui_widgets::controls::{StatusIndicator, StatusStyle, StatusTone};
204    /// let style = StatusStyle::from_theme(Theme::dark(), StatusTone::Accent);
205    /// let indicator = StatusIndicator::new(StatusTone::Accent).status_style(style);
206    /// let _ = indicator;
207    /// ```
208    pub fn status_style(mut self, style: StatusStyle) -> Self {
209        self.style = style;
210        self
211    }
212
213    /// Re-resolves colors and metrics for `tone` using the default theme.
214    ///
215    /// This resets custom size, ring width, and gap values as well as colors.
216    ///
217    /// # Examples
218    ///
219    /// ```
220    /// use ailloli_ui_widgets::controls::{StatusIndicator, StatusTone};
221    /// let indicator = StatusIndicator::new(StatusTone::Muted).tone(StatusTone::Success);
222    /// let _ = indicator;
223    /// ```
224    pub fn tone(mut self, tone: StatusTone) -> Self {
225        self.tone = tone;
226        self.style = StatusStyle::from_theme(Theme::default(), tone);
227        self
228    }
229}
230
231/// Retained leaf widget that resolves and paints one status shape.
232struct StatusIndicatorWidget {
233    /// Layout copied from the builder.
234    layout: LayoutStyle,
235    /// Shape copied from the builder.
236    variant: StatusVariant,
237    /// Resolved style copied from the builder.
238    style: StatusStyle,
239}
240
241impl<A: 'static> Widget<A> for StatusIndicatorWidget {
242    fn debug_name(&self) -> &'static str {
243        "StatusIndicator"
244    }
245
246    fn layout(
247        &self,
248        _engine: &mut ailloli_ui_runtime::layout::LayoutEngine<'_, A>,
249        _ctx: &mut LayoutCtx<'_>,
250        _children: &mut [LayoutChild],
251        constraints: Constraints,
252    ) -> LayoutResult {
253        let intrinsic = match self.variant {
254            StatusVariant::Bars => Size::new(self.style.size * 1.5, self.style.size),
255            StatusVariant::Dot | StatusVariant::Ring => Size::new(self.style.size, self.style.size),
256        };
257        let size = apply_layout_size(intrinsic, self.layout, constraints);
258        LayoutResult {
259            size,
260            children: Vec::new(),
261            paint_bounds: Rect::new(0.0, 0.0, size.w, size.h),
262            visual_bounds: Rect::new(0.0, 0.0, size.w, size.h),
263            overlay_hit_bounds: Vec::new(),
264            clip: None,
265            is_window_root_clip: false,
266            artifact: None,
267        }
268    }
269
270    fn paint(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, _layout: &LayoutResult) {
271        match self.variant {
272            StatusVariant::Dot => {
273                let size = bounds.w.min(bounds.h);
274                let rect = centered_square(bounds, size);
275                ctx.push(DrawCmd::RRect(DrawRRect {
276                    rect,
277                    radius: size * 0.5,
278                    color: self.style.color,
279                }));
280            }
281            StatusVariant::Ring => {
282                let size = bounds.w.min(bounds.h);
283                let rect = centered_square(bounds, size);
284                ctx.push(DrawCmd::Border(DrawBorder {
285                    rect,
286                    radius: Radius::uniform(size * 0.5),
287                    border: Border::new(self.style.ring_width, self.style.color),
288                }));
289                let inner = (size - self.style.ring_width * 4.0).max(0.0);
290                if inner > 0.0 {
291                    ctx.push(DrawCmd::RRect(DrawRRect {
292                        rect: centered_square(bounds, inner),
293                        radius: inner * 0.5,
294                        color: self.style.color.with_alpha(0.22),
295                    }));
296                }
297            }
298            StatusVariant::Bars => paint_bars(ctx, bounds, &self.style),
299        }
300    }
301
302    fn event(&self, _ctx: &mut EventCtx<A>, _event: &Event, _bounds: Rect, _layout: &LayoutResult) {
303    }
304
305    fn focus_policy(&self) -> FocusPolicy {
306        FocusPolicy::NotFocusable
307    }
308}
309
310impl<A: 'static> IntoView<A> for StatusIndicator {
311    fn into_view(self) -> View<A> {
312        finish_view_sized(
313            View::leaf(StatusIndicatorWidget {
314                layout: self.layout,
315                variant: self.variant,
316                style: self.style,
317            }),
318            self.flex_item,
319            LayoutSizeHint::from_layout(self.layout),
320        )
321    }
322}
323
324/// Paints three ascending bars, clamping negative gaps and bar widths.
325fn paint_bars(ctx: &mut PaintCtx<'_>, bounds: Rect, style: &StatusStyle) {
326    let gap = style.bar_gap.max(0.0);
327    let bar_w = ((bounds.w - gap * 2.0) / 3.0).max(1.0);
328    let heights = [0.45, 0.72, 1.0];
329    for (idx, ratio) in heights.iter().enumerate() {
330        let h = bounds.h * ratio;
331        let x = bounds.x + idx as f32 * (bar_w + gap);
332        let y = bounds.bottom() - h;
333        ctx.push(DrawCmd::RRect(DrawRRect {
334            rect: Rect::new(x, y, bar_w, h),
335            radius: (bar_w * 0.5).min(2.0),
336            color: style.color,
337        }));
338    }
339}
340
341/// Returns a square of `size` centered within `bounds` without clipping.
342fn centered_square(bounds: Rect, size: f32) -> Rect {
343    Rect::new(
344        bounds.x + (bounds.w - size) * 0.5,
345        bounds.y + (bounds.h - size) * 0.5,
346        size,
347        size,
348    )
349}
350
351/// Maps a semantic status tone to its concrete theme palette color.
352fn status_tone_color(theme: Theme, tone: StatusTone) -> Color {
353    let palette = theme.palette();
354    match tone {
355        StatusTone::Neutral => palette.text,
356        StatusTone::Accent => palette.accent,
357        StatusTone::Danger => palette.danger,
358        StatusTone::Success => palette.success,
359        StatusTone::Warning => palette.warning,
360        StatusTone::Info => palette.info,
361        StatusTone::Muted => palette.text_muted,
362    }
363}