Skip to main content

day_piece_settings/
lib.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! day-piece-settings: the settings and About surface every Day app shares (docs/settings.md).
5//!
6//! Three layers, all toolkit-neutral:
7//!
8//! - **Values.** [`Pref<T>`]: a typed, persisted, reactive setting declared once as a static.
9//!   Reads are signals the app can watch; writes land in the [`Store`] (the platform's own
10//!   preferences store through day-part-preferences unless the app installs another).
11//! - **Declaration.** [`Preferences`] holds an [`About`] and the [`Group`]s of [`Section`]s of
12//!   rows ([`rows::toggle`], [`rows::choice`], [`rows::slider`], [`rows::stepper`], [`rows::text`], [`rows::action`], [`rows::link`],
13//!   [`rows::navigate`], [`rows::info`], [`rows::note`], [`rows::custom`]). Groups carry a localized title, an icon and
14//!   a route id. Other crates contribute groups through a [`Provider`].
15//! - **Presentation.** [`Preferences::install`] registers the Preferences window (desktop) or
16//!   the navigation presentation (mobile: an About header, then the groups as a list that
17//!   pushes one page per group), the About window, the Settings…/About/Check for Updates… menu
18//!   items, and the `settings/<group>` string routes. The pieces are composed from ordinary Day
19//!   pieces on every backend; a toolkit feature adds native rows and panels where the platform
20//!   has a stronger idiom.
21//!
22//! ```ignore
23//! // root(), after res::locales::install():
24//! let prefs = day_piece_settings::Preferences::new()
25//!     .about(About::from_manifest().link(res::str::about_website(), "https://daybrite.dev"))
26//!     .group(day_piece_settings::general_group(res::locales::ALL))
27//!     .install();
28//! // … and in the nav, for the platforms with no menu bar:
29//! nav(section)
30//!     .items(prefs.nav_item(Section::Settings))
31//!     .destination(move |_: &Section| prefs.page())
32//! ```
33
34use std::cell::{Cell, RefCell};
35use std::collections::HashMap;
36use std::rc::Rc;
37
38use day_core::{AnyPiece, Piece};
39use day_pieces::prelude::*;
40use day_pieces::{Label, TextSource};
41use day_reactive::{Signal, watch};
42use day_spec::{Cap, Support};
43
44day_pieces::glue_modules!(appkit, gtk, qt, uikit, material, arkui);
45
46#[cfg(all(feature = "xaml", target_os = "windows"))]
47#[path = "lib-xaml.rs"]
48mod xaml_impl;
49
50/// A `(tag, autonym)` locale table, the shape of a generated `res::locales::ALL`.
51pub type LocaleTable = &'static [(&'static str, &'static str)];
52
53/// What an app's `root()` and settings module import: the declaration types, the handle, the
54/// row constructors as a module, and the General group.
55pub mod prelude {
56    pub use crate::{
57        APPEARANCE, About, Appearance, Group, LANGUAGE, Pref, PrefValue, Preferences, Prefs,
58        Presentation, Providers, Row, Section, appearance_row, general_group, language_row,
59        pref_enum, rows,
60    };
61}
62
63// ===========================================================================
64// Values: Pref<T> over a Store
65// ===========================================================================
66
67pub use day_part_preferences::{
68    MemoryStore, NativeStore, Pref, PrefValue, Store, install_store, persistence_failures,
69    pref_enum,
70};
71
72day_core::tls_group! {
73    /// The installed declaration, what the free functions ([`open`], [`open_at`]) reach.
74    static INSTALLED: RefCell<Option<Rc<Installed>>> = const { RefCell::new(None) };
75    /// Providers registered at run time ([`register_provider`]): the wasm path, and explicit
76    /// registration anywhere.
77    static RUNTIME_PROVIDERS: RefCell<Vec<&'static Provider>> = const { RefCell::new(Vec::new()) };
78    /// Whether the General group's appearance/language watchers are installed (once per process).
79    static GENERAL_WIRED: Cell<bool> = const { Cell::new(false) };
80    /// The locale the app started in (system or `--locale`), captured before any stored
81    /// override applies: what the language picker's "System" entry restores.
82    static SYSTEM_LOCALE: std::cell::OnceCell<String> = const { std::cell::OnceCell::new() };
83    /// Sub-page builders by title, what a pushed `page:<title>` route builds.
84    static SUBPAGES: RefCell<HashMap<String, Build>> = RefCell::new(HashMap::new());
85}
86
87// ===========================================================================
88// Declaration: Preferences, Group, Section, rows
89// ===========================================================================
90
91/// A group's icon: a bundled vector/image (`res::vectors::prefs_weather`) or a standard glyph.
92#[derive(Clone, Debug, PartialEq)]
93pub enum GroupIcon {
94    Image(day_spec::ImageName),
95    Symbol(day_spec::Symbol),
96}
97
98impl From<day_spec::Symbol> for GroupIcon {
99    fn from(s: day_spec::Symbol) -> Self {
100        GroupIcon::Symbol(s)
101    }
102}
103impl From<day_spec::ImageName> for GroupIcon {
104    fn from(n: day_spec::ImageName) -> Self {
105        GroupIcon::Image(n)
106    }
107}
108impl From<day_spec::VectorName> for GroupIcon {
109    fn from(n: day_spec::VectorName) -> Self {
110        GroupIcon::Image(n.into())
111    }
112}
113
114type Build = Rc<dyn Fn() -> AnyPiece>;
115type Avail = Rc<dyn Fn() -> bool>;
116
117/// One group of settings (docs/settings.md): a page on desktop (a toolbar tab, a dialog page,
118/// a sidebar entry) and a row of the mobile root list that pushes the page.
119#[derive(Clone)]
120#[must_use]
121pub struct Group {
122    id: &'static str,
123    title: TextSource,
124    subtitle: Option<TextSource>,
125    icon: Option<GroupIcon>,
126    sections: Vec<Section>,
127    custom: Option<Build>,
128    order: i32,
129    available: Option<Avail>,
130}
131
132impl Group {
133    /// A group with a route id (also its element id, `prefs-group-<id>`) and a localized title.
134    pub fn new<M>(id: &'static str, title: impl IntoText<M>) -> Self {
135        Group {
136            id,
137            title: title.into_text(),
138            subtitle: None,
139            icon: None,
140            sections: Vec::new(),
141            custom: None,
142            order: 0,
143            available: None,
144        }
145    }
146    /// The glyph beside the title: a bundled vector (the same name a `nav` item takes) or a
147    /// standard [`day_spec::Symbol`].
148    pub fn icon(mut self, icon: impl Into<GroupIcon>) -> Self {
149        self.icon = Some(icon.into());
150        self
151    }
152    /// One line under the title in the mobile root list ("Units, data source").
153    pub fn subtitle<M>(mut self, t: impl IntoText<M>) -> Self {
154        self.subtitle = Some(t.into_text());
155        self
156    }
157    /// Append a section.
158    pub fn section(mut self, section: Section) -> Self {
159        self.sections.push(section);
160        self
161    }
162    /// Append a row to the group's trailing untitled section (created as needed).
163    pub fn row(mut self, row: Row) -> Self {
164        match self.sections.last_mut() {
165            Some(s) if s.title.is_none() && s.footer.is_none() => s.rows.push(row),
166            _ => self.sections.push(Section::new().row(row)),
167        }
168        self
169    }
170    /// A bespoke piece that is the whole group page (Skies' city editor). Sections, if any,
171    /// render above it.
172    pub fn custom<P: Piece>(mut self, build: impl Fn() -> P + 'static) -> Self {
173        self.custom = Some(Rc::new(move || AnyPiece::new(build())));
174        self
175    }
176    /// Sort key: app groups keep declaration order at 0, providers default to 500, About is
177    /// always last.
178    pub fn order(mut self, order: i32) -> Self {
179        self.order = order;
180        self
181    }
182    /// Hide the whole group when false (evaluated at install and at each build).
183    pub fn available(mut self, f: impl Fn() -> bool + 'static) -> Self {
184        self.available = Some(Rc::new(f));
185        self
186    }
187    /// Hide the group unless the toolkit supports `cap`.
188    pub fn requires(self, cap: Cap) -> Self {
189        self.available(move || day_core::capability(cap) != Support::Unsupported)
190    }
191    /// The route id.
192    #[must_use]
193    pub fn id(&self) -> &'static str {
194        self.id
195    }
196    fn is_available(&self) -> bool {
197        self.available.as_ref().is_none_or(|f| f())
198    }
199}
200
201/// A titled card of rows inside a group.
202#[derive(Clone, Default)]
203#[must_use]
204pub struct Section {
205    title: Option<TextSource>,
206    footer: Option<TextSource>,
207    rows: Vec<Row>,
208}
209
210impl Section {
211    pub fn new() -> Self {
212        Section::default()
213    }
214    /// The header above the card.
215    pub fn title<M>(mut self, t: impl IntoText<M>) -> Self {
216        self.title = Some(t.into_text());
217        self
218    }
219    /// The footnote under the card.
220    pub fn footer<M>(mut self, t: impl IntoText<M>) -> Self {
221        self.footer = Some(t.into_text());
222        self
223    }
224    pub fn row(mut self, row: Row) -> Self {
225        self.rows.push(row);
226        self
227    }
228    pub fn rows(mut self, rows: impl IntoIterator<Item = Row>) -> Self {
229        self.rows.extend(rows);
230        self
231    }
232}
233
234/// How a [`rows::choice`] row presents its options.
235#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
236pub enum ChoiceStyle {
237    /// A menu/combo (the default): any number of options.
238    #[default]
239    Menu,
240    /// A segmented control: for a few short labels (Light / Dark / System).
241    Segmented,
242}
243
244#[derive(Clone)]
245enum RowKind {
246    Toggle(Signal<bool>),
247    Choice {
248        labels: Vec<TextSource>,
249        index: Signal<usize>,
250        style: ChoiceStyle,
251    },
252    Slider {
253        value: Signal<f64>,
254        range: std::ops::RangeInclusive<f64>,
255        step: Option<f64>,
256        value_text: Option<Rc<dyn Fn(f64) -> String>>,
257    },
258    Stepper {
259        value: Signal<f64>,
260        range: std::ops::RangeInclusive<f64>,
261        step: f64,
262    },
263    Text {
264        value: Signal<String>,
265        placeholder: Option<TextSource>,
266        secure: bool,
267    },
268    Action {
269        on: Rc<dyn Fn()>,
270        destructive: bool,
271        confirm: Option<TextSource>,
272        confirm_label: Option<TextSource>,
273        busy: Option<Reactive<bool>>,
274    },
275    Link(String),
276    Navigate(Build),
277    Info {
278        value: TextSource,
279        copyable: bool,
280    },
281    Note,
282    Custom(Build),
283}
284
285/// One row of a section (docs/settings.md), built by the row constructors.
286#[derive(Clone)]
287#[must_use]
288pub struct Row {
289    title: TextSource,
290    caption: Option<TextSource>,
291    id: Option<day_core::ElementId>,
292    enabled: Option<Reactive<bool>>,
293    available: Option<Avail>,
294    kind: RowKind,
295}
296
297impl Row {
298    fn new<M>(title: impl IntoText<M>, kind: RowKind) -> Self {
299        Row {
300            title: title.into_text(),
301            caption: None,
302            id: None,
303            enabled: None,
304            available: None,
305            kind,
306        }
307    }
308    /// The row's title (every row constructor takes one, this replaces it).
309    pub fn title<M>(mut self, t: impl IntoText<M>) -> Self {
310        self.title = t.into_text();
311        self
312    }
313    /// A secondary line under the title.
314    pub fn caption<M>(mut self, t: impl IntoText<M>) -> Self {
315        self.caption = Some(t.into_text());
316        self
317    }
318    /// The element id of the row's control (default `pref-<key>` for a pref row).
319    pub fn id(mut self, id: day_core::ElementId) -> Self {
320        self.id = Some(id);
321        self
322    }
323    /// Gray the control out while this reads false: a `Signal<bool>`, or a derived condition
324    /// (`|| !INCOGNITO.get()`), tracked like any reactive read.
325    pub fn enabled<M>(mut self, enabled: impl IntoReactive<bool, M>) -> Self {
326        self.enabled = Some(enabled.into_reactive());
327        self
328    }
329    /// Omit the row when false.
330    pub fn available(mut self, f: impl Fn() -> bool + 'static) -> Self {
331        self.available = Some(Rc::new(f));
332        self
333    }
334    /// Omit the row unless the toolkit supports `cap`.
335    pub fn requires(self, cap: Cap) -> Self {
336        self.available(move || day_core::capability(cap) != Support::Unsupported)
337    }
338    fn is_available(&self) -> bool {
339        self.available.as_ref().is_none_or(|f| f())
340    }
341}
342
343/// The row constructors (docs/settings.md). Use them qualified (`rows::toggle(..)`): several
344/// share a name with a piece in the Day prelude.
345pub mod rows {
346    use super::*;
347
348    fn pref_id<T: PrefValue>(p: &Pref<T>) -> day_core::ElementId {
349        day_core::id!(pref, p.key())
350    }
351
352    /// An on/off row bound to a `Pref<bool>`.
353    pub fn toggle<M>(pref: &'static Pref<bool>, title: impl IntoText<M>) -> Row {
354        Row::new(title, RowKind::Toggle(pref.signal())).id(pref_id(pref))
355    }
356
357    /// A one-of-N row: `options` pairs each value with its label. Menu by default;
358    /// [`Row::segmented`] for a few short labels.
359    pub fn choice<T: PrefValue, M, L, LM>(
360        pref: &'static Pref<T>,
361        title: impl IntoText<M>,
362        options: impl IntoIterator<Item = (T, L)>,
363    ) -> Row
364    where
365        L: IntoText<LM>,
366    {
367        let (values, labels): (Vec<T>, Vec<TextSource>) =
368            options.into_iter().map(|(v, l)| (v, l.into_text())).unzip();
369        let sig = pref.signal();
370        let current = sig.get_untracked();
371        let index = Signal::global(values.iter().position(|v| *v == current).unwrap_or(0));
372        // Two-way: the index drives the pref; an outside write to the pref (a menu command, a
373        // reset) moves the index. `set_if_changed` on both ends breaks the echo.
374        {
375            let values = values.clone();
376            watch(
377                move || index.get(),
378                move |ix, _| {
379                    if let Some(v) = values.get(*ix) {
380                        pref.set(v.clone());
381                    }
382                },
383            );
384        }
385        watch(
386            move || sig.get(),
387            move |v, _| {
388                if let Some(ix) = values.iter().position(|x| x == v) {
389                    index.set_if_changed(ix);
390                }
391            },
392        );
393        Row::new(
394            title,
395            RowKind::Choice {
396                labels,
397                index,
398                style: ChoiceStyle::Menu,
399            },
400        )
401        .id(pref_id(pref))
402    }
403
404    impl Row {
405        /// Present a [`choice`] as a segmented control.
406        pub fn segmented(mut self) -> Self {
407            if let RowKind::Choice { style, .. } = &mut self.kind {
408                *style = ChoiceStyle::Segmented;
409            }
410            self
411        }
412        /// A [`slider`]'s or [`stepper`]'s step.
413        pub fn step(mut self, s: f64) -> Self {
414            match &mut self.kind {
415                RowKind::Slider { step, .. } => *step = Some(s),
416                RowKind::Stepper { step, .. } => *step = s,
417                _ => {}
418            }
419            self
420        }
421        /// A [`slider`]'s value label, shown beside the control.
422        pub fn value_text(mut self, f: impl Fn(f64) -> String + 'static) -> Self {
423            if let RowKind::Slider { value_text, .. } = &mut self.kind {
424                *value_text = Some(Rc::new(f));
425            }
426            self
427        }
428        /// A [`text`] row's placeholder.
429        pub fn placeholder<M>(mut self, t: impl IntoText<M>) -> Self {
430            if let RowKind::Text { placeholder, .. } = &mut self.kind {
431                *placeholder = Some(t.into_text());
432            }
433            self
434        }
435        /// A [`text`] row that hides its characters.
436        pub fn secure(mut self) -> Self {
437            if let RowKind::Text { secure, .. } = &mut self.kind {
438                *secure = true;
439            }
440            self
441        }
442        /// An [`action`] drawn as destructive (red where the platform has a red).
443        pub fn destructive(mut self) -> Self {
444            if let RowKind::Action { destructive, .. } = &mut self.kind {
445                *destructive = true;
446            }
447            self
448        }
449        /// An [`action`] that asks first: a confirm dialog with `message`, destructive when the
450        /// row is.
451        pub fn confirm<M>(mut self, message: impl IntoText<M>) -> Self {
452            if let RowKind::Action { confirm, .. } = &mut self.kind {
453                *confirm = Some(message.into_text());
454            }
455            self
456        }
457        /// The confirm dialog's own button label ("Reset" rather than the generic OK).
458        pub fn confirm_label<M>(mut self, label: impl IntoText<M>) -> Self {
459            if let RowKind::Action { confirm_label, .. } = &mut self.kind {
460                *confirm_label = Some(label.into_text());
461            }
462            self
463        }
464        /// An [`action`] that shows a spinner and disables while this reads true: a
465        /// `Signal<bool>` or a closure.
466        pub fn busy<M>(mut self, busy: impl IntoReactive<bool, M>) -> Self {
467            if let RowKind::Action { busy: b, .. } = &mut self.kind {
468                *b = Some(busy.into_reactive());
469            }
470            self
471        }
472        /// An [`info`] row with a copy affordance.
473        pub fn copyable(mut self) -> Self {
474            if let RowKind::Info { copyable, .. } = &mut self.kind {
475                *copyable = true;
476            }
477            self
478        }
479    }
480
481    /// A continuous value over `range`.
482    pub fn slider<M>(
483        pref: &'static Pref<f64>,
484        title: impl IntoText<M>,
485        range: std::ops::RangeInclusive<f64>,
486    ) -> Row {
487        let sig = pref.signal();
488        Row::new(
489            title,
490            RowKind::Slider {
491                value: sig,
492                range,
493                step: None,
494                value_text: None,
495            },
496        )
497        .id(pref_id(pref))
498    }
499
500    /// A small integer with increment/decrement controls.
501    pub fn stepper<M>(
502        pref: &'static Pref<i64>,
503        title: impl IntoText<M>,
504        range: std::ops::RangeInclusive<i64>,
505    ) -> Row {
506        let sig = pref.signal();
507        let value = Signal::global(sig.get_untracked() as f64);
508        watch(move || value.get(), move |v, _| pref.set(v.round() as i64));
509        watch(
510            move || sig.get(),
511            move |v, _| value.set_if_changed(*v as f64),
512        );
513        Row::new(
514            title,
515            RowKind::Stepper {
516                value,
517                range: (*range.start() as f64)..=(*range.end() as f64),
518                step: 1.0,
519            },
520        )
521        .id(pref_id(pref))
522    }
523
524    /// A free-text value; every edit persists.
525    pub fn text<M>(pref: &'static Pref<String>, title: impl IntoText<M>) -> Row {
526        let sig = pref.signal();
527        Row::new(
528            title,
529            RowKind::Text {
530                value: sig,
531                placeholder: None,
532                secure: false,
533            },
534        )
535        .id(pref_id(pref))
536    }
537
538    /// A command row: a button with the title. [`Row::destructive`], [`Row::confirm`],
539    /// [`Row::busy`].
540    pub fn action<M>(title: impl IntoText<M>, on: impl Fn() + 'static) -> Row {
541        Row::new(
542            title,
543            RowKind::Action {
544                on: Rc::new(on),
545                destructive: false,
546                confirm: None,
547                confirm_label: None,
548                busy: None,
549            },
550        )
551    }
552
553    /// A row that opens `url` in the platform's handler.
554    pub fn link<M>(title: impl IntoText<M>, url: impl Into<String>) -> Row {
555        Row::new(title, RowKind::Link(url.into()))
556    }
557
558    /// A row that pushes a sub-page built by `build` (a chevron row).
559    pub fn navigate<M, P: Piece>(title: impl IntoText<M>, build: impl Fn() -> P + 'static) -> Row {
560        Row::new(
561            title,
562            RowKind::Navigate(Rc::new(move || AnyPiece::new(build()))),
563        )
564    }
565
566    /// A read-only title/value pair. [`Row::copyable`].
567    pub fn info<M, VM>(title: impl IntoText<M>, value: impl IntoText<VM>) -> Row {
568        Row::new(
569            title,
570            RowKind::Info {
571                value: value.into_text(),
572                copyable: false,
573            },
574        )
575    }
576
577    /// A footnote paragraph inside a section.
578    pub fn note<M>(text: impl IntoText<M>) -> Row {
579        Row::new(text, RowKind::Note)
580    }
581
582    /// Any piece as a row, inside the section's card.
583    pub fn custom<P: Piece>(build: impl Fn() -> P + 'static) -> Row {
584        Row::new("", RowKind::Custom(Rc::new(move || AnyPiece::new(build()))))
585    }
586}
587
588// ===========================================================================
589// About
590// ===========================================================================
591
592/// The app's About content (docs/settings.md): a window on the desktops, the toolkit's About
593/// dialog on GTK, a page inside Settings on mobile and Windows.
594#[derive(Clone, Default)]
595#[must_use]
596pub struct About {
597    name: Option<TextSource>,
598    version: Option<String>,
599    build: Option<String>,
600    tagline: Option<TextSource>,
601    copyright: Option<TextSource>,
602    icon: Option<day_spec::ImageName>,
603    links: Vec<(TextSource, String)>,
604    privacy: Option<String>,
605    credits: Option<TextSource>,
606    licenses: Option<TextSource>,
607    custom: Option<Build>,
608}
609
610impl About {
611    /// Name, version and build from the app identity `day build` exports (`Day.toml`
612    /// `[app]`), falling back to the window's app name and `WindowOptions::version` at run
613    /// time.
614    pub fn from_manifest() -> Self {
615        About {
616            version: option_env!("DAY_SETTINGS_APP_VERSION").map(str::to_owned),
617            build: option_env!("DAY_SETTINGS_APP_BUILD").map(str::to_owned),
618            ..Default::default()
619        }
620    }
621    /// The display name (default: the app title from the manifest, else the window title).
622    pub fn name<M>(mut self, t: impl IntoText<M>) -> Self {
623        self.name = Some(t.into_text());
624        self
625    }
626    pub fn version(mut self, v: impl Into<String>) -> Self {
627        self.version = Some(v.into());
628        self
629    }
630    pub fn build(mut self, b: impl Into<String>) -> Self {
631        self.build = Some(b.into());
632        self
633    }
634    /// One line under the name.
635    pub fn tagline<M>(mut self, t: impl IntoText<M>) -> Self {
636        self.tagline = Some(t.into_text());
637        self
638    }
639    pub fn copyright<M>(mut self, t: impl IntoText<M>) -> Self {
640        self.copyright = Some(t.into_text());
641        self
642    }
643    /// The app icon as a bundled image (`res::images::icon`).
644    pub fn icon(mut self, icon: impl Into<day_spec::ImageName>) -> Self {
645        self.icon = Some(icon.into());
646        self
647    }
648    /// A titled link. The two links most apps carry have their own methods with localized
649    /// titles: [`website`](Self::website) and [`source`](Self::source).
650    pub fn link<M>(mut self, title: impl IntoText<M>, url: impl Into<String>) -> Self {
651        self.links.push((title.into_text(), url.into()));
652        self
653    }
654    /// The app's website, titled from Day's catalog (`day_about_website`).
655    pub fn website(self, url: impl Into<String>) -> Self {
656        self.link(day_localization_ui::res::str::day_about_website(), url)
657    }
658    /// The app's source code, titled from Day's catalog (`day_about_source`).
659    pub fn source(self, url: impl Into<String>) -> Self {
660        self.link(day_localization_ui::res::str::day_about_source(), url)
661    }
662    /// The privacy policy URL: a known slot (the stores ask for it, GTK has a field).
663    pub fn privacy(mut self, url: impl Into<String>) -> Self {
664        self.privacy = Some(url.into());
665        self
666    }
667    /// Acknowledgements, as a text block (Markdown where the toolkit renders it).
668    pub fn credits<M>(mut self, t: impl IntoText<M>) -> Self {
669        self.credits = Some(t.into_text());
670        self
671    }
672    /// Third-party license notices, as one text block.
673    pub fn licenses<M>(mut self, t: impl IntoText<M>) -> Self {
674        self.licenses = Some(t.into_text());
675        self
676    }
677    /// A bespoke piece that replaces the composed About body.
678    pub fn custom<P: Piece>(mut self, build: impl Fn() -> P + 'static) -> Self {
679        self.custom = Some(Rc::new(move || AnyPiece::new(build())));
680        self
681    }
682
683    /// The resolved display name.
684    pub fn display_name(&self) -> String {
685        match &self.name {
686            Some(n) => n.initial(),
687            None => option_env!("DAY_SETTINGS_APP_TITLE")
688                .map(str::to_owned)
689                .or_else(|| day_core::launch_options().map(|o| o.app_name.unwrap_or(o.title)))
690                .unwrap_or_default(),
691        }
692    }
693    /// The version line, localized ("Version 2.3.0 (14)").
694    #[must_use]
695    pub fn version_line(&self) -> Option<String> {
696        use std::fmt::Write as _;
697        let version = self
698            .version
699            .clone()
700            .or_else(|| day_core::launch_options().and_then(|o| o.version.clone()))?;
701        let mut line = day_localization_ui::res::str::day_about_version(version).format();
702        if let Some(build) = &self.build
703            && !build.is_empty()
704        {
705            let _ = write!(line, " ({build})");
706        }
707        Some(line)
708    }
709    #[must_use]
710    pub fn version_value(&self) -> Option<&str> {
711        self.version.as_deref()
712    }
713    #[must_use]
714    pub fn build_value(&self) -> Option<&str> {
715        self.build.as_deref()
716    }
717    #[must_use]
718    pub fn links(&self) -> &[(TextSource, String)] {
719        &self.links
720    }
721    #[must_use]
722    pub fn privacy_url(&self) -> Option<&str> {
723        self.privacy.as_deref()
724    }
725    #[must_use]
726    pub fn icon_name(&self) -> Option<&day_spec::ImageName> {
727        self.icon.as_ref()
728    }
729    pub fn tagline_text(&self) -> Option<String> {
730        self.tagline.as_ref().map(TextSource::initial)
731    }
732    pub fn copyright_text(&self) -> Option<String> {
733        self.copyright.as_ref().map(TextSource::initial)
734    }
735    pub fn credits_text(&self) -> Option<String> {
736        self.credits.as_ref().map(TextSource::initial)
737    }
738    pub fn licenses_text(&self) -> Option<String> {
739        self.licenses.as_ref().map(TextSource::initial)
740    }
741    #[must_use]
742    pub fn custom_piece(&self) -> Option<AnyPiece> {
743        self.custom.as_ref().map(|b| b())
744    }
745}
746
747// ===========================================================================
748// Providers
749// ===========================================================================
750
751/// A settings group contributed by another crate (docs/settings.md): the self-updater's
752/// Updates group is the first. Declared as a static through [`provider!`], which registers it
753/// in the link-time slice on native targets; on wasm (no linkme) and anywhere an explicit
754/// order matters, [`register_provider`] / [`Preferences::provider`] name it directly.
755pub struct Provider {
756    /// The group's route id; also used by [`Preferences::without_provider`].
757    pub id: &'static str,
758    /// Sort key among the app's groups (apps default to 0, providers to 500).
759    pub order: i32,
760    /// Whether the group applies to this build/platform at all.
761    pub available: fn() -> bool,
762    /// The group.
763    pub group: fn() -> Group,
764    /// Runs once inside [`Preferences::install`], after the store is reachable: register menu
765    /// actions, start a scheduler, apply a persisted value.
766    pub startup: Option<fn()>,
767}
768
769/// Every statically registered [`Provider`] (native targets; empty on wasm).
770#[cfg(not(target_arch = "wasm32"))]
771#[linkme::distributed_slice]
772pub static PROVIDERS: [&'static Provider];
773
774/// Declare a provider static and register it (docs/settings.md):
775///
776/// ```ignore
777/// day_piece_settings::provider! {
778///     static UPDATES: Provider = Provider { id: "updates", order: 900, available: || true,
779///         group: updates_group, startup: Some(schedule) };
780/// }
781/// ```
782#[macro_export]
783macro_rules! provider {
784    ($(#[$meta:meta])* $vis:vis static $name:ident : Provider = $init:expr ;) => {
785        $(#[$meta])*
786        $vis static $name: $crate::Provider = $init;
787        // The crate path keeps an out-of-tree provider free of its own `linkme` dependency.
788        #[cfg(not(target_arch = "wasm32"))]
789        #[$crate::linkme::distributed_slice($crate::PROVIDERS)]
790        #[linkme(crate = $crate::linkme)]
791        static __DAY_SETTINGS_PROVIDER: &'static $crate::Provider = &$name;
792    };
793}
794
795#[doc(hidden)]
796pub use linkme;
797
798/// Register a provider at run time (before [`Preferences::install`]): the wasm path, and the
799/// explicit alternative to the link-time slice anywhere.
800pub fn register_provider(p: &'static Provider) {
801    RUNTIME_PROVIDERS.with(|r| {
802        let mut r = r.borrow_mut();
803        if !r.iter().any(|q| std::ptr::eq(*q, p)) {
804            r.push(p);
805        }
806    });
807}
808
809fn all_providers() -> Vec<&'static Provider> {
810    let mut out: Vec<&'static Provider> = Vec::new();
811    #[cfg(not(target_arch = "wasm32"))]
812    out.extend(PROVIDERS.iter().copied());
813    RUNTIME_PROVIDERS.with(|r| {
814        for p in r.borrow().iter() {
815            if !out.iter().any(|q| std::ptr::eq(*q, *p)) {
816                out.push(p);
817            }
818        }
819    });
820    out
821}
822
823/// Which providers [`Preferences::install`] collects.
824#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
825pub enum Providers {
826    /// Every registered provider whose `available` says yes (the default).
827    #[default]
828    Registered,
829    /// Only the ones named with [`Preferences::provider`].
830    None,
831}
832
833// ===========================================================================
834// Preferences: the declaration and install()
835// ===========================================================================
836
837/// How the surface is presented; chosen per toolkit by default.
838#[derive(Clone, Copy, Debug, PartialEq, Eq)]
839pub enum Presentation {
840    /// A desktop Preferences window with the groups as tabs/pages (the app menu opens it).
841    Window,
842    /// A navigation presentation: a root list (About header, groups) pushing one page per
843    /// group. Mobile, and any app that keeps settings as an in-app route.
844    Navigation,
845}
846
847/// The settings declaration (docs/settings.md). Build it in `root()` and call
848/// [`Self::install`].
849#[must_use]
850pub struct Preferences {
851    about: Option<About>,
852    groups: Vec<Group>,
853    providers: Providers,
854    explicit: Vec<&'static Provider>,
855    excluded: Vec<&'static str>,
856    presentation: Option<Presentation>,
857    window_size: day_spec::Size,
858    title: Option<TextSource>,
859}
860
861impl Default for Preferences {
862    fn default() -> Self {
863        Self::new()
864    }
865}
866
867impl Preferences {
868    pub fn new() -> Self {
869        Preferences {
870            about: None,
871            groups: Vec::new(),
872            providers: Providers::Registered,
873            explicit: Vec::new(),
874            excluded: Vec::new(),
875            presentation: None,
876            window_size: day_spec::Size::new(560.0, 640.0),
877            title: None,
878        }
879    }
880    /// The About content; registers the About menu item and window.
881    pub fn about(mut self, about: About) -> Self {
882        self.about = Some(about);
883        self
884    }
885    /// Append a group.
886    pub fn group(mut self, group: Group) -> Self {
887        self.groups.push(group);
888        self
889    }
890    /// Which registered providers to collect (default: all available).
891    pub fn providers(mut self, policy: Providers) -> Self {
892        self.providers = policy;
893        self
894    }
895    /// Name a provider explicitly (also what a wasm build does, where the link-time slice is
896    /// empty).
897    pub fn provider(mut self, p: &'static Provider) -> Self {
898        self.explicit.push(p);
899        self
900    }
901    /// Leave out a registered provider by id.
902    pub fn without_provider(mut self, id: &'static str) -> Self {
903        self.excluded.push(id);
904        self
905    }
906    /// Pin the presentation instead of letting the toolkit decide.
907    pub fn presentation(mut self, p: Presentation) -> Self {
908        self.presentation = Some(p);
909        self
910    }
911    /// The desktop window's size (height is a ceiling: the window fits its page).
912    pub fn window_size(mut self, width: f64, height: f64) -> Self {
913        self.window_size = day_spec::Size::new(width, height);
914        self
915    }
916    /// The surface's title (default: the platform's word, Settings or Preferences).
917    pub fn title<M>(mut self, t: impl IntoText<M>) -> Self {
918        self.title = Some(t.into_text());
919        self
920    }
921
922    /// Wire everything up (docs/settings.md) and return the handle the app's nav and pages
923    /// use. Call once, in `root()`, after the locale catalog installs and before `app_menu`.
924    pub fn install(self) -> Prefs {
925        let Preferences {
926            about,
927            mut groups,
928            providers,
929            explicit,
930            excluded,
931            presentation,
932            window_size,
933            title,
934        } = self;
935        // Collect providers: the registered set (unless opted out), plus explicit ones.
936        let mut chosen: Vec<&'static Provider> = Vec::new();
937        if providers == Providers::Registered {
938            chosen.extend(all_providers());
939        }
940        for p in explicit {
941            if !chosen.iter().any(|q| std::ptr::eq(*q, p)) {
942                chosen.push(p);
943            }
944        }
945        chosen.retain(|p| !excluded.contains(&p.id) && (p.available)());
946        for p in &chosen {
947            if let Some(startup) = p.startup {
948                startup();
949            }
950            groups.push((p.group)().order(p.order));
951        }
952        groups.sort_by_key(|g| g.order);
953        let presentation = presentation.unwrap_or_else(default_presentation);
954        let title = title.unwrap_or_else(|| TextSource::Dyn(Rc::new(platform_word)));
955        let installed = Rc::new(Installed {
956            in_nav: Cell::default(),
957            about,
958            groups,
959            presentation,
960            title,
961            selected: Signal::global(String::new()),
962            path: Signal::global(Vec::new()),
963        });
964        INSTALLED.with(|i| *i.borrow_mut() = Some(installed.clone()));
965
966        // Desktop: the Preferences window and its menu item, and the About window. A
967        // navigation-presentation toolkit with an app menu (the web's emulated menu button)
968        // registers the cover as the surface instead, so the injected Settings… item exists
969        // and opens it; without a menu nothing is registered and the app's nav item is the
970        // entry.
971        match presentation {
972            Presentation::Window => {
973                let inst = installed.clone();
974                day_core::register_preferences_with(
975                    day_spec::WindowOptions {
976                        title: installed.title.initial(),
977                        size: window_size,
978                        size_to_fit: true,
979                        ..day_spec::WindowOptions::default()
980                    },
981                    move || window_shell(inst.clone()),
982                );
983            }
984            Presentation::Navigation
985                if day_core::capability(Cap::AppMenu) != Support::Unsupported =>
986            {
987                let inst = installed.clone();
988                day_core::register_preferences_with(
989                    day_spec::WindowOptions {
990                        title: installed.title.initial(),
991                        ..day_spec::WindowOptions::default()
992                    },
993                    move || navigation_shell_with_done(inst.clone()),
994                );
995            }
996            Presentation::Navigation => {}
997        }
998        if installed.about.is_some() {
999            install_about(installed.clone());
1000        }
1001        register_route_controller(installed.clone());
1002        Prefs(installed)
1003    }
1004}
1005
1006/// The installed declaration, shared by the handle and the free functions.
1007struct Installed {
1008    about: Option<About>,
1009    groups: Vec<Group>,
1010    presentation: Presentation,
1011    title: TextSource,
1012    /// The selected group id in the desktop window ("" = first).
1013    selected: Signal<String>,
1014    /// The pushed path in the navigation presentation.
1015    path: Signal<Vec<SettingsRoute>>,
1016    /// The app placed the navigation presentation in its own navigation (a nav item or an
1017    /// embedded page), which then owns the `settings` route.
1018    in_nav: std::cell::Cell<bool>,
1019}
1020
1021impl Installed {
1022    fn visible_groups(&self) -> Vec<&Group> {
1023        self.groups.iter().filter(|g| g.is_available()).collect()
1024    }
1025    fn group(&self, id: &str) -> Option<&Group> {
1026        self.groups.iter().find(|g| g.id == id && g.is_available())
1027    }
1028}
1029
1030/// The word the platform uses for the surface: "Settings" on macOS, Windows and the phones,
1031/// "Preferences" on GNOME and KDE.
1032fn platform_word() -> String {
1033    let gnome_or_kde = matches!(day_core::toolkit_key(), Some("gtk" | "qt"));
1034    if gnome_or_kde {
1035        day_localization::t(day_localization::key::day_preferences)
1036    } else {
1037        day_localization::t(day_localization::key::day_settings)
1038    }
1039}
1040
1041fn default_presentation() -> Presentation {
1042    // A toolkit that can open a window and has a menu bar to reach it from gets the window;
1043    // everything else (the phones, HarmonyOS, the web) gets the navigation presentation.
1044    let windows = day_core::capability(Cap::MultiWindow) != Support::Unsupported;
1045    let menu = day_core::capability(Cap::AppMenu) != Support::Unsupported;
1046    if windows && menu {
1047        Presentation::Window
1048    } else {
1049        Presentation::Navigation
1050    }
1051}
1052
1053/// The handle [`Preferences::install`] returns: `Copy`, so pages and the nav take it by value.
1054#[derive(Clone)]
1055pub struct Prefs(Rc<Installed>);
1056
1057impl Prefs {
1058    /// Open-or-focus the surface: the window on desktop; on mobile, select the nav item when
1059    /// one is mounted, else present the navigation presentation as a cover.
1060    pub fn open(&self) -> bool {
1061        open()
1062    }
1063    /// Open and select a group (`"updates"`), optionally a row (`"updates/check"`).
1064    pub fn open_at(&self, route: &str) -> bool {
1065        open_at(route)
1066    }
1067    /// Whether the app should place a Settings entry in its own navigation: true where the
1068    /// platform gives no app menu to reach the surface from (the phones); false on the
1069    /// desktops and on the web, whose menu button carries Settings… and About.
1070    #[must_use]
1071    pub fn in_nav(&self) -> bool {
1072        self.0.presentation == Presentation::Navigation
1073            && day_core::capability(Cap::AppMenu) == Support::Unsupported
1074    }
1075    /// The Settings entry for the app's navigation, titled with the platform's word and
1076    /// opening [`page`](Self::page): `Some` where [`Self::in_nav`], `None` where the platform's
1077    /// application menu already carries Settings. Goes straight into a nav's items:
1078    /// `nav(sel).items((…, prefs.nav_item(Section::Settings)))`.
1079    pub fn nav_item<K>(&self, key: impl Into<K>) -> Option<NavItem<K>> {
1080        self.in_nav().then(|| self.nav_item_everywhere(key))
1081    }
1082    /// The Settings entry on every platform, menu or not: for an app that wants Settings in
1083    /// its sidebar on the desktop too. Most apps want [`nav_item`](Self::nav_item).
1084    pub fn nav_item_everywhere<K>(&self, key: impl Into<K>) -> NavItem<K> {
1085        self.0.in_nav.set(true);
1086        let title = self.0.title.clone();
1087        let inst = self.0.clone();
1088        item(key, move || title.initial()).page(move || navigation_shell(inst.clone()))
1089    }
1090    /// The navigation presentation as a piece: the destination of the nav item, or any place
1091    /// the app embeds settings.
1092    pub fn page(&self) -> AnyPiece {
1093        self.0.in_nav.set(true);
1094        navigation_shell(self.0.clone())
1095    }
1096    /// One group's page alone (an in-reader sheet, a sidebar pane).
1097    pub fn group_page(&self, id: &str) -> AnyPiece {
1098        match self.0.group(id) {
1099            Some(g) => group_page(self.0.clone(), g, false),
1100            None => column(()).any(),
1101        }
1102    }
1103    /// One group's sections without a scroll, for a sheet that stacks several groups and
1104    /// owns the scrolling itself: put the bodies in one `scroll`. The phones keep their native
1105    /// shape, sized to its rows.
1106    pub fn group_body(&self, id: &str) -> AnyPiece {
1107        match self.0.group(id) {
1108            Some(g) => group_body(self.0.clone(), g),
1109            None => column(()).any(),
1110        }
1111    }
1112    /// The composed About page.
1113    pub fn about_page(&self) -> AnyPiece {
1114        about_page(self.0.clone())
1115    }
1116    /// The surface's title.
1117    #[must_use]
1118    pub fn title(&self) -> String {
1119        self.0.title.initial()
1120    }
1121}
1122
1123fn installed() -> Option<Rc<Installed>> {
1124    INSTALLED.with(|i| i.borrow().clone())
1125}
1126
1127/// Open-or-focus the installed settings surface (see [`Prefs::open`]).
1128pub fn open() -> bool {
1129    let Some(inst) = installed() else {
1130        log::warn!("day-piece-settings: open() before Preferences::install()");
1131        return false;
1132    };
1133    match inst.presentation {
1134        Presentation::Window => day_core::open_preferences(),
1135        Presentation::Navigation => day_core::navigate(NAV_KEY) || open_cover(inst),
1136    }
1137}
1138
1139/// Present the navigation presentation as a cover (a Done button closes it): the mobile path
1140/// when no nav item is mounted.
1141fn open_cover(inst: Rc<Installed>) -> bool {
1142    // A newly presented Settings cover starts at its group list. Keep the current
1143    // page when merely focusing a cover that is already open. `open_at` applies its
1144    // requested group after this call, so deep links still land on that group.
1145    if day_core::window_by_key(day_core::windows::PREFERENCES_KEY).is_none() {
1146        inst.path.set(Vec::new());
1147    }
1148    day_core::open_window(
1149        day_spec::WindowOptions::default()
1150            .title(inst.title.initial())
1151            .key(day_core::windows::PREFERENCES_KEY)
1152            .kind(day_spec::WindowKind::Preferences),
1153        move || navigation_shell_with_done(inst.clone()),
1154    );
1155    true
1156}
1157
1158/// The nav item key an app conventionally mounts the surface under; `open()` tries it first.
1159pub const NAV_KEY: &str = "settings";
1160
1161/// The installed navigation presentation as a piece (see [`Prefs::page`]), for code that has
1162/// no [`Prefs`] handle at hand. An empty piece before [`Preferences::install`].
1163pub fn page() -> AnyPiece {
1164    match installed() {
1165        Some(inst) => {
1166            // The app is placing Settings in its own navigation, which then owns the
1167            // `settings` route (the phone cover controller stands aside).
1168            inst.in_nav.set(true);
1169            navigation_shell(inst)
1170        }
1171        None => column(()).any(),
1172    }
1173}
1174
1175/// One installed group's page alone (see [`Prefs::group_page`]).
1176pub fn group_page_of(id: &str) -> AnyPiece {
1177    match installed() {
1178        Some(inst) => Prefs(inst).group_page(id),
1179        None => column(()).any(),
1180    }
1181}
1182
1183/// Open the surface at a group route (`"updates"`, `"updates/check"`).
1184pub fn open_at(route: &str) -> bool {
1185    let Some(inst) = installed() else {
1186        return false;
1187    };
1188    let (group, _row) = route.split_once('/').unwrap_or((route, ""));
1189    if group == "about" {
1190        return day_core::open_about();
1191    }
1192    if inst.group(group).is_none() {
1193        return false;
1194    }
1195    match inst.presentation {
1196        Presentation::Window => {
1197            inst.selected.set_if_changed(group.to_string());
1198            day_core::open_preferences()
1199        }
1200        Presentation::Navigation => {
1201            // Already inside the settings section (a route's second segment arriving while
1202            // the first is current): just move the stack, without re-entering `navigate`.
1203            let inside = day_core::current_route()
1204                .is_some_and(|r| r == NAV_KEY || r.starts_with(&format!("{NAV_KEY}/")));
1205            let ok = inside || open();
1206            inst.path.set(vec![SettingsRoute::Group(group.to_string())]);
1207            ok
1208        }
1209    }
1210}
1211
1212/// Register the desktop surface as a route root, so `navigate("settings/updates")` and a deep
1213/// link open the window on the group (the navigation presentation routes through its nav
1214/// item instead).
1215///
1216/// Two controllers: the root answers `settings` (and `about`, and a bare group id) by opening
1217/// the window; a second, registered right after it, answers the group segment that follows.
1218/// day-core feeds an absolute path's tail only to the surfaces nested after the one that
1219/// took its head, never to that surface itself, and the window's own nav is `.local()` (it
1220/// must not contribute to the app's route), so the tail needs a surface of its own to land on.
1221///
1222/// For the window presentation, and for a navigation presentation whose toolkit has an app
1223/// menu (the web). Where the platform has no menu the app's nav item owns the `settings`
1224/// route and the stack inside it owns the group segment; a controller there would be
1225/// consulted before the app's nav (it registers earlier) and would present the cover over a
1226/// section that never switched. An app with no nav host on such a platform reaches the
1227/// cover through [`open`] from its own affordance.
1228fn register_route_controller(inst: Rc<Installed>) {
1229    // The web is the navigation presentation with an emulated app menu: the cover is the
1230    // registered preferences surface and no nav item claims `settings`, so the routes land
1231    // here too (the starter's `navigate: settings` step runs on every target).
1232    let menu = day_core::capability(Cap::AppMenu) != Support::Unsupported;
1233    if inst.presentation != Presentation::Window && !menu {
1234        register_cover_route_controller(inst);
1235        return;
1236    }
1237    let open_surface = day_core::open_preferences;
1238    let root = inst.clone();
1239    let open_root = open_surface;
1240    let _root_token = day_core::register_nav(day_core::NavController {
1241        push: Box::new(move |route| {
1242            if route == NAV_KEY {
1243                open_root()
1244            } else if route == "about" {
1245                day_core::open_about()
1246            } else if root.group(route).is_some() {
1247                open_at(route)
1248            } else {
1249                false
1250            }
1251        }),
1252        pop: Box::new(|_| false),
1253        current: Box::new(String::new),
1254        enter: Box::new(move |segment| segment == NAV_KEY && open_surface()),
1255        segments: Box::new(Vec::new),
1256        depth: 0,
1257        layer: Box::new(|| 0),
1258        active: Box::new(|| true),
1259    });
1260    let group = inst;
1261    let _group_token = day_core::register_nav(day_core::NavController {
1262        push: Box::new(|_| false),
1263        pop: Box::new(|_| false),
1264        current: Box::new(String::new),
1265        enter: Box::new(move |segment| group.group(segment).is_some() && open_at(segment)),
1266        segments: Box::new(Vec::new),
1267        // Depth 0, like the root: day-core offers an absolute path's tail to the surfaces
1268        // after the anchor in depth order, registration order within a depth. At depth 1
1269        // this controller came after the app's own nav (depth 0, registered later), which
1270        // took a tail naming one of its sections (`settings/practice` opened Lexicon's
1271        // Practice section). At depth 0 it is consulted first, and a segment naming no group
1272        // still falls through to the app.
1273        depth: 0,
1274        layer: Box::new(|| 0),
1275        active: Box::new(|| true),
1276    });
1277}
1278
1279/// The routes for a phone app with no nav host: `navigate("settings/search")` and a deep link
1280/// present the Settings cover on that group, as [`open_at`] does. A fallback
1281/// ([`day_core::register_nav_fallback`]): consulted only when no mounted surface accepts the
1282/// route, so an app with a `settings` section of its own (built yet or not: a sidebar builds a
1283/// page on its first visit) selects that section, whose Settings stack then takes the group.
1284/// It also stands aside once the app has mounted Settings anywhere in its own navigation
1285/// ([`Prefs::nav_item`], [`Prefs::page`], [`page`]).
1286fn register_cover_route_controller(inst: Rc<Installed>) {
1287    let root = inst.clone();
1288    let active = inst.clone();
1289    let enter = inst;
1290    let _token = day_core::register_nav_fallback(day_core::NavController {
1291        push: Box::new(move |route| {
1292            if route == NAV_KEY {
1293                open_cover(root.clone())
1294            } else if route == "about" {
1295                day_core::open_about()
1296            } else if root.group(route).is_some() {
1297                open_cover(root.clone());
1298                root.path.set(vec![SettingsRoute::Group(route.to_string())]);
1299                true
1300            } else {
1301                false
1302            }
1303        }),
1304        pop: Box::new(|_| false),
1305        current: Box::new(String::new),
1306        // The rest of `settings/<group>` once `push` has opened the cover.
1307        enter: Box::new(move |segment| {
1308            if enter.group(segment).is_none() {
1309                return false;
1310            }
1311            enter
1312                .path
1313                .set(vec![SettingsRoute::Group(segment.to_string())]);
1314            true
1315        }),
1316        segments: Box::new(Vec::new),
1317        depth: 0,
1318        layer: Box::new(|| 0),
1319        active: Box::new(move || !active.in_nav.get()),
1320    });
1321}
1322
1323fn install_about(inst: Rc<Installed>) {
1324    #[cfg(feature = "gtk")]
1325    {
1326        if gtk_impl::install_about(inst.clone()) {
1327            return;
1328        }
1329    }
1330    let name = inst.about.as_ref().map_or_default(About::display_name);
1331    let title = day_localization_ui::res::str::day_about_app(name);
1332    // Where windows open as covers (the web, a phone), About is a sheet with a title bar and a
1333    // Done button, as Settings is there: a bare page had no way out.
1334    let cover = day_core::capability(day_spec::Cap::MultiWindow) == day_spec::Support::Unsupported;
1335    day_core::register_about_window(
1336        day_spec::WindowOptions {
1337            title: title.format(),
1338            size: day_spec::Size::new(320.0, 480.0),
1339            size_to_fit: true,
1340            ..day_spec::WindowOptions::default()
1341        },
1342        move || {
1343            if cover {
1344                let title = title.clone();
1345                nav_stack(
1346                    Signal::new(Vec::<SettingsRoute>::new()),
1347                    about_page(inst.clone()),
1348                )
1349                .title(move || title.format())
1350                .toolbar(
1351                    toolbar_button(
1352                        day_core::id!(about_done),
1353                        day_localization_ui::res::str::day_settings_done(),
1354                    )
1355                    .action(|| {
1356                        if let Some(w) = day_core::window_by_key(day_core::windows::ABOUT_KEY) {
1357                            w.close();
1358                        }
1359                    }),
1360                )
1361                .any()
1362            } else {
1363                about_page(inst.clone())
1364            }
1365        },
1366    );
1367}
1368
1369// ===========================================================================
1370// The General group: appearance + language
1371// ===========================================================================
1372
1373pref_enum! {
1374    /// The app's appearance override: the platform's light or dark look, or whatever the system
1375    /// says (the default).
1376    pub enum Appearance { Light = "light", Dark = "dark", System = "system" }
1377}
1378
1379/// The appearance pref every app shares, key `day.appearance`. `DAY_THEME` wins at launch.
1380pub static APPEARANCE: Pref<Appearance> =
1381    Pref::new("day.appearance", || Appearance::System).env("DAY_THEME");
1382
1383/// The language pref every app shares, key `day.locale`: a locale tag, or empty for the
1384/// system language. `DAY_LOCALE` wins at launch.
1385pub static LANGUAGE: Pref<String> = Pref::new("day.locale", String::new).env("DAY_LOCALE");
1386
1387fn system_locale() -> String {
1388    SYSTEM_LOCALE
1389        .with(|c| c.get().cloned())
1390        .unwrap_or_else(|| day_localization_ui::locale().get_untracked())
1391}
1392
1393fn apply_appearance(a: Appearance) {
1394    if day_core::capability(Cap::Appearance) == Support::Unsupported {
1395        return;
1396    }
1397    day_core::set_appearance(match a {
1398        Appearance::Light => Some(false),
1399        Appearance::Dark => Some(true),
1400        Appearance::System => None,
1401    });
1402}
1403
1404fn apply_language(tag: &str) {
1405    if tag.is_empty() {
1406        day_localization_ui::set_locale(&system_locale());
1407    } else {
1408        day_localization_ui::set_locale(tag);
1409    }
1410}
1411
1412/// Apply the persisted appearance and language at boot and keep applying every later change
1413/// (docs/settings.md). Runs once per process; [`general_group`] calls it, and an app that
1414/// uses the prefs without the group calls it itself. Honors the env-wins rule: under
1415/// `DAY_THEME`/`DAY_LOCALE` the stored value is not applied at boot (the launch override
1416/// stays deterministic), while live changes always apply.
1417pub fn wire_general() {
1418    if GENERAL_WIRED.with(|w| w.replace(true)) {
1419        return;
1420    }
1421    SYSTEM_LOCALE.with(|c| {
1422        let _ = c.set(day_localization_ui::locale().get_untracked());
1423    });
1424    if !APPEARANCE.env_forced() {
1425        apply_appearance(APPEARANCE.get_untracked());
1426    }
1427    if !LANGUAGE.env_forced() {
1428        let tag = LANGUAGE.get_untracked();
1429        if !tag.is_empty() {
1430            apply_language(&tag);
1431        }
1432    }
1433    let root = day_reactive::Scope::root();
1434    root.enter(|| {
1435        APPEARANCE.watch(|a| apply_appearance(*a));
1436        LANGUAGE.watch(|tag| apply_language(tag));
1437    });
1438}
1439
1440/// The "General" group every app starts with: Appearance (`theme-picker`, present where the
1441/// toolkit honors a runtime override) and Language (`language-picker`: System plus every
1442/// bundled locale under its own name). `locales` is the app's generated `res::locales::ALL`.
1443pub fn general_group(locales: LocaleTable) -> Group {
1444    wire_general();
1445    Group::new(
1446        "general",
1447        day_localization_ui::res::str::day_settings_general(),
1448    )
1449    .icon(day_spec::Symbol::Settings)
1450    .row(appearance_row())
1451    .row(language_row(locales))
1452}
1453
1454/// The Light / Dark / System row alone (id `theme-picker`), for apps composing their own group.
1455pub fn appearance_row() -> Row {
1456    wire_general();
1457    rows::choice(
1458        &APPEARANCE,
1459        day_localization_ui::res::str::day_settings_theme(),
1460        [
1461            (
1462                Appearance::Light,
1463                day_localization_ui::res::str::day_theme_light(),
1464            ),
1465            (
1466                Appearance::Dark,
1467                day_localization_ui::res::str::day_theme_dark(),
1468            ),
1469            (
1470                Appearance::System,
1471                day_localization_ui::res::str::day_theme_system(),
1472            ),
1473        ],
1474    )
1475    .segmented()
1476    .id(day_core::id!(theme_picker))
1477    .requires(Cap::Appearance)
1478}
1479
1480/// The language row alone (id `language-picker`).
1481pub fn language_row(locales: LocaleTable) -> Row {
1482    wire_general();
1483    let mut options: Vec<(String, TextSource)> = vec![(
1484        String::new(),
1485        day_localization_ui::res::str::day_theme_system().into_text(),
1486    )];
1487    options.extend(
1488        locales
1489            .iter()
1490            .map(|(tag, name)| ((*tag).to_string(), TextSource::Static((*name).to_string()))),
1491    );
1492    choice_text(
1493        &LANGUAGE,
1494        day_localization_ui::res::str::day_settings_language(),
1495        options,
1496    )
1497    .id(day_core::id!(language_picker))
1498}
1499
1500/// [`choice`] over already-resolved label sources (what [`language_row`] builds from a
1501/// locale table).
1502fn choice_text<T: PrefValue, M>(
1503    pref: &'static Pref<T>,
1504    title: impl IntoText<M>,
1505    options: Vec<(T, TextSource)>,
1506) -> Row {
1507    rows::choice(
1508        pref,
1509        title,
1510        options.into_iter().map(|(v, l)| (v, Resolved(l))),
1511    )
1512}
1513
1514/// An `IntoText` adapter over a `TextSource` (the sources module offers no direct impl).
1515struct Resolved(TextSource);
1516struct ResolvedMark;
1517impl IntoText<ResolvedMark> for Resolved {
1518    fn into_text(self) -> TextSource {
1519        self.0
1520    }
1521}
1522
1523// ===========================================================================
1524// Composed presentation
1525// ===========================================================================
1526
1527/// The route type of the navigation presentation's stack: pushed pages are groups, About, a
1528/// row's sub-page or a choice list.
1529#[derive(Clone, PartialEq, Debug)]
1530pub enum SettingsRoute {
1531    About,
1532    Group(String),
1533}
1534
1535impl Route for SettingsRoute {
1536    fn key(&self) -> String {
1537        match self {
1538            SettingsRoute::About => "about".into(),
1539            SettingsRoute::Group(g) => g.clone(),
1540        }
1541    }
1542    fn from_key(key: &str) -> Option<Self> {
1543        Some(match key {
1544            "about" => SettingsRoute::About,
1545            g => SettingsRoute::Group(g.to_string()),
1546        })
1547    }
1548    /// Tracked, so a shown page's bar follows a language change (`nav_stack` re-reads it).
1549    fn title(&self) -> String {
1550        match self {
1551            SettingsRoute::About => day_localization::t(day_localization::key::day_about),
1552            // A row's sub-page goes by its title (`push_subpage`); its key carries a prefix.
1553            SettingsRoute::Group(g) => match g.strip_prefix("page:") {
1554                Some(title) => title.to_string(),
1555                None => installed()
1556                    .and_then(|i| i.group(g).map(|g| resolve_text(&g.title)))
1557                    .unwrap_or_else(|| g.clone()),
1558            },
1559        }
1560    }
1561}
1562
1563fn text_label(t: &TextSource) -> Label {
1564    match t {
1565        TextSource::Static(s) => label(s.clone()),
1566        TextSource::Dyn(f) => {
1567            let f = f.clone();
1568            label(move || f())
1569        }
1570    }
1571}
1572
1573/// A text source as a closure a label or a control re-reads: tracked, so a localized source
1574/// (`tr(..)`, a generated accessor) relabels when the locale changes, and a signal-backed
1575/// one when the signal does.
1576fn text_source_fn(t: &TextSource) -> impl Fn() -> String + 'static {
1577    let t = t.clone();
1578    move || resolve_text(&t)
1579}
1580
1581/// Resolve a text source, tracked (see [`text_source_fn`]).
1582pub(crate) fn resolve_text(t: &TextSource) -> String {
1583    match t {
1584        TextSource::Static(s) => s.clone(),
1585        TextSource::Dyn(f) => f(),
1586    }
1587}
1588
1589/// A choice row's picker, the same on every presentation: the option titles are the row's
1590/// text sources (so they re-resolve on locale change), bound to the row's index, and the
1591/// row's enabled gate reaches the control. Every arm builds its picker here, so the two
1592/// behaviors cannot drift between the composed rows and a native row's suffix control.
1593pub(crate) fn choice_picker(
1594    labels: &[TextSource],
1595    index: Signal<usize>,
1596    segmented: bool,
1597    enabled: impl Fn() -> bool + 'static,
1598) -> day_pieces::Picker<usize, day_pieces::Required<Signal<usize>>> {
1599    let options: Vec<(usize, TextSource)> = labels.iter().cloned().enumerate().collect();
1600    let mut p = picker(index, options).enabled(enabled);
1601    if segmented {
1602        p = p.segmented();
1603    }
1604    p
1605}
1606
1607/// A stepper row's two buttons, the same on every presentation: each steps the value within
1608/// the bounds, and each is enabled only while the row's gate holds AND the bound leaves room.
1609/// A native row's disabled styling never reaches its child buttons, so the gate is applied to
1610/// the buttons themselves here.
1611pub(crate) fn stepper_buttons(
1612    v: Signal<f64>,
1613    range: &std::ops::RangeInclusive<f64>,
1614    step: f64,
1615    enabled: impl Fn() -> bool + Clone + 'static,
1616) -> (day_pieces::Button, day_pieces::Button) {
1617    let (lo, hi, st) = (*range.start(), *range.end(), step);
1618    let enabled_inc = enabled.clone();
1619    let dec = button("−")
1620        .action(move || v.set((v.get_untracked() - st).max(lo)))
1621        .enabled(move || enabled() && v.get() > lo);
1622    let inc = button("+")
1623        .action(move || v.set((v.get_untracked() + st).min(hi)))
1624        .enabled(move || enabled_inc() && v.get() < hi);
1625    (dec, inc)
1626}
1627
1628/// The same script targets on every settings presentation: the id names the value label,
1629/// and its two buttons have stable suffixes. Keep these on the controls, not their row.
1630pub(crate) fn stepper_control(
1631    value: Signal<f64>,
1632    dec: day_pieces::Button,
1633    inc: day_pieces::Button,
1634    id: Option<&day_core::ElementId>,
1635) -> AnyPiece {
1636    let value_label = label(move || format!("{}", value.get() as i64)).tabular();
1637    match id {
1638        Some(id) => row((
1639            dec.id(day_core::id!(pref_decrement, id.as_str())),
1640            value_label.id(id.clone()),
1641            inc.id(day_core::id!(pref_increment, id.as_str())),
1642        ))
1643        .spacing(8.0)
1644        .align(VAlign::Center)
1645        .any(),
1646        None => row((dec, value_label, inc))
1647            .spacing(8.0)
1648            .align(VAlign::Center)
1649            .any(),
1650    }
1651}
1652
1653/// The desktop window: a sidebar of groups beside the selected page (one group: the page
1654/// alone). A toolkit feature replaces this with its native panel.
1655fn window_shell(inst: Rc<Installed>) -> AnyPiece {
1656    #[cfg(all(feature = "appkit", target_os = "macos"))]
1657    {
1658        if let Some(p) = appkit_impl::window_shell(inst.clone()) {
1659            return p;
1660        }
1661    }
1662    #[cfg(feature = "gtk")]
1663    {
1664        if let Some(p) = gtk_impl::window_shell(inst.clone()) {
1665            return p;
1666        }
1667    }
1668    #[cfg(feature = "qt")]
1669    {
1670        if let Some(p) = qt_impl::window_shell(inst.clone()) {
1671            return p;
1672        }
1673    }
1674    composed_window_shell(inst)
1675}
1676
1677#[expect(
1678    clippy::needless_pass_by_value,
1679    reason = "every settings builder, per-toolkit ones included, takes the shared `Rc` by value"
1680)]
1681fn composed_window_shell(inst: Rc<Installed>) -> AnyPiece {
1682    let groups = inst.visible_groups();
1683    if groups.len() <= 1 {
1684        return match groups.first() {
1685            Some(g) => group_page(inst.clone(), g, true),
1686            None => column(()).any(),
1687        };
1688    }
1689    if inst.selected.get_untracked().is_empty() {
1690        inst.selected.set(groups[0].id.to_string());
1691    }
1692    let mut nav = nav(inst.selected)
1693        .style(NavStyle::Sidebar)
1694        .local()
1695        .id(day_core::id!(prefs_nav));
1696    for g in groups {
1697        let id = g.id;
1698        let title = text_source_fn(&g.title);
1699        let inst2 = inst.clone();
1700        let build = move || {
1701            let inst = inst2.clone();
1702            match inst.group(id) {
1703                Some(g) => group_page(inst.clone(), g, true),
1704                None => column(()).any(),
1705            }
1706        };
1707        nav = match &g.icon {
1708            Some(GroupIcon::Image(name)) => {
1709                nav.items(item(id, title).icon(name.clone()).page(build))
1710            }
1711            _ => nav.item(id, title, build),
1712        };
1713    }
1714    let nav = nav.any();
1715    #[cfg(all(feature = "xaml", target_os = "windows"))]
1716    let nav = xaml_impl::sidebar_symbols(nav, &inst.visible_groups());
1717    nav
1718}
1719
1720/// A group's page: its sections as a form, then its custom piece.
1721fn group_page(inst: Rc<Installed>, g: &Group, desktop: bool) -> AnyPiece {
1722    // The phones draw a group as their own grouped table (a `UITableView` in the inset
1723    // grouped style, a Material preference list) when the arm provides one.
1724    if !desktop {
1725        #[cfg(all(feature = "uikit", target_os = "ios"))]
1726        {
1727            if let Some(p) = uikit_impl::group_page(inst.clone(), g) {
1728                return p;
1729            }
1730        }
1731        #[cfg(all(feature = "material", target_os = "android"))]
1732        {
1733            if let Some(p) = android_impl::group_page(inst.clone(), g) {
1734                return p;
1735            }
1736        }
1737        #[cfg(all(feature = "arkui", target_env = "ohos"))]
1738        {
1739            if let Some(p) = arkui_impl::group_page(inst.clone(), g) {
1740                return p;
1741            }
1742        }
1743    }
1744    composed_group_page(inst, g, desktop)
1745}
1746
1747/// One group's sections with no scroll of their own (see [`Prefs::group_body`]). The phones'
1748/// native pages size themselves to their rows inside a Day `scroll`.
1749fn group_body(inst: Rc<Installed>, g: &Group) -> AnyPiece {
1750    #[cfg(all(feature = "uikit", target_os = "ios"))]
1751    {
1752        if let Some(p) = uikit_impl::group_body(inst.clone(), g) {
1753            return p;
1754        }
1755    }
1756    #[cfg(all(feature = "material", target_os = "android"))]
1757    {
1758        if let Some(p) = android_impl::group_body(inst.clone(), g) {
1759            return p;
1760        }
1761    }
1762    #[cfg(all(feature = "arkui", target_env = "ohos"))]
1763    {
1764        if let Some(p) = arkui_impl::group_body(inst.clone(), g) {
1765            return p;
1766        }
1767    }
1768    column((composed_group_form(inst, g, false),))
1769        .align(HAlign::Leading)
1770        .padding(16.0)
1771        .grow(Dimension::Width)
1772        .any()
1773}
1774
1775/// A group's sections as a form, then its custom piece.
1776#[expect(
1777    clippy::needless_pass_by_value,
1778    reason = "every settings builder, per-toolkit ones included, takes the shared `Rc` by value"
1779)]
1780fn composed_group_form(inst: Rc<Installed>, g: &Group, desktop: bool) -> AnyPiece {
1781    let mut parts: Vec<AnyPiece> = Vec::new();
1782    for s in &g.sections {
1783        if let Some(p) = section_piece(inst.clone(), s, desktop) {
1784            parts.push(p);
1785        }
1786    }
1787    if let Some(custom) = &g.custom {
1788        parts.push(custom());
1789    }
1790    form(parts).id(day_core::id!(prefs_group, g.id)).any()
1791}
1792
1793/// A group's page from ordinary Day pieces: its sections as a form, then its custom piece.
1794fn composed_group_page(inst: Rc<Installed>, g: &Group, desktop: bool) -> AnyPiece {
1795    let body = composed_group_form(inst, g, desktop);
1796    // A desktop panel fits its page (`size_to_fit`), so the page measures its content; past
1797    // the height the window can give it (a long page, a large text size) it scrolls.
1798    if desktop {
1799        hugging_scroll(
1800            column((body,))
1801                .align(HAlign::Leading)
1802                .padding(20.0)
1803                .grow(Dimension::Width),
1804        )
1805        .any()
1806    } else {
1807        scroll(
1808            column((body,))
1809                .align(HAlign::Leading)
1810                .padding(16.0)
1811                .grow(Dimension::Width),
1812        )
1813        .any()
1814    }
1815}
1816
1817#[expect(
1818    clippy::needless_pass_by_value,
1819    reason = "every settings builder, per-toolkit ones included, takes the shared `Rc` by value"
1820)]
1821fn section_piece(inst: Rc<Installed>, s: &Section, desktop: bool) -> Option<AnyPiece> {
1822    let rows: Vec<AnyPiece> = s
1823        .rows
1824        .iter()
1825        .filter(|r| r.is_available())
1826        .map(|r| row_piece(inst.clone(), r, desktop))
1827        .collect();
1828    if rows.is_empty() {
1829        return None;
1830    }
1831    let mut sec = section(rows);
1832    if let Some(t) = &s.title {
1833        sec = sec.title(text_source_fn(t));
1834    }
1835    if let Some(f) = &s.footer {
1836        sec = sec.footer(text_source_fn(f));
1837    }
1838    Some(sec.any())
1839}
1840
1841/// One composed row: title (and caption) leading, the control trailing, the System Settings
1842/// / iOS Settings shape every platform reads. A toolkit feature replaces it with its native row.
1843fn row_piece(inst: Rc<Installed>, r: &Row, desktop: bool) -> AnyPiece {
1844    #[cfg(feature = "gtk")]
1845    {
1846        if let Some(p) = gtk_impl::row_piece(inst.clone(), r, desktop) {
1847            return p;
1848        }
1849    }
1850    #[cfg(all(feature = "uikit", target_os = "ios"))]
1851    {
1852        if let Some(p) = uikit_impl::row_piece(inst.clone(), r, desktop) {
1853            return p;
1854        }
1855    }
1856    #[cfg(all(feature = "material", target_os = "android"))]
1857    {
1858        if let Some(p) = android_impl::row_piece(inst.clone(), r, desktop) {
1859            return p;
1860        }
1861    }
1862    #[cfg(all(feature = "xaml", target_os = "windows"))]
1863    {
1864        if let Some(p) = xaml_impl::row_piece(inst.clone(), r, desktop) {
1865            return p;
1866        }
1867    }
1868    #[cfg(all(feature = "arkui", target_env = "ohos"))]
1869    {
1870        if let Some(p) = arkui_impl::row_piece(inst.clone(), r, desktop) {
1871            return p;
1872        }
1873    }
1874    composed_row(inst, r, desktop)
1875}
1876
1877/// The title column of a row: the title, and the caption under it in the footnote style.
1878fn title_column(r: &Row) -> AnyPiece {
1879    let title = text_label(&r.title);
1880    match &r.caption {
1881        Some(c) => column((
1882            title,
1883            text_label(c).font(day_spec::Font::Footnote).secondary(),
1884        ))
1885        .spacing(2.0)
1886        .align(HAlign::Leading)
1887        .any(),
1888        None => title.any(),
1889    }
1890}
1891
1892/// Title leading, control trailing, on one line; a stretching control (a text field) takes
1893/// the row's remaining width.
1894fn trailing_row(titles: AnyPiece, control: AnyPiece) -> AnyPiece {
1895    // The title column wraps past a readable width rather than widening into the control:
1896    // a long caption would otherwise push a popup off the panel's edge.
1897    row((titles.max_width(TITLE_COLUMN_MAX), spacer(), control))
1898        .spacing(12.0)
1899        .align(VAlign::Center)
1900        .grow(Dimension::Width)
1901        .any()
1902}
1903
1904/// The widest a composed row's title column grows before its caption wraps.
1905const TITLE_COLUMN_MAX: f64 = 360.0;
1906/// A composed slider's width, the same on every row so a page of sliders aligns.
1907const SLIDER_WIDTH: f64 = 200.0;
1908/// The value column beside a composed slider: room for "1000%", trailing-aligned.
1909const VALUE_WIDTH: f64 = 52.0;
1910
1911fn composed_row(inst: Rc<Installed>, r: &Row, _desktop: bool) -> AnyPiece {
1912    let id = r.id.clone();
1913    let enabled = r.enabled.clone();
1914    let with_id = |p: AnyPiece| match &id {
1915        Some(id) => p.id(id.clone()).any(),
1916        None => p,
1917    };
1918    let enabled_fn = move || enabled.as_ref().is_none_or(day_pieces::Reactive::get);
1919    match &r.kind {
1920        RowKind::Toggle(sig) => {
1921            let ctl = with_id(toggle(*sig).enabled(enabled_fn).any());
1922            trailing_row(title_column(r), ctl)
1923        }
1924        RowKind::Choice {
1925            labels,
1926            index,
1927            style,
1928        } => {
1929            let p = choice_picker(labels, *index, *style == ChoiceStyle::Segmented, enabled_fn);
1930            trailing_row(title_column(r), with_id(p.any()))
1931        }
1932        RowKind::Slider {
1933            value,
1934            range,
1935            step,
1936            value_text,
1937        } => {
1938            let mut s = slider(*value).range(range.clone()).enabled(enabled_fn);
1939            if let Some(st) = step {
1940                s = s.step(*st);
1941            }
1942            // The id goes on the control itself, before the layout modifiers wrap it. The
1943            // slider takes one fixed width on every row, so a page of sliders lines up at
1944            // both ends however long each row's title is (System Settings does the same);
1945            // only a row too narrow for it stacks the control under the title.
1946            let ctl = match &id {
1947                Some(i) => s
1948                    .id(i.clone())
1949                    .min_width(SLIDER_WIDTH)
1950                    .max_width(SLIDER_WIDTH)
1951                    .any(),
1952                None => s.min_width(SLIDER_WIDTH).max_width(SLIDER_WIDTH).any(),
1953            };
1954            let ctl = match value_text {
1955                Some(f) => {
1956                    let f = f.clone();
1957                    let v = *value;
1958                    // One line, trailing-aligned in a fixed column so the values line up
1959                    // whatever their length; id `<id>-value` for scripts.
1960                    let value_label = label(move || f(v.get()))
1961                        .tabular()
1962                        .secondary()
1963                        .single_line()
1964                        .align(day_spec::props::TextAlign::Trailing);
1965                    let value_label = match &id {
1966                        Some(i) => value_label
1967                            .id(day_core::id!(pref_value, i.as_str()))
1968                            .min_width(VALUE_WIDTH)
1969                            .max_width(VALUE_WIDTH)
1970                            .any(),
1971                        None => value_label
1972                            .min_width(VALUE_WIDTH)
1973                            .max_width(VALUE_WIDTH)
1974                            .any(),
1975                    };
1976                    row((ctl, value_label))
1977                        .spacing(8.0)
1978                        .align(VAlign::Center)
1979                        .any()
1980                }
1981                None => ctl,
1982            };
1983            trailing_row(title_column(r), ctl)
1984        }
1985        RowKind::Stepper { value, range, step } => {
1986            let v = *value;
1987            let (dec, inc) = stepper_buttons(v, range, *step, enabled_fn);
1988            let ctl = stepper_control(v, dec, inc, id.as_ref());
1989            trailing_row(title_column(r), ctl)
1990        }
1991        RowKind::Text {
1992            value,
1993            placeholder,
1994            secure,
1995        } => {
1996            let mut f = if *secure {
1997                secure_field(*value)
1998            } else {
1999                text_field(*value)
2000            };
2001            if let Some(ph) = placeholder {
2002                f = f.placeholder(text_source_fn(ph));
2003            }
2004            let f = f.enabled(enabled_fn);
2005            let ctl = match &id {
2006                Some(i) => f
2007                    .id(i.clone())
2008                    .grow(Dimension::Width)
2009                    .min_width(160.0)
2010                    .any(),
2011                None => f.grow(Dimension::Width).min_width(160.0).any(),
2012            };
2013            trailing_row(title_column(r), ctl)
2014        }
2015        RowKind::Action {
2016            on,
2017            destructive: _,
2018            confirm,
2019            confirm_label,
2020            busy,
2021        } => {
2022            let on = on.clone();
2023            let title = text_source_fn(&r.title);
2024            let confirm = confirm.clone();
2025            let confirm_label = confirm_label.clone();
2026            let busy = busy.clone();
2027            let run = move || {
2028                let on = on.clone();
2029                match &confirm {
2030                    Some(message) => {
2031                        let message = message.initial();
2032                        let title = title();
2033                        let label = confirm_label.as_ref().map(TextSource::initial);
2034                        day_core::task(async move {
2035                            if crate::confirm_dialog(&title, &message, label).await {
2036                                on();
2037                            }
2038                        });
2039                    }
2040                    None => on(),
2041                }
2042            };
2043            let busy_gate = busy.clone();
2044            let b = button(text_source_fn(&r.title))
2045                .action(run)
2046                .enabled(move || {
2047                    enabled_fn() && !busy_gate.as_ref().is_some_and(day_pieces::Reactive::get)
2048                });
2049            let ctl = with_id(b.any());
2050            let ctl = match busy {
2051                Some(b) => row((when(move || b.get(), spinner), ctl))
2052                    .spacing(8.0)
2053                    .align(VAlign::Center)
2054                    .any(),
2055                None => ctl,
2056            };
2057            // The button carries the title; a caption is the row's explanatory line, so it
2058            // stands alone in the title column rather than repeating the title above it.
2059            match &r.caption {
2060                Some(c) => trailing_row(caption_only(c), ctl),
2061                None => ctl,
2062            }
2063        }
2064        RowKind::Link(url) => {
2065            let url = url.clone();
2066            let l = link(text_source_fn(&r.title), url);
2067            match &r.caption {
2068                Some(c) => trailing_row(caption_only(c), with_id(l.any())),
2069                None => with_id(l.any()),
2070            }
2071        }
2072        RowKind::Navigate(build) => {
2073            let build = build.clone();
2074            let title = text_source_fn(&r.title);
2075            let open = move || {
2076                let build = build.clone();
2077                let title = title();
2078                push_subpage(inst.clone(), title, build);
2079            };
2080            with_id(
2081                row((title_column(r), spacer(), label("›").secondary()))
2082                    .spacing(12.0)
2083                    .align(VAlign::Center)
2084                    .grow(Dimension::Width)
2085                    .on_tap(open)
2086                    .any(),
2087            )
2088        }
2089        RowKind::Info { value, copyable } => {
2090            let v = text_label(value).secondary();
2091            let v = if *copyable {
2092                // A visible affordance: the value plus a plain copy button.
2093                let text = value.clone();
2094                row((
2095                    v,
2096                    button("")
2097                        .icon(day_spec::Symbol::Copy)
2098                        .icon_only()
2099                        .plain()
2100                        .action(move || {
2101                            let _ = day_part_clipboard::set_text(&text.initial());
2102                        }),
2103                ))
2104                .spacing(4.0)
2105                .align(VAlign::Center)
2106                .any()
2107            } else {
2108                v.any()
2109            };
2110            trailing_row(title_column(r), with_id(v))
2111        }
2112        RowKind::Note => with_id(
2113            text_label(&r.title)
2114                .font(day_spec::Font::Footnote)
2115                .secondary()
2116                .any(),
2117        ),
2118        RowKind::Custom(build) => with_id(build()),
2119    }
2120}
2121
2122/// Push a row's sub-page: onto the navigation presentation's stack when inside one, else into
2123/// a cover.
2124#[expect(
2125    clippy::needless_pass_by_value,
2126    reason = "every settings builder, per-toolkit ones included, takes the shared `Rc` by value"
2127)]
2128fn push_subpage(inst: Rc<Installed>, title: String, build: Build) {
2129    SUBPAGES.with(|s| s.borrow_mut().insert(title.clone(), build.clone()));
2130    #[cfg(feature = "gtk")]
2131    {
2132        // Into the open preferences dialog, as one of its own sub-pages.
2133        if gtk_impl::push_subpage(inst.clone(), title.clone(), build.clone()) {
2134            return;
2135        }
2136    }
2137    if inst.presentation == Presentation::Navigation {
2138        inst.path
2139            .update(|p| p.push(SettingsRoute::Group(format!("page:{title}"))));
2140    } else {
2141        day_core::open_window(
2142            day_spec::WindowOptions::default()
2143                .key(format!("day.settings.{title}"))
2144                .title(title)
2145                .size(480.0, 560.0)
2146                .size_to_fit()
2147                .kind(day_spec::WindowKind::Preferences),
2148            move || build(),
2149        );
2150    }
2151}
2152
2153async fn confirm_dialog(title: &str, message: &str, label: Option<String>) -> bool {
2154    let dialog = confirm(title.to_string())
2155        .message(message.to_string())
2156        .destructive();
2157    match label {
2158        Some(l) => dialog.confirm_label(l).await,
2159        None => dialog.await,
2160    }
2161}
2162
2163/// A row's caption alone, for rows whose control already shows the title (a button, a link).
2164fn caption_only(c: &TextSource) -> AnyPiece {
2165    text_label(c)
2166        .font(day_spec::Font::Footnote)
2167        .secondary()
2168        .any()
2169}
2170
2171/// The navigation presentation: a stack whose root lists About and the groups.
2172fn navigation_shell(inst: Rc<Installed>) -> AnyPiece {
2173    navigation_stack(inst, false)
2174}
2175
2176/// The same inside a cover: a Done button closes it.
2177fn navigation_shell_with_done(inst: Rc<Installed>) -> AnyPiece {
2178    navigation_stack(inst, true)
2179}
2180
2181#[expect(
2182    clippy::needless_pass_by_value,
2183    reason = "every settings builder, per-toolkit ones included, takes the shared `Rc` by value"
2184)]
2185fn navigation_stack(inst: Rc<Installed>, done: bool) -> AnyPiece {
2186    let root_inst = inst.clone();
2187    let dest_inst = inst.clone();
2188    let mut stack = nav_stack(inst.path, root_page(root_inst))
2189        .title(text_source_fn(&inst.title))
2190        .destination(move |r: &SettingsRoute| destination(dest_inst.clone(), r));
2191    if done {
2192        stack = stack.toolbar(
2193            toolbar_button(
2194                day_core::id!(settings_done),
2195                day_localization_ui::res::str::day_settings_done(),
2196            )
2197            .action(|| {
2198                if let Some(w) = day_core::window_by_key(day_core::windows::PREFERENCES_KEY) {
2199                    w.close();
2200                }
2201            })
2202            // The cover's way out, on the bar on every platform: without an icon, an Automatic
2203            // item folds into Android's overflow menu.
2204            .placement(day_spec::ToolbarPlacement::Primary),
2205        );
2206    }
2207    stack.id(day_core::id!(settings_stack)).any()
2208}
2209
2210fn destination(inst: Rc<Installed>, r: &SettingsRoute) -> AnyPiece {
2211    match r {
2212        SettingsRoute::About => about_page(inst),
2213        SettingsRoute::Group(g) => {
2214            if let Some(title) = g.strip_prefix("page:") {
2215                return SUBPAGES
2216                    .with(|s| s.borrow().get(title).cloned())
2217                    .map_or_else(|| column(()).any(), |b| b());
2218            }
2219            match inst.group(g) {
2220                Some(group) => group_page(inst.clone(), group, false),
2221                None => column(()).any(),
2222            }
2223        }
2224    }
2225}
2226
2227/// The mobile root page: the About header card, then the groups as chevron rows (one group:
2228/// its rows inline under the header).
2229/// One row of the mobile root list, for a toolkit arm that draws the list natively: a group
2230/// (or the About header) with what the row shows and what tapping it does.
2231// Consumed by the uikit/android/arkui arms, which only compile for their targets.
2232#[allow(dead_code)]
2233pub(crate) struct RootEntry {
2234    /// The group id (`"about"` for the About header), also the row's element id suffix.
2235    pub id: String,
2236    pub title: TextSource,
2237    pub subtitle: Option<TextSource>,
2238    pub icon: Option<GroupIcon>,
2239    /// Push the entry's page onto the settings stack.
2240    pub open: Rc<dyn Fn()>,
2241}
2242
2243/// The root list's entries in order: the About header first (when an About is declared),
2244/// then every visible group.
2245#[allow(dead_code)]
2246pub(crate) fn root_entries(inst: &Rc<Installed>) -> (Option<RootEntry>, Vec<RootEntry>) {
2247    let path = inst.path;
2248    let about = inst.about.as_ref().map(|about| RootEntry {
2249        id: "about".into(),
2250        title: TextSource::Static(about.display_name()),
2251        subtitle: about.version_line().map(TextSource::Static),
2252        icon: about.icon_name().cloned().map(GroupIcon::Image),
2253        open: Rc::new(move || path.update(|p| p.push(SettingsRoute::About))),
2254    });
2255    let groups = inst
2256        .visible_groups()
2257        .into_iter()
2258        .map(|g| {
2259            let id = g.id;
2260            RootEntry {
2261                id: id.to_string(),
2262                title: g.title.clone(),
2263                subtitle: g.subtitle.clone(),
2264                icon: g.icon.clone(),
2265                open: Rc::new(move || {
2266                    path.update(|p| p.push(SettingsRoute::Group(id.to_string())));
2267                }),
2268            }
2269        })
2270        .collect();
2271    (about, groups)
2272}
2273
2274/// The mobile root page: the arm's native grouped list where one exists, else composed.
2275fn root_page(inst: Rc<Installed>) -> AnyPiece {
2276    #[cfg(all(feature = "uikit", target_os = "ios"))]
2277    {
2278        if let Some(p) = uikit_impl::root_page(inst.clone()) {
2279            return p;
2280        }
2281    }
2282    #[cfg(all(feature = "material", target_os = "android"))]
2283    {
2284        if let Some(p) = android_impl::root_page(inst.clone()) {
2285            return p;
2286        }
2287    }
2288    #[cfg(all(feature = "arkui", target_env = "ohos"))]
2289    {
2290        if let Some(p) = arkui_impl::root_page(inst.clone()) {
2291            return p;
2292        }
2293    }
2294    composed_root_page(inst)
2295}
2296
2297/// The mobile root page from ordinary Day pieces: the About header card, then the groups as
2298/// chevron rows (one group: its rows inline under the header).
2299#[expect(
2300    clippy::needless_pass_by_value,
2301    reason = "every settings builder, per-toolkit ones included, takes the shared `Rc` by value"
2302)]
2303fn composed_root_page(inst: Rc<Installed>) -> AnyPiece {
2304    let mut parts: Vec<AnyPiece> = Vec::new();
2305    if let Some(about) = &inst.about {
2306        parts.push(about_header(inst.clone(), about));
2307    }
2308    let groups = inst.visible_groups();
2309    if groups.len() == 1 {
2310        let g = groups[0];
2311        for s in &g.sections {
2312            if let Some(p) = section_piece(inst.clone(), s, false) {
2313                parts.push(p);
2314            }
2315        }
2316        if let Some(custom) = &g.custom {
2317            parts.push(custom());
2318        }
2319    } else {
2320        let rows: Vec<AnyPiece> = groups
2321            .iter()
2322            .map(|g| {
2323                let id = g.id;
2324                let path = inst.path;
2325                let titles = match &g.subtitle {
2326                    Some(sub) => column((
2327                        text_label(&g.title),
2328                        text_label(sub).font(day_spec::Font::Footnote).secondary(),
2329                    ))
2330                    .spacing(2.0)
2331                    .align(HAlign::Leading)
2332                    .any(),
2333                    None => text_label(&g.title).any(),
2334                };
2335                // A bundled vector draws as an image; a standard glyph has no image name, so
2336                // it draws as a plain icon-only button that opens the same page (the only piece
2337                // that renders a `Symbol` on every toolkit). No icon: an empty slot keeps the
2338                // titles of iconed and icon-less rows aligned.
2339                // A standard glyph draws from day-spec's shared outline as a template image
2340                // (an icon-only button would bring the toolkit's button chrome with it: on
2341                // the web a pill that squashed the glyph). No icon: an empty slot keeps the
2342                // titles of iconed and icon-less rows aligned.
2343                let leading = match &g.icon {
2344                    Some(GroupIcon::Image(name)) => {
2345                        image(name.clone()).template().frame(24.0, 24.0).any()
2346                    }
2347                    Some(GroupIcon::Symbol(sym)) => match sym.outline_svg() {
2348                        Some(svg) => image(svg.into_bytes()).template().frame(24.0, 24.0).any(),
2349                        None => spacer().frame(24.0, 24.0).any(),
2350                    },
2351                    None => spacer().frame(24.0, 24.0).any(),
2352                };
2353                row((leading, titles, spacer(), label("›").secondary()))
2354                    .spacing(12.0)
2355                    .align(VAlign::Center)
2356                    .grow(Dimension::Width)
2357                    .on_tap(move || path.update(|p| p.push(SettingsRoute::Group(id.to_string()))))
2358                    .id(day_core::id!(prefs_group, id))
2359                    .any()
2360            })
2361            .collect();
2362        parts.push(section(rows).any());
2363    }
2364    scroll(
2365        form(parts)
2366            .padding(16.0)
2367            .grow(Dimension::Width)
2368            .id(day_core::id!(settings_root)),
2369    )
2370    .any()
2371}
2372
2373/// The About header card on the mobile root: icon, name, version; tapping opens the About page.
2374#[expect(
2375    clippy::needless_pass_by_value,
2376    reason = "every settings builder, per-toolkit ones included, takes the shared `Rc` by value"
2377)]
2378fn about_header(inst: Rc<Installed>, about: &About) -> AnyPiece {
2379    let path = inst.path;
2380    let name = about.display_name();
2381    let version = about.version_line().unwrap_or_default();
2382    let icon = match about.icon_name() {
2383        Some(n) => image(n.clone()).frame(48.0, 48.0).corner_radius(10.0).any(),
2384        None => column(()).any(),
2385    };
2386    section((row((
2387        icon,
2388        column((
2389            label(name).bold(),
2390            label(version).font(day_spec::Font::Footnote).secondary(),
2391        ))
2392        .spacing(2.0)
2393        .align(HAlign::Leading),
2394        spacer(),
2395        label("›").secondary(),
2396    ))
2397    .spacing(12.0)
2398    .align(VAlign::Center)
2399    .grow(Dimension::Width)
2400    .on_tap(move || path.update(|p| p.push(SettingsRoute::About)))
2401    .id(day_core::id!(settings_about)),))
2402    .any()
2403}
2404
2405/// The composed About page: icon, name, version, tagline, links, credits, licenses, copyright.
2406#[expect(
2407    clippy::needless_pass_by_value,
2408    reason = "every settings builder, per-toolkit ones included, takes the shared `Rc` by value"
2409)]
2410fn about_page(inst: Rc<Installed>) -> AnyPiece {
2411    let Some(about) = &inst.about else {
2412        return column(()).any();
2413    };
2414    if let Some(custom) = about.custom_piece() {
2415        return custom;
2416    }
2417    if inst.presentation == Presentation::Navigation {
2418        #[cfg(all(feature = "uikit", target_os = "ios"))]
2419        {
2420            if let Some(p) = uikit_impl::about_page(inst.clone()) {
2421                return p;
2422            }
2423        }
2424        #[cfg(all(feature = "material", target_os = "android"))]
2425        {
2426            if let Some(p) = android_impl::about_page(inst.clone()) {
2427                return p;
2428            }
2429        }
2430    }
2431    let mut head: Vec<AnyPiece> = Vec::new();
2432    if let Some(n) = about.icon_name() {
2433        head.push(image(n.clone()).frame(96.0, 96.0).corner_radius(20.0).any());
2434    }
2435    head.push(
2436        label(about.display_name())
2437            .font(day_spec::Font::Title2)
2438            .bold()
2439            .id(day_core::id!(about_name))
2440            .any(),
2441    );
2442    if let Some(v) = about.version_line() {
2443        head.push(label(v).secondary().id(day_core::id!(about_version)).any());
2444    }
2445    if let Some(t) = about.tagline_text() {
2446        head.push(label(t).id(day_core::id!(about_tagline)).any());
2447    }
2448    let mut parts: Vec<AnyPiece> = vec![
2449        column(head)
2450            .spacing(6.0)
2451            .align(HAlign::Center)
2452            .grow(Dimension::Width)
2453            .any(),
2454    ];
2455    // Ids by position (`about-link-0`, …) and `about-privacy`: what a walkthrough asserts.
2456    let mut links: Vec<AnyPiece> = about
2457        .links()
2458        .iter()
2459        .enumerate()
2460        .map(|(i, (t, url))| {
2461            link(text_source_fn(t), url.clone())
2462                .id(day_core::id!(about_link, i))
2463                .any()
2464        })
2465        .collect();
2466    if let Some(p) = about.privacy_url() {
2467        links.push(
2468            link(
2469                day_localization_ui::res::str::day_about_privacy(),
2470                p.to_string(),
2471            )
2472            .id(day_core::id!(about_privacy))
2473            .any(),
2474        );
2475    }
2476    if !links.is_empty() {
2477        parts.push(section(links).any());
2478    }
2479    let mut notes: Vec<AnyPiece> = Vec::new();
2480    if let Some(c) = about.credits_text() {
2481        let credits = c.clone();
2482        notes.push(
2483            rows::navigate(
2484                day_localization_ui::res::str::day_about_acknowledgements(),
2485                move || scroll(label(credits.clone()).padding(16.0)),
2486            )
2487            .into_piece(inst.clone()),
2488        );
2489    }
2490    if let Some(l) = about.licenses_text() {
2491        let licenses = l.clone();
2492        notes.push(
2493            rows::navigate(
2494                day_localization_ui::res::str::day_about_licenses(),
2495                move || scroll(label(licenses.clone()).monospace().padding(16.0)),
2496            )
2497            .into_piece(inst.clone()),
2498        );
2499    }
2500    if !notes.is_empty() {
2501        parts.push(section(notes).any());
2502    }
2503    if let Some(c) = about.copyright_text() {
2504        parts.push(
2505            label(c)
2506                .font(day_spec::Font::Footnote)
2507                .secondary()
2508                .id(day_core::id!(about_copyright))
2509                .any(),
2510        );
2511    }
2512    let body = form(parts)
2513        .padding(20.0)
2514        .grow(Dimension::Width)
2515        .id(day_core::id!(about_page));
2516    // The About window fits its content like the settings panel and scrolls past the height
2517    // it can have; a pushed page scrolls.
2518    if inst.presentation == Presentation::Window {
2519        hugging_scroll(body).any()
2520    } else {
2521        scroll(body).any()
2522    }
2523}
2524
2525/// A vertical scroll that hugs its content: it measures as tall as the content up to the
2526/// height it is offered, so a window that fits its content (`size_to_fit`) still shrinks to a
2527/// short page, and a page taller than the window can be scrolls instead of clipping. Day's
2528/// `scroll` takes the whole proposal, which would pin a fitted window at its ceiling.
2529fn hugging_scroll<P: Piece>(child: P) -> impl Piece {
2530    day_core::piece_fn(move |cx: &mut day_core::BuildCx| {
2531        let node = cx.native(
2532            day_spec::kinds::SCROLL,
2533            &day_spec::props::ScrollProps {
2534                horizontal: false,
2535                ..Default::default()
2536            },
2537            Rc::new(HuggingScrollLayout),
2538            day_core::Flex {
2539                grow_w: true,
2540                ..Default::default()
2541            },
2542            day_core::Boundary::Yes,
2543        );
2544        cx.under(node, |cx| {
2545            let _ = child.build(cx);
2546        });
2547        node
2548    })
2549}
2550
2551/// The layout behind [`hugging_scroll`]: `day_core::ScrollLayout` with a content-hugging
2552/// measure.
2553struct HuggingScrollLayout;
2554
2555impl day_core::Layout for HuggingScrollLayout {
2556    fn measure(
2557        &self,
2558        cx: &mut dyn day_core::LayoutOps,
2559        children: &[day_core::RNode],
2560        p: day_spec::Proposal,
2561    ) -> day_spec::Size {
2562        let cs = match children.first() {
2563            Some(&c) => cx.measure_child(c, day_spec::Proposal::new(p.width, None)),
2564            None => day_spec::Size::ZERO,
2565        };
2566        let height = match p.height {
2567            Some(h) => cs.height.min(h),
2568            None => cs.height,
2569        };
2570        day_spec::Size::new(p.width.unwrap_or(cs.width), height)
2571    }
2572    fn place(
2573        &self,
2574        cx: &mut dyn day_core::LayoutOps,
2575        children: &[day_core::RNode],
2576        bounds: day_spec::Rect,
2577    ) {
2578        let Some(&c) = children.first() else {
2579            return;
2580        };
2581        let mut width = bounds.size.width;
2582        let mut cs = cx.measure_child(c, day_spec::Proposal::new(Some(width), None));
2583        if cs.height > bounds.size.height {
2584            // A classic scroll bar takes room from the viewport; lay the content out beside it.
2585            let inset = cx.scroll_bar_inset(true);
2586            if inset > 0.0 {
2587                width = (width - inset).max(0.0);
2588                cs = cx.measure_child(c, day_spec::Proposal::new(Some(width), None));
2589            }
2590        }
2591        let content = day_spec::Size::new(width, cs.height.max(bounds.size.height));
2592        cx.place_child(c, day_spec::Rect::from_size(content));
2593        cx.set_scroll_content(content);
2594    }
2595}
2596
2597impl Row {
2598    /// Build this row as a piece for `inst`'s presentation (what sections do internally).
2599    fn into_piece(self, inst: Rc<Installed>) -> AnyPiece {
2600        let desktop = inst.presentation == Presentation::Window;
2601        row_piece(inst, &self, desktop)
2602    }
2603}
2604
2605// ===========================================================================
2606// Conformance cases (docs/testing.md)
2607// ===========================================================================
2608
2609/// The settings surface's conformance cases.
2610#[cfg(feature = "conformance")]
2611pub mod conformance {
2612    // Synthetic shared store: assertions observe exactly the store the fixture installed.
2613    struct SharedTestStore(std::rc::Rc<super::MemoryStore>);
2614    impl super::Store for SharedTestStore {
2615        fn get(&self, key: &str) -> Option<String> {
2616            self.0.get(key)
2617        }
2618        fn set(&self, key: &str, value: &str) -> bool {
2619            self.0.set(key, value)
2620        }
2621        fn remove(&self, key: &str) -> bool {
2622            self.0.remove(key)
2623        }
2624    }
2625
2626    use day_core::conformance::{Case, Drive};
2627    use day_spec::Cap;
2628
2629    use super::*;
2630
2631    static SOUND: Pref<bool> = Pref::new("conformance.sound", || true);
2632    static SCALE: Pref<f64> = Pref::new("conformance.scale", || 100.0);
2633
2634    /// A real Windows card must reflow its control before its header becomes a column of
2635    /// broken words, while keeping a roomy card horizontal.
2636    #[cfg(all(feature = "xaml", target_os = "windows"))]
2637    #[day_macros::test(day_core)]
2638    fn settings_card_keeps_header_readable() -> Case {
2639        Case::new()
2640            .proves("day-piece-settings.row")
2641            .page(|| {
2642                let inst = Rc::new(Installed {
2643                    in_nav: Default::default(),
2644                    about: None,
2645                    groups: Vec::new(),
2646                    presentation: Presentation::Window,
2647                    title: TextSource::Static("Settings".into()),
2648                    selected: Signal::new(String::new()),
2649                    path: Signal::new(Vec::new()),
2650                });
2651                let narrow = xaml_impl::row_piece(
2652                    inst.clone(),
2653                    &appearance_row().id(day_core::id!(settings::narrow_theme)),
2654                    true,
2655                )
2656                .unwrap();
2657                let wide = xaml_impl::row_piece(
2658                    inst,
2659                    &appearance_row().id(day_core::id!(settings::wide_theme)),
2660                    true,
2661                )
2662                .unwrap();
2663                column((
2664                    narrow.id(day_core::id!(settings::narrow_card)).width(250.0),
2665                    wide.id(day_core::id!(settings::wide_card)).width(520.0),
2666                ))
2667            })
2668            .drive(|d: Drive| async move {
2669                for (card_id, control_id, stacked) in [
2670                    ("settings::narrow_card", "settings::narrow_theme", true),
2671                    ("settings::wide_card", "settings::wide_theme", false),
2672                ] {
2673                    d.assert_frame(card_id, day_core::conformance::FrameExpect {
2674                        width: Some(if stacked { 250.0 } else { 520.0 }),
2675                        ..Default::default()
2676                    }).await?;
2677                    let (card, control) = day_core::with_tree(|t| {
2678                        let card = t
2679                            .read_native(t.find_by_id(card_id).unwrap())
2680                            .unwrap()
2681                            .frame
2682                            .unwrap();
2683                        let control = t
2684                            .read_native(t.find_by_id(control_id).unwrap())
2685                            .unwrap()
2686                            .frame
2687                            .unwrap();
2688                        (card, control)
2689                    });
2690                    let y = control.origin.y - card.origin.y;
2691                    d.check(
2692                        if stacked { y >= 48.0 } else { y < 40.0 },
2693                        "the theme control must move below its header only in a narrow card",
2694                    )?;
2695                    d.check(
2696                        control.origin.x >= card.origin.x + 15.0
2697                            && control.origin.x + control.size.width
2698                                <= card.origin.x + card.size.width - 15.0,
2699                        &format!("the theme control must remain within the card padding: {card:?}, {control:?}"),
2700                    )?;
2701                }
2702                d.select("settings::narrow_theme", 1).await?;
2703                d.check(
2704                    APPEARANCE.get_untracked() == Appearance::Dark,
2705                    "reflowed theme control must remain interactive",
2706                )?;
2707                d.select("settings::narrow_theme", 2).await
2708            })
2709    }
2710
2711    /// Choosing a theme applies it and persists; System clears the stored key again.
2712    #[day_macros::test(day_core)]
2713    fn settings_theme_applies_and_persists() -> Case {
2714        let store = Rc::new(MemoryStore::default());
2715        let page_store = store.clone();
2716        Case::new()
2717            .proves_cap(Cap::Appearance)
2718            .proves_duty("set_appearance")
2719            .requires(Cap::Appearance)
2720            .page(move || {
2721                install_store(SharedTestStore(page_store.clone()));
2722                let inst = Rc::new(Installed {
2723                    in_nav: Cell::default(),
2724                    about: None,
2725                    groups: vec![Group::new("general", "General").row(appearance_row())],
2726                    presentation: Presentation::Window,
2727                    title: TextSource::Static("Settings".into()),
2728                    selected: Signal::new(String::new()),
2729                    path: Signal::new(Vec::new()),
2730                });
2731                let g = inst.groups[0].clone();
2732                column((group_page(inst, &g, true),))
2733            })
2734            .drive(move |d: Drive| {
2735                let store = store.clone();
2736                async move {
2737                    d.select(day_core::id!(theme_picker).as_str(), 1).await?;
2738                    d.wait_idle().await?;
2739                    d.check(
2740                        store.get("day.appearance").as_deref() == Some("dark"),
2741                        "dark not saved",
2742                    )?;
2743                    d.select(day_core::id!(theme_picker).as_str(), 2).await?;
2744                    d.wait_idle().await?;
2745                    d.check(
2746                        store.get("day.appearance").is_none(),
2747                        "System (the default) did not clear the key",
2748                    )
2749                }
2750            })
2751    }
2752
2753    /// A toggle row and a slider row round-trip through the store.
2754    #[day_macros::test(day_core)]
2755    fn settings_rows_persist() -> Case {
2756        let store = Rc::new(MemoryStore::default());
2757        let page_store = store.clone();
2758        Case::new()
2759            .page(move || {
2760                install_store(SharedTestStore(page_store.clone()));
2761                let inst = Rc::new(Installed {
2762                    in_nav: Cell::default(),
2763                    about: None,
2764                    groups: vec![
2765                        Group::new("sound", "Sound")
2766                            .row(rows::toggle(&SOUND, "Sounds"))
2767                            .row(rows::slider(&SCALE, "Scale", 50.0..=200.0).step(10.0)),
2768                    ],
2769                    presentation: Presentation::Window,
2770                    title: TextSource::Static("Settings".into()),
2771                    selected: Signal::new(String::new()),
2772                    path: Signal::new(Vec::new()),
2773                });
2774                let g = inst.groups[0].clone();
2775                column((group_page(inst, &g, true),))
2776            })
2777            .drive(move |d: Drive| {
2778                let store = store.clone();
2779                async move {
2780                    d.toggle(day_core::id!(pref, "conformance.sound").as_str(), false)
2781                        .await?;
2782                    d.wait_idle().await?;
2783                    d.check(!SOUND.get_untracked(), "toggle did not write the pref")?;
2784                    d.check(
2785                        store.get("conformance.sound").as_deref() == Some("false"),
2786                        "toggle did not persist",
2787                    )?;
2788                    d.set_value(day_core::id!(pref, "conformance.scale").as_str(), 150.0)
2789                        .await?;
2790                    d.wait_idle().await?;
2791                    d.check(
2792                        (SCALE.get_untracked() - 150.0).abs() < 0.5,
2793                        "slider did not write the pref",
2794                    )?;
2795                    SOUND.reset();
2796                    d.check(
2797                        store.get("conformance.sound").is_none(),
2798                        "reset did not remove the key",
2799                    )
2800                }
2801            })
2802    }
2803
2804    static COUNT: Pref<i64> = Pref::new("conformance.count", || 3);
2805
2806    /// A row's enabled gate reaches every interactive control the row builds: a stepper's two
2807    /// buttons stay disabled while the gate is off, however the bounds would allow a step.
2808    #[day_macros::test(day_core)]
2809    fn settings_row_enabled_gates_stepper() -> Case {
2810        let gate = Signal::new(false);
2811        Case::new()
2812            .page(move || {
2813                let inst = Rc::new(Installed {
2814                    in_nav: Cell::default(),
2815                    about: None,
2816                    groups: vec![
2817                        Group::new("counts", "Counts")
2818                            .row(rows::stepper(&COUNT, "Count", 0..=10).enabled(gate)),
2819                    ],
2820                    presentation: Presentation::Window,
2821                    title: TextSource::Static("Settings".into()),
2822                    selected: Signal::new(String::new()),
2823                    path: Signal::new(Vec::new()),
2824                });
2825                let g = inst.groups[0].clone();
2826                column((
2827                    group_page(inst, &g, true),
2828                    button("Enable")
2829                        .action(move || gate.set(true))
2830                        .id(day_core::id!(settings::enable)),
2831                ))
2832            })
2833            .drive(|d: Drive| async move {
2834                let count = day_core::id!(pref, "conformance.count");
2835                let increment = day_core::id!(pref_increment, count.as_str());
2836                let decrement = day_core::id!(pref_decrement, count.as_str());
2837                d.assert_enabled(increment.as_str(), false).await?;
2838                d.assert_enabled(decrement.as_str(), false).await?;
2839                d.tap("settings::enable").await?;
2840                d.wait_idle().await?;
2841                d.assert_enabled(increment.as_str(), true).await?;
2842                d.assert_enabled(decrement.as_str(), true).await?;
2843                let initial = COUNT.get_untracked();
2844                d.assert_text(count.as_str(), &initial.to_string()).await?;
2845                d.tap(increment.as_str()).await?;
2846                d.assert_text(count.as_str(), &(initial + 1).to_string())
2847                    .await?;
2848                d.tap(decrement.as_str()).await?;
2849                d.assert_text(count.as_str(), &initial.to_string()).await
2850            })
2851    }
2852}