Preferences: custom rows whose host draws its own labels (RowKind::CustomRows, SettingRule::custom_rows)

This commit is contained in:
aiongg
2026-11-21 08:51:15 +00:00
parent 9bafed916f
commit e576f99df7
6 changed files with 77 additions and 10 deletions
@@ -91,7 +91,7 @@ impl<T: Serialize + DeserializeOwned + Default + Clone + PartialEq, C: CustomSet
(PrefValue::Int(n), Value::Float(_)) => Value::Float(clamp_float(n as f64)),
(PrefValue::Float(x), Value::Float(_)) if x.is_finite() => Value::Float(clamp_float(x)),
(PrefValue::Float(x), Value::Integer(_)) if x.is_finite() => Value::Integer(clamp_int(x.round() as i64)),
(PrefValue::Text(text), Value::String(_)) if matches!(kind, None | Some(RuleKind::Custom)) => Value::String(text),
(PrefValue::Text(text), Value::String(_)) if matches!(kind, None | Some(RuleKind::Custom | RuleKind::CustomRows)) => Value::String(text),
(PrefValue::Choice(id), Value::String(_) | Value::Integer(_)) => match kind {
Some(RuleKind::Choice(options)) if options.iter().any(|(option, _)| *option == id) => match id.parse::<i64>() {
Ok(n) if self.rules.get(key).is_some_and(|rule| rule.integer) => Value::Integer(n),
@@ -71,8 +71,10 @@ pub enum RuleKind {
Choice(Vec<(String, String)>),
/// A `#rrggbb` string as a swatch and hex field.
Color,
/// The app draws it ([`CustomSettings::row`]).
/// The app draws it ([`CustomSettings::row`]); the window labels it.
Custom,
/// The app draws whole rows, labels included ([`CustomSettings::row`]).
CustomRows,
}
impl SettingRule {
@@ -158,13 +160,21 @@ impl SettingRule {
self
}
/// The app draws the control ([`CustomSettings::row`]).
/// The app draws the control ([`CustomSettings::row`]); the window labels it beside the control.
#[must_use]
pub fn custom(mut self) -> Self {
self.kind = Some(RuleKind::Custom);
self
}
/// The app draws whole rows with their labels ([`CustomSettings::row`]): the window adds none. The rule's label
/// stays the row's search text and its group's name.
#[must_use]
pub fn custom_rows(mut self) -> Self {
self.kind = Some(RuleKind::CustomRows);
self
}
/// Shows the row only while the setting at `key` has `value`. Called again, the row shows only while every
/// condition holds.
#[must_use]
@@ -57,6 +57,7 @@ enum Shape {
Choice(Vec<(String, Label)>, Option<UnitKind>),
Color,
Custom,
CustomRows,
}
/// The range of a number without a rule.
@@ -65,8 +66,10 @@ pub(super) const OPEN_RANGE: f64 = 1e9;
fn shape_of(rule: Option<&SettingRule>, value: Option<&toml::Value>) -> Option<Shape> {
use toml::Value;
let kind = rule.and_then(|rule| rule.kind.as_ref());
if matches!(kind, Some(RuleKind::Custom)) {
return Some(Shape::Custom);
match kind {
Some(RuleKind::Custom) => return Some(Shape::Custom),
Some(RuleKind::CustomRows) => return Some(Shape::CustomRows),
_ => {}
}
Some(match (kind, value?) {
(Some(RuleKind::Choice(options)), Value::String(_) | Value::Integer(_)) => {
@@ -169,7 +172,7 @@ impl<T: Serialize + DeserializeOwned + Default + Clone + PartialEq, C: CustomSet
let prefix = format!("{}.", page.id);
for (path, rule) in self.rules.range(prefix.clone()..).take_while(|(path, _)| path.starts_with(&prefix)) {
let key = &path[prefix.len()..];
if matches!(rule.kind, Some(RuleKind::Custom)) && !keys.iter().any(|k| k == key) {
if matches!(rule.kind, Some(RuleKind::Custom | RuleKind::CustomRows)) && !keys.iter().any(|k| k == key) {
keys.push(key.to_owned());
}
}
@@ -235,6 +238,7 @@ impl<T: Serialize + DeserializeOwned + Default + Clone + PartialEq, C: CustomSet
(Shape::Choice(options, counted), Some(Value::String(id))) => choice_kind(options, *counted, id),
(Shape::Color, Some(Value::String(text))) => RowKind::Color(Rgba::from_hex(text).unwrap_or(Rgba::rgb(128, 128, 128))),
(Shape::Custom, _) => RowKind::Custom,
(Shape::CustomRows, _) => RowKind::CustomRows,
_ => return None,
};
let spec = RowSpec::new(&row.key, &row.label, kind).keywords(&row.keywords).visible(self.row_visible(&row.key));
@@ -204,8 +204,11 @@ pub enum RowKind<'a> {
},
/// A text field.
Text(&'a str),
/// The host draws the control ([`PreferencesModel::custom_row`]).
/// The host draws the control ([`PreferencesModel::custom_row`]); the window labels it beside the control.
Custom,
/// The host draws whole rows, labels included ([`PreferencesModel::custom_row`]): the window adds no label. The
/// row's label stays its search text and its group's name.
CustomRows,
}
impl<'a> RowKind<'a> {
@@ -35,6 +35,7 @@ pub(super) enum Kind {
Float { value: f64, range: RangeInclusive<f64>, decimals: u8, step: Option<f64>, unit: Option<UnitKind> },
Text(String),
Custom,
CustomRows,
}
impl ShownRow {
@@ -59,6 +60,7 @@ impl ShownRow {
}
RowKind::Text(text) => Kind::Text((*text).to_owned()),
RowKind::Custom => Kind::Custom,
RowKind::CustomRows => Kind::CustomRows,
};
Self {
key: row.key.to_owned(),
@@ -176,7 +178,7 @@ pub(super) fn show_row<H: PreferencesModel + ?Sized>(ui: &mut Ui, host: &mut H,
out.pick_color = ask;
}
}
Kind::Custom if label.as_str().is_empty() => {
Kind::CustomRows => {
Stack::new().id_salt(key).show(ui, |ui, _| host.custom_row(ui, key));
}
Kind::Custom => {
@@ -1,7 +1,11 @@
//! `PreferencesPage` over a model with no draft: each edit reaches the model in the pass it lands in.
use craft_ui::contract::{Bind, Role};
use craft_ui::patterns::preferences::{PageSpec, PrefValue, PreferencesModel, PreferencesPage, PreferencesState, PreferencesWords, RowKind, RowSpec};
use craft_ui::contract::{Bind, Role, Show as _, ShowContainer as _};
use craft_ui::display::Text;
use craft_ui::form::Field;
use craft_ui::patterns::preferences::{
GroupSpec, PageSpec, PrefValue, PreferencesModel, PreferencesPage, PreferencesState, PreferencesWords, RowKind, RowSpec,
};
use craft_ui::runtime::env::Env;
use craft_ui::runtime::words::CommonWords;
use craft_ui::testing::pointer::{moved, press, release};
@@ -83,3 +87,47 @@ fn a_page_edit_reaches_the_model_in_the_same_pass_and_no_draft_method_runs() {
assert_eq!(live.borrow().sets.len(), 1, "later passes apply nothing again");
assert!(live.borrow().snap, "the model holds the value");
}
/// A page of two titled groups with labels of different lengths, and a host-labelled row that draws its own field.
struct Grouped;
impl PreferencesModel for Grouped {
fn pages(&self) -> Vec<PageSpec<'_>> {
let text = |key, label| RowSpec::new(key, label, RowKind::Text("v"));
let mut page = PageSpec::new("general", "General", Vec::new());
page.groups = vec![
GroupSpec::new(Some("First"), vec![text("general.a", "Aa"), RowSpec::new("general.host", "Hosted", RowKind::CustomRows)]),
GroupSpec::new(Some("Second"), vec![text("general.b", "A much longer label")]),
];
vec![page]
}
fn set(&mut self, _: &str, _: PrefValue) {}
fn custom_row(&mut self, ui: &mut Ui, _: &str) {
let _ = Field::new("Hosted").show(ui, |ui, _| {
Text::new("hosted value").show(ui);
});
}
fn custom_page(&mut self, _: &mut Ui, _: &str) {}
fn reset_page(&mut self, _: &str) {}
}
fn grouped_page() -> Fixture {
let mut state = PreferencesState::default();
let mut fixture = Fixture::new(move |ui| {
PreferencesPage::new(Bind::bound(&mut state)).show(ui, &mut Grouped);
});
fixture.settle();
fixture
}
#[trial]
fn a_host_labelled_custom_row_shows_its_label_once() {
let fixture = grouped_page();
let tree = fixture.tree();
let fields = tree.keys().into_iter().filter(|key| tree.name_of(*key) == Some("Hosted") && tree.role_of(*key) == Some(Role::GROUP)).count();
assert_eq!(fields, 1, "the host's field is the row's only labelled group");
}