Skip to main content

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    Element, Event, Length, Padding, Pixels, Rectangle, Shell, Size, Vector, Widget,
10};
11
12/// A container that distributes its contents horizontally.
13///
14/// # Example
15/// ```no_run
16/// # mod iced { pub mod widget { pub use iced_widget::*; } }
17/// # pub type State = ();
18/// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>;
19/// use iced::widget::{button, row};
20///
21/// #[derive(Debug, Clone)]
22/// enum Message {
23///     // ...
24/// }
25///
26/// fn view(state: &State) -> Element<'_, Message> {
27///     row![
28///         "I am to the left!",
29///         button("I am in the middle!"),
30///         "I am to the right!",
31///     ].into()
32/// }
33/// ```
34pub struct Row<'a, Message, Theme = crate::Theme, Renderer = crate::Renderer> {
35    spacing: f32,
36    padding: Padding,
37    width: Length,
38    height: Length,
39    align: Alignment,
40    clip: bool,
41    children: Vec<Element<'a, Message, Theme, Renderer>>,
42}
43
44impl<'a, Message, Theme, Renderer> Row<'a, Message, Theme, Renderer>
45where
46    Renderer: crate::core::Renderer,
47{
48    /// Creates an empty [`Row`].
49    pub fn new() -> Self {
50        Self::from_vec(Vec::new())
51    }
52
53    /// Creates a [`Row`] with the given capacity.
54    pub fn with_capacity(capacity: usize) -> Self {
55        Self::from_vec(Vec::with_capacity(capacity))
56    }
57
58    /// Creates a [`Row`] with the given elements.
59    pub fn with_children(
60        children: impl IntoIterator<Item = Element<'a, Message, Theme, Renderer>>,
61    ) -> Self {
62        let iterator = children.into_iter();
63
64        Self::with_capacity(iterator.size_hint().0).extend(iterator)
65    }
66
67    /// Creates a [`Row`] from an already allocated [`Vec`].
68    ///
69    /// Keep in mind that the [`Row`] will not inspect the [`Vec`], which means
70    /// it won't automatically adapt to the sizing strategy of its contents.
71    ///
72    /// If any of the children have a [`Length::Fill`] strategy, you will need to
73    /// call [`Row::width`] or [`Row::height`] accordingly.
74    pub fn from_vec(children: Vec<Element<'a, Message, Theme, Renderer>>) -> Self {
75        Self {
76            spacing: 0.0,
77            padding: Padding::ZERO,
78            width: Length::Shrink,
79            height: Length::Shrink,
80            align: Alignment::Start,
81            clip: false,
82            children,
83        }
84    }
85
86    /// Sets the horizontal spacing _between_ elements.
87    ///
88    /// Custom margins per element do not exist in iced. You should use this
89    /// method instead! While less flexible, it helps you keep spacing between
90    /// elements consistent.
91    pub fn spacing(mut self, amount: impl Into<Pixels>) -> Self {
92        self.spacing = amount.into().0;
93        self
94    }
95
96    /// Sets the [`Padding`] of the [`Row`].
97    pub fn padding<P: Into<Padding>>(mut self, padding: P) -> Self {
98        self.padding = padding.into();
99        self
100    }
101
102    /// Sets the width of the [`Row`].
103    pub fn width(mut self, width: impl Into<Length>) -> Self {
104        self.width = width.into();
105        self
106    }
107
108    /// Sets the height of the [`Row`].
109    pub fn height(mut self, height: impl Into<Length>) -> Self {
110        self.height = height.into();
111        self
112    }
113
114    /// Sets the vertical alignment of the contents of the [`Row`] .
115    pub fn align_y(mut self, align: impl Into<alignment::Vertical>) -> Self {
116        self.align = Alignment::from(align.into());
117        self
118    }
119
120    /// Sets whether the contents of the [`Row`] should be clipped on
121    /// overflow.
122    pub fn clip(mut self, clip: bool) -> Self {
123        self.clip = clip;
124        self
125    }
126
127    /// Adds an [`Element`] to the [`Row`].
128    pub fn push(mut self, child: impl Into<Element<'a, Message, Theme, Renderer>>) -> Self {
129        let child = child.into();
130        let child_size = child.as_widget().size_hint();
131
132        if !child_size.is_void() {
133            self.width = self.width.enclose(child_size.width);
134            self.height = self.height.enclose(child_size.height);
135            self.children.push(child);
136        }
137
138        self
139    }
140
141    /// Extends the [`Row`] with the given children.
142    pub fn extend(
143        self,
144        children: impl IntoIterator<Item = Element<'a, Message, Theme, Renderer>>,
145    ) -> Self {
146        children.into_iter().fold(self, Self::push)
147    }
148
149    /// Turns the [`Row`] into a [`Wrapping`] row.
150    ///
151    /// The original alignment of the [`Row`] is preserved per row wrapped.
152    pub fn wrap(self) -> Wrapping<'a, Message, Theme, Renderer> {
153        Wrapping {
154            row: self,
155            vertical_spacing: None,
156            align_x: alignment::Horizontal::Left,
157        }
158    }
159}
160
161impl<Message, Renderer> Default for Row<'_, Message, Renderer>
162where
163    Renderer: crate::core::Renderer,
164{
165    fn default() -> Self {
166        Self::new()
167    }
168}
169
170impl<'a, Message, Theme, Renderer: crate::core::Renderer>
171    FromIterator<Element<'a, Message, Theme, Renderer>> for Row<'a, Message, Theme, Renderer>
172{
173    fn from_iter<T: IntoIterator<Item = Element<'a, Message, Theme, Renderer>>>(iter: T) -> Self {
174        Self::with_children(iter)
175    }
176}
177
178impl<Message, Theme, Renderer> Widget<Message, Theme, Renderer>
179    for Row<'_, Message, Theme, Renderer>
180where
181    Renderer: crate::core::Renderer,
182{
183    fn children(&self) -> Vec<Tree> {
184        self.children.iter().map(Tree::new).collect()
185    }
186
187    fn diff(&self, tree: &mut Tree) {
188        tree.diff_children(&self.children);
189    }
190
191    fn size(&self) -> Size<Length> {
192        Size {
193            width: self.width,
194            height: self.height,
195        }
196    }
197
198    fn layout(
199        &mut self,
200        tree: &mut Tree,
201        renderer: &Renderer,
202        limits: &layout::Limits,
203    ) -> layout::Node {
204        layout::flex::resolve(
205            layout::flex::Axis::Horizontal,
206            renderer,
207            limits,
208            self.width,
209            self.height,
210            self.padding,
211            self.spacing,
212            self.align,
213            &mut self.children,
214            &mut tree.children,
215        )
216    }
217
218    fn operate(
219        &mut self,
220        tree: &mut Tree,
221        layout: Layout<'_>,
222        renderer: &Renderer,
223        operation: &mut dyn Operation,
224    ) {
225        operation.container(None, layout.bounds());
226        operation.traverse(&mut |operation| {
227            self.children
228                .iter_mut()
229                .zip(&mut tree.children)
230                .zip(layout.children())
231                .for_each(|((child, state), layout)| {
232                    child
233                        .as_widget_mut()
234                        .operate(state, layout, renderer, operation);
235                });
236        });
237    }
238
239    fn update(
240        &mut self,
241        tree: &mut Tree,
242        event: &Event,
243        layout: Layout<'_>,
244        cursor: mouse::Cursor,
245        renderer: &Renderer,
246        shell: &mut Shell<'_, Message>,
247        viewport: &Rectangle,
248    ) {
249        for ((child, tree), layout) in self
250            .children
251            .iter_mut()
252            .zip(&mut tree.children)
253            .zip(layout.children())
254        {
255            child
256                .as_widget_mut()
257                .update(tree, event, layout, cursor, renderer, shell, viewport);
258        }
259    }
260
261    fn mouse_interaction(
262        &self,
263        tree: &Tree,
264        layout: Layout<'_>,
265        cursor: mouse::Cursor,
266        viewport: &Rectangle,
267        renderer: &Renderer,
268    ) -> mouse::Interaction {
269        self.children
270            .iter()
271            .zip(&tree.children)
272            .zip(layout.children())
273            .map(|((child, tree), layout)| {
274                child
275                    .as_widget()
276                    .mouse_interaction(tree, layout, cursor, viewport, renderer)
277            })
278            .max()
279            .unwrap_or_default()
280    }
281
282    fn draw(
283        &self,
284        tree: &Tree,
285        renderer: &mut Renderer,
286        theme: &Theme,
287        style: &renderer::Style,
288        layout: Layout<'_>,
289        cursor: mouse::Cursor,
290        viewport: &Rectangle,
291    ) {
292        if let Some(clipped_viewport) = layout.bounds().intersection(viewport) {
293            let viewport = if self.clip {
294                &clipped_viewport
295            } else {
296                viewport
297            };
298
299            for ((child, tree), layout) in self
300                .children
301                .iter()
302                .zip(&tree.children)
303                .zip(layout.children())
304                .filter(|(_, layout)| layout.bounds().intersects(viewport))
305            {
306                child
307                    .as_widget()
308                    .draw(tree, renderer, theme, style, layout, cursor, viewport);
309            }
310        }
311    }
312
313    fn overlay<'b>(
314        &'b mut self,
315        tree: &'b mut Tree,
316        layout: Layout<'b>,
317        renderer: &Renderer,
318        viewport: &Rectangle,
319        translation: Vector,
320    ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> {
321        overlay::from_children(
322            &mut self.children,
323            tree,
324            layout,
325            renderer,
326            viewport,
327            translation,
328        )
329    }
330}
331
332impl<'a, Message, Theme, Renderer> From<Row<'a, Message, Theme, Renderer>>
333    for Element<'a, Message, Theme, Renderer>
334where
335    Message: 'a,
336    Theme: 'a,
337    Renderer: crate::core::Renderer + 'a,
338{
339    fn from(row: Row<'a, Message, Theme, Renderer>) -> Self {
340        Self::new(row)
341    }
342}
343
344/// A [`Row`] that wraps its contents.
345///
346/// Create a [`Row`] first, and then call [`Row::wrap`] to
347/// obtain a [`Row`] that wraps its contents.
348///
349/// The original alignment of the [`Row`] is preserved per row wrapped.
350pub struct Wrapping<'a, Message, Theme = crate::Theme, Renderer = crate::Renderer> {
351    row: Row<'a, Message, Theme, Renderer>,
352    vertical_spacing: Option<f32>,
353    align_x: alignment::Horizontal,
354}
355
356impl<Message, Theme, Renderer> Wrapping<'_, Message, Theme, Renderer> {
357    /// Sets the vertical spacing _between_ lines.
358    pub fn vertical_spacing(mut self, amount: impl Into<Pixels>) -> Self {
359        self.vertical_spacing = Some(amount.into().0);
360        self
361    }
362
363    /// Sets the horizontal alignment of the wrapping [`Row`].
364    pub fn align_x(mut self, align_x: impl Into<alignment::Horizontal>) -> Self {
365        self.align_x = align_x.into();
366        self
367    }
368}
369
370impl<Message, Theme, Renderer> Widget<Message, Theme, Renderer>
371    for Wrapping<'_, Message, Theme, Renderer>
372where
373    Renderer: crate::core::Renderer,
374{
375    fn children(&self) -> Vec<Tree> {
376        self.row.children()
377    }
378
379    fn diff(&self, tree: &mut Tree) {
380        self.row.diff(tree);
381    }
382
383    fn size(&self) -> Size<Length> {
384        self.row.size()
385    }
386
387    fn layout(
388        &mut self,
389        tree: &mut Tree,
390        renderer: &Renderer,
391        limits: &layout::Limits,
392    ) -> layout::Node {
393        let limits = limits
394            .width(self.row.width)
395            .height(self.row.height)
396            .shrink(self.row.padding);
397
398        let child_limits = limits.loose();
399        let spacing = self.row.spacing;
400        let vertical_spacing = self.vertical_spacing.unwrap_or(spacing);
401        let max_width = limits.max().width;
402
403        let mut children: Vec<layout::Node> = Vec::new();
404        let mut intrinsic_size = Size::ZERO;
405        let mut row_start = 0;
406        let mut row_height = 0.0;
407        let mut x = 0.0;
408        let mut y = 0.0;
409
410        let align_factor = match self.row.align {
411            Alignment::Start => 0.0,
412            Alignment::Center => 2.0,
413            Alignment::End => 1.0,
414        };
415
416        let align_y = |row_start: std::ops::Range<usize>,
417                       row_height: f32,
418                       children: &mut Vec<layout::Node>| {
419            if align_factor != 0.0 {
420                for node in &mut children[row_start] {
421                    let height = node.size().height;
422
423                    node.translate_mut(Vector::new(0.0, (row_height - height) / align_factor));
424                }
425            }
426        };
427
428        for (i, child) in self.row.children.iter_mut().enumerate() {
429            let node = child
430                .as_widget_mut()
431                .layout(&mut tree.children[i], renderer, &child_limits);
432
433            let child_size = node.size();
434
435            if x != 0.0 && x + child_size.width > max_width {
436                intrinsic_size.width = intrinsic_size.width.max(x - spacing);
437
438                align_y(row_start..i, row_height, &mut children);
439
440                y += row_height + vertical_spacing;
441                x = 0.0;
442                row_start = i;
443                row_height = 0.0;
444            }
445
446            row_height = row_height.max(child_size.height);
447
448            children.push(node.move_to((x + self.row.padding.left, y + self.row.padding.top)));
449
450            x += child_size.width + spacing;
451        }
452
453        if x != 0.0 {
454            intrinsic_size.width = intrinsic_size.width.max(x - spacing);
455        }
456
457        intrinsic_size.height = y + row_height;
458        align_y(row_start..children.len(), row_height, &mut children);
459
460        let align_factor = match self.align_x {
461            alignment::Horizontal::Left => 0.0,
462            alignment::Horizontal::Center => 2.0,
463            alignment::Horizontal::Right => 1.0,
464        };
465
466        if align_factor != 0.0 {
467            let total_width = intrinsic_size.width;
468
469            let mut row_start = 0;
470
471            for i in 0..children.len() {
472                let bounds = children[i].bounds();
473                let row_width = bounds.x + bounds.width;
474
475                let next_x = children
476                    .get(i + 1)
477                    .map(|node| node.bounds().x)
478                    .unwrap_or_default();
479
480                if next_x == 0.0 {
481                    let translation = Vector::new((total_width - row_width) / align_factor, 0.0);
482
483                    for node in &mut children[row_start..=i] {
484                        node.translate_mut(translation);
485                    }
486
487                    row_start = i + 1;
488                }
489            }
490        }
491
492        let size = limits.resolve(self.row.width, self.row.height, intrinsic_size);
493
494        layout::Node::with_children(size.expand(self.row.padding), children)
495    }
496
497    fn operate(
498        &mut self,
499        tree: &mut Tree,
500        layout: Layout<'_>,
501        renderer: &Renderer,
502        operation: &mut dyn Operation,
503    ) {
504        self.row.operate(tree, layout, renderer, operation);
505    }
506
507    fn update(
508        &mut self,
509        tree: &mut Tree,
510        event: &Event,
511        layout: Layout<'_>,
512        cursor: mouse::Cursor,
513        renderer: &Renderer,
514        shell: &mut Shell<'_, Message>,
515        viewport: &Rectangle,
516    ) {
517        self.row
518            .update(tree, event, layout, cursor, renderer, shell, viewport);
519    }
520
521    fn mouse_interaction(
522        &self,
523        tree: &Tree,
524        layout: Layout<'_>,
525        cursor: mouse::Cursor,
526        viewport: &Rectangle,
527        renderer: &Renderer,
528    ) -> mouse::Interaction {
529        self.row
530            .mouse_interaction(tree, layout, cursor, viewport, renderer)
531    }
532
533    fn draw(
534        &self,
535        tree: &Tree,
536        renderer: &mut Renderer,
537        theme: &Theme,
538        style: &renderer::Style,
539        layout: Layout<'_>,
540        cursor: mouse::Cursor,
541        viewport: &Rectangle,
542    ) {
543        self.row
544            .draw(tree, renderer, theme, style, layout, cursor, viewport);
545    }
546
547    fn overlay<'b>(
548        &'b mut self,
549        tree: &'b mut Tree,
550        layout: Layout<'b>,
551        renderer: &Renderer,
552        viewport: &Rectangle,
553        translation: Vector,
554    ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> {
555        self.row
556            .overlay(tree, layout, renderer, viewport, translation)
557    }
558}
559
560impl<'a, Message, Theme, Renderer> From<Wrapping<'a, Message, Theme, Renderer>>
561    for Element<'a, Message, Theme, Renderer>
562where
563    Message: 'a,
564    Theme: 'a,
565    Renderer: crate::core::Renderer + 'a,
566{
567    fn from(row: Wrapping<'a, Message, Theme, Renderer>) -> Self {
568        Self::new(row)
569    }
570}