1pub mod generate;
27pub mod hooks;
28pub mod layers;
29pub mod template;
30pub mod transfer;
31pub mod wizard;
32
33use serde::{Deserialize, Serialize};
34use serde_json::Value as Json;
35
36use crate::diagnostics::{Diagnostic, Diagnostics, Level};
37use crate::when::{When, WhenContext};
38pub use layers::ValueScope;
39pub use wizard::{Check, Finish, Flow, Step, Wizard};
40
41pub const FORMAT: u32 = 1;
43
44#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
49#[serde(default)]
50pub struct Meta {
51 pub id: String,
52 pub title: String,
53 #[serde(skip_serializing_if = "String::is_empty")]
54 pub description: String,
55 #[serde(skip_serializing_if = "Vec::is_empty")]
56 pub keywords: Vec<String>,
57 #[serde(skip_serializing_if = "Option::is_none")]
58 pub icon: Option<String>,
59 pub order: i32,
60 #[serde(skip_serializing_if = "Option::is_none")]
62 pub when: Option<String>,
63 #[serde(skip_serializing_if = "Option::is_none")]
65 pub enabled: Option<String>,
66 #[serde(skip_serializing_if = "Option::is_none")]
68 pub reason: Option<String>,
69}
70
71impl Meta {
72 pub fn new(id: &str, title: &str) -> Meta {
73 Meta {
74 id: id.into(),
75 title: title.into(),
76 ..Meta::default()
77 }
78 }
79}
80
81#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
83pub struct Scope {
84 #[serde(flatten)]
85 pub meta: Meta,
86}
87
88#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
90pub struct Section {
91 #[serde(flatten)]
92 pub meta: Meta,
93 pub scope: String,
95 #[serde(default, skip_serializing_if = "Option::is_none")]
97 pub parent: Option<String>,
98 #[serde(default, skip_serializing_if = "Option::is_none")]
102 pub after: Option<String>,
103 #[serde(default, skip_serializing_if = "Option::is_none")]
105 pub before: Option<String>,
106 #[serde(default)]
107 pub groups: Vec<Group>,
108}
109
110impl Section {
111 pub fn path(&self) -> String {
113 format!("{}/{}", self.scope, self.meta.id)
114 }
115}
116
117#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
119pub struct Group {
120 #[serde(flatten)]
121 pub meta: Meta,
122 #[serde(default)]
123 pub items: Vec<Item>,
124}
125
126#[derive(Clone, Debug, PartialEq, Serialize)]
133#[serde(tag = "node", rename_all = "snake_case")]
134pub enum Item {
135 Field(Field),
136 Action(Action),
137 Status(Status),
138 Callout(Callout),
139 Widget(Widget),
141 List(Records),
143 Table(Records),
145 #[serde(untagged)]
147 Unknown(Unknown),
148}
149
150impl Item {
151 pub const NODES: [&'static str; 7] = [
153 "field", "action", "status", "callout", "widget", "list", "table",
154 ];
155
156 pub fn meta(&self) -> &Meta {
157 match self {
158 Item::Field(f) => &f.meta,
159 Item::Action(a) => &a.meta,
160 Item::Status(s) => &s.meta,
161 Item::Callout(c) => &c.meta,
162 Item::Widget(w) => &w.meta,
163 Item::List(r) | Item::Table(r) => &r.meta,
164 Item::Unknown(u) => &u.meta,
165 }
166 }
167}
168
169#[derive(Deserialize)]
172#[serde(tag = "node", rename_all = "snake_case")]
173enum KnownItem {
174 Field(Field),
175 Action(Action),
176 Status(Status),
177 Callout(Callout),
178 Widget(Widget),
179 List(Records),
180 Table(Records),
181}
182
183impl From<KnownItem> for Item {
184 fn from(k: KnownItem) -> Item {
185 match k {
186 KnownItem::Field(f) => Item::Field(f),
187 KnownItem::Action(a) => Item::Action(a),
188 KnownItem::Status(s) => Item::Status(s),
189 KnownItem::Callout(c) => Item::Callout(c),
190 KnownItem::Widget(w) => Item::Widget(w),
191 KnownItem::List(r) => Item::List(r),
192 KnownItem::Table(r) => Item::Table(r),
193 }
194 }
195}
196
197impl<'de> Deserialize<'de> for Item {
198 fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Item, D::Error> {
199 use serde::de::Error;
200 let raw = Json::deserialize(d)?;
201 let node = raw
202 .get("node")
203 .and_then(Json::as_str)
204 .ok_or_else(|| D::Error::missing_field("node"))?
205 .to_owned();
206 if Item::NODES.contains(&node.as_str()) {
207 return KnownItem::deserialize(raw)
208 .map(Item::from)
209 .map_err(D::Error::custom);
210 }
211 let meta = Meta::deserialize(&raw).unwrap_or_default();
212 Ok(Item::Unknown(Unknown { node, meta, raw }))
213 }
214}
215
216#[derive(Clone, Debug, PartialEq)]
220pub struct Unknown {
221 pub node: String,
222 pub meta: Meta,
223 pub raw: Json,
224}
225
226impl Serialize for Unknown {
227 fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
228 self.raw.serialize(s)
229 }
230}
231
232pub(crate) fn unknown_node(d: &mut Diagnostics, at: &str, item: &Item) -> bool {
235 let Item::Unknown(u) = item else {
236 return false;
237 };
238 d.warn(
239 "admin-unknown-node",
240 None,
241 at,
242 format!(
243 "unknown node `{}` (`{}`), from a newer format: left out",
244 u.node, u.meta.id
245 ),
246 );
247 true
248}
249
250pub trait Clauses: Sized {
252 fn meta_mut(&mut self) -> &mut Meta;
253
254 fn when(mut self, clause: &str) -> Self {
257 self.meta_mut().when = Some(clause.into());
258 self
259 }
260
261 fn enabled(mut self, clause: &str, reason: &str) -> Self {
263 let m = self.meta_mut();
264 m.enabled = Some(clause.into());
265 m.reason = Some(reason.into());
266 self
267 }
268}
269
270macro_rules! clauses {
271 ($($t:ty),*) => {$(
272 impl Clauses for $t {
273 fn meta_mut(&mut self) -> &mut Meta {
274 &mut self.meta
275 }
276 }
277 )*};
278}
279
280clauses!(Field, Action, Status, Callout, Records, RowField);
281
282#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
286#[serde(rename_all = "kebab-case")]
287pub enum FieldKind {
288 Toggle,
289 Number,
290 Choice,
291 Multi,
292 Text,
293 LongText,
294 Path,
295 List,
296 Colour,
297 Keys,
298 Note,
302}
303
304impl FieldKind {
305 pub const ALL: [FieldKind; 11] = [
306 FieldKind::Toggle,
307 FieldKind::Number,
308 FieldKind::Choice,
309 FieldKind::Multi,
310 FieldKind::Text,
311 FieldKind::LongText,
312 FieldKind::Path,
313 FieldKind::List,
314 FieldKind::Colour,
315 FieldKind::Keys,
316 FieldKind::Note,
317 ];
318
319 pub fn of(d: &crate::values::Descriptor) -> FieldKind {
321 use crate::values::Type;
322 match d.ty {
323 Type::Bool => FieldKind::Toggle,
324 Type::Float | Type::Int => FieldKind::Number,
325 Type::Choice => FieldKind::Choice,
326 Type::Text if d.path.is_some() => FieldKind::Path,
327 Type::Text => FieldKind::Text,
328 Type::Floats | Type::Ints => FieldKind::List,
329 }
330 }
331}
332
333#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
335#[serde(tag = "to", rename_all = "snake_case")]
336pub enum Bind {
337 Setting { setting: String },
340 Draft { task: String, key: String },
342}
343
344#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
346pub struct Field {
347 #[serde(flatten)]
348 pub meta: Meta,
349 pub bind: Bind,
350 #[serde(default, skip_serializing_if = "Option::is_none")]
352 pub kind: Option<FieldKind>,
353 #[serde(default, skip_serializing_if = "Vec::is_empty")]
356 pub scopes: Vec<ValueScope>,
357 #[serde(default, skip_serializing_if = "String::is_empty")]
359 pub help: String,
360 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
362 pub restart: bool,
363 #[serde(default, skip_serializing_if = "FieldHooks::is_empty")]
365 pub hooks: FieldHooks,
366 #[serde(default, skip_serializing_if = "Input::is_empty")]
369 pub input: Input,
370}
371
372#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
377#[serde(default)]
378pub struct Input {
379 #[serde(skip_serializing_if = "Json::is_null")]
380 pub default: Json,
381 #[serde(skip_serializing_if = "Vec::is_empty")]
382 pub choices: Vec<RowChoice>,
383 #[serde(skip_serializing_if = "Option::is_none")]
384 pub min: Option<f64>,
385 #[serde(skip_serializing_if = "Option::is_none")]
386 pub max: Option<f64>,
387 #[serde(skip_serializing_if = "std::ops::Not::not")]
388 pub required: bool,
389 #[serde(skip_serializing_if = "Option::is_none")]
392 pub file: Option<FileInput>,
393}
394
395#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
397#[serde(default)]
398pub struct FileInput {
399 #[serde(skip_serializing_if = "std::ops::Not::not")]
402 pub save: bool,
403 #[serde(skip_serializing_if = "String::is_empty")]
405 pub name: String,
406 #[serde(skip_serializing_if = "Vec::is_empty")]
408 pub extensions: Vec<String>,
409 #[serde(skip_serializing_if = "std::ops::Not::not")]
411 pub folder: bool,
412 #[serde(skip_serializing_if = "String::is_empty")]
415 pub title: String,
416 #[serde(skip_serializing_if = "String::is_empty")]
419 pub purpose: String,
420 #[serde(skip_serializing_if = "String::is_empty")]
423 pub filter_name: String,
424}
425
426impl Input {
427 pub fn is_empty(&self) -> bool {
428 *self == Input::default()
429 }
430}
431
432#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
434#[serde(default)]
435pub struct FieldHooks {
436 #[serde(skip_serializing_if = "Option::is_none")]
437 pub validate: Option<String>,
438 #[serde(skip_serializing_if = "Option::is_none")]
439 pub transform: Option<String>,
440 #[serde(skip_serializing_if = "Option::is_none")]
441 pub choices: Option<String>,
442 #[serde(skip_serializing_if = "Option::is_none")]
443 pub preview: Option<String>,
444}
445
446impl FieldHooks {
447 pub fn is_empty(&self) -> bool {
448 *self == FieldHooks::default()
449 }
450}
451
452impl Field {
453 pub fn setting(id: &str) -> Field {
455 Field {
456 meta: Meta::new(id, ""),
457 bind: Bind::Setting { setting: id.into() },
458 kind: None,
459 scopes: Vec::new(),
460 help: String::new(),
461 restart: false,
462 hooks: FieldHooks::default(),
463 input: Input::default(),
464 }
465 }
466
467 pub fn draft(task: &str, key: &str, title: &str, kind: FieldKind) -> Field {
469 Field {
470 meta: Meta::new(key, title),
471 bind: Bind::Draft {
472 task: task.into(),
473 key: key.into(),
474 },
475 kind: Some(kind),
476 ..Field::setting(key)
477 }
478 }
479
480 pub fn kind(mut self, kind: FieldKind) -> Field {
481 self.kind = Some(kind);
482 self
483 }
484
485 pub fn scopes(mut self, scopes: &[ValueScope]) -> Field {
486 self.scopes = scopes.to_vec();
487 self
488 }
489
490 pub fn help(mut self, help: &str) -> Field {
491 self.help = help.into();
492 self
493 }
494
495 pub fn restart(mut self) -> Field {
496 self.restart = true;
497 self
498 }
499
500 pub fn validate(mut self, hook: &str) -> Field {
501 self.hooks.validate = Some(hook.into());
502 self
503 }
504
505 pub fn choices(mut self, hook: &str) -> Field {
506 self.hooks.choices = Some(hook.into());
507 self
508 }
509
510 pub fn preview(mut self, hook: &str) -> Field {
511 self.hooks.preview = Some(hook.into());
512 self
513 }
514
515 pub fn transform(mut self, hook: &str) -> Field {
516 self.hooks.transform = Some(hook.into());
517 self
518 }
519
520 pub fn default_value(mut self, value: Json) -> Field {
522 self.input.default = value;
523 self
524 }
525
526 pub fn choice(mut self, value: Json, label: &str) -> Field {
528 self.input.choices.push(RowChoice {
529 value,
530 label: label.into(),
531 });
532 self
533 }
534
535 pub fn range(mut self, min: f64, max: f64) -> Field {
537 self.input.min = Some(min);
538 self.input.max = Some(max);
539 self
540 }
541
542 pub fn open_file(mut self, extensions: &[&str]) -> Field {
544 self.kind = Some(FieldKind::Path);
545 self.input.file = Some(FileInput {
546 extensions: extensions.iter().map(|e| e.to_string()).collect(),
547 ..FileInput::default()
548 });
549 self
550 }
551
552 pub fn open_folder(mut self) -> Field {
554 self.kind = Some(FieldKind::Path);
555 self.input.file = Some(FileInput {
556 folder: true,
557 ..FileInput::default()
558 });
559 self
560 }
561
562 pub fn dialog_title(mut self, title: &str) -> Field {
566 if let Some(file) = &mut self.input.file {
567 file.title = title.into();
568 }
569 self
570 }
571
572 pub fn dialog_purpose(mut self, key: &str) -> Field {
576 if let Some(file) = &mut self.input.file {
577 file.purpose = key.into();
578 }
579 self
580 }
581
582 pub fn filter_name(mut self, name: &str) -> Field {
586 if let Some(file) = &mut self.input.file {
587 file.filter_name = name.into();
588 }
589 self
590 }
591
592 pub fn save_file(mut self, name: &str, extensions: &[&str]) -> Field {
595 self.kind = Some(FieldKind::Path);
596 self.input.file = Some(FileInput {
597 save: true,
598 name: name.into(),
599 extensions: extensions.iter().map(|e| e.to_string()).collect(),
600 ..FileInput::default()
601 });
602 self
603 }
604
605 pub fn note(task: &str, key: &str, text: &str) -> Field {
611 Field::draft(task, key, "", FieldKind::Note).default_value(Json::String(text.into()))
612 }
613
614 pub fn icon(mut self, name: &str) -> Field {
616 self.meta.icon = Some(name.into());
617 self
618 }
619
620 pub fn note_text(&self, value: &Json) -> String {
623 let text = match value {
624 Json::Null => String::new(),
625 Json::String(s) => s.trim().to_string(),
626 other => cell_text(other),
627 };
628 if text.is_empty() {
629 self.meta.title.clone()
630 } else {
631 text
632 }
633 }
634
635 pub fn required(mut self) -> Field {
636 self.input.required = true;
637 self
638 }
639
640 pub fn draft_key(&self) -> Option<&str> {
642 match &self.bind {
643 Bind::Draft { key, .. } => Some(key),
644 Bind::Setting { .. } => None,
645 }
646 }
647
648 pub fn check(&self, value: &Json) -> Option<Check> {
651 let i = &self.input;
652 let empty = match value {
653 Json::Null => true,
654 Json::String(s) => s.trim().is_empty(),
655 Json::Array(a) => a.is_empty(),
656 _ => false,
657 };
658 if empty {
659 return i.required.then_some(Check::Required);
660 }
661 if let Some(n) = value.as_f64() {
662 if let Some(min) = i.min.filter(|m| n < *m) {
663 return Some(Check::Below(min));
664 }
665 if let Some(max) = i.max.filter(|m| n > *m) {
666 return Some(Check::Above(max));
667 }
668 }
669 if self.kind != Some(FieldKind::Multi)
672 && !i.choices.is_empty()
673 && !i.choices.iter().any(|c| c.value == *value)
674 {
675 return Some(Check::NotAChoice);
676 }
677 None
678 }
679
680 pub fn shown(&self, value: &Json) -> String {
683 let one = |v: &Json| {
684 self.input
685 .choices
686 .iter()
687 .find(|c| c.value == *v)
688 .map_or_else(|| cell_text(v), |c| c.label.clone())
689 };
690 match value {
691 Json::Array(a) if self.kind == Some(FieldKind::Multi) => {
692 a.iter().map(one).collect::<Vec<_>>().join(", ")
693 }
694 v => one(v),
695 }
696 }
697
698 pub fn setting_id(&self) -> Option<&str> {
700 match &self.bind {
701 Bind::Setting { setting } => Some(setting),
702 Bind::Draft { .. } => None,
703 }
704 }
705}
706
707#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
709#[serde(rename_all = "snake_case")]
710pub enum ActionStyle {
711 Primary,
713 #[default]
714 Secondary,
715 Danger,
716 Link,
717}
718
719#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
723pub struct Action {
724 #[serde(flatten)]
725 pub meta: Meta,
726 pub command: String,
727 #[serde(default, skip_serializing_if = "Json::is_null")]
729 pub args: Json,
730 #[serde(default)]
731 pub style: ActionStyle,
732 #[serde(default, skip_serializing_if = "Option::is_none")]
734 pub confirm: Option<String>,
735 #[serde(default, skip_serializing_if = "Option::is_none")]
738 pub confirmation: Option<Confirmation>,
739}
740
741#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
745pub struct Confirmation {
746 pub title: String,
747 #[serde(default, skip_serializing_if = "String::is_empty")]
748 pub text: String,
749 pub verb: String,
750 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
751 pub danger: bool,
752}
753
754impl Confirmation {
755 pub fn new(title: &str, text: &str, verb: &str) -> Confirmation {
756 Confirmation {
757 title: title.into(),
758 text: text.into(),
759 verb: verb.into(),
760 danger: false,
761 }
762 }
763
764 pub fn danger(mut self) -> Confirmation {
765 self.danger = true;
766 self
767 }
768
769 pub fn filled(&self, values: &hooks::Values) -> Confirmation {
771 let fill = |s: &str| match template::expand(&Json::String(s.into()), values).0 {
772 Json::String(s) => s,
773 other => cell_text(&other),
774 };
775 Confirmation {
776 title: fill(&self.title),
777 text: fill(&self.text),
778 verb: fill(&self.verb),
779 danger: self.danger,
780 }
781 }
782}
783
784impl Action {
785 pub fn command(command: &str) -> Action {
786 Action {
787 meta: Meta::new(command, ""),
788 command: command.into(),
789 args: Json::Null,
790 style: ActionStyle::Secondary,
791 confirm: None,
792 confirmation: None,
793 }
794 }
795
796 pub fn title(mut self, title: &str) -> Action {
797 self.meta.title = title.into();
798 self
799 }
800
801 pub fn args(mut self, args: Json) -> Action {
802 self.args = args;
803 self
804 }
805
806 pub fn primary(mut self) -> Action {
807 self.style = ActionStyle::Primary;
808 self
809 }
810
811 pub fn danger(mut self) -> Action {
812 self.style = ActionStyle::Danger;
813 self
814 }
815
816 pub fn confirm(mut self, hook: &str) -> Action {
817 self.confirm = Some(hook.into());
818 self
819 }
820
821 pub fn confirmation(mut self, confirmation: Confirmation) -> Action {
823 self.confirmation = Some(confirmation);
824 self
825 }
826}
827
828#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
830#[serde(rename_all = "snake_case")]
831pub enum Tone {
832 #[default]
833 Info,
834 Success,
835 Warning,
836 Danger,
837 Muted,
839}
840
841#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
843#[serde(tag = "from", rename_all = "snake_case")]
844pub enum StatusSource {
845 Command { command: String, pointer: String },
847 Hook { hook: String },
849}
850
851#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
854pub struct Status {
855 #[serde(flatten)]
856 pub meta: Meta,
857 pub source: StatusSource,
858 #[serde(default, skip_serializing_if = "Vec::is_empty")]
859 pub refresh: Vec<String>,
860}
861
862impl Status {
863 pub fn command(id: &str, title: &str, command: &str, pointer: &str) -> Status {
864 Status {
865 meta: Meta::new(id, title),
866 source: StatusSource::Command {
867 command: command.into(),
868 pointer: pointer.into(),
869 },
870 refresh: Vec::new(),
871 }
872 }
873
874 pub fn hook(id: &str, title: &str, hook: &str) -> Status {
875 Status {
876 meta: Meta::new(id, title),
877 source: StatusSource::Hook { hook: hook.into() },
878 refresh: Vec::new(),
879 }
880 }
881
882 pub fn refresh(mut self, event: &str) -> Status {
883 self.refresh.push(event.into());
884 self
885 }
886}
887
888#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
891pub struct Callout {
892 #[serde(flatten)]
893 pub meta: Meta,
894 pub tone: Tone,
895 pub text: String,
896 #[serde(default, skip_serializing_if = "Option::is_none")]
897 pub action: Option<Action>,
898}
899
900impl Callout {
901 pub fn new(id: &str, tone: Tone, text: &str) -> Callout {
902 Callout {
903 meta: Meta::new(id, ""),
904 tone,
905 text: text.into(),
906 action: None,
907 }
908 }
909
910 pub fn action(mut self, action: Action) -> Callout {
911 self.action = Some(action);
912 self
913 }
914}
915
916#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
918#[serde(tag = "from", rename_all = "snake_case")]
919pub enum RecordSource {
920 Command {
923 command: String,
924 #[serde(default, skip_serializing_if = "Json::is_null")]
925 args: Json,
926 #[serde(default)]
927 pointer: String,
928 },
929 Hook { hook: String },
931}
932
933#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
936pub struct Column {
937 pub key: String,
938 pub title: String,
939 #[serde(default, skip_serializing_if = "CellKind::is_text")]
940 pub kind: CellKind,
941 #[serde(default, skip_serializing_if = "Option::is_none")]
944 pub text: Option<String>,
945}
946
947#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
949#[serde(rename_all = "snake_case")]
950pub enum CellKind {
951 #[default]
953 Text,
954 Meter,
957 Icon,
960}
961
962impl CellKind {
963 pub fn is_text(&self) -> bool {
964 *self == CellKind::Text
965 }
966}
967
968#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
976#[serde(untagged)]
977pub enum CellText {
978 Plain(String),
979 Key {
980 key: String,
981 #[serde(default, skip_serializing_if = "String::is_empty")]
983 text: String,
984 #[serde(default, skip_serializing_if = "serde_json::Map::is_empty")]
987 args: serde_json::Map<String, Json>,
988 },
989}
990
991impl CellText {
992 pub fn plain(text: &str) -> CellText {
994 CellText::Plain(text.into())
995 }
996
997 pub fn key(key: &str, english: &str) -> CellText {
999 CellText::Key {
1000 key: key.into(),
1001 text: english.into(),
1002 args: serde_json::Map::new(),
1003 }
1004 }
1005
1006 pub fn arg(mut self, name: &str, value: impl Into<Json>) -> CellText {
1008 if let CellText::Key { args, .. } = &mut self {
1009 args.insert(name.into(), value.into());
1010 }
1011 self
1012 }
1013}
1014
1015#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
1025pub struct IconCell {
1026 pub icon: String,
1027 #[serde(default, skip_serializing_if = "Option::is_none")]
1028 pub tone: Option<Tone>,
1029 #[serde(default, skip_serializing_if = "Option::is_none")]
1030 pub tip: Option<CellText>,
1031}
1032
1033impl IconCell {
1034 pub fn new(icon: &str) -> IconCell {
1035 IconCell {
1036 icon: icon.into(),
1037 tone: None,
1038 tip: None,
1039 }
1040 }
1041
1042 pub fn tone(mut self, tone: Tone) -> IconCell {
1043 self.tone = Some(tone);
1044 self
1045 }
1046
1047 pub fn tip(mut self, tip: CellText) -> IconCell {
1048 self.tip = Some(tip);
1049 self
1050 }
1051
1052 pub fn of(v: &Json) -> Option<IconCell> {
1056 let (icon, tone, tip) = match v {
1057 Json::String(s) => (s.as_str(), None, None),
1058 Json::Object(o) => (
1059 o.get("icon").and_then(Json::as_str)?,
1060 o.get("tone").and_then(Json::as_str).and_then(tone_named),
1061 o.get("tip")
1062 .and_then(|t| serde_json::from_value::<CellText>(t.clone()).ok()),
1063 ),
1064 _ => return None,
1065 };
1066 if icon.is_empty() {
1067 return None;
1068 }
1069 Some(IconCell {
1070 icon: icon.into(),
1071 tone,
1072 tip,
1073 })
1074 }
1075}
1076
1077pub fn meter_share(v: &Json) -> Option<f32> {
1079 v.as_f64().map(|x| x.clamp(0.0, 1.0) as f32)
1080}
1081
1082#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
1084pub struct RowChoice {
1085 pub value: Json,
1086 pub label: String,
1087}
1088
1089#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
1096pub struct RowField {
1097 #[serde(flatten)]
1098 pub meta: Meta,
1099 pub key: String,
1101 pub kind: FieldKind,
1103 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1104 pub choices: Vec<RowChoice>,
1105 #[serde(default, skip_serializing_if = "Option::is_none")]
1108 pub choices_key: Option<String>,
1109 pub command: String,
1110 #[serde(default, skip_serializing_if = "Json::is_null")]
1111 pub args: Json,
1112}
1113
1114impl RowField {
1115 fn new(kind: FieldKind, key: &str, title: &str, command: &str, args: Json) -> RowField {
1116 RowField {
1117 meta: Meta::new(key, title),
1118 key: key.into(),
1119 kind,
1120 choices: Vec::new(),
1121 choices_key: None,
1122 command: command.into(),
1123 args,
1124 }
1125 }
1126
1127 pub fn toggle(key: &str, title: &str, command: &str, args: Json) -> RowField {
1129 RowField::new(FieldKind::Toggle, key, title, command, args)
1130 }
1131
1132 pub fn text(key: &str, title: &str, command: &str, args: Json) -> RowField {
1134 RowField::new(FieldKind::Text, key, title, command, args)
1135 }
1136
1137 pub fn choice(
1139 key: &str,
1140 title: &str,
1141 choices: &[(Json, &str)],
1142 command: &str,
1143 args: Json,
1144 ) -> RowField {
1145 let mut f = RowField::new(FieldKind::Choice, key, title, command, args);
1146 f.choices = choices
1147 .iter()
1148 .map(|(value, label)| RowChoice {
1149 value: value.clone(),
1150 label: (*label).into(),
1151 })
1152 .collect();
1153 f
1154 }
1155
1156 pub fn choices_from(mut self, key: &str) -> RowField {
1158 self.choices_key = Some(key.into());
1159 self
1160 }
1161
1162 pub fn id(mut self, id: &str) -> RowField {
1164 self.meta.id = id.into();
1165 self
1166 }
1167
1168 pub fn help(mut self, text: &str) -> RowField {
1170 self.meta.description = text.into();
1171 self
1172 }
1173
1174 pub fn choices_of(&self, row: &Json) -> Vec<RowChoice> {
1177 let mut out = self.choices.clone();
1178 if let Some(k) = &self.choices_key {
1179 out.extend(
1180 row[k.as_str()]
1181 .as_array()
1182 .into_iter()
1183 .flatten()
1184 .filter_map(|c| serde_json::from_value::<RowChoice>(c.clone()).ok()),
1185 );
1186 }
1187 out
1188 }
1189
1190 pub fn write_args(&self, values: &hooks::Values, value: Json) -> Json {
1193 let mut v = values.clone();
1194 v.insert("value".into(), value);
1195 template::expand(&self.args, &v).0
1196 }
1197}
1198
1199#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
1201pub struct Empty {
1202 pub text: String,
1203 #[serde(default, skip_serializing_if = "Option::is_none")]
1204 pub action: Option<Action>,
1205}
1206
1207#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
1210pub struct Records {
1211 #[serde(flatten)]
1212 pub meta: Meta,
1213 pub source: RecordSource,
1214 pub key: String,
1216 #[serde(default, skip_serializing_if = "Option::is_none")]
1218 pub title_key: Option<String>,
1219 #[serde(default, skip_serializing_if = "Option::is_none")]
1220 pub subtitle_key: Option<String>,
1221 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1223 pub columns: Vec<Column>,
1224 #[serde(default, skip_serializing_if = "Option::is_none")]
1227 pub tone_key: Option<String>,
1228 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1229 pub row_fields: Vec<RowField>,
1230 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1231 pub row_actions: Vec<Action>,
1232 #[serde(default, skip_serializing_if = "Option::is_none")]
1233 pub empty: Option<Empty>,
1234 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1236 pub refresh: Vec<String>,
1237 #[serde(default, skip_serializing_if = "Option::is_none")]
1239 pub detail: Option<Detail>,
1240}
1241
1242#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
1246pub struct Detail {
1247 #[serde(default, skip_serializing_if = "Option::is_none")]
1250 pub title_key: Option<String>,
1251 pub lines: Vec<DetailLine>,
1253}
1254
1255#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
1257pub struct DetailLine {
1258 pub key: String,
1259 pub title: String,
1260}
1261
1262impl Detail {
1263 pub fn new() -> Detail {
1264 Detail::default()
1265 }
1266
1267 pub fn title(mut self, key: &str) -> Detail {
1269 self.title_key = Some(key.into());
1270 self
1271 }
1272
1273 pub fn line(mut self, key: &str, title: &str) -> Detail {
1275 self.lines.push(DetailLine {
1276 key: key.into(),
1277 title: title.into(),
1278 });
1279 self
1280 }
1281}
1282
1283impl Records {
1284 fn new(id: &str, title: &str, source: RecordSource, key: &str) -> Records {
1285 Records {
1286 meta: Meta::new(id, title),
1287 source,
1288 key: key.into(),
1289 title_key: None,
1290 subtitle_key: None,
1291 columns: Vec::new(),
1292 tone_key: None,
1293 row_fields: Vec::new(),
1294 row_actions: Vec::new(),
1295 empty: None,
1296 refresh: Vec::new(),
1297 detail: None,
1298 }
1299 }
1300
1301 pub fn command(id: &str, title: &str, command: &str, pointer: &str, key: &str) -> Records {
1303 Records::new(
1304 id,
1305 title,
1306 RecordSource::Command {
1307 command: command.into(),
1308 args: Json::Null,
1309 pointer: pointer.into(),
1310 },
1311 key,
1312 )
1313 }
1314
1315 pub fn hook(id: &str, title: &str, hook: &str, key: &str) -> Records {
1317 Records::new(id, title, RecordSource::Hook { hook: hook.into() }, key)
1318 }
1319
1320 pub fn args(mut self, args: Json) -> Records {
1322 if let RecordSource::Command { args: a, .. } = &mut self.source {
1323 *a = args;
1324 }
1325 self
1326 }
1327
1328 pub fn titles(mut self, title: &str, subtitle: Option<&str>) -> Records {
1330 self.title_key = Some(title.into());
1331 self.subtitle_key = subtitle.map(Into::into);
1332 self
1333 }
1334
1335 pub fn column(mut self, key: &str, title: &str) -> Records {
1336 self.columns.push(Column {
1337 key: key.into(),
1338 title: title.into(),
1339 kind: CellKind::Text,
1340 text: None,
1341 });
1342 self
1343 }
1344
1345 pub fn meter(mut self, key: &str, title: &str, text: &str) -> Records {
1347 self.columns.push(Column {
1348 key: key.into(),
1349 title: title.into(),
1350 kind: CellKind::Meter,
1351 text: Some(text.into()),
1352 });
1353 self
1354 }
1355
1356 pub fn icon(mut self, key: &str, title: &str, tip: Option<&str>) -> Records {
1359 self.columns.push(Column {
1360 key: key.into(),
1361 title: title.into(),
1362 kind: CellKind::Icon,
1363 text: tip.map(Into::into),
1364 });
1365 self
1366 }
1367
1368 pub fn row_field(mut self, field: RowField) -> Records {
1370 self.row_fields.push(field);
1371 self
1372 }
1373
1374 pub fn field_for(&self, key: &str) -> Option<&RowField> {
1376 self.row_fields.iter().find(|f| f.key == key)
1377 }
1378
1379 pub fn extra_fields(&self) -> impl Iterator<Item = &RowField> {
1382 self.row_fields
1383 .iter()
1384 .filter(|f| !self.columns.iter().any(|c| c.key == f.key))
1385 }
1386
1387 pub fn tone(mut self, key: &str) -> Records {
1388 self.tone_key = Some(key.into());
1389 self
1390 }
1391
1392 pub fn row_action(mut self, action: Action) -> Records {
1393 self.row_actions.push(action);
1394 self
1395 }
1396
1397 pub fn empty(mut self, text: &str, action: Option<Action>) -> Records {
1398 self.empty = Some(Empty {
1399 text: text.into(),
1400 action,
1401 });
1402 self
1403 }
1404
1405 pub fn refresh(mut self, event: &str) -> Records {
1406 self.refresh.push(event.into());
1407 self
1408 }
1409
1410 pub fn detail(mut self, detail: Detail) -> Records {
1413 self.detail = Some(detail);
1414 self
1415 }
1416
1417 pub fn row_title(&self, row: &Json) -> String {
1420 let key = self
1421 .title_key
1422 .as_deref()
1423 .or_else(|| self.columns.first().map(|c| c.key.as_str()))
1424 .unwrap_or(&self.key);
1425 cell_text(&row[key])
1426 }
1427
1428 pub fn detail_title(&self, row: &Json) -> String {
1431 self.detail
1432 .as_ref()
1433 .and_then(|d| d.title_key.as_deref())
1434 .map(|k| cell_text(&row[k]))
1435 .filter(|t| !t.is_empty())
1436 .unwrap_or_else(|| self.row_title(row))
1437 }
1438
1439 pub fn rows_of(answer: &Json, pointer: &str) -> Vec<Json> {
1443 match answer.pointer(pointer) {
1444 Some(Json::Array(a)) => a.iter().filter(|r| r.is_object()).cloned().collect(),
1445 Some(o @ Json::Object(_)) => vec![o.clone()],
1446 _ => Vec::new(),
1447 }
1448 }
1449
1450 pub fn row_values(values: &hooks::Values, row: &Json) -> hooks::Values {
1453 let mut v = values.clone();
1454 if let Some(o) = row.as_object() {
1455 for (k, x) in o {
1456 v.insert(format!("row.{k}"), x.clone());
1457 }
1458 }
1459 v
1460 }
1461}
1462
1463pub fn row_context(mut cx: WhenContext, row: &Json) -> WhenContext {
1466 if let Some(o) = row.as_object() {
1467 for (k, v) in o {
1468 cx.set(&format!("row.{k}"), &cell_text(v));
1469 }
1470 }
1471 cx
1472}
1473
1474pub fn cell_text(v: &Json) -> String {
1477 match v {
1478 Json::Null => String::new(),
1479 Json::String(s) => s.clone(),
1480 Json::Array(a) => a.iter().map(cell_text).collect::<Vec<_>>().join(", "),
1481 other => other.to_string(),
1482 }
1483}
1484
1485pub fn tone_named(name: &str) -> Option<Tone> {
1487 match name {
1488 "info" => Some(Tone::Info),
1489 "success" | "ok" | "fine" => Some(Tone::Success),
1490 "warning" | "warn" => Some(Tone::Warning),
1491 "danger" | "error" | "problem" => Some(Tone::Danger),
1492 "muted" => Some(Tone::Muted),
1493 _ => None,
1494 }
1495}
1496
1497pub fn form_context(mut cx: WhenContext, values: &hooks::Values) -> WhenContext {
1501 for (k, v) in values {
1502 cx.set(&format!("form.{k}"), &cell_text(v));
1503 }
1504 cx
1505}
1506
1507pub fn holds(clause: Option<&str>, cx: &WhenContext) -> bool {
1510 clause.is_none_or(|c| When::parse(c).map_or(true, |w| w.eval(cx)))
1511}
1512
1513#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
1515pub struct Widget {
1516 #[serde(flatten)]
1517 pub meta: Meta,
1518 pub kind: String,
1519 #[serde(default, skip_serializing_if = "Json::is_null")]
1520 pub options: Json,
1521}
1522
1523impl Widget {
1524 pub fn settings(&self) -> impl Iterator<Item = &str> {
1526 self.options
1527 .get("settings")
1528 .and_then(Json::as_array)
1529 .into_iter()
1530 .flatten()
1531 .filter_map(Json::as_str)
1532 }
1533}
1534
1535#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
1538pub struct Manifest {
1539 pub version: u32,
1540 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1541 pub scopes: Vec<Scope>,
1542 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1543 pub sections: Vec<Section>,
1544 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1546 pub wizards: Vec<Wizard>,
1547 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1550 pub quick: Vec<String>,
1551}
1552
1553#[derive(Clone, Debug, PartialEq)]
1555pub enum ManifestError {
1556 Newer { version: u32, supported: u32 },
1558 Parse(String),
1560}
1561
1562impl std::fmt::Display for ManifestError {
1563 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1564 match self {
1565 ManifestError::Newer { version, supported } => write!(
1566 f,
1567 "manifest format {version} is newer than this framework's ({supported})"
1568 ),
1569 ManifestError::Parse(e) => write!(f, "not a manifest: {e}"),
1570 }
1571 }
1572}
1573
1574impl std::error::Error for ManifestError {}
1575
1576#[derive(Debug)]
1578pub struct SectionBuilder<'a> {
1579 section: &'a mut Section,
1580}
1581
1582impl SectionBuilder<'_> {
1583 pub fn group(&mut self, id: &str, title: &str) -> &mut Self {
1586 let order = self.section.groups.len() as i32;
1587 self.section.groups.push(Group {
1588 meta: Meta {
1589 order,
1590 ..Meta::new(id, title)
1591 },
1592 items: Vec::new(),
1593 });
1594 self
1595 }
1596
1597 fn push(&mut self, item: Item) -> &mut Self {
1598 if self.section.groups.is_empty() {
1599 self.group("main", "");
1600 }
1601 if let Some(g) = self.section.groups.last_mut() {
1602 g.items.push(item);
1603 }
1604 self
1605 }
1606
1607 pub fn field(&mut self, field: Field) -> &mut Self {
1608 self.push(Item::Field(field))
1609 }
1610
1611 pub fn action(&mut self, action: Action) -> &mut Self {
1612 self.push(Item::Action(action))
1613 }
1614
1615 pub fn status(&mut self, status: Status) -> &mut Self {
1616 self.push(Item::Status(status))
1617 }
1618
1619 pub fn callout(&mut self, callout: Callout) -> &mut Self {
1620 self.push(Item::Callout(callout))
1621 }
1622
1623 pub fn widget(&mut self, id: &str, kind: &str, options: Json) -> &mut Self {
1624 self.push(Item::Widget(Widget {
1625 meta: Meta::new(id, ""),
1626 kind: kind.into(),
1627 options,
1628 }))
1629 }
1630
1631 pub fn list(&mut self, records: Records) -> &mut Self {
1633 self.push(Item::List(records))
1634 }
1635
1636 pub fn table(&mut self, records: Records) -> &mut Self {
1638 self.push(Item::Table(records))
1639 }
1640
1641 pub fn group_when(&mut self, clause: &str) -> &mut Self {
1643 if let Some(g) = self.section.groups.last_mut() {
1644 g.meta.when = Some(clause.into());
1645 }
1646 self
1647 }
1648
1649 pub fn when(&mut self, clause: &str) -> &mut Self {
1651 self.section.meta.when = Some(clause.into());
1652 self
1653 }
1654
1655 pub fn description(&mut self, text: &str) -> &mut Self {
1656 self.section.meta.description = text.into();
1657 self
1658 }
1659
1660 pub fn keywords(&mut self, words: &[&str]) -> &mut Self {
1661 self.section.meta.keywords = words.iter().map(|w| w.to_string()).collect();
1662 self
1663 }
1664
1665 pub fn under(&mut self, parent: &str) -> &mut Self {
1666 self.section.parent = Some(parent.into());
1667 self
1668 }
1669
1670 pub fn after(&mut self, anchor: &str) -> &mut Self {
1674 self.section.after = Some(anchor.into());
1675 self
1676 }
1677
1678 pub fn before(&mut self, anchor: &str) -> &mut Self {
1680 self.section.before = Some(anchor.into());
1681 self
1682 }
1683
1684 pub fn order(&mut self, order: i32) -> &mut Self {
1688 self.section.meta.order = order;
1689 self
1690 }
1691}
1692
1693impl Manifest {
1694 pub fn new(version: u32) -> Manifest {
1696 Manifest {
1697 version,
1698 scopes: Vec::new(),
1699 sections: Vec::new(),
1700 wizards: Vec::new(),
1701 quick: Vec::new(),
1702 }
1703 }
1704
1705 pub fn quick(mut self, ids: &[&str]) -> Manifest {
1708 self.quick.extend(ids.iter().map(|id| id.to_string()));
1709 self
1710 }
1711
1712 pub fn wizard(mut self, wizard: Wizard) -> Manifest {
1714 self.wizards.push(wizard);
1715 self
1716 }
1717
1718 pub fn scope_at(mut self, id: &str, title: &str, icon: &str, order: i32) -> Manifest {
1721 self = self.scope(id, title, icon);
1722 if let Some(s) = self.scopes.last_mut() {
1723 s.meta.order = order;
1724 }
1725 self
1726 }
1727
1728 pub fn scope(mut self, id: &str, title: &str, icon: &str) -> Manifest {
1730 let order = self.scopes.len() as i32;
1731 self.scopes.push(Scope {
1732 meta: Meta {
1733 icon: Some(icon.into()),
1734 order,
1735 ..Meta::new(id, title)
1736 },
1737 });
1738 self
1739 }
1740
1741 pub fn section(
1743 mut self,
1744 path: &str,
1745 title: &str,
1746 build: impl FnOnce(&mut SectionBuilder<'_>),
1747 ) -> Manifest {
1748 let (scope, id) = path.split_once('/').unwrap_or(("general", path));
1749 let mut section = Section {
1751 meta: Meta::new(id, title),
1752 scope: scope.into(),
1753 ..Section::default()
1754 };
1755 build(&mut SectionBuilder {
1756 section: &mut section,
1757 });
1758 self.sections.push(section);
1759 self
1760 }
1761
1762 pub fn to_json(&self) -> Json {
1763 serde_json::to_value(self).unwrap_or(Json::Null)
1764 }
1765
1766 pub fn bound_settings(&self) -> impl Iterator<Item = &str> {
1770 self.sections
1771 .iter()
1772 .flat_map(|s| &s.groups)
1773 .flat_map(|g| &g.items)
1774 .flat_map(|i| -> Box<dyn Iterator<Item = &str> + '_> {
1775 match i {
1776 Item::Field(f) => Box::new(f.setting_id().into_iter()),
1777 Item::Widget(w) => Box::new(w.settings()),
1778 _ => Box::new(std::iter::empty()),
1779 }
1780 })
1781 }
1782
1783 pub fn from_json(json: &Json) -> Result<Manifest, ManifestError> {
1786 let version =
1787 json.get("version")
1788 .and_then(Json::as_u64)
1789 .ok_or_else(|| ManifestError::Parse("no `version`".into()))? as u32;
1790 if version > FORMAT {
1791 return Err(ManifestError::Newer {
1792 version,
1793 supported: FORMAT,
1794 });
1795 }
1796 serde_json::from_value(json.clone()).map_err(|e| ManifestError::Parse(e.to_string()))
1797 }
1798
1799 pub fn check(
1803 &mut self,
1804 scopes: &[String],
1805 setting_exists: &dyn Fn(&str) -> bool,
1806 ) -> Diagnostics {
1807 let mut d = Diagnostics::new();
1808 let mut seen: Vec<String> = Vec::new();
1809 self.scopes.retain(|s| {
1810 if seen.contains(&s.meta.id) {
1811 d.warn(
1812 "admin-duplicate",
1813 None,
1814 &s.meta.id,
1815 "a scope with this id is already declared: left out",
1816 );
1817 return false;
1818 }
1819 seen.push(s.meta.id.clone());
1820 true
1821 });
1822 let known: Vec<String> = seen.iter().chain(scopes).cloned().collect();
1823 let mut paths: Vec<String> = Vec::new();
1824 self.sections.retain_mut(|s| {
1825 if !known.contains(&s.scope) {
1826 d.warn(
1827 "admin-no-scope",
1828 None,
1829 s.path(),
1830 format!("no scope `{}`: left out", s.scope),
1831 );
1832 return false;
1833 }
1834 if paths.contains(&s.path()) {
1835 d.warn(
1836 "admin-duplicate",
1837 None,
1838 s.path(),
1839 "a section with this path is already declared: left out",
1840 );
1841 return false;
1842 }
1843 paths.push(s.path());
1844 let at = s.path();
1845 bad_clauses(&mut d, &at, &mut s.meta);
1846 for g in &mut s.groups {
1847 bad_clauses(&mut d, &at, &mut g.meta);
1848 let mut ids: Vec<String> = Vec::new();
1849 g.items.retain(|item| {
1850 if unknown_node(&mut d, &format!("{}/{}", s.scope, s.meta.id), item) {
1851 return false;
1852 }
1853 let id = item.meta().id.clone();
1854 if ids.contains(&id) {
1855 d.warn(
1856 "admin-duplicate",
1857 None,
1858 format!("{}/{}/{id}", s.scope, s.meta.id),
1859 "an item with this id is already in the group: left out",
1860 );
1861 return false;
1862 }
1863 ids.push(id.clone());
1864 for clause in [&item.meta().when, &item.meta().enabled]
1865 .into_iter()
1866 .flatten()
1867 {
1868 if let Err(e) = When::parse(clause) {
1869 d.warn(
1870 "admin-bad-clause",
1871 None,
1872 format!("{}/{}/{id}", s.scope, s.meta.id),
1873 format!("`{clause}` does not parse ({e}): it always holds"),
1874 );
1875 }
1876 }
1877 if let Item::Field(f) = item
1878 && let Some(setting) = f.setting_id()
1879 && !setting_exists(setting)
1880 {
1881 d.warn(
1882 "admin-no-setting",
1883 None,
1884 format!("{}/{}/{id}", s.scope, s.meta.id),
1885 format!("no setting `{setting}`: left out"),
1886 );
1887 return false;
1888 }
1889 true
1890 });
1891 }
1892 true
1893 });
1894 let mut ids: Vec<String> = Vec::new();
1895 self.wizards.retain_mut(|w| {
1896 if ids.contains(&w.meta.id) {
1897 d.warn(
1898 "admin-duplicate",
1899 None,
1900 &w.meta.id,
1901 "a wizard with this id is already declared: left out",
1902 );
1903 return false;
1904 }
1905 ids.push(w.meta.id.clone());
1906 w.check(&mut d, setting_exists);
1907 true
1908 });
1909 d
1910 }
1911}
1912
1913pub(crate) fn bad_clauses(d: &mut Diagnostics, at: &str, meta: &mut Meta) {
1916 for clause in [&mut meta.when, &mut meta.enabled] {
1917 if let Some(c) = clause.as_deref()
1918 && let Err(e) = When::parse(c)
1919 {
1920 d.warn(
1921 "admin-bad-clause",
1922 None,
1923 at,
1924 format!("`{c}` does not parse ({e}): left out"),
1925 );
1926 *clause = None;
1927 }
1928 }
1929}
1930
1931#[derive(Clone, Debug, Default, PartialEq, Serialize)]
1934pub struct Tree {
1935 pub scopes: Vec<Scope>,
1936 pub sections: Vec<Section>,
1937 #[serde(skip_serializing_if = "Vec::is_empty")]
1938 pub wizards: Vec<Wizard>,
1939 #[serde(skip_serializing_if = "Vec::is_empty")]
1941 pub quick: Vec<String>,
1942 #[serde(skip)]
1946 origins: Vec<(String, usize, usize, usize)>,
1947 #[serde(skip)]
1949 merged: usize,
1950 #[serde(skip)]
1952 order_notes: Vec<Diagnostic>,
1953}
1954
1955#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
1958pub struct Place {
1959 pub scope: String,
1960 pub section: Option<String>,
1961 pub key: Option<String>,
1963}
1964
1965impl Tree {
1966 pub fn merge(&mut self, m: Manifest) {
1971 let rank = self.merged;
1972 self.merged += 1;
1973 for s in m.scopes {
1974 if !self.scopes.iter().any(|x| x.meta.id == s.meta.id) {
1975 self.scopes.push(s);
1976 }
1977 }
1978 let mut scopes_seen: Vec<String> = Vec::new();
1979 for (position, s) in m.sections.into_iter().enumerate() {
1980 let in_scope = scopes_seen.iter().filter(|x| **x == s.scope).count();
1981 scopes_seen.push(s.scope.clone());
1982 match self.sections.iter_mut().find(|x| x.path() == s.path()) {
1983 Some(x) => x.groups.extend(s.groups),
1984 None => {
1985 self.origins.push((s.path(), rank, in_scope, position));
1986 self.sections.push(s);
1987 }
1988 }
1989 }
1990 for w in m.wizards {
1991 if !self.wizards.iter().any(|x| x.meta.id == w.meta.id) {
1992 self.wizards.push(w);
1993 }
1994 }
1995 for q in m.quick {
1996 if !self.quick.contains(&q) {
1997 self.quick.push(q);
1998 }
1999 }
2000 self.scopes.sort_by_key(|s| s.meta.order);
2001 self.place();
2002 }
2003
2004 pub fn order_diagnostics(&self) -> &[Diagnostic] {
2011 &self.order_notes
2012 }
2013
2014 fn place(&mut self) {
2028 let origin = |origins: &[(String, usize, usize, usize)], path: &str| {
2029 origins
2030 .iter()
2031 .find(|(p, ..)| p == path)
2032 .map_or((usize::MAX, usize::MAX, usize::MAX), |&(_, r, l, p)| {
2033 (r, l, p)
2034 })
2035 };
2036 let mut all = std::mem::take(&mut self.sections);
2037 all.sort_by_key(|s| {
2038 let (rank, in_scope, position) = origin(&self.origins, &s.path());
2039 let weight = if s.meta.order == 0 {
2040 i64::try_from(in_scope).unwrap_or(i64::MAX)
2041 } else {
2042 i64::from(s.meta.order)
2043 };
2044 (weight, rank, position)
2045 });
2046 let mut notes = Vec::new();
2047 let (anchored, mut placed): (Vec<Section>, Vec<Section>) = all
2048 .into_iter()
2049 .partition(|s| s.after.is_some() || s.before.is_some());
2050 for (i, a) in placed.iter().enumerate() {
2053 if a.meta.order == 0 {
2054 continue;
2055 }
2056 let (ra, ..) = origin(&self.origins, &a.path());
2057 if let Some(b) = placed[i + 1..].iter().find(|b| {
2058 b.scope == a.scope
2059 && b.meta.order == a.meta.order
2060 && origin(&self.origins, &b.path()).0 != ra
2061 }) {
2062 notes.push(Diagnostic {
2063 level: Level::Warning,
2064 code: "admin-order-tie",
2065 owner: None,
2066 subject: b.path(),
2067 message: format!(
2068 "`{}` and `{}` both have order {}: placed in registration order; \
2069 anchor one with `after` or `before`",
2070 a.path(),
2071 b.path(),
2072 a.meta.order
2073 ),
2074 });
2075 }
2076 }
2077 let target = |s: &Section| -> (String, bool) {
2078 let (anchor, after) = match (&s.after, &s.before) {
2079 (Some(a), _) => (a, true),
2080 (None, Some(b)) => (b, false),
2081 (None, None) => unreachable!("only anchored sections"),
2082 };
2083 let path = if anchor.contains('/') {
2084 anchor.clone()
2085 } else {
2086 format!("{}/{anchor}", s.scope)
2087 };
2088 (path, after)
2089 };
2090 let mut pending = anchored;
2091 loop {
2092 let before = pending.len();
2093 let mut left = Vec::new();
2094 for s in pending {
2095 let (path, after) = target(&s);
2096 let found = placed
2097 .iter()
2098 .position(|x| x.path() == path && x.scope == s.scope);
2099 match found {
2100 Some(mut i) => {
2101 if after {
2102 i += 1;
2103 while placed.get(i).is_some_and(|x| {
2105 x.after.as_ref().is_some_and(|_| target(x).0 == path)
2106 }) {
2107 i += 1;
2108 }
2109 }
2110 placed.insert(i, s);
2111 }
2112 None => left.push(s),
2113 }
2114 }
2115 pending = left;
2116 if pending.is_empty() || pending.len() == before {
2117 break;
2118 }
2119 }
2120 for s in pending {
2121 let (path, _) = target(&s);
2122 notes.push(Diagnostic {
2123 level: Level::Warning,
2124 code: "admin-unknown-anchor",
2125 owner: None,
2126 subject: s.path(),
2127 message: format!(
2128 "anchored to `{path}`, which is no section of scope `{}` \
2129 (or anchors back to it): placed at the end of its scope",
2130 s.scope
2131 ),
2132 });
2133 let end = placed
2134 .iter()
2135 .rposition(|x| x.scope == s.scope)
2136 .map_or(placed.len(), |i| i + 1);
2137 placed.insert(end, s);
2138 }
2139 self.sections = placed;
2140 self.order_notes = notes;
2141 }
2142
2143 pub fn shown_scopes(&self) -> Vec<&Scope> {
2145 self.scopes
2146 .iter()
2147 .filter(|s| self.sections.iter().any(|x| x.scope == s.meta.id))
2148 .collect()
2149 }
2150
2151 pub fn sections_of(&self, scope: &str) -> Vec<&Section> {
2153 self.sections.iter().filter(|s| s.scope == scope).collect()
2154 }
2155
2156 pub fn section(&self, path: &str) -> Option<&Section> {
2157 self.sections.iter().find(|s| s.path() == path)
2158 }
2159
2160 pub fn wizard(&self, id: &str) -> Option<&Wizard> {
2161 self.wizards.iter().find(|w| w.meta.id == id)
2162 }
2163
2164 pub fn resolve(&self, link: &str) -> Option<Place> {
2168 let parts: Vec<&str> = link.splitn(3, '/').collect();
2169 if self.scopes.iter().any(|s| s.meta.id == parts[0]) {
2170 let section = parts.get(1).map(|s| s.to_string());
2171 if let Some(sec) = §ion
2172 && self.section(&format!("{}/{sec}", parts[0])).is_none()
2173 {
2174 return None;
2175 }
2176 return Some(Place {
2177 scope: parts[0].into(),
2178 section,
2179 key: parts.get(2).map(|s| s.to_string()),
2180 });
2181 }
2182 self.sections.iter().find_map(|s| {
2183 s.groups
2184 .iter()
2185 .flat_map(|g| &g.items)
2186 .any(|i| match i {
2187 Item::Field(f) => f.setting_id() == Some(link),
2188 Item::Widget(w) => w.settings().any(|x| x == link),
2189 _ => false,
2190 })
2191 .then(|| Place {
2192 scope: s.scope.clone(),
2193 section: Some(s.meta.id.clone()),
2194 key: Some(link.into()),
2195 })
2196 })
2197 }
2198
2199 pub fn fields(&self) -> Vec<(String, &Field)> {
2201 self.sections
2202 .iter()
2203 .flat_map(|s| {
2204 s.groups.iter().flat_map(move |g| {
2205 g.items.iter().filter_map(move |i| match i {
2206 Item::Field(f) => Some((s.path(), f)),
2207 _ => None,
2208 })
2209 })
2210 })
2211 .collect()
2212 }
2213}
2214
2215#[cfg(test)]
2216mod tests {
2217 use super::*;
2218
2219 #[test]
2220 fn a_path_field_chooses_a_folder_with_its_own_title_and_purpose() {
2221 let f = Field::draft("node", "library", "Library", FieldKind::Text)
2222 .open_folder()
2223 .dialog_title("Choose the library folder")
2224 .dialog_purpose("app.library");
2225 assert_eq!(f.kind, Some(FieldKind::Path));
2226 let file = f.input.file.as_ref().unwrap();
2227 assert!(file.folder && !file.save);
2228 assert_eq!(file.title, "Choose the library folder");
2229 assert_eq!(file.purpose, "app.library");
2230 let json = serde_json::to_value(&f.input.file).unwrap();
2231 assert_eq!(json["folder"], true);
2232 let f = Field::draft("node", "enrol", "Enrolment", FieldKind::Text)
2233 .open_file(&["enrol"])
2234 .filter_name("Enrolment files");
2235 assert_eq!(f.input.file.unwrap().filter_name, "Enrolment files");
2236 let f = Field::draft("node", "x", "X", FieldKind::Text).dialog_title("T");
2238 assert!(f.input.file.is_none());
2239 }
2240 use serde_json::json;
2241
2242 fn sample() -> Manifest {
2243 Manifest::new(FORMAT)
2244 .scope("backup", "Backup", "shield")
2245 .section("backup/strategy", "Strategy", |s| {
2246 s.description("How many copies, and where.")
2247 .group("copies", "Copies")
2248 .field(Field::setting("backup.copies").scopes(&[ValueScope::new("library")]))
2249 .field(
2250 Field::draft("import", "into", "Into", FieldKind::Path)
2251 .validate("writable"),
2252 )
2253 .status(Status::command(
2254 "last",
2255 "Last backup",
2256 "backup.status",
2257 "/last",
2258 ))
2259 .action(
2260 Action::command("library.backupNow")
2261 .primary()
2262 .args(json!({"copies": "${copies}"})),
2263 )
2264 .callout(Callout::new("hint", Tone::Warning, "No disk yet."))
2265 .widget("browser", "file-browser", json!({"modes": ["grid"]}));
2266 })
2267 }
2268
2269 #[test]
2270 fn a_widget_claims_the_settings_it_edits() {
2271 let m = Manifest::new(FORMAT).section("interface/fonts", "Fonts", |s| {
2272 s.field(Field::setting("text.size")).widget(
2273 "fonts",
2274 "fonts",
2275 json!({ "settings": ["text.font_ui", "text.font_mono"] }),
2276 );
2277 });
2278 let bound: Vec<&str> = m.bound_settings().collect();
2279 assert_eq!(bound, ["text.size", "text.font_ui", "text.font_mono"]);
2280 }
2281
2282 #[test]
2283 fn a_manifest_round_trips_through_json() {
2284 let m = sample();
2285 let json = m.to_json();
2286 assert_eq!(json["version"], FORMAT);
2287 assert_eq!(
2288 json["sections"][0]["groups"][0]["items"][0]["node"],
2289 "field"
2290 );
2291 assert_eq!(Manifest::from_json(&json).unwrap(), m);
2292 let text = serde_json::to_string(&m).unwrap();
2293 let back: Manifest = serde_json::from_str(&text).unwrap();
2294 assert_eq!(back, m);
2295 }
2296
2297 #[test]
2298 fn a_newer_manifest_is_refused() {
2299 let mut json = sample().to_json();
2300 json["version"] = json!(FORMAT + 1);
2301 assert!(matches!(
2302 Manifest::from_json(&json),
2303 Err(ManifestError::Newer { .. })
2304 ));
2305 assert!(matches!(
2306 Manifest::from_json(&json!({})),
2307 Err(ManifestError::Parse(_))
2308 ));
2309 }
2310
2311 #[test]
2312 fn the_check_leaves_out_what_does_not_resolve() {
2313 let mut m = sample().section("nowhere/x", "X", |s| {
2314 s.field(Field::setting("a"));
2315 });
2316 let d = m.check(&[], &|id| id != "backup.copies");
2317 assert_eq!(m.sections.len(), 1);
2318 assert_eq!(m.sections[0].groups[0].items.len(), 5);
2320 let codes: Vec<&str> = d.all().iter().map(|x| x.code).collect();
2321 assert!(codes.contains(&"admin-no-scope"), "{codes:?}");
2322 assert!(codes.contains(&"admin-no-setting"), "{codes:?}");
2323 }
2324
2325 #[test]
2326 fn deep_links_resolve_to_a_place() {
2327 let mut t = Tree::default();
2328 t.merge(sample());
2329 let p = t.resolve("backup/strategy/copies").unwrap();
2330 assert_eq!(p.section.as_deref(), Some("strategy"));
2331 assert_eq!(p.key.as_deref(), Some("copies"));
2332 let p = t.resolve("backup.copies").unwrap();
2333 assert_eq!(
2334 (p.scope.as_str(), p.key.as_deref()),
2335 ("backup", Some("backup.copies"))
2336 );
2337 assert!(t.resolve("backup/none").is_none());
2338 assert!(t.resolve("nothing").is_none());
2339 assert_eq!(t.shown_scopes().len(), 1);
2340 t.merge(Manifest::new(FORMAT).section("backup/disks", "Disks", |s| {
2342 s.widget(
2343 "page",
2344 "settings-page",
2345 json!({ "settings": ["backup.disk"] }),
2346 );
2347 }));
2348 let p = t.resolve("backup.disk").unwrap();
2349 assert_eq!(
2350 (p.section.as_deref(), p.key.as_deref()),
2351 (Some("disks"), Some("backup.disk"))
2352 );
2353 }
2354
2355 fn paths_of(t: &Tree, scope: &str) -> Vec<String> {
2356 t.sections_of(scope).iter().map(|s| s.path()).collect()
2357 }
2358
2359 fn page(m: Manifest, path: &str) -> Manifest {
2360 m.section(path, path, |_| {})
2361 }
2362
2363 #[test]
2364 fn inserting_in_one_manifest_never_moves_another_s_sections() {
2365 let other = || {
2368 page(
2369 page(Manifest::new(FORMAT), "interface/language"),
2370 "interface/units",
2371 )
2372 };
2373 let before = |nodes: bool| {
2374 let mut m = page(Manifest::new(FORMAT), "storage/volumes");
2375 if nodes {
2376 m = page(m, "storage/nodes");
2377 }
2378 page(m, "interface/workbench")
2379 };
2380 let mut t = Tree::default();
2381 t.merge(before(false));
2382 t.merge(other());
2383 let was = paths_of(&t, "interface");
2384 let mut t = Tree::default();
2385 t.merge(before(true));
2386 t.merge(other());
2387 assert_eq!(paths_of(&t, "interface"), was);
2388 assert_eq!(
2389 was,
2390 [
2391 "interface/workbench",
2392 "interface/language",
2393 "interface/units"
2394 ]
2395 );
2396 assert_eq!(
2397 paths_of(&t, "storage"),
2398 ["storage/volumes", "storage/nodes"]
2399 );
2400 assert!(t.order_diagnostics().is_empty());
2401 }
2402
2403 #[test]
2404 fn the_default_ranking_keeps_the_generated_pages_places() {
2405 let mut t = Tree::default();
2408 t.merge(super::generate::settings([
2409 super::generate::Entry {
2410 id: "appearance.theme",
2411 section: "Appearance",
2412 },
2413 super::generate::Entry {
2414 id: "general.a",
2415 section: "Startup",
2416 },
2417 super::generate::Entry {
2418 id: "general.b",
2419 section: "Files",
2420 },
2421 ]));
2422 t.merge(page(Manifest::new(FORMAT), "general/greeting"));
2423 assert_eq!(
2424 paths_of(&t, "general"),
2425 ["general/greeting", "general/startup", "general/files"]
2426 );
2427 }
2428
2429 #[test]
2430 fn an_anchor_places_a_section_among_another_manifest_s() {
2431 let mut t = Tree::default();
2432 t.merge(page(
2433 page(
2434 page(Manifest::new(FORMAT), "storage/volumes"),
2435 "storage/cards",
2436 ),
2437 "storage/trash",
2438 ));
2439 t.merge(
2440 Manifest::new(FORMAT)
2441 .section("storage/nodes", "Nodes", |s| {
2442 s.after("storage/volumes");
2443 })
2444 .section("storage/peers", "Peers", |s| {
2445 s.after("volumes");
2446 })
2447 .section("storage/first", "First", |s| {
2448 s.before("storage/volumes");
2449 }),
2450 );
2451 assert_eq!(
2452 paths_of(&t, "storage"),
2453 [
2454 "storage/first",
2455 "storage/volumes",
2456 "storage/nodes",
2457 "storage/peers",
2458 "storage/cards",
2459 "storage/trash"
2460 ]
2461 );
2462 let mut t = Tree::default();
2465 t.merge(
2466 Manifest::new(FORMAT).section("storage/nodes", "Nodes", |s| {
2467 s.after("storage/volumes");
2468 }),
2469 );
2470 t.merge(page(
2471 page(Manifest::new(FORMAT), "storage/volumes"),
2472 "storage/cards",
2473 ));
2474 assert_eq!(
2475 paths_of(&t, "storage"),
2476 ["storage/volumes", "storage/nodes", "storage/cards"]
2477 );
2478 assert!(t.order_diagnostics().is_empty());
2479 let m = Manifest::new(FORMAT).section("storage/nodes", "Nodes", |s| {
2481 s.after("storage/volumes");
2482 });
2483 assert_eq!(Manifest::from_json(&m.to_json()).unwrap(), m);
2484 }
2485
2486 #[test]
2487 fn an_unknown_anchor_is_reported_and_falls_to_the_end_of_its_scope() {
2488 let mut t = Tree::default();
2489 t.merge(
2490 Manifest::new(FORMAT)
2491 .section("storage/lost", "Lost", |s| {
2492 s.after("storage/nowhere");
2493 })
2494 .section("storage/elsewhere", "Elsewhere", |s| {
2495 s.after("interface/language");
2497 }),
2498 );
2499 t.merge(page(
2500 page(
2501 page(Manifest::new(FORMAT), "storage/volumes"),
2502 "interface/language",
2503 ),
2504 "storage/cards",
2505 ));
2506 assert_eq!(
2507 paths_of(&t, "storage"),
2508 [
2509 "storage/volumes",
2510 "storage/cards",
2511 "storage/lost",
2512 "storage/elsewhere"
2513 ]
2514 );
2515 let codes: Vec<(&str, &str)> = t
2516 .order_diagnostics()
2517 .iter()
2518 .map(|d| (d.code, d.subject.as_str()))
2519 .collect();
2520 assert_eq!(
2521 codes,
2522 [
2523 ("admin-unknown-anchor", "storage/lost"),
2524 ("admin-unknown-anchor", "storage/elsewhere")
2525 ]
2526 );
2527 }
2528
2529 #[test]
2530 fn an_explicit_order_weighs_across_manifests_and_a_tie_is_reported() {
2531 let mut t = Tree::default();
2532 t.merge(
2533 Manifest::new(FORMAT)
2534 .section("general/about", "About", |_| {})
2535 .section("general/advanced", "Advanced", |s| {
2536 s.order(2000);
2537 }),
2538 );
2539 t.merge(page(Manifest::new(FORMAT), "general/language"));
2540 assert_eq!(
2541 paths_of(&t, "general"),
2542 ["general/about", "general/language", "general/advanced"]
2543 );
2544 assert!(t.order_diagnostics().is_empty());
2545 t.merge(Manifest::new(FORMAT).section("general/last", "Last", |s| {
2546 s.order(2000);
2547 }));
2548 assert_eq!(
2549 paths_of(&t, "general"),
2550 [
2551 "general/about",
2552 "general/language",
2553 "general/advanced",
2554 "general/last"
2555 ]
2556 );
2557 let d = t.order_diagnostics();
2558 assert_eq!(d.len(), 1);
2559 assert_eq!(d[0].code, "admin-order-tie");
2560 assert!(
2561 d[0].message.contains("general/advanced") && d[0].message.contains("general/last"),
2562 "{}",
2563 d[0].message
2564 );
2565 }
2566
2567 #[test]
2568 fn records_read_their_rows_and_round_trip() {
2569 let r = Records::command("volumes", "Volumes", "storage.volumes", "/volumes", "id")
2570 .column("name", "Name")
2571 .tone("level")
2572 .row_action(Action::command("storage.forget").args(json!({"volume": "${row.id}"})))
2573 .empty("No disk yet.", None)
2574 .when("form.copies > 0");
2575 let m = Manifest::new(FORMAT)
2576 .scope("storage", "Storage", "disk")
2577 .section("storage/volumes", "Volumes", |s| {
2578 s.table(r.clone());
2579 });
2580 assert_eq!(Manifest::from_json(&m.to_json()).unwrap(), m);
2581 assert_eq!(
2582 m.to_json()["sections"][0]["groups"][0]["items"][0]["node"],
2583 "table"
2584 );
2585 let answer = json!({"volumes": [{"id": "a", "name": "Disk"}, 3]});
2586 assert_eq!(Records::rows_of(&answer, "/volumes").len(), 1);
2587 assert!(Records::rows_of(&answer, "/none").is_empty());
2588 assert_eq!(cell_text(&json!(["a", 2])), "a, 2");
2589 assert_eq!(tone_named("problem"), Some(Tone::Danger));
2590 }
2591
2592 #[test]
2593 fn a_detail_sheet_round_trips_and_titles_itself() {
2594 let r = Records::command("nodes", "Nodes", "storage.nodes", "/nodes", "id")
2595 .titles("name", None)
2596 .detail(Detail::new().line("kind", "Kind").line("status", "Status"));
2597 let m = Manifest::new(FORMAT).section("storage/nodes", "Nodes", |s| {
2598 s.list(r.clone());
2599 });
2600 assert_eq!(Manifest::from_json(&m.to_json()).unwrap(), m);
2601 let item = &m.to_json()["sections"][0]["groups"][0]["items"][0];
2602 assert_eq!(item["detail"]["lines"][1]["key"], "status");
2603 assert!(item["detail"].get("title_key").is_none());
2604 let row = json!({"id": "n1", "name": "NAS", "host": "cloudy"});
2605 assert_eq!(r.row_title(&row), "NAS");
2606 assert_eq!(r.detail_title(&row), "NAS");
2607 let r = r.detail(Detail::new().title("host"));
2608 assert_eq!(r.detail_title(&row), "cloudy");
2609 assert_eq!(r.detail_title(&json!({"id": "n2", "name": "PC"})), "PC");
2611 let plain = Records::hook("x", "", "h", "id");
2613 assert!(
2614 serde_json::to_value(&plain)
2615 .unwrap()
2616 .get("detail")
2617 .is_none()
2618 );
2619 assert_eq!(plain.row_title(&row), "n1");
2620 assert_eq!(plain.column("host", "Host").row_title(&row), "cloudy");
2621 }
2622
2623 #[test]
2624 fn an_icon_column_and_its_cells_round_trip() {
2625 let r = Records::command("nodes", "Nodes", "storage.nodes", "/nodes", "id")
2626 .column("name", "Name")
2627 .icon("state", "State", Some("why"));
2628 let json = serde_json::to_value(&r).unwrap();
2629 assert_eq!(
2630 json["columns"][1],
2631 json!({ "key": "state", "title": "State", "kind": "icon", "text": "why" })
2632 );
2633 assert_eq!(serde_json::from_value::<Records>(json).unwrap(), r);
2634
2635 let cell = IconCell::new("phosphor:cloud-slash")
2636 .tone(Tone::Muted)
2637 .tip(CellText::key("node-offline", "Offline since { $since }").arg("since", "Monday"));
2638 let json = serde_json::to_value(&cell).unwrap();
2639 assert_eq!(
2640 json,
2641 json!({ "icon": "phosphor:cloud-slash", "tone": "muted", "tip": {
2642 "key": "node-offline", "text": "Offline since { $since }",
2643 "args": { "since": "Monday" } } })
2644 );
2645 assert_eq!(
2646 serde_json::from_value::<IconCell>(json.clone()).unwrap(),
2647 cell
2648 );
2649 assert_eq!(IconCell::of(&json), Some(cell));
2650
2651 let plain = IconCell::new("success").tip(CellText::plain("Online"));
2654 let json = serde_json::to_value(&plain).unwrap();
2655 assert_eq!(json, json!({ "icon": "success", "tip": "Online" }));
2656 assert_eq!(serde_json::from_value::<IconCell>(json).unwrap(), plain);
2657 assert_eq!(
2658 IconCell::of(&json!("warning")),
2659 Some(IconCell::new("warning"))
2660 );
2661 assert_eq!(
2662 IconCell::of(&json!({ "icon": "error", "tone": "problem" })),
2663 Some(IconCell::new("error").tone(Tone::Danger))
2664 );
2665 assert_eq!(IconCell::of(&Json::Null), None);
2666 assert_eq!(IconCell::of(&json!("")), None);
2667 assert_eq!(tone_named("muted"), Some(Tone::Muted));
2668 }
2669
2670 #[test]
2671 fn clauses_read_the_forms_values_and_bad_ones_are_reported() {
2672 let mut v = hooks::Values::new();
2673 v.insert("copy".into(), json!(true));
2674 v.insert("mode".into(), json!("fast"));
2675 let cx = form_context(WhenContext::new(), &v);
2676 assert!(holds(Some("form.copy"), &cx));
2677 assert!(holds(Some("form.mode == fast"), &cx));
2678 assert!(!holds(Some("!form.copy"), &cx));
2679 assert!(holds(None, &cx));
2680 let mut m = Manifest::new(FORMAT)
2681 .scope("a", "A", "x")
2682 .section("a/b", "B", |s| {
2683 s.when("((")
2684 .action(Action::command("x").enabled("(((", "never"));
2685 });
2686 let d = m.check(&[], &|_| true);
2687 let codes: Vec<&str> = d.all().iter().map(|x| x.code).collect();
2688 assert_eq!(codes, ["admin-bad-clause", "admin-bad-clause"]);
2689 assert!(m.sections[0].meta.when.is_none());
2690 }
2691
2692 #[test]
2693 fn row_fields_fill_their_command_with_the_row_and_the_value() {
2694 let f = RowField::text(
2695 "name",
2696 "Name",
2697 "storage.volumeSet",
2698 json!({"volume": "${row.id}", "name": "${value}"}),
2699 );
2700 let row = json!({"id": "d1", "name": "Disk", "dests": [{"value": "a", "label": "A"}, 3]});
2701 let v = Records::row_values(&hooks::Values::new(), &row);
2702 assert_eq!(
2703 f.write_args(&v, json!("Studio")),
2704 json!({"volume": "d1", "name": "Studio"})
2705 );
2706 let c = RowField::choice("dest", "To", &[(json!("any"), "Any")], "x", Json::Null)
2707 .choices_from("dests");
2708 let labels: Vec<String> = c.choices_of(&row).into_iter().map(|c| c.label).collect();
2709 assert_eq!(labels, ["Any", "A"]);
2710 let r = Records::command("v", "", "c", "", "id")
2711 .column("name", "Name")
2712 .meter("share", "Space", "spaceText")
2713 .row_field(f)
2714 .row_field(RowField::toggle("raid", "RAID", "x", Json::Null).when("row.online"));
2715 assert!(r.field_for("name").is_some());
2716 assert_eq!(r.extra_fields().count(), 1);
2717 assert_eq!(
2718 Manifest::from_json(&Manifest::new(FORMAT).to_json())
2719 .unwrap()
2720 .version,
2721 FORMAT
2722 );
2723 let cx = row_context(WhenContext::new(), &json!({"online": true, "weak": false}));
2724 assert!(holds(Some("row.online"), &cx));
2725 assert!(!holds(Some("row.weak"), &cx));
2726 assert_eq!(meter_share(&json!(1.5)), Some(1.0));
2727 assert_eq!(meter_share(&json!("x")), None);
2728 assert_eq!(
2730 Records::rows_of(&json!({"s": {"set": true}}), "/s").len(),
2731 1
2732 );
2733 let m = Manifest::new(FORMAT)
2734 .scope("s", "S", "x")
2735 .section("s/v", "V", |s| {
2736 s.table(r.clone());
2737 });
2738 assert_eq!(Manifest::from_json(&m.to_json()).unwrap(), m);
2739 }
2740
2741 #[test]
2742 fn a_confirmation_names_the_row() {
2743 let a = Action::command("storage.forget")
2744 .confirmation(Confirmation::new("Forget ${row.name}?", "It goes.", "Forget").danger());
2745 let json = serde_json::to_value(&a).unwrap();
2746 assert_eq!(json["confirmation"]["danger"], true);
2747 let back: Action = serde_json::from_value(json).unwrap();
2748 assert_eq!(back, a);
2749 let v = Records::row_values(&hooks::Values::new(), &json!({"name": "Disk"}));
2750 let c = a.confirmation.unwrap().filled(&v);
2751 assert_eq!(c.title, "Forget Disk?");
2752 assert!(c.danger);
2753 }
2754
2755 #[test]
2756 fn there_are_eleven_field_kinds() {
2757 assert_eq!(FieldKind::ALL.len(), 11);
2758 let names: Vec<String> = FieldKind::ALL
2759 .iter()
2760 .map(|k| {
2761 serde_json::to_value(k)
2762 .unwrap()
2763 .as_str()
2764 .unwrap()
2765 .to_string()
2766 })
2767 .collect();
2768 assert!(names.contains(&"long-text".to_string()));
2769 assert!(names.contains(&"note".to_string()));
2770 }
2771
2772 #[test]
2773 fn a_note_reads_its_draft_value_else_its_title() {
2774 let f = Field::note("rename", "also", "Also updates 2 templates");
2775 assert_eq!(f.kind, Some(FieldKind::Note));
2776 assert_eq!(f.draft_key(), Some("also"));
2777 assert_eq!(f.input.default, json!("Also updates 2 templates"));
2778 assert_eq!(
2779 f.note_text(&json!("Also updates 1 smart album")),
2780 "Also updates 1 smart album"
2781 );
2782 assert_eq!(f.note_text(&json!(3)), "3");
2783 assert_eq!(f.note_text(&Json::Null), "");
2784 let titled = Field::draft("t", "k", "Nothing else changes", FieldKind::Note);
2785 assert_eq!(titled.note_text(&json!(" ")), "Nothing else changes");
2786 assert_eq!(f.check(&Json::Null), None, "a note is never required");
2787 }
2788
2789 #[test]
2790 fn an_unknown_brick_degrades_with_a_diagnostic() {
2791 let json = json!({
2792 "version": FORMAT,
2793 "scopes": [{"id": "s", "title": "S"}],
2794 "sections": [{"id": "v", "title": "V", "scope": "s", "groups": [{
2795 "id": "g", "title": "G",
2796 "items": [
2797 {"node": "callout", "id": "c", "tone": "info", "text": "Hello"},
2798 {"node": "gauge", "id": "future", "title": "Later", "needle": 3},
2799 {"node": "callout", "id": "d", "tone": "info", "text": "Still here"},
2800 ],
2801 }]}],
2802 "wizards": [{"id": "w", "title": "W", "finish": {"command": "x.go"}, "steps": [{"id": "one", "title": "One",
2803 "groups": [{"id": "g", "title": "G", "items": [
2804 {"node": "slider3d", "id": "z"},
2805 ]}]}]}],
2806 });
2807 let mut m = Manifest::from_json(&json).expect("an unknown node does not fail the page");
2808 let items = &m.sections[0].groups[0].items;
2809 let Item::Unknown(u) = &items[1] else {
2810 panic!("read as unknown: {items:?}");
2811 };
2812 assert_eq!((u.node.as_str(), u.meta.id.as_str()), ("gauge", "future"));
2813 assert_eq!(
2815 serde_json::to_value(&items[1]).unwrap(),
2816 json["sections"][0]["groups"][0]["items"][1]
2817 );
2818 let d = m.check(&[], &|_| true);
2819 assert_eq!(d.codes(), vec!["admin-unknown-node", "admin-unknown-node"]);
2820 let ids: Vec<&str> = m.sections[0].groups[0]
2821 .items
2822 .iter()
2823 .map(|i| i.meta().id.as_str())
2824 .collect();
2825 assert_eq!(ids, ["c", "d"], "the rest of the page still shows");
2826 assert!(m.wizards[0].steps[0].groups[0].items.is_empty());
2827 }
2828
2829 #[test]
2830 fn a_known_brick_that_does_not_read_is_still_an_error() {
2831 let json = json!({
2832 "version": FORMAT,
2833 "sections": [{"id": "v", "title": "V", "scope": "s", "groups": [{
2834 "id": "g", "title": "G",
2835 "items": [{"node": "callout", "id": "c", "tone": 42, "text": "x"}],
2836 }]}],
2837 });
2838 assert!(matches!(
2839 Manifest::from_json(&json),
2840 Err(ManifestError::Parse(_))
2841 ));
2842 }
2843}