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