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
// Copyright 2022 System76 <info@system76.com>
// SPDX-License-Identifier: MPL-2.0

use crate::ext::CollectionWidget;
use crate::widget::{column, text, ListColumn};
use crate::Element;
use std::borrow::Cow;

/// A section within a settings view column.
#[deprecated(note = "use `settings::section().title()` instead")]
pub fn view_section<'a, Message: 'static>(title: impl Into<Cow<'a, str>>) -> Section<'a, Message> {
    Section {
        title: title.into(),
        children: ListColumn::default(),
    }
}

/// A section within a settings view column.
pub fn section<'a, Message: 'static>() -> Section<'a, Message> {
    with_column(ListColumn::default())
}

/// A section with a pre-defined list column.
pub fn with_column<'a, Message: 'static>(
    children: ListColumn<'a, Message>,
) -> Section<'a, Message> {
    Section {
        title: Cow::Borrowed(""),
        children,
    }
}

#[must_use]
pub struct Section<'a, Message> {
    title: Cow<'a, str>,
    children: ListColumn<'a, Message>,
}

impl<'a, Message: 'static> Section<'a, Message> {
    /// Define an optional title for the section.
    pub fn title(mut self, title: impl Into<Cow<'a, str>>) -> Self {
        self.title = title.into();
        self
    }

    /// Add a child element to the section's list column.
    #[allow(clippy::should_implement_trait)]
    pub fn add(mut self, item: impl Into<Element<'a, Message>>) -> Self {
        self.children = self.children.add(item.into());
        self
    }

    /// Add a child element to the section's list column, if `Some`.
    pub fn add_maybe(self, item: Option<impl Into<Element<'a, Message>>>) -> Self {
        if let Some(item) = item {
            self.add(item)
        } else {
            self
        }
    }

    /// Extends the [`Section`] with the given children.
    pub fn extend(
        self,
        children: impl IntoIterator<Item = impl Into<Element<'a, Message>>>,
    ) -> Self {
        children.into_iter().fold(self, Self::add)
    }
}

impl<'a, Message: 'static> From<Section<'a, Message>> for Element<'a, Message> {
    fn from(data: Section<'a, Message>) -> Self {
        column::with_capacity(2)
            .spacing(8)
            .push_maybe(if data.title.is_empty() {
                None
            } else {
                Some(text::heading(data.title))
            })
            .push(data.children)
            .into()
    }
}