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/// ```
35#[allow(missing_debug_implementations)]
36pub struct Column<'a, Message, Theme = crate::Theme, Renderer = crate::Renderer>
37{
38    spacing: f32,
39    padding: Padding,
40    width: Length,
41    height: Length,
42    max_width: f32,
43    align: Alignment,
44    clip: bool,
45    children: Vec<Element<'a, Message, Theme, Renderer>>,
46}
47
48impl<'a, Message, Theme, Renderer> Column<'a, Message, Theme, Renderer>
49where
50    Renderer: crate::core::Renderer,
51{
52    /// Creates an empty [`Column`].
53    pub fn new() -> Self {
54        Self::from_vec(Vec::new())
55    }
56
57    /// Creates a [`Column`] with the given capacity.
58    pub fn with_capacity(capacity: usize) -> Self {
59        Self::from_vec(Vec::with_capacity(capacity))
60    }
61
62    /// Creates a [`Column`] with the given elements.
63    pub fn with_children(
64        children: impl IntoIterator<Item = Element<'a, Message, Theme, Renderer>>,
65    ) -> Self {
66        let iterator = children.into_iter();
67
68        Self::with_capacity(iterator.size_hint().0).extend(iterator)
69    }
70
71    /// Creates a [`Column`] from an already allocated [`Vec`].
72    ///
73    /// Keep in mind that the [`Column`] will not inspect the [`Vec`], which means
74    /// it won't automatically adapt to the sizing strategy of its contents.
75    ///
76    /// If any of the children have a [`Length::Fill`] strategy, you will need to
77    /// call [`Column::width`] or [`Column::height`] accordingly.
78    pub fn from_vec(
79        children: Vec<Element<'a, Message, Theme, Renderer>>,
80    ) -> Self {
81        Self {
82            spacing: 0.0,
83            padding: Padding::ZERO,
84            width: Length::Shrink,
85            height: Length::Shrink,
86            max_width: f32::INFINITY,
87            align: Alignment::Start,
88            clip: false,
89            children,
90        }
91    }
92
93    /// Sets the vertical spacing _between_ elements.
94    ///
95    /// Custom margins per element do not exist in iced. You should use this
96    /// method instead! While less flexible, it helps you keep spacing between
97    /// elements consistent.
98    pub fn spacing(mut self, amount: impl Into<Pixels>) -> Self {
99        self.spacing = amount.into().0;
100        self
101    }
102
103    /// Sets the [`Padding`] of the [`Column`].
104    pub fn padding<P: Into<Padding>>(mut self, padding: P) -> Self {
105        self.padding = padding.into();
106        self
107    }
108
109    /// Sets the width of the [`Column`].
110    pub fn width(mut self, width: impl Into<Length>) -> Self {
111        self.width = width.into();
112        self
113    }
114
115    /// Sets the height of the [`Column`].
116    pub fn height(mut self, height: impl Into<Length>) -> Self {
117        self.height = height.into();
118        self
119    }
120
121    /// Sets the maximum width of the [`Column`].
122    pub fn max_width(mut self, max_width: impl Into<Pixels>) -> Self {
123        self.max_width = max_width.into().0;
124        self
125    }
126
127    /// Sets the horizontal alignment of the contents of the [`Column`] .
128    pub fn align_x(mut self, align: impl Into<alignment::Horizontal>) -> Self {
129        self.align = Alignment::from(align.into());
130        self
131    }
132
133    /// Sets whether the contents of the [`Column`] should be clipped on
134    /// overflow.
135    pub fn clip(mut self, clip: bool) -> Self {
136        self.clip = clip;
137        self
138    }
139
140    /// Adds an element to the [`Column`].
141    pub fn push(
142        mut self,
143        child: impl Into<Element<'a, Message, Theme, Renderer>>,
144    ) -> Self {
145        let child = child.into();
146        let child_size = child.as_widget().size_hint();
147
148        if !child_size.is_void() {
149            self.width = self.width.enclose(child_size.width);
150            self.height = self.height.enclose(child_size.height);
151            self.children.push(child);
152        }
153
154        self
155    }
156
157    /// Extends the [`Column`] with the given children.
158    pub fn extend(
159        self,
160        children: impl IntoIterator<Item = Element<'a, Message, Theme, Renderer>>,
161    ) -> Self {
162        children.into_iter().fold(self, Self::push)
163    }
164}
165
166impl<Message, Renderer> Default for Column<'_, Message, Renderer>
167where
168    Renderer: crate::core::Renderer,
169{
170    fn default() -> Self {
171        Self::new()
172    }
173}
174
175impl<'a, Message, Theme, Renderer: crate::core::Renderer>
176    FromIterator<Element<'a, Message, Theme, Renderer>>
177    for Column<'a, Message, Theme, Renderer>
178{
179    fn from_iter<
180        T: IntoIterator<Item = Element<'a, Message, Theme, Renderer>>,
181    >(
182        iter: T,
183    ) -> Self {
184        Self::with_children(iter)
185    }
186}
187
188impl<Message, Theme, Renderer> Widget<Message, Theme, Renderer>
189    for Column<'_, Message, Theme, Renderer>
190where
191    Renderer: crate::core::Renderer,
192{
193    fn children(&self) -> Vec<Tree> {
194        self.children.iter().map(Tree::new).collect()
195    }
196
197    fn diff(&self, tree: &mut Tree) {
198        tree.diff_children(&self.children);
199    }
200
201    fn size(&self) -> Size<Length> {
202        Size {
203            width: self.width,
204            height: self.height,
205        }
206    }
207
208    fn layout(
209        &self,
210        tree: &mut Tree,
211        renderer: &Renderer,
212        limits: &layout::Limits,
213    ) -> layout::Node {
214        let limits = limits.max_width(self.max_width);
215
216        layout::flex::resolve(
217            layout::flex::Axis::Vertical,
218            renderer,
219            &limits,
220            self.width,
221            self.height,
222            self.padding,
223            self.spacing,
224            self.align,
225            &self.children,
226            &mut tree.children,
227        )
228    }
229
230    fn operate(
231        &self,
232        tree: &mut Tree,
233        layout: Layout<'_>,
234        renderer: &Renderer,
235        operation: &mut dyn Operation,
236    ) {
237        operation.container(None, layout.bounds(), &mut |operation| {
238            self.children
239                .iter()
240                .zip(&mut tree.children)
241                .zip(layout.children())
242                .for_each(|((child, state), layout)| {
243                    child
244                        .as_widget()
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}