Merge pull request #3856 from dotCooCoo/fix/form-row-additional-enable-condition

Forms: let a field require more than one enabled condition
This commit is contained in:
BFlat authored and GitHub committed 2026-11-27 14:23:50 +07:00
commit f78fca080f
5 files changed
+220 -33

No files matched your search

+16
View File
@@ -470,6 +470,7 @@ impl DialogRole {
pub struct FooterButton {
label: Label,
role: DialogRole,
tag: Option<Id>,
letter: Option<char>,
chord: Option<Chord>,
enabled: bool,
@@ -504,6 +505,7 @@ impl FooterButton {
FooterButton {
label: label.into(),
role,
tag: None,
letter: None,
chord: None,
enabled: true,
@@ -514,6 +516,20 @@ impl FooterButton {
}
}
/// Associates a generated button with the dialog body that handles it.
#[doc(hidden)]
#[must_use]
pub const fn tagged(mut self, tag: Id) -> Self {
self.tag = Some(tag);
self
}
/// The generated button's identity, preserved through footer settlement and picking.
#[doc(hidden)]
pub const fn tag(&self) -> Option<Id> {
self.tag
}
/// The letter that activates the button while its dialog holds focus and no text part owns the keys. On Windows
/// and Linux, Alt with the letter also activates it while its dialog is the top modal, whatever has the focus. The
/// button reports the letter as its `access_key`.
@@ -36,7 +36,7 @@ use crate::runtime::env::{Env, Label};
use crate::text::RangeAlert;
use craft_behavior::{CanvasTransform, DisplayOrder, EditEvent, ItemSource, Mixed, SelectionChange};
use crate::runtime::memory::{Lifetime, MemoryStage, with_session};
use crate::runtime::memory::{Lifetime, MemoryStage};
use crate::runtime::overlay::CloseReason;
use crate::runtime::words::CommonWords;
@@ -45,10 +45,11 @@ use crate::sections::{DialogRole, FooterButton};
use crate::contract::{CaptionColumn, LabelScheme};
use craft_theme::Srgba;
use craft_theme::variant::Tone;
use egui::{Context, Pos2, Rect, Response, Ui};
use egui::{Context, Id, Pos2, Rect, Response, Ui};
use serde_json::Value;
use std::borrow::Cow;
use std::collections::HashMap;
use std::sync::Arc;
#[cfg(feature = "suite")]
@@ -471,14 +472,6 @@ impl<'a> ParamPresets<'a> {
}
}
/// The footer rows of a [`ParamDialog`] between passes: whether each was on when the last pass ended, which its
/// button label shows, and the key of the row whose button was pressed, which the next pass flips.
#[derive(Clone, Debug, Default)]
struct FooterRows {
on: Vec<bool>,
flip: Option<String>,
}
/// What `ParamDialog::below` draws under the rows.
pub struct BelowRows<'a>(BelowRowsFn<'a>);
@@ -719,17 +712,11 @@ impl<'a> ParamDialog<'a> {
}
// The pane shows only in a dialog that previews.
let preview = preview.filter(|_| previews);
// The footer rows' buttons follow the extra buttons. A button's label cannot change inside the pass that
// draws it, so it shows the state the previous pass left.
// The footer rows' buttons follow the extra buttons; the body settles them by tag after it reads the fields.
let footer_rows: Vec<&Param> = params.iter().filter(|param| param.footer_on().is_some()).collect();
let footer_id = crate::runtime::memory::unique(("paramDialog.footer", key.as_str()));
let footer_states: Vec<bool> =
if footer_rows.is_empty() { Vec::new() } else { with_session(ui.ctx(), footer_id, |footer: &mut FooterRows| footer.on.clone()) };
let footer_buttons = footer_rows.iter().enumerate().map(|(at, param)| {
let on = footer_states.get(at).copied().unwrap_or(false);
let label = param.footer_on().filter(|_| on).unwrap_or_else(|| param.label.clone());
FooterButton::new(label, DialogRole::Other).stays_open(true)
});
let footer_buttons = footer_rows.iter().map(|param| footer_toggle(param, false, true));
let footer_owner = crate::runtime::overlay::running_dialog(ui.ctx()).unwrap_or_else(|| ui.scope_id());
let footer_owner = crate::runtime::memory::unique(("paramDialog.footer.owner", footer_owner, key.as_str()));
let buttons: Vec<FooterButton> = extra_buttons.iter().map(|(_, button)| button.clone()).chain(footer_buttons).collect();
if !buttons.is_empty() {
form = form.extra_buttons(buttons);
@@ -807,7 +794,8 @@ impl<'a> ParamDialog<'a> {
// A footer row pressed in the previous pass flips once; a measuring run leaves it for the real one.
if !footer_rows.is_empty()
&& !crate::runtime::measure::active(ui.ctx())
&& let Some(flip) = with_session(ui.ctx(), footer_id, |footer: &mut FooterRows| footer.flip.take())
&& let Some(flip) = footer_flips(ui.ctx(), |flips| flips.ready.remove(&footer_owner))
&& footer_rows.iter().any(|param| param.key == flip && param.enabled(values))
{
let on = values.bool(&flip).unwrap_or(false);
values.set(flip, FieldValue::Bool(!on));
@@ -883,10 +871,13 @@ impl<'a> ParamDialog<'a> {
}
}
*cx.memory::<Live>() = live.clone();
if !footer_rows.is_empty() {
let states: Vec<bool> = footer_rows.iter().map(|param| values.bool(&param.key).unwrap_or(false)).collect();
with_session(ui.ctx(), footer_id, |footer: &mut FooterRows| footer.on = states);
}
*cx.memory::<FooterToggles>() = FooterToggles {
owner: Some(footer_owner),
buttons: footer_rows
.iter()
.map(|param| (param.key.clone(), footer_toggle(param, values.bool(&param.key).unwrap_or(false), param.enabled(values))))
.collect(),
};
// OK and Enter wait while a row's text does not parse.
rows.as_ref().is_none_or(|rows| !rows.unparsed)
});
@@ -897,12 +888,6 @@ impl<'a> ParamDialog<'a> {
Some(ResetPick::Extra(at)) => extra_buttons.get(at).map(|(id, _)| id.clone()),
_ => None,
};
if let Some(ResetPick::Extra(at)) = pick
&& let Some(param) = at.checked_sub(extra_buttons.len()).and_then(|at| footer_rows.get(at))
{
with_session(ui.ctx(), footer_id, |footer: &mut FooterRows| footer.flip = Some(param.key.clone()));
crate::runtime::frame::request_repaint(ui.ctx());
}
// Footer and row buttons share one channel. The rows' own slot is emptied, so a host that absorbs the rows
// files the press once.
let action = rows.as_mut().and_then(|rows: &mut ParamRowsOutput| rows.action.take()).or(pressed);
@@ -1020,6 +1005,48 @@ struct Footing {
ok: Option<bool>,
}
/// The current labels and enablement of the generated footer buttons, from this dialog's body.
#[derive(Clone, Default)]
struct FooterToggles {
owner: Option<Id>,
buttons: Vec<(String, FooterButton)>,
}
/// One pass of queued flips, keyed by dialog instance. Flips whose dialogs do not show on the next pass expire.
#[derive(Default)]
struct FooterFlips {
ready: HashMap<Id, String>,
next: HashMap<Id, String>,
}
impl crate::runtime::frame::Stored for FooterFlips {}
fn footer_flips<R>(ctx: &Context, f: impl FnOnce(&mut FooterFlips) -> R) -> R {
use crate::runtime::frame::{PassStep, PerViewport, Stamped, running};
let (viewport, pass) = if let Some(facts) = running(ctx) {
(facts.viewport, facts.pass_nr)
} else {
let viewport = ctx.viewport_id();
(viewport, ctx.cumulative_pass_nr_for(viewport))
};
PerViewport::<Stamped<FooterFlips>>::with_pass(
ctx,
viewport,
pass,
|flips, step| match step {
PassStep::Next => flips.ready = std::mem::take(&mut flips.next),
PassStep::Skipped => *flips = FooterFlips::default(),
},
f,
)
}
fn footer_toggle(param: &Param, on: bool, enabled: bool) -> FooterButton {
let label = param.footer_on().filter(|_| on).unwrap_or_else(|| param.label.clone());
let tag = crate::runtime::memory::unique(("paramDialog.footer", &param.key));
FooterButton::new(label, DialogRole::Other).tagged(tag).stays_open(true).enabled(enabled)
}
/// What a footer with a Reset alternative answered with.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
@@ -1117,12 +1144,31 @@ impl ResetFooter {
if let (Some(ok), Some(accept)) = (footing.ok, buttons.first_mut()) {
accept.set_enabled(ok);
}
let toggles = &cx.memory::<FooterToggles>().buttons;
for button in buttons {
if let Some(tag) = button.tag()
&& let Some((_, toggle)) = toggles.iter().find(|(_, toggle)| toggle.tag() == Some(tag))
{
*button = toggle.clone();
}
}
})
.on_pick(move |button, cx| {
if pick.resetting() && button.role() == DialogRole::Other && *button.label() == pick.reset {
restore(cx);
crate::runtime::frame::request_repaint(cx.memory.ctx());
}
let toggles = cx.memory::<FooterToggles>();
if let (Some(owner), Some(tag)) = (toggles.owner, button.tag())
&& let Some((key, _)) = toggles.buttons.iter().find(|(_, toggle)| toggle.tag() == Some(tag))
{
let key = key.clone();
let ctx = cx.memory.ctx();
footer_flips(ctx, |flips| {
flips.next.insert(owner, key);
});
crate::runtime::frame::request_repaint(ctx);
}
})
}
@@ -622,6 +622,8 @@ pub(crate) struct RowOptions {
resets: Vec<String>,
/// The row takes input only while the number under the key is above the bound ([`Param::enabled_above`]).
enabled_above: Option<(String, f64)>,
/// Additional field conditions that must all hold ([`Param::and_enabled_when_in`]).
enabled_when_also: Vec<(String, Vec<FieldValue>)>,
/// The row takes input only while the values under the two keys differ ([`Param::enabled_when_differs`]).
enabled_when_differs: Option<(String, String)>,
/// The value the row shows while it is disabled ([`Param::disabled_value`]).
@@ -922,6 +924,14 @@ impl Param {
self
}
/// Adds a condition: the row takes input only while `fields[key]` equals one of `values` and every other
/// enable condition holds. A missing field does not satisfy it.
#[must_use]
pub fn and_enabled_when_in(mut self, key: impl Into<String>, values: impl IntoIterator<Item = impl Into<FieldValue>>) -> Self {
self.options.get_or_insert_default().enabled_when_also.push((key.into(), values.into_iter().map(Into::into).collect()));
self
}
/// The row takes input only while the number `fields[key]` is above `bound` (an int reads as a number); otherwise
/// it is shown disabled.
#[must_use]
@@ -1531,8 +1541,7 @@ impl Param {
self.shown && self.visible_when.iter().all(|(key, values)| fields.get(key).is_some_and(|held| values.contains(held)))
}
/// Whether the row takes input with `fields`: every condition its `enabled_when`,
/// [`enabled_above`](Param::enabled_above) and [`enabled_when_differs`](Param::enabled_when_differs) set holds.
/// Whether the row takes input with `fields`: every enable condition must hold.
pub fn enabled(&self, fields: &DialogFields) -> bool {
let options = self.options.as_deref();
let enabled = match &self.enable {
@@ -1541,6 +1550,8 @@ impl Param {
Enable::Off => false,
};
enabled
&& options
.is_none_or(|options| options.enabled_when_also.iter().all(|(key, values)| fields.get(key).is_some_and(|held| values.contains(held))))
&& options.and_then(|options| options.enabled_above.as_ref()).is_none_or(|(key, bound)| fields.number(key).is_some_and(|n| n > *bound))
&& options.and_then(|options| options.enabled_when_differs.as_ref()).is_none_or(|(a, b)| fields.get(a) != fields.get(b))
}
@@ -1139,6 +1139,88 @@ fn a_footer_row_flips_its_value_and_automation_sets_it() {
assert!(!ParamDialog::remembered(&footer_params(), &fields).contains("grid"), "the footer key is not remembered");
}
#[trial]
fn a_footer_toggle_takes_input_only_while_all_its_conditions_hold() {
let (host, twice) = (Rc::new(RefCell::new(DialogHost::new())), Rc::new(Cell::new(false)));
let mut fixture = host_fixture(&host, &twice);
let ctx = fixture.ctx().clone();
fn build(fields: &mut DialogFields) -> ParamDialog<'_> {
let rows = vec![
Param::new("custom", "Custom", ParamKind::bool(false)),
Param::new("advanced", "Advanced", ParamKind::bool(false)),
Param::new("grid", "Show Grid", ParamKind::bool(false))
.enabled_when("custom", true)
.and_enabled_when_in("advanced", [true])
.in_footer("Hide Grid"),
];
ParamDialog::new("conditional-grid", "Grid", rows).values(Bind::bound(fields))
}
let id = host.borrow_mut().open(HostedParamDialog::new(&ctx, "conditional-grid", DialogFields::new(), build));
let grid = || on_dialog(&host, |dialog| dialog.fields().bool("grid")).flatten();
fixture.idle(6);
assert_eq!(host.borrow_mut().set_json_field(&ctx, id, "custom", json!(true)), Ok(()));
fixture.idle(6);
let button = fixture.by_label("Show Grid").expect("the footer button stays visible");
assert!(fixture.tree().is_disabled_key(button.node));
fixture.click(&button).idle(6);
assert_ne!(grid(), Some(true), "a disabled footer button does not flip the value");
assert!(host.borrow_mut().set_json_field(&ctx, id, "grid", json!(true)).is_err());
assert_eq!(host.borrow_mut().set_json_field(&ctx, id, "advanced", json!(true)), Ok(()));
fixture.idle(6);
let button = fixture.by_label("Show Grid").expect("the footer button");
assert!(!fixture.tree().is_disabled_key(button.node));
fixture.press(&button).release(&button);
assert_ne!(grid(), Some(true), "the flip waits for the next pass");
assert_eq!(host.borrow_mut().set_json_field(&ctx, id, "advanced", json!(false)), Ok(()));
fixture.idle(6);
assert_ne!(grid(), Some(true), "a queued flip is dropped once its condition no longer holds");
assert_eq!(host.borrow_mut().set_json_field(&ctx, id, "advanced", json!(true)), Ok(()));
fixture.idle(6);
let button = fixture.by_label("Show Grid").expect("the footer button is enabled again");
fixture.click(&button).idle(6);
assert_eq!(grid(), Some(true));
assert!(fixture.by_label("Hide Grid").is_some());
}
#[trial]
fn a_queued_footer_press_follows_its_dialog_when_the_stack_changes() {
let (host, twice) = (Rc::new(RefCell::new(DialogHost::new())), Rc::new(Cell::new(false)));
let mut fixture = host_fixture(&host, &twice);
let ctx = fixture.ctx().clone();
let lower = host.borrow_mut().open(HostedParamDialog::new(&ctx, "grid", DialogFields::new(), gridded).instance("lower"));
let top = host.borrow_mut().open(HostedParamDialog::new(&ctx, "grid", DialogFields::new(), gridded).instance("top"));
fixture.idle(6);
let top_button = fixture.by_label("Show Grid").expect("the top dialog's toggle");
fixture.press(&top_button).release(&top_button);
assert!(host.borrow_mut().cancel_by_id(&ctx, lower));
let new = host.borrow_mut().open(HostedParamDialog::new(&ctx, "grid", DialogFields::new(), gridded).instance("new"));
fixture.idle(6);
let grid = |id| host.borrow().get_by_id::<HostedParamDialog>(id).and_then(|dialog| dialog.fields().bool("grid"));
assert_eq!(grid(top), Some(true), "the press follows the original dialog");
assert_eq!(grid(new), Some(false), "the new dialog does not inherit the press");
}
#[trial]
fn a_replacement_footer_button_keeps_its_own_enablement() {
let mut fixture = Fixture::new(|ui| {
ParamDialog::new("custom-footer", "Custom Footer", footer_params())
.shaped(|dialog| {
dialog.buttons([
FooterButton::new("OK", DialogRole::Accept),
FooterButton::new("Cancel", DialogRole::Cancel),
FooterButton::new("Unavailable", DialogRole::Other).enabled(false),
])
})
.show(ui);
});
fixture.settle();
let replacement = fixture.by_label("Unavailable").expect("the caller's replacement button");
assert!(fixture.tree().is_disabled_key(replacement.node));
assert!(fixture.by_label("Show Grid").is_none());
}
// The presets row lists the presets; a pick writes the preset's values as one edit, and a value edited after it
// leaves the values matching no preset.
#[trial]
@@ -220,6 +220,38 @@ fn rows_follow_their_predicates_and_carry_their_tooltip() {
assert!(fixture.tree().is_disabled_key(detail.node), "disabled for the third value");
}
#[trial]
fn a_row_checks_all_its_enable_conditions_on_screen_and_in_automation() {
let params = vec![
Param::new("hyphenate", "Hyphenation", ParamKind::bool(false)),
Param::new("zone", "Hyphenation Zone", ParamKind::int(Some(0), None, 0))
.enabled_when("hyphenate", true)
.and_enabled_when_in("composer", ["singleLine", "standardSingleLine"]),
];
let values = Rc::new(RefCell::new(DialogFields::new()));
let mut fixture = rows(params.clone(), &values);
for (hyphenate, composer, enabled) in [
(true, None, false),
(false, Some("singleLine"), false),
(true, Some("everyLine"), false),
(true, Some("singleLine"), true),
(true, Some("standardSingleLine"), true),
] {
{
let mut fields = values.borrow_mut();
fields.set("hyphenate", hyphenate);
if let Some(composer) = composer {
fields.set("composer", composer);
}
}
fixture.settle();
let zone = fixture.by_label("Hyphenation Zone").expect("the row stays visible");
assert_eq!(!fixture.tree().is_disabled_key(zone.node), enabled, "{hyphenate}, {composer:?}");
let mut fields = values.borrow().clone();
assert_eq!(set_param_field(&params, &mut fields, "zone", json!(8)).is_ok(), enabled, "{hyphenate}, {composer:?}");
}
}
// A row with two `visible_when` conditions is there only while both hold: the second call adds a condition, not
// replaces the first. A `disabled` row takes no input whatever the fields hold, from a click or from automation.
#[trial]