mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-17 00:34:25 +00:00
ui-patterns: hosted parameter dialogs open their values at open; custom rows declare companions and an opening value
This commit is contained in:
@@ -18,13 +18,13 @@ fn call(host: &mut DialogHost, ctx: &Context, method: &str, params: Value) -> Re
|
||||
fn dialog_methods_read_set_and_answer_typed_dialogs() {
|
||||
let ctx = Context::default();
|
||||
let mut host = DialogHost::new();
|
||||
host.open(HostedParamDialog::new("gaussianBlur", DialogFields::from_pairs([("radius", 1.0)]), |fields| {
|
||||
host.open(HostedParamDialog::new(&ctx, "gaussianBlur", DialogFields::from_pairs([("radius", 1.0)]), |fields| {
|
||||
ParamDialog::new("gaussianBlur", "Gaussian Blur", Param::parse_list(r#"{"radius":0.1..1000=1,"method":"spin|zoom"}"#))
|
||||
.values(Bind::bound(fields))
|
||||
}));
|
||||
let listed = inspect(&host);
|
||||
assert_eq!(listed[0]["key"], "gaussianBlur");
|
||||
assert_eq!(listed[0]["fields"], json!({"radius": 1.0}));
|
||||
assert_eq!(listed[0]["fields"], json!({"radius": 1.0, "method": "spin"}), "the dialog lists its defaults from its open");
|
||||
let blur = listed[0]["id"].clone();
|
||||
|
||||
assert_eq!(call(&mut host, &ctx, "ui.dialog.set", json!({"dialog": blur, "field": "radius", "value": 4.5})), Ok(Value::Null));
|
||||
@@ -72,14 +72,14 @@ fn dialog_methods_read_set_and_answer_typed_dialogs() {
|
||||
const REMEMBERED: SaveKey = SaveKey::new("craft_automation.blur");
|
||||
|
||||
/// A hosted parameter dialog's automation follows its rows as a user meets them: OK is refused while disabled, a
|
||||
/// disabled row takes no value, a value is read as its row's kind (three integers for a three-cell grid), and OK
|
||||
/// before the first pass answers with the remembered values the first pass would have loaded.
|
||||
/// disabled row takes no value, a value is read as its row's kind (three integers for a three-cell grid), and from its
|
||||
/// open, before any pass, the dialog lists and answers with the remembered values over the defaults.
|
||||
#[trial]
|
||||
fn param_dialog_automation_follows_its_rows() {
|
||||
let ctx = Context::default();
|
||||
let mut host = DialogHost::new();
|
||||
let blur = |ok: bool| {
|
||||
HostedParamDialog::new("blur", DialogFields::new(), move |fields| {
|
||||
HostedParamDialog::new(&ctx, "blur", DialogFields::new(), move |fields| {
|
||||
let mut params = Param::parse_list(r#"{"radius":0.1..1000=1,"method":"spin|zoom"}"#);
|
||||
params.push(Param::new("amount", "Amount", ParamKind::range(0.0, 100.0, 10.0, Default::default())).enabled_when("method", "zoom"));
|
||||
params.push(Param::new("cells", "Cells", ParamKind::grid(3, 0)));
|
||||
@@ -109,7 +109,10 @@ fn param_dialog_automation_follows_its_rows() {
|
||||
result.remember(&ctx);
|
||||
|
||||
host.open(blur(true));
|
||||
let id = inspect(&host)[0]["id"].clone();
|
||||
let listed = inspect(&host);
|
||||
let id = listed[0]["id"].clone();
|
||||
let fields = &listed[0]["fields"];
|
||||
assert_eq!((fields["radius"].as_f64(), &fields["method"], &fields["cells"]), (Some(7.0), &json!("zoom"), &json!([0, 1, 0])), "{fields}");
|
||||
assert_eq!(call(&mut host, &ctx, "ui.dialog.confirm", json!({"dialog": id})), Ok(Value::Null));
|
||||
let Some(DialogResult::Ok(reopened)) = host.take::<HostedParamDialog>() else { panic!("the reopened dialog answers OK") };
|
||||
assert_eq!((reopened.fields.number("radius"), reopened.fields.text("method")), (Some(7.0), Some("zoom")));
|
||||
|
||||
@@ -148,7 +148,7 @@ fn body(ui: &mut Ui, cx: &mut BodyCx<'_>, state: &mut MockState) {
|
||||
for command in dialogs {
|
||||
match command {
|
||||
AppCommand::GaussianBlur => {
|
||||
host.open(HostedParamDialog::new(BLUR_KEY, DialogFields::new(), |fields| {
|
||||
host.open(HostedParamDialog::new(ui.ctx(), BLUR_KEY, DialogFields::new(), |fields| {
|
||||
ParamDialog::new(BLUR_KEY, "Gaussian Blur", Param::parse_list(BLUR)).values(Bind::bound(fields)).remember(BLUR_MEMORY)
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -741,7 +741,7 @@ type Build = dyn for<'b> Fn(&'b mut DialogFields) -> ParamDialog<'b> + Send;
|
||||
/// [`answer_ok`](HostedParamDialog::answer_ok).
|
||||
///
|
||||
/// ```ignore
|
||||
/// host.open(HostedParamDialog::new("radial-blur", DialogFields::new(), |fields| {
|
||||
/// host.open(HostedParamDialog::new(ctx, "radial-blur", DialogFields::new(), |fields| {
|
||||
/// ParamDialog::new("radial-blur", "Radial Blur", params.clone()).values(Bind::bound(fields))
|
||||
/// }));
|
||||
/// // each pass: if dialog.is_previewing() { dialog.set_preview(Some(render(dialog.fields()))) }
|
||||
@@ -751,8 +751,6 @@ pub struct HostedParamDialog {
|
||||
key: String,
|
||||
instance: Option<DialogId>,
|
||||
fields: DialogFields,
|
||||
/// The values were opened (remembered values and defaults loaded) by the first show, OK or set.
|
||||
opened: bool,
|
||||
build: Box<Build>,
|
||||
requests: HostRequests,
|
||||
/// Whether the dialog is open: bound to the dialog's `opened` prop, so the dialog's own open state, kept under
|
||||
@@ -799,20 +797,26 @@ struct Refused {
|
||||
}
|
||||
|
||||
impl HostedParamDialog {
|
||||
/// A hosted dialog for the command `key`, opening with `fields`; `build` makes the dialog over the values.
|
||||
/// A hosted dialog for the command `key`, opening with `fields`; `build` makes the dialog over the values. The
|
||||
/// values open now, as a `ParamDialog`'s first pass opens its own: the remembered values `ctx` keeps over
|
||||
/// `fields`, then the defaults of the keys still missing. Automation reads and sets these values before any pass.
|
||||
pub fn new(
|
||||
ctx: &Context,
|
||||
key: impl Into<String>,
|
||||
fields: DialogFields,
|
||||
mut fields: DialogFields,
|
||||
build: impl for<'b> Fn(&'b mut DialogFields) -> ParamDialog<'b> + Send + 'static,
|
||||
) -> Self {
|
||||
let key = key.into();
|
||||
let ParamDialog { params, remember, patterns, .. } = build(&mut fields);
|
||||
let (params, patterns) = (params.into_owned(), patterns.into_owned());
|
||||
let saved = remember.and_then(|key| MemoryStage::peek_saved::<Option<DialogFields>>(ctx, &key));
|
||||
ParamDialog::open_values(¶ms, &patterns, saved.as_ref(), &mut fields);
|
||||
HostedParamDialog {
|
||||
id: dialog_id(key.as_str()),
|
||||
key,
|
||||
instance: None,
|
||||
opening: fields.clone(),
|
||||
fields,
|
||||
opened: false,
|
||||
opening: DialogFields::default(),
|
||||
build: Box::new(build),
|
||||
requests: HostRequests::new(),
|
||||
open: true,
|
||||
@@ -828,11 +832,12 @@ impl HostedParamDialog {
|
||||
/// A hosted command form: the same as [`new`](HostedParamDialog::new), with `build` making a
|
||||
/// [`ParamDialog::command`].
|
||||
pub fn command(
|
||||
ctx: &Context,
|
||||
key: impl Into<String>,
|
||||
fields: DialogFields,
|
||||
build: impl for<'b> Fn(&'b mut DialogFields) -> ParamDialog<'b> + Send + 'static,
|
||||
) -> Self {
|
||||
Self::new(key, fields, build)
|
||||
Self::new(ctx, key, fields, build)
|
||||
}
|
||||
|
||||
/// Names this dialog among others made with the same key (one per document, say), so they keep separate state.
|
||||
@@ -989,32 +994,23 @@ impl HostedParamDialog {
|
||||
pub fn cancel_requests(&mut self) {
|
||||
self.requests.cancel();
|
||||
}
|
||||
|
||||
/// Opens the values once, as a `ParamDialog`'s first pass does, before the first show, OK or set reads them.
|
||||
fn open(&mut self, ctx: &Context) {
|
||||
if std::mem::replace(&mut self.opened, true) {
|
||||
return;
|
||||
}
|
||||
let ParamDialog { params, remember, patterns, .. } = (self.build)(&mut self.fields);
|
||||
let (params, patterns) = (params.into_owned(), patterns.into_owned());
|
||||
let saved = remember.and_then(|key| MemoryStage::peek_saved::<Option<DialogFields>>(ctx, &key));
|
||||
ParamDialog::open_values(¶ms, &patterns, saved.as_ref(), &mut self.fields);
|
||||
self.opening = self.fields.clone();
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks `value` against the row `field` of `params` and sets it in `fields`, as the user editing the row would; `Err`
|
||||
/// says why the row refused (`FieldRefusal`). The field is a row's key or its unit key; a Files row takes a
|
||||
/// `{files, folder, useFolder}` object and sets its two companion keys with it. Every dialog built on `Param`s sets
|
||||
/// its fields through this one rule.
|
||||
/// says why the row refused (`FieldRefusal`). The field is a row's key, its unit key or a custom row's companion key
|
||||
/// ([`Param::companions`]); a Files row takes a `{files, folder, useFolder}` object and sets its two companion keys with
|
||||
/// it. Every dialog built on `Param`s sets its fields through this one rule.
|
||||
pub fn set_param_field(params: &[Param], fields: &mut DialogFields, field: &str, value: Value) -> Result<(), String> {
|
||||
let Some(param) = params.iter().find(|param| param.key == field || param.unit_key() == Some(field)) else {
|
||||
let companion = |param: &Param| matches!(¶m.kind, ParamKind::Custom(row) if row.has_companion(field));
|
||||
let Some(param) = params.iter().find(|param| param.key == field || param.unit_key() == Some(field) || companion(param)) else {
|
||||
return Err(FieldRefusal::Unknown.message(field));
|
||||
};
|
||||
if !param.visible(fields) || !param.enabled(fields) {
|
||||
return Err(FieldRefusal::Inactive.message(field));
|
||||
}
|
||||
let writes = if param.key != field {
|
||||
let writes = if companion(param) {
|
||||
Some(vec![(field.to_owned(), Some(FieldValue::Json(value.clone())).filter(|_| !value.is_null()))])
|
||||
} else if param.key != field {
|
||||
value.as_str().map(|unit| vec![(field.to_owned(), Some(FieldValue::Text(unit.to_owned())))])
|
||||
} else if matches!(param.kind, ParamKind::Files { .. }) {
|
||||
read_files(param, &value)
|
||||
@@ -1081,7 +1077,6 @@ impl StackDialog for HostedParamDialog {
|
||||
fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option<DialogResult<ParamResult>> {
|
||||
let measuring = crate::runtime::measure::active(ui.ctx());
|
||||
let answers = if measuring { Vec::new() } else { self.requests.take_answers() };
|
||||
self.open(ui.ctx());
|
||||
let finish = self.held.as_ref().is_some_and(|held| held.accepted);
|
||||
// A measuring run keeps the centre: the real run of the pass takes it.
|
||||
let centre = if measuring { self.centre } else { self.centre.take() };
|
||||
@@ -1152,8 +1147,7 @@ impl StackDialog for HostedParamDialog {
|
||||
/// Answers OK as the button does: none while OK is disabled. The result keeps what a remembering dialog saves. A
|
||||
/// held dialog files the answer for the host, as its button does, and answers none; once the host accepted the
|
||||
/// held answer, it answers that.
|
||||
fn confirm(&mut self, ctx: &Context) -> Option<ParamResult> {
|
||||
self.open(ctx);
|
||||
fn confirm(&mut self, _: &Context) -> Option<ParamResult> {
|
||||
if self.held.as_ref().is_some_and(|held| held.accepted) {
|
||||
return self.held.take().map(|held| held.result);
|
||||
}
|
||||
@@ -1181,8 +1175,7 @@ impl StackDialog for HostedParamDialog {
|
||||
|
||||
/// Keeps `value` when the row `field` names (a parameter or its unit choice) is shown, takes input, and takes
|
||||
/// the value ([`set_param_field`]).
|
||||
fn set_json_field(&mut self, ctx: &Context, field: &str, value: Value) -> Result<(), String> {
|
||||
self.open(ctx);
|
||||
fn set_json_field(&mut self, _: &Context, field: &str, value: Value) -> Result<(), String> {
|
||||
let params = (self.build)(&mut self.fields).params.into_owned();
|
||||
let before = self.fields.clone();
|
||||
set_param_field(¶ms, &mut self.fields, field, value)?;
|
||||
|
||||
@@ -85,7 +85,7 @@ const REFUSAL: &str = "The radius is too large for this layer.";
|
||||
fn hosted_param_dialog_with_a_refused_ok(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let ctx = ui.ctx().clone();
|
||||
let open = move || {
|
||||
let mut dialog = HostedParamDialog::new("blur", DialogFields::new(), |fields| {
|
||||
let mut dialog = HostedParamDialog::new(&ctx, "blur", DialogFields::new(), |fields| {
|
||||
ParamDialog::new("blur", "Blur", Param::parse_list(SPEC)).values(Bind::bound(fields))
|
||||
})
|
||||
.held_ok();
|
||||
|
||||
@@ -719,14 +719,15 @@ fn jpeg_params(words: &FormatOptionsWords, options: JpegOptions) -> Vec<Param> {
|
||||
vec![
|
||||
Param::section(words.image_options.clone()),
|
||||
Param::custom(QUALITY, words.quality.clone(), move |ui, fields, _| quality_rows(ui, fields, &quality_name, &preset_name, &presets, start))
|
||||
.opens_with(FieldValue::Int(i64::from(start)))
|
||||
.full_width(),
|
||||
Param::new(FORMAT, words.format_options.clone(), ParamKind::radio(formats, Some(options.format.id().to_owned()))),
|
||||
]
|
||||
}
|
||||
|
||||
/// The quality in `fields`, else `start`, the quality the dialog opened with.
|
||||
/// The quality in `fields`, in whatever form it was set, else `start`, the quality the dialog opened with.
|
||||
fn quality_of(fields: &DialogFields, start: u8) -> u8 {
|
||||
fields.int(QUALITY).map_or(start, |quality| quality.clamp(0, i64::from(MAX_QUALITY)) as u8)
|
||||
fields.number(QUALITY).filter(|quality| quality.is_finite()).map_or(start, |quality| quality.round().clamp(0.0, f64::from(MAX_QUALITY)) as u8)
|
||||
}
|
||||
|
||||
/// The quality rows: the field named `name` and the preset list on one line, the slider across the form under them.
|
||||
|
||||
@@ -129,10 +129,14 @@ impl DialogFields {
|
||||
self.values.contains_key(key)
|
||||
}
|
||||
|
||||
// The scalar readers also read the `Json` form of their value, which automation stores for a custom row's keys
|
||||
// (`Param::custom`): one read whatever form the value was set in.
|
||||
|
||||
/// `Bool`, else `None`.
|
||||
pub fn bool(&self, key: &str) -> Option<bool> {
|
||||
match self.values.get(key)? {
|
||||
FieldValue::Bool(b) => Some(*b),
|
||||
FieldValue::Json(value) => value.as_bool(),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -142,15 +146,18 @@ impl DialogFields {
|
||||
match self.values.get(key)? {
|
||||
FieldValue::Number(n) => Some(*n),
|
||||
FieldValue::Int(i) => Some(*i as f64),
|
||||
FieldValue::Json(value) => value.as_f64(),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// `Int`, or a whole `Number`.
|
||||
pub fn int(&self, key: &str) -> Option<i64> {
|
||||
let whole = |n: f64| (n.fract() == 0.0 && n.abs() < 9.0e15).then_some(n as i64);
|
||||
match self.values.get(key)? {
|
||||
FieldValue::Int(i) => Some(*i),
|
||||
FieldValue::Number(n) if n.fract() == 0.0 && n.abs() < 9.0e15 => Some(*n as i64),
|
||||
FieldValue::Number(n) => whole(*n),
|
||||
FieldValue::Json(value) => value.as_i64().or_else(|| value.as_f64().and_then(whole)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -159,6 +166,7 @@ impl DialogFields {
|
||||
pub fn text(&self, key: &str) -> Option<&str> {
|
||||
match self.values.get(key)? {
|
||||
FieldValue::Text(s) => Some(s),
|
||||
FieldValue::Json(value) => value.as_str(),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -188,14 +196,18 @@ impl DialogFields {
|
||||
}
|
||||
|
||||
/// A `List`, or a `Grid`, `Point` or `Color` as the list of its numbers (the shapes an
|
||||
/// untagged read gives a stored list of numbers, and an empty list). The key may have no
|
||||
/// parameter row: a host keeps its own data under it (a key without a row is not remembered).
|
||||
/// untagged read gives a stored list of numbers, and an empty list), or a `Json` array read as
|
||||
/// those values. The key may have no parameter row: a host keeps its own data under it (a key
|
||||
/// without a row is not remembered).
|
||||
pub fn list(&self, key: &str) -> Option<Cow<'_, [FieldValue]>> {
|
||||
Some(match self.values.get(key)? {
|
||||
FieldValue::List(items) => Cow::Borrowed(items.as_slice()),
|
||||
FieldValue::Grid(cells) => Cow::Owned(cells.iter().map(|c| FieldValue::Int(*c)).collect()),
|
||||
FieldValue::Point(p) => Cow::Owned(p.iter().map(|n| FieldValue::Number(*n)).collect()),
|
||||
FieldValue::Color(c) => Cow::Owned(c.iter().map(|n| FieldValue::Number(f64::from(*n))).collect()),
|
||||
FieldValue::Json(serde_json::Value::Array(items)) => {
|
||||
Cow::Owned(items.iter().map(|item| serde_json::from_value(item.clone())).collect::<Result<_, _>>().ok()?)
|
||||
}
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -145,7 +145,7 @@ pub enum ParamKind {
|
||||
/// The text shown; line breaks start new lines.
|
||||
text: Label,
|
||||
},
|
||||
/// A row the host draws: see [`Param::custom`]. It has no value of its own.
|
||||
/// A row the host draws: see [`Param::custom`]. Its value and its companions' are what `draw` keeps.
|
||||
Custom(CustomRow),
|
||||
/// A select of blend modes, each with the Shift+Alt key that picks it.
|
||||
#[non_exhaustive]
|
||||
@@ -288,7 +288,8 @@ impl ParamKind {
|
||||
}
|
||||
ParamKind::Pattern { default } => FieldValue::Text(default.clone()?),
|
||||
ParamKind::Files { open_files, .. } => path_list(open_files),
|
||||
ParamKind::ReadOnlyText { .. } | ParamKind::Custom(_) | ParamKind::Section => return None,
|
||||
ParamKind::Custom(row) => row.opens_with.clone()?,
|
||||
ParamKind::ReadOnlyText { .. } | ParamKind::Section => return None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -316,7 +317,8 @@ impl ParamKind {
|
||||
(ParamKind::Channel { names, .. }, FieldValue::Int(i)) => usize::try_from(*i).is_ok_and(|i| i < names.len()),
|
||||
(ParamKind::Text { .. }, FieldValue::Text(_)) => true,
|
||||
(ParamKind::OptionalNumber { min, max, .. }, v) => number(v).is_some_and(|n| n.is_finite() && n >= *min && n <= *max),
|
||||
(ParamKind::Custom(_), FieldValue::Json(_)) => true,
|
||||
// A custom row keeps whatever its `draw` writes.
|
||||
(ParamKind::Custom(_), _) => true,
|
||||
(ParamKind::Blend { modes, .. }, FieldValue::Text(id)) => modes.iter().any(|(entry, _)| entry.key == *id),
|
||||
(ParamKind::Pattern { .. }, FieldValue::Text(_)) => true,
|
||||
(ParamKind::Files { .. }, v) => is_path_list(v),
|
||||
@@ -328,31 +330,43 @@ impl ParamKind {
|
||||
type CustomDraw = dyn Fn(&mut Ui, &mut DialogFields, &mut CustomContext) -> Response + Send + Sync;
|
||||
|
||||
/// What draws a [`ParamKind::Custom`] row: it gets the row's control cell, the form's values and the row's
|
||||
/// [`CustomContext`], and returns the response the row label names. Equal only to itself.
|
||||
/// [`CustomContext`], and returns the response the row label names. Besides the row's own key, `draw` may keep values
|
||||
/// under its companion keys ([`Param::companions`]). Equal only to a clone of itself with the same value and companions.
|
||||
#[derive(Clone)]
|
||||
pub struct CustomRow(Arc<CustomDraw>);
|
||||
pub struct CustomRow {
|
||||
draw: Arc<CustomDraw>,
|
||||
/// The value the row's key opens with ([`Param::opens_with`]).
|
||||
opens_with: Option<FieldValue>,
|
||||
/// The other keys `draw` keeps values under.
|
||||
companions: Vec<String>,
|
||||
}
|
||||
|
||||
impl CustomRow {
|
||||
/// Wraps `draw`, which draws the row and edits the values it owns through the [`DialogFields`].
|
||||
pub fn new(draw: impl Fn(&mut Ui, &mut DialogFields, &mut CustomContext) -> Response + Send + Sync + 'static) -> Self {
|
||||
Self(Arc::new(draw))
|
||||
Self { draw: Arc::new(draw), opens_with: None, companions: Vec::new() }
|
||||
}
|
||||
|
||||
/// Draws the row.
|
||||
pub(crate) fn draw(&self, ui: &mut Ui, fields: &mut DialogFields, context: &mut CustomContext) -> Response {
|
||||
(self.0)(ui, fields, context)
|
||||
(self.draw)(ui, fields, context)
|
||||
}
|
||||
|
||||
/// Whether `key` is one of the row's companion keys.
|
||||
pub(crate) fn has_companion(&self, key: &str) -> bool {
|
||||
self.companions.iter().any(|companion| companion == key)
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for CustomRow {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str("CustomRow")
|
||||
f.debug_struct("CustomRow").field("opens_with", &self.opens_with).field("companions", &self.companions).finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for CustomRow {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
Arc::ptr_eq(&self.0, &other.0)
|
||||
Arc::ptr_eq(&self.draw, &other.draw) && self.opens_with == other.opens_with && self.companions == other.companions
|
||||
}
|
||||
}
|
||||
|
||||
@@ -591,8 +605,10 @@ impl Param {
|
||||
}
|
||||
|
||||
/// A row the host draws. `draw` gets the control cell, the form's values and the row's [`CustomContext`] (to ask
|
||||
/// for the host's colour picker); the row label names the response it returns. The row has no default and
|
||||
/// nothing remembered; `draw` reads and writes [`DialogFields`] under whatever keys it likes.
|
||||
/// for the host's colour picker); the row label names the response it returns. Nothing of the row is remembered;
|
||||
/// it opens with no value unless [`opens_with`](Param::opens_with) gives one. `draw` reads and writes the
|
||||
/// [`DialogFields`] under its key and the keys [`companions`](Param::companions) declares; automation
|
||||
/// (`set_json_field`) sets any of those keys to a JSON value, kept as [`FieldValue::Json`] (`null` removes it).
|
||||
pub fn custom(
|
||||
key: impl Into<String>,
|
||||
label: impl Into<Label>,
|
||||
@@ -601,6 +617,25 @@ impl Param {
|
||||
Self::new(key, label, ParamKind::Custom(CustomRow::new(draw)))
|
||||
}
|
||||
|
||||
/// The value a [`Param::custom`] row's key opens with, as another row opens with its default. Other rows ignore it.
|
||||
#[must_use]
|
||||
pub fn opens_with(mut self, value: impl Into<FieldValue>) -> Self {
|
||||
if let ParamKind::Custom(row) = &mut self.kind {
|
||||
row.opens_with = Some(value.into());
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// The other keys a [`Param::custom`] row keeps values under (Color Lookup's `file` beside its `lut`), so automation
|
||||
/// sets them as it sets the row's own key. Other rows ignore it.
|
||||
#[must_use]
|
||||
pub fn companions(mut self, keys: impl IntoIterator<Item = impl Into<String>>) -> Self {
|
||||
if let ParamKind::Custom(row) = &mut self.kind {
|
||||
row.companions.extend(keys.into_iter().map(Into::into));
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// A row of read-only `text` beside the label, wrapped to the form's width: the user can select and copy it, and
|
||||
/// Tab passes over it. It has no value, so nothing is remembered or in the result. With
|
||||
/// [`full_width`](Param::full_width) it has no label and spans the form (a note over the rows).
|
||||
@@ -792,12 +827,15 @@ impl Param {
|
||||
!self.option().not_remembered
|
||||
}
|
||||
|
||||
/// Whether `value` is one the field `key` of this row can hold: the row's own value, or the unit id of a row with
|
||||
/// units.
|
||||
/// Whether `value` is one the field `key` of this row can hold: the row's own value, the unit id of a row with
|
||||
/// units, a Files row's companions, or a custom row's companion.
|
||||
pub fn accepts(&self, key: &str, value: &FieldValue) -> bool {
|
||||
if self.key == key {
|
||||
return self.kind.fits(value) && self.option_allowed(value);
|
||||
}
|
||||
if let ParamKind::Custom(row) = &self.kind {
|
||||
return row.has_companion(key);
|
||||
}
|
||||
if matches!(self.kind, ParamKind::Files { .. }) {
|
||||
return match value {
|
||||
FieldValue::Text(_) => key == self.folder_key(),
|
||||
|
||||
@@ -141,7 +141,7 @@ const REFUSED: &str = "The radius is too large for this layer.";
|
||||
fn a_held_ok_refused_keeps_the_dialog_open_and_an_accepted_one_closes() {
|
||||
let (host, twice) = (Rc::new(RefCell::new(DialogHost::new())), Rc::new(Cell::new(false)));
|
||||
let mut fixture = host_fixture(&host, &twice);
|
||||
host.borrow_mut().open(HostedParamDialog::new("blur", DialogFields::new(), blur).held_ok());
|
||||
host.borrow_mut().open(HostedParamDialog::new(fixture.ctx(), "blur", DialogFields::new(), blur).held_ok());
|
||||
fixture.idle(10);
|
||||
|
||||
twice.set(true);
|
||||
@@ -190,14 +190,14 @@ fn a_hosted_dialog_reopened_under_the_same_key_opens() {
|
||||
host.run(ui);
|
||||
if let Some(result) = host.take::<HostedParamDialog>() {
|
||||
if again.replace(false) {
|
||||
host.open(HostedParamDialog::new("blur", DialogFields::new(), blur));
|
||||
host.open(HostedParamDialog::new(ui.ctx(), "blur", DialogFields::new(), blur));
|
||||
} else {
|
||||
*out.borrow_mut() = Some(result);
|
||||
}
|
||||
}
|
||||
});
|
||||
fixture.room(Vec2::new(1200.0, 900.0));
|
||||
host.borrow_mut().open(HostedParamDialog::new("blur", DialogFields::new(), blur));
|
||||
host.borrow_mut().open(HostedParamDialog::new(fixture.ctx(), "blur", DialogFields::new(), blur));
|
||||
fixture.idle(10);
|
||||
fixture.key(Key::Escape, Modifiers::NONE).idle(10);
|
||||
assert!(!reopen.get(), "Escape closed the first dialog");
|
||||
@@ -224,7 +224,7 @@ fn folder_value(folder: &str) -> serde_json::Value {
|
||||
fn a_hosted_dialogs_new_requests_come_once_and_a_cancel_drops_them() {
|
||||
let (host, twice) = (Rc::new(RefCell::new(DialogHost::new())), Rc::new(Cell::new(false)));
|
||||
let mut fixture = host_fixture(&host, &twice);
|
||||
host.borrow_mut().open(HostedParamDialog::new("stack", DialogFields::new(), stack_dialog));
|
||||
host.borrow_mut().open(HostedParamDialog::new(fixture.ctx(), "stack", DialogFields::new(), stack_dialog));
|
||||
fixture.idle(10);
|
||||
|
||||
let save = fixture.by_label("Save…").expect("the Save… button");
|
||||
@@ -264,7 +264,7 @@ fn brush_tip(fields: &mut DialogFields) -> ParamDialog<'_> {
|
||||
fn a_disabled_radio_option_is_greyed_and_refused() {
|
||||
let (host, twice) = (Rc::new(RefCell::new(DialogHost::new())), Rc::new(Cell::new(false)));
|
||||
let mut fixture = host_fixture(&host, &twice);
|
||||
host.borrow_mut().open(HostedParamDialog::new("brush", DialogFields::new(), brush_tip));
|
||||
host.borrow_mut().open(HostedParamDialog::new(fixture.ctx(), "brush", DialogFields::new(), brush_tip));
|
||||
fixture.idle(10);
|
||||
let shape = || on_dialog(&host, |dialog| dialog.fields().text("shape").map(str::to_owned)).flatten();
|
||||
|
||||
@@ -330,7 +330,7 @@ fn a_remembered_value_its_row_refuses_opens_as_the_default() {
|
||||
fixture.room(Vec2::new(1200.0, 900.0));
|
||||
let ctx = fixture.ctx().clone();
|
||||
|
||||
host.borrow_mut().open(HostedParamDialog::new("filter", DialogFields::new(), wide_filter));
|
||||
host.borrow_mut().open(HostedParamDialog::new(fixture.ctx(), "filter", DialogFields::new(), wide_filter));
|
||||
fixture.idle(4);
|
||||
let values =
|
||||
[("radius", json!(80.0)), ("method", json!("twist")), ("edge", json!("repeat")), ("pattern", json!("stripes")), ("smooth", json!(true))];
|
||||
@@ -340,7 +340,7 @@ fn a_remembered_value_its_row_refuses_opens_as_the_default() {
|
||||
assert!(host.borrow_mut().confirm::<HostedParamDialog>(&ctx), "OK answers");
|
||||
fixture.idle(2);
|
||||
|
||||
host.borrow_mut().open(HostedParamDialog::new("filter", DialogFields::new(), narrow_filter));
|
||||
host.borrow_mut().open(HostedParamDialog::new(fixture.ctx(), "filter", DialogFields::new(), narrow_filter));
|
||||
fixture.idle(4);
|
||||
let fields = host.borrow().get::<HostedParamDialog>().map(|dialog| dialog.fields().clone()).expect("the next version is open");
|
||||
assert_eq!(fields.bool("smooth"), Some(true), "a value its row still takes opens as remembered");
|
||||
@@ -422,7 +422,12 @@ fn a_previewed_colour_shows_in_its_row_and_leaves_the_fields() {
|
||||
let (host, twice) = (Rc::new(RefCell::new(DialogHost::new())), Rc::new(Cell::new(false)));
|
||||
let mut fixture = host_fixture(&host, &twice);
|
||||
let (red, blue) = (craft_theme::Srgba::new(1.0, 0.0, 0.0, 1.0), craft_theme::Srgba::new(0.0, 0.0, 1.0, 1.0));
|
||||
host.borrow_mut().open(HostedParamDialog::new("tint", DialogFields::from_pairs([("tint", FieldValue::Color([0.0, 0.0, 1.0]))]), tint));
|
||||
host.borrow_mut().open(HostedParamDialog::new(
|
||||
fixture.ctx(),
|
||||
"tint",
|
||||
DialogFields::from_pairs([("tint", FieldValue::Color([0.0, 0.0, 1.0]))]),
|
||||
tint,
|
||||
));
|
||||
fixture.idle(10);
|
||||
let before = on_dialog(&host, |dialog| dialog.fields().clone()).expect("the dialog is open");
|
||||
assert!(paints(&fixture.frame_shapes(), blue.into()), "the swatch shows the stored colour");
|
||||
@@ -443,7 +448,7 @@ fn a_previewed_colour_shows_in_its_row_and_leaves_the_fields() {
|
||||
fn a_field_set_before_the_first_show_resets_to_the_opening_value() {
|
||||
let (host, twice) = (Rc::new(RefCell::new(DialogHost::new())), Rc::new(Cell::new(false)));
|
||||
let mut fixture = host_fixture(&host, &twice);
|
||||
host.borrow_mut().open(HostedParamDialog::new("blur", DialogFields::new(), blur));
|
||||
host.borrow_mut().open(HostedParamDialog::new(fixture.ctx(), "blur", DialogFields::new(), blur));
|
||||
let ctx = fixture.ctx().clone();
|
||||
host.borrow_mut().set_json_field(&ctx, dialog_id("blur"), "radius", json!(60.0)).expect("the radius row takes a number");
|
||||
fixture.idle(10);
|
||||
|
||||
Reference in New Issue
Block a user