Skip to main content

hyprforge_ui/widgets/
layout.rs

1//! The shapes a settings page is built from: its header, its rows, the
2//! card that leads it, and the bar that holds unapplied changes.
3
4use super::{config_line, primary_button, scaled_text, secondary_button, Tint};
5use crate::density;
6use crate::theme::{self, spacing, surface, FontScale};
7use iced::widget::{column, container, row, text::IntoFragment, Column, Container, Space};
8use iced::{Background, Border, Element, Length};
9
10// --- the page header -------------------------------------------------------
11
12/// A page title's size at 100%.
13const PAGE_TITLE_BASE: f32 = 20.0;
14
15/// A page's title, with a short mono line beside it saying what the page
16/// is talking to or what it found — `NetworkManager`,
17/// `2 connected · drag to arrange`, `86 binds · 1 conflict`.
18///
19/// Drawn by the app's shell rather than by each page, so every page has
20/// one and they all sit at the same height.
21pub fn page_header<'a, Message: 'a>(
22    title: impl IntoFragment<'a>,
23    subtitle: Option<String>,
24    scale: FontScale,
25) -> Element<'a, Message> {
26    let title = scaled_text(title, PAGE_TITLE_BASE, scale)
27        .font(iced::Font { weight: iced::font::Weight::Semibold, ..iced::Font::DEFAULT })
28        .color(theme::text());
29    let mut header = row![title].spacing(spacing::SM + spacing::XS).align_y(iced::Alignment::Center);
30    if let Some(subtitle) = subtitle {
31        header = header.push(config_line(subtitle, scale));
32    }
33    header.into()
34}
35
36// --- setting rows ----------------------------------------------------------
37
38/// The gap between setting rows: the mockup's 2px, which with the
39/// alternating fill is what makes a stack read as rows without a divider
40/// between each.
41pub const SETTING_ROW_GAP: f32 = 2.0;
42
43/// A stack of [`setting_row`]s, [`SETTING_ROW_GAP`] apart.
44pub fn setting_list<'a, Message: 'a>(
45    rows: impl IntoIterator<Item = Element<'a, Message>>,
46) -> Column<'a, Message> {
47    column(rows).spacing(SETTING_ROW_GAP).width(Length::Fill)
48}
49
50/// The fill of the row at `index` in a stack: every even row striped,
51/// every odd one clear.
52///
53/// Even rather than odd so the first row is striped — the mockup's
54/// choice, and the one that makes the top of a stack visible as the
55/// top of something.
56pub fn setting_row_style(index: usize) -> container::Style {
57    container::Style {
58        background: index.is_multiple_of(2).then(|| Background::Color(theme::row_tint())),
59        border: Border { radius: density::card_radius().into(), ..Border::default() },
60        ..container::Style::default()
61    }
62}
63
64/// A dim second line under a row's label — what the setting does, or
65/// the config line it writes (use [`config_line`] for the latter).
66pub fn hint_text<'a>(content: impl IntoFragment<'a>, scale: FontScale) -> iced::widget::Text<'a> {
67    super::meta_text(content, density::META_TEXT_BASE * 0.9, scale)
68}
69
70/// One setting: its label on the left (with an optional hint under it),
71/// its control on the right, on a card that is striped or clear by
72/// `index`.
73///
74/// The label and control sit at the row's two ends rather than in a
75/// fixed 2:3 split. The split put a wide gap between "Description" and
76/// its field, so the two read as unrelated; at the ends, the row itself
77/// is what joins them, which is the job the stripe is doing anyway.
78///
79/// At least [`density::setting_row_height`] tall, so a page of one-line
80/// rows keeps a steady rhythm, and taller when a hint needs the room —
81/// never clipped to fit.
82pub fn setting_row<'a, Message: 'a>(
83    index: usize,
84    label: impl IntoFragment<'a>,
85    hint: Option<Element<'a, Message>>,
86    control: impl Into<Element<'a, Message>>,
87    scale: FontScale,
88) -> Element<'a, Message> {
89    let mut left = column![scaled_text(label, density::ROW_TEXT_BASE * 0.9, scale).color(theme::text())]
90        .spacing(2.0);
91    if let Some(hint) = hint {
92        left = left.push(hint);
93    }
94    // The floor: a strut as tall as the least row, so the row can grow
95    // past it but never shrink below it. iced's container has a maximum
96    // height and no minimum.
97    //
98    // One pixel wide, not zero. Measured: with a zero-width strut every
99    // row came out 37px — the height of the tallest control — as though
100    // the strut were not there, and at one pixel they are the 52 asked
101    // for. Do not "tidy" it back to zero. It sits beside the label with
102    // no spacing of its own, or the row's gap would indent every label.
103    let strut = Space::new()
104        .width(Length::Fixed(1.0))
105        .height(Length::Fixed(density::setting_row_height(scale)));
106    let label = row![strut, left.width(Length::Fill)].align_y(iced::Alignment::Center);
107    container(
108        row![label.width(Length::Fill), control.into()]
109            .spacing(spacing::MD)
110            .align_y(iced::Alignment::Center),
111    )
112    .padding([0.0, scale.apply(14.0)])
113    .width(Length::Fill)
114    .style(move |_t: &iced::Theme| setting_row_style(index))
115    .into()
116}
117
118// --- the hero card ---------------------------------------------------------
119
120const HERO_FILL_ALPHA: f32 = 0.10;
121const HERO_BORDER_ALPHA: f32 = 0.40;
122
123/// The card that leads a page with the one thing it is about — the
124/// network you are on, the battery's charge.
125///
126/// Tinted by what that thing's *state* is: `Success` for charging,
127/// `Accent` for "this is the connected one". Faintly, so the content
128/// stays the loudest thing on it.
129pub fn hero_card<'a, Message: 'a>(
130    tint: Tint,
131    content: impl Into<Element<'a, Message>>,
132) -> Container<'a, Message> {
133    let color = tint.iced();
134    container(content)
135        .padding(spacing::MD)
136        .width(Length::Fill)
137        .style(move |_t: &iced::Theme| container::Style {
138            background: Some(Background::Color(iced::Color { a: HERO_FILL_ALPHA, ..color })),
139            border: Border {
140                radius: density::card_radius().into(),
141                width: 1.0,
142                color: iced::Color { a: HERO_BORDER_ALPHA, ..color },
143            },
144            ..container::Style::default()
145        })
146}
147
148/// A small filled circle in `tint` — "connected", "pending", "muted".
149pub fn status_dot<'a, Message: 'a>(tint: Tint, scale: FontScale) -> Element<'a, Message> {
150    let side = scale.apply(7.0);
151    let color = tint.iced();
152    container(Space::new())
153        .width(Length::Fixed(side))
154        .height(Length::Fixed(side))
155        .style(move |_t: &iced::Theme| container::Style {
156            background: Some(Background::Color(color)),
157            border: Border { radius: (side / 2.0).into(), ..Border::default() },
158            ..container::Style::default()
159        })
160        .into()
161}
162
163// --- pending changes -------------------------------------------------------
164
165/// "N pending changes", in words.
166pub fn pending_label(count: usize) -> String {
167    match count {
168        1 => "1 pending change".to_string(),
169        n => format!("{n} pending changes"),
170    }
171}
172
173/// The bar along the foot of a page that has changes nobody has applied
174/// yet: what they are, the setting they will write, and Discard/Apply.
175///
176/// `summary` is usually [`pending_label`]'s count, but not always — a
177/// layout edited on a canvas is one change with no count to give.
178/// `on_discard` is optional because not every page can take its drafts
179/// back, and a Discard button that does nothing is worse than none.
180///
181/// One bar for every page, drawn by the shell, rather than each page's
182/// own wording of "N fields typed but not applied" — nothing is written
183/// until Apply, and the bar is what says so, so it has to look the same
184/// everywhere or a user learns it on one page and misses it on the next.
185///
186/// The preview is the line that will actually change, not a summary of
187/// it: the suite's rule is that nothing silently rewrites a dotfile, and
188/// showing the line is how "silently" is ruled out.
189pub fn pending_bar<'a, Message: Clone + 'a>(
190    summary: String,
191    preview: Option<String>,
192    on_discard: Option<Message>,
193    on_apply: Message,
194    scale: FontScale,
195) -> Element<'a, Message> {
196    let mut info = row![
197        status_dot(Tint::Warning, scale),
198        scaled_text(summary, density::META_TEXT_BASE, scale).color(theme::text()),
199    ]
200    .spacing(spacing::SM)
201    .align_y(iced::Alignment::Center);
202    if let Some(preview) = preview {
203        info = info.push(config_line(preview, scale));
204    }
205    let mut actions = row![].spacing(spacing::SM).align_y(iced::Alignment::Center);
206    if let Some(discard) = on_discard {
207        actions = actions.push(secondary_button("Discard").on_press(discard));
208    }
209    actions = actions.push(primary_button("Apply").on_press(on_apply));
210    container(
211        row![info.width(Length::Fill), actions]
212            .spacing(spacing::SM)
213            .align_y(iced::Alignment::Center),
214    )
215    .padding([spacing::SM, spacing::MD])
216    .width(Length::Fill)
217    .style(|_t: &iced::Theme| container::Style {
218        background: Some(Background::Color(surface::sidebar())),
219        border: Border { width: 1.0, color: surface::card_border(), ..Border::default() },
220        ..container::Style::default()
221    })
222    .into()
223}
224
225#[cfg(test)]
226mod tests {
227    use super::*;
228
229    /// A stripe and a gap, and nothing else: the two row looks must
230    /// share their shape exactly, or alternating rows would read as two
231    /// different kinds of row rather than one list.
232    #[test]
233    fn alternating_rows_differ_only_in_fill() {
234        let striped = setting_row_style(0);
235        let clear = setting_row_style(1);
236        assert_eq!(striped.border, clear.border);
237        assert_eq!(striped.text_color, clear.text_color);
238        assert_eq!(striped.shadow, clear.shadow);
239        assert_eq!(striped.background, Some(Background::Color(theme::row_tint())));
240        assert_eq!(clear.background, None);
241        assert_eq!(setting_row_style(2), striped, "the pattern repeats");
242    }
243
244    #[test]
245    fn a_single_pending_change_is_not_plural() {
246        assert_eq!(pending_label(1), "1 pending change");
247        assert_eq!(pending_label(2), "2 pending changes");
248        assert_eq!(pending_label(0), "0 pending changes");
249    }
250}