1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
//! Constraint-validation candidacy (HTML §4.10.20.1) — which elements
//! take part in constraint validation at all. Names, attributes and tree
//! shape only; the validity *states* need values and patterns and live
//! in the backend (rdom-tui's `validation` builtin).
//!
//! - [`Dom::will_validate`] — a submittable element that is not *barred
//! from constraint validation*: the `willValidate` IDL attribute.
//! - [`Dom::constraint_validity`] — what `:valid` / `:invalid` match
//! (HTML §4.16.3), with the per-candidate verdict delegated to the
//! backend's [`ValidityHook`].
//! - [`Dom::is_required_control`] / [`Dom::is_optional_control`] — what
//! `:required` / `:optional` match.
use crate::dom::Dom;
use crate::input_type::InputTypeState;
use crate::node_id::NodeId;
/// A backend's constraint check: whether candidate `id` satisfies its
/// constraints. The validity states need values, patterns and state the
/// substrate does not model (rdom-tui's `validation` builtin computes
/// them), so the substrate asks the backend through this hook — a plain
/// `fn`, so matching (`&self`) can call it. Installed with
/// [`Dom::set_validity_hook`].
pub type ValidityHook<Ext> = fn(&Dom<Ext>, NodeId) -> bool;
/// Storage for the hook with a `Debug` impl.
pub(crate) struct ValiditySlot<Ext: 'static>(pub(crate) Option<ValidityHook<Ext>>);
impl<Ext: 'static> std::fmt::Debug for ValiditySlot<Ext> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(if self.0.is_some() {
"ValiditySlot(Some(hook))"
} else {
"ValiditySlot(None)"
})
}
}
impl<Ext: 'static> Dom<Ext> {
/// Install (or remove, with `None`) the backend's constraint check
/// behind `:valid` / `:invalid` and [`constraint_validity`](Self::constraint_validity).
///
/// **A `Dom` has no hook until one is installed, and without one
/// every candidate is valid.** rdom-core cannot compute validity
/// states itself (they need values, patterns and a custom validity),
/// so an unhooked `Dom` answers "valid" for every candidate — an
/// `<input>`, `<select>`, `<textarea>` or submit button, and so a
/// `<form>` / `<fieldset>` holding one: `:valid` matches, `:invalid`
/// never does, whatever `required` / `pattern` say. The answer is
/// the same in debug and release builds, and nothing is logged
/// (rdom-core has no warning channel). rdom-tui's `App` installs its
/// hook at construction; a bare `TuiDom` cascaded without an `App`
/// must call `rdom_tui::runtime::builtins::validation::install`, and
/// a backend-less `Dom` that matches these pseudo-classes installs
/// its own.
pub fn set_validity_hook(&mut self, hook: Option<ValidityHook<Ext>>) {
self.validity_hook = ValiditySlot(hook);
}
/// What `:valid` / `:invalid` match (HTML §4.16.3):
///
/// - a [candidate](Self::will_validate): `Some(verdict)` of the
/// validity hook ([`set_validity_hook`](Self::set_validity_hook));
/// `Some(true)` without one, in every build;
/// - a `<form>`: `Some(false)` when a candidate it owns
/// ([`form_listed_elements`](Self::form_listed_elements)) is
/// invalid, else `Some(true)`;
/// - a `<fieldset>`: the same over its descendant candidates;
/// - anything else, barred controls included: `None` (neither).
pub fn constraint_validity(&self, id: NodeId) -> Option<bool> {
let tag = self.get_node(id)?.tag_name()?;
match tag {
"form" => Some(
!self
.form_listed_elements(id)
.into_iter()
.any(|c| self.suffers(c)),
),
"fieldset" => Some(!self.any_descendant_suffers(id)),
_ if self.will_validate(id) => Some(self.satisfies(id)),
_ => None,
}
}
/// Whether `id` matches `:required` (HTML §4.16.3): an `<input>` in
/// a state the `required` attribute applies to (not hidden, range,
/// color or the button types), a `<select>` or a `<textarea>`, with
/// `required`.
pub fn is_required_control(&self, id: NodeId) -> bool {
self.required_applies(id) && self.has_attribute(id, "required")
}
/// Whether the `required` attribute applies to `id` (HTML §4.10.5.3.4
/// and the per-state lists of §4.10.5.1): a `<select>`, a
/// `<textarea>`, or an `<input>` in any state but hidden, range,
/// color and the button types — the one list behind `:required` /
/// `:optional` and a backend's `valueMissing` check.
pub fn required_applies(&self, id: NodeId) -> bool {
use InputTypeState as T;
match self.get_node(id).and_then(|n| n.tag_name()) {
Some("select" | "textarea") => true,
Some("input") => !matches!(
self.input_type_state(id),
Some(T::Hidden | T::Range | T::Color | T::Submit | T::Image | T::Reset | T::Button)
),
_ => false,
}
}
/// Whether `id` matches `:optional`: an `<input>`, `<select>` or
/// `<textarea>` that is not [required](Self::is_required_control).
pub fn is_optional_control(&self, id: NodeId) -> bool {
matches!(
self.get_node(id).and_then(|n| n.tag_name()),
Some("input" | "select" | "textarea")
) && !self.is_required_control(id)
}
/// The hook's verdict for candidate `id`; "valid" without a hook
/// (`set_validity_hook`), in every build (`P7G-PUBLIC-SURFACE-2`).
fn satisfies(&self, id: NodeId) -> bool {
self.validity_hook.0.is_none_or(|hook| hook(self, id))
}
/// A candidate that does not satisfy its constraints.
fn suffers(&self, id: NodeId) -> bool {
self.will_validate(id) && !self.satisfies(id)
}
fn any_descendant_suffers(&self, id: NodeId) -> bool {
let mut stack: Vec<NodeId> = Vec::new();
let push_children = |stack: &mut Vec<NodeId>, of: NodeId| {
let mut c = self.get_node(of).and_then(|n| n.first_child);
while let Some(cid) = c {
stack.push(cid);
c = self.get_node(cid).and_then(|n| n.next_sibling);
}
};
push_children(&mut stack, id);
while let Some(n) = stack.pop() {
if self.suffers(n) {
return true;
}
push_children(&mut stack, n);
}
false
}
}
impl<Ext> Dom<Ext> {
/// Whether `id` is a *candidate for constraint validation* (HTML
/// §4.10.20.1, the `willValidate` IDL attribute): a submittable
/// element (`<button>`, `<input>`, `<select>`, `<textarea>`) that is
/// not barred. Barred are:
///
/// - an [actually disabled](Self::is_actually_disabled) control
/// (own `disabled`, or a disabled `<fieldset>`);
/// - a control with a `<datalist>` ancestor;
/// - a `<button>` that is not a submit button;
/// - an `<input>` in the Hidden, Reset or Button state;
/// - an `<input>` with `readonly` in a state `readonly` applies to
/// (the text, date / time and number states — not a checkbox), and
/// a `<textarea readonly>`.
///
/// `<object>`, `<output>` and `<fieldset>` are never candidates.
pub fn will_validate(&self, id: NodeId) -> bool {
let Some(tag) = self.get_node(id).and_then(|n| n.tag_name()) else {
return false;
};
let submittable_and_not_self_barred = match tag {
"button" => self.is_submit_button(id),
"input" => {
use InputTypeState as T;
match self.input_type_state(id) {
Some(T::Hidden | T::Reset | T::Button) | None => false,
Some(t) => !(readonly_applies(t) && self.has_attribute(id, "readonly")),
}
}
"select" => true,
"textarea" => !self.has_attribute(id, "readonly"),
_ => false,
};
submittable_and_not_self_barred
&& !self.is_actually_disabled(id)
&& !self.has_datalist_ancestor(id)
}
fn has_datalist_ancestor(&self, id: NodeId) -> bool {
let mut cur = self.parent_element_id(id);
while let Some(a) = cur {
if self.tag_is(a, "datalist") {
return true;
}
cur = self.parent_element_id(a);
}
false
}
}
/// The `<input>` states the `readonly` attribute applies to (HTML
/// §4.10.5, the "readonly" row of the attribute table).
fn readonly_applies(t: InputTypeState) -> bool {
use InputTypeState as T;
matches!(
t,
T::Text
| T::Search
| T::Url
| T::Tel
| T::Email
| T::Password
| T::Date
| T::Month
| T::Week
| T::Time
| T::DateTimeLocal
| T::Number
)
}
#[cfg(test)]
mod tests {
use crate::Dom;
use crate::node_id::NodeId;
fn el(dom: &mut Dom, parent: NodeId, tag: &str, attrs: &[(&str, &str)]) -> NodeId {
let e = dom.create_element(tag);
for (k, v) in attrs {
dom.set_attribute(e, k, v).unwrap();
}
dom.append_child(parent, e).unwrap();
e
}
#[test]
fn candidates_are_the_submittable_controls_that_are_not_barred() {
let mut dom: Dom = Dom::new();
let root = dom.root();
for (tag, attrs, candidate) in [
("input", vec![], true),
("input", vec![("type", "checkbox")], true),
("input", vec![("type", "Submit")], true),
("input", vec![("type", "hidden")], false),
("input", vec![("type", "reset")], false),
("input", vec![("type", "button")], false),
("button", vec![], true),
("button", vec![("type", "button")], false),
("button", vec![("type", "reset")], false),
("select", vec![], true),
("textarea", vec![], true),
("fieldset", vec![], false),
("output", vec![], false),
("object", vec![], false),
("form", vec![], false),
("div", vec![], false),
] {
let id = el(&mut dom, root, tag, &attrs);
assert_eq!(dom.will_validate(id), candidate, "{tag} {attrs:?}");
}
}
#[test]
fn disabled_readonly_and_datalist_controls_are_barred() {
let mut dom: Dom = Dom::new();
let root = dom.root();
let disabled = el(&mut dom, root, "input", &[("disabled", "")]);
let fs = el(&mut dom, root, "fieldset", &[("disabled", "")]);
let in_fs = el(&mut dom, fs, "select", &[]);
let ro_text = el(&mut dom, root, "input", &[("readonly", "")]);
let ro_area = el(&mut dom, root, "textarea", &[("readonly", "")]);
let ro_box = el(
&mut dom,
root,
"input",
&[("type", "checkbox"), ("readonly", "")],
);
let list = el(&mut dom, root, "datalist", &[]);
let in_list = el(&mut dom, list, "input", &[]);
for id in [disabled, in_fs, ro_text, ro_area, in_list] {
assert!(!dom.will_validate(id), "{id:?}");
}
assert!(
dom.will_validate(ro_box),
"readonly does not apply to a checkbox"
);
}
}