ailloli_ui_widgets/primitives/
icon_widget.rs

1//! Retained square icon widget for font glyphs and embedded SVG sources.
2
3use std::sync::Arc;
4
5use ailloli_ui_core::event::Event;
6use ailloli_ui_core::geometry::{Constraints, Rect, Size};
7use ailloli_ui_core::style::{FlexItemStyle, LayoutSizeHint, LayoutStyle};
8use ailloli_ui_core::{Color, IconId, SvgSource};
9use ailloli_ui_runtime::component::{IntoView, View, Widget};
10use ailloli_ui_runtime::input::EventCtx;
11use ailloli_ui_runtime::layout::{LayoutChild, LayoutCtx, LayoutResult};
12use ailloli_ui_runtime::scene::PaintCtx;
13use ailloli_ui_runtime::{DrawCmd, DrawImage};
14use lucide_icons::Icon as LucideIcon;
15
16use crate::layout::layout_ext::{apply_layout_size, finish_view_sized};
17
18/// Declarative icon widget (Lucide, Devicon, or custom SVG).
19///
20/// For font glyphs, `tint` replaces the mask color.
21/// For full-color SVGs, use `Color::WHITE` to preserve native colors.
22/// The defaults are a 16-logical-pixel square, white tint, interactive tinting,
23/// and zero rotation.
24///
25/// # Examples
26///
27/// ```
28/// use ailloli_ui_core::IconId;
29/// use ailloli_ui_widgets::primitives::Icon;
30/// let icon = Icon::new(IconId::Close).size(20.0);
31/// let _ = icon;
32/// ```
33pub struct Icon {
34    /// Outer logical sizing policy.
35    pub(crate) layout: LayoutStyle,
36    /// Parent-flex participation metadata.
37    pub(crate) flex_item: FlexItemStyle,
38    /// Icon catalogue identity resolved during painting.
39    source: IconId,
40    /// Base RGBA tint applied to the icon mask.
41    tint: Color,
42    /// Square logical-pixel icon extent.
43    size: f32,
44    /// Whether hover/press/focus state modifies the base tint.
45    interactive_tint: bool,
46    /// Clockwise rotation in radians around the icon center.
47    rotation_rad: f32,
48}
49
50crate::impl_layout_builders_unit!(Icon);
51
52impl Icon {
53    /// Creates a default icon from any [`IconId`]-compatible source.
54    ///
55    /// # Examples
56    ///
57    /// ```
58    /// use ailloli_ui_core::IconId;
59    /// use ailloli_ui_widgets::primitives::Icon;
60    /// let icon = Icon::new(IconId::Check);
61    /// let _ = icon;
62    /// ```
63    pub fn new(source: impl Into<IconId>) -> Self {
64        Self {
65            layout: LayoutStyle::default(),
66            flex_item: FlexItemStyle::default(),
67            source: source.into(),
68            tint: Color::WHITE,
69            size: 16.0,
70            interactive_tint: true,
71            rotation_rad: 0.0,
72        }
73    }
74
75    /// Creates a Lucide font-glyph icon.
76    ///
77    /// # Examples
78    ///
79    /// ```
80    /// use ailloli_ui_widgets::primitives::Icon;
81    /// let icon = Icon::lucide(lucide_icons::Icon::Plus);
82    /// let _ = icon;
83    /// ```
84    pub fn lucide(icon: LucideIcon) -> Self {
85        Self::new(IconId::Lucide(icon))
86    }
87
88    /// Creates a Devicon font glyph from its Unicode scalar.
89    ///
90    /// The glyph is not checked against the bundled font at construction.
91    ///
92    /// # Examples
93    ///
94    /// ```
95    /// use ailloli_ui_widgets::primitives::Icon;
96    /// let icon = Icon::devicon('\u{e7a8}');
97    /// let _ = icon;
98    /// ```
99    pub fn devicon(ch: char) -> Self {
100        Self::new(IconId::Devicon(ch))
101    }
102
103    /// Creates an SVG icon borrowing compile-time-static bytes.
104    ///
105    /// Bytes are retained and validated only by a renderer/cache when used.
106    ///
107    /// # Examples
108    ///
109    /// ```
110    /// use ailloli_ui_widgets::primitives::Icon;
111    /// let icon = Icon::svg_static(b"<svg/>");
112    /// let _ = icon;
113    /// ```
114    pub fn svg_static(bytes: &'static [u8]) -> Self {
115        Self::new(IconId::Svg(SvgSource::Static(bytes)))
116    }
117
118    /// Creates an SVG icon from shared owned bytes.
119    ///
120    /// # Examples
121    ///
122    /// ```
123    /// use std::sync::Arc;
124    /// use ailloli_ui_widgets::primitives::Icon;
125    /// let icon = Icon::svg_bytes(Arc::<[u8]>::from(&b"<svg/>"[..]));
126    /// let _ = icon;
127    /// ```
128    pub fn svg_bytes(bytes: impl Into<Arc<[u8]>>) -> Self {
129        Self::new(IconId::Svg(SvgSource::Owned(bytes.into())))
130    }
131
132    /// Creates an SVG icon from shared UTF-8 markup.
133    ///
134    /// # Examples
135    ///
136    /// ```
137    /// use std::sync::Arc;
138    /// use ailloli_ui_widgets::primitives::Icon;
139    /// let icon = Icon::svg_str(Arc::<str>::from("<svg/>"));
140    /// let _ = icon;
141    /// ```
142    pub fn svg_str(s: impl Into<Arc<str>>) -> Self {
143        Self::new(IconId::Svg(SvgSource::Str(s.into())))
144    }
145
146    /// Replaces the render tint.
147    ///
148    /// Use [`Color::WHITE`] to preserve a full-color SVG.
149    ///
150    /// # Examples
151    ///
152    /// ```
153    /// use ailloli_ui_core::{Color, IconId};
154    /// use ailloli_ui_widgets::primitives::Icon;
155    /// let icon = Icon::new(IconId::Close).tint(Color::rgba(255, 0, 0, 1.0));
156    /// let _ = icon;
157    /// ```
158    pub fn tint(mut self, color: Color) -> Self {
159        self.tint = color;
160        self
161    }
162
163    /// Sets the square extent in logical pixels, clamped to at least zero.
164    ///
165    /// Non-finite values follow [`f32::max`]; a `NaN` therefore resolves to
166    /// zero while positive infinity remains unbounded for later constraints.
167    ///
168    /// # Examples
169    ///
170    /// ```
171    /// use ailloli_ui_core::IconId;
172    /// use ailloli_ui_widgets::primitives::Icon;
173    /// let icon = Icon::new(IconId::Close).size(-4.0);
174    /// let _ = icon;
175    /// ```
176    pub fn size(mut self, px: f32) -> Self {
177        self.size = px.max(0.0);
178        self
179    }
180
181    /// Enables or disables automatic hover/pressed tint adjustments.
182    ///
183    /// Disable this for full-color brand artwork.
184    ///
185    /// # Examples
186    ///
187    /// ```
188    /// use ailloli_ui_core::IconId;
189    /// use ailloli_ui_widgets::primitives::Icon;
190    /// let icon = Icon::new(IconId::Close).interactive_tint(false);
191    /// let _ = icon;
192    /// ```
193    pub fn interactive_tint(mut self, enabled: bool) -> Self {
194        self.interactive_tint = enabled;
195        self
196    }
197
198    /// Sets clockwise renderer rotation in radians.
199    ///
200    /// `NaN` and either infinity are replaced with zero; finite angles are not
201    /// normalized and may exceed one full turn.
202    ///
203    /// # Examples
204    ///
205    /// ```
206    /// use ailloli_ui_core::IconId;
207    /// use ailloli_ui_widgets::primitives::Icon;
208    /// let icon = Icon::new(IconId::Close).rotation_rad(std::f32::consts::FRAC_PI_2);
209    /// let _ = icon;
210    /// ```
211    pub fn rotation_rad(mut self, radians: f32) -> Self {
212        self.rotation_rad = if radians.is_finite() { radians } else { 0.0 };
213        self
214    }
215}
216
217/// Converts an icon identifier with the same defaults as [`Icon::new`].
218impl From<IconId> for Icon {
219    fn from(source: IconId) -> Self {
220        Self::new(source)
221    }
222}
223
224/// Frozen render state used after the declarative builder becomes a view.
225struct IconWidget {
226    /// Outer logical sizing policy.
227    layout: LayoutStyle,
228    /// Icon catalogue identity resolved during painting.
229    source: IconId,
230    /// Base RGBA tint applied to the icon mask.
231    tint: Color,
232    /// Square logical-pixel icon extent.
233    size: f32,
234    /// Whether hover/press/focus state modifies the base tint.
235    interactive_tint: bool,
236    /// Clockwise rotation in radians around the icon center.
237    rotation_rad: f32,
238}
239
240/// Implements square layout and interaction-aware tint painting.
241impl<A: 'static> Widget<A> for IconWidget {
242    fn debug_name(&self) -> &'static str {
243        "Icon"
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 = Size::new(self.size, self.size);
254        let size = apply_layout_size(intrinsic, self.layout, constraints);
255        LayoutResult {
256            size,
257            children: Vec::new(),
258            paint_bounds: Rect::new(0.0, 0.0, size.w, size.h),
259            visual_bounds: Rect::new(0.0, 0.0, size.w, size.h),
260            overlay_hit_bounds: Vec::new(),
261            clip: None,
262            is_window_root_clip: false,
263            artifact: None,
264        }
265    }
266
267    fn paint(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, _layout: &LayoutResult) {
268        let i = ctx.interaction();
269        let mut tint = self.tint;
270        if self.interactive_tint && i.hovered {
271            tint = Color::f32(
272                tint.r + (1.0 - tint.r) * 0.14,
273                tint.g + (1.0 - tint.g) * 0.14,
274                tint.b + (1.0 - tint.b) * 0.14,
275                tint.a,
276            );
277        }
278        if self.interactive_tint && i.pressed {
279            tint = Color::f32(
280                (tint.r * 0.88).max(0.0),
281                (tint.g * 0.88).max(0.0),
282                (tint.b * 0.88).max(0.0),
283                tint.a,
284            );
285        }
286        ctx.push(DrawCmd::Image(DrawImage {
287            rect: bounds,
288            icon: self.source.clone(),
289            tint,
290            rotation_rad: self.rotation_rad,
291        }));
292    }
293
294    fn event(&self, _ctx: &mut EventCtx<A>, _event: &Event, _bounds: Rect, _layout: &LayoutResult) {
295    }
296}
297
298/// Converts the builder into a leaf retained widget.
299impl<A: 'static> IntoView<A> for Icon {
300    fn into_view(self) -> View<A> {
301        finish_view_sized(
302            View::leaf(IconWidget {
303                layout: self.layout,
304                source: self.source,
305                tint: self.tint,
306                size: self.size,
307                interactive_tint: self.interactive_tint,
308                rotation_rad: self.rotation_rad,
309            }),
310            self.flex_item,
311            LayoutSizeHint::from_layout(self.layout),
312        )
313    }
314}