Merge pull request #9085 from dotCooCoo/feat/plugin-slider-param

Plug-ins: a number parameter can show a slider beside its field
This commit is contained in:
BFlat
2026-11-26 16:59:14 +07:00
committed by GitHub
5 changed files with 112 additions and 3 deletions
+89 -1
View File
@@ -1,5 +1,6 @@
//! How the host's generated dialogs show a plug-in's parameters: the optional `label`, `unit`,
//! `group`, `help`, `helpUrl` and `visibleWhen` keys of each one (docs/plugins.md › Parameters).
//! `group`, `help`, `helpUrl`, `visibleWhen` and `widget` keys of each one
//! (docs/plugins.md › Parameters).
//!
//! These keys are presentation only. A host from before them ignores them, so a plug-in that
//! declares them still installs there, and a plug-in is given every parameter whether its dialog
@@ -58,6 +59,48 @@ pub struct ParamUi {
/// Shown only while each parameter named here has one of the values listed for it.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub visible_when: BTreeMap<String, Vec<Value>>,
/// The control that shows a number: [`Widget::Slider`] adds a slider beside its field.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub widget: Option<Widget>,
}
/// The control a `number` or `int` parameter's row shows besides its number field (`widget`).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum Widget {
/// A slider over `min..max`, beside the number field.
Slider,
}
/// The largest whole number an `f64` holds exactly, which bounds an `int` slider's range.
const EXACT_INT: i64 = 1 << 53;
impl ParamUi {
/// The range a slider shows `spec`'s value over, when the parameter asks for one
/// ([`Widget::Slider`]) and `spec` is a `number` or `int` the manifest checks allow it on.
pub fn slider_range(&self, spec: &ParamSpec) -> Option<std::ops::RangeInclusive<f64>> {
if self.widget != Some(Widget::Slider) {
return None;
}
match spec {
ParamSpec::Number { min, max, .. } if min < max => Some(*min..=*max),
ParamSpec::Int { min, max, .. } if min < max && -EXACT_INT <= *min && *max <= EXACT_INT => Some(*min as f64..=*max as f64),
_ => None,
}
}
/// Checks `widget` against parameter `spec`; `bad` builds the error.
fn validate_slider(&self, spec: &ParamSpec, bad: impl Fn(&str) -> Result<()>) -> Result<()> {
if self.widget.is_none() || self.slider_range(spec).is_some() {
return Ok(());
}
match spec {
ParamSpec::Number { .. } | ParamSpec::Int { .. } => {
bad(&format!("a slider needs `min` below `max`, and an `int` slider a range within ±{EXACT_INT}"))
}
_ => bad("a slider is only for `number` and `int` parameters"),
}
}
}
/// Is `s` 1 to `max` characters, not all spaces, without control characters (`\n` too, unless
@@ -86,6 +129,9 @@ impl ParamUi {
return bad(&format!("`helpUrl` must be an https:// address of at most {MAX_HELP_URL} bytes"));
}
}
if let Some((_, p)) = m.params.get(index) {
self.validate_slider(&p.spec, bad)?;
}
if self.visible_when.len() > MAX_CONDITIONS {
return bad(&format!("`visibleWhen` names at most {MAX_CONDITIONS} parameters"));
}
@@ -304,4 +350,46 @@ mod tests {
let fine = with("help", r#""Two\nlines.""#);
assert!(Manifest::parse(fine.as_bytes()).is_ok());
}
/// A `number` or `int` parameter with a range may ask for a slider; the key reads back as
/// written, and a parameter without it asks for none.
#[test]
fn slider_key_parses_and_round_trips() {
let m = Manifest::parse(
br#"{"id":"a","name":"x","kind":"filter","params":{
"area":{"type":"number","min":0,"max":100,"default":10,"widget":"slider"},
"count":{"type":"int","min":1,"max":20,"default":4,"widget":"slider"},
"plain":{"type":"number","min":0,"max":100,"default":10}}}"#,
)
.unwrap();
let (area, count, plain) = (m.param("area").unwrap(), m.param("count").unwrap(), m.param("plain").unwrap());
assert_eq!(area.ui.slider_range(&area.spec), Some(0.0..=100.0));
assert_eq!(count.ui.slider_range(&count.spec), Some(1.0..=20.0));
assert_eq!(plain.ui.slider_range(&plain.spec), None);
assert_eq!(Manifest::parse(&serde_json::to_vec(&m).unwrap()).unwrap(), m);
assert_eq!(serde_json::to_value(&m).unwrap()["params"]["count"]["widget"], json!("slider"));
}
#[test]
fn slider_keys_that_cannot_apply_are_refused() {
let param = |p: &str| format!(r#"{{"id":"a","name":"x","kind":"filter","params":{{"p":{p}}}}}"#);
for bad in [
// Only numbers have a slider, over a range that has room to move.
r#"{"type":"bool","widget":"slider"}"#,
r#"{"type":"choice","options":["a","b"],"widget":"slider"}"#,
r#"{"type":"numberList","min":0,"max":1,"widget":"slider"}"#,
r#"{"type":"number","min":5,"max":5,"default":5,"widget":"slider"}"#,
r#"{"type":"int","min":0,"max":9007199254740993,"widget":"slider"}"#,
// A control the host doesn't have.
r#"{"type":"number","min":0,"max":1,"default":0,"widget":"knob"}"#,
] {
assert!(Manifest::parse(param(bad).as_bytes()).is_err(), "{bad}");
}
// A command's parameters are checked the same way.
let command = |p: &str| format!(r#"{{"id":"a","name":"x","kind":"filter","commands":[{{"id":"go","label":"Go","params":{{"p":{p}}}}}]}}"#);
assert!(Manifest::parse(command(r#"{"type":"number","min":0,"max":1,"default":0,"widget":"slider"}"#).as_bytes()).is_ok());
assert!(Manifest::parse(command(r#"{"type":"bool","widget":"slider"}"#).as_bytes()).is_err());
let fine = param(r#"{"type":"int","min":0,"max":10,"widget":"slider"}"#);
assert!(Manifest::parse(fine.as_bytes()).is_ok());
}
}
+4 -1
View File
@@ -298,7 +298,10 @@ fn plugin_row(key: &str, p: &PluginParam) -> Param {
// there. Past it, the number typed is read as an integer.
const EXACT: i64 = 1 << 53;
let start = (*default).max(*min).min(*max);
if -EXACT <= *min && *max <= EXACT {
if let Some(range) = p.ui.slider_range(&p.spec) {
// A slider over the whole numbers of the range, as the framework's range row with no decimals.
Param::new(key, name, ParamKind::range(*range.start(), *range.end(), start as f64, SliderScale::Linear)).decimals(0)
} else if -EXACT <= *min && *max <= EXACT {
Param::new(key, name, ParamKind::int(Some(*min), Some(*max), start))
} else {
let (min, max) = (*min, *max);
@@ -87,6 +87,21 @@ fn labels_units_sections_text_and_lists_come_from_the_manifest() {
assert_eq!(rows.iter().filter(|p| p.key == "angles").count(), 1);
}
#[test]
fn a_slider_widget_makes_a_whole_number_range_row_of_an_int_parameter() {
use craft::ui::patterns::form_dialogs::ParamKind;
let manifest = r#"{"id":"test.ui.fields.slider","name":"Slide","version":"1","kind":"filter","params":{
"count":{"type":"int","min":1,"max":20,"default":4,"widget":"slider"},
"plain":{"type":"int","min":1,"max":20,"default":4}}}"#;
let parsed = vectorcraft_plugins::manifest::Manifest::parse(manifest.as_bytes()).unwrap();
let rows = super::form::plugin_params(&parsed, &Map::new());
let kind = |key: &str| &rows.iter().find(|p| p.key == key).unwrap_or_else(|| panic!("no row for {key}")).kind;
assert!(matches!(kind("count"), ParamKind::Range { min, max, .. } if (*min, *max) == (1.0, 20.0)), "an int slider is a range row");
assert!(matches!(kind("plain"), ParamKind::Int { .. }), "an int without the key stays a number field");
// The slider's value reaches the plug-in as a whole number.
assert_eq!(super::form::typed_number(7.0), json!(7));
}
#[test]
fn visible_when_shows_a_parameter_only_while_its_condition_holds() {
let id = "test.ui.fields.visible";
+3 -1
View File
@@ -740,10 +740,12 @@ declares them still installs there:
| `help` | Shows what the parameter does when the pointer rests on its label (1–1,000 characters; line breaks allowed). |
| `helpUrl` | Opens this `https://` page (at most 512 bytes) from a button after the field. |
| `visibleWhen` | `{"pattern": ["lines", "crosshatch"], "outline": [true]}` shows the parameter only while each parameter it names (a checkbox or a choice declared before it) has one of the values listed and is shown itself. |
| `widget` | `"slider"` shows an `int` parameter as a slider over `min..max` with its number field, moving by 1. A `number` parameter with `min` below `max` always shows a slider with its field, with or without the key. The key needs `min` below `max`, and an `int`'s range within ±9,007,199,254,740,992; on any other parameter, or with another value, the manifest is refused at install. |
A hidden parameter still goes to the plug-in with its value: what the dialog showed never changes a run. The
filter, live-effect and exporter dialogs use all of these keys. The Appearance panel's editor of a plug-in effect's
parameters uses `label`, `unit`, `help` and `visibleWhen`, and lists the parameters without sections or help buttons.
parameters uses `label`, `unit`, `help`, `visibleWhen` and `widget`, and lists the parameters without sections or
help buttons.
### Input
+1
View File
@@ -2701,6 +2701,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- **Importer plug-ins place their files (G17):** an importer whose manifest has `"place": true` also reads its files for File › Place, which lists them under "All placeable files" and a filter named after the importer. `file.place`, `file.place.info` and `file.place.queue` use the importer `importer` names, which must set `place`, or, for a file no built-in format reads, the first such importer by id that lists its extension. It is given at most 128 MiB of the file (a larger file is refused from its size, before any of it is read when `importer` names the importer) and `_context.mode` `"place"`, and its objects are placed as one group named after the file, in the order it returned them, at `at`, in `rect`, over the object Replace swaps or on a template layer, as one undo step, embedded whatever `link` says. A decline, invalid output, a trap or Cancel places nothing and leaves the undo steps as they were; an importer without `place` is not used by File › Place. These rules are VectorCraft's own. Regressions: `crates/engine/tests/plugin_place.rs`, `crates/plugins/src/manifest.rs`. Scores and hours unchanged.
- **Plug-in parameters as their manifest presents them (G17):** each parameter may have a `label`, a `unit` shown after its value, `help` on its label and a `helpUrl` page opened from a button, a `group` (sections that fold, after the parameters outside any group) and a `visibleWhen` that shows it only while the checkboxes and choices it names have one of the listed values (a hidden parameter still goes to the plug-in). `string` and `numberList` parameters join number, int, bool and choice, and a plug-in declares up to 256 parameters, at most 64 outside groups. The filter, live-effect and exporter dialogs use these keys, and the Appearance panel's effect editor the labels, units, help and conditions; hosts from before them ignore them. Regressions: `crates/plugins/src/dialog.rs`, `crates/plugins/src/manifest.rs`, `crates/ui-egui/src/dialogs/tests_plugin_fields.rs`, `crates/ui-egui/src/panels/appearance.rs`. Scores and hours unchanged.
- **Plug-in int parameters as sliders (G17):** an `int` parameter with `"widget": "slider"` shows a slider over its range with its number field, in the filter, live-effect and exporter dialogs and in the Appearance panel's effect editor; the manifest is refused at install when the parameter cannot have one. Regressions: `crates/plugins/src/dialog.rs`, `crates/ui-egui/src/dialogs/tests_plugin_fields.rs`. Scores and hours unchanged.
- **Live-effect plug-ins read their object's paints (G17):** a live effect is given the object's `fills` and `strokes` as a filter gets them, read only, and `_context.item` (`"object"`, or the fill or stroke whose own effects hold it); the result is cached by paint too, so a change of paint runs it again. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/plugins/src/effect.rs`. Scores and hours unchanged.
- **Live-effect plug-ins before a fill's or stroke's own 3D effect:** a live effect listed before a fill's or stroke's own Extrude & Bevel, Inflate or Rotate effect is given `_context.item` for that fill or stroke (`{"fill": i}` or `{"stroke": i}`), not `"object"`, in the drawn art, in the 3D meshes and in Expand as Wireframes; a deferred stage there is listed at that fill's or stroke's place. Regressions: `crates/effects/src/tests/solidcontext.rs`. Scores and hours unchanged.
- **Filter plug-ins set effects and stroke styles (G17):** a filter is given each object's effect records and its strokes' `join`, `cap` and `miterLimit`, and may return them; the records are admitted as `effect.apply` admits them (a known effect or installed live-effect plug-in, parameters it takes, one 3D effect that fits, no texture read from a file), and one refused refuses the output. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/plugins/src/objects/tests.rs`. Scores and hours unchanged.