iced_widget/keyed/
column.rs

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