1
//! Form constraint validation - the `Invalid` half of 11b-i.
2
//!
3
//! HTML's rule, and the one implemented here: on submit, every control in the
4
//! form is checked against its constraint attributes; if any fails, `invalid`
5
//! fires on it and the submission is CANCELLED. An app that wants to submit
6
//! anyway calls `prevent_default` on the `Invalid`, exactly as it would in a
7
//! browser.
8
//!
9
//! Every constraint is read from attributes that ALREADY EXISTED
10
//! (`Required`, `MinLength`, `MaxLength`, `Min`, `Max`) - the item said
11
//! validation needed "a `required` / `pattern` attribute or a validator
12
//! callback", and the attributes turned out to be in the DOM already.
13
//!
14
//! # `pattern` (11b-i-b)
15
//!
16
//! Needs a regex engine, and the user chose `regex-lite` for it (minimal
17
//! configuration: the string API only) over a hand-rolled matcher that would
18
//! accept and reject the wrong strings. HTML's rules, applied here:
19
//!
20
//! * the WHOLE value must match - the pattern is compiled as `^(?:p)$`, so `pattern="[0-9]{3}"`
21
//!   rejects `1234` even though it contains three digits;
22
//! * an empty value is exempt (that is `required`'s job);
23
//! * a pattern that does not compile is IGNORED, not treated as a mismatch - a browser does the
24
//!   same, and failing every submit over a typo in an attribute would be the worse behaviour.
25
//!
26
//! Known deviation: HTML compiles patterns with the `v` (unicode sets) flag.
27
//! `regex-lite` is Unicode-aware for `.`, `\w` and classes but has no `\p{..}`
28
//! properties or set operations; such a pattern fails to compile and is
29
//! therefore ignored rather than mis-matched.
30

            
31
use alloc::{collections::BTreeMap, string::String, vec::Vec};
32

            
33
use azul_core::{
34
    dom::{AttributeType, DomId, DomNodeId, NodeId},
35
    form::{ValidityReason, ValidityState},
36
};
37

            
38
use crate::window::DomLayoutResult;
39

            
40
/// One control that failed, and EVERY constraint it failed.
41
///
42
/// `ValidityReason` and `ValidityState` moved to `azul_core::form` when
43
/// 11b-i-c exposed them: a type an app reads has to live where the FFI can
44
/// reach it. They are re-exported here so this module still reads as one
45
/// piece.
46
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47
pub struct InvalidControl {
48
    pub node: DomNodeId,
49
    /// Every constraint this control failed, not just the first.
50
    ///
51
    /// It used to be one `reason` per entry, which meant a field failing two
52
    /// constraints produced TWO entries and therefore two `Invalid` events on
53
    /// one node. HTML fires `invalid` once per control, and an app marking
54
    /// fields would have marked one twice and mis-counted its error list.
55
    pub state: ValidityState,
56
}
57

            
58
/// Validate every control inside `form`, in document order.
59
///
60
/// `value_of` reads a control's CURRENT value; it is a callback rather than a
61
/// lookup here because the value lives in the text-edit pipeline, which this
62
/// crate's pure layer cannot reach - and because it makes the whole function
63
/// testable without a live window.
64
///
65
/// Returns every failure, not just the first: an app showing all errors at
66
/// once needs them all, and the caller decides how many to report.
67
26
pub fn validate_form(
68
26
    form: DomNodeId,
69
26
    layout_results: &BTreeMap<DomId, DomLayoutResult>,
70
26
    value_of: &dyn Fn(DomNodeId) -> Option<String>,
71
26
) -> Vec<InvalidControl> {
72
26
    let mut failures = Vec::new();
73
26
    let Some(layout) = layout_results.get(&form.dom) else {
74
        return failures;
75
    };
76
26
    let Some(form_id) = form.node.into_crate_internal() else {
77
        return failures;
78
    };
79
26
    let node_data = layout.styled_dom.node_data.as_container();
80
26
    let hierarchy = layout.styled_dom.node_hierarchy.as_container();
81

            
82
    // Descendants are CONTIGUOUS after the parent, which is what `subtree_len`
83
    // measures - so the form's controls are one index range rather than a
84
    // recursive walk.
85
26
    let count = hierarchy.subtree_len(form_id);
86
26
    let start = form_id.index() + 1;
87
28
    for index in start..start + count {
88
28
        let node_id = NodeId::new(index);
89
28
        let Some(data) = node_data.get(node_id) else {
90
            continue;
91
        };
92

            
93
        // Disabled and readonly controls are BARRED from constraint
94
        // validation in HTML - a disabled required field must not block a
95
        // submit the user cannot fix.
96
28
        let attrs = data.attributes();
97
28
        let barred = attrs
98
28
            .as_ref()
99
28
            .iter()
100
36
            .any(|a| matches!(a, AttributeType::Disabled | AttributeType::Readonly));
101
28
        if barred {
102
2
            continue;
103
26
        }
104

            
105
26
        let node = DomNodeId {
106
26
            dom: form.dom,
107
26
            node: azul_core::styled_dom::NodeHierarchyItemId::from_crate_internal(Some(node_id)),
108
26
        };
109
26
        let value = value_of(node).unwrap_or_default();
110

            
111
        // ONE entry per control, accumulating every failed constraint. See
112
        // `InvalidControl::state`.
113
26
        let mut state = ValidityState::valid();
114
26
        let mut push = |reason| {
115
14
            state.insert(reason);
116
14
        };
117

            
118
32
        for attr in attrs.as_ref() {
119
5
            match attr {
120
5
                AttributeType::Required if value.trim().is_empty() => {
121
4
                    push(ValidityReason::ValueMissing);
122
4
                }
123
                // `minlength` applies only to a NON-EMPTY value: an empty
124
                // optional field is not "too short", it is unfilled, and
125
                // reporting both for one empty required field would be two
126
                // errors for one mistake.
127
5
                AttributeType::MinLength(n) if !value.is_empty() => {
128
4
                    if usize::try_from(*n).is_ok_and(|n| value.chars().count() < n) {
129
2
                        push(ValidityReason::TooShort);
130
2
                    }
131
                }
132
3
                AttributeType::MaxLength(n) => {
133
3
                    if usize::try_from(*n).is_ok_and(|n| value.chars().count() > n) {
134
1
                        push(ValidityReason::TooLong);
135
2
                    }
136
                }
137
                // Range checks need BOTH sides to parse as numbers. A `min`
138
                // on a text field, or a non-numeric value, is not a failure -
139
                // the constraint simply does not apply.
140
5
                AttributeType::Min(bound) => {
141
5
                    if let (Ok(v), Ok(b)) = (value.parse::<f64>(), bound.as_str().parse::<f64>()) {
142
4
                        if v < b {
143
1
                            push(ValidityReason::RangeUnderflow);
144
3
                        }
145
1
                    }
146
                }
147
5
                AttributeType::Max(bound) => {
148
5
                    if let (Ok(v), Ok(b)) = (value.parse::<f64>(), bound.as_str().parse::<f64>()) {
149
5
                        if v > b {
150
2
                            push(ValidityReason::RangeOverflow);
151
3
                        }
152
                    }
153
                }
154
                // `pattern` applies only to a NON-EMPTY value, like `minlength`:
155
                // an empty optional field is unfilled, not mismatched.
156
9
                AttributeType::Pattern(pattern) if !value.is_empty() => {
157
8
                    if pattern_matches(pattern.as_str(), &value) == Some(false) {
158
4
                        push(ValidityReason::PatternMismatch);
159
4
                    }
160
                }
161
3
                _ => {}
162
            }
163
        }
164
26
        if !state.is_valid() {
165
13
            failures.push(InvalidControl { node, state });
166
13
        }
167
    }
168
26
    failures
169
26
}
170

            
171
/// Does `value` match the HTML `pattern` `pattern` as a whole?
172
///
173
/// `None` when the pattern does not compile, which the caller treats as "no
174
/// constraint" - HTML ignores an invalid `pattern` attribute rather than
175
/// failing the field. The anchoring is HTML's own recipe (`^(?:p)$`), which
176
/// also means an unbalanced `)` in the pattern cannot escape the group: it
177
/// makes the whole expression invalid, and so ignored.
178
#[must_use]
179
11
pub fn pattern_matches(pattern: &str, value: &str) -> Option<bool> {
180
11
    let anchored = alloc::format!("^(?:{pattern})$");
181
11
    regex_lite::Regex::new(&anchored)
182
11
        .ok()
183
11
        .map(|re| re.is_match(value))
184
11
}
185

            
186
/// What a control is FOR, so a soft keyboard can show the right layout.
187
///
188
/// This is HTML's `type` attribute, which `AttributeType::InputType` already
189
/// carries - the 10a-iii note said an input-purpose attribute was needed
190
/// "first, which is a design question", and it was already in the DOM.
191
///
192
/// The values are a deliberate SUBSET: only purposes that change what a
193
/// keyboard shows. `type="checkbox"` has no keyboard, so it is `Text` here
194
/// rather than a variant nobody would branch on.
195
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
196
#[repr(i32)]
197
pub enum InputPurpose {
198
    /// Ordinary text - the platform default, and what an unset or unknown
199
    /// `type` resolves to. Per the user's ruling: default to the platform
200
    /// default rather than guessing.
201
    #[default]
202
    Text = 0,
203
    /// Digits only (`type="number"`).
204
    Number = 1,
205
    /// Digits plus a decimal separator.
206
    Decimal = 2,
207
    /// A phone pad (`type="tel"`).
208
    Phone = 3,
209
    /// Text with `@` and `.` promoted (`type="email"`).
210
    Email = 4,
211
    /// Text with `/` and `.com` promoted (`type="url"`).
212
    Url = 5,
213
    /// Obscured, and excluded from autocorrect and learning
214
    /// (`type="password"`).
215
    Password = 6,
216
    /// A Search key instead of Enter (`type="search"`).
217
    Search = 7,
218
}
219

            
220
/// The purpose of one control, from its `type` attribute.
221
///
222
/// Unknown and absent both give `Text`: a `type` this build does not know is
223
/// not a reason to show the wrong keyboard.
224
#[must_use]
225
11
pub fn input_purpose(
226
11
    node: DomNodeId,
227
11
    layout_results: &BTreeMap<DomId, DomLayoutResult>,
228
11
) -> InputPurpose {
229
11
    let Some(layout) = layout_results.get(&node.dom) else {
230
        return InputPurpose::Text;
231
    };
232
11
    let Some(id) = node.node.into_crate_internal() else {
233
        return InputPurpose::Text;
234
    };
235
11
    let node_data = layout.styled_dom.node_data.as_container();
236
11
    let Some(data) = node_data.get(id) else {
237
        return InputPurpose::Text;
238
    };
239
11
    for attr in data.attributes().as_ref() {
240
10
        if let AttributeType::InputType(t) = attr {
241
10
            let t = t.as_str();
242
            // ASCII-case-insensitive, as HTML attribute values are.
243
10
            return if t.eq_ignore_ascii_case("number") {
244
1
                InputPurpose::Number
245
9
            } else if t.eq_ignore_ascii_case("decimal") {
246
1
                InputPurpose::Decimal
247
8
            } else if t.eq_ignore_ascii_case("tel") {
248
1
                InputPurpose::Phone
249
7
            } else if t.eq_ignore_ascii_case("email") {
250
2
                InputPurpose::Email
251
5
            } else if t.eq_ignore_ascii_case("url") {
252
1
                InputPurpose::Url
253
4
            } else if t.eq_ignore_ascii_case("password") {
254
1
                InputPurpose::Password
255
3
            } else if t.eq_ignore_ascii_case("search") {
256
1
                InputPurpose::Search
257
            } else {
258
2
                InputPurpose::Text
259
            };
260
        }
261
    }
262
1
    InputPurpose::Text
263
11
}
264

            
265
/// Whether a control accepts newlines, which decides whether the Enter key is
266
/// a line break or an action key (Done / Go / Search).
267
///
268
/// `TextArea` is the multiline control; everything else is single-line. The
269
/// Android bridge hardcoded `MULTI_LINE` for every field, so a single-line input
270
/// showed a newline key and had no way to dismiss the keyboard.
271
#[must_use]
272
pub fn is_multiline(node: DomNodeId, layout_results: &BTreeMap<DomId, DomLayoutResult>) -> bool {
273
    let Some(layout) = layout_results.get(&node.dom) else {
274
        return false;
275
    };
276
    let Some(id) = node.node.into_crate_internal() else {
277
        return false;
278
    };
279
    layout
280
        .styled_dom
281
        .node_data
282
        .as_container()
283
        .get(id)
284
        .is_some_and(|d| {
285
            matches!(d.get_node_type(), azul_core::dom::NodeType::TextArea)
286
                || d.attributes()
287
                    .as_ref()
288
                    .iter()
289
                    .any(|a| matches!(a, AttributeType::ContentEditable(true)))
290
        })
291
}
292

            
293
/// Every control in `form` paired with the value a reset restores it to.
294
///
295
/// HTML restores each control to its `value` ATTRIBUTE - the DEFAULT value,
296
/// not whatever it currently holds - so the "initial values to restore" the
297
/// original item said were missing are already in the DOM. A control with no
298
/// `value` attribute resets to EMPTY, which is also what HTML does.
299
///
300
/// Disabled and readonly controls are NOT skipped here, unlike in validation:
301
/// a reset clears a readonly field in a browser, because the reset is the
302
/// app's action rather than the user's.
303
#[must_use]
304
4
pub fn default_values(
305
4
    form: DomNodeId,
306
4
    layout_results: &BTreeMap<DomId, DomLayoutResult>,
307
4
) -> Vec<(DomNodeId, String)> {
308
4
    let mut out = Vec::new();
309
4
    let Some(layout) = layout_results.get(&form.dom) else {
310
        return out;
311
    };
312
4
    let Some(form_id) = form.node.into_crate_internal() else {
313
        return out;
314
    };
315
4
    let node_data = layout.styled_dom.node_data.as_container();
316
4
    let hierarchy = layout.styled_dom.node_hierarchy.as_container();
317

            
318
4
    let count = hierarchy.subtree_len(form_id);
319
4
    let start = form_id.index() + 1;
320
4
    for index in start..start + count {
321
4
        let node_id = NodeId::new(index);
322
4
        let Some(data) = node_data.get(node_id) else {
323
            continue;
324
        };
325
4
        let attrs = data.attributes();
326
        // Only controls that can HOLD a value are reset. A form full of divs
327
        // would otherwise have every one of them blanked.
328
4
        let is_control = matches!(
329
4
            data.get_node_type(),
330
            azul_core::dom::NodeType::Input
331
                | azul_core::dom::NodeType::TextArea
332
                | azul_core::dom::NodeType::Select
333
        );
334
4
        if !is_control {
335
            continue;
336
4
        }
337
4
        let default = attrs
338
4
            .as_ref()
339
4
            .iter()
340
4
            .find_map(|a| match a {
341
3
                AttributeType::Value(v) => Some(v.as_str().to_string()),
342
1
                _ => None,
343
4
            })
344
4
            .unwrap_or_default();
345
4
        out.push((
346
4
            DomNodeId {
347
4
                dom: form.dom,
348
4
                node: azul_core::styled_dom::NodeHierarchyItemId::from_crate_internal(Some(
349
4
                    node_id,
350
4
                )),
351
4
            },
352
4
            default,
353
4
        ));
354
    }
355
4
    out
356
4
}
357

            
358
#[cfg(all(test, feature = "std"))]
359
mod tests {
360
    use azul_core::{
361
        dom::{Dom, NodeData, NodeType},
362
        styled_dom::StyledDom,
363
    };
364

            
365
    use super::*;
366

            
367
    /// A form whose children carry the constraint under test.
368
32
    fn form_with(attrs: Vec<Vec<AttributeType>>) -> BTreeMap<DomId, DomLayoutResult> {
369
32
        let mut form = Dom::create_node(NodeType::Form);
370
66
        for a in attrs {
371
34
            let mut data = NodeData::create_node(NodeType::Input);
372
34
            data.set_attributes(a.into());
373
34
            form = form.with_child(Dom::create_from_data(data));
374
34
        }
375
32
        let styled_dom = StyledDom::create_from_dom(Dom::create_body().with_child(form));
376
32
        let mut map = BTreeMap::new();
377
32
        map.insert(
378
            DomId::ROOT_ID,
379
32
            DomLayoutResult {
380
32
                styled_dom,
381
32
                layout_tree: crate::solver3::layout_tree::LayoutTree {
382
32
                    nodes: Vec::new(),
383
32
                    warm: Vec::new(),
384
32
                    cold: Vec::new(),
385
32
                    root: 0,
386
32
                    dom_to_layout: BTreeMap::new(),
387
32
                    children_arena: Vec::new(),
388
32
                    children_offsets: Vec::new(),
389
32
                    subtree_needs_intrinsic: Vec::new(),
390
32
                },
391
32
                calculated_positions: Vec::new(),
392
32
                viewport: azul_core::geom::LogicalRect::zero(),
393
32
                display_list: std::sync::Arc::new(
394
32
                    crate::solver3::display_list::DisplayList::default(),
395
32
                ),
396
32
                scroll_ids: std::collections::HashMap::new(),
397
32
                scroll_id_to_node_id: std::collections::HashMap::new(),
398
32
            },
399
        );
400
32
        map
401
32
    }
402

            
403
45
    fn node(index: usize) -> DomNodeId {
404
45
        DomNodeId {
405
45
            dom: DomId::ROOT_ID,
406
45
            node: azul_core::styled_dom::NodeHierarchyItemId::from_crate_internal(Some(
407
45
                NodeId::new(index),
408
45
            )),
409
45
        }
410
45
    }
411

            
412
    /// Node 0 = body, 1 = form, 2.. = controls.
413
    const FORM: usize = 1;
414

            
415
    #[test]
416
1
    fn a_required_control_with_no_value_is_value_missing() {
417
1
        let layouts = form_with(vec![vec![AttributeType::Required]]);
418
1
        let got = validate_form(node(FORM), &layouts, &|_| None);
419
1
        assert_eq!(got.len(), 1);
420
1
        assert!(got[0].state.has(ValidityReason::ValueMissing));
421
1
        assert_eq!(got[0].node, node(2));
422
1
    }
423

            
424
    /// WHITESPACE IS EMPTY. A field containing only spaces has not been
425
    /// filled in, and accepting it is the classic required-field hole.
426
    #[test]
427
1
    fn whitespace_does_not_satisfy_required() {
428
1
        let layouts = form_with(vec![vec![AttributeType::Required]]);
429
1
        let got = validate_form(node(FORM), &layouts, &|_| Some("   ".into()));
430
1
        assert_eq!(got.len(), 1, "whitespace must not count as a value");
431
1
    }
432

            
433
    #[test]
434
1
    fn a_filled_required_control_passes() {
435
1
        let layouts = form_with(vec![vec![AttributeType::Required]]);
436
1
        assert!(validate_form(node(FORM), &layouts, &|_| Some("x".into())).is_empty());
437
1
    }
438

            
439
    /// A DISABLED required field must not block a submit the user cannot fix -
440
    /// HTML bars disabled and readonly controls from validation entirely.
441
    #[test]
442
1
    fn disabled_and_readonly_controls_are_barred_from_validation() {
443
2
        for barred in [AttributeType::Disabled, AttributeType::Readonly] {
444
2
            let layouts = form_with(vec![vec![AttributeType::Required, barred.clone()]]);
445
2
            assert!(
446
2
                validate_form(node(FORM), &layouts, &|_| None).is_empty(),
447
                "{barred:?} must bar the control from validation"
448
            );
449
        }
450
1
    }
451

            
452
    /// `minlength` must NOT fire on an empty value: an empty optional field is
453
    /// unfilled, not too short, and an empty REQUIRED field would otherwise
454
    /// report two errors for one mistake.
455
    #[test]
456
1
    fn minlength_ignores_an_empty_value() {
457
1
        let layouts = form_with(vec![vec![AttributeType::MinLength(5)]]);
458
1
        assert!(validate_form(node(FORM), &layouts, &|_| Some(String::new())).is_empty());
459
1
    }
460

            
461
    #[test]
462
1
    fn minlength_and_maxlength_are_measured_in_characters() {
463
1
        let layouts = form_with(vec![vec![
464
1
            AttributeType::MinLength(3),
465
1
            AttributeType::MaxLength(4),
466
        ]]);
467
        // "é" is two BYTES and one character; a byte-length check would call
468
        // this 4 long and wrongly pass minlength on a 2-char value.
469
1
        let got = validate_form(node(FORM), &layouts, &|_| Some("éé".into()));
470
1
        assert_eq!(got.len(), 1);
471
1
        assert!(got[0].state.has(ValidityReason::TooShort));
472

            
473
1
        let got = validate_form(node(FORM), &layouts, &|_| Some("ééé".into()));
474
1
        assert!(got.is_empty(), "3 characters satisfies minlength 3");
475

            
476
1
        let got = validate_form(node(FORM), &layouts, &|_| Some("ééééé".into()));
477
1
        assert!(got[0].state.has(ValidityReason::TooLong));
478
1
    }
479

            
480
    /// ONE ENTRY PER CONTROL, however many constraints it breaks.
481
    ///
482
    /// This used to be one entry per failed CONSTRAINT, so a field that was
483
    /// both too short and out of range produced two entries - and therefore
484
    /// two `Invalid` events on one node. HTML fires `invalid` once per
485
    /// control, and an app marking bad fields would have marked this one
486
    /// twice and reported two errors for one field.
487
    #[test]
488
1
    fn a_control_failing_two_constraints_is_reported_once_with_both() {
489
1
        let layouts = form_with(vec![vec![
490
1
            AttributeType::MinLength(5),
491
1
            AttributeType::Max("10".into()),
492
        ]]);
493
        // "99" is 2 characters (too short) AND numerically above 10.
494
1
        let got = validate_form(node(FORM), &layouts, &|_| Some("99".into()));
495
1
        assert_eq!(
496
1
            got.len(),
497
            1,
498
            "one control must produce one entry, got {got:?}"
499
        );
500
1
        assert!(got[0].state.has(ValidityReason::TooShort));
501
1
        assert!(got[0].state.has(ValidityReason::RangeOverflow));
502
1
        assert!(!got[0].state.has(ValidityReason::ValueMissing));
503
1
    }
504

            
505
    #[test]
506
1
    fn min_and_max_compare_numerically() {
507
1
        let layouts = form_with(vec![vec![
508
1
            AttributeType::Min("10".into()),
509
1
            AttributeType::Max("20".into()),
510
        ]]);
511
1
        assert!(
512
1
            validate_form(node(FORM), &layouts, &|_| Some("9".into()))[0]
513
                .state
514
1
                .has(ValidityReason::RangeUnderflow)
515
        );
516
1
        assert!(
517
1
            validate_form(node(FORM), &layouts, &|_| Some("21".into()))[0]
518
                .state
519
1
                .has(ValidityReason::RangeOverflow)
520
        );
521
1
        assert!(validate_form(node(FORM), &layouts, &|_| Some("15".into())).is_empty());
522
        // STRING comparison would call "9" greater than "20"; the numeric one
523
        // is the whole point of parsing both sides.
524
1
        assert!(validate_form(node(FORM), &layouts, &|_| Some("10".into())).is_empty());
525
1
    }
526

            
527
    /// A non-numeric value against a numeric bound is NOT a failure - the
528
    /// constraint simply does not apply, and reporting it would make every
529
    /// text field with a stray `min` permanently invalid.
530
    #[test]
531
1
    fn a_non_numeric_value_is_not_a_range_failure() {
532
1
        let layouts = form_with(vec![vec![AttributeType::Min("10".into())]]);
533
1
        assert!(validate_form(node(FORM), &layouts, &|_| Some("abc".into())).is_empty());
534
1
    }
535

            
536
    /// Every failing control is reported, not just the first: an app showing
537
    /// all errors at once needs them all.
538
    #[test]
539
1
    fn every_failing_control_is_reported() {
540
1
        let layouts = form_with(vec![
541
1
            vec![AttributeType::Required],
542
1
            vec![AttributeType::Required],
543
        ]);
544
1
        let got = validate_form(node(FORM), &layouts, &|_| None);
545
1
        assert_eq!(got.len(), 2);
546
1
        assert_eq!(got[0].node, node(2));
547
1
        assert_eq!(got[1].node, node(3), "in document order");
548
1
    }
549

            
550
    #[test]
551
1
    fn every_html_type_maps_to_its_purpose() {
552
8
        for (html, expected) in [
553
1
            ("number", InputPurpose::Number),
554
1
            ("decimal", InputPurpose::Decimal),
555
1
            ("tel", InputPurpose::Phone),
556
1
            ("email", InputPurpose::Email),
557
1
            ("url", InputPurpose::Url),
558
1
            ("password", InputPurpose::Password),
559
1
            ("search", InputPurpose::Search),
560
1
            ("text", InputPurpose::Text),
561
        ] {
562
8
            let layouts = form_with(vec![vec![AttributeType::InputType(html.into())]]);
563
8
            assert_eq!(input_purpose(node(2), &layouts), expected, "type={html}");
564
        }
565
1
    }
566

            
567
    /// HTML attribute values are ASCII-case-insensitive, and real documents
568
    /// contain `type="EMAIL"`.
569
    #[test]
570
1
    fn the_type_attribute_is_case_insensitive() {
571
1
        let layouts = form_with(vec![vec![AttributeType::InputType("EMAIL".into())]]);
572
1
        assert_eq!(input_purpose(node(2), &layouts), InputPurpose::Email);
573
1
    }
574

            
575
    /// An absent or unrecognised `type` gives the PLATFORM DEFAULT, per the
576
    /// ruling - not a guess, and not a failure. A `type` a future HTML adds
577
    /// must not produce the wrong keyboard.
578
    #[test]
579
1
    fn an_unknown_or_absent_type_defaults_to_text() {
580
1
        let layouts = form_with(vec![vec![]]);
581
1
        assert_eq!(input_purpose(node(2), &layouts), InputPurpose::Text);
582

            
583
1
        let layouts = form_with(vec![vec![AttributeType::InputType("colour-picker".into())]]);
584
1
        assert_eq!(input_purpose(node(2), &layouts), InputPurpose::Text);
585
1
    }
586

            
587
    /// The discriminants are a WIRE FORMAT: `NativeTextBridge.java` switches on
588
    /// these exact integers. Renumbering the enum would silently give every
589
    /// field the wrong keyboard - the same hazard as the sensor codes, and it
590
    /// gets the same guard.
591
    #[test]
592
1
    fn the_purpose_discriminants_are_the_jni_wire_codes() {
593
8
        for (purpose, code) in [
594
1
            (InputPurpose::Text, 0),
595
1
            (InputPurpose::Number, 1),
596
1
            (InputPurpose::Decimal, 2),
597
1
            (InputPurpose::Phone, 3),
598
1
            (InputPurpose::Email, 4),
599
1
            (InputPurpose::Url, 5),
600
1
            (InputPurpose::Password, 6),
601
1
            (InputPurpose::Search, 7),
602
        ] {
603
8
            assert_eq!(
604
8
                purpose as i32, code,
605
                "{purpose:?} moved; NativeTextBridge.java still switches on {code}"
606
            );
607
        }
608
1
    }
609

            
610
    /// A control resets to its `value` ATTRIBUTE - the default - not to
611
    /// whatever it currently holds. That is the whole reason the "initial
612
    /// values" did not need storing anywhere.
613
    #[test]
614
1
    fn a_control_resets_to_its_value_attribute() {
615
1
        let layouts = form_with(vec![vec![AttributeType::Value("hello".into())]]);
616
1
        let got = default_values(node(FORM), &layouts);
617
1
        assert_eq!(got.len(), 1);
618
1
        assert_eq!(got[0].0, node(2));
619
1
        assert_eq!(got[0].1, "hello");
620
1
    }
621

            
622
    /// No `value` attribute means reset-to-EMPTY, which is what HTML does -
623
    /// not "leave it alone".
624
    #[test]
625
1
    fn a_control_with_no_value_attribute_resets_to_empty() {
626
1
        let layouts = form_with(vec![vec![AttributeType::Required]]);
627
1
        let got = default_values(node(FORM), &layouts);
628
1
        assert_eq!(got.len(), 1);
629
1
        assert_eq!(got[0].1, "");
630
1
    }
631

            
632
    /// Disabled and readonly controls ARE reset, unlike in validation where
633
    /// they are barred: a reset is the app's action, not the user's, and a
634
    /// browser clears a readonly field too.
635
    #[test]
636
1
    fn reset_does_not_skip_disabled_or_readonly_controls() {
637
2
        for barred in [AttributeType::Disabled, AttributeType::Readonly] {
638
2
            let layouts = form_with(vec![vec![AttributeType::Value("v".into()), barred.clone()]]);
639
2
            assert_eq!(
640
2
                default_values(node(FORM), &layouts).len(),
641
                1,
642
                "{barred:?} must still be reset"
643
            );
644
        }
645
1
    }
646

            
647
    #[test]
648
1
    fn a_form_with_no_constraints_is_valid() {
649
1
        let layouts = form_with(vec![vec![], vec![]]);
650
1
        assert!(validate_form(node(FORM), &layouts, &|_| None).is_empty());
651
1
    }
652

            
653
    /// THE WHOLE VALUE MUST MATCH (HTML anchors the pattern): three digits
654
    /// means exactly three, not "contains three".
655
    #[test]
656
1
    fn pattern_must_match_the_whole_value() {
657
1
        let layouts = form_with(vec![vec![AttributeType::Pattern("[0-9]{3}".into())]]);
658
1
        assert!(validate_form(node(FORM), &layouts, &|_| Some("123".into())).is_empty());
659
4
        for bad in ["1234", "12", "x123", "123x"] {
660
4
            let got = validate_form(node(FORM), &layouts, &|_| Some(bad.into()));
661
4
            assert_eq!(
662
4
                got.len(),
663
                1,
664
                "{bad:?} must not match an anchored [0-9]{{3}}"
665
            );
666
4
            assert!(got[0].state.has(ValidityReason::PatternMismatch));
667
        }
668
1
    }
669

            
670
    /// An empty value is `required`'s business, not `pattern`'s.
671
    #[test]
672
1
    fn pattern_ignores_an_empty_value() {
673
1
        let layouts = form_with(vec![vec![AttributeType::Pattern("[0-9]+".into())]]);
674
1
        assert!(validate_form(node(FORM), &layouts, &|_| Some(String::new())).is_empty());
675
1
    }
676

            
677
    /// A pattern that does not compile is IGNORED, as a browser ignores an
678
    /// invalid `pattern` attribute - not treated as "nothing matches".
679
    #[test]
680
1
    fn an_uncompilable_pattern_is_ignored_like_html() {
681
3
        for broken in ["(", "[0-9", "a)b"] {
682
3
            let layouts = form_with(vec![vec![AttributeType::Pattern(broken.into())]]);
683
3
            assert!(
684
3
                validate_form(node(FORM), &layouts, &|_| Some("anything".into())).is_empty(),
685
                "{broken:?} must be ignored, not fail the field"
686
            );
687
        }
688
1
        assert_eq!(pattern_matches("(", "x"), None);
689
1
    }
690

            
691
    /// `.` is a CHARACTER, not a byte - "\u{e9}a" is two characters.
692
    #[test]
693
1
    fn pattern_matching_is_unicode_aware() {
694
1
        assert_eq!(pattern_matches(".{2}", "\u{e9}a"), Some(true));
695
1
        assert_eq!(pattern_matches(".{3}", "\u{e9}a"), Some(false));
696
1
    }
697
}