ailloli_ui_widgets/layout/
container.rs

1//! Declarative single-child box model with background, border, shadow, and clip.
2
3use ailloli_ui_core::event::Event;
4use ailloli_ui_core::geometry::{ClipShape, Constraints, Rect, Size};
5use ailloli_ui_core::style::{
6    Background, Border, BoxShadow, BoxStyle, FlexItemStyle, LayoutSizeHint, LayoutStyle, Radius,
7};
8use ailloli_ui_core::{Color, EdgeInsets, Offset, Theme};
9use ailloli_ui_runtime::component::{IntoView, View, Widget};
10use ailloli_ui_runtime::input::EventCtx;
11use ailloli_ui_runtime::layout::LayoutEngine;
12use ailloli_ui_runtime::layout::{ChildLayout, LayoutChild, LayoutCtx, LayoutResult};
13use ailloli_ui_runtime::scene::PaintCtx;
14use ailloli_ui_runtime::{DrawBorder, DrawBoxShadow, DrawCmd, DrawRRect, DrawRect};
15
16use super::layout_ext::finish_view_sized;
17
18/// Insets a rectangle and floors resulting dimensions at zero.
19fn deflate_rect(mut rect: Rect, by: EdgeInsets) -> Rect {
20    rect.x += by.left;
21    rect.y += by.top;
22    rect.w = (rect.w - by.left - by.right).max(0.0);
23    rect.h = (rect.h - by.top - by.bottom).max(0.0);
24    rect
25}
26
27/// Subtracts insets independently from every constraint bound, floored at zero.
28fn deflate_constraints(c: Constraints, by: EdgeInsets) -> Constraints {
29    Constraints {
30        min_w: (c.min_w - by.horizontal()).max(0.0),
31        max_w: (c.max_w - by.horizontal()).max(0.0),
32        min_h: (c.min_h - by.vertical()).max(0.0),
33        max_h: (c.max_h - by.vertical()).max(0.0),
34    }
35}
36
37/// Adds corresponding inset edges without overflow or finiteness checks.
38fn add_insets(a: EdgeInsets, b: EdgeInsets) -> EdgeInsets {
39    EdgeInsets::new(
40        a.left + b.left,
41        a.top + b.top,
42        a.right + b.right,
43        a.bottom + b.bottom,
44    )
45}
46
47/// Inflates a size by horizontal and vertical inset totals.
48fn add_insets_to_size(size: Size, insets: EdgeInsets) -> Size {
49    Size::new(size.w + insets.horizontal(), size.h + insets.vertical())
50}
51
52/// Multiplies alpha and clamps the result to the normalized color range.
53fn apply_opacity(mut c: Color, opacity: f32) -> Color {
54    c.a = (c.a * opacity).clamp(0.0, 1.0);
55    c
56}
57
58/// Applies container opacity independently to all four border colors.
59fn apply_border_opacity(mut border: Border, opacity: f32) -> Border {
60    border.colors.left = apply_opacity(border.colors.left, opacity);
61    border.colors.top = apply_opacity(border.colors.top, opacity);
62    border.colors.right = apply_opacity(border.colors.right, opacity);
63    border.colors.bottom = apply_opacity(border.colors.bottom, opacity);
64    border
65}
66
67/// Applies container opacity to a shadow color.
68fn apply_shadow_opacity(mut shadow: BoxShadow, opacity: f32) -> BoxShadow {
69    shadow.color = apply_opacity(shadow.color, opacity);
70    shadow
71}
72
73/// Returns the last shadow, first inserting the medium default when empty.
74fn ensure_shadow(shadows: &mut Vec<BoxShadow>) -> &mut BoxShadow {
75    if shadows.is_empty() {
76        shadows.push(BoxShadow::md());
77    }
78    shadows.last_mut().expect("shadow inserted when empty")
79}
80
81/// Returns the smallest axis-aligned rectangle containing both inputs.
82fn union_rect(a: Rect, b: Rect) -> Rect {
83    let x0 = a.x.min(b.x);
84    let y0 = a.y.min(b.y);
85    let x1 = a.right().max(b.right());
86    let y1 = a.bottom().max(b.bottom());
87    Rect::new(x0, y0, x1 - x0, y1 - y0)
88}
89
90/// Declarative box with background, border, shadows, and optional child clip.
91///
92/// The default is transparent, borderless, shadowless, unclipped, automatically
93/// sized, and has no child. Margin surrounds the border box; border and padding
94/// surround the content. Only one child is retained.
95///
96/// # Examples
97///
98/// ```
99/// use ailloli_ui_core::Color;
100/// use ailloli_ui_widgets::{layout::Container, text::Text};
101/// let card: Container<()> = Container::new().background(Color::BLACK).padding(8.0).child(Text::new("Body"));
102/// let _ = card;
103/// ```
104pub struct Container<A = ()> {
105    /// Outer logical sizing policy.
106    pub(crate) layout: LayoutStyle,
107    /// Parent-flex participation metadata.
108    pub(crate) flex_item: FlexItemStyle,
109    /// Background, border, radius, padding, and shadow styling.
110    box_style: BoxStyle,
111    /// Whether child paint and hit testing are clipped to the content shape.
112    clip_children: bool,
113    /// Whether this clip establishes the native window-root boundary.
114    window_root_clip: bool,
115    /// Optional sole retained child.
116    child: Option<View<A>>,
117}
118
119crate::impl_layout_builders!(Container);
120
121/// Creates the same empty transparent box as [`Container::new`].
122impl<A: 'static> Default for Container<A> {
123    fn default() -> Self {
124        Self::new()
125    }
126}
127
128impl<A: 'static> Container<A> {
129    /// Creates an empty transparent box with automatic layout.
130    ///
131    /// # Examples
132    ///
133    /// ```
134    /// use ailloli_ui_widgets::layout::Container;
135    /// let container: Container<()> = Container::new();
136    /// let _ = container;
137    /// ```
138    pub fn new() -> Self {
139        Self {
140            layout: LayoutStyle::default(),
141            flex_item: FlexItemStyle::default(),
142            box_style: BoxStyle::default(),
143            clip_children: false,
144            window_root_clip: false,
145            child: None,
146        }
147    }
148
149    /// Creates a theme surface with a one-pixel border and large radius.
150    ///
151    /// # Examples
152    ///
153    /// ```
154    /// use ailloli_ui_core::Theme;
155    /// use ailloli_ui_widgets::layout::Container;
156    /// let surface: Container<()> = Container::surface(Theme::dark());
157    /// let _ = surface;
158    /// ```
159    pub fn surface(theme: Theme) -> Self {
160        let palette = theme.palette();
161        Self::new()
162            .background(palette.surface)
163            .border(1.0, palette.border)
164            .radius(theme.radius().lg)
165    }
166
167    /// Creates an elevated themed surface with the medium theme shadow.
168    ///
169    /// # Examples
170    ///
171    /// ```
172    /// use ailloli_ui_core::Theme;
173    /// use ailloli_ui_widgets::layout::Container;
174    /// let panel: Container<()> = Container::panel(Theme::dark());
175    /// let _ = panel;
176    /// ```
177    pub fn panel(theme: Theme) -> Self {
178        let palette = theme.palette();
179        Self::surface(theme)
180            .background(palette.surface_elevated)
181            .shadow(theme.shadows().md)
182    }
183
184    /// Replaces the background with one solid color.
185    ///
186    /// # Examples
187    ///
188    /// ```
189    /// use ailloli_ui_core::Color;
190    /// use ailloli_ui_widgets::layout::Container;
191    /// let box_: Container<()> = Container::new().background(Color::BLACK);
192    /// let _ = box_;
193    /// ```
194    pub fn background(mut self, color: Color) -> Self {
195        self.box_style.background = Background::color(color);
196        self
197    }
198
199    /// Sets a uniform logical-pixel corner radius without clamping.
200    ///
201    /// # Examples
202    ///
203    /// ```
204    /// use ailloli_ui_widgets::layout::Container;
205    /// let box_: Container<()> = Container::new().radius(8.0);
206    /// let _ = box_;
207    /// ```
208    pub fn radius(mut self, value: f32) -> Self {
209        self.box_style.radius = Radius::uniform(value);
210        self
211    }
212
213    /// Replaces all four border widths and colors.
214    ///
215    /// Width normalization follows [`Border::new`].
216    ///
217    /// # Examples
218    ///
219    /// ```
220    /// use ailloli_ui_core::Color;
221    /// use ailloli_ui_widgets::layout::Container;
222    /// let box_: Container<()> = Container::new().border(1.0, Color::WHITE);
223    /// let _ = box_;
224    /// ```
225    pub fn border(mut self, width: f32, color: Color) -> Self {
226        self.box_style.border = Border::new(width, color);
227        self
228    }
229
230    /// Replaces all four widths while preserving edge colors.
231    ///
232    /// # Examples
233    ///
234    /// ```
235    /// use ailloli_ui_widgets::layout::Container;
236    /// let box_: Container<()> = Container::new().border_width(2.0);
237    /// let _ = box_;
238    /// ```
239    pub fn border_width(mut self, width: f32) -> Self {
240        self.box_style.border = self.box_style.border.with_width(width);
241        self
242    }
243
244    /// Replaces all four colors while preserving edge widths.
245    ///
246    /// # Examples
247    ///
248    /// ```
249    /// use ailloli_ui_core::Color;
250    /// use ailloli_ui_widgets::layout::Container;
251    /// let box_: Container<()> = Container::new().border_color(Color::WHITE);
252    /// let _ = box_;
253    /// ```
254    pub fn border_color(mut self, color: Color) -> Self {
255        self.box_style.border = self.box_style.border.with_color(color);
256        self
257    }
258
259    /// Replaces only the left border width and color.
260    ///
261    /// # Examples
262    ///
263    /// ```
264    /// use ailloli_ui_core::Color;
265    /// use ailloli_ui_widgets::layout::Container;
266    /// let box_: Container<()> = Container::new().border_left(2.0, Color::WHITE);
267    /// let _ = box_;
268    /// ```
269    pub fn border_left(mut self, width: f32, color: Color) -> Self {
270        self.box_style.border = self.box_style.border.with_left(width, color);
271        self
272    }
273
274    /// Replaces only the top border width and color.
275    ///
276    /// # Examples
277    ///
278    /// ```
279    /// use ailloli_ui_core::Color;
280    /// use ailloli_ui_widgets::layout::Container;
281    /// let box_: Container<()> = Container::new().border_top(2.0, Color::WHITE);
282    /// let _ = box_;
283    /// ```
284    pub fn border_top(mut self, width: f32, color: Color) -> Self {
285        self.box_style.border = self.box_style.border.with_top(width, color);
286        self
287    }
288
289    /// Replaces only the right border width and color.
290    ///
291    /// # Examples
292    ///
293    /// ```
294    /// use ailloli_ui_core::Color;
295    /// use ailloli_ui_widgets::layout::Container;
296    /// let box_: Container<()> = Container::new().border_right(2.0, Color::WHITE);
297    /// let _ = box_;
298    /// ```
299    pub fn border_right(mut self, width: f32, color: Color) -> Self {
300        self.box_style.border = self.box_style.border.with_right(width, color);
301        self
302    }
303
304    /// Replaces only the bottom border width and color.
305    ///
306    /// # Examples
307    ///
308    /// ```
309    /// use ailloli_ui_core::Color;
310    /// use ailloli_ui_widgets::layout::Container;
311    /// let box_: Container<()> = Container::new().border_bottom(2.0, Color::WHITE);
312    /// let _ = box_;
313    /// ```
314    pub fn border_bottom(mut self, width: f32, color: Color) -> Self {
315        self.box_style.border = self.box_style.border.with_bottom(width, color);
316        self
317    }
318
319    /// Appends one shadow; later shadows paint after earlier shadows.
320    ///
321    /// # Examples
322    ///
323    /// ```
324    /// use ailloli_ui_core::style::BoxShadow;
325    /// use ailloli_ui_widgets::layout::Container;
326    /// let box_: Container<()> = Container::new().shadow(BoxShadow::md());
327    /// let _ = box_;
328    /// ```
329    pub fn shadow(mut self, shadow: BoxShadow) -> Self {
330        self.box_style.shadows.push(shadow);
331        self
332    }
333
334    /// Removes every configured shadow.
335    ///
336    /// # Examples
337    ///
338    /// ```
339    /// use ailloli_ui_core::style::BoxShadow;
340    /// use ailloli_ui_widgets::layout::Container;
341    /// let box_: Container<()> = Container::new().shadow(BoxShadow::md()).shadow_none();
342    /// let _ = box_;
343    /// ```
344    pub fn shadow_none(mut self) -> Self {
345        self.box_style.shadows.clear();
346        self
347    }
348
349    /// Replaces the last shadow color, inserting a medium shadow if absent.
350    ///
351    /// # Examples
352    ///
353    /// ```
354    /// use ailloli_ui_core::Color;
355    /// use ailloli_ui_widgets::layout::Container;
356    /// let box_: Container<()> = Container::new().shadow_color(Color::BLACK);
357    /// let _ = box_;
358    /// ```
359    pub fn shadow_color(mut self, color: Color) -> Self {
360        ensure_shadow(&mut self.box_style.shadows).color = color;
361        self
362    }
363
364    /// Replaces the last shadow blur radius in logical pixels.
365    ///
366    /// Negative and `NaN` values resolve to zero; an absent shadow first inserts
367    /// the medium default.
368    ///
369    /// # Examples
370    ///
371    /// ```
372    /// use ailloli_ui_widgets::layout::Container;
373    /// let box_: Container<()> = Container::new().shadow_blur(12.0);
374    /// let _ = box_;
375    /// ```
376    pub fn shadow_blur(mut self, value: f32) -> Self {
377        ensure_shadow(&mut self.box_style.shadows).blur_radius = value.max(0.0);
378        self
379    }
380
381    /// Replaces the last shadow offset in logical pixels.
382    ///
383    /// Values are stored without finiteness checks; an absent shadow first
384    /// inserts the medium default.
385    ///
386    /// # Examples
387    ///
388    /// ```
389    /// use ailloli_ui_widgets::layout::Container;
390    /// let box_: Container<()> = Container::new().shadow_offset(0.0, 4.0);
391    /// let _ = box_;
392    /// ```
393    pub fn shadow_offset(mut self, x: f32, y: f32) -> Self {
394        ensure_shadow(&mut self.box_style.shadows).offset = Offset::new(x, y);
395        self
396    }
397
398    /// Replaces the last shadow spread in logical pixels.
399    ///
400    /// Negative and `NaN` values resolve to zero; an absent shadow first inserts
401    /// the medium default.
402    ///
403    /// # Examples
404    ///
405    /// ```
406    /// use ailloli_ui_widgets::layout::Container;
407    /// let box_: Container<()> = Container::new().shadow_spread(2.0);
408    /// let _ = box_;
409    /// ```
410    pub fn shadow_spread(mut self, value: f32) -> Self {
411        ensure_shadow(&mut self.box_style.shadows).spread = value.max(0.0);
412        self
413    }
414
415    /// Clips children to the inner rect (rounded when `radius > 0`).
416    ///
417    /// The clip excludes margin, border, and padding. It is disabled by default.
418    ///
419    /// # Examples
420    ///
421    /// ```
422    /// use ailloli_ui_widgets::layout::Container;
423    /// let box_: Container<()> = Container::new().radius(8.0).clip_children(true);
424    /// let _ = box_;
425    /// ```
426    pub fn clip_children(mut self, value: bool) -> Self {
427        self.clip_children = value;
428        self
429    }
430
431    /// Marks this container as the window root clip (`Window::radius`).
432    /// Enables window-root stencil heuristics on the GPU path.
433    ///
434    /// This marker is independent of `clip_children`; callers are responsible
435    /// for applying it only to the actual root clip.
436    ///
437    /// # Examples
438    ///
439    /// ```
440    /// use ailloli_ui_widgets::layout::Container;
441    /// let root: Container<()> = Container::new().clip_children(true).window_root_clip(true);
442    /// let _ = root;
443    /// ```
444    pub fn window_root_clip(mut self, value: bool) -> Self {
445        self.window_root_clip = value;
446        self
447    }
448
449    /// Sets the single content child, replacing any previous child.
450    ///
451    /// # Examples
452    ///
453    /// ```
454    /// use ailloli_ui_widgets::{layout::Container, text::Text};
455    /// let box_: Container<()> = Container::new().child(Text::new("content"));
456    /// let _ = box_;
457    /// ```
458    pub fn child(mut self, child: impl IntoView<A>) -> Self {
459        self.child = Some(child.into_view());
460        self
461    }
462}
463
464/// Frozen box/layout state installed in the retained tree.
465struct ContainerWidget {
466    /// Outer logical sizing policy.
467    layout: LayoutStyle,
468    /// Background, border, radius, padding, and shadow styling.
469    style: BoxStyle,
470    /// Whether child paint and hit testing are clipped to the content shape.
471    clip_children: bool,
472    /// Whether this clip establishes the native window-root boundary.
473    window_root_clip: bool,
474}
475
476/// Implements box-model layout, clip publication, and layered surface painting.
477impl<A: 'static> Widget<A> for ContainerWidget {
478    fn debug_name(&self) -> &'static str {
479        "Container"
480    }
481
482    fn layout(
483        &self,
484        engine: &mut LayoutEngine<'_, A>,
485        ctx: &mut LayoutCtx<'_>,
486        children: &mut [LayoutChild],
487        constraints: Constraints,
488    ) -> LayoutResult {
489        let m = self.layout.margin;
490        let p = self.layout.padding;
491        let b = self.style.border.layout_widths();
492        let content_insets = add_insets(b, p);
493
494        let outer_constraints = deflate_constraints(constraints, m);
495
496        let slot_tight = outer_constraints.min_w == outer_constraints.max_w
497            && outer_constraints.min_h == outer_constraints.max_h;
498
499        let inner = if slot_tight {
500            deflate_constraints(outer_constraints, content_insets)
501        } else {
502            let inner = self.layout.constraints_for_children(outer_constraints);
503            deflate_constraints(inner, content_insets)
504        };
505
506        let mut child_layouts = Vec::new();
507        let mut child_size = Size::default();
508
509        if let Some(child) = children.first_mut() {
510            let r = child.layout(engine, ctx, inner);
511            child_size = r.size;
512            child_layouts.push(ChildLayout {
513                offset: Offset::new(m.left + b.left + p.left, m.top + b.top + p.top),
514                size: r.size,
515                paint_bounds: Rect::new(0.0, 0.0, r.size.w, r.size.h),
516                visual_bounds: r.visual_bounds,
517            });
518        }
519
520        let border_box = add_insets_to_size(child_size, content_insets);
521        let outer_box = add_insets_to_size(border_box, m);
522
523        let size = {
524            let resolved = self.layout.resolve(constraints);
525            let (mut w, mut h) = resolved.size(outer_box.w, outer_box.h, constraints);
526            if slot_tight && !self.layout.width.is_auto() {
527                w = outer_constraints.max_w;
528            }
529            if slot_tight && !self.layout.height.is_auto() {
530                h = outer_constraints.max_h;
531            }
532            Size::new(w, h)
533        };
534
535        let content_bounds = deflate_rect(
536            Rect::new(
537                m.left,
538                m.top,
539                (size.w - m.horizontal()).max(0.0),
540                (size.h - m.vertical()).max(0.0),
541            ),
542            content_insets,
543        );
544        let inner_radius = self.style.border.inner_radius(self.style.radius);
545        let clip_radius = (inner_radius.tl - p.left.max(p.top)).max(0.0);
546        let clip = if self.clip_children {
547            if clip_radius > 0.0 {
548                Some(ClipShape::RoundRect {
549                    rect: content_bounds,
550                    radius: clip_radius,
551                })
552            } else {
553                Some(ClipShape::Rect(content_bounds))
554            }
555        } else {
556            None
557        };
558
559        let paint_bounds = Rect::new(0.0, 0.0, size.w, size.h);
560        let border_bounds = deflate_rect(paint_bounds, m);
561        let visual_bounds = union_rect(paint_bounds, self.style.visual_bounds(border_bounds));
562
563        LayoutResult {
564            size,
565            children: child_layouts,
566            paint_bounds,
567            visual_bounds,
568            overlay_hit_bounds: Vec::new(),
569            clip,
570            is_window_root_clip: self.window_root_clip,
571            artifact: None,
572        }
573    }
574
575    fn paint(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, _layout: &LayoutResult) {
576        let border_bounds = deflate_rect(bounds, self.layout.margin);
577        let opacity = self.style.opacity.0;
578
579        for shadow in self.style.shadows.iter().copied().filter(|s| !s.inset) {
580            let shadow = apply_shadow_opacity(shadow, opacity);
581            if shadow.color.a > 0.0 {
582                ctx.push(DrawCmd::BoxShadow(DrawBoxShadow {
583                    rect: border_bounds,
584                    radius: self.style.radius,
585                    shadow,
586                }));
587            }
588        }
589
590        if let Background::Color(bg) = self.style.background {
591            let bg = apply_opacity(bg, opacity);
592            if self.style.radius != Radius::zero() {
593                ctx.push(DrawCmd::RRect(DrawRRect {
594                    rect: border_bounds,
595                    radius: self.style.radius.tl,
596                    color: bg,
597                }));
598            } else {
599                ctx.push(DrawCmd::Rect(DrawRect {
600                    rect: border_bounds,
601                    color: bg,
602                }));
603            }
604        }
605    }
606
607    fn paint_overlay(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, _layout: &LayoutResult) {
608        let border = apply_border_opacity(self.style.border, self.style.opacity.0);
609        if border.is_visible() {
610            ctx.push(DrawCmd::Border(DrawBorder {
611                rect: deflate_rect(bounds, self.layout.margin),
612                radius: self.style.radius,
613                border,
614            }));
615        }
616    }
617
618    fn event(&self, _ctx: &mut EventCtx<A>, _event: &Event, _bounds: Rect, _layout: &LayoutResult) {
619    }
620}
621
622/// Converts the builder into one retained box node and optional child.
623impl<A: 'static> IntoView<A> for Container<A> {
624    fn into_view(self) -> View<A> {
625        let widget = ContainerWidget {
626            layout: self.layout,
627            style: self.box_style,
628            clip_children: self.clip_children,
629            window_root_clip: self.window_root_clip,
630        };
631
632        let mut children = Vec::new();
633        if let Some(child) = self.child {
634            children.push(child);
635        }
636        finish_view_sized(
637            View::node(widget, children),
638            self.flex_item,
639            LayoutSizeHint::from_layout(self.layout),
640        )
641    }
642}