iced_widget/
row.rs

1//! Distribute content horizontally.
2use crate::core::alignment::{self, Alignment};
3use crate::core::layout::{self, 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, Length, Padding, Pixels, Rectangle, Shell, Size,
10    Vector, Widget,
11};
12
13/// A container that distributes its contents horizontally.
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, row};
21///
22/// #[derive(Debug, Clone)]
23/// enum Message {
24///     // ...
25/// }
26///
27/// fn view(state: &State) -> Element<'_, Message> {
28///     row![
29///         "I am to the left!",
30///         button("I am in the middle!"),
31///         "I am to the right!",
32///     ].into()
33/// }
34/// ```
35pub struct Row<'a, Message, Theme = crate::Theme, Renderer = crate::Renderer> {
36    spacing: f32,
37    padding: Padding,
38    width: Length,
39    height: Length,
40    align: Alignment,
41    clip: bool,
42    children: Vec<Element<'a, Message, Theme, Renderer>>,
43}
44
45impl<'a, Message, Theme, Renderer> Row<'a, Message, Theme, Renderer>
46where
47    Renderer: crate::core::Renderer,
48{
49    /// Creates an empty [`Row`].
50    pub fn new() -> Self {
51        Self::from_vec(Vec::new())
52    }
53
54    /// Creates a [`Row`] with the given capacity.
55    pub fn with_capacity(capacity: usize) -> Self {
56        Self::from_vec(Vec::with_capacity(capacity))
57    }
58
59    /// Creates a [`Row`] with the given elements.
60    pub fn with_children(
61        children: impl IntoIterator<Item = Element<'a, Message, Theme, Renderer>>,
62    ) -> Self {
63        let iterator = children.into_iter();
64
65        Self::with_capacity(iterator.size_hint().0).extend(iterator)
66    }
67
68    /// Creates a [`Row`] from an already allocated [`Vec`].
69    ///
70    /// Keep in mind that the [`Row`] will not inspect the [`Vec`], which means
71    /// it won't automatically adapt to the sizing strategy of its contents.
72    ///
73    /// If any of the children have a [`Length::Fill`] strategy, you will need to
74    /// call [`Row::width`] or [`Row::height`] accordingly.
75    pub fn from_vec(
76        children: Vec<Element<'a, Message, Theme, Renderer>>,
77    ) -> Self {
78        Self {
79            spacing: 0.0,
80            padding: Padding::ZERO,
81            width: Length::Shrink,
82            height: Length::Shrink,
83            align: Alignment::Start,
84            clip: false,
85            children,
86        }
87    }
88
89    /// Sets the horizontal spacing _between_ elements.
90    ///
91    /// Custom margins per element do not exist in iced. You should use this
92    /// method instead! While less flexible, it helps you keep spacing between
93    /// elements consistent.
94    pub fn spacing(mut self, amount: impl Into<Pixels>) -> Self {
95        self.spacing = amount.into().0;
96        self
97    }
98
99    /// Sets the [`Padding`] of the [`Row`].
100    pub fn padding<P: Into<Padding>>(mut self, padding: P) -> Self {
101        self.padding = padding.into();
102        self
103    }
104
105    /// Sets the width of the [`Row`].
106    pub fn width(mut self, width: impl Into<Length>) -> Self {
107        self.width = width.into();
108        self
109    }
110
111    /// Sets the height of the [`Row`].
112    pub fn height(mut self, height: impl Into<Length>) -> Self {
113        self.height = height.into();
114        self
115    }
116
117    /// Sets the vertical alignment of the contents of the [`Row`] .
118    pub fn align_y(mut self, align: impl Into<alignment::Vertical>) -> Self {
119        self.align = Alignment::from(align.into());
120        self
121    }
122
123    /// Sets whether the contents of the [`Row`] should be clipped on
124    /// overflow.
125    pub fn clip(mut self, clip: bool) -> Self {
126        self.clip = clip;
127        self
128    }
129
130    /// Adds an [`Element`] to the [`Row`].
131    pub fn push(
132        mut self,
133        child: impl Into<Element<'a, Message, Theme, Renderer>>,
134    ) -> Self {
135        let child = child.into();
136        let child_size = child.as_widget().size_hint();
137
138        if !child_size.is_void() {
139            self.width = self.width.enclose(child_size.width);
140            self.height = self.height.enclose(child_size.height);
141            self.children.push(child);
142        }
143
144        self
145    }
146
147    /// Extends the [`Row`] with the given children.
148    pub fn extend(
149        self,
150        children: impl IntoIterator<Item = Element<'a, Message, Theme, Renderer>>,
151    ) -> Self {
152        children.into_iter().fold(self, Self::push)
153    }
154
155    /// Turns the [`Row`] into a [`Wrapping`] row.
156    ///
157    /// The original alignment of the [`Row`] is preserved per row wrapped.
158    pub fn wrap(self) -> Wrapping<'a, Message, Theme, Renderer> {
159        Wrapping {
160            row: self,
161            vertical_spacing: None,
162            align_x: alignment::Horizontal::Left,
163        }
164    }
165}
166
167impl<Message, Renderer> Default for Row<'_, Message, Renderer>
168where
169    Renderer: crate::core::Renderer,
170{
171    fn default() -> Self {
172        Self::new()
173    }
174}
175
176impl<'a, Message, Theme, Renderer: crate::core::Renderer>
177    FromIterator<Element<'a, Message, Theme, Renderer>>
178    for Row<'a, Message, Theme, Renderer>
179{
180    fn from_iter<
181        T: IntoIterator<Item = Element<'a, Message, Theme, Renderer>>,
182    >(
183        iter: T,
184    ) -> Self {
185        Self::with_children(iter)
186    }
187}
188
189impl<Message, Theme, Renderer> Widget<Message, Theme, Renderer>
190    for Row<'_, Message, Theme, Renderer>
191where
192    Renderer: crate::core::Renderer,
193{
194    fn children(&self) -> Vec<Tree> {
195        self.children.iter().map(Tree::new).collect()
196    }
197
198    fn diff(&self, tree: &mut Tree) {
199        tree.diff_children(&self.children);
200    }
201
202    fn size(&self) -> Size<Length> {
203        Size {
204            width: self.width,
205            height: self.height,
206        }
207    }
208
209    fn layout(
210        &mut self,
211        tree: &mut Tree,
212        renderer: &Renderer,
213        limits: &layout::Limits,
214    ) -> layout::Node {
215        layout::flex::resolve(
216            layout::flex::Axis::Horizontal,
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<Row<'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(row: Row<'a, Message, Theme, Renderer>) -> Self {
353        Self::new(row)
354    }
355}
356
357/// A [`Row`] that wraps its contents.
358///
359/// Create a [`Row`] first, and then call [`Row::wrap`] to
360/// obtain a [`Row`] that wraps its contents.
361///
362/// The original alignment of the [`Row`] is preserved per row wrapped.
363pub struct Wrapping<
364    'a,
365    Message,
366    Theme = crate::Theme,
367    Renderer = crate::Renderer,
368> {
369    row: Row<'a, Message, Theme, Renderer>,
370    vertical_spacing: Option<f32>,
371    align_x: alignment::Horizontal,
372}
373
374impl<Message, Theme, Renderer> Wrapping<'_, Message, Theme, Renderer> {
375    /// Sets the vertical spacing _between_ lines.
376    pub fn vertical_spacing(mut self, amount: impl Into<Pixels>) -> Self {
377        self.vertical_spacing = Some(amount.into().0);
378        self
379    }
380
381    /// Sets the horizontal alignment of the wrapping [`Row`].
382    pub fn align_x(
383        mut self,
384        align_x: impl Into<alignment::Horizontal>,
385    ) -> Self {
386        self.align_x = align_x.into();
387        self
388    }
389}
390
391impl<Message, Theme, Renderer> Widget<Message, Theme, Renderer>
392    for Wrapping<'_, Message, Theme, Renderer>
393where
394    Renderer: crate::core::Renderer,
395{
396    fn children(&self) -> Vec<Tree> {
397        self.row.children()
398    }
399
400    fn diff(&self, tree: &mut Tree) {
401        self.row.diff(tree);
402    }
403
404    fn size(&self) -> Size<Length> {
405        self.row.size()
406    }
407
408    fn layout(
409        &mut self,
410        tree: &mut Tree,
411        renderer: &Renderer,
412        limits: &layout::Limits,
413    ) -> layout::Node {
414        let limits = limits
415            .width(self.row.width)
416            .height(self.row.height)
417            .shrink(self.row.padding);
418
419        let child_limits = limits.loose();
420        let spacing = self.row.spacing;
421        let vertical_spacing = self.vertical_spacing.unwrap_or(spacing);
422        let max_width = limits.max().width;
423
424        let mut children: Vec<layout::Node> = Vec::new();
425        let mut intrinsic_size = Size::ZERO;
426        let mut row_start = 0;
427        let mut row_height = 0.0;
428        let mut x = 0.0;
429        let mut y = 0.0;
430
431        let align_factor = match self.row.align {
432            Alignment::Start => 0.0,
433            Alignment::Center => 2.0,
434            Alignment::End => 1.0,
435        };
436
437        let align_y = |row_start: std::ops::Range<usize>,
438                       row_height: f32,
439                       children: &mut Vec<layout::Node>| {
440            if align_factor != 0.0 {
441                for node in &mut children[row_start] {
442                    let height = node.size().height;
443
444                    node.translate_mut(Vector::new(
445                        0.0,
446                        (row_height - height) / align_factor,
447                    ));
448                }
449            }
450        };
451
452        for (i, child) in self.row.children.iter_mut().enumerate() {
453            let node = child.as_widget_mut().layout(
454                &mut tree.children[i],
455                renderer,
456                &child_limits,
457            );
458
459            let child_size = node.size();
460
461            if x != 0.0 && x + child_size.width > max_width {
462                intrinsic_size.width = intrinsic_size.width.max(x - spacing);
463
464                align_y(row_start..i, row_height, &mut children);
465
466                y += row_height + vertical_spacing;
467                x = 0.0;
468                row_start = i;
469                row_height = 0.0;
470            }
471
472            row_height = row_height.max(child_size.height);
473
474            children.push(node.move_to((
475                x + self.row.padding.left,
476                y + self.row.padding.top,
477            )));
478
479            x += child_size.width + spacing;
480        }
481
482        if x != 0.0 {
483            intrinsic_size.width = intrinsic_size.width.max(x - spacing);
484        }
485
486        intrinsic_size.height = y + row_height;
487        align_y(row_start..children.len(), row_height, &mut children);
488
489        let align_factor = match self.align_x {
490            alignment::Horizontal::Left => 0.0,
491            alignment::Horizontal::Center => 2.0,
492            alignment::Horizontal::Right => 1.0,
493        };
494
495        if align_factor != 0.0 {
496            let total_width = intrinsic_size.width;
497
498            let mut row_start = 0;
499
500            for i in 0..children.len() {
501                let bounds = children[i].bounds();
502                let row_width = bounds.x + bounds.width;
503
504                let next_x = children
505                    .get(i + 1)
506                    .map(|node| node.bounds().x)
507                    .unwrap_or_default();
508
509                if next_x == 0.0 {
510                    let translation = Vector::new(
511                        (total_width - row_width) / align_factor,
512                        0.0,
513                    );
514
515                    for node in &mut children[row_start..=i] {
516                        node.translate_mut(translation);
517                    }
518
519                    row_start = i + 1;
520                }
521            }
522        }
523
524        let size =
525            limits.resolve(self.row.width, self.row.height, intrinsic_size);
526
527        layout::Node::with_children(size.expand(self.row.padding), children)
528    }
529
530    fn operate(
531        &mut self,
532        tree: &mut Tree,
533        layout: Layout<'_>,
534        renderer: &Renderer,
535        operation: &mut dyn Operation,
536    ) {
537        self.row.operate(tree, layout, renderer, operation);
538    }
539
540    fn update(
541        &mut self,
542        tree: &mut Tree,
543        event: &Event,
544        layout: Layout<'_>,
545        cursor: mouse::Cursor,
546        renderer: &Renderer,
547        clipboard: &mut dyn Clipboard,
548        shell: &mut Shell<'_, Message>,
549        viewport: &Rectangle,
550    ) {
551        self.row.update(
552            tree, event, layout, cursor, renderer, clipboard, shell, viewport,
553        );
554    }
555
556    fn mouse_interaction(
557        &self,
558        tree: &Tree,
559        layout: Layout<'_>,
560        cursor: mouse::Cursor,
561        viewport: &Rectangle,
562        renderer: &Renderer,
563    ) -> mouse::Interaction {
564        self.row
565            .mouse_interaction(tree, layout, cursor, viewport, renderer)
566    }
567
568    fn draw(
569        &self,
570        tree: &Tree,
571        renderer: &mut Renderer,
572        theme: &Theme,
573        style: &renderer::Style,
574        layout: Layout<'_>,
575        cursor: mouse::Cursor,
576        viewport: &Rectangle,
577    ) {
578        self.row
579            .draw(tree, renderer, theme, style, layout, cursor, viewport);
580    }
581
582    fn overlay<'b>(
583        &'b mut self,
584        tree: &'b mut Tree,
585        layout: Layout<'b>,
586        renderer: &Renderer,
587        viewport: &Rectangle,
588        translation: Vector,
589    ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> {
590        self.row
591            .overlay(tree, layout, renderer, viewport, translation)
592    }
593}
594
595impl<'a, Message, Theme, Renderer> From<Wrapping<'a, Message, Theme, Renderer>>
596    for Element<'a, Message, Theme, Renderer>
597where
598    Message: 'a,
599    Theme: 'a,
600    Renderer: crate::core::Renderer + 'a,
601{
602    fn from(row: Wrapping<'a, Message, Theme, Renderer>) -> Self {
603        Self::new(row)
604    }
605}