-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig.rs
More file actions
1613 lines (1454 loc) · 54.2 KB
/
Copy pathconfig.rs
File metadata and controls
1613 lines (1454 loc) · 54.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Typed schema for a node template's editable configuration.
//!
//! Replaces the opaque `serde_json::Value` the inspector used
//! previously with a strongly-typed enum so the editor (and hosts
//! that render their own inspector chrome) can match on property
//! kind, walk per-variant validation, and emit coherent patches.
//!
//! A `ConfigSchema` is just a list of [`PropertyDefinition`]s. Each
//! property declares its `key` (the field name in
//! [`NodeInstance::config`](crate::node::NodeInstance::config) — a
//! `serde_json::Value::Object`), a human-readable label, optional
//! description, and per-variant validation / defaults.
//!
//! ## Backwards compatibility
//!
//! Templates that need to ship an opaque payload (Zeal-style
//! `propertyRules`, `dataOperations`, custom rule DSLs that the
//! editor doesn't speak) can use [`PropertyDefinition::Custom`] —
//! the inspector skips its own form generation for those slots and
//! hosts render the field with their own widget.
//!
//! ## Example
//!
//! ```ignore
//! use blinc_node_editor::config::*;
//!
//! let schema = ConfigSchema::new()
//! .with_property(
//! SelectProperty::new("mode", "Mode")
//! .option("strict", "Strict")
//! .option("lenient", "Lenient")
//! .default("strict"),
//! )
//! .with_property(
//! NumberProperty::new("threshold", "Threshold")
//! .default(0.5)
//! .range(0.0, 1.0),
//! )
//! // Mode = "lenient" lowers the threshold default + clears any
//! // user-supplied strict-only field.
//! .with_rule(
//! PropertyRule::new()
//! .trigger("mode")
//! .when(Predicate::Eq { key: "mode".into(), value: serde_json::json!("lenient") })
//! .set("threshold", serde_json::json!(0.2)),
//! );
//! ```
//!
//! ## Rules engine
//!
//! Schemas carry an optional list of [`PropertyRule`]s that drive
//! reactive cascades when config values change. [`cascade_rules`]
//! applies them iteratively (up to [`MAX_RULE_CASCADE_DEPTH`]) until
//! the config stabilises. Predicates ([`Predicate`]) compose with
//! `All` / `Any` / `Not` so a rule can key off arbitrary value
//! combinations; effects ([`PropertyEffect`]) patch the config in
//! turn. Hosts subscribe to the editor's `NodeConfigChanged` event
//! to observe each cascade step.
use serde_json::{Map, Value};
/// Schema for a node template's editable configuration.
///
/// Combines a list of [`PropertyDefinition`]s (the form widgets) with
/// an optional list of [`PropertyRule`]s (reactive cascades). An
/// empty schema means the node has no editable config (no inspector
/// pane is shown).
///
/// Construct via `ConfigSchema::new().with_property(...).with_rule(...)`,
/// or convert directly from a property vector via
/// `ConfigSchema::from(vec![...])` for cases that don't need rules.
#[derive(Debug, Clone, Default)]
pub struct ConfigSchema {
/// Property definitions in render order.
pub properties: Vec<PropertyDefinition>,
/// Optional reactive cascades — fired when a property
/// matching `triggers` changes. See [`cascade_rules`].
pub rules: Vec<PropertyRule>,
}
impl ConfigSchema {
pub fn new() -> Self {
Self::default()
}
/// Append a property to the schema.
pub fn with_property(mut self, property: impl Into<PropertyDefinition>) -> Self {
self.properties.push(property.into());
self
}
/// Append a reactive rule to the schema.
pub fn with_rule(mut self, rule: PropertyRule) -> Self {
self.rules.push(rule);
self
}
/// Returns `true` when the schema has no properties — the
/// inspector treats this as "no config pane".
pub fn is_empty(&self) -> bool {
self.properties.is_empty()
}
}
impl From<Vec<PropertyDefinition>> for ConfigSchema {
fn from(properties: Vec<PropertyDefinition>) -> Self {
Self {
properties,
rules: Vec::new(),
}
}
}
// ─────────────────────────────────────────────────────────────────────
// PropertyMeta — fields common to every property variant
// ─────────────────────────────────────────────────────────────────────
/// Common metadata every [`PropertyDefinition`] carries.
///
/// `key` is the field name written into
/// [`NodeInstance::config`](crate::node::NodeInstance::config); the
/// host receives it back unchanged in
/// [`InspectorPatchRequest::path`](crate::inspector::InspectorPatchRequest).
#[derive(Debug, Clone)]
pub struct PropertyMeta {
pub key: String,
pub label: String,
pub description: Option<String>,
/// When `true` the inspector flags missing / empty values during
/// validation. Defaults to `false`.
pub required: bool,
}
impl PropertyMeta {
pub fn new(key: impl Into<String>, label: impl Into<String>) -> Self {
Self {
key: key.into(),
label: label.into(),
description: None,
required: false,
}
}
}
// ─────────────────────────────────────────────────────────────────────
// PropertyDefinition + variants
// ─────────────────────────────────────────────────────────────────────
/// A single editable field on a node template.
///
/// Variant choice maps to the widget the inspector renders. Hosts
/// that want richer types can extend via
/// [`PropertyDefinition::Custom`] and render their own form widget
/// for that field.
#[derive(Debug, Clone)]
pub enum PropertyDefinition {
Text(TextProperty),
Textarea(TextareaProperty),
Number(NumberProperty),
Boolean(BooleanProperty),
Select(SelectProperty),
Color(ColorProperty),
File(FileProperty),
CodeEditor(CodeEditorProperty),
/// Opaque JSON payload for host-rendered fields. The inspector
/// surfaces the meta (label / description) and exposes the
/// `value` to hosts via [`crate::inspector::InspectorField`] —
/// the host renders its own widget and emits patches against
/// `meta.key`.
///
/// **Default-seeding caveat**: unlike every other variant
/// (which has a separate `Option<default>` field),
/// [`PropertyDefinition::default_value`] returns
/// `Some(value.clone())` for `Custom` whenever `value` is not
/// `Value::Null`. So `Custom { ..., value: json!({...}) }`
/// will be seeded into [`default_config`] output as if the
/// payload were a default. Set `value` to `Value::Null` when
/// the field should NOT be auto-seeded, or use a different
/// variant if you need separate "schema example" + "default
/// value" semantics.
Custom {
meta: PropertyMeta,
value: Value,
},
}
impl PropertyDefinition {
/// Borrow the common metadata block.
pub fn meta(&self) -> &PropertyMeta {
match self {
Self::Text(p) => &p.meta,
Self::Textarea(p) => &p.meta,
Self::Number(p) => &p.meta,
Self::Boolean(p) => &p.meta,
Self::Select(p) => &p.meta,
Self::Color(p) => &p.meta,
Self::File(p) => &p.meta,
Self::CodeEditor(p) => &p.meta,
Self::Custom { meta, .. } => meta,
}
}
/// Convenience accessor for the property's config key.
pub fn key(&self) -> &str {
&self.meta().key
}
/// The default value for this property, if any, as a JSON value.
pub fn default_value(&self) -> Option<Value> {
match self {
Self::Text(p) => p.default.as_ref().map(|s| Value::String(s.clone())),
Self::Textarea(p) => p.default.as_ref().map(|s| Value::String(s.clone())),
Self::Number(p) => p.default.map(|n| {
serde_json::Number::from_f64(n)
.map(Value::Number)
.unwrap_or(Value::Null)
}),
Self::Boolean(p) => p.default.map(Value::Bool),
Self::Select(p) => p.default.as_ref().map(|s| Value::String(s.clone())),
Self::Color(p) => p.default.as_ref().map(|s| Value::String(s.clone())),
Self::File(p) => p.default.as_ref().map(|s| Value::String(s.clone())),
Self::CodeEditor(p) => p.default.as_ref().map(|s| Value::String(s.clone())),
Self::Custom { value, .. } => {
if value.is_null() {
None
} else {
Some(value.clone())
}
}
}
}
}
// ─── Text ──────────────────────────────────────────────────────────────
/// Single-line text field. Renders to a `text_input`.
#[derive(Debug, Clone)]
pub struct TextProperty {
pub meta: PropertyMeta,
pub default: Option<String>,
pub placeholder: Option<String>,
pub max_length: Option<usize>,
}
impl TextProperty {
pub fn new(key: impl Into<String>, label: impl Into<String>) -> Self {
Self {
meta: PropertyMeta::new(key, label),
default: None,
placeholder: None,
max_length: None,
}
}
pub fn description(mut self, text: impl Into<String>) -> Self {
self.meta.description = Some(text.into());
self
}
pub fn required(mut self, required: bool) -> Self {
self.meta.required = required;
self
}
pub fn default(mut self, value: impl Into<String>) -> Self {
self.default = Some(value.into());
self
}
pub fn placeholder(mut self, text: impl Into<String>) -> Self {
self.placeholder = Some(text.into());
self
}
pub fn max_length(mut self, n: usize) -> Self {
self.max_length = Some(n);
self
}
}
impl From<TextProperty> for PropertyDefinition {
fn from(p: TextProperty) -> Self {
Self::Text(p)
}
}
// ─── Textarea ─────────────────────────────────────────────────────────
/// Multi-line text field. Renders to a `text_area`.
#[derive(Debug, Clone)]
pub struct TextareaProperty {
pub meta: PropertyMeta,
pub default: Option<String>,
pub placeholder: Option<String>,
/// Visible row count hint for the renderer. `None` lets the
/// inspector pick.
pub rows: Option<u32>,
}
impl TextareaProperty {
pub fn new(key: impl Into<String>, label: impl Into<String>) -> Self {
Self {
meta: PropertyMeta::new(key, label),
default: None,
placeholder: None,
rows: None,
}
}
pub fn description(mut self, text: impl Into<String>) -> Self {
self.meta.description = Some(text.into());
self
}
pub fn required(mut self, required: bool) -> Self {
self.meta.required = required;
self
}
pub fn default(mut self, value: impl Into<String>) -> Self {
self.default = Some(value.into());
self
}
pub fn placeholder(mut self, text: impl Into<String>) -> Self {
self.placeholder = Some(text.into());
self
}
pub fn rows(mut self, n: u32) -> Self {
self.rows = Some(n);
self
}
}
impl From<TextareaProperty> for PropertyDefinition {
fn from(p: TextareaProperty) -> Self {
Self::Textarea(p)
}
}
// ─── Number ───────────────────────────────────────────────────────────
/// Numeric field. Renders to a `number_input` (or slider, if a
/// finite range is given). Set [`integer`](Self::integer) to clamp
/// to integers; otherwise the field accepts decimals.
#[derive(Debug, Clone)]
pub struct NumberProperty {
pub meta: PropertyMeta,
pub default: Option<f64>,
pub min: Option<f64>,
pub max: Option<f64>,
pub step: Option<f64>,
/// Constrain to integer values. Defaults to `false`.
pub integer: bool,
/// Optional unit suffix surfaced next to the input (e.g. "ms",
/// "px", "%"). Editor convention — hosts can ignore.
pub unit: Option<String>,
}
impl NumberProperty {
pub fn new(key: impl Into<String>, label: impl Into<String>) -> Self {
Self {
meta: PropertyMeta::new(key, label),
default: None,
min: None,
max: None,
step: None,
integer: false,
unit: None,
}
}
pub fn description(mut self, text: impl Into<String>) -> Self {
self.meta.description = Some(text.into());
self
}
pub fn required(mut self, required: bool) -> Self {
self.meta.required = required;
self
}
pub fn default(mut self, value: f64) -> Self {
self.default = Some(value);
self
}
pub fn min(mut self, value: f64) -> Self {
self.min = Some(value);
self
}
pub fn max(mut self, value: f64) -> Self {
self.max = Some(value);
self
}
pub fn range(self, min: f64, max: f64) -> Self {
self.min(min).max(max)
}
pub fn step(mut self, value: f64) -> Self {
self.step = Some(value);
self
}
pub fn integer(mut self) -> Self {
self.integer = true;
self
}
pub fn unit(mut self, suffix: impl Into<String>) -> Self {
self.unit = Some(suffix.into());
self
}
}
impl From<NumberProperty> for PropertyDefinition {
fn from(p: NumberProperty) -> Self {
Self::Number(p)
}
}
// ─── Boolean ──────────────────────────────────────────────────────────
/// Boolean toggle. Renders to a switch / checkbox.
#[derive(Debug, Clone)]
pub struct BooleanProperty {
pub meta: PropertyMeta,
pub default: Option<bool>,
}
impl BooleanProperty {
pub fn new(key: impl Into<String>, label: impl Into<String>) -> Self {
Self {
meta: PropertyMeta::new(key, label),
default: None,
}
}
pub fn description(mut self, text: impl Into<String>) -> Self {
self.meta.description = Some(text.into());
self
}
pub fn required(mut self, required: bool) -> Self {
self.meta.required = required;
self
}
pub fn default(mut self, value: bool) -> Self {
self.default = Some(value);
self
}
}
impl From<BooleanProperty> for PropertyDefinition {
fn from(p: BooleanProperty) -> Self {
Self::Boolean(p)
}
}
// ─── Select ───────────────────────────────────────────────────────────
/// Enumerated value picked from a fixed option list. Renders to a
/// radio group / select / dropdown depending on inspector chrome.
#[derive(Debug, Clone)]
pub struct SelectProperty {
pub meta: PropertyMeta,
pub default: Option<String>,
pub options: Vec<SelectOption>,
/// When `true`, the selected value is a JSON array of option
/// values rather than a single string. Defaults to `false`.
pub multiple: bool,
}
impl SelectProperty {
pub fn new(key: impl Into<String>, label: impl Into<String>) -> Self {
Self {
meta: PropertyMeta::new(key, label),
default: None,
options: Vec::new(),
multiple: false,
}
}
pub fn description(mut self, text: impl Into<String>) -> Self {
self.meta.description = Some(text.into());
self
}
pub fn required(mut self, required: bool) -> Self {
self.meta.required = required;
self
}
pub fn default(mut self, value: impl Into<String>) -> Self {
self.default = Some(value.into());
self
}
pub fn multiple(mut self) -> Self {
self.multiple = true;
self
}
pub fn option(mut self, value: impl Into<String>, label: impl Into<String>) -> Self {
self.options.push(SelectOption {
value: value.into(),
label: label.into(),
});
self
}
}
impl From<SelectProperty> for PropertyDefinition {
fn from(p: SelectProperty) -> Self {
Self::Select(p)
}
}
/// A single entry in a [`SelectProperty`].
#[derive(Debug, Clone)]
pub struct SelectOption {
/// Stored in `NodeInstance::config` under the property's key.
pub value: String,
/// Shown to the user.
pub label: String,
}
// ─── Color ────────────────────────────────────────────────────────────
/// Colour picker. Stored as a hex string ("#rrggbb" or "#rrggbbaa").
#[derive(Debug, Clone)]
pub struct ColorProperty {
pub meta: PropertyMeta,
pub default: Option<String>,
/// When `true` the picker exposes an alpha channel. Defaults to
/// `false`.
pub with_alpha: bool,
}
impl ColorProperty {
pub fn new(key: impl Into<String>, label: impl Into<String>) -> Self {
Self {
meta: PropertyMeta::new(key, label),
default: None,
with_alpha: false,
}
}
pub fn description(mut self, text: impl Into<String>) -> Self {
self.meta.description = Some(text.into());
self
}
pub fn required(mut self, required: bool) -> Self {
self.meta.required = required;
self
}
pub fn default(mut self, hex: impl Into<String>) -> Self {
self.default = Some(hex.into());
self
}
pub fn with_alpha(mut self) -> Self {
self.with_alpha = true;
self
}
}
impl From<ColorProperty> for PropertyDefinition {
fn from(p: ColorProperty) -> Self {
Self::Color(p)
}
}
// ─── File ─────────────────────────────────────────────────────────────
/// File path / upload picker. Stored as a string (host-defined —
/// path, URL, content URI).
#[derive(Debug, Clone)]
pub struct FileProperty {
pub meta: PropertyMeta,
pub default: Option<String>,
/// Suggested file extensions (no leading dot) e.g.
/// `["png", "jpg", "svg"]`. Advisory — hosts MAY enforce.
pub accept: Vec<String>,
}
impl FileProperty {
pub fn new(key: impl Into<String>, label: impl Into<String>) -> Self {
Self {
meta: PropertyMeta::new(key, label),
default: None,
accept: Vec::new(),
}
}
pub fn description(mut self, text: impl Into<String>) -> Self {
self.meta.description = Some(text.into());
self
}
pub fn required(mut self, required: bool) -> Self {
self.meta.required = required;
self
}
pub fn default(mut self, path: impl Into<String>) -> Self {
self.default = Some(path.into());
self
}
pub fn accept<I, S>(mut self, exts: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.accept = exts.into_iter().map(Into::into).collect();
self
}
}
impl From<FileProperty> for PropertyDefinition {
fn from(p: FileProperty) -> Self {
Self::File(p)
}
}
// ─── CodeEditor ───────────────────────────────────────────────────────
/// Multi-line code editor with an optional language hint. Stored as
/// a string.
#[derive(Debug, Clone)]
pub struct CodeEditorProperty {
pub meta: PropertyMeta,
pub default: Option<String>,
/// Language tag for syntax highlighting (e.g. `"rust"`,
/// `"javascript"`, `"sql"`, `"json"`, `"yaml"`). The inspector
/// passes this to the host's code widget; the editor itself
/// doesn't interpret it.
pub language: Option<String>,
/// Show line numbers in the gutter. Defaults to `true`.
pub line_numbers: bool,
/// Soft-wrap long lines. Defaults to `false`.
pub line_wrap: bool,
}
impl CodeEditorProperty {
pub fn new(key: impl Into<String>, label: impl Into<String>) -> Self {
Self {
meta: PropertyMeta::new(key, label),
default: None,
language: None,
line_numbers: true,
line_wrap: false,
}
}
pub fn description(mut self, text: impl Into<String>) -> Self {
self.meta.description = Some(text.into());
self
}
pub fn required(mut self, required: bool) -> Self {
self.meta.required = required;
self
}
pub fn default(mut self, source: impl Into<String>) -> Self {
self.default = Some(source.into());
self
}
pub fn language(mut self, tag: impl Into<String>) -> Self {
self.language = Some(tag.into());
self
}
pub fn line_numbers(mut self, on: bool) -> Self {
self.line_numbers = on;
self
}
pub fn line_wrap(mut self, on: bool) -> Self {
self.line_wrap = on;
self
}
}
impl From<CodeEditorProperty> for PropertyDefinition {
fn from(p: CodeEditorProperty) -> Self {
Self::CodeEditor(p)
}
}
// ─────────────────────────────────────────────────────────────────────
// Defaults + validation
// ─────────────────────────────────────────────────────────────────────
/// Build the initial config object for a template — every property
/// with a declared default lands at its `key` in the resulting JSON
/// object. Properties without defaults are omitted (host can decide
/// whether to seed them as `null` or skip until first user edit).
/// Cascading rules run once over the seeded values so the initial
/// config already reflects any rule-driven defaults.
///
/// Returns `Value::Object({})` for an empty schema.
pub fn default_config(schema: &ConfigSchema) -> Value {
let mut map = Map::new();
for prop in &schema.properties {
if let Some(v) = prop.default_value() {
map.insert(prop.meta().key.clone(), v);
}
}
let mut config = Value::Object(map);
if !schema.rules.is_empty() {
let trigger_keys: Vec<String> = schema
.properties
.iter()
.map(|p| p.meta().key.clone())
.collect();
cascade_rules(&schema.rules, &mut config, &trigger_keys);
}
config
}
/// A single validation issue found by [`validate`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ValidationIssue {
/// The property `key` that failed.
pub key: String,
/// Human-readable message.
pub message: String,
pub severity: IssueSeverity,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IssueSeverity {
/// Renderer surfaces with an error glyph; host should treat as
/// invalid.
Error,
/// Renderer surfaces with a warning glyph; node is still
/// considered usable.
Warning,
}
/// Walk a schema against a current config and surface issues:
/// missing required values, out-of-range numbers, select values
/// outside the declared option list, duplicate keys in the schema
/// itself. The inspector renders error chips next to offending
/// fields; hosts can also block "save" on `Error`-level issues.
pub fn validate(schema: &ConfigSchema, config: &Value) -> Vec<ValidationIssue> {
let mut issues = Vec::new();
let object = config.as_object();
// Duplicate-key detection. Quadratic but schemas are tiny in
// practice (the largest Zeal templates ship ~20 properties); a
// HashSet would barely shave runtime.
for (i, prop) in schema.properties.iter().enumerate() {
let key = &prop.meta().key;
if schema.properties[..i].iter().any(|p| &p.meta().key == key) {
issues.push(ValidationIssue {
key: key.clone(),
message: format!("duplicate property key `{key}` in schema"),
severity: IssueSeverity::Error,
});
}
}
for prop in &schema.properties {
let meta = prop.meta();
let current = object.and_then(|o| o.get(&meta.key));
// required + empty?
if meta.required {
let empty = match current {
None => true,
Some(Value::Null) => true,
Some(Value::String(s)) => s.is_empty(),
Some(Value::Array(a)) => a.is_empty(),
_ => false,
};
if empty {
issues.push(ValidationIssue {
key: meta.key.clone(),
message: format!("`{}` is required", meta.label),
severity: IssueSeverity::Error,
});
continue;
}
}
match (prop, current) {
(PropertyDefinition::Number(n), Some(value)) => {
if let Some(num) = value.as_f64() {
if n.integer && num.fract() != 0.0 {
issues.push(ValidationIssue {
key: meta.key.clone(),
message: format!("`{}` must be an integer", meta.label),
severity: IssueSeverity::Error,
});
}
if let Some(min) = n.min {
if num < min {
issues.push(ValidationIssue {
key: meta.key.clone(),
message: format!("`{}` < {} (min)", meta.label, min),
severity: IssueSeverity::Error,
});
}
}
if let Some(max) = n.max {
if num > max {
issues.push(ValidationIssue {
key: meta.key.clone(),
message: format!("`{}` > {} (max)", meta.label, max),
severity: IssueSeverity::Error,
});
}
}
} else {
issues.push(ValidationIssue {
key: meta.key.clone(),
message: format!("`{}` must be a number", meta.label),
severity: IssueSeverity::Error,
});
}
}
(PropertyDefinition::Select(s), Some(value)) if !s.options.is_empty() => {
if s.multiple {
if let Some(arr) = value.as_array() {
for v in arr {
if let Some(text) = v.as_str() {
if !s.options.iter().any(|o| o.value == text) {
issues.push(ValidationIssue {
key: meta.key.clone(),
message: format!(
"`{}` contains unknown value `{}`",
meta.label, text
),
severity: IssueSeverity::Error,
});
}
}
}
}
} else if let Some(text) = value.as_str() {
if !s.options.iter().any(|o| o.value == text) {
issues.push(ValidationIssue {
key: meta.key.clone(),
message: format!("`{}` has unknown value `{}`", meta.label, text),
severity: IssueSeverity::Error,
});
}
}
}
(PropertyDefinition::Text(t), Some(Value::String(s))) => {
if let Some(max) = t.max_length {
if s.chars().count() > max {
issues.push(ValidationIssue {
key: meta.key.clone(),
message: format!(
"`{}` exceeds max length {} characters",
meta.label, max
),
severity: IssueSeverity::Error,
});
}
}
}
_ => {}
}
}
issues
}
// ─────────────────────────────────────────────────────────────────────
// Rules engine — declarative reactive cascades
// ─────────────────────────────────────────────────────────────────────
/// Predicate over a config object. Used by [`PropertyRule::when`]
/// to gate effect application. JSON-value comparisons use
/// `serde_json::Value::eq`; numeric comparators coerce via
/// `Value::as_f64` and silently fail (return `false`) on non-numeric
/// values.
#[derive(Debug, Clone)]
pub enum Predicate {
/// Always matches. Pair with explicit triggers when the rule
/// should fire on every cascade pass without a value test.
Always,
/// `config[key] == value`.
Eq {
key: String,
value: Value,
},
/// `config[key] != value`.
NotEq {
key: String,
value: Value,
},
/// `config[key]` is in `values`.
In {
key: String,
values: Vec<Value>,
},
/// JSON-truthy: present, not null, not `false`, not `""`, not
/// `0`, not empty array, not empty object.
Truthy(String),
/// Key exists in the config object (even when its value is
/// `null`). Distinct from `Truthy` — useful for "user has
/// touched this field" semantics.
Exists(String),
Gt {
key: String,
value: f64,
},
Lt {
key: String,
value: f64,
},
Gte {
key: String,
value: f64,
},
Lte {
key: String,
value: f64,
},
/// All sub-predicates match. Empty `Vec` returns `true`.
All(Vec<Predicate>),
/// Any sub-predicate matches. Empty `Vec` returns `false`.
Any(Vec<Predicate>),
/// Negation.
Not(Box<Predicate>),
}
impl Predicate {
/// Evaluate against a config value. Non-object configs match
/// only [`Predicate::Always`] / `Not(Always)` / nested boolean
/// compositions — every key-based predicate returns `false`.
pub fn evaluate(&self, config: &Value) -> bool {
let obj = config.as_object();
match self {
Self::Always => true,
Self::Eq { key, value } => obj
.and_then(|o| o.get(key))
.map(|v| values_eq(v, value))
.unwrap_or(false),
Self::NotEq { key, value } => match obj.and_then(|o| o.get(key)) {
Some(v) => !values_eq(v, value),
// Missing keys are NotEq to any concrete value —
// matches the symmetry with Eq, which is `false` on
// a missing key (so NotEq is `true`).
None => true,
},
Self::In { key, values } => obj
.and_then(|o| o.get(key))
.map(|v| values.iter().any(|x| values_eq(x, v)))
.unwrap_or(false),
Self::Truthy(key) => obj
.and_then(|o| o.get(key))
.map(is_json_truthy)
.unwrap_or(false),
Self::Exists(key) => obj.map(|o| o.contains_key(key)).unwrap_or(false),
Self::Gt { key, value } => obj
.and_then(|o| o.get(key))
.and_then(|v| v.as_f64())
.map(|n| n > *value)
.unwrap_or(false),
Self::Lt { key, value } => obj
.and_then(|o| o.get(key))
.and_then(|v| v.as_f64())
.map(|n| n < *value)
.unwrap_or(false),
Self::Gte { key, value } => obj
.and_then(|o| o.get(key))
.and_then(|v| v.as_f64())
.map(|n| n >= *value)
.unwrap_or(false),
Self::Lte { key, value } => obj
.and_then(|o| o.get(key))
.and_then(|v| v.as_f64())
.map(|n| n <= *value)
.unwrap_or(false),
Self::All(preds) => preds.iter().all(|p| p.evaluate(config)),
Self::Any(preds) => preds.iter().any(|p| p.evaluate(config)),
Self::Not(inner) => !inner.evaluate(config),
}
}
}
/// JSON value equality with numeric-bridge: two `Value::Number`s
/// compare via `as_f64` so integer-encoded values (`Number::from(3)`)
/// match float-encoded ones (`Number::from_f64(3.0)`). Without this
/// bridge `Predicate::Eq` silently never matched a default-seeded