iced_widget/
column.rs

1//! Distribute content vertically.
2use crate::core::alignment::{self, Alignment};
3use crate::core::layout;
4use crate::core::mouse;
5use crate::core::overlay;
6use crate::core::renderer;
7use crate::core::widget::{Operation, Tree};
8use crate::core::{
9    Clipboard, Element, Event, Layout, Length, Padding, Pixels, Rectangle,
10    Shell, Size, Vector, Widget,
11};
12
13/// A container that distributes its contents vertically.
14///
15/// # Example
16/// ```no_run
17/// # mod iced { pub mod widget { pub use iced_widget::*; } }
18/// # pub type State = ();
19/// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>;
20/// use iced::widget::{button, column};
21///
22/// #[derive(Debug, Clone)]
23/// enum Message {
24///     // ...
25/// }
26///
27/// fn view(state: &State) -> Element<'_, Message> {
28///     column![
29///         "I am on top!",
30///         button("I am in the center!"),
31///         "I am below.",
32///     ].into()
33/// }
34/// ```
35pub struct Column<'a, Message, Theme = crate::Theme, Renderer = crate::Renderer>
36{
37    spacing: f32,
38    padding: Padding,
39    width: Length,
40    height: Length,
41    max_width: f32,
42    align: Alignment,
43    clip: bool,
44    children: Vec<Element<'a, Message, Theme, Renderer>>,
45}
46
47impl<'a, Message, Theme, Renderer> Column<'a, Message, Theme, Renderer>
48where
49    Renderer: crate::core::Renderer,
50{
51    /// Creates an empty [`Column`].
52    pub fn new() -> Self {
53        Self::from_vec(Vec::new())
54    }
55
56    /// Creates a [`Column`] with the given capacity.
57    pub fn with_capacity(capacity: usize) -> Self {
58        Self::from_vec(Vec::with_capacity(capacity))
59    }
60
61    /// Creates a [`Column`] with the given elements.
62    pub fn with_children(
63        children: impl IntoIterator<Item = Element<'a, Message, Theme, Renderer>>,
64    ) -> Self {
65        let iterator = children.into_iter();
66
67        Self::with_capacity(iterator.size_hint().0).extend(iterator)
68    }
69
70    /// Creates a [`Column`] from an already allocated [`Vec`].
71    ///
72    /// Keep in mind that the [`Column`] will not inspect the [`Vec`], which means
73    /// it won't automatically adapt to the sizing strategy of its contents.
74    ///
75    /// If any of the children have a [`Length::Fill`] strategy, you will need to
76    /// call [`Column::width`] or [`Column::height`] accordingly.
77    pub fn from_vec(
78        children: Vec<Element<'a, Message, Theme, Renderer>>,
79    ) -> Self {
80        Self {
81            spacing: 0.0,
82            padding: Padding::ZERO,
83            width: Length::Shrink,
84            height: Length::Shrink,
85            max_width: f32::INFINITY,
86            align: Alignment::Start,
87            clip: false,
88            children,
89        }
90    }
91
92    /// Sets the vertical spacing _between_ elements.
93    ///
94    /// Custom margins per element do not exist in iced. You should use this
95    /// method instead! While less flexible, it helps you keep spacing between
96    /// elements consistent.
97    pub fn spacing(mut self, amount: impl Into<Pixels>) -> Self {
98        self.spacing = amount.into().0;
99        self
100    }
101
102    /// Sets the [`Padding`] of the [`Column`].
103    pub fn padding<P: Into<Padding>>(mut self, padding: P) -> Self {
104        self.padding = padding.into();
105        self
106    }
107
108    /// Sets the width of the [`Column`].
109    pub fn width(mut self, width: impl Into<Length>) -> Self {
110        self.width = width.into();
111        self
112    }
113
114    /// Sets the height of the [`Column`].
115    pub fn height(mut self, height: impl Into<Length>) -> Self {
116        self.height = height.into();
117        self
118    }
119
120    /// Sets the maximum width of the [`Column`].
121    pub fn max_width(mut self, max_width: impl Into<Pixels>) -> Self {
122        self.max_width = max_width.into().0;
123        self
124    }
125
126    /// Sets the horizontal alignment of the contents of the [`Column`] .
127    pub fn align_x(mut self, align: impl Into<alignment::Horizontal>) -> Self {
128        self.align = Alignment::from(align.into());
129        self
130    }
131
132    /// Sets whether the contents of the [`Column`] should be clipped on
133    /// overflow.
134    pub fn clip(mut self, clip: bool) -> Self {
135        self.clip = clip;
136        self
137    }
138
139    /// Adds an element to the [`Column`].
140    pub fn push(
141        mut self,
142        child: impl Into<Element<'a, Message, Theme, Renderer>>,
143    ) -> Self {
144        let child = child.into();
145        let child_size = child.as_widget().size_hint();
146
147        if !child_size.is_void() {
148            self.width = self.width.enclose(child_size.width);
149            self.height = self.height.enclose(child_size.height);
150            self.children.push(child);
151        }
152
153        self
154    }
155
156    /// Extends the [`Column`] with the given children.
157    pub fn extend(
158        self,
159        children: impl IntoIterator<Item = Element<'a, Message, Theme, Renderer>>,
160    ) -> Self {
161        children.into_iter().fold(self, Self::push)
162    }
163}
164
165impl<Message, Renderer> Default for Column<'_, Message, Renderer>
166where
167    Renderer: crate::core::Renderer,
168{
169    fn default() -> Self {
170        Self::new()
171    }
172}
173
174impl<'a, Message, Theme, Renderer: crate::core::Renderer>
175    FromIterator<Element<'a, Message, Theme, Renderer>>
176    for Column<'a, Message, Theme, Renderer>
177{
178    fn from_iter<
179        T: IntoIterator<Item = Element<'a, Message, Theme, Renderer>>,
180    >(
181        iter: T,
182    ) -> Self {
183        Self::with_children(iter)
184    }
185}
186
187impl<Message, Theme, Renderer> Widget<Message, Theme, Renderer>
188    for Column<'_, Message, Theme, Renderer>
189where
190    Renderer: crate::core::Renderer,
191{
192    fn children(&self) -> Vec<Tree> {
193        self.children.iter().map(Tree::new).collect()
194    }
195
196    fn diff(&self, tree: &mut Tree) {
197        tree.diff_children(&self.children);
198    }
199
200    fn size(&self) -> Size<Length> {
201        Size {
202            width: self.width,
203            height: self.height,
204        }
205    }
206
207    fn layout(
208        &mut self,
209        tree: &mut Tree,
210        renderer: &Renderer,
211        limits: &layout::Limits,
212    ) -> layout::Node {
213        let limits = limits.max_width(self.max_width);
214
215        layout::flex::resolve(
216            layout::flex::Axis::Vertical,
217            renderer,
218            &limits,
219            self.width,
220            self.height,
221            self.padding,
222            self.spacing,
223            self.align,
224            &mut self.children,
225            &mut tree.children,
226        )
227    }
228
229    fn operate(
230        &mut self,
231        tree: &mut Tree,
232        layout: Layout<'_>,
233        renderer: &Renderer,
234        operation: &mut dyn Operation,
235    ) {
236        operation.container(None, layout.bounds());
237        operation.traverse(&mut |operation| {
238            self.children
239                .iter_mut()
240                .zip(&mut tree.children)
241                .zip(layout.children())
242                .for_each(|((child, state), layout)| {
243                    child
244                        .as_widget_mut()
245                        .operate(state, layout, renderer, operation);
246                });
247        });
248    }
249
250    fn update(
251        &mut self,
252        tree: &mut Tree,
253        event: &Event,
254        layout: Layout<'_>,
255        cursor: mouse::Cursor,
256        renderer: &Renderer,
257        clipboard: &mut dyn Clipboard,
258        shell: &mut Shell<'_, Message>,
259        viewport: &Rectangle,
260    ) {
261        for ((child, state), layout) in self
262            .children
263            .iter_mut()
264            .zip(&mut tree.children)
265            .zip(layout.children())
266        {
267            child.as_widget_mut().update(
268                state, event, layout, cursor, renderer, clipboard, shell,
269                viewport,
270            );
271        }
272    }
273
274    fn mouse_interaction(
275        &self,
276        tree: &Tree,
277        layout: Layout<'_>,
278        cursor: mouse::Cursor,
279        viewport: &Rectangle,
280        renderer: &Renderer,
281    ) -> mouse::Interaction {
282        self.children
283            .iter()
284            .zip(&tree.children)
285            .zip(layout.children())
286            .map(|((child, state), layout)| {
287                child.as_widget().mouse_interaction(
288                    state, layout, cursor, viewport, renderer,
289                )
290            })
291            .max()
292            .unwrap_or_default()
293    }
294
295    fn draw(
296        &self,
297        tree: &Tree,
298        renderer: &mut Renderer,
299        theme: &Theme,
300        style: &renderer::Style,
301        layout: Layout<'_>,
302        cursor: mouse::Cursor,
303        viewport: &Rectangle,
304    ) {
305        if let Some(clipped_viewport) = layout.bounds().intersection(viewport) {
306            let viewport = if self.clip {
307                &clipped_viewport
308            } else {
309                viewport
310            };
311
312            for ((child, state), layout) in self
313                .children
314                .iter()
315                .zip(&tree.children)
316                .zip(layout.children())
317                .filter(|(_, layout)| layout.bounds().intersects(viewport))
318            {
319                child.as_widget().draw(
320                    state, renderer, theme, style, layout, cursor, viewport,
321                );
322            }
323        }
324    }
325
326    fn overlay<'b>(
327        &'b mut self,
328        tree: &'b mut Tree,
329        layout: Layout<'b>,
330        renderer: &Renderer,
331        viewport: &Rectangle,
332        translation: Vector,
333    ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> {
334        overlay::from_children(
335            &mut self.children,
336            tree,
337            layout,
338            renderer,
339            viewport,
340            translation,
341        )
342    }
343}
344
345impl<'a, Message, Theme, Renderer> From<Column<'a, Message, Theme, Renderer>>
346    for Element<'a, Message, Theme, Renderer>
347where
348    Message: 'a,
349    Theme: 'a,
350    Renderer: crate::core::Renderer + 'a,
351{
352    fn from(column: Column<'a, Message, Theme, Renderer>) -> Self {
353        Self::new(column)
354    }
355}