Contract stubs: craft-ui-patterns

This commit is contained in:
Martin Ball committed 2026-11-18 08:28:04 +00:00
1 parent 10b23c3d55
commit 80b8ea1f67
22 files changed
+329 -79

No files matched your search

+2 -2
View File
@@ -11,8 +11,8 @@ mod panes;
pub use area::{DockArea, DockAreaOutput, InvalidGeometry};
pub use panes::{
PaneArea, PaneAreaOutput, PaneCommands, PaneContent, PaneFrame, PaneFrameOutput, PaneFrameStyle, PanePlace, PaneRequest, PaneSpec, PaneState,
SidePolicy,
PaneArea, PaneAreaOutput, PaneCommands, PaneContent, PaneEdges, PaneFrame, PaneFrameOutput, PaneFrameStyle, PanePlace, PaneRequest, PaneSpec,
PaneState, SidePolicy,
};
pub use switcher::{WorkspaceSwitcher, WorkspaceSwitcherOutput};
pub use words::WorkspaceDialogWords;
@@ -186,6 +186,25 @@ pub struct PaneSpec {
/// `true`: the body is one collection (a layers list, a bin) that owns the scroll. `false`: the pane scrolls its
/// body.
pub collection_body: bool,
/// The edges the pane may dock at; a request for another edge is refused and its commands are left out.
pub edges: PaneEdges,
}
/// A set of dock edges.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PaneEdges(u8);
impl PaneEdges {
/// Every edge, the centre included.
pub const ALL: PaneEdges = PaneEdges(0b1_1111);
/// The four sides, without the centre.
pub const SIDES: PaneEdges = PaneEdges(0b1111);
/// Whether `edge` is in the set.
pub fn contains(self, edge: PaneEdge) -> bool {
let _ = (self, edge);
todo!("ch.C12")
}
}
impl PaneSpec {
@@ -200,6 +219,7 @@ impl PaneSpec {
closable: true,
title_bar: true,
collection_body: false,
edges: PaneEdges::ALL,
}
}
}
@@ -104,6 +104,25 @@ pub enum AboutTab {
Contributors,
/// The credited AI models.
Models,
/// The app's own tab at this position in the app's tabs, shown after Models.
App(u8),
}
/// A tab the app adds after Models: a name for the hosted dialog's `tab` field, a title and a body.
pub struct AboutAppTab {
#[allow(dead_code)] // P3(chrome-w4): ch.C11
name: &'static str,
#[allow(dead_code)] // P3(chrome-w4): ch.C11
title: Label,
#[allow(dead_code)] // P3(chrome-w4): ch.C11
body: Box<dyn FnMut(&mut Ui) + Send>,
}
impl AboutAppTab {
/// A tab named `name` in the hosted dialog's `tab` field, titled `title`, whose content `body` draws.
pub fn new(name: &'static str, title: impl Into<Label>, body: impl FnMut(&mut Ui) + Send + 'static) -> Self {
AboutAppTab { name, title: title.into(), body: Box::new(body) }
}
}
/// What the dialog keeps while it is open, in its container's slot.
@@ -216,17 +235,25 @@ pub struct AboutDialog<'a> {
/// Binds the shown tab to `tab`; the dialog opens on it.
#[prop]
tab: Option<Bind<'a, AboutTab>>,
app_tabs: Option<&'a mut [AboutAppTab]>,
}
impl<'a> AboutDialog<'a> {
/// The dialog over `info` and `credits`, opening on the About tab.
pub fn new(info: &'a AboutInfo, credits: &'a Credits) -> Self {
AboutDialog { info, credits, open: None, tab: None }
AboutDialog { info, credits, open: None, tab: None, app_tabs: None }
}
/// The app's own tabs, shown after Models.
pub fn app_tabs(mut self, tabs: &'a mut [AboutAppTab]) -> Self {
self.app_tabs = Some(tabs);
self
}
/// Shows the dialog.
pub fn show(self, ui: &mut Ui) -> AboutOutput {
let AboutDialog { info, credits, open, tab } = self;
let AboutDialog { info, credits, open, tab, app_tabs } = self;
let _ = app_tabs; // P3(chrome-w4): ch.C11
let env = Env::of(ui);
let words = env.words::<AboutWords>();
let common = env.words::<CommonWords>();
@@ -259,6 +286,7 @@ impl<'a> AboutDialog<'a> {
AboutTab::About => shown.about(ui, &link),
AboutTab::Contributors => shown.contributors(ui, &view, &link),
AboutTab::Models => shown.models(ui),
AboutTab::App(_) => todo!("ch.C11"),
}
});
let picked = view.borrow().tab;
@@ -489,6 +517,7 @@ pub struct HostedAbout {
tab: AboutTab,
link: Option<String>,
open: bool,
app_tabs: Vec<AboutAppTab>,
#[cfg(feature = "testing")]
facts: crate::testing::StoryOutput,
}
@@ -503,11 +532,19 @@ impl HostedAbout {
tab: AboutTab::default(),
link: None,
open: true,
app_tabs: Vec::new(),
#[cfg(feature = "testing")]
facts: crate::testing::StoryOutput::default(),
}
}
/// Adds an app tab after Models.
#[must_use]
pub fn app_tab(mut self, tab: AboutAppTab) -> Self {
self.app_tabs.push(tab);
self
}
/// The tab the dialog opens on.
#[must_use]
pub fn tab(mut self, tab: AboutTab) -> Self {
@@ -527,8 +564,16 @@ const ABOUT_KEY: &str = "help.about";
/// The tabs' names in the hosted dialog's `tab` field.
const TAB_NAMES: [(AboutTab, &str); 3] = [(AboutTab::About, "about"), (AboutTab::Contributors, "contributors"), (AboutTab::Models, "models")];
fn tab_name(tab: AboutTab) -> &'static str {
TAB_NAMES.iter().find(|(known, _)| *known == tab).map_or("about", |(_, name)| *name)
impl HostedAbout {
/// The name of `tab` in the dialog's `tab` field: the app tabs' names as well as the three built in.
fn tab_name(&self, tab: AboutTab) -> &str {
if let AboutTab::App(at) = tab
&& let Some(app) = self.app_tabs.get(usize::from(at))
{
return app.name;
}
TAB_NAMES.iter().find(|(known, _)| *known == tab).map_or("about", |(_, name)| *name)
}
}
impl StackDialog for HostedAbout {
@@ -539,7 +584,7 @@ impl StackDialog for HostedAbout {
}
fn json_fields(&self) -> Option<Value> {
Some(json!({ "tab": tab_name(self.tab) }))
Some(json!({ "tab": self.tab_name(self.tab) }))
}
fn set_json_field(&mut self, _: &egui::Context, field: &str, value: Value) -> Result<(), String> {
@@ -557,9 +602,14 @@ impl StackDialog for HostedAbout {
}
fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option<DialogResult<()>> {
let shown =
AboutDialog { info: &self.info, credits: &self.credits, open: Some(Bind::bound(&mut self.open)), tab: Some(Bind::bound(&mut self.tab)) }
.show(ui);
let shown = AboutDialog {
info: &self.info,
credits: &self.credits,
open: Some(Bind::bound(&mut self.open)),
tab: Some(Bind::bound(&mut self.tab)),
app_tabs: Some(&mut self.app_tabs[..]),
}
.show(ui);
#[cfg(feature = "testing")]
{
self.facts = crate::contract::Outcome::story_facts(&shown);
@@ -277,6 +277,8 @@ pub struct ParamDialog<'a> {
/// The colours the colour rows show in place of their values in this pass, by row key.
#[prop(vis = "pub(crate)")]
preview_colors: Vec<(String, Srgba)>,
/// Where OK files the values instead of closing; replaces `hold`.
held: Option<&'a mut HeldAnswer<DialogFields>>,
}
/// What `ParamDialog::shaped` applies to the built [`Dialog`].
@@ -333,9 +335,17 @@ impl<'a> ParamDialog<'a> {
refusal: None,
centre: None,
preview_colors: Vec::new(),
held: None,
}
}
/// OK files the values in `held` and the dialog stays open; a refusal shows until the values change.
#[allow(dead_code)] // P3(dialogs-w5): dg.F11
pub(crate) fn held(mut self, held: &'a mut HeldAnswer<DialogFields>) -> Self {
self.held = Some(held);
self
}
/// Changes the built [`Dialog`] before it shows, for the `Dialog` settings a form track needs and `ParamDialog`
/// has no setter for (`Dialog::overlay`, say). It runs after the settings `ParamDialog` makes itself.
pub fn shaped(mut self, shape: impl FnOnce(Dialog<'a>) -> Dialog<'a> + 'a) -> Self {
@@ -438,7 +448,9 @@ impl<'a> ParamDialog<'a> {
refusal,
centre,
preview_colors,
held,
} = self;
let _ = held; // P3(dialogs-w5): dg.F11
let preview_label = Env::of(ui).words::<FormDialogWords>().preview.clone();
// The footer `FormDialog` builds for this pass, made the same way, so its `pick` reads `FormOutput::picked`.
let footer = ResetFooter::new(ui, cancel_label.clone(), alt_resets);
@@ -9,7 +9,7 @@ use crate::contract::{Bind, BodyCx, Props as _, Remember as _, Show as _, ShowCo
use crate::runtime::commands::Commands as _;
use crate::runtime::requests::HostAnswer;
use crate::dialog::{Dialog, DialogOutput};
use crate::dialog::{Dialog, DialogOutput, HeldAnswer};
use crate::runtime::env::{Env, Label};
@@ -191,6 +191,8 @@ pub struct FormDialog<'a, V: Value + Default> {
on_reset: Option<OnResetFn<'a>>,
/// The host's opening values: each pass given them keeps them as the values Reset restores.
opening: Option<V>,
/// Where OK files the values instead of closing; a refusal shows until the values change.
held: Option<&'a mut HeldAnswer<V>>,
}
impl<'a, V: Value + Default> FormDialog<'a, V> {
@@ -221,9 +223,17 @@ impl<'a, V: Value + Default> FormDialog<'a, V> {
reset_with: None,
opening: None,
on_reset: None,
held: None,
}
}
/// OK files the values in `held` and the dialog stays open; a refusal shows through `Dialog::refusal` until the
/// values change, and an accepted answer closes it.
pub fn held(mut self, held: &'a mut HeldAnswer<V>) -> Self {
self.held = Some(held);
self
}
/// A dialog that keeps its value in its own memory while it is open.
pub fn own(title: impl Into<Label>) -> Self {
FormDialog { fresh: true, ..FormDialog::new(title, Bind::kept()) }
@@ -393,7 +403,9 @@ impl<'a, V: Value + Default> FormDialog<'a, V> {
reset_with,
on_reset,
opening,
held,
} = self;
let _ = held; // P3(dialogs-w5): dg.F11
let env = Env::of(ui);
let common = env.words::<CommonWords>();
let name: Arc<str> = title.as_str().into();
@@ -96,6 +96,10 @@ pub enum ActionEnabled {
},
/// When the name box holds a name no entry has (Create).
OnNewName,
/// When the name box holds a name `name_check` accepts.
OnValidName,
/// Never: the button is shown disabled.
Never,
}
/// One button of the column, top to bottom.
@@ -285,9 +289,24 @@ pub struct ListManager<'a> {
/// Binds the open state to `open`.
#[prop(name = "opened")]
open: Option<Bind<'a, bool>>,
/// Whether a name is valid, for [`ActionEnabled::OnValidName`].
#[prop]
name_check: Option<fn(&str) -> bool>,
/// The second button's label when it is not Cancel.
#[prop(into)]
cancel_label: Option<Label>,
/// Draws a section under the list.
under: Option<Box<dyn FnMut(&mut Ui) + 'a>>,
}
impl<'a> ListManager<'a> {
/// Draws `content` under the list.
#[must_use]
pub fn under_list(mut self, content: impl FnMut(&mut Ui) + 'a) -> Self {
self.under = Some(Box::new(content));
self
}
/// A list manager titled `title` whose name box is labelled `name_label` ("Macro name:").
pub fn new(
title: impl Into<Label>,
@@ -305,12 +324,16 @@ impl<'a> ListManager<'a> {
searchable: false,
name: None,
open: None,
name_check: None,
cancel_label: None,
under: None,
}
}
/// Shows the dialog.
pub fn show(self, ui: &mut Ui) -> ListManagerOutput {
let ListManager { title, name_label, entries, actions, empty, note, searchable, name, open } = self;
let ListManager { title, name_label, entries, actions, empty, note, searchable, name, open, name_check, cancel_label, under } = self;
let _ = (name_check, cancel_label, under); // P3(dialogs-w5): dg.F13
let env = Env::of(ui);
let words = env.words::<ListManagerWords>();
let common = env.words::<CommonWords>();
@@ -61,8 +61,8 @@ pub use new_document::{
mod about;
pub use about::{
AboutDialog, AboutInfo, AboutLink, AboutOutput, AboutTab, AboutWords, CommitShare, Contributor, ContributorSort, Credits, HostedAbout,
ModelCredit, NameMode,
AboutAppTab, AboutDialog, AboutInfo, AboutLink, AboutOutput, AboutTab, AboutWords, CommitShare, Contributor, ContributorSort, Credits,
HostedAbout, ModelCredit, NameMode,
};
mod color_choice;
@@ -762,6 +762,20 @@ impl Param {
self
}
/// The most characters a [`ParamKind::Text`] row takes: the field limits its input and `accepts` refuses longer text.
#[must_use]
pub fn max_chars(mut self, chars: usize) -> Self {
let _ = (&mut self, chars);
todo!("dg.F17")
}
/// Shows a [`ParamKind::Text`] row's text in the monospace face.
#[must_use]
pub fn mono(mut self) -> Self {
let _ = &mut self;
todo!("dg.F17")
}
/// Hover text for the whole row, label and control, of any kind.
#[must_use]
pub fn tooltip(mut self, text: impl Into<Label>) -> Self {
@@ -140,6 +140,8 @@ pub enum PasswordPurpose {
/// A new password typed twice, with its strength under the first field; OK stays disabled until both match and
/// are not empty.
Set,
/// A new password typed twice; both fields empty is valid and clears the password.
SetOrClear,
}
impl PasswordPurpose {
@@ -265,6 +267,7 @@ impl<'a> PasswordDialog<'a> {
(words.permissions_title.clone(), Some(Label::from(words.permissions_message.fill(&[("name", name.as_str())]))), words.unlock.clone())
}
PasswordPurpose::Set => (words.set_title.clone(), None, common.ok.clone()),
PasswordPurpose::SetOrClear => todo!("dg.F14"),
};
let mut dialog = Dialog::new(title)
.buttons([FooterButton::new(ok, DialogRole::Accept), FooterButton::new(common.cancel.clone(), DialogRole::Cancel)])
@@ -65,6 +65,9 @@ pub struct PathRow<'a> {
/// What Browse asks the host's file service to pick; without it the caller files the request.
#[prop(into)]
pick: Option<PickRequest>,
/// Browse is disabled and this tells why.
#[prop(into)]
browse_reason: Option<Label>,
}
/// The pick the row is waiting for, kept in the row's container while it is shown.
@@ -74,12 +77,13 @@ struct Ticket(Option<PickId>);
impl<'a> PathRow<'a> {
/// A row over the path `value`, its field named `name`.
pub fn new(name: impl Into<Label>, value: Bind<'a, String>) -> Self {
PathRow { name: name.into(), value, button: None, placeholder: None, pick: None }
PathRow { name: name.into(), value, button: None, placeholder: None, pick: None, browse_reason: None }
}
/// Shows the row.
pub fn show(self, ui: &mut Ui) -> PathRowOutput {
let PathRow { name, mut value, button, placeholder, pick } = self;
let PathRow { name, mut value, button, placeholder, pick, browse_reason } = self;
let _ = browse_reason; // P3(dialogs-w5): dg.F16
let button = button.unwrap_or_else(|| Env::of(ui).words::<PathRowWords>().browse.clone());
let mut edit = EditEvents::new();
let mut browse = false;
@@ -168,12 +168,29 @@ pub struct HostedReport {
lines: Vec<String>,
open: bool,
copied: Option<String>,
#[allow(dead_code)] // P3(dialogs-w5): dg.F15
notes: Vec<ReportNote>,
}
impl HostedReport {
/// A report titled `title` with one `summary` line and the `lines`.
pub fn new(title: impl Into<Label>, summary: impl Into<Label>, lines: Vec<String>) -> Self {
HostedReport { id: crate::dialog::dialog_id("report"), title: title.into(), summary: summary.into(), lines, open: true, copied: None }
HostedReport {
id: crate::dialog::dialog_id("report"),
title: title.into(),
summary: summary.into(),
lines,
open: true,
copied: None,
notes: Vec::new(),
}
}
/// Shows `notes` with the report; `json_fields` lists them.
#[must_use]
pub fn notes(mut self, notes: Vec<ReportNote>) -> Self {
self.notes = notes;
self
}
/// The text the Copy button copied since the last call, once. The app puts it on the clipboard.
@@ -206,8 +206,9 @@ impl<'a> CanvasSize<'a> {
}
let growth = (f64::from(now.width) - f64::from(size.width), f64::from(now.height) - f64::from(size.height));
Field::new(words.anchor.clone()).id_salt("anchor").show(ui, |ui, _| {
let picked = ReferencePoint::new(words.anchor.clone(), Bind::given(state.anchor)).growth(growth).show(ui);
if let Some(anchor) = picked.value().copied() {
// P3(dialogs-w12): dg.F30
let picked = ReferencePoint::new(words.anchor.clone(), Bind::given(Some(state.anchor))).growth(growth).show(ui);
if let Some(anchor) = picked.value().copied().flatten() {
state.anchor = anchor;
}
});
@@ -262,7 +262,9 @@ fn rows(ui: &mut Ui, words: &WatermarkWords, units: &Units, now: &mut WatermarkS
}
}
Field::new(words.position.clone()).id_salt("position").show(ui, |ui, _| {
if let Some(position) = ReferencePoint::new(words.position.clone(), Bind::given(now.position)).show(ui).value().cloned() {
// P3(dialogs-w12): dg.F30
let picked = ReferencePoint::new(words.position.clone(), Bind::given(Some(now.position))).show(ui);
if let Some(position) = picked.value().cloned().flatten() {
now.position = position;
}
});
@@ -18,6 +18,6 @@ pub use modifier_keys::ModifierKeysPanel;
mod palette;
mod tour;
pub use palette::{CommandPalette, PaletteOutput};
pub use palette::{CommandPalette, PaletteFace, PaletteOutput};
pub use tour::{Tour, TourEvent, TourOutput, TourStep};
pub use words::PanelWords;
@@ -11,7 +11,7 @@ use crate::list::{List, ListRow};
use crate::menu::search::{HelpEntry, search_order};
use crate::popover::Popover;
use crate::runtime::commands::{self, CommandRef, FireSource};
use crate::runtime::env::{Env, Label};
use crate::runtime::env::{Env, Label, WordTemplate};
use crate::runtime::memory::Remember as _;
use crate::runtime::overlay::CloseReason;
use crate::runtime::words::common::CommonWords;
@@ -41,6 +41,17 @@ struct Session {
announced: Option<usize>,
}
/// Where a [`CommandPalette`] shows its search.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum PaletteFace {
/// A centred box.
#[default]
Dialog,
/// A search box where it is laid out (the title bar) that opens to the field and its results in place.
InPlace,
}
/// What a palette reports: its response, the command picked in this pass and how it closed.
#[derive(Debug)]
#[non_exhaustive]
@@ -51,6 +62,8 @@ pub struct PaletteOutput {
pub picked: Option<CommandRef>,
/// How the palette closed in this pass; `None` while it stays open.
pub closed: Option<CloseReason>,
/// The query the fallback row handed back, when the user picked it in this pass.
pub fallback: Option<String>,
}
impl crate::contract::Outcome for PaletteOutput {
@@ -82,12 +95,33 @@ pub struct CommandPalette<'a> {
/// The commands last run, newest first.
#[prop]
recents: Bind<'a, Vec<CommandRef>>,
/// Where the search shows: a centred box or in place.
#[prop]
face: PaletteFace,
/// The hint the in-place search box shows while it is closed.
#[prop(into)]
placeholder: Option<Label>,
/// The rows listed on an empty query, under a heading.
#[prop(into)]
suggested: Option<(Label, Vec<CommandRef>)>,
/// The row that hands the query back; its text is the template filled with the query as `{text}`.
#[prop]
fallback: Option<WordTemplate>,
}
impl<'a> CommandPalette<'a> {
/// A palette named `label` over `entries`, open while `open` is true.
pub fn new(label: impl Into<Label>, entries: &'a [HelpEntry], open: Bind<'a, bool>) -> Self {
CommandPalette { label: label.into(), entries, open, recents: Bind::kept() }
CommandPalette {
label: label.into(),
entries,
open,
recents: Bind::kept(),
face: PaletteFace::default(),
placeholder: None,
suggested: None,
fallback: None,
}
}
/// Puts `command` first in `recents`, once, keeping the newest `RECENT`.
@@ -99,7 +133,8 @@ impl<'a> CommandPalette<'a> {
/// Shows the palette while it is open.
pub fn show(self, ui: &mut Ui) -> PaletteOutput {
let CommandPalette { label, entries, open, mut recents } = self;
let CommandPalette { label, entries, open, mut recents, face, placeholder, suggested, fallback } = self;
let _ = (face, placeholder, suggested, fallback); // P3(chrome-w3): ch.C9, dg.F27
let ctx = ui.ctx().clone();
let env = Env::of(ui);
let words = env.words::<PanelWords>();
@@ -166,7 +201,7 @@ impl<'a> CommandPalette<'a> {
}
});
let closed = shown.output.closed;
PaletteOutput { response: shown.output.response, picked, closed }
PaletteOutput { response: shown.output.response, picked, closed, fallback: None }
}
}
@@ -186,7 +221,8 @@ fn texts_of(entries: &[HelpEntry], env: &crate::runtime::env::EnvView<'_>) -> Ve
/// The entries the list shows, by position in `entries`: the matches for a query, best first, else the commands
/// last run, newest first, else the first entries. A command appears once.
fn listing(entries: &[HelpEntry], query: &str, folder: &craft_i18n::Folder, texts: &[[String; 3]], recent: &[CommandRef]) -> Vec<usize> {
let refs: Vec<[&str; 3]> = texts.iter().map(|[label, english, path]| [label.as_str(), english.as_str(), path.as_str()]).collect();
// P3(chrome-w3): dg.F26 (the fourth text is the command id; empty until chrome-w3 passes it)
let refs: Vec<[&str; 4]> = texts.iter().map(|[label, english, path]| [label.as_str(), english.as_str(), path.as_str(), ""]).collect();
let candidates: Vec<usize> = if query.trim().is_empty() {
let last: Vec<usize> = recent.iter().filter_map(|command| entries.iter().position(|entry| entry.command() == command)).collect();
if last.is_empty() { (0..entries.len()).collect() } else { last }
@@ -4,7 +4,7 @@ use super::draft::{SettingsDraft, insert, lookup};
use super::rules::RuleKind;
use super::texts::OPEN_RANGE;
use super::{CustomSettings, SettingsDocument, table_of};
use crate::patterns::preferences::model::{GroupSpec, PageSpec, PrefValue, PreferencesModel};
use crate::patterns::preferences::model::{GroupSpec, PageSpec, PrefValue, PreferencesDraft, PreferencesModel};
use craft_theme::Rgba;
use egui::{Context, Ui};
use serde::Serialize;
@@ -116,6 +116,33 @@ impl<T: Serialize + DeserializeOwned + Default + Clone + PartialEq, C: CustomSet
self.custom.page(ui, page, &mut self.draft);
}
fn reset_page(&mut self, page: &str) {
if let Some(toml::Value::Table(defaults)) = self.defaults.get(page) {
// The page is replaced, so a key the defaults leave out (an `Option` that is `None`) goes too; only the
// `keep_on_reset` keys survive.
let mut reset = defaults.clone();
if let Some(toml::Value::Table(current)) = self.draft.table.get(page) {
for (key, value) in current {
if self.rules.get(&format!("{page}.{key}")).is_some_and(|rule| rule.keep_on_reset) {
reset.insert(key.clone(), value.clone());
}
}
}
self.draft.table.insert(page.to_owned(), toml::Value::Table(reset));
}
self.custom.reset_page(page);
}
fn nested(&mut self, ctx: &Context) {
self.custom.nested(ctx, &mut self.draft);
}
fn nested_open(&self) -> bool {
self.custom.nested_open()
}
}
impl<T: Serialize + DeserializeOwned + Default + Clone + PartialEq, C: CustomSettings<T>> PreferencesDraft for SettingsDocument<T, C> {
fn differs(&self) -> bool {
self.draft.table != self.saved_table || self.custom.differs()
}
@@ -142,29 +169,4 @@ impl<T: Serialize + DeserializeOwned + Default + Clone + PartialEq, C: CustomSet
self.draft = SettingsDraft { table: self.saved_table.clone() };
self.custom.cancel();
}
fn reset_page(&mut self, page: &str) {
if let Some(toml::Value::Table(defaults)) = self.defaults.get(page) {
// The page is replaced, so a key the defaults leave out (an `Option` that is `None`) goes too; only the
// `keep_on_reset` keys survive.
let mut reset = defaults.clone();
if let Some(toml::Value::Table(current)) = self.draft.table.get(page) {
for (key, value) in current {
if self.rules.get(&format!("{page}.{key}")).is_some_and(|rule| rule.keep_on_reset) {
reset.insert(key.clone(), value.clone());
}
}
}
self.draft.table.insert(page.to_owned(), toml::Value::Table(reset));
}
self.custom.reset_page(page);
}
fn nested(&mut self, ctx: &Context) {
self.custom.nested(ctx, &mut self.draft);
}
fn nested_open(&self) -> bool {
self.custom.nested_open()
}
}
@@ -19,16 +19,19 @@ mod model;
mod search;
pub use document::{CustomSettings, PageInfo, RuleKind, SettingRule, SettingsDocument, SettingsDraft, StandardPage, setting_label};
pub use model::{Closed, GroupSpec, PageSpec, PrefValue, PreferencesModel, PreferencesOutput, RowKind, RowSpec};
pub use model::{Closed, GroupSpec, PageSpec, PrefValue, PreferencesDraft, PreferencesModel, PreferencesOutput, RowKind, RowSpec};
pub use search::{Listed, list_pages, matches, row_matches, row_shown, shown_position};
pub use words::{PreferencesWords, SettingsDocumentWords};
// The window, its body and its rows.
mod body;
mod page;
mod path_setting;
mod rows;
mod window;
pub use page::{PreferencesPage, PreferencesPageOutput};
pub use path_setting::{PathSetting, PathSettingOutput};
pub use window::{DEFAULT_SIZE, MIN_SIZE, PreferencesState, PreferencesWindow};
@@ -299,16 +299,6 @@ pub trait PreferencesModel {
fn custom_row(&mut self, ui: &mut Ui, key: &str);
/// Draws a [`PageSpec::custom`] page.
fn custom_page(&mut self, ui: &mut Ui, page: &str);
/// Whether the draft differs from the saved settings: enables Apply.
fn differs(&self) -> bool;
/// Whether OK may close the window.
fn can_ok(&self) -> bool {
true
}
/// Commits the draft. `Err` keeps it and the window open and shows the message.
fn apply(&mut self) -> Result<(), String>;
/// Drops the draft and undoes previews (the language).
fn cancel(&mut self);
/// Resets the page's rows in the draft to their defaults.
fn reset_page(&mut self, page: &str);
/// Draws the dialogs the host opened from this window (a colour picker) inside the same viewport. Called last in
@@ -319,3 +309,17 @@ pub trait PreferencesModel {
false
}
}
/// The draft side of a preferences model: what a window with Apply, OK and Cancel needs beyond the rows.
pub trait PreferencesDraft: PreferencesModel {
/// Whether the draft differs from the saved settings: enables Apply.
fn differs(&self) -> bool;
/// Whether OK may close the window.
fn can_ok(&self) -> bool {
true
}
/// Commits the draft. `Err` keeps it and the window open and shows the message.
fn apply(&mut self) -> Result<(), String>;
/// Drops the draft and undoes previews (the language).
fn cancel(&mut self);
}
@@ -0,0 +1,42 @@
//! `PreferencesPage`: the preferences body without a window, applying each value at once.
use super::model::PreferencesModel;
use super::window::PreferencesState;
use crate::contract::{Bind, Pattern, Props};
use crate::runtime::requests::ColorRequest;
use egui::{Response, Ui};
/// A preferences page that applies each value at once, with search and Reset Section. [`PreferencesWindow`] shows its
/// body through this page, so one page path remains.
///
/// [`PreferencesWindow`]: super::PreferencesWindow
#[derive(Pattern, Props)]
pub struct PreferencesPage<'a> {
#[allow(dead_code)] // P3(chrome-w4): ch.C10
state: Bind<'a, PreferencesState>,
}
/// What a [`PreferencesPage`] reports: its response, the colour the host should pick and the page shown.
#[derive(Debug)]
#[non_exhaustive]
pub struct PreferencesPageOutput {
/// The page's response.
pub response: Response,
/// A colour row asked for the picker; the host answers through [`PreferencesModel::set_color`].
pub pick_color: Option<ColorRequest>,
/// The page the user switched to in this pass.
pub page: Option<String>,
}
impl<'a> PreferencesPage<'a> {
/// A page over the host's `state`.
pub fn new(state: Bind<'a, PreferencesState>) -> Self {
PreferencesPage { state }
}
/// Shows the page for this pass over `host`.
pub fn show<H: PreferencesModel + ?Sized>(self, ui: &mut Ui, host: &mut H) -> PreferencesPageOutput {
let _ = (ui, host);
todo!("ch.C10")
}
}
@@ -5,7 +5,9 @@
mod stories;
use super::body::{self, BodyOut};
use super::model::{Closed, PreferencesModel, PreferencesOutput};
#[cfg(doc)]
use super::model::PreferencesModel;
use super::model::{Closed, PreferencesDraft, PreferencesOutput};
use super::words::PreferencesWords;
use crate::contract::{Bind, Props as _, Remember, SaveKey, Show as _, ShowContainer as _};
use crate::dialog::{Dialog, DialogOutput};
@@ -88,7 +90,7 @@ struct Session<'h, 'b, H: ?Sized> {
applied: bool,
}
impl<H: PreferencesModel + ?Sized> Session<'_, '_, H> {
impl<H: PreferencesDraft + ?Sized> Session<'_, '_, H> {
/// Reads the state at the start of the body. A window that has just opened starts with no search and no error.
fn begin(&mut self, cx: &mut (impl StageAccess + Remember)) {
self.before = match self.state.reborrow().read(cx) {
@@ -134,7 +136,7 @@ impl<'a> PreferencesWindow<'a> {
}
/// Shows the window for this pass over `host`. The output's `closed` tells the host to stop showing it.
pub fn show<H: PreferencesModel + ?Sized>(self, ui: &mut Ui, host: &mut H) -> PreferencesOutput {
pub fn show<H: PreferencesDraft + ?Sized>(self, ui: &mut Ui, host: &mut H) -> PreferencesOutput {
let PreferencesWindow { state, title, embedded, remember } = self;
let env = Env::of(ui);
let words = env.words::<PreferencesWords>();
@@ -2,7 +2,7 @@
use super::{PreferencesState, PreferencesWindow};
use crate::contract::{Bind, Entry};
use crate::patterns::preferences::{PageSpec, PrefValue, PreferencesModel, RowKind, RowSpec};
use crate::patterns::preferences::{PageSpec, PrefValue, PreferencesDraft, PreferencesModel, RowKind, RowSpec};
use crate::runtime::env::UnitKind;
use crate::testing::{Drive, StoryData, StoryOutput, story};
use craft_theme::Rgba;
@@ -77,6 +77,19 @@ impl PreferencesModel for Demo {
fn custom_page(&mut self, _: &mut Ui, _: &str) {}
fn reset_page(&mut self, page: &str) {
let defaults = Values::default();
match page {
"general" => (self.draft.snap, self.draft.language, self.draft.name) = (defaults.snap, defaults.language, defaults.name),
"canvas" => (self.draft.size, self.draft.opacity, self.draft.tint) = (defaults.size, defaults.opacity, defaults.tint),
_ => {}
}
}
fn nested(&mut self, _: &Context) {}
}
impl PreferencesDraft for Demo {
fn differs(&self) -> bool {
self.draft != self.saved
}
@@ -92,17 +105,6 @@ impl PreferencesModel for Demo {
fn cancel(&mut self) {
self.draft = self.saved.clone();
}
fn reset_page(&mut self, page: &str) {
let defaults = Values::default();
match page {
"general" => (self.draft.snap, self.draft.language, self.draft.name) = (defaults.snap, defaults.language, defaults.name),
"canvas" => (self.draft.size, self.draft.opacity, self.draft.tint) = (defaults.size, defaults.opacity, defaults.tint),
_ => {}
}
}
fn nested(&mut self, _: &Context) {}
}
fn window(ui: &mut Ui, data: &mut StoryData, state: PreferencesState, demo: Demo) -> StoryOutput {
@@ -1,8 +1,9 @@
//! The settings document without a window: rows, applied edits, rebase and row conditions.
use craft_theme::Rgba;
// P3(chrome-w4): ch.C10
use craft_ui::patterns::preferences::{
CustomSettings, PageInfo, PrefValue, PreferencesModel, RowKind, SettingRule, SettingsDocument, SettingsDraft, StandardPage,
CustomSettings, PageInfo, PrefValue, PreferencesDraft, PreferencesModel, RowKind, SettingRule, SettingsDocument, SettingsDraft, StandardPage,
};
use craft_ui::testing::trial;
use serde::{Deserialize, Serialize};