iced-widget-kit 0.1.0

Extra widgets for the Iced GUI library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
//! A horizontal set of [Group]s that adapt their appearance and arrangement when the [Ribbon]
//! is resized.
pub mod group;

pub use group::{Group, Size};

use crate::ribbon::group::is_collapsed;

use iced_core::{
    Background, Border, Clipboard, Color, Element, Event, Font, Gradient, Layout, Length, Padding,
    Pixels, Point, Rectangle, Shadow, Shell, Size as IcedSize, Theme, Vector, Widget,
    gradient::Linear,
    keyboard,
    layout::{self, Limits, Node},
    mouse::{self, Cursor, Interaction},
    overlay,
    renderer::{self, Quad},
    touch,
    widget::{
        Tree,
        tree::{self, Tag},
    },
    window,
};

use core::panic;
use iced_widget::{button, svg, text};
use std::{f32, time::Instant};

const SEPARATOR_WIDTH: f32 = 1.0;

/// A horizontal collection of [`Group`]s which change their appearance and layout
/// when the [`Ribbon`] is resized.
pub struct Ribbon<'a, Id, Message, Theme = iced_widget::Theme, Renderer = iced_widget::Renderer>
where
    Id: Clone + Eq,
    Theme: Catalog + button::Catalog + text::Catalog,
    Renderer: iced_core::Renderer + iced_core::text::Renderer,
{
    groups: Vec<Group<'a, Id, Message, Theme, Renderer>>,
    width: Length,
    height: Length,
    padding: Padding,
    spacing: f32,
    on_group_dropdown_dismiss: Option<OnDismiss<'a, Message>>,
    class: <Theme as Catalog>::Class<'a>,
}

impl<'a, Id, Message, Theme, Renderer> Ribbon<'a, Id, Message, Theme, Renderer>
where
    Id: Clone + Eq,
    Message: 'a + Clone,
    Theme: 'a + Catalog + button::Catalog + svg::Catalog + text::Catalog,
    <Theme as text::Catalog>::Class<'a>: From<text::StyleFn<'a, Theme>>,
    Renderer: 'a + iced_core::Renderer + iced_core::svg::Renderer + iced_core::text::Renderer,
    <Renderer as iced_core::text::Renderer>::Font: From<iced_core::Font>,
    <Renderer as iced_core::text::Renderer>::Paragraph: Clone,
{
    /// Creates a new [`Ribbon`] which the provided [`Group`]s.
    #[must_use]
    pub fn new(groups: impl IntoIterator<Item = Group<'a, Id, Message, Theme, Renderer>>) -> Self {
        Self {
            groups: groups.into_iter().collect(),
            width: Length::Fill,
            height: Length::Shrink,
            padding: Padding::new(4.0),
            spacing: 0.0,
            on_group_dropdown_dismiss: None,
            class: <Theme as Catalog>::default(),
        }
    }

    /// Sets the width of the [`Ribbon`].
    #[must_use]
    pub fn width(mut self, width: impl Into<Length>) -> Self {
        self.width = width.into();
        self
    }

    /// Sets the height of the [`Ribbon`].
    #[must_use]
    pub fn height(mut self, height: impl Into<Length>) -> Self {
        self.height = height.into();
        self
    }

    /// Sets the spacing between [`Group`]s.
    #[must_use]
    pub fn spacing(mut self, amount: impl Into<Pixels>) -> Self {
        self.spacing = amount.into().0;
        self
    }

    /// Sets the [`Padding`] of the [`Ribbon`].
    #[must_use]
    pub fn padding<P: Into<Padding>>(mut self, padding: P) -> Self {
        self.padding = padding.into();
        self
    }

    /// Opens the [`Group`] as a dropdown when collapsed.
    ///
    /// # Panics
    /// Panics if no [`Group`] in the [`Ribbon`] has the provided id.
    #[must_use]
    pub fn open_group(mut self, id: Id) -> Self {
        let mut is_found = false;

        for group in &mut self.groups {
            if group.id() == id {
                is_found = true;
                group.open_dropdown();
            } else {
                group.close_dropdown();
            }
        }

        if !is_found {
            panic!("expect group with id")
        };

        self
    }

    /// Sets the message that will be sent when the [`Group`] collapsed dropdown is dismissed.
    #[must_use]
    pub fn on_group_dropdown_dismiss(mut self, on_dismiss: Message) -> Self {
        self.on_group_dropdown_dismiss = Some(OnDismiss::Direct(on_dismiss));
        self
    }

    /// Sets the message that will be sent when the [`Group`] collapsed dropdown is dismissed.
    ///
    /// This is analogous to [`Ribbon::on_group_dropdown_dismiss`], but using a closure to produce
    /// the message.
    #[must_use]
    pub fn on_group_dropdown_dismiss_with(mut self, on_dismiss: impl Fn() -> Message + 'a) -> Self {
        self.on_group_dropdown_dismiss = Some(OnDismiss::Closure(Box::new(on_dismiss)));
        self
    }

    /// Sets the style of the [`Ribbon`].
    #[must_use]
    pub fn style(mut self, style: impl Fn(&Theme) -> Style + 'a) -> Self
    where
        <Theme as Catalog>::Class<'a>: From<StyleFn<'a, Theme>>,
    {
        self.class = (Box::new(style) as StyleFn<'a, Theme>).into();
        self
    }

    fn total_spacing(&self) -> f32 {
        (self.groups.len() - 1) as f32 * self.spacing
    }

    fn can_shrink(&self, current_sizes: &[group::Size]) -> bool {
        self.groups
            .iter()
            .zip(current_sizes)
            .any(|(group, current_size)| group.shrink_hint(*current_size).is_some())
    }

    fn should_shrink(&mut self, available_width: f32, current_sizes: &[group::Size]) -> bool {
        let groups_width = self
            .groups
            .iter()
            .zip(current_sizes)
            .fold(0.0, |total, (group, size)| {
                total + group.size_width(*size).unwrap()
            })
            + self.total_spacing()
            + self.padding.left
            + self.padding.right;

        (available_width - groups_width) < 0.0 && self.can_shrink(current_sizes)
    }
}

fn group_sizes(tree: &Tree) -> Vec<group::Size> {
    tree.children.iter().map(group::current_size).collect()
}

enum OnDismiss<'a, Message> {
    Direct(Message),
    Closure(Box<dyn Fn() -> Message + 'a>),
}

impl<'a, Message: Clone> OnDismiss<'a, Message> {
    fn get(&self) -> Message {
        match self {
            OnDismiss::Direct(msg) => msg.clone(),
            OnDismiss::Closure(f) => f(),
        }
    }
}

#[derive(Debug, Default)]
struct State {
    now: Option<Instant>,
    open_collapsed_group: Option<usize>,
    available_width: f32,
    group_sizes: Vec<group::Size>,
}

impl<'a, Id, Message, Theme, Renderer> Widget<Message, Theme, Renderer>
    for Ribbon<'a, Id, Message, Theme, Renderer>
where
    Id: Clone + Eq,
    Message: 'a + Clone,
    Theme: 'a + Catalog + button::Catalog + svg::Catalog + text::Catalog,
    Renderer: 'a + iced_core::svg::Renderer + iced_core::text::Renderer,
    <Renderer as iced_core::text::Renderer>::Font: From<iced_core::Font>,
    <Theme as text::Catalog>::Class<'a>: From<text::StyleFn<'a, Theme>>,
    <Renderer as iced_core::text::Renderer>::Paragraph: Clone,
{
    fn tag(&self) -> Tag {
        Tag::of::<State>()
    }

    fn state(&self) -> tree::State {
        tree::State::new(State::default())
    }

    fn children(&self) -> Vec<Tree> {
        self.groups.iter().map(Group::tree).collect()
    }

    fn diff(&self, tree: &mut Tree) {
        tree.diff_children_custom(&self.groups, |tree, group| group.diff(tree), Group::tree);
    }

    fn size(&self) -> IcedSize<Length> {
        IcedSize::new(self.width, self.height)
    }

    fn layout(&mut self, tree: &mut Tree, renderer: &Renderer, limits: &Limits) -> Node {
        let limits = limits.width(self.width).height(self.height);

        let groups_max_height = self.groups.iter_mut().zip(&mut tree.children).fold(
            0.0_f32,
            |max_height, (group, tree)| {
                group
                    .height_check_layout(tree, renderer, &limits)
                    .size()
                    .height
                    .max(max_height)
            },
        );

        // Calculate if Groups need their group::Size changed
        let previous_available_width = tree.state.downcast_ref::<State>().available_width;
        let available_width = limits.shrink(self.padding).width(self.width).max().width;
        let previous_sizes = &tree.state.downcast_ref::<State>().group_sizes;

        if previous_available_width != available_width || *previous_sizes != group_sizes(tree) {
            let is_group_animating = tree.children.iter().any(|child| {
                let state = child.state.downcast_ref::<group::State>();
                state.is_resizing()
            });

            if !is_group_animating {
                let mut current_sizes = self
                    .groups
                    .iter()
                    .map(|group| group.maximum_size())
                    .collect::<Vec<_>>();

                // Starting from the right, step through each group reducing its size until
                // the Ribbon fits in the available width
                while self.should_shrink(available_width, &current_sizes) {
                    let max_size = self
                        .groups
                        .iter()
                        .zip(&current_sizes)
                        .filter(|(group, current_size)| group.can_shrink(**current_size))
                        .fold(group::Size::Collapsed, |size, (_, current_size)| {
                            group::Size::max(size, *current_size)
                        });

                    for (group, current_size) in
                        self.groups.iter_mut().zip(current_sizes.iter_mut()).rev()
                    {
                        if let Some(size_hint) = group.shrink_hint(*current_size)
                            && *current_size >= max_size
                        {
                            *current_size = size_hint;
                            break;
                        }
                    }
                }

                for (group_tree, size) in tree.children.iter_mut().zip(&current_sizes) {
                    match tree.state.downcast_ref::<State>().now {
                        Some(now) => group::resize(group_tree, *size, now),
                        None => group::resize_fixed(group_tree, *size),
                    }
                }

                let group_sizes = group_sizes(tree);
                let state = tree.state.downcast_mut::<State>();
                state.available_width = available_width;
                state.group_sizes = group_sizes;
            }
        }

        let groups_limits =
            limits.max_height(groups_max_height + self.padding.top + self.padding.bottom);

        layout::padded(
            &groups_limits,
            self.width,
            self.height,
            self.padding,
            |limits| {
                // Interleave groups with separators and position
                let (size, nodes) = self.groups.iter_mut().zip(&mut tree.children).fold(
                    (IcedSize::ZERO, vec![]),
                    |(mut total_size, mut nodes), (group, group_tree)| {
                        let group_node = group
                            .layout(group_tree, renderer, limits)
                            .move_to([total_size.width, 0.0]);

                        let total_width = total_size.width + group_node.size().width;
                        nodes.push(group_node);

                        // Every second node is a separator line node
                        let separator_width = SEPARATOR_WIDTH + self.spacing;

                        let separator_node =
                            Node::new(IcedSize::new(separator_width, limits.max().height))
                                .move_to([total_width, 0.0]);

                        total_size =
                            IcedSize::new(total_width + separator_width, groups_max_height);

                        nodes.push(separator_node);
                        (total_size, nodes)
                    },
                );

                Node::with_children(size, nodes)
            },
        )
    }

    fn operate(
        &mut self,
        tree: &mut Tree,
        layout: Layout<'_>,
        renderer: &Renderer,
        operation: &mut dyn iced_core::widget::Operation,
    ) {
        operation.container(None, layout.bounds());

        operation.traverse(&mut |operation| {
            self.groups
                .iter_mut()
                .zip(&mut tree.children)
                .zip(layout.child(0).children().step_by(2))
                .for_each(|((group, state), layout)| {
                    group.operate(state, layout, renderer, operation);
                });
        });
    }

    fn update(
        &mut self,
        tree: &mut Tree,
        event: &Event,
        layout: Layout<'_>,
        cursor: Cursor,
        renderer: &Renderer,
        clipboard: &mut dyn Clipboard,
        shell: &mut Shell<'_, Message>,
        viewport: &Rectangle,
    ) {
        for ((group, group_tree), layout) in self
            .groups
            .iter_mut()
            .zip(&mut tree.children)
            .zip(layout.child(0).children().step_by(2))
        {
            group.update(
                group_tree, event, layout, cursor, renderer, clipboard, shell, viewport,
            );

            if shell.is_event_captured() {
                return;
            }
        }

        let state = tree.state.downcast_mut::<State>();

        match event {
            Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left))
            | Event::Touch(touch::Event::FingerLifted { .. })
            | Event::Touch(touch::Event::FingerLost { .. }) => {
                state.open_collapsed_group = None;
            }
            Event::Window(window::Event::RedrawRequested(now)) => {
                state.now = Some(*now);
            }
            _ => {}
        }
    }

    fn draw(
        &self,
        tree: &Tree,
        renderer: &mut Renderer,
        theme: &Theme,
        style: &renderer::Style,
        layout: Layout<'_>,
        cursor: Cursor,
        viewport: &Rectangle,
    ) {
        let ribbon_style = <Theme as Catalog>::style(theme, &self.class);
        let groups_bounds = layout.bounds();

        renderer.fill_quad(
            Quad {
                bounds: groups_bounds,
                border: ribbon_style.border,
                shadow: ribbon_style.shadow,
                snap: ribbon_style.snap,
            },
            ribbon_style.background.unwrap_or(Color::TRANSPARENT.into()),
        );

        let mut layouts = layout.child(0).children();
        let mut trees = tree.children.iter();
        let mut next_group_trees = tree.children.iter().skip(1);

        for group in self.groups.iter() {
            let group_tree = trees.next().unwrap();

            // Every odd node is a Group
            group.draw(
                group_tree,
                renderer,
                theme,
                style,
                layouts.next().unwrap(),
                cursor,
                viewport,
            );

            // Every even node is a separator line
            let layout = layouts.next().unwrap();
            let bounds = layout.bounds();

            let is_group_collapsed = is_collapsed(group_tree);
            let is_next_group_collapsed = next_group_trees.next().is_some_and(is_collapsed);

            let x = match (is_group_collapsed, is_next_group_collapsed) {
                (true, _) => bounds.x,
                (_, true) => bounds.x + (bounds.width - 1.0),
                (false, false) => bounds.x + (bounds.width - 1.0) / 2.0,
            };

            renderer.fill_quad(
                Quad {
                    bounds: Rectangle {
                        x,
                        y: bounds.y,
                        width: 1.0,
                        height: bounds.height,
                    },
                    ..Quad::default()
                },
                ribbon_style.separator_color.unwrap_or(Color::TRANSPARENT),
            );
        }
    }

    fn mouse_interaction(
        &self,
        tree: &Tree,
        layout: Layout<'_>,
        cursor: Cursor,
        viewport: &Rectangle,
        renderer: &Renderer,
    ) -> Interaction {
        self.groups
            .iter()
            .zip(&tree.children)
            .zip(layout.child(0).children().step_by(2))
            .map(|((group, tree), layout)| {
                group.mouse_interaction(tree, layout, cursor, viewport, renderer)
            })
            .max()
            .unwrap_or_default()
    }

    fn overlay<'b>(
        &'b mut self,
        tree: &'b mut Tree,
        layout: Layout<'b>,
        renderer: &Renderer,
        viewport: &Rectangle,
        translation: Vector,
    ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> {
        let overlays = self
            .groups
            .iter_mut()
            .zip(&mut tree.children)
            .zip(layout.child(0).children().step_by(2))
            .flat_map(|((group, tree), layout)| {
                if is_collapsed(tree) && group.is_dropdown_open() {
                    Some(overlay::Element::new(Box::new(GroupDropdown {
                        position: layout.position(),
                        tree,
                        group,
                        padding: self.padding,
                        on_dismiss: self.on_group_dropdown_dismiss.as_ref(),
                        class: &self.class,
                    })))
                } else {
                    group.overlay(tree, layout, renderer, viewport, translation)
                }
            })
            .collect();

        Some(overlay::Group::with_children(overlays).overlay())
    }
}

impl<'a, Id, Message, Theme, Renderer> From<Ribbon<'a, Id, Message, Theme, Renderer>>
    for Element<'a, Message, Theme, Renderer>
where
    Id: 'a + Clone + Eq,
    Message: 'a + Clone,
    Theme: 'a + Catalog + button::Catalog + svg::Catalog + text::Catalog,
    Renderer: 'a + iced_core::svg::Renderer + iced_core::text::Renderer,
    <Renderer as iced_core::text::Renderer>::Font: From<Font>,
    <Theme as text::Catalog>::Class<'a>: From<text::StyleFn<'a, Theme>>,
    <Renderer as iced_core::text::Renderer>::Paragraph: Clone,
{
    fn from(ribbon: Ribbon<'a, Id, Message, Theme, Renderer>) -> Self {
        Element::new(ribbon)
    }
}

struct GroupDropdown<
    'a,
    'b,
    Id,
    Message,
    Theme = iced_core::Theme,
    Renderer = iced_widget::Renderer,
> where
    Id: Clone + Eq,
    Theme: Catalog + button::Catalog + text::Catalog,
    Renderer: iced_core::Renderer + iced_core::text::Renderer,
{
    position: Point,
    tree: &'b mut Tree,
    group: &'b mut Group<'a, Id, Message, Theme, Renderer>,
    padding: Padding,
    on_dismiss: Option<&'b OnDismiss<'b, Message>>,
    class: &'b <Theme as Catalog>::Class<'a>,
}

impl<'a, 'b, Id, Message, Theme, Renderer> overlay::Overlay<Message, Theme, Renderer>
    for GroupDropdown<'a, 'b, Id, Message, Theme, Renderer>
where
    Id: Clone + Eq,
    Message: 'a + Clone,
    Theme: 'a + Catalog + button::Catalog + svg::Catalog + text::Catalog,
    <Theme as text::Catalog>::Class<'a>: From<text::StyleFn<'a, Theme>>,
    Renderer: 'a + iced_core::Renderer + iced_core::svg::Renderer + iced_core::text::Renderer,
    <Renderer as iced_core::text::Renderer>::Font: From<Font>,
    <Renderer as iced_core::text::Renderer>::Paragraph: Clone,
{
    fn update(
        &mut self,
        event: &Event,
        layout: Layout<'_>,
        cursor: Cursor,
        renderer: &Renderer,
        clipboard: &mut dyn Clipboard,
        shell: &mut Shell<'_, Message>,
    ) {
        let bounds = layout.bounds();
        let max_size = self.group.maximum_size();

        self.group.size_update(
            max_size,
            self.tree,
            event,
            layout.child(0),
            cursor,
            renderer,
            clipboard,
            shell,
            &bounds,
        );

        let mut publish_dismiss = || {
            if let Some(on_dismiss) = self.on_dismiss {
                shell.publish(on_dismiss.get());
            }
        };

        if cursor.position_over(bounds).is_none() {
            match event {
                Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left))
                | Event::Touch(touch::Event::FingerLifted { .. })
                | Event::Window(window::Event::Resized(_)) => publish_dismiss(),
                Event::Keyboard(keyboard::Event::KeyPressed { key, .. })
                    if *key == keyboard::Key::Named(keyboard::key::Named::Escape) =>
                {
                    publish_dismiss()
                }

                _ => {}
            }
        }
    }

    fn layout(&mut self, renderer: &Renderer, bounds: IcedSize) -> layout::Node {
        let limits = Limits::new(IcedSize::ZERO, bounds);

        let mut node = layout::padded(
            &limits,
            Length::Shrink,
            Length::Shrink,
            self.padding,
            |limits| {
                self.group
                    .size_layout(self.group.maximum_size(), true, self.tree, renderer, limits)
            },
        );

        let size = node.size();

        // Try to stay inside borders
        let mut position = Point::new(self.position.x, self.position.y + size.height);

        if position.x + size.width > bounds.width {
            position.x = f32::max(0.0, bounds.width - size.width);
        }
        if position.y + size.height > bounds.height {
            position.y = f32::max(0.0, bounds.height - size.height);
        }

        node.move_to_mut(position);
        node
    }

    fn draw(
        &self,
        renderer: &mut Renderer,
        theme: &Theme,
        style: &renderer::Style,
        layout: Layout<'_>,
        cursor: Cursor,
    ) {
        let bounds = layout.bounds();
        let background_style = <Theme as Catalog>::style(theme, self.class);

        renderer.fill_quad(
            renderer::Quad {
                bounds,
                border: background_style.border,
                shadow: background_style.shadow,
                snap: background_style.snap,
            },
            background_style
                .background
                .unwrap_or(Color::TRANSPARENT.into()),
        );

        let max_size = self.group.maximum_size();
        let layout = layout.child(0);
        let bounds = layout.bounds();

        self.group.size_draw(
            max_size, self.tree, renderer, theme, style, layout, cursor, &bounds,
        );
    }

    fn mouse_interaction(
        &self,
        layout: Layout<'_>,
        cursor: Cursor,
        renderer: &Renderer,
    ) -> Interaction {
        self.group.size_mouse_interaction(
            self.group.maximum_size(),
            self.tree,
            layout.child(0),
            cursor,
            &layout.bounds(),
            renderer,
        )
    }
}

/// The appearance of a [`Ribbon`].
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct Style {
    /// The [`Background`] of the [`Ribbon`].
    pub background: Option<Background>,
    /// The [`Border`] of the [`Ribbon`].
    pub border: Border,
    /// The [`Shadow`] of the [`Ribbon`].
    pub shadow: Shadow,
    /// The color of the separator between groups.
    pub separator_color: Option<Color>,
    /// Whether the [`Ribbon`] should be snapped to the pixel grid.
    pub snap: bool,
}

impl Style {
    /// Updates the border of the [`Style`].
    pub fn border(self, border: impl Into<Border>) -> Self {
        Self {
            border: border.into(),
            ..self
        }
    }

    /// Updates the background of the [`Style`].
    pub fn background(self, background: impl Into<Background>) -> Self {
        Self {
            background: Some(background.into()),
            ..self
        }
    }

    /// Updates the shadow of the [`Style`].
    pub fn shadow(self, shadow: impl Into<Shadow>) -> Self {
        Self {
            shadow: shadow.into(),
            ..self
        }
    }

    /// Update the separator color.
    pub fn separator_color(self, color: Color) -> Self {
        Self {
            separator_color: Some(color),
            ..self
        }
    }
}

impl From<Color> for Style {
    fn from(color: Color) -> Self {
        Self::default().background(color)
    }
}

impl From<Gradient> for Style {
    fn from(gradient: Gradient) -> Self {
        Self::default().background(gradient)
    }
}

impl From<Linear> for Style {
    fn from(gradient: Linear) -> Self {
        Self::default().background(gradient)
    }
}

/// The theme catalog of a [`Ribbon`].
pub trait Catalog {
    /// The item class of the [`Catalog`].
    type Class<'a>;

    /// The default class produced by the [`Catalog`].
    fn default<'a>() -> Self::Class<'a>;

    /// The [`Style`] of a class.
    fn style(&self, class: &Self::Class<'_>) -> Style;
}

/// A styling function for a [`Ribbon`].
pub type StyleFn<'a, Theme> = Box<dyn Fn(&Theme) -> Style + 'a>;

impl<Theme> From<Style> for StyleFn<'_, Theme> {
    fn from(style: Style) -> Self {
        Box::new(move |_theme| style)
    }
}

impl Catalog for Theme {
    type Class<'a> = StyleFn<'a, Self>;

    fn default<'a>() -> Self::Class<'a> {
        Box::new(|_| Style::default())
    }

    fn style(&self, class: &Self::Class<'_>) -> Style {
        class(self)
    }
}

pub fn group<'a, Id, Message, Theme, Renderer>(
    id: Id,
    header: impl text::IntoFragment<'a>,
    content: impl Fn(Size) -> Option<Element<'a, Message, Theme, Renderer>> + 'a,
) -> Group<'a, Id, Message, Theme, Renderer>
where
    Id: Clone + Eq,
    Message: 'a + Clone,
    Theme: 'a + button::Catalog + svg::Catalog + text::Catalog,
    <Theme as svg::Catalog>::Class<'a>: From<svg::StyleFn<'a, Theme>>,
    <Theme as text::Catalog>::Class<'a>: From<text::StyleFn<'a, Theme>>,
    Renderer: 'a + iced_core::Renderer + iced_core::svg::Renderer + iced_core::text::Renderer,
    <Renderer as iced_core::text::Renderer>::Font: From<Font>,
    <Renderer as iced_core::text::Renderer>::Paragraph: Clone,
{
    Group::new(id, header, content)
}