node: added support for enums (#6421)

This commit is contained in:
FloVanGH 2024-10-01 14:49:39 +00:00 committed by GitHub
parent d6706494a5
commit 9d3a8c9dd2
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 68 additions and 1 deletions

View file

@ -23,6 +23,11 @@ All notable changes to this project are documented in this file.
- Bring the window to the front and focus when clicking on "Show preview" in the editor. (#196)
### Node API
- Added support for enums
## 1.8.0 - 2024-09-23
### Slint language

View file

@ -193,6 +193,7 @@ The types used for properties in .slint design markup each translate to specific
| `angle` | `Number` | The angle in degrees |
| structure | `Object` | Structures are mapped to JavaScript objects where each structure field is a property. |
| array | `Array` or any implementation of Model | |
| enumeration | `String` | The value of an enum |
### Arrays and Models

View file

@ -498,6 +498,54 @@ test("get/set brush properties", (t) => {
}
});
test("get/set enum properties", (t) => {
const compiler = new private_api.ComponentCompiler();
const definition = compiler.buildFromSource(
`export enum Direction { up, down }
export component App { in-out property <Direction> direction: up; }`,
"",
);
t.not(definition.App, null);
const instance = definition.App!.create();
t.not(instance, null);
t.is(instance!.getProperty("direction"), "up");
instance!.setProperty("direction", "down");
t.is(instance!.getProperty("direction"), "down");
t.throws(
() => {
instance!.setProperty("direction", 42);
},
{
code: "InvalidArg",
message: "expect String, got: Number",
},
);
t.throws(
() => {
instance!.setProperty("direction", { blah: "foo" });
},
{
code: "InvalidArg",
message: "expect String, got: Object",
},
);
t.throws(
() => {
instance!.setProperty("direction", "left");
},
{
code: "GenericFailure",
message: "left is not a value of enum Direction",
},
);
});
test("ArrayModel", (t) => {
const compiler = new private_api.ComponentCompiler();
const definition = compiler.buildFromSource(

View file

@ -78,6 +78,7 @@ pub fn to_js_unknown(env: &Env, value: &Value) -> Result<JsUnknown> {
model_wrapper.into_js(env)
}
}
Value::EnumerationValue(_, value) => env.create_string(value).map(|v| v.into_unknown()),
_ => env.get_undefined().map(|v| v.into_unknown()),
}
}
@ -257,7 +258,19 @@ pub fn to_value(env: &Env, unknown: JsUnknown, typ: &Type) -> Result<Value> {
Ok(Value::Model(rust_model))
}
}
Type::Enumeration(_) => todo!(),
Type::Enumeration(e) => {
let js_string: JsString = unknown.try_into()?;
let value: String = js_string.into_utf8()?.as_str()?.into();
if !e.values.contains(&value) {
return Err(napi::Error::from_reason(format!(
"{value} is not a value of enum {}",
e.name
)));
}
Ok(Value::EnumerationValue(e.name.clone(), value))
}
Type::Invalid
| Type::Model
| Type::Void