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        self.width = self.width.enclose(child_size.width);
149        self.height = self.height.enclose(child_size.height);
150
151        self.children.push(child);
152        self
153    }
154
155    /// Adds an element to the [`Column`], if `Some`.
156    pub fn push_maybe(
157        self,
158        child: Option<impl Into<Element<'a, Message, Theme, Renderer>>>,
159    ) -> Self {
160        if let Some(child) = child {
161            self.push(child)
162        } else {
163            self
164        }
165    }
166
167    /// Extends the [`Column`] with the given children.
168    pub fn extend(
169        self,
170        children: impl IntoIterator<Item = Element<'a, Message, Theme, Renderer>>,
171    ) -> Self {
172        children.into_iter().fold(self, Self::push)
173    }
174}
175
176impl<Message, Renderer> Default for Column<'_, Message, Renderer>
177where
178    Renderer: crate::core::Renderer,
179{
180    fn default() -> Self {
181        Self::new()
182    }
183}
184
185impl<'a, Message, Theme, Renderer: crate::core::Renderer>
186    FromIterator<Element<'a, Message, Theme, Renderer>>
187    for Column<'a, Message, Theme, Renderer>
188{
189    fn from_iter<
190        T: IntoIterator<Item = Element<'a, Message, Theme, Renderer>>,
191    >(
192        iter: T,
193    ) -> Self {
194        Self::with_children(iter)
195    }
196}
197
198impl<Message, Theme, Renderer> Widget<Message, Theme, Renderer>
199    for Column<'_, Message, Theme, Renderer>
200where
201    Renderer: crate::core::Renderer,
202{
203    fn children(&self) -> Vec<Tree> {
204        self.children.iter().map(Tree::new).collect()
205    }
206
207    fn diff(&self, tree: &mut Tree) {
208        tree.diff_children(&self.children);
209    }
210
211    fn size(&self) -> Size<Length> {
212        Size {
213            width: self.width,
214            height: self.height,
215        }
216    }
217
218    fn layout(
219        &self,
220        tree: &mut Tree,
221        renderer: &Renderer,
222        limits: &layout::Limits,
223    ) -> layout::Node {
224        let limits = limits.max_width(self.max_width);
225
226        layout::flex::resolve(
227            layout::flex::Axis::Vertical,
228            renderer,
229            &limits,
230            self.width,
231            self.height,
232            self.padding,
233            self.spacing,
234            self.align,
235            &self.children,
236            &mut tree.children,
237        )
238    }
239
240    fn operate(
241        &self,
242        tree: &mut Tree,
243        layout: Layout<'_>,
244        renderer: &Renderer,
245        operation: &mut dyn Operation,
246    ) {
247        operation.container(None, layout.bounds(), &mut |operation| {
248            self.children
249                .iter()
250                .zip(&mut tree.children)
251                .zip(layout.children())
252                .for_each(|((child, state), layout)| {
253                    child
254                        .as_widget()
255                        .operate(state, layout, renderer, operation);
256                });
257        });
258    }
259
260    fn update(
261        &mut self,
262        tree: &mut Tree,
263        event: &Event,
264        layout: Layout<'_>,
265        cursor: mouse::Cursor,
266        renderer: &Renderer,
267        clipboard: &mut dyn Clipboard,
268        shell: &mut Shell<'_, Message>,
269        viewport: &Rectangle,
270    ) {
271        for ((child, state), layout) in self
272            .children
273            .iter_mut()
274            .zip(&mut tree.children)
275            .zip(layout.children())
276        {
277            child.as_widget_mut().update(
278                state, event, layout, cursor, renderer, clipboard, shell,
279                viewport,
280            );
281        }
282    }
283
284    fn mouse_interaction(
285        &self,
286        tree: &Tree,
287        layout: Layout<'_>,
288        cursor: mouse::Cursor,
289        viewport: &Rectangle,
290        renderer: &Renderer,
291    ) -> mouse::Interaction {
292        self.children
293            .iter()
294            .zip(&tree.children)
295            .zip(layout.children())
296            .map(|((child, state), layout)| {
297                child.as_widget().mouse_interaction(
298                    state, layout, cursor, viewport, renderer,
299                )
300            })
301            .max()
302            .unwrap_or_default()
303    }
304
305    fn draw(
306        &self,
307        tree: &Tree,
308        renderer: &mut Renderer,
309        theme: &Theme,
310        style: &renderer::Style,
311        layout: Layout<'_>,
312        cursor: mouse::Cursor,
313        viewport: &Rectangle,
314    ) {
315        if let Some(clipped_viewport) = layout.bounds().intersection(viewport) {
316            let viewport = if self.clip {
317                &clipped_viewport
318            } else {
319                viewport
320            };
321
322            for ((child, state), layout) in self
323                .children
324                .iter()
325                .zip(&tree.children)
326                .zip(layout.children())
327                .filter(|(_, layout)| layout.bounds().intersects(viewport))
328            {
329                child.as_widget().draw(
330                    state, renderer, theme, style, layout, cursor, viewport,
331                );
332            }
333        }
334    }
335
336    fn overlay<'b>(
337        &'b mut self,
338        tree: &'b mut Tree,
339        layout: Layout<'_>,
340        renderer: &Renderer,
341        translation: Vector,
342    ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> {
343        overlay::from_children(
344            &mut self.children,
345            tree,
346            layout,
347            renderer,
348            translation,
349        )
350    }
351}
352
353impl<'a, Message, Theme, Renderer> From<Column<'a, Message, Theme, Renderer>>
354    for Element<'a, Message, Theme, Renderer>
355where
356    Message: 'a,
357    Theme: 'a,
358    Renderer: crate::core::Renderer + 'a,
359{
360    fn from(column: Column<'a, Message, Theme, Renderer>) -> Self {
361        Self::new(column)
362    }
363}