Skip to main content

artifactize_core/review/
form.rs

1//! Owner fields for one verdict, as a person enters them. A Human eval's result schemas may
2//! use only shapes a form can enter ([`check`] refuses any other when the declaration loads):
3//! an object whose properties are strings, integers, numbers, booleans, string choices and
4//! constants, lists of strings, and lists of flat objects of those scalars (repeated groups).
5
6use serde_json::{Map, Value, json};
7
8/// Annotations allowed on any schema the form accepts.
9const NOTES: [&str; 3] = ["title", "description", "$comment"];
10/// Keys of the result object itself, and of each object in a list of groups.
11const OBJECT: [&str; 4] = ["type", "properties", "required", "additionalProperties"];
12const STRING: [&str; 3] = ["type", "minLength", "maxLength"];
13const NUMERIC: [&str; 6] = [
14    "type",
15    "minimum",
16    "maximum",
17    "exclusiveMinimum",
18    "exclusiveMaximum",
19    "multipleOf",
20];
21const ARRAY: [&str; 4] = ["type", "items", "minItems", "maxItems"];
22/// What a Human result schema may hold, as a declaration error says it.
23const SHAPES: &str = "a Human result field is a string (with minLength or maxLength), an \
24integer or number, a boolean, a string enum, a const, an array of strings, or an array of \
25objects whose properties are those scalars";
26
27/// A key as the form edits with it; each interface maps its own key events onto these.
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub enum Key {
30    Char(char),
31    Backspace,
32    Delete,
33    Left,
34    Right,
35    Up,
36    Down,
37    Home,
38    End,
39    Enter,
40    Tab,
41    BackTab,
42    /// A key the form does not use.
43    Other,
44}
45
46#[derive(Debug, Clone, PartialEq)]
47pub enum Input {
48    /// A `const` value: filled in and fixed.
49    Fixed(Value),
50    /// `None` until chosen.
51    Bool(Option<bool>),
52    /// String `enum` options and the chosen index.
53    Choice(Choice),
54    Text(String),
55    Integer(String),
56    Number(String),
57    /// An array of strings, one entry per item; empty entries are left out of the result.
58    List(Vec<String>),
59    /// An array of flat objects: one group of fields per item. `fields` is an empty item;
60    /// an item with nothing entered is left out of the result.
61    Groups {
62        fields: Vec<Field>,
63        items: Vec<Vec<Field>>,
64    },
65}
66
67/// A nonempty string enum, with an optional index into its own options.
68#[derive(Debug, Clone, PartialEq, Eq)]
69pub struct Choice {
70    options: Vec<String>,
71    selected: Option<usize>,
72}
73
74impl Choice {
75    pub fn new(options: Vec<String>) -> Option<Self> {
76        (!options.is_empty()).then_some(Self {
77            options,
78            selected: None,
79        })
80    }
81
82    pub fn options(&self) -> &[String] {
83        &self.options
84    }
85
86    pub fn selected(&self) -> Option<usize> {
87        self.selected
88    }
89
90    /// Restore a draft selection. An index no longer offered clears the selection.
91    pub fn select(&mut self, selected: Option<usize>) {
92        self.selected = selected.filter(|&index| index < self.options.len());
93    }
94
95    fn value(&self) -> Option<Value> {
96        self.selected
97            .map(|index| Value::String(self.options[index].clone()))
98    }
99
100    fn cycle(&mut self, backwards: bool, required: bool) {
101        self.selected = if backwards {
102            match self.selected {
103                Some(0) if !required => None,
104                Some(0) | None => Some(self.options.len() - 1),
105                Some(index) => Some(index - 1),
106            }
107        } else {
108            match self.selected {
109                None => Some(0),
110                Some(index) if index + 1 < self.options.len() => Some(index + 1),
111                Some(_) if required => Some(0),
112                Some(_) => None,
113            }
114        };
115    }
116}
117
118#[derive(Debug, Clone, PartialEq)]
119pub struct Field {
120    pub name: String,
121    pub required: bool,
122    /// The type and constraints, then any description.
123    pub hint: String,
124    pub input: Input,
125}
126
127/// One row a terminal form moves through: a field, a field of one group, or a group list's
128/// `+ Add`. Constants are filled in and get no row.
129#[derive(Debug, Clone, Copy, PartialEq, Eq)]
130pub enum Row {
131    Field(usize),
132    Item {
133        field: usize,
134        item: usize,
135        sub: usize,
136    },
137    Add(usize),
138}
139
140impl Field {
141    /// The JSON value to submit, named `label` in errors; `None` leaves an empty optional
142    /// field out.
143    fn value(&self, label: &str) -> Result<Option<Value>, String> {
144        let number = |text: &str, integer: bool| {
145            let value: Value = serde_json::from_str(text.trim()).unwrap_or_default();
146            let valid = if integer {
147                value.is_i64() || value.is_u64()
148            } else {
149                value.is_number()
150            };
151            let kind = if integer { "an integer" } else { "a number" };
152            valid
153                .then_some(value)
154                .ok_or_else(|| format!("{label}: enter {kind}."))
155        };
156        Ok(match &self.input {
157            Input::Fixed(value) => Some(value.clone()),
158            Input::Bool(value) => value.map(Value::Bool),
159            Input::Choice(choice) => choice.value(),
160            Input::Text(text) => (self.required || !text.is_empty()).then(|| json!(text)),
161            Input::Integer(text) | Input::Number(text) if text.trim().is_empty() => None,
162            Input::Integer(text) => Some(number(text, true)?),
163            Input::Number(text) => Some(number(text, false)?),
164            Input::List(items) => {
165                let items: Vec<_> = items
166                    .iter()
167                    .filter(|item| !item.trim().is_empty())
168                    .collect();
169                (self.required || !items.is_empty()).then(|| json!(items))
170            }
171            Input::Groups { items, .. } => {
172                let mut values = Vec::new();
173                for (at, item) in items.iter().enumerate().filter(|(_, item)| entered(item)) {
174                    let mut object = Map::new();
175                    for field in item {
176                        let label = format!("{label} {} · {}", at + 1, field.name);
177                        if let Some(value) = field.value(&label)? {
178                            object.insert(field.name.clone(), value);
179                        }
180                    }
181                    values.push(Value::Object(object));
182                }
183                (self.required || !values.is_empty()).then_some(Value::Array(values))
184            }
185        })
186    }
187
188    /// Nothing is entered yet.
189    fn empty(&self) -> bool {
190        match &self.input {
191            Input::Fixed(_) => true,
192            Input::Bool(value) => value.is_none(),
193            Input::Choice(choice) => choice.selected().is_none(),
194            Input::Text(text) | Input::Integer(text) | Input::Number(text) => {
195                text.trim().is_empty()
196            }
197            Input::List(items) => items.iter().all(|item| item.trim().is_empty()),
198            Input::Groups { items, .. } => !items.iter().any(|item| entered(item)),
199        }
200    }
201
202    /// What the form shows for the current value.
203    pub fn display(&self) -> String {
204        match &self.input {
205            Input::Fixed(value) => format!("{value} (fixed)"),
206            Input::Bool(None) => "–".into(),
207            Input::Bool(Some(value)) => value.to_string(),
208            Input::Choice(choice) => choice
209                .value()
210                .map_or_else(|| "–".into(), |value| value.to_string()),
211            Input::Text(text) | Input::Integer(text) | Input::Number(text) => text.clone(),
212            Input::List(items) if items.iter().all(String::is_empty) => "–".into(),
213            Input::List(items) => items.join("; "),
214            Input::Groups { items, .. } => format!("{} item(s)", items.len()),
215        }
216    }
217
218    fn text_like(&self) -> bool {
219        matches!(
220            self.input,
221            Input::Text(_) | Input::Integer(_) | Input::Number(_) | Input::List(_)
222        )
223    }
224
225    /// Append pasted or typed text, bounded like the Human result.
226    fn paste(&mut self, text: &str) -> Result<(), String> {
227        let fits = |size: usize| size.saturating_add(text.len()) <= crate::human::MAX_RESULT_BYTES;
228        let too_big = || {
229            format!(
230                "Human fields exceed {} bytes.",
231                crate::human::MAX_RESULT_BYTES
232            )
233        };
234        match &mut self.input {
235            Input::List(items) => {
236                if !fits(items.iter().map(String::len).sum()) {
237                    return Err(too_big());
238                }
239                match items.last_mut() {
240                    Some(item) => item.push_str(text),
241                    None => items.push(text.to_owned()),
242                }
243            }
244            Input::Text(value) | Input::Integer(value) | Input::Number(value) => {
245                if !fits(value.len()) {
246                    return Err(too_big());
247                }
248                value.push_str(text);
249            }
250            _ => {}
251        }
252        Ok(())
253    }
254
255    fn key(&mut self, key: Key) {
256        let required = self.required;
257        match (&mut self.input, key) {
258            (Input::Text(text) | Input::Integer(text) | Input::Number(text), Key::Char(c)) => {
259                text.push(c)
260            }
261            (Input::Text(text) | Input::Integer(text) | Input::Number(text), Key::Backspace) => {
262                text.pop();
263            }
264            // A list types into its last item; Enter starts the next, Backspace on an empty
265            // item removes it.
266            (Input::List(items), Key::Char(c)) => match items.last_mut() {
267                Some(item) => item.push(c),
268                None => items.push(c.to_string()),
269            },
270            (Input::List(items), Key::Enter) => items.push(String::new()),
271            (Input::List(items), Key::Backspace) => {
272                if items.last().is_some_and(String::is_empty) && items.len() > 1 {
273                    items.pop();
274                } else if let Some(item) = items.last_mut() {
275                    item.pop();
276                }
277            }
278            (Input::Bool(value), Key::Char('t' | 'y')) => *value = Some(true),
279            (Input::Bool(value), Key::Char('f' | 'n')) => *value = Some(false),
280            (Input::Bool(value), Key::Char(' ') | Key::Left | Key::Right) => {
281                *value = match value {
282                    None => Some(true),
283                    Some(true) => Some(false),
284                    Some(false) if required => Some(true),
285                    Some(false) => None,
286                }
287            }
288            (Input::Choice(choice), Key::Char(' ') | Key::Right) => choice.cycle(false, required),
289            (Input::Choice(choice), Key::Left) => choice.cycle(true, required),
290            _ => {}
291        }
292    }
293}
294
295/// Something is entered in a group.
296fn entered(item: &[Field]) -> bool {
297    item.iter().any(|field| !field.empty())
298}
299
300#[derive(Debug, Clone, PartialEq)]
301pub struct Form {
302    pub verdict: crate::runtime::Verdict,
303    pub fields: Vec<Field>,
304    /// The selected row of [`Form::rows`].
305    pub selected: usize,
306    /// The last local or `human::submit` error.
307    pub error: Option<String>,
308}
309
310impl Form {
311    /// Open the form using an already validated specification.
312    pub fn from_spec(verdict: crate::runtime::Verdict, spec: &Specification) -> Self {
313        Self {
314            verdict,
315            fields: spec.0.clone(),
316            selected: 0,
317            error: None,
318        }
319    }
320
321    /// Parse an externally supplied JSON schema into a form at the input boundary.
322    pub fn new(verdict: crate::runtime::Verdict, schema: Option<&Value>) -> Result<Self, String> {
323        let schema = schema
324            .map(|value| {
325                value
326                    .as_object()
327                    .ok_or("A Human result schema must be a JSON object.")
328            })
329            .transpose()?;
330        Ok(Self::from_spec(verdict, &Specification::parse(schema)?))
331    }
332
333    /// The typed answer after validating the form's fields.
334    pub fn submission(&self) -> Result<super::Submission, String> {
335        let object = self
336            .fields
337            .iter()
338            .filter_map(|field| {
339                field
340                    .value(&field.name)
341                    .transpose()
342                    .map(|value| value.map(|value| (field.name.clone(), value)))
343            })
344            .collect::<Result<Map<_, _>, _>>()?;
345        if object.contains_key("verdict") {
346            return Err("Choose the verdict in the review, not inside the owner fields.".into());
347        }
348        super::Submission::new(self.verdict, object)
349    }
350
351    /// The complete result as JSON: owner fields plus the chosen verdict.
352    pub fn result(&self) -> Result<Value, String> {
353        self.submission().map(|submission| submission.to_json())
354    }
355
356    /// The rows a person moves through, in order.
357    pub fn rows(&self) -> Vec<Row> {
358        let mut rows = Vec::new();
359        for (index, field) in self.fields.iter().enumerate() {
360            match &field.input {
361                Input::Fixed(_) => {}
362                Input::Groups { items, .. } => {
363                    for (item, fields) in items.iter().enumerate() {
364                        let subs = fields.iter().enumerate();
365                        rows.extend(
366                            subs.filter(|(_, sub)| !matches!(sub.input, Input::Fixed(_)))
367                                .map(|(sub, _)| Row::Item {
368                                    field: index,
369                                    item,
370                                    sub,
371                                }),
372                        );
373                    }
374                    rows.push(Row::Add(index));
375                }
376                _ => rows.push(Row::Field(index)),
377            }
378        }
379        rows
380    }
381
382    /// The selected row, if the form has any.
383    pub fn row(&self) -> Option<Row> {
384        self.rows().get(self.selected).copied()
385    }
386
387    /// The field a row edits.
388    pub fn field(&self, row: Row) -> Option<&Field> {
389        match row {
390            Row::Field(index) | Row::Add(index) => self.fields.get(index),
391            Row::Item { field, item, sub } => match &self.fields.get(field)?.input {
392                Input::Groups { items, .. } => items.get(item)?.get(sub),
393                _ => None,
394            },
395        }
396    }
397
398    fn field_mut(&mut self, row: Row) -> Option<&mut Field> {
399        match row {
400            Row::Field(index) => self.fields.get_mut(index),
401            Row::Add(_) => None,
402            Row::Item { field, item, sub } => match &mut self.fields.get_mut(field)?.input {
403                Input::Groups { items, .. } => items.get_mut(item)?.get_mut(sub),
404                _ => None,
405            },
406        }
407    }
408
409    /// Add an empty item to the list of field `index`: an empty text to a list of strings, an
410    /// empty group to a list of groups, which the selection moves into.
411    pub fn add(&mut self, index: usize) {
412        match self.fields.get_mut(index).map(|field| &mut field.input) {
413            Some(Input::List(items)) => items.push(String::new()),
414            Some(Input::Groups { fields, items }) => {
415                items.push(fields.clone());
416                let item = items.len() - 1;
417                if let Some(at) = self.rows().iter().position(
418                    |row| matches!(row, Row::Item { field, item: i, .. } if *field == index && *i == item),
419                ) {
420                    self.selected = at;
421                }
422            }
423            _ => {}
424        }
425    }
426
427    /// Remove item `item` of the list of field `index`; one empty item always stays to type in.
428    pub fn remove(&mut self, index: usize, item: usize) {
429        match self.fields.get_mut(index).map(|field| &mut field.input) {
430            Some(Input::List(items)) => {
431                if item < items.len() {
432                    items.remove(item);
433                }
434                if items.is_empty() {
435                    items.push(String::new());
436                }
437            }
438            Some(Input::Groups { fields, items }) => {
439                if item < items.len() {
440                    items.remove(item);
441                }
442                if items.is_empty() {
443                    items.push(fields.clone());
444                }
445            }
446            _ => return,
447        }
448        self.selected = self.selected.min(self.rows().len().saturating_sub(1));
449    }
450
451    /// Remove the group the selection is in.
452    pub fn remove_selected(&mut self) {
453        if let Some(Row::Item { field, item, .. }) = self.row() {
454            self.remove(field, item);
455        }
456    }
457
458    /// Bounded paste follows the existing Human result limit, without splitting UTF-8.
459    pub fn paste(&mut self, text: &str) {
460        let Some(row) = self.row() else {
461            return;
462        };
463        if let Some(field) = self.field_mut(row)
464            && let Err(error) = field.paste(text)
465        {
466            self.error = Some(error);
467        }
468    }
469
470    /// A key typed into the form. Enter never submits: on `+ Add` it adds a group, in a list
471    /// it starts the next item. Keys with Control or Alt are not the form's.
472    pub fn inline_key(&mut self, key: Key, modified: bool) {
473        if modified {
474            return;
475        }
476        let row = self.row();
477        let text = row
478            .and_then(|row| self.field(row))
479            .is_some_and(Field::text_like);
480        match (key, row) {
481            (Key::Char(character), _) if text => self.paste(&character.to_string()),
482            (Key::Enter | Key::Char(' '), Some(Row::Add(index))) => self.add(index),
483            _ => self.key(key),
484        }
485    }
486
487    pub fn key(&mut self, key: Key) {
488        let count = self.rows().len();
489        match key {
490            Key::Up | Key::BackTab if count > 0 => {
491                self.selected = (self.selected + count - 1) % count
492            }
493            Key::Down | Key::Tab if count > 0 => self.selected = (self.selected + 1) % count,
494            _ => {
495                if let Some(row) = self.row()
496                    && let Some(field) = self.field_mut(row)
497                {
498                    field.key(key);
499                }
500            }
501        }
502    }
503}
504
505/// Whether a Human eval may declare `schema` as a result schema: only shapes a form can
506/// enter. The error names the offending key and what is allowed instead.
507#[derive(Debug, Clone, Default, PartialEq)]
508pub struct Specification(Vec<Field>);
509
510impl Specification {
511    pub(crate) fn parse(schema: Option<&Map<String, Value>>) -> Result<Self, String> {
512        schema.map_or_else(
513            || Ok(Self::default()),
514            |schema| fields(schema, "").map(Self),
515        )
516    }
517}
518
519#[cfg(test)]
520fn check(schema: &Map<String, Value>) -> Result<(), String> {
521    Specification::parse(Some(schema)).map(drop)
522}
523
524/// The fields of an object schema at `path` (empty for the result itself).
525fn fields(schema: &Map<String, Value>, path: &str) -> Result<Vec<Field>, String> {
526    let at = |key: &str| {
527        if path.is_empty() {
528            key.to_owned()
529        } else {
530            format!("{path}.{key}")
531        }
532    };
533    if let Some(key) = schema
534        .keys()
535        .find(|key| !OBJECT.contains(&key.as_str()) && !NOTES.contains(&key.as_str()))
536    {
537        let what = if path.is_empty() {
538            "A Human result schema"
539        } else {
540            "An object in a Human result list"
541        };
542        return Err(format!(
543            "{what} may use only type, properties, required and additionalProperties (with \
544             title, description and $comment); `{}` is not allowed.",
545            at(key)
546        ));
547    }
548    if let Some(kind) = schema.get("type")
549        && kind != "object"
550    {
551        return Err(format!("`{}` must be \"object\".", at("type")));
552    }
553    if schema
554        .get("additionalProperties")
555        .is_some_and(|value| !value.is_boolean())
556    {
557        return Err(format!(
558            "`{}` must be true or false in a Human result schema.",
559            at("additionalProperties")
560        ));
561    }
562    let empty = Map::new();
563    let properties = match schema.get("properties") {
564        None => &empty,
565        Some(Value::Object(properties)) => properties,
566        Some(_) => return Err(format!("`{}` must be an object.", at("properties"))),
567    };
568    let required: Vec<&str> = match schema.get("required") {
569        None => Vec::new(),
570        Some(Value::Array(names)) => names
571            .iter()
572            .map(Value::as_str)
573            .collect::<Option<_>>()
574            .ok_or_else(|| format!("`{}` must list property names.", at("required")))?,
575        Some(_) => return Err(format!("`{}` must list property names.", at("required"))),
576    };
577    if let Some(name) = required
578        .iter()
579        .find(|name| !properties.contains_key(**name))
580    {
581        return Err(format!(
582            "`{}` names `{name}`, which `{}` does not declare, so a reviewer could never enter it.",
583            at("required"),
584            at("properties")
585        ));
586    }
587    properties
588        .iter()
589        .map(|(name, property)| {
590            let nested = !path.is_empty();
591            let path = at(&format!("properties.{name}"));
592            // An object below the result is a group, whose fields are scalars.
593            let (input, hint) = input(property, &path, nested)?;
594            Ok(Field {
595                name: name.clone(),
596                required: required.contains(&name.as_str()),
597                hint,
598                input,
599            })
600        })
601        .collect()
602}
603
604/// The input of the property at `path`, and its hint. Inside a group (`nested`) only scalars
605/// are allowed.
606fn input(property: &Value, path: &str, nested: bool) -> Result<(Input, String), String> {
607    let refuse = |detail: &str| Err(format!("`{path}`: {detail}; {SHAPES}."));
608    let Some(property) = property.as_object() else {
609        return refuse("a property schema must be an object");
610    };
611    let only = |keys: &[&str]| match property
612        .keys()
613        .find(|key| !keys.contains(&key.as_str()) && !NOTES.contains(&key.as_str()))
614    {
615        Some(key) => Err(format!(
616            "`{path}`: `{key}` is not allowed here; {SHAPES}, and only {} may be used on it.",
617            keys.join(", ")
618        )),
619        None => Ok(()),
620    };
621    let kind = property.get("type");
622    let input = if let Some(value) = property.get("const") {
623        only(&["const", "type"])?;
624        Input::Fixed(value.clone())
625    } else if let Some(options) = property.get("enum") {
626        only(&["enum", "type"])?;
627        let strings: Option<Vec<String>> = options.as_array().and_then(|options| {
628            options
629                .iter()
630                .map(|option| option.as_str().map(str::to_owned))
631                .collect()
632        });
633        match strings.and_then(Choice::new) {
634            Some(choice) if kind.is_none_or(|kind| kind == "string") => Input::Choice(choice),
635            _ => return refuse("an enum lists one or more strings"),
636        }
637    } else {
638        if kind.is_some_and(|kind| !kind.is_string()) {
639            return refuse("`type` names a single type");
640        }
641        match kind.and_then(Value::as_str) {
642            Some("boolean") => {
643                only(&["type"])?;
644                Input::Bool(None)
645            }
646            Some("string") => {
647                only(&STRING)?;
648                Input::Text(String::new())
649            }
650            Some("integer") => {
651                only(&NUMERIC)?;
652                Input::Integer(String::new())
653            }
654            Some("number") => {
655                only(&NUMERIC)?;
656                Input::Number(String::new())
657            }
658            Some("array") if nested => return refuse("a list cannot hold another list"),
659            Some("array") => {
660                only(&ARRAY)?;
661                array(property, path)?
662            }
663            Some(other) => return refuse(&format!("type \"{other}\" is not one of them")),
664            None => return refuse("a property needs a type, an enum or a const"),
665        }
666    };
667    Ok((input, hint(property)))
668}
669
670/// A list of strings, or of groups: `items` is a string schema or a flat object schema.
671fn array(property: &Map<String, Value>, path: &str) -> Result<Input, String> {
672    let path = format!("{path}.items");
673    let items = match property.get("items") {
674        Some(Value::Object(items)) => items,
675        _ => {
676            return Err(format!(
677                "`{path}` must be a string schema or an object schema; {SHAPES}."
678            ));
679        }
680    };
681    match items.get("type").and_then(Value::as_str) {
682        Some("string") => {
683            if let Some(key) = items
684                .keys()
685                .find(|key| !STRING.contains(&key.as_str()) && !NOTES.contains(&key.as_str()))
686            {
687                return Err(format!(
688                    "`{path}`: `{key}` is not allowed here; the items of a list of strings may \
689                     use only minLength and maxLength."
690                ));
691            }
692            Ok(Input::List(vec![String::new()]))
693        }
694        Some("object") => {
695            let fields = fields(items, &path)?;
696            Ok(Input::Groups {
697                items: vec![fields.clone()],
698                fields,
699            })
700        }
701        _ => Err(format!(
702            "`{path}` must be a string schema or an object schema; {SHAPES}."
703        )),
704    }
705}
706
707/// The type and constraints of a property, then any description.
708fn hint(property: &Map<String, Value>) -> String {
709    let constraints = property
710        .iter()
711        .filter(|(key, _)| !["type", "const", "enum", "items"].contains(&key.as_str()))
712        .filter(|(key, _)| !NOTES.contains(&key.as_str()))
713        .map(|(key, value)| format!("{key} {value}"));
714    let kind = property
715        .get("type")
716        .and_then(Value::as_str)
717        .map(str::to_owned);
718    let hint = kind
719        .into_iter()
720        .chain(constraints)
721        .collect::<Vec<_>>()
722        .join(", ");
723    match property.get("description").and_then(Value::as_str) {
724        Some(description) if hint.is_empty() => description.to_owned(),
725        Some(description) => format!("{hint} — {description}"),
726        None => hint,
727    }
728}
729
730#[cfg(test)]
731mod tests {
732    use super::*;
733    use crate::runtime::Verdict;
734
735    fn schema(value: Value) -> Map<String, Value> {
736        value.as_object().unwrap().clone()
737    }
738
739    #[test]
740    fn human_schemas_take_scalars_lists_of_strings_and_lists_of_flat_objects() {
741        let accepted = json!({
742            "type": "object",
743            "title": "Review",
744            "properties": {
745                "approved": {"const": true},
746                "comment": {"type": "string", "maxLength": 200, "description": "Why"},
747                "count": {"type": "integer", "minimum": 0},
748                "score": {"type": "number"},
749                "ok": {"type": "boolean"},
750                "level": {"enum": ["low", "high"]},
751                "changes": {"type": "array", "items": {"type": "string", "minLength": 1}, "minItems": 1},
752                "findings": {"type": "array", "maxItems": 5, "items": {
753                    "type": "object",
754                    "properties": {"line": {"type": "integer"}, "problem": {"type": "string"}},
755                    "required": ["problem"],
756                    "additionalProperties": false
757                }}
758            },
759            "required": ["approved"],
760            "additionalProperties": false
761        });
762        check(&schema(accepted)).unwrap();
763        for (refused, says) in [
764            (json!({"oneOf": []}), "`oneOf` is not allowed"),
765            (json!({"type": "array"}), "`type` must be \"object\""),
766            (
767                json!({"properties": {"a": {"type": "object"}}}),
768                "`properties.a`: type \"object\"",
769            ),
770            (
771                json!({"properties": {"a": {"type": "string", "pattern": "x"}}}),
772                "`pattern` is not allowed",
773            ),
774            (
775                json!({"properties": {"a": {"enum": [1, 2]}}}),
776                "an enum lists one or more strings",
777            ),
778            (
779                json!({"properties": {"a": {"type": "array", "items": {"type": "integer"}}}}),
780                "`properties.a.items` must be",
781            ),
782            (
783                json!({"properties": {"a": {"type": "array", "items": {"type": "object", "properties": {"b": {"type": "array", "items": {"type": "string"}}}}}}}),
784                "`properties.a.items.properties.b`: a list cannot hold another list",
785            ),
786            (
787                json!({"properties": {"a": {"type": "string"}}, "required": ["b"]}),
788                "names `b`",
789            ),
790            (
791                json!({"additionalProperties": {"type": "string"}}),
792                "true or false",
793            ),
794        ] {
795            let error = check(&schema(refused.clone())).unwrap_err();
796            assert!(error.contains(says), "{refused}: {error}");
797        }
798    }
799
800    #[test]
801    fn a_stale_choice_index_is_cleared_for_display_and_submission() {
802        assert!(Choice::new(Vec::new()).is_none());
803        let mut form = Form::new(
804            Verdict::Green,
805            Some(&json!({"type":"object","properties":{"level":{"enum":["low","high"]}}})),
806        )
807        .unwrap();
808        let select = |form: &mut Form, selected| {
809            let Input::Choice(choice) = &mut form.fields[0].input else {
810                panic!("expected choice field");
811            };
812            choice.select(Some(selected));
813        };
814        select(&mut form, 1);
815        assert_eq!(form.fields[0].display(), "\"high\"");
816        assert_eq!(form.result().unwrap()["level"], "high");
817        select(&mut form, 2);
818        assert_eq!(form.fields[0].display(), "–");
819        assert!(form.result().unwrap().get("level").is_none());
820    }
821
822    fn groups_form() -> Form {
823        Form::new(
824            Verdict::Red,
825            Some(&json!({
826                "type": "object",
827                "properties": {
828                    "kind": {"const": "review"},
829                    "findings": {"type": "array", "items": {
830                        "type": "object",
831                        "properties": {
832                            "tag": {"const": "x"},
833                            "line": {"type": "integer"},
834                            "problem": {"type": "string"}
835                        },
836                        "required": ["problem"]
837                    }}
838                },
839                "required": ["findings"]
840            })),
841        )
842        .unwrap()
843    }
844
845    #[test]
846    fn groups_are_rows_to_type_into_with_an_add_row_and_empty_groups_are_left_out() {
847        // Properties come in name order: findings, kind; line, problem, tag.
848        let mut form = groups_form();
849        assert_eq!(
850            form.rows(),
851            [
852                Row::Item {
853                    field: 0,
854                    item: 0,
855                    sub: 0
856                },
857                Row::Item {
858                    field: 0,
859                    item: 0,
860                    sub: 1
861                },
862                Row::Add(0),
863            ]
864        );
865        form.inline_key(Key::Char('7'), false);
866        form.key(Key::Down);
867        form.paste("typo");
868        form.key(Key::Down);
869        form.inline_key(Key::Enter, false);
870        assert_eq!(
871            form.row(),
872            Some(Row::Item {
873                field: 0,
874                item: 1,
875                sub: 0
876            })
877        );
878        assert_eq!(
879            form.result().unwrap(),
880            json!({"kind": "review", "verdict": "RED", "findings": [
881                {"tag": "x", "line": 7, "problem": "typo"}
882            ]})
883        );
884        form.paste("x");
885        assert_eq!(
886            form.result().unwrap_err(),
887            "findings 2 · line: enter an integer."
888        );
889        form.remove_selected();
890        form.remove(0, 0);
891        assert_eq!(form.rows().len(), 3, "one empty group always stays");
892        assert_eq!(
893            form.result().unwrap(),
894            json!({"kind": "review", "verdict": "RED", "findings": []})
895        );
896    }
897
898    #[test]
899    fn a_list_of_strings_adds_and_removes_items_and_keeps_one_to_type_in() {
900        let mut form = Form::new(
901            Verdict::Green,
902            Some(&json!({"properties": {"notes": {"type": "array", "items": {"type": "string"}}}})),
903        )
904        .unwrap();
905        form.paste("a");
906        form.add(0);
907        form.paste("b");
908        assert_eq!(
909            form.fields[0].input,
910            Input::List(vec!["a".into(), "b".into()])
911        );
912        form.remove(0, 0);
913        assert_eq!(
914            form.result().unwrap(),
915            json!({"verdict": "GREEN", "notes": ["b"]})
916        );
917        form.remove(0, 0);
918        assert_eq!(form.fields[0].input, Input::List(vec![String::new()]));
919        assert_eq!(form.result().unwrap(), json!({"verdict": "GREEN"}));
920    }
921
922    #[test]
923    fn a_schema_a_form_cannot_enter_is_refused_rather_than_shown() {
924        let error = Form::new(
925            Verdict::Green,
926            Some(&json!({"properties": {"a": {"type": "object"}}})),
927        )
928        .unwrap_err();
929        assert!(error.contains("properties.a"), "{error}");
930        assert_eq!(
931            Form::new(Verdict::Green, None).unwrap().result().unwrap(),
932            json!({"verdict": "GREEN"})
933        );
934    }
935}