Skip to main content

cosmic/widget/menu/
menu_column.rs

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