cosmic/widget/settings/
section.rs

1// Copyright 2022 System76 <info@system76.com>
2// SPDX-License-Identifier: MPL-2.0
3
4use crate::Element;
5use crate::widget::{ListColumn, column, text};
6use std::borrow::Cow;
7
8/// A section within a settings view column.
9#[deprecated(note = "use `settings::section().title()` instead")]
10pub fn view_section<'a, Message: 'static>(title: impl Into<Cow<'a, str>>) -> Section<'a, Message> {
11    section().title(title)
12}
13
14/// A section within a settings view column.
15pub fn section<'a, Message: 'static>() -> Section<'a, Message> {
16    with_column(ListColumn::default())
17}
18
19/// A section with a pre-defined list column.
20pub fn with_column<Message: 'static>(children: ListColumn<'_, Message>) -> Section<'_, Message> {
21    Section {
22        header: None,
23        children,
24    }
25}
26
27#[must_use]
28pub struct Section<'a, Message> {
29    header: Option<Element<'a, Message>>,
30    children: ListColumn<'a, Message>,
31}
32
33impl<'a, Message: 'static> Section<'a, Message> {
34    /// Define an optional title for the section.
35    pub fn title(mut self, title: impl Into<Cow<'a, str>>) -> Self {
36        self.header(text::heading(title.into()))
37    }
38
39    /// Define an optional custom header for the section.
40    pub fn header(mut self, header: impl Into<Element<'a, Message>>) -> Self {
41        self.header = Some(header.into());
42        self
43    }
44
45    /// Add a child element to the section's list column.
46    #[allow(clippy::should_implement_trait)]
47    pub fn add(mut self, item: impl Into<Element<'a, Message>>) -> Self {
48        self.children = self.children.add(item.into());
49        self
50    }
51
52    /// Add a child element to the section's list column, if `Some`.
53    pub fn add_maybe(self, item: Option<impl Into<Element<'a, Message>>>) -> Self {
54        if let Some(item) = item {
55            self.add(item)
56        } else {
57            self
58        }
59    }
60
61    /// Extends the [`Section`] with the given children.
62    pub fn extend(
63        self,
64        children: impl IntoIterator<Item = impl Into<Element<'a, Message>>>,
65    ) -> Self {
66        children.into_iter().fold(self, Self::add)
67    }
68}
69
70impl<'a, Message: 'static> From<Section<'a, Message>> for Element<'a, Message> {
71    fn from(data: Section<'a, Message>) -> Self {
72        column::with_capacity(2)
73            .spacing(8)
74            .push_maybe(data.header)
75            .push(data.children)
76            .into()
77    }
78}