ailloli_ui_widgets/controls/
divider.rs

1//! Non-interactive horizontal and vertical separators.
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::{FlexItemStyle, LayoutSizeHint, LayoutStyle};
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::{DrawCmd, DrawRect};
13
14#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
15/// Main axis of a [`Divider`].
16///
17/// # Examples
18///
19/// ```
20/// use ailloli_ui_widgets::controls::DividerOrientation;
21/// assert_eq!(DividerOrientation::default(), DividerOrientation::Horizontal);
22/// ```
23pub enum DividerOrientation {
24    /// Length runs left to right and thickness runs top to bottom.
25    #[default]
26    Horizontal,
27    /// Length runs top to bottom and thickness runs left to right.
28    Vertical,
29}
30
31#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
32/// Stroke pattern used by a [`Divider`].
33///
34/// # Examples
35///
36/// ```
37/// use ailloli_ui_widgets::controls::DividerVariant;
38/// assert_eq!(DividerVariant::default(), DividerVariant::Solid);
39/// ```
40pub enum DividerVariant {
41    /// One rectangle filling the resolved bounds.
42    #[default]
43    Solid,
44    /// Rectangular segments using [`DividerStyle::dash`] and `gap`.
45    Dashed,
46    /// Short segments whose length equals the resolved thickness.
47    Dotted,
48}
49
50#[derive(Clone, Debug, PartialEq)]
51/// Resolved color and logical-pixel metrics for a [`Divider`].
52///
53/// # Examples
54///
55/// ```
56/// use ailloli_ui_core::Theme;
57/// use ailloli_ui_widgets::controls::DividerStyle;
58/// let style = DividerStyle::from_theme(Theme::dark());
59/// assert_eq!(style.thickness, 1.0);
60/// assert_eq!(style.length, 160.0);
61/// ```
62pub struct DividerStyle {
63    /// Segment fill color.
64    pub color: Color,
65    /// Cross-axis thickness in logical pixels.
66    pub thickness: f32,
67    /// Main-axis intrinsic length in logical pixels.
68    pub length: f32,
69    /// Dashed segment length in logical pixels.
70    pub dash: f32,
71    /// Space between dashed or dotted segments in logical pixels.
72    pub gap: f32,
73}
74
75impl Default for DividerStyle {
76    fn default() -> Self {
77        Self::from_theme(Theme::default())
78    }
79}
80
81impl DividerStyle {
82    /// Resolves the default separator color from `theme`.
83    ///
84    /// Geometry remains fixed at `1 × 160` logical pixels, with 10-pixel
85    /// dashes and 6-pixel gaps.
86    ///
87    /// # Examples
88    ///
89    /// ```
90    /// use ailloli_ui_core::Theme;
91    /// use ailloli_ui_widgets::controls::DividerStyle;
92    /// let style = DividerStyle::from_theme(Theme::dark());
93    /// assert_eq!(style.dash, 10.0);
94    /// assert_eq!(style.gap, 6.0);
95    /// ```
96    pub fn from_theme(theme: Theme) -> Self {
97        Self {
98            color: theme.palette().border,
99            thickness: 1.0,
100            length: 160.0,
101            dash: 10.0,
102            gap: 6.0,
103        }
104    }
105}
106
107/// A decorative separator that does not receive focus or events.
108///
109/// Explicit layout width and height may override the style's intrinsic length
110/// and thickness. Segments are clipped by construction to the resolved bounds.
111///
112/// # Examples
113///
114/// ```
115/// use ailloli_ui_widgets::controls::Divider;
116/// let divider = Divider::horizontal();
117/// let _ = divider;
118/// ```
119pub struct Divider {
120    /// Layout configuration used to resolve intrinsic geometry.
121    pub(crate) layout: LayoutStyle,
122    /// Flex-item behavior used by the parent layout.
123    pub(crate) flex_item: FlexItemStyle,
124    /// Main-axis direction.
125    orientation: DividerOrientation,
126    /// Stroke pattern.
127    variant: DividerVariant,
128    /// Resolved color and metrics.
129    style: DividerStyle,
130}
131
132crate::impl_layout_builders_unit!(Divider);
133
134impl Divider {
135    /// Creates a solid horizontal divider using the default style.
136    ///
137    /// # Examples
138    ///
139    /// ```
140    /// use ailloli_ui_widgets::controls::Divider;
141    /// let divider = Divider::horizontal();
142    /// let _ = divider;
143    /// ```
144    pub fn horizontal() -> Self {
145        Self::new(DividerOrientation::Horizontal)
146    }
147
148    /// Creates a solid vertical divider using the default style.
149    ///
150    /// # Examples
151    ///
152    /// ```
153    /// use ailloli_ui_widgets::controls::Divider;
154    /// let divider = Divider::vertical();
155    /// let _ = divider;
156    /// ```
157    pub fn vertical() -> Self {
158        Self::new(DividerOrientation::Vertical)
159    }
160
161    /// Selects the solid, dashed, or dotted paint pattern.
162    ///
163    /// # Examples
164    ///
165    /// ```
166    /// use ailloli_ui_widgets::controls::{Divider, DividerVariant};
167    /// let divider = Divider::horizontal().variant(DividerVariant::Dashed);
168    /// let _ = divider;
169    /// ```
170    pub fn variant(mut self, variant: DividerVariant) -> Self {
171        self.variant = variant;
172        self
173    }
174
175    /// Sets cross-axis thickness in logical pixels, clamped to at least zero.
176    ///
177    /// `NaN` is treated as zero.
178    ///
179    /// # Examples
180    ///
181    /// ```
182    /// use ailloli_ui_widgets::controls::Divider;
183    /// let divider = Divider::horizontal().thickness(2.0);
184    /// let _ = divider;
185    /// ```
186    pub fn thickness(mut self, value: f32) -> Self {
187        self.style.thickness = value.max(0.0);
188        self
189    }
190
191    /// Sets intrinsic main-axis length in logical pixels, clamped to zero.
192    ///
193    /// Explicit layout dimensions may override this intrinsic value. `NaN` is
194    /// treated as zero.
195    ///
196    /// # Examples
197    ///
198    /// ```
199    /// use ailloli_ui_widgets::controls::Divider;
200    /// let divider = Divider::vertical().length(240.0);
201    /// let _ = divider;
202    /// ```
203    pub fn length(mut self, value: f32) -> Self {
204        self.style.length = value.max(0.0);
205        self
206    }
207
208    /// Replaces the segment fill color.
209    ///
210    /// # Examples
211    ///
212    /// ```
213    /// use ailloli_ui_core::Color;
214    /// use ailloli_ui_widgets::controls::Divider;
215    /// let divider = Divider::horizontal().color(Color::WHITE);
216    /// let _ = divider;
217    /// ```
218    pub fn color(mut self, color: Color) -> Self {
219        self.style.color = color;
220        self
221    }
222
223    /// Replaces the complete divider style without pre-clamping its values.
224    ///
225    /// Layout clamps negative `thickness` and `length` to zero. Dashed/dotted
226    /// painting clamps gaps and segment lengths to at least one logical pixel.
227    ///
228    /// # Examples
229    ///
230    /// ```
231    /// use ailloli_ui_core::Theme;
232    /// use ailloli_ui_widgets::controls::{Divider, DividerStyle};
233    /// let style = DividerStyle::from_theme(Theme::dark());
234    /// let divider = Divider::horizontal().divider_style(style);
235    /// let _ = divider;
236    /// ```
237    pub fn divider_style(mut self, style: DividerStyle) -> Self {
238        self.style = style;
239        self
240    }
241
242    /// Creates a divider in `orientation` with the default solid style.
243    fn new(orientation: DividerOrientation) -> Self {
244        Self {
245            layout: LayoutStyle::default(),
246            flex_item: FlexItemStyle::default(),
247            orientation,
248            variant: DividerVariant::Solid,
249            style: DividerStyle::default(),
250        }
251    }
252}
253
254/// Retained leaf widget holding the divider's resolved geometry and style.
255struct DividerWidget {
256    /// Layout copied from the builder.
257    layout: LayoutStyle,
258    /// Orientation copied from the builder.
259    orientation: DividerOrientation,
260    /// Pattern copied from the builder.
261    variant: DividerVariant,
262    /// Style copied from the builder.
263    style: DividerStyle,
264}
265
266impl<A: 'static> Widget<A> for DividerWidget {
267    fn debug_name(&self) -> &'static str {
268        "Divider"
269    }
270
271    fn layout(
272        &self,
273        _engine: &mut ailloli_ui_runtime::layout::LayoutEngine<'_, A>,
274        _ctx: &mut LayoutCtx<'_>,
275        _children: &mut [LayoutChild],
276        constraints: Constraints,
277    ) -> LayoutResult {
278        let thickness = self.style.thickness.max(0.0);
279        let length = self.style.length.max(0.0);
280        let intrinsic = match self.orientation {
281            DividerOrientation::Horizontal => Size::new(length, thickness),
282            DividerOrientation::Vertical => Size::new(thickness, length),
283        };
284        let size = apply_layout_size(intrinsic, self.layout, constraints);
285        LayoutResult {
286            size,
287            children: Vec::new(),
288            paint_bounds: Rect::new(0.0, 0.0, size.w, size.h),
289            visual_bounds: Rect::new(0.0, 0.0, size.w, size.h),
290            overlay_hit_bounds: Vec::new(),
291            clip: None,
292            is_window_root_clip: false,
293            artifact: None,
294        }
295    }
296
297    fn paint(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, _layout: &LayoutResult) {
298        match self.variant {
299            DividerVariant::Solid => {
300                if bounds.w > 0.0 && bounds.h > 0.0 {
301                    ctx.push(DrawCmd::Rect(DrawRect {
302                        rect: bounds,
303                        color: self.style.color,
304                    }));
305                }
306            }
307            DividerVariant::Dashed => paint_segments(
308                ctx,
309                bounds,
310                self.orientation,
311                self.style.dash.max(self.style.thickness).max(1.0),
312                self.style.gap.max(1.0),
313                self.style.color,
314            ),
315            DividerVariant::Dotted => paint_segments(
316                ctx,
317                bounds,
318                self.orientation,
319                self.style.thickness.max(1.0),
320                self.style.gap.max(1.0),
321                self.style.color,
322            ),
323        }
324    }
325
326    fn event(&self, _ctx: &mut EventCtx<A>, _event: &Event, _bounds: Rect, _layout: &LayoutResult) {
327    }
328
329    fn focus_policy(&self) -> FocusPolicy {
330        FocusPolicy::NotFocusable
331    }
332}
333
334impl<A: 'static> IntoView<A> for Divider {
335    fn into_view(self) -> View<A> {
336        finish_view_sized(
337            View::leaf(DividerWidget {
338                layout: self.layout,
339                orientation: self.orientation,
340                variant: self.variant,
341                style: self.style,
342            }),
343            self.flex_item,
344            LayoutSizeHint::from_layout(self.layout),
345        )
346    }
347}
348
349/// Paints non-overlapping rectangular segments along the main axis.
350///
351/// The final segment is shortened to the remaining length. Callers guarantee
352/// positive `segment_len` and `gap`, which makes the loop progress.
353fn paint_segments(
354    ctx: &mut PaintCtx<'_>,
355    bounds: Rect,
356    orientation: DividerOrientation,
357    segment_len: f32,
358    gap: f32,
359    color: Color,
360) {
361    let main_len = match orientation {
362        DividerOrientation::Horizontal => bounds.w,
363        DividerOrientation::Vertical => bounds.h,
364    };
365    if main_len <= 0.0 {
366        return;
367    }
368
369    let mut cursor = 0.0;
370    while cursor < main_len {
371        let len = segment_len.min(main_len - cursor);
372        let rect = match orientation {
373            DividerOrientation::Horizontal => Rect::new(bounds.x + cursor, bounds.y, len, bounds.h),
374            DividerOrientation::Vertical => Rect::new(bounds.x, bounds.y + cursor, bounds.w, len),
375        };
376        if rect.w > 0.0 && rect.h > 0.0 {
377            ctx.push(DrawCmd::Rect(DrawRect { rect, color }));
378        }
379        cursor += segment_len + gap;
380    }
381}