Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

refactor(html): centralize input type states

ldm0e194c2add876
diff --git a/Cargo.lock b/Cargo.lock
index 3aa78f743..142169359 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2489,6 +2489,7 @@ dependencies = [
"indexmap",
"moli-css-parse",
"moli-html-input-temporal",
+ "moli-html-input-type",
"percent-encoding",
"selectors",
"serde_json",
@@ -2575,6 +2576,13 @@ dependencies = [
"time",
]
+[[package]]
+name = "moli-html-input-type"
+version = "0.1.0"
+dependencies = [
+ "strum",
+]
+
[[package]]
name = "moli-http-cache"
version = "0.1.0"
@@ -2822,6 +2830,7 @@ dependencies = [
"moli-cookie-jar",
"moli-core",
"moli-fetch",
+ "moli-html-input-type",
"moli-protocol",
"moli-protocol-cdp",
"moli-protocol-webdriver-bidi",
diff --git a/Cargo.toml b/Cargo.toml
index 314dcfbcc..36165f9c9 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -75,6 +75,7 @@ members = [
"moli-file-api",
"moli-geometry",
"moli-header-field",
+ "moli-html-input-type",
"moli-html-input-temporal",
"moli-window-features",
"moli-time",
diff --git a/moli-dom/Cargo.toml b/moli-dom/Cargo.toml
index 188044b6f..878b52ccd 100644
--- a/moli-dom/Cargo.toml
+++ b/moli-dom/Cargo.toml
@@ -8,6 +8,7 @@ edition = "2024"
html5ever = "0.39.0"
indexmap = "2.6"
moli-css-parse = { path = "../moli-css-parse" }
+moli-html-input-type = { path = "../moli-html-input-type" }
moli-html-input-temporal = { path = "../moli-html-input-temporal" }
percent-encoding = "2.3"
selectors = "0.40"
diff --git a/moli-dom/src/accessibility/ax_projection.rs b/moli-dom/src/accessibility/ax_projection.rs
index c3f11dd40..81e0c733a 100644
--- a/moli-dom/src/accessibility/ax_projection.rs
+++ b/moli-dom/src/accessibility/ax_projection.rs
@@ -1,5 +1,6 @@
use crate::{
NodeData, NodeId,
+ forms::InputType,
native::{Element, NativeDom, Node},
};
@@ -170,7 +171,7 @@ fn ax_node_inclusion(node: &Node) -> AxNodeInclusion {
}
fn ax_element_inclusion(element: &Element) -> AxNodeInclusion {
- if element.is_html_input() && element.input_type() == "hidden" {
+ if element.is_html_input() && element.input_type() == InputType::Hidden {
return AxNodeInclusion::ExcludeSubtree;
}
diff --git a/moli-dom/src/accessibility/ax_properties.rs b/moli-dom/src/accessibility/ax_properties.rs
index bce2bd5ae..4e5f35470 100644
--- a/moli-dom/src/accessibility/ax_properties.rs
+++ b/moli-dom/src/accessibility/ax_properties.rs
@@ -1,5 +1,6 @@
use crate::{
NodeData, NodeId,
+ forms::InputType,
native::{Element, NativeDom, Node},
};
use serde_json::{Value, json};
@@ -178,11 +179,11 @@ fn ax_native_element_name(
}
match element.local_name() {
- "input" => match element.input_type().as_str() {
- "button" => Some(normalize_ax_whitespace(&element.input_value())),
- "submit" => Some(ax_input_button_name(element, "Submit")),
- "reset" => Some(ax_input_button_name(element, "Reset")),
- "image" => element
+ "input" => match element.input_type() {
+ InputType::Button => Some(normalize_ax_whitespace(&element.input_value())),
+ InputType::Submit => Some(ax_input_button_name(element, "Submit")),
+ InputType::Reset => Some(ax_input_button_name(element, "Reset")),
+ InputType::Image => element
.attribute("alt")
.map(normalize_ax_whitespace)
.or_else(|| {
@@ -267,7 +268,7 @@ fn ax_is_labelable(element: &Element) -> bool {
}
match element.local_name() {
"button" | "meter" | "output" | "progress" | "select" | "textarea" => true,
- "input" => element.is_html_input() && element.input_type() != "hidden",
+ "input" => element.is_html_input() && element.input_type() != InputType::Hidden,
_ => false,
}
}
@@ -276,8 +277,14 @@ fn ax_is_text_control(element: &Element) -> bool {
element.is_html_textarea()
|| (element.is_html_input()
&& matches!(
- element.input_type().as_str(),
- "email" | "number" | "password" | "search" | "tel" | "text" | "url"
+ element.input_type(),
+ InputType::Email
+ | InputType::Number
+ | InputType::Password
+ | InputType::Search
+ | InputType::Tel
+ | InputType::Text
+ | InputType::Url
))
}
@@ -386,8 +393,14 @@ pub(super) fn ax_value(document: &NativeDom, node_id: NodeId, node: &Node) -> Op
let value = match element.local_name() {
"input"
if !matches!(
- element.input_type().as_str(),
- "button" | "checkbox" | "hidden" | "image" | "radio" | "reset" | "submit"
+ element.input_type(),
+ InputType::Button
+ | InputType::Checkbox
+ | InputType::Hidden
+ | InputType::Image
+ | InputType::Radio
+ | InputType::Reset
+ | InputType::Submit
) =>
{
element.input_value()
@@ -494,8 +507,14 @@ pub(super) fn ax_properties(document: &NativeDom, node_id: NodeId, node: &Node)
}
if element.is_html_element("input") {
let input_type = element.input_type();
- match input_type.as_str() {
- "text" | "email" | "tel" | "url" | "search" | "password" | "number" => {
+ match input_type {
+ InputType::Text
+ | InputType::Email
+ | InputType::Tel
+ | InputType::Url
+ | InputType::Search
+ | InputType::Password
+ | InputType::Number => {
let disabled = ax_control_is_disabled(document, node_id, element);
if disabled {
properties.push(ax_bool_property("disabled", "boolean", true));
@@ -528,7 +547,7 @@ pub(super) fn ax_properties(document: &NativeDom, node_id: NodeId, node: &Node)
element.has_attribute("required"),
));
}
- "checkbox" | "radio" => {
+ InputType::Checkbox | InputType::Radio => {
let disabled = ax_control_is_disabled(document, node_id, element);
if disabled {
properties.push(ax_bool_property("disabled", "boolean", true));
@@ -543,7 +562,7 @@ pub(super) fn ax_properties(document: &NativeDom, node_id: NodeId, node: &Node)
}
properties.push(ax_tristate_property(
"checked",
- if input_type == "checkbox" && element.indeterminate() {
+ if input_type == InputType::Checkbox && element.indeterminate() {
"mixed"
} else if element.checked() {
"true"
@@ -552,7 +571,7 @@ pub(super) fn ax_properties(document: &NativeDom, node_id: NodeId, node: &Node)
},
));
}
- "button" | "submit" | "reset" | "image" => {
+ InputType::Button | InputType::Submit | InputType::Reset | InputType::Image => {
let disabled = ax_control_is_disabled(document, node_id, element);
if disabled {
properties.push(ax_bool_property("disabled", "boolean", true));
diff --git a/moli-dom/src/forms/input_type.rs b/moli-dom/src/forms/input_type.rs
index 113331378..b42fddaf5 100644
--- a/moli-dom/src/forms/input_type.rs
+++ b/moli-dom/src/forms/input_type.rs
@@ -4,83 +4,17 @@ use moli_html_input_temporal::{
is_valid_date_input_value, is_valid_month_input_value, is_valid_time_input_value,
is_valid_week_input_value,
};
-
-pub fn canonical_input_type(value: &str) -> &'static str {
- match value.trim().to_ascii_lowercase().as_str() {
- "button" => "button",
- "checkbox" => "checkbox",
- "color" => "color",
- "date" => "date",
- "datetime-local" => "datetime-local",
- "email" => "email",
- "file" => "file",
- "hidden" => "hidden",
- "image" => "image",
- "month" => "month",
- "number" => "number",
- "password" => "password",
- "radio" => "radio",
- "range" => "range",
- "reset" => "reset",
- "search" => "search",
- "submit" => "submit",
- "tel" => "tel",
- "text" => "text",
- "time" => "time",
- "url" => "url",
- "week" => "week",
- _ => "text",
- }
-}
-
-pub fn input_type_supports_value_as_number(input_type: &str) -> bool {
- matches!(
- canonical_input_type(input_type),
- "number" | "range" | "date" | "time" | "datetime-local" | "month" | "week"
- )
-}
-
-pub fn input_type_supports_pattern(input_type: &str) -> bool {
- matches!(
- canonical_input_type(input_type),
- "text" | "search" | "tel" | "url" | "email" | "password"
- )
-}
-
-pub fn input_type_supports_text_length_validation(input_type: &str) -> bool {
- matches!(
- canonical_input_type(input_type),
- "text" | "search" | "url" | "tel" | "email" | "password"
- )
-}
-
-pub fn input_type_suppresses_immutable_required(input_type: &str) -> bool {
- matches!(
- canonical_input_type(input_type),
- "text"
- | "search"
- | "url"
- | "tel"
- | "email"
- | "password"
- | "date"
- | "month"
- | "week"
- | "time"
- | "datetime-local"
- | "number"
- )
-}
+use moli_html_input_type::InputType;
pub fn form_control_type_supports_intrinsic_validation(
local_name: &str,
- input_type: Option<&str>,
+ input_type: Option<InputType>,
button_type: Option<&str>,
) -> bool {
match local_name {
"input" => !matches!(
- canonical_input_type(input_type.unwrap_or("text")),
- "hidden" | "button" | "reset"
+ input_type.unwrap_or_default(),
+ InputType::Hidden | InputType::Button | InputType::Reset
),
"select" | "textarea" => true,
"button" => !matches!(
@@ -95,37 +29,39 @@ pub fn form_control_type_supports_intrinsic_validation(
}
}
-pub fn sanitize_input_value_for_type(input_type: &str, value: &str) -> String {
- match canonical_input_type(input_type) {
+pub fn sanitize_input_value_for_type(input_type: InputType, value: &str) -> String {
+ match input_type {
// Text-family — strip newlines / CR but leave whitespace runs alone.
- "text" | "search" | "tel" | "password" => strip_input_value_line_breaks(value),
+ InputType::Text | InputType::Search | InputType::Tel | InputType::Password => {
+ strip_input_value_line_breaks(value)
+ }
// URL / Email — strip newlines AND trim leading/trailing ASCII whitespace.
// (Email's multi-value parsing isn't relevant here since the dirty
// value path only ever sees a single value.)
- "url" | "email" => {
+ InputType::Url | InputType::Email => {
let stripped = strip_input_value_line_breaks(value);
stripped.trim_matches(is_ascii_whitespace_char).to_owned()
}
- "number" if !is_valid_number_input_value(value) => String::new(),
- "date" if !is_valid_date_input_value(value) => String::new(),
- "time" if !is_valid_time_input_value(value) => String::new(),
- "datetime-local" => datetime_local_input_milliseconds(value)
+ InputType::Number if !is_valid_number_input_value(value) => String::new(),
+ InputType::Date if !is_valid_date_input_value(value) => String::new(),
+ InputType::Time if !is_valid_time_input_value(value) => String::new(),
+ InputType::DatetimeLocal => datetime_local_input_milliseconds(value)
.and_then(datetime_local_input_value_from_milliseconds)
.unwrap_or_default(),
- "month" if !is_valid_month_input_value(value) => String::new(),
- "week" if !is_valid_week_input_value(value) => String::new(),
+ InputType::Month if !is_valid_month_input_value(value) => String::new(),
+ InputType::Week if !is_valid_week_input_value(value) => String::new(),
// Range — sanitization: parse as float, clamp to [min, max], else
// default to "(min+max)/2". Without min/max context here we use the
// attribute-less default range 0..=100 (midpoint 50). Callers with
// attribute context can override.
- "range" => sanitize_range_value(value),
+ InputType::Range => sanitize_range_value(value),
// HTML-compatible color inputs accept CSS colors, discard alpha, and
// expose an opaque lowercase sRGB simple color.
- "color" => sanitize_color_value(value),
+ InputType::Color => sanitize_color_value(value),
// File — IDL value is always the empty string when set
// programmatically; the user-selected files are the only path to a
// non-empty file list.
- "file" => String::new(),
+ InputType::File => String::new(),
_ => value.to_owned(),
}
}
@@ -165,20 +101,25 @@ fn sanitize_color_value(value: &str) -> String {
.unwrap_or_else(|| "#000000".to_owned())
}
-pub fn input_type_has_value_sanitization(input_type: &str) -> bool {
+pub fn input_type_has_value_sanitization(input_type: InputType) -> bool {
matches!(
- canonical_input_type(input_type),
- "number" | "date" | "time" | "datetime-local" | "month" | "week"
+ input_type,
+ InputType::Number
+ | InputType::Date
+ | InputType::Time
+ | InputType::DatetimeLocal
+ | InputType::Month
+ | InputType::Week
)
}
-pub fn input_type_value_mismatch(input_type: &str, value: &str, multiple: bool) -> bool {
+pub fn input_type_value_mismatch(input_type: InputType, value: &str, multiple: bool) -> bool {
if value.is_empty() {
return false;
}
- match canonical_input_type(input_type) {
- "email" => email_value_type_mismatch(value, multiple),
- "url" => url_value_type_mismatch(value),
+ match input_type {
+ InputType::Email => email_value_type_mismatch(value, multiple),
+ InputType::Url => url_value_type_mismatch(value),
_ => false,
}
}
@@ -251,84 +192,130 @@ pub fn url_value_type_mismatch(value: &str) -> bool {
#[cfg(test)]
mod tests {
use super::sanitize_input_value_for_type;
+ use moli_html_input_type::InputType;
const INITIAL: &str = " foo\rbar ";
#[test]
fn text_family_strips_cr_but_preserves_surrounding_whitespace() {
- for kw in ["text", "search", "tel", "password"] {
+ for input_type in [
+ InputType::Text,
+ InputType::Search,
+ InputType::Tel,
+ InputType::Password,
+ ] {
assert_eq!(
- sanitize_input_value_for_type(kw, INITIAL),
+ sanitize_input_value_for_type(input_type, INITIAL),
" foobar ",
- "{kw}: surrounding whitespace must survive"
+ "{input_type}: surrounding whitespace must survive"
);
}
}
#[test]
fn url_email_strip_cr_then_trim_whitespace() {
- for kw in ["url", "email"] {
+ for input_type in [InputType::Url, InputType::Email] {
assert_eq!(
- sanitize_input_value_for_type(kw, INITIAL),
+ sanitize_input_value_for_type(input_type, INITIAL),
"foobar",
- "{kw}: must trim AND strip CR"
+ "{input_type}: must trim AND strip CR"
);
- assert_eq!(sanitize_input_value_for_type(kw, ""), "");
+ assert_eq!(sanitize_input_value_for_type(input_type, ""), "");
// Already-trimmed values pass through unchanged.
- assert_eq!(sanitize_input_value_for_type(kw, "foobar"), "foobar");
+ assert_eq!(
+ sanitize_input_value_for_type(input_type, "foobar"),
+ "foobar"
+ );
}
}
#[test]
fn range_defaults_to_midpoint_for_invalid_input() {
// " foo\rbar " parses as NaN -> default midpoint of 0..=100 = "50".
- assert_eq!(sanitize_input_value_for_type("range", INITIAL), "50");
+ assert_eq!(
+ sanitize_input_value_for_type(InputType::Range, INITIAL),
+ "50"
+ );
// Empty -> default.
- assert_eq!(sanitize_input_value_for_type("range", ""), "50");
+ assert_eq!(sanitize_input_value_for_type(InputType::Range, ""), "50");
// Valid float in-range round-trips and gets integer-serialised when
// it lands exactly on an integer.
- assert_eq!(sanitize_input_value_for_type("range", "42"), "42");
+ assert_eq!(sanitize_input_value_for_type(InputType::Range, "42"), "42");
// Out-of-range -> clamped.
- assert_eq!(sanitize_input_value_for_type("range", "150"), "100");
- assert_eq!(sanitize_input_value_for_type("range", "-5"), "0");
+ assert_eq!(
+ sanitize_input_value_for_type(InputType::Range, "150"),
+ "100"
+ );
+ assert_eq!(sanitize_input_value_for_type(InputType::Range, "-5"), "0");
}
#[test]
fn color_parses_css_colors_and_defaults_to_black_for_invalid_input() {
- assert_eq!(sanitize_input_value_for_type("color", INITIAL), "#000000");
- assert_eq!(sanitize_input_value_for_type("color", ""), "#000000");
- assert_eq!(sanitize_input_value_for_type("color", "red"), "#ff0000");
- assert_eq!(sanitize_input_value_for_type("color", "#FFAA00"), "#ffaa00");
- assert_eq!(sanitize_input_value_for_type("color", "#abc"), "#aabbcc");
assert_eq!(
- sanitize_input_value_for_type("color", "color(display-p3 .5 0 0)"),
+ sanitize_input_value_for_type(InputType::Color, INITIAL),
+ "#000000"
+ );
+ assert_eq!(
+ sanitize_input_value_for_type(InputType::Color, ""),
+ "#000000"
+ );
+ assert_eq!(
+ sanitize_input_value_for_type(InputType::Color, "red"),
+ "#ff0000"
+ );
+ assert_eq!(
+ sanitize_input_value_for_type(InputType::Color, "#FFAA00"),
+ "#ffaa00"
+ );
+ assert_eq!(
+ sanitize_input_value_for_type(InputType::Color, "#abc"),
+ "#aabbcc"
+ );
+ assert_eq!(
+ sanitize_input_value_for_type(InputType::Color, "color(display-p3 .5 0 0)"),
"#8c0000"
);
assert_eq!(
- sanitize_input_value_for_type("color", "not-a-color"),
+ sanitize_input_value_for_type(InputType::Color, "not-a-color"),
"#000000"
);
}
#[test]
fn file_always_yields_empty_string() {
- assert_eq!(sanitize_input_value_for_type("file", INITIAL), "");
- assert_eq!(sanitize_input_value_for_type("file", "anything"), "");
+ assert_eq!(sanitize_input_value_for_type(InputType::File, INITIAL), "");
+ assert_eq!(
+ sanitize_input_value_for_type(InputType::File, "anything"),
+ ""
+ );
}
#[test]
fn states_without_sanitization_pass_value_through_unchanged() {
- for kw in [
- "hidden", "checkbox", "radio", "submit", "reset", "button", "image",
+ for input_type in [
+ InputType::Hidden,
+ InputType::Checkbox,
+ InputType::Radio,
+ InputType::Submit,
+ InputType::Reset,
+ InputType::Button,
+ InputType::Image,
] {
- assert_eq!(sanitize_input_value_for_type(kw, INITIAL), INITIAL);
+ assert_eq!(sanitize_input_value_for_type(input_type, INITIAL), INITIAL);
}
}
#[test]
fn invalid_temporal_values_collapse_to_empty_string() {
- for kw in ["number", "date", "time", "datetime-local", "month", "week"] {
- assert_eq!(sanitize_input_value_for_type(kw, INITIAL), "");
+ for input_type in [
+ InputType::Number,
+ InputType::Date,
+ InputType::Time,
+ InputType::DatetimeLocal,
+ InputType::Month,
+ InputType::Week,
+ ] {
+ assert_eq!(sanitize_input_value_for_type(input_type, INITIAL), "");
}
}
}
diff --git a/moli-dom/src/forms/mod.rs b/moli-dom/src/forms/mod.rs
index aa89cf49e..5b5e0a1b4 100644
--- a/moli-dom/src/forms/mod.rs
+++ b/moli-dom/src/forms/mod.rs
@@ -4,12 +4,9 @@ mod text;
mod validity;
pub use input_type::{
- canonical_input_type, email_value_type_mismatch,
- form_control_type_supports_intrinsic_validation, input_type_has_value_sanitization,
- input_type_supports_pattern, input_type_supports_text_length_validation,
- input_type_supports_value_as_number, input_type_suppresses_immutable_required,
- input_type_value_mismatch, is_valid_email_address, sanitize_input_value_for_type,
- url_value_type_mismatch,
+ email_value_type_mismatch, form_control_type_supports_intrinsic_validation,
+ input_type_has_value_sanitization, input_type_value_mismatch, is_valid_email_address,
+ sanitize_input_value_for_type, url_value_type_mismatch,
};
pub use moli_html_input_temporal::{
MS_PER_DAY, MS_PER_HOUR, MS_PER_MINUTE, MS_PER_SECOND, MS_PER_WEEK, WEEK_INPUT_STEP_BASE,
@@ -21,6 +18,7 @@ pub use moli_html_input_temporal::{
time_input_value_from_milliseconds, week_input_milliseconds,
week_input_value_from_milliseconds,
};
+pub use moli_html_input_type::InputType;
pub use numeric::{
InputStepDirection, InputStepError, InputStepOutcome, InputStepState, MeterElementValues,
MeterGaugeRegion, ProgressElementValues, input_number_to_value_string, input_range_overflow,
diff --git a/moli-dom/src/forms/numeric.rs b/moli-dom/src/forms/numeric.rs
index 9f4ab4ad3..7cfaff0bf 100644
--- a/moli-dom/src/forms/numeric.rs
+++ b/moli-dom/src/forms/numeric.rs
@@ -1,4 +1,3 @@
-use super::input_type::{canonical_input_type, input_type_supports_value_as_number};
use moli_html_input_temporal::{
MS_PER_DAY, MS_PER_SECOND, MS_PER_WEEK, WEEK_INPUT_STEP_BASE, date_input_milliseconds,
date_input_value_from_milliseconds, datetime_local_input_milliseconds,
@@ -6,6 +5,7 @@ use moli_html_input_temporal::{
month_input_value_from_number, time_input_milliseconds, time_input_value_from_milliseconds,
week_input_milliseconds, week_input_value_from_milliseconds,
};
+use moli_html_input_type::InputType;
pub fn is_valid_number_input_value(value: &str) -> bool {
if value.is_empty() {
@@ -175,31 +175,31 @@ pub fn parse_html_floating_point_prefix(value: &str) -> Option<f64> {
value[..end].parse::<f64>().ok()
}
-pub fn parse_input_numeric_value(input_type: &str, value: &str) -> Option<f64> {
- match canonical_input_type(input_type) {
- "number" | "range" => parse_finite_number(value),
- "date" => date_input_milliseconds(value),
- "time" => time_input_milliseconds(value),
- "datetime-local" => datetime_local_input_milliseconds(value),
- "month" => month_input_number(value),
- "week" => week_input_milliseconds(value),
+pub fn parse_input_numeric_value(input_type: InputType, value: &str) -> Option<f64> {
+ match input_type {
+ InputType::Number | InputType::Range => parse_finite_number(value),
+ InputType::Date => date_input_milliseconds(value),
+ InputType::Time => time_input_milliseconds(value),
+ InputType::DatetimeLocal => datetime_local_input_milliseconds(value),
+ InputType::Month => month_input_number(value),
+ InputType::Week => week_input_milliseconds(value),
_ => None,
}
}
-pub fn input_number_to_value_string(input_type: &str, value: f64) -> Option<String> {
- match canonical_input_type(input_type) {
- "number" | "range" => Some(value.to_string()),
- "date" => date_input_value_from_milliseconds(value),
- "time" => time_input_value_from_milliseconds(value),
- "datetime-local" => datetime_local_input_value_from_milliseconds(value),
- "month" => month_input_value_from_number(value),
- "week" => week_input_value_from_milliseconds(value),
+pub fn input_number_to_value_string(input_type: InputType, value: f64) -> Option<String> {
+ match input_type {
+ InputType::Number | InputType::Range => Some(value.to_string()),
+ InputType::Date => date_input_value_from_milliseconds(value),
+ InputType::Time => time_input_value_from_milliseconds(value),
+ InputType::DatetimeLocal => datetime_local_input_value_from_milliseconds(value),
+ InputType::Month => month_input_value_from_number(value),
+ InputType::Week => week_input_value_from_milliseconds(value),
_ => None,
}
}
-pub fn input_step(input_type: &str, step: Option<&str>) -> Option<f64> {
+pub fn input_step(input_type: InputType, step: Option<&str>) -> Option<f64> {
let Some(step) = step else {
return Some(default_input_step(input_type));
};
@@ -214,35 +214,33 @@ pub fn input_step(input_type: &str, step: Option<&str>) -> Option<f64> {
)
}
-fn default_input_step(input_type: &str) -> f64 {
- match canonical_input_type(input_type) {
- "date" => MS_PER_DAY,
- "time" => 60.0 * MS_PER_SECOND,
- "datetime-local" => 60.0 * MS_PER_SECOND,
- "week" => MS_PER_WEEK,
+fn default_input_step(input_type: InputType) -> f64 {
+ match input_type {
+ InputType::Date => MS_PER_DAY,
+ InputType::Time | InputType::DatetimeLocal => 60.0 * MS_PER_SECOND,
+ InputType::Week => MS_PER_WEEK,
_ => 1.0,
}
}
-fn input_step_scale(input_type: &str) -> f64 {
- match canonical_input_type(input_type) {
- "date" => MS_PER_DAY,
- "time" => MS_PER_SECOND,
- "datetime-local" => MS_PER_SECOND,
- "week" => MS_PER_WEEK,
+fn input_step_scale(input_type: InputType) -> f64 {
+ match input_type {
+ InputType::Date => MS_PER_DAY,
+ InputType::Time | InputType::DatetimeLocal => MS_PER_SECOND,
+ InputType::Week => MS_PER_WEEK,
_ => 1.0,
}
}
-pub fn input_step_base(input_type: &str, min: Option<&str>, value: Option<&str>) -> f64 {
+pub fn input_step_base(input_type: InputType, min: Option<&str>, value: Option<&str>) -> f64 {
min.and_then(|value| parse_input_numeric_value(input_type, value))
.or_else(|| value.and_then(|value| parse_input_numeric_value(input_type, value)))
.unwrap_or_else(|| default_input_step_base(input_type))
}
-fn default_input_step_base(input_type: &str) -> f64 {
- match canonical_input_type(input_type) {
- "week" => WEEK_INPUT_STEP_BASE,
+fn default_input_step_base(input_type: InputType) -> f64 {
+ match input_type {
+ InputType::Week => WEEK_INPUT_STEP_BASE,
_ => 0.0,
}
}
@@ -254,7 +252,7 @@ pub fn number_aligns_to_step(value: f64, base: f64, step: f64) -> bool {
}
pub fn input_range_underflow(
- input_type: &str,
+ input_type: InputType,
value: f64,
min: Option<&str>,
max: Option<&str>,
@@ -267,7 +265,7 @@ pub fn input_range_underflow(
}
pub fn input_range_overflow(
- input_type: &str,
+ input_type: InputType,
value: f64,
min: Option<&str>,
max: Option<&str>,
@@ -280,11 +278,11 @@ pub fn input_range_overflow(
}
fn reversed_time_range(
- input_type: &str,
+ input_type: InputType,
min: Option<&str>,
max: Option<&str>,
) -> Option<(f64, f64)> {
- if canonical_input_type(input_type) != "time" {
+ if input_type != InputType::Time {
return None;
}
let min = min.and_then(|min| parse_input_numeric_value(input_type, min))?;
@@ -328,7 +326,7 @@ pub enum InputStepError {
#[derive(Clone, Copy, Debug)]
pub struct InputStepState<'a> {
- pub input_type: &'a str,
+ pub input_type: InputType,
pub value: &'a str,
pub min: Option<&'a str>,
pub max: Option<&'a str>,
@@ -341,7 +339,7 @@ pub fn step_input_value(
direction: InputStepDirection,
n: f64,
) -> Result<InputStepOutcome, InputStepError> {
- if !input_type_supports_value_as_number(state.input_type) {
+ if !state.input_type.supports_value_as_number() {
return Err(InputStepError::Unsupported);
}
let Some(step) = input_step(state.input_type, state.step) else {
diff --git a/moli-dom/src/forms/tests.rs b/moli-dom/src/forms/tests.rs
index 1754fac9b..17e848db6 100644
--- a/moli-dom/src/forms/tests.rs
+++ b/moli-dom/src/forms/tests.rs
@@ -67,40 +67,36 @@ fn integer_prefix_parsers_follow_html_attribute_rules() {
#[test]
fn input_type_tokens_and_support_matrices_are_shared() {
- assert_eq!(canonical_input_type("EMAIL"), "email");
- assert_eq!(canonical_input_type(" datetime-local "), "datetime-local");
- assert_eq!(canonical_input_type("unknown"), "text");
+ assert!(InputType::Week.supports_value_as_number());
+ assert!(!InputType::Email.supports_value_as_number());
- assert!(input_type_supports_value_as_number("week"));
- assert!(!input_type_supports_value_as_number("email"));
+ assert!(InputType::Password.supports_pattern());
+ assert!(!InputType::Number.supports_pattern());
- assert!(input_type_supports_pattern("password"));
- assert!(!input_type_supports_pattern("number"));
+ assert!(InputType::Email.supports_text_length_validation());
+ assert!(!InputType::Date.supports_text_length_validation());
- assert!(input_type_supports_text_length_validation("email"));
- assert!(!input_type_supports_text_length_validation("date"));
-
- assert!(input_type_suppresses_immutable_required("number"));
- assert!(!input_type_suppresses_immutable_required("checkbox"));
+ assert!(InputType::Number.supports_readonly());
+ assert!(!InputType::Checkbox.supports_readonly());
assert!(form_control_type_supports_intrinsic_validation(
"input",
- Some("text"),
+ Some(InputType::Text),
None
));
assert!(!form_control_type_supports_intrinsic_validation(
"input",
- Some("hidden"),
+ Some(InputType::Hidden),
None
));
assert!(form_control_type_supports_intrinsic_validation(
"input",
- Some("submit"),
+ Some(InputType::Submit),
None
));
assert!(form_control_type_supports_intrinsic_validation(
"input",
- Some("image"),
+ Some(InputType::Image),
None
));
assert!(!form_control_type_supports_intrinsic_validation(
@@ -112,26 +108,38 @@ fn input_type_tokens_and_support_matrices_are_shared() {
#[test]
fn input_type_mismatch_and_length_rules_are_shared() {
- assert!(!input_type_value_mismatch("email", "[email protected]", false));
- assert!(input_type_value_mismatch("email", "a@", false));
assert!(!input_type_value_mismatch(
- "email",
+ InputType::Email,
+ false
+ ));
+ assert!(input_type_value_mismatch(InputType::Email, "a@", false));
+ assert!(!input_type_value_mismatch(
+ InputType::Email,
true
));
assert!(input_type_value_mismatch(
- "email",
+ InputType::Email,
"[email protected], broken",
true
));
assert!(!input_type_value_mismatch(
- "url",
+ InputType::Url,
"https://example.com/a",
false
));
- assert!(input_type_value_mismatch("url", "not a url", false));
- assert!(!input_type_value_mismatch("text", "not a url", false));
+ assert!(input_type_value_mismatch(
+ InputType::Url,
+ "not a url",
+ false
+ ));
+ assert!(!input_type_value_mismatch(
+ InputType::Text,
+ "not a url",
+ false
+ ));
assert_eq!(text_control_value_length("a\u{1f980}"), 3);
assert!(text_control_suffers_too_long("abcd", Some("3")));
@@ -142,82 +150,129 @@ fn input_type_mismatch_and_length_rules_are_shared() {
#[test]
fn input_value_sanitization_uses_shared_temporal_parsers() {
- assert_eq!(sanitize_input_value_for_type("text", "a\nb\rc"), "abc");
- assert_eq!(sanitize_input_value_for_type("search", "a\r\nb"), "ab");
assert_eq!(
- sanitize_input_value_for_type("password", "\nsecret\r"),
+ sanitize_input_value_for_type(InputType::Text, "a\nb\rc"),
+ "abc"
+ );
+ assert_eq!(
+ sanitize_input_value_for_type(InputType::Search, "a\r\nb"),
+ "ab"
+ );
+ assert_eq!(
+ sanitize_input_value_for_type(InputType::Password, "\nsecret\r"),
"secret"
);
- assert_eq!(sanitize_input_value_for_type("number", "NaN"), "");
- assert_eq!(sanitize_input_value_for_type("number", "1."), "");
- assert_eq!(sanitize_input_value_for_type("number", "+1"), "");
- assert_eq!(sanitize_input_value_for_type("number", " 1"), "");
- assert_eq!(sanitize_input_value_for_type("date", "2024-02-30"), "");
- assert_eq!(sanitize_input_value_for_type("time", "24:00"), "");
+ assert_eq!(sanitize_input_value_for_type(InputType::Number, "NaN"), "");
+ assert_eq!(sanitize_input_value_for_type(InputType::Number, "1."), "");
+ assert_eq!(sanitize_input_value_for_type(InputType::Number, "+1"), "");
+ assert_eq!(sanitize_input_value_for_type(InputType::Number, " 1"), "");
+ assert_eq!(
+ sanitize_input_value_for_type(InputType::Date, "2024-02-30"),
+ ""
+ );
+ assert_eq!(sanitize_input_value_for_type(InputType::Time, "24:00"), "");
assert_eq!(
- sanitize_input_value_for_type("datetime-local", "2024-02-29 12:30"),
+ sanitize_input_value_for_type(InputType::DatetimeLocal, "2024-02-29 12:30"),
"2024-02-29T12:30"
);
assert_eq!(
- sanitize_input_value_for_type("datetime-local", "2022-04-19T12:34:56.010"),
+ sanitize_input_value_for_type(InputType::DatetimeLocal, "2022-04-19T12:34:56.010"),
"2022-04-19T12:34:56.01"
);
- assert_eq!(sanitize_input_value_for_type("month", "2024-13"), "");
- assert_eq!(sanitize_input_value_for_type("week", "2024-W99"), "");
assert_eq!(
- sanitize_input_value_for_type("text", "2024-W99"),
+ sanitize_input_value_for_type(InputType::Month, "2024-13"),
+ ""
+ );
+ assert_eq!(
+ sanitize_input_value_for_type(InputType::Week, "2024-W99"),
+ ""
+ );
+ assert_eq!(
+ sanitize_input_value_for_type(InputType::Text, "2024-W99"),
"2024-W99"
);
- assert!(input_type_has_value_sanitization("DATETIME-LOCAL"));
+ assert!(input_type_has_value_sanitization(InputType::DatetimeLocal));
}
#[test]
fn input_numeric_value_and_step_rules_are_shared() {
- assert_eq!(parse_input_numeric_value("number", "1.25"), Some(1.25));
- assert_eq!(parse_input_numeric_value("range", "50"), Some(50.0));
assert_eq!(
- parse_input_numeric_value("date", "1970-01-02"),
+ parse_input_numeric_value(InputType::Number, "1.25"),
+ Some(1.25)
+ );
+ assert_eq!(
+ parse_input_numeric_value(InputType::Range, "50"),
+ Some(50.0)
+ );
+ assert_eq!(
+ parse_input_numeric_value(InputType::Date, "1970-01-02"),
Some(MS_PER_DAY)
);
assert_eq!(
- input_number_to_value_string("month", 13.0),
+ input_number_to_value_string(InputType::Month, 13.0),
Some("1971-02".to_owned())
);
assert_eq!(
- input_number_to_value_string("range", 50.0),
+ input_number_to_value_string(InputType::Range, 50.0),
Some("50".to_owned())
);
assert_eq!(
- input_number_to_value_string("time", -MS_PER_HOUR),
+ input_number_to_value_string(InputType::Time, -MS_PER_HOUR),
Some("23:00".to_owned())
);
assert_eq!(
- input_number_to_value_string("time", 2.734_333_707_189_448e26),
+ input_number_to_value_string(InputType::Time, 2.734_333_707_189_448e26),
Some("10:54:10.944".to_owned())
);
- assert_eq!(input_step("number", None), Some(1.0));
- assert_eq!(input_step("time", Some("2")), Some(2.0 * MS_PER_SECOND));
- assert_eq!(input_step("week", Some("any")), None);
- assert_eq!(input_step_base("week", None, None), WEEK_INPUT_STEP_BASE);
+ assert_eq!(input_step(InputType::Number, None), Some(1.0));
+ assert_eq!(
+ input_step(InputType::Time, Some("2")),
+ Some(2.0 * MS_PER_SECOND)
+ );
+ assert_eq!(input_step(InputType::Week, Some("any")), None);
assert_eq!(
- input_step_base("date", Some("1970-01-02"), Some("1970-01-03")),
+ input_step_base(InputType::Week, None, None),
+ WEEK_INPUT_STEP_BASE
+ );
+ assert_eq!(
+ input_step_base(InputType::Date, Some("1970-01-02"), Some("1970-01-03")),
MS_PER_DAY
);
assert!(number_aligns_to_step(4.0, 0.0, 2.0));
- assert!(input_range_underflow("number", 2.0, Some("3"), Some("8")));
- assert!(!input_range_underflow("number", 4.0, Some("3"), Some("8")));
- assert!(input_range_overflow("number", 9.0, Some("3"), Some("8")));
- assert!(!input_range_overflow("number", 4.0, Some("3"), Some("8")));
assert!(input_range_underflow(
- "time",
+ InputType::Number,
+ 2.0,
+ Some("3"),
+ Some("8")
+ ));
+ assert!(!input_range_underflow(
+ InputType::Number,
+ 4.0,
+ Some("3"),
+ Some("8")
+ ));
+ assert!(input_range_overflow(
+ InputType::Number,
+ 9.0,
+ Some("3"),
+ Some("8")
+ ));
+ assert!(!input_range_overflow(
+ InputType::Number,
+ 4.0,
+ Some("3"),
+ Some("8")
+ ));
+ assert!(input_range_underflow(
+ InputType::Time,
time_input_milliseconds("06:00").unwrap(),
Some("23:00"),
Some("05:00")
));
assert!(input_range_overflow(
- "time",
+ InputType::Time,
time_input_milliseconds("06:00").unwrap(),
Some("23:00"),
Some("05:00")
@@ -359,7 +414,7 @@ fn meter_values_share_html_numeric_clamping_and_gauge_region_rules() {
fn input_step_up_down_rules_are_shared() {
let stepped = step_input_value(
InputStepState {
- input_type: "number",
+ input_type: InputType::Number,
value: "2",
min: Some("0"),
max: Some("10"),
@@ -374,7 +429,7 @@ fn input_step_up_down_rules_are_shared() {
let unaligned = step_input_value(
InputStepState {
- input_type: "number",
+ input_type: InputType::Number,
value: "3",
min: Some("0"),
max: Some("10"),
@@ -389,7 +444,7 @@ fn input_step_up_down_rules_are_shared() {
let empty_with_positive_min = step_input_value(
InputStepState {
- input_type: "number",
+ input_type: InputType::Number,
value: "",
min: Some("7"),
max: None,
@@ -407,7 +462,7 @@ fn input_step_up_down_rules_are_shared() {
let below_min_step_down = step_input_value(
InputStepState {
- input_type: "number",
+ input_type: InputType::Number,
value: "3",
min: Some("7"),
max: None,
@@ -422,7 +477,7 @@ fn input_step_up_down_rules_are_shared() {
let clamped = step_input_value(
InputStepState {
- input_type: "date",
+ input_type: InputType::Date,
value: "1970-01-01",
min: Some("1970-01-01"),
max: Some("1970-01-02"),
@@ -437,7 +492,7 @@ fn input_step_up_down_rules_are_shared() {
let huge_date_step = step_input_value(
InputStepState {
- input_type: "date",
+ input_type: InputType::Date,
value: "",
min: Some("2010-02-10"),
max: None,
@@ -455,7 +510,7 @@ fn input_step_up_down_rules_are_shared() {
let impossible_range = step_input_value(
InputStepState {
- input_type: "number",
+ input_type: InputType::Number,
value: "1",
min: Some("10"),
max: Some("1"),
@@ -470,7 +525,7 @@ fn input_step_up_down_rules_are_shared() {
let no_allowed_step = step_input_value(
InputStepState {
- input_type: "number",
+ input_type: InputType::Number,
value: "1",
min: None,
max: None,
@@ -484,7 +539,7 @@ fn input_step_up_down_rules_are_shared() {
let unsupported = step_input_value(
InputStepState {
- input_type: "text",
+ input_type: InputType::Text,
value: "1",
min: None,
max: None,
diff --git a/moli-dom/src/native/element/control_state.rs b/moli-dom/src/native/element/control_state.rs
index 136c0ed0c..5ef1e8329 100644
--- a/moli-dom/src/native/element/control_state.rs
+++ b/moli-dom/src/native/element/control_state.rs
@@ -1,6 +1,7 @@
use super::Attribute;
use crate::forms::{input_type_has_value_sanitization, sanitize_input_value_for_type};
use indexmap::IndexSet;
+use moli_html_input_type::InputType;
#[derive(Debug, Clone, PartialEq)]
pub struct SelectedFile {
@@ -206,7 +207,7 @@ impl ElementControlState {
};
if local_name == "input" {
- let input_type = attribute("type").unwrap_or("text");
+ let input_type = InputType::from_attribute_value(attribute("type"));
state.input_value = Some(sanitize_input_value_for_type(
input_type,
attribute("value").unwrap_or_default(),
@@ -822,7 +823,7 @@ impl ElementControlState {
&mut self,
namespace: &str,
local_name: &str,
- input_type: &str,
+ input_type: InputType,
attribute_name: &str,
attribute_value: Option<&str>,
) {
diff --git a/moli-dom/src/native/element/mod.rs b/moli-dom/src/native/element/mod.rs
index 18ab41dbb..412428169 100644
--- a/moli-dom/src/native/element/mod.rs
+++ b/moli-dom/src/native/element/mod.rs
@@ -21,9 +21,7 @@ use thin_vec::ThinVec;
use super::NativeDom;
use super::node::{NativeNodeId, Node};
use crate::custom_elements::is_valid_custom_element_name;
-use crate::forms::{
- canonical_input_type, is_valid_number_input_value, sanitize_input_value_for_type,
-};
+use crate::forms::{InputType, is_valid_number_input_value, sanitize_input_value_for_type};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CustomElementState {
@@ -449,13 +447,13 @@ impl Element {
self.namespace() == "http://www.w3.org/1999/xhtml" && self.name_attribute() == Some(name)
}
- pub fn input_type(&self) -> String {
- canonical_input_type(self.attribute("type").unwrap_or("text")).to_owned()
+ pub fn input_type(&self) -> InputType {
+ InputType::from_attribute_value(self.attribute("type"))
}
pub fn input_value(&self) -> String {
if self.is_html_input()
- && matches!(self.input_type().as_str(), "checkbox" | "radio")
+ && self.input_type().is_checkable()
&& !self.input_value_dirty()
&& self.attribute("value").is_none()
{
@@ -548,14 +546,14 @@ impl Element {
if !self.is_html_input() && !self.is_html_textarea() {
return false;
}
- if self.is_html_input() && self.input_type() == "file" {
+ if self.is_html_input() && self.input_type() == InputType::File {
if !value.is_empty() {
return false;
}
return self.set_selected_files(Vec::new());
}
let value = if self.is_html_input() {
- sanitize_input_value_for_type(&self.input_type(), value)
+ sanitize_input_value_for_type(self.input_type(), value)
} else {
value.to_owned()
};
@@ -566,14 +564,14 @@ impl Element {
if !self.is_html_input() && !self.is_html_textarea() {
return false;
}
- if self.is_html_input() && self.input_type() == "file" {
+ if self.is_html_input() && self.input_type() == InputType::File {
if !value.is_empty() {
return false;
}
return self.set_selected_files(Vec::new());
}
let value = if self.is_html_input() {
- sanitize_input_value_for_type(&self.input_type(), value)
+ sanitize_input_value_for_type(self.input_type(), value)
} else {
value.to_owned()
};
@@ -592,17 +590,18 @@ impl Element {
if !self.is_html_input() && !self.is_html_textarea() {
return false;
}
- if self.is_html_input() && self.input_type() == "file" {
+ if self.is_html_input() && self.input_type() == InputType::File {
return false;
}
let (value, bad_input) = if self.is_html_input() {
let input_type = self.input_type();
- let bad_input =
- input_type == "number" && !value.is_empty() && !is_valid_number_input_value(value);
+ let bad_input = input_type == InputType::Number
+ && !value.is_empty()
+ && !is_valid_number_input_value(value);
let value = if bad_input {
String::new()
} else {
- sanitize_input_value_for_type(&input_type, value)
+ sanitize_input_value_for_type(input_type, value)
};
(value, bad_input)
} else {
@@ -619,7 +618,10 @@ impl Element {
has_connected_datalist: bool,
) -> bool {
if !self.is_html_input()
- || !matches!(self.input_type().as_str(), "text" | "tel" | "url" | "email")
+ || !matches!(
+ self.input_type(),
+ InputType::Text | InputType::Tel | InputType::Url | InputType::Email
+ )
{
return false;
}
@@ -628,7 +630,7 @@ impl Element {
}
pub fn set_selected_files(&mut self, files: Vec<SelectedFile>) -> bool {
- if !self.is_html_input() || self.input_type() != "file" {
+ if !self.is_html_input() || self.input_type() != InputType::File {
return false;
}
@@ -1104,14 +1106,14 @@ impl Element {
&& self.local_name() == "input"
&& attribute_name == "type"
{
- attribute_value.unwrap_or("text").to_owned()
+ InputType::from_attribute_value(attribute_value)
} else {
self.input_type()
};
self.rare_data.sync_control_state_from_attribute(
self.namespace.as_ref(),
self.local_name.as_ref(),
- &input_type,
+ input_type,
attribute_name,
attribute_value,
);
diff --git a/moli-dom/src/native/element/rare_data.rs b/moli-dom/src/native/element/rare_data.rs
index 9eef1c5ec..f43d4319b 100644
--- a/moli-dom/src/native/element/rare_data.rs
+++ b/moli-dom/src/native/element/rare_data.rs
@@ -1,6 +1,7 @@
use std::sync::LazyLock;
use super::{Attribute, CustomElementState, ElementControlState};
+use crate::forms::InputType;
use crate::native::NativeNodeId;
static EMPTY_CONTROL_STATE: LazyLock<ElementControlState> =
@@ -165,7 +166,7 @@ impl ElementRareData {
&mut self,
namespace: &str,
local_name: &str,
- input_type: &str,
+ input_type: InputType,
attribute_name: &str,
attribute_value: Option<&str>,
) {
diff --git a/moli-dom/src/native/host/collections/form.rs b/moli-dom/src/native/host/collections/form.rs
index 33552ce43..312f8897d 100644
--- a/moli-dom/src/native/host/collections/form.rs
+++ b/moli-dom/src/native/host/collections/form.rs
@@ -1,5 +1,5 @@
use super::*;
-use crate::forms::parse_non_negative_integer_prefix;
+use crate::forms::{InputType, parse_non_negative_integer_prefix};
impl DomHost {
pub fn option_value(&self, handle: DomHandle) -> Option<String> {
@@ -10,20 +10,20 @@ impl DomHost {
let input = self.node(handle).and_then(Node::as_element)?;
if !input.is_html_input()
|| !matches!(
- input.input_type().as_str(),
- "text"
- | "search"
- | "tel"
- | "url"
- | "email"
- | "date"
- | "month"
- | "week"
- | "time"
- | "datetime-local"
- | "number"
- | "range"
- | "color"
+ input.input_type(),
+ InputType::Text
+ | InputType::Search
+ | InputType::Tel
+ | InputType::Url
+ | InputType::Email
+ | InputType::Date
+ | InputType::Month
+ | InputType::Week
+ | InputType::Time
+ | InputType::DatetimeLocal
+ | InputType::Number
+ | InputType::Range
+ | InputType::Color
)
{
return None;
@@ -147,7 +147,7 @@ impl DomHost {
let Some(element) = self.node(handle).and_then(Node::as_element) else {
return Vec::new();
};
- if !element.is_html_input() || element.input_type() != "radio" {
+ if !element.is_html_input() || element.input_type() != InputType::Radio {
return Vec::new();
}
let Some(name) = element.name_attribute() else {
@@ -162,7 +162,7 @@ impl DomHost {
.and_then(Node::as_element)
.is_some_and(|candidate_element| {
candidate_element.is_html_input()
- && candidate_element.input_type() == "radio"
+ && candidate_element.input_type() == InputType::Radio
&& candidate_element.matches_name(name)
&& self.form_control_owner(candidate) == form_owner
})
@@ -289,7 +289,7 @@ fn is_listed_form_control_element(element: &Element) -> bool {
}
match element.local_name() {
- "input" => element.input_type() != "image",
+ "input" => element.input_type() != InputType::Image,
"button" | "fieldset" | "object" | "output" | "select" | "textarea" => true,
_ => false,
}
diff --git a/moli-dom/src/native/host/mutation/state.rs b/moli-dom/src/native/host/mutation/state.rs
index 96fc0a11e..1d2608cda 100644
--- a/moli-dom/src/native/host/mutation/state.rs
+++ b/moli-dom/src/native/host/mutation/state.rs
@@ -1,4 +1,5 @@
use super::*;
+use crate::forms::InputType;
use crate::native::{CustomElementState, SelectedFile};
impl DomHost {
@@ -658,7 +659,7 @@ impl DomHost {
.and_then(Node::as_element)
.is_some_and(|element| {
element.is_html_input()
- && element.input_type() == "radio"
+ && element.input_type() == InputType::Radio
&& element.checked()
})
})
@@ -678,7 +679,7 @@ impl DomHost {
.and_then(Node::as_element)
.is_some_and(|element| {
element.is_html_input()
- && element.input_type() == "radio"
+ && element.input_type() == InputType::Radio
&& element.checked()
});
if !is_still_checked_radio || self.form_control_owner(radio) == previous_form_owner {
diff --git a/moli-html-input-type/Cargo.toml b/moli-html-input-type/Cargo.toml
new file mode 100644
index 000000000..832fe2d44
--- /dev/null
+++ b/moli-html-input-type/Cargo.toml
@@ -0,0 +1,10 @@
+[package]
+name = "moli-html-input-type"
+version = "0.1.0"
+edition = "2024"
+
+[dependencies]
+strum = { version = "0.28.0", features = ["derive"] }
+
+[lints]
+workspace = true
diff --git a/moli-html-input-type/src/lib.rs b/moli-html-input-type/src/lib.rs
new file mode 100644
index 000000000..509a840cc
--- /dev/null
+++ b/moli-html-input-type/src/lib.rs
@@ -0,0 +1,224 @@
+//! Canonical states for the HTML `<input type>` enumerated attribute.
+
+/// The state selected by an HTML `<input>` element's `type` attribute.
+///
+/// Missing and invalid attribute values select [`InputType::Text`]. The raw
+/// content attribute remains available at the DOM boundary when callers need
+/// to distinguish an invalid keyword from the resulting state.
+#[derive(
+ Clone,
+ Copy,
+ Debug,
+ Default,
+ Eq,
+ Hash,
+ PartialEq,
+ strum::AsRefStr,
+ strum::Display,
+ strum::EnumIter,
+ strum::EnumString,
+)]
+#[strum(serialize_all = "kebab-case", ascii_case_insensitive)]
+pub enum InputType {
+ Button,
+ Checkbox,
+ Color,
+ Date,
+ DatetimeLocal,
+ Email,
+ File,
+ Hidden,
+ Image,
+ Month,
+ Number,
+ Password,
+ Radio,
+ Range,
+ Reset,
+ Search,
+ Submit,
+ Tel,
+ #[default]
+ Text,
+ Time,
+ Url,
+ Week,
+}
+
+impl InputType {
+ /// Applies the enumerated-attribute keyword matching and invalid-value
+ /// default used by `HTMLInputElement.type`.
+ pub fn from_attribute_value(value: Option<&str>) -> Self {
+ value
+ .and_then(|value| value.parse().ok())
+ .unwrap_or_default()
+ }
+
+ pub const fn is_checkable(self) -> bool {
+ matches!(self, Self::Checkbox | Self::Radio)
+ }
+
+ pub const fn is_submit_button(self) -> bool {
+ matches!(self, Self::Submit | Self::Image)
+ }
+
+ pub const fn supports_value_as_number(self) -> bool {
+ matches!(
+ self,
+ Self::Number
+ | Self::Range
+ | Self::Date
+ | Self::Time
+ | Self::DatetimeLocal
+ | Self::Month
+ | Self::Week
+ )
+ }
+
+ pub const fn supports_value_as_date(self) -> bool {
+ matches!(self, Self::Date | Self::Month | Self::Week | Self::Time)
+ }
+
+ pub const fn supports_pattern(self) -> bool {
+ matches!(
+ self,
+ Self::Text | Self::Search | Self::Tel | Self::Url | Self::Email | Self::Password
+ )
+ }
+
+ pub const fn supports_placeholder(self) -> bool {
+ matches!(
+ self,
+ Self::Text | Self::Search | Self::Url | Self::Tel | Self::Email | Self::Password
+ )
+ }
+
+ pub const fn supports_required(self) -> bool {
+ !matches!(
+ self,
+ Self::Hidden | Self::Button | Self::Submit | Self::Reset | Self::Image
+ )
+ }
+
+ pub const fn supports_text_length_validation(self) -> bool {
+ matches!(
+ self,
+ Self::Text | Self::Search | Self::Url | Self::Tel | Self::Email | Self::Password
+ )
+ }
+
+ pub const fn supports_readonly(self) -> bool {
+ matches!(
+ self,
+ Self::Text
+ | Self::Search
+ | Self::Url
+ | Self::Tel
+ | Self::Email
+ | Self::Password
+ | Self::Date
+ | Self::Month
+ | Self::Week
+ | Self::Time
+ | Self::DatetimeLocal
+ | Self::Number
+ )
+ }
+
+ pub const fn supports_variable_length_selection(self) -> bool {
+ matches!(
+ self,
+ Self::Text | Self::Search | Self::Tel | Self::Url | Self::Password
+ )
+ }
+
+ pub const fn supports_dirname(self) -> bool {
+ matches!(
+ self,
+ Self::Hidden
+ | Self::Text
+ | Self::Search
+ | Self::Tel
+ | Self::Url
+ | Self::Email
+ | Self::Password
+ )
+ }
+
+ pub const fn uses_value_for_auto_direction(self) -> bool {
+ matches!(
+ self,
+ Self::Hidden
+ | Self::Text
+ | Self::Search
+ | Self::Tel
+ | Self::Url
+ | Self::Email
+ | Self::Password
+ | Self::Submit
+ | Self::Reset
+ | Self::Button
+ )
+ }
+}
+
+impl From<Option<&str>> for InputType {
+ fn from(value: Option<&str>) -> Self {
+ Self::from_attribute_value(value)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::InputType;
+ use strum::IntoEnumIterator;
+
+ #[test]
+ fn canonical_keywords_round_trip() {
+ for input_type in InputType::iter() {
+ let keyword: &str = input_type.as_ref();
+ assert_eq!(keyword.parse::<InputType>(), Ok(input_type));
+ assert_eq!(input_type.to_string(), keyword);
+ }
+ }
+
+ #[test]
+ fn matching_is_ascii_case_insensitive() {
+ assert_eq!("EMAIL".parse::<InputType>(), Ok(InputType::Email));
+ assert_eq!(
+ "DaTeTiMe-LoCaL".parse::<InputType>(),
+ Ok(InputType::DatetimeLocal)
+ );
+ }
+
+ #[test]
+ fn missing_invalid_and_whitespace_padded_values_select_text() {
+ assert_eq!(InputType::from_attribute_value(None), InputType::Text);
+ for value in [
+ "unknown",
+ "DatetimeLocal",
+ "datetime_local",
+ " datetime-local ",
+ ] {
+ assert!(value.parse::<InputType>().is_err());
+ assert_eq!(
+ InputType::from_attribute_value(Some(value)),
+ InputType::Text
+ );
+ }
+ }
+
+ #[test]
+ fn capability_sets_are_defined_on_canonical_states() {
+ assert!(InputType::Week.supports_value_as_number());
+ assert!(!InputType::Email.supports_value_as_number());
+ assert!(InputType::Password.supports_pattern());
+ assert!(InputType::Email.supports_placeholder());
+ assert!(!InputType::Submit.supports_required());
+ assert!(InputType::Email.supports_text_length_validation());
+ assert!(InputType::Number.supports_readonly());
+ assert!(InputType::Url.supports_variable_length_selection());
+ assert!(InputType::Hidden.supports_dirname());
+ assert!(InputType::Submit.uses_value_for_auto_direction());
+ }
+}
diff --git a/moli-protocol-server/Cargo.toml b/moli-protocol-server/Cargo.toml
index 5f7da7f2a..a88de811f 100644
--- a/moli-protocol-server/Cargo.toml
+++ b/moli-protocol-server/Cargo.toml
@@ -14,6 +14,7 @@ moli-bounded-json = { path = "../moli-bounded-json" }
moli-cookie-jar = { path = "../moli-cookie-jar" }
moli-core = { path = "../moli-core" }
moli-fetch = { path = "../moli-fetch" }
+moli-html-input-type = { path = "../moli-html-input-type" }
moli-protocol = { path = "../moli-protocol" }
moli-protocol-cdp = { path = "../moli-protocol-cdp" }
moli-protocol-webdriver-bidi = { path = "../moli-protocol-webdriver-bidi" }
diff --git a/moli-protocol-server/src/protocol_server/webdriver_classic.rs b/moli-protocol-server/src/protocol_server/webdriver_classic.rs
index ba7ed13ac..5cd733d26 100644
--- a/moli-protocol-server/src/protocol_server/webdriver_classic.rs
+++ b/moli-protocol-server/src/protocol_server/webdriver_classic.rs
@@ -12,6 +12,7 @@ use axum::{
response::Response,
};
use moli_core::page::RendererDocumentLifecycleMilestone;
+use moli_html_input_type::InputType;
use moli_protocol::{
DevToolsPageResidenceIdentity,
devtools_runtime::{
@@ -3862,7 +3863,7 @@ pub(super) async fn webdriver_classic_is_element_selected(
Ok(value) => value.as_str().unwrap_or_default().to_ascii_lowercase(),
Err(error) => return classic_error_into_response(error),
};
- if input_type == "checkbox" || input_type == "radio" {
+ if InputType::from_attribute_value(Some(&input_type)).is_checkable() {
match webdriver_classic_element_property_value(
&state,
&binding,
diff --git a/moli-renderer-v8/src/context_bootstrap/form_data_runtime/serialize.rs b/moli-renderer-v8/src/context_bootstrap/form_data_runtime/serialize.rs
index f9e535913..2e1ced88f 100644
--- a/moli-renderer-v8/src/context_bootstrap/form_data_runtime/serialize.rs
+++ b/moli-renderer-v8/src/context_bootstrap/form_data_runtime/serialize.rs
@@ -1,7 +1,7 @@
use super::storage::{form_data_entries, form_data_is_object, push_form_data_entry};
use super::*;
use crate::custom_elements::is_form_associated_custom_element_handle;
-use crate::dom::native::Node;
+use crate::dom::{forms::InputType, native::Node};
use crate::native_bridge::{
element::{
element_attribute_for_object, element_internals_form_value_for_target,
@@ -93,8 +93,8 @@ fn append_form_data_entries_for_control<'s>(
let is_submitter = submitter.is_some_and(|submitter| control.strict_equals(submitter.into()));
match tag.as_str() {
- "input" => match control_type.as_str() {
- "checkbox" | "radio" => {
+ "input" => match InputType::from_attribute_value(Some(&control_type)) {
+ InputType::Checkbox | InputType::Radio => {
if !object_bool_property(scope, control, "checked").unwrap_or(false)
|| name.is_empty()
{
@@ -103,7 +103,7 @@ fn append_form_data_entries_for_control<'s>(
let value = form_control_value(scope, control, "on");
push_string_form_data_entry(scope, entries, &name, value);
}
- "submit" => {
+ InputType::Submit => {
if is_submitter {
if !name.is_empty() {
let value = form_control_value(scope, control, "");
@@ -112,7 +112,7 @@ fn append_form_data_entries_for_control<'s>(
append_dirname_form_data_entry(scope, entries, control);
}
}
- "image" => {
+ InputType::Image => {
if is_submitter {
let (x, y) = image_submitter_coordinates(scope, control);
let prefix = if name.is_empty() {
@@ -134,14 +134,14 @@ fn append_form_data_entries_for_control<'s>(
);
}
}
- "button" | "reset" => {}
- "file" => {
+ InputType::Button | InputType::Reset => {}
+ InputType::File => {
if name.is_empty() {
return;
}
append_file_form_data_entries(scope, entries, control, &name);
}
- "hidden" if is_charset_control_name(&name) => {
+ InputType::Hidden if is_charset_control_name(&name) => {
push_string_form_data_entry(scope, entries, &name, "UTF-8".to_owned());
append_dirname_form_data_entry(scope, entries, control);
}
@@ -151,7 +151,7 @@ fn append_form_data_entries_for_control<'s>(
}
let value = form_control_value(scope, control, "");
push_string_form_data_entry(scope, entries, &name, value);
- if input_type_supports_dirname(&control_type) {
+ if InputType::from_attribute_value(Some(&control_type)).supports_dirname() {
append_dirname_form_data_entry(scope, entries, control);
}
}
@@ -261,13 +261,6 @@ fn image_submitter_coordinates(
.unwrap_or((0, 0))
}
-fn input_type_supports_dirname(input_type: &str) -> bool {
- matches!(
- input_type,
- "hidden" | "text" | "search" | "tel" | "url" | "email" | "password"
- )
-}
-
fn is_charset_control_name(name: &str) -> bool {
is_charset_sentinel_name(name)
}
diff --git a/moli-renderer-v8/src/native_bridge/collections.rs b/moli-renderer-v8/src/native_bridge/collections.rs
index f84fc7f9a..ab20be437 100644
--- a/moli-renderer-v8/src/native_bridge/collections.rs
+++ b/moli-renderer-v8/src/native_bridge/collections.rs
@@ -1,6 +1,6 @@
use std::ffi::c_void;
-use crate::dom::native::Node;
+use crate::dom::{forms::InputType, native::Node};
use super::super::{
document_runtime::DomHandle,
diff --git a/moli-renderer-v8/src/native_bridge/collections/radio_node_list.rs b/moli-renderer-v8/src/native_bridge/collections/radio_node_list.rs
index faefabebe..ac8f56aa2 100644
--- a/moli-renderer-v8/src/native_bridge/collections/radio_node_list.rs
+++ b/moli-renderer-v8/src/native_bridge/collections/radio_node_list.rs
@@ -25,7 +25,10 @@ pub(in crate::native_bridge::collections) fn radio_node_list_value_getter<'s>(
let Some(element) = runtime.dom_host().node(handle).and_then(Node::as_element) else {
continue;
};
- if !element.is_html_input() || element.input_type() != "radio" || !element.checked() {
+ if !element.is_html_input()
+ || element.input_type() != InputType::Radio
+ || !element.checked()
+ {
continue;
}
if let Some(value) = v8_string(scope, &element.input_value()) {
@@ -69,7 +72,7 @@ pub(in crate::native_bridge::collections) fn radio_node_list_value_setter<'s>(
.and_then(Node::as_element)
.is_some_and(|element| {
element.is_html_input()
- && element.input_type() == "radio"
+ && element.input_type() == InputType::Radio
&& element.input_value() == target
})
})
diff --git a/moli-renderer-v8/src/native_bridge/element/activation/default_action.rs b/moli-renderer-v8/src/native_bridge/element/activation/default_action.rs
index 6e0aab663..6d47e6df1 100644
--- a/moli-renderer-v8/src/native_bridge/element/activation/default_action.rs
+++ b/moli-renderer-v8/src/native_bridge/element/activation/default_action.rs
@@ -2,7 +2,10 @@ use crate::context_bootstrap::{
LocationNavigationKind, navigate_location_object_with_source_element,
selection_value_for_window,
};
-use crate::dom::native::{Element, Node, SelectedFile};
+use crate::dom::{
+ forms::InputType,
+ native::{Element, Node, SelectedFile},
+};
use crate::util::{
call_object_method, get_private_value, node_wrapper_from_handle, object_bool_property,
object_number_property, object_property_as_object, utf16_len, v8_string, v8str,
@@ -159,8 +162,14 @@ fn is_text_drop_target(element: &Element) -> bool {
return false;
}
matches!(
- element.input_type().as_str(),
- "" | "text" | "search" | "url" | "tel" | "email" | "password" | "number"
+ element.input_type(),
+ InputType::Text
+ | InputType::Search
+ | InputType::Url
+ | InputType::Tel
+ | InputType::Email
+ | InputType::Password
+ | InputType::Number
)
}
@@ -652,7 +661,7 @@ fn is_radio_input(runtime: &JsContextHost, handle: DomHandle) -> bool {
.dom_host()
.node(handle)
.and_then(Node::as_element)
- .is_some_and(|element| element.is_html_input() && element.input_type() == "radio")
+ .is_some_and(|element| element.is_html_input() && element.input_type() == InputType::Radio)
}
fn is_checkbox_input(runtime: &JsContextHost, handle: DomHandle) -> bool {
@@ -660,7 +669,9 @@ fn is_checkbox_input(runtime: &JsContextHost, handle: DomHandle) -> bool {
.dom_host()
.node(handle)
.and_then(Node::as_element)
- .is_some_and(|element| element.is_html_input() && element.input_type() == "checkbox")
+ .is_some_and(|element| {
+ element.is_html_input() && element.input_type() == InputType::Checkbox
+ })
}
fn radio_group_members(runtime: &JsContextHost, handle: DomHandle) -> Vec<DomHandle> {
@@ -686,7 +697,7 @@ fn radio_group_members(runtime: &JsContextHost, handle: DomHandle) -> Vec<DomHan
.and_then(Node::as_element)
.is_some_and(|candidate_element| {
candidate_element.is_html_input()
- && candidate_element.input_type() == "radio"
+ && candidate_element.input_type() == InputType::Radio
&& candidate_element.attribute("name") == Some(name)
&& form_associated_form_owner(runtime, *candidate) == form_owner
})
@@ -1662,7 +1673,7 @@ fn is_valid_reset_button(runtime: &JsContextHost, handle: DomHandle) -> bool {
.node(handle)
.and_then(Node::as_element)
.is_some_and(|element| {
- (element.is_html_input() && element.input_type() == "reset")
+ (element.is_html_input() && element.input_type() == InputType::Reset)
|| (element.is_html_element("button") && element.attribute("type") == Some("reset"))
})
}
@@ -1672,7 +1683,7 @@ fn is_image_submit_button(runtime: &JsContextHost, handle: DomHandle) -> bool {
.dom_host()
.node(handle)
.and_then(Node::as_element)
- .is_some_and(|element| element.is_html_input() && element.input_type() == "image")
+ .is_some_and(|element| element.is_html_input() && element.input_type() == InputType::Image)
}
fn image_submitter_coordinate(
@@ -1789,7 +1800,7 @@ fn perform_file_chooser_default_action_with_source(
let (allow_multiple, should_auto_cancel) = {
let runtime = unsafe { &*runtime_ptr };
let element = runtime.dom_host().node(handle).and_then(Node::as_element)?;
- if !element.is_html_input() || element.input_type() != "file" {
+ if !element.is_html_input() || element.input_type() != InputType::File {
return None;
}
(
@@ -2218,7 +2229,7 @@ pub(crate) fn perform_drop_default_action(
let Some(element) = runtime.dom_host().node(handle).and_then(Node::as_element) else {
return false;
};
- let is_file_input = element.is_html_input() && element.input_type() == "file";
+ let is_file_input = element.is_html_input() && element.input_type() == InputType::File;
let is_text_target = is_text_drop_target(element);
let editing_host = (!is_text_target && !is_file_input)
.then(|| contenteditable_editing_host(runtime, handle))
diff --git a/moli-renderer-v8/src/native_bridge/element/forms.rs b/moli-renderer-v8/src/native_bridge/element/forms.rs
index 0562964eb..7e68d29ec 100644
--- a/moli-renderer-v8/src/native_bridge/element/forms.rs
+++ b/moli-renderer-v8/src/native_bridge/element/forms.rs
@@ -1,4 +1,7 @@
-use crate::dom::native::{Element, Node};
+use crate::dom::{
+ forms::InputType,
+ native::{Element, Node},
+};
use crate::{
construct_form_data_entries_for_form, custom_elements,
document_runtime::DomHandle,
diff --git a/moli-renderer-v8/src/native_bridge/element/forms/autocomplete.rs b/moli-renderer-v8/src/native_bridge/element/forms/autocomplete.rs
index ac1b3813f..f1c8baab1 100644
--- a/moli-renderer-v8/src/native_bridge/element/forms/autocomplete.rs
+++ b/moli-renderer-v8/src/native_bridge/element/forms/autocomplete.rs
@@ -169,7 +169,8 @@ pub(crate) fn autocomplete_field_name(
handle: DomHandle,
) -> Option<String> {
let element = runtime.dom_host().node(handle).and_then(Node::as_element)?;
- let wears_autofill_anchor_mantle = element.is_html_input() && element.input_type() == "hidden";
+ let wears_autofill_anchor_mantle =
+ element.is_html_input() && element.input_type() == InputType::Hidden;
let canonical = idl_exposed_autofill_value(
element.attribute("autocomplete"),
wears_autofill_anchor_mantle,
diff --git a/moli-renderer-v8/src/native_bridge/element/forms/form_element.rs b/moli-renderer-v8/src/native_bridge/element/forms/form_element.rs
index 0d39b486a..994bf1272 100644
--- a/moli-renderer-v8/src/native_bridge/element/forms/form_element.rs
+++ b/moli-renderer-v8/src/native_bridge/element/forms/form_element.rs
@@ -416,7 +416,7 @@ fn is_form_control_handle(
return false;
}
match element.local_name() {
- "input" => include_image_inputs || element.input_type() != "image",
+ "input" => include_image_inputs || element.input_type() != InputType::Image,
"button" | "fieldset" | "object" | "output" | "select" | "textarea" => true,
_ => false,
}
diff --git a/moli-renderer-v8/src/native_bridge/element/forms/input/files.rs b/moli-renderer-v8/src/native_bridge/element/forms/input/files.rs
index b9436f69a..fc6e3b283 100644
--- a/moli-renderer-v8/src/native_bridge/element/forms/input/files.rs
+++ b/moli-renderer-v8/src/native_bridge/element/forms/input/files.rs
@@ -76,7 +76,7 @@ fn input_files_getter_from_object<'s>(
rv.set_null();
return;
};
- if !element.is_html_input() || element.input_type() != "file" {
+ if !element.is_html_input() || element.input_type() != InputType::File {
rv.set_null();
return;
}
@@ -123,7 +123,7 @@ fn input_files_setter_on_object<'s>(
let Some(element) = runtime.dom_host().node(handle).and_then(Node::as_element) else {
return;
};
- if !element.is_html_input() || element.input_type() != "file" {
+ if !element.is_html_input() || element.input_type() != InputType::File {
return;
}
if value.is_null_or_undefined() {
diff --git a/moli-renderer-v8/src/native_bridge/element/forms/input/value.rs b/moli-renderer-v8/src/native_bridge/element/forms/input/value.rs
index 105cf782f..c11c0177a 100644
--- a/moli-renderer-v8/src/native_bridge/element/forms/input/value.rs
+++ b/moli-renderer-v8/src/native_bridge/element/forms/input/value.rs
@@ -1,9 +1,8 @@
use super::super::*;
use crate::webidl;
use moli_dom::forms::{
- InputStepDirection, InputStepError, InputStepOutcome, InputStepState, canonical_input_type,
- date_input_milliseconds, date_input_value_from_milliseconds,
- input_type_supports_value_as_number, month_input_milliseconds,
+ InputStepDirection, InputStepError, InputStepOutcome, InputStepState, date_input_milliseconds,
+ date_input_value_from_milliseconds, month_input_milliseconds,
month_input_value_from_milliseconds, sanitize_input_value_for_type, step_input_value,
time_input_milliseconds, time_input_value_from_milliseconds, week_input_milliseconds,
week_input_value_from_milliseconds,
@@ -41,13 +40,13 @@ fn input_type_getter_from_object<'s>(
rv.set_null();
return;
};
- let value = unsafe { &*runtime_ptr }
+ let input_type = unsafe { &*runtime_ptr }
.dom_host()
.node(handle)
.and_then(Node::as_element)
- .map(|element| canonical_input_type(&element.input_type()).to_owned())
- .unwrap_or_else(|| "text".to_owned());
- let Some(value) = v8_string(scope, &value) else {
+ .map(Element::input_type)
+ .unwrap_or_default();
+ let Some(value) = v8_string(scope, input_type.as_ref()) else {
rv.set_null();
return;
};
@@ -73,7 +72,7 @@ fn input_type_setter_on_object<'s>(
else {
return;
};
- let canonical = canonical_input_type(&value).to_owned();
+ let canonical = InputType::from_attribute_value(Some(&value));
let Ok((runtime_ptr, handle)) = node_runtime_and_handle_from_object_or_detached(scope, object)
else {
return;
@@ -83,7 +82,7 @@ fn input_type_setter_on_object<'s>(
// (either the dirty IDL value or, if unset, the `value` content
// attribute's default) BEFORE flipping the type so we can re-run the
// new state's sanitizer against the old text.
- let (previous_type, current_value): (Option<String>, Option<String>) = {
+ let (previous_type, current_value): (Option<InputType>, Option<String>) = {
let runtime = unsafe { &*runtime_ptr };
runtime
.dom_host()
@@ -96,12 +95,11 @@ fn input_type_setter_on_object<'s>(
set_reflected_attribute(scope, runtime_ptr, handle, "type", &value);
if let Some(raw) = current_value {
- let sanitized = sanitize_input_value_for_type(&canonical, &raw);
- let was_selectable = previous_type
- .as_deref()
- .is_some_and(input_type_supports_variable_length_selection);
- let is_selectable = input_type_supports_variable_length_selection(&canonical);
- if sanitized.is_empty() && matches!(canonical.as_str(), "checkbox" | "radio") {
+ let sanitized = sanitize_input_value_for_type(canonical, &raw);
+ let was_selectable =
+ previous_type.is_some_and(InputType::supports_variable_length_selection);
+ let is_selectable = canonical.supports_variable_length_selection();
+ if sanitized.is_empty() && canonical.is_checkable() {
let runtime = unsafe { &mut *runtime_ptr };
let _ = runtime.set_input_value_with_dirty(handle, "", false);
} else if sanitized != raw {
@@ -117,7 +115,7 @@ fn input_type_setter_on_object<'s>(
}
}
- if canonical == "radio" {
+ if canonical == InputType::Radio {
let checked = unsafe { &*runtime_ptr }
.dom_host()
.node(handle)
@@ -175,9 +173,9 @@ pub(in crate::native_bridge) fn input_value_setter_function<'s>(
.dom_host()
.node(handle)
.and_then(Node::as_element)
- .map(|element| canonical_input_type(&element.input_type()).to_owned())
- .unwrap_or_else(|| "text".to_owned());
- if matches!(input_type.as_str(), "checkbox" | "radio") {
+ .map(Element::input_type)
+ .unwrap_or_default();
+ if input_type.is_checkable() {
// Checkbox and radio inputs use the HTML default/on value mode. Their
// IDL setter reflects the content attribute instead of creating a
// dirty, non-attribute value.
@@ -185,7 +183,7 @@ pub(in crate::native_bridge) fn input_value_setter_function<'s>(
rv.set_undefined();
return;
}
- if input_type == "file" && !next_value.is_empty() {
+ if input_type == InputType::File && !next_value.is_empty() {
throw_dom_exception(
scope,
"InvalidStateError",
@@ -214,19 +212,12 @@ pub(in crate::native_bridge) fn input_value_setter_function<'s>(
rv.set_undefined();
}
-fn input_type_supports_variable_length_selection(input_type: &str) -> bool {
- matches!(
- canonical_input_type(input_type),
- "text" | "search" | "tel" | "url" | "password"
- )
-}
-
fn reset_input_selection_to_end(runtime: &mut JsContextHost, handle: DomHandle) {
let Some(end) = runtime
.dom_host()
.node(handle)
.and_then(Node::as_element)
- .filter(|element| input_type_supports_variable_length_selection(&element.input_type()))
+ .filter(|element| element.input_type().supports_variable_length_selection())
.map(|element| element.input_value().chars().count() as u32)
else {
return;
@@ -305,9 +296,8 @@ fn input_value_as_number_setter_on_object<'s>(
.node(handle)
.and_then(Node::as_element)
.filter(|element| element.is_html_input())
- .map(|element| element.input_type().to_owned());
- let Some(input_type) =
- input_type.filter(|input_type| input_type_supports_value_as_number(input_type))
+ .map(Element::input_type);
+ let Some(input_type) = input_type.filter(|input_type| input_type.supports_value_as_number())
else {
throw_dom_exception(
scope,
@@ -320,7 +310,7 @@ fn input_value_as_number_setter_on_object<'s>(
let next_value = if number.is_nan() {
String::new()
} else {
- moli_dom::forms::input_number_to_value_string(&input_type, number).unwrap_or_default()
+ moli_dom::forms::input_number_to_value_string(input_type, number).unwrap_or_default()
};
let _ = runtime.set_input_value(handle, &next_value);
}
@@ -354,7 +344,7 @@ fn input_value_as_date_getter_from_object<'s>(
return;
};
let Some(millis) =
- input_value_as_date_milliseconds(&element.input_type(), &element.input_value())
+ input_value_as_date_milliseconds(element.input_type(), &element.input_value())
else {
rv.set_null();
return;
@@ -390,8 +380,8 @@ fn input_value_as_date_setter_on_object<'s>(
.and_then(Node::as_element)
.filter(|element| element.is_html_input())
.map(Element::input_type)
- .unwrap_or_else(|| "text".to_owned());
- if !input_type_supports_value_as_date(&input_type) {
+ .unwrap_or_default();
+ if !input_type.supports_value_as_date() {
throw_dom_exception(
scope,
"InvalidStateError",
@@ -411,7 +401,7 @@ fn input_value_as_date_setter_on_object<'s>(
);
return;
};
- input_date_value_from_milliseconds(&input_type, date.value_of()).unwrap_or_default()
+ input_date_value_from_milliseconds(input_type, date.value_of()).unwrap_or_default()
};
let _ = unsafe { &mut *runtime_ptr }.set_input_value(handle, &next_value);
}
@@ -476,7 +466,7 @@ fn input_step_by(
let input_value = element.input_value();
step_input_value(
InputStepState {
- input_type: &input_type,
+ input_type,
value: &input_value,
min: element.attribute("min"),
max: element.attribute("max"),
@@ -520,35 +510,28 @@ fn input_step_by(
}
fn input_value_as_number(element: &Element) -> Option<f64> {
- moli_dom::forms::parse_input_numeric_value(&element.input_type(), &element.input_value())
-}
-
-fn input_type_supports_value_as_date(input_type: &str) -> bool {
- matches!(
- canonical_input_type(input_type),
- "date" | "month" | "week" | "time"
- )
+ moli_dom::forms::parse_input_numeric_value(element.input_type(), &element.input_value())
}
-fn input_value_as_date_milliseconds(input_type: &str, value: &str) -> Option<f64> {
- match canonical_input_type(input_type) {
- "date" => date_input_milliseconds(value),
- "month" => month_input_milliseconds(value),
- "week" => week_input_milliseconds(value),
- "time" => time_input_milliseconds(value),
+fn input_value_as_date_milliseconds(input_type: InputType, value: &str) -> Option<f64> {
+ match input_type {
+ InputType::Date => date_input_milliseconds(value),
+ InputType::Month => month_input_milliseconds(value),
+ InputType::Week => week_input_milliseconds(value),
+ InputType::Time => time_input_milliseconds(value),
_ => None,
}
}
-fn input_date_value_from_milliseconds(input_type: &str, value: f64) -> Option<String> {
+fn input_date_value_from_milliseconds(input_type: InputType, value: f64) -> Option<String> {
if !value.is_finite() {
return Some(String::new());
}
- match canonical_input_type(input_type) {
- "date" => date_input_value_from_milliseconds(value),
- "month" => month_input_value_from_milliseconds(value),
- "week" => week_input_value_from_milliseconds(value),
- "time" => time_input_value_from_milliseconds(value),
+ match input_type {
+ InputType::Date => date_input_value_from_milliseconds(value),
+ InputType::Month => month_input_value_from_milliseconds(value),
+ InputType::Week => week_input_value_from_milliseconds(value),
+ InputType::Time => time_input_value_from_milliseconds(value),
_ => None,
}
}
@@ -557,15 +540,6 @@ fn input_date_value_from_milliseconds(input_type: &str, value: f64) -> Option<St
mod tests {
use super::*;
- #[test]
- fn canonical_input_type_uses_html_input_type_tokens() {
- assert_eq!(canonical_input_type("text"), "text");
- assert_eq!(canonical_input_type("EMAIL"), "email");
- assert_eq!(canonical_input_type(" datetime-local "), "datetime-local");
- assert_eq!(canonical_input_type("week"), "week");
- assert_eq!(canonical_input_type("unknown"), "text");
- }
-
#[test]
fn webidl_long_conversion_handles_special_and_wrapping_values() {
assert_eq!(webidl_long_from_number(f64::NAN), 0);
diff --git a/moli-renderer-v8/src/native_bridge/element/forms/labels.rs b/moli-renderer-v8/src/native_bridge/element/forms/labels.rs
index 87ef6006c..2f9af7db4 100644
--- a/moli-renderer-v8/src/native_bridge/element/forms/labels.rs
+++ b/moli-renderer-v8/src/native_bridge/element/forms/labels.rs
@@ -7,7 +7,7 @@ fn is_labelable_element(element: &Element) -> bool {
}
match element.local_name() {
"button" | "meter" | "output" | "progress" | "select" | "textarea" => true,
- "input" => element.input_type() != "hidden",
+ "input" => element.input_type() != InputType::Hidden,
_ => false,
}
}
@@ -28,7 +28,7 @@ fn is_label_interactive_content(element: &Element) -> bool {
"a" | "area" => element.has_attribute("href"),
"audio" | "video" => element.has_attribute("controls"),
"img" => element.has_attribute("usemap"),
- "input" => element.input_type() != "hidden",
+ "input" => element.input_type() != InputType::Hidden,
"label" => true,
_ => false,
}
diff --git a/moli-renderer-v8/src/native_bridge/element/forms/owner.rs b/moli-renderer-v8/src/native_bridge/element/forms/owner.rs
index 51dfe04ba..0b7b2f626 100644
--- a/moli-renderer-v8/src/native_bridge/element/forms/owner.rs
+++ b/moli-renderer-v8/src/native_bridge/element/forms/owner.rs
@@ -115,7 +115,7 @@ pub(crate) fn is_valid_submit_button(runtime: &JsContextHost, handle: DomHandle)
.and_then(Node::as_element)
.is_some_and(|element| {
if element.is_html_input() {
- matches!(element.input_type().as_str(), "submit" | "image")
+ element.input_type().is_submit_button()
} else if element.is_html_element("button") {
!matches!(element.attribute("type"), Some("reset" | "button"))
} else {
diff --git a/moli-renderer-v8/src/native_bridge/element/forms/submission.rs b/moli-renderer-v8/src/native_bridge/element/forms/submission.rs
index 88516c1a3..f2c18e359 100644
--- a/moli-renderer-v8/src/native_bridge/element/forms/submission.rs
+++ b/moli-renderer-v8/src/native_bridge/element/forms/submission.rs
@@ -629,7 +629,7 @@ fn dialog_submission_result(
return Some(String::new());
};
let element = runtime.dom_host().node(submitter)?.as_element()?;
- if element.is_html_input() && element.input_type() == "image" {
+ if element.is_html_input() && element.input_type() == InputType::Image {
let (x, y) = runtime
.active_image_submitter_coordinate(submitter)
.unwrap_or((0, 0));
@@ -1044,7 +1044,7 @@ fn build_form_reset_plan(runtime: &JsContextHost, handle: DomHandle) -> Option<F
match element.local_name() {
"input" => {
let input_type = element.input_type();
- if matches!(input_type.as_str(), "checkbox" | "radio") {
+ if input_type.is_checkable() {
Some(FormResetPlan::Checked {
handle,
checked: element.attribute("checked").is_some(),
diff --git a/moli-renderer-v8/src/native_bridge/element/forms/text_control/value.rs b/moli-renderer-v8/src/native_bridge/element/forms/text_control/value.rs
index 41326acc3..3cbe1b5cd 100644
--- a/moli-renderer-v8/src/native_bridge/element/forms/text_control/value.rs
+++ b/moli-renderer-v8/src/native_bridge/element/forms/text_control/value.rs
@@ -52,8 +52,14 @@ pub(crate) fn is_text_control(runtime: &JsContextHost, handle: DomHandle) -> boo
element.is_html_textarea()
|| (element.is_html_input()
&& !matches!(
- element.input_type().as_str(),
- "hidden" | "checkbox" | "radio" | "button" | "submit" | "reset" | "image"
+ element.input_type(),
+ InputType::Hidden
+ | InputType::Checkbox
+ | InputType::Radio
+ | InputType::Button
+ | InputType::Submit
+ | InputType::Reset
+ | InputType::Image
))
})
}
@@ -69,10 +75,7 @@ pub(super) fn supports_variable_length_selection(
.is_some_and(|element| {
element.is_html_textarea()
|| (element.is_html_input()
- && matches!(
- element.input_type().as_str(),
- "text" | "search" | "tel" | "url" | "password"
- ))
+ && element.input_type().supports_variable_length_selection())
})
}
diff --git a/moli-renderer-v8/src/native_bridge/element/forms/validation.rs b/moli-renderer-v8/src/native_bridge/element/forms/validation.rs
index 75dc33b25..5e7db795b 100644
--- a/moli-renderer-v8/src/native_bridge/element/forms/validation.rs
+++ b/moli-renderer-v8/src/native_bridge/element/forms/validation.rs
@@ -5,10 +5,8 @@ use crate::webidl;
use moli_dom::forms::{
FormControlValidity, form_control_type_supports_intrinsic_validation, input_range_overflow,
input_range_underflow, input_step as form_input_step, input_step_base as form_input_step_base,
- input_type_supports_pattern, input_type_supports_text_length_validation,
- input_type_suppresses_immutable_required, input_type_value_mismatch,
- normalize_custom_validation_message, number_aligns_to_step, number_step_mismatch,
- parse_input_numeric_value as parse_input_numeric_value_for_type,
+ input_type_value_mismatch, normalize_custom_validation_message, number_aligns_to_step,
+ number_step_mismatch, parse_input_numeric_value as parse_input_numeric_value_for_type,
parse_non_negative_integer_prefix,
text_control_suffers_too_long as form_text_control_suffers_too_long,
text_control_suffers_too_short as form_text_control_suffers_too_short,
@@ -386,7 +384,7 @@ fn control_suffers_bad_input(
element: &Element,
) -> bool {
element.is_html_input()
- && element.input_type() == "number"
+ && element.input_type() == InputType::Number
&& element_type_supports_intrinsic_validation(element)
&& element.input_bad_input()
}
@@ -410,7 +408,7 @@ fn control_suffers_required_value_missing(
return false;
}
- if element.is_html_input() && element.input_type() == "radio" {
+ if element.is_html_input() && element.input_type() == InputType::Radio {
return radio_group_suffers_required_value_missing(runtime, handle);
}
@@ -463,7 +461,7 @@ fn element_type_supports_intrinsic_validation(element: &Element) -> bool {
let input_type = element.is_html_input().then(|| element.input_type());
form_control_type_supports_intrinsic_validation(
element.local_name(),
- input_type.as_deref(),
+ input_type,
element
.is_html_button()
.then(|| element.attribute("type").unwrap_or("submit")),
@@ -486,8 +484,7 @@ fn required_value_missing_is_suppressed_for_immutable_control(
element.has_attribute("readonly") || form_control_is_effectively_disabled(runtime, handle);
immutable
&& (element.is_html_textarea()
- || (element.is_html_input()
- && input_type_suppresses_immutable_required(&element.input_type())))
+ || (element.is_html_input() && element.input_type().supports_readonly()))
}
fn control_has_datalist_ancestor(runtime: &JsContextHost, handle: DomHandle) -> bool {
@@ -511,9 +508,9 @@ fn input_suffers_required_value_missing(
handle: DomHandle,
element: &Element,
) -> bool {
- match element.input_type().as_str() {
- "checkbox" => !element.checked(),
- "radio" => {
+ match element.input_type() {
+ InputType::Checkbox => !element.checked(),
+ InputType::Radio => {
!element.attribute("name").unwrap_or_default().is_empty()
&& !radio_group_has_checked_control(runtime, handle)
}
@@ -534,7 +531,7 @@ fn control_suffers_type_mismatch(
return false;
}
input_type_value_mismatch(
- &element.input_type(),
+ element.input_type(),
&value,
element.has_attribute("multiple"),
)
@@ -548,7 +545,7 @@ fn control_suffers_pattern_mismatch(
) -> bool {
if !element.is_html_input()
|| !element_type_supports_intrinsic_validation(element)
- || !input_type_supports_pattern(&element.input_type())
+ || !element.input_type().supports_pattern()
{
return false;
}
@@ -559,7 +556,7 @@ fn control_suffers_pattern_mismatch(
if value.is_empty() {
return false;
}
- if element.input_type() == "email" && element.has_attribute("multiple") {
+ if element.input_type() == InputType::Email && element.has_attribute("multiple") {
return v8_pattern_is_usable(scope, pattern).is_some_and(|()| {
value
.split(',')
@@ -648,8 +645,7 @@ fn text_control_length_validation_applies(
) -> bool {
element_is_constraint_validation_candidate(runtime, handle, element)
&& (element.is_html_textarea()
- || (element.is_html_input()
- && input_type_supports_text_length_validation(&element.input_type())))
+ || (element.is_html_input() && element.input_type().supports_text_length_validation()))
}
fn control_suffers_range_underflow(
@@ -661,7 +657,7 @@ fn control_suffers_range_underflow(
return false;
};
input_range_underflow(
- &element.input_type(),
+ element.input_type(),
value,
element.attribute("min"),
element.attribute("max"),
@@ -677,7 +673,7 @@ fn control_suffers_range_overflow(
return false;
};
input_range_overflow(
- &element.input_type(),
+ element.input_type(),
value,
element.attribute("min"),
element.attribute("max"),
@@ -703,7 +699,7 @@ fn control_suffers_step_mismatch(
}
fn control_suffers_number_step_mismatch(element: &Element) -> Option<bool> {
- if !element.is_html_input() || element.input_type() != "number" {
+ if !element.is_html_input() || element.input_type() != InputType::Number {
return None;
}
number_step_mismatch(
@@ -729,16 +725,16 @@ pub(in crate::native_bridge::element::forms) fn parse_input_numeric_value(
element: &Element,
value: &str,
) -> Option<f64> {
- parse_input_numeric_value_for_type(&element.input_type(), value)
+ parse_input_numeric_value_for_type(element.input_type(), value)
}
pub(in crate::native_bridge::element::forms) fn input_step(element: &Element) -> Option<f64> {
- form_input_step(&element.input_type(), element.attribute("step"))
+ form_input_step(element.input_type(), element.attribute("step"))
}
pub(in crate::native_bridge::element::forms) fn input_step_base(element: &Element) -> f64 {
form_input_step_base(
- &element.input_type(),
+ element.input_type(),
element.attribute("min"),
element.attribute("value"),
)
diff --git a/moli-renderer-v8/src/native_bridge/element/global_attributes.rs b/moli-renderer-v8/src/native_bridge/element/global_attributes.rs
index 24ce9c548..2a32f99c3 100644
--- a/moli-renderer-v8/src/native_bridge/element/global_attributes.rs
+++ b/moli-renderer-v8/src/native_bridge/element/global_attributes.rs
@@ -1,5 +1,5 @@
use crate::document_runtime::DomHandle;
-use crate::dom::native::Node;
+use crate::dom::{forms::InputType, native::Node};
use crate::util::v8_string;
use crate::webidl;
@@ -1923,7 +1923,10 @@ pub(in crate::native_bridge) fn node_autocorrect_getter_function<'s>(
};
if element.is_html_input()
- && matches!(element.input_type().as_str(), "email" | "password" | "url")
+ && matches!(
+ element.input_type(),
+ InputType::Email | InputType::Password | InputType::Url
+ )
{
rv.set_bool(false);
return;
diff --git a/moli-renderer-v8/src/runtime/page_generated_dom.rs b/moli-renderer-v8/src/runtime/page_generated_dom.rs
index 88ed20027..a4acf4ceb 100644
--- a/moli-renderer-v8/src/runtime/page_generated_dom.rs
+++ b/moli-renderer-v8/src/runtime/page_generated_dom.rs
@@ -1,5 +1,5 @@
use crate::dom::native::{DomHost, NodeType};
-use moli_dom::forms::{MeterElementValues, MeterGaugeRegion};
+use moli_dom::forms::{InputType, MeterElementValues, MeterGaugeRegion};
use moli_page_types::{
DocumentNodeAttributeSnapshot, DocumentNodeInspectorIdentity, DocumentNodeSnapshot,
};
@@ -102,17 +102,17 @@ fn full_user_agent_shadow_root_snapshot(
&& dom_host
.input_datalist_handle(originating_element.node_id)
.is_some();
- if element.is_html_input() && element.input_type() == "number" {
+ if element.is_html_input() && element.input_type() == InputType::Number {
return Some(number_input_shadow_root_snapshot(
element.input_value(),
has_datalist,
originating_element,
));
}
- if element.is_html_input() && element.input_type() == "range" {
+ if element.is_html_input() && element.input_type() == InputType::Range {
return Some(range_input_shadow_root_snapshot(originating_element));
}
- if element.is_html_input() && element.input_type() == "date" {
+ if element.is_html_input() && element.input_type() == InputType::Date {
return Some(date_input_shadow_root_snapshot(
element.input_value(),
element.attribute("min"),
@@ -120,7 +120,7 @@ fn full_user_agent_shadow_root_snapshot(
originating_element,
));
}
- if element.is_html_input() && element.input_type() == "search" {
+ if element.is_html_input() && element.input_type() == InputType::Search {
return Some(search_input_shadow_root_snapshot(
element.input_value(),
element.input_value_dirty(),
@@ -157,8 +157,12 @@ fn full_user_agent_shadow_root_snapshot(
}
let (tree_kind, value) = if element.is_html_input()
&& matches!(
- element.input_type().as_str(),
- "text" | "tel" | "url" | "email" | "password"
+ element.input_type(),
+ InputType::Text
+ | InputType::Tel
+ | InputType::Url
+ | InputType::Email
+ | InputType::Password
) {
(INPUT_TEXT_CONTROL_TREE_KIND, element.input_value())
} else if element.is_html_textarea() {
diff --git a/moli-renderer-v8/src/script_vm/autofill.rs b/moli-renderer-v8/src/script_vm/autofill.rs
index a3af1bc11..2251ab63f 100644
--- a/moli-renderer-v8/src/script_vm/autofill.rs
+++ b/moli-renderer-v8/src/script_vm/autofill.rs
@@ -3,7 +3,7 @@ use anyhow::Result;
use super::ScriptVm;
use crate::{
document_runtime::DomHandle,
- dom::native::Node,
+ dom::{forms::InputType, native::Node},
native_bridge::element::{
autocomplete_field_name, autofill_related_form_control_elements, construct_simple_event,
dispatch_public_event, form_control_is_effectively_disabled,
@@ -189,7 +189,7 @@ fn fill_credit_card_control(
if form_control_is_effectively_disabled(runtime, handle)
|| element.has_attribute("readonly")
|| (element.is_html_input()
- && matches!(element.input_type().as_str(), "file" | "hidden"))
+ && matches!(element.input_type(), InputType::File | InputType::Hidden))
{
return None;
}
diff --git a/moli-renderer-v8/src/script_vm/input_dispatch.rs b/moli-renderer-v8/src/script_vm/input_dispatch.rs
index d638d12b3..8ffb21b5b 100644
--- a/moli-renderer-v8/src/script_vm/input_dispatch.rs
+++ b/moli-renderer-v8/src/script_vm/input_dispatch.rs
@@ -11,7 +11,10 @@ use super::inspector::{
};
use super::{ActiveDragSession, ActiveScrollbarDrag, ActiveTouchPoint, ScriptVm};
use crate::document_runtime::DomHandle;
-use crate::dom::native::{Node, SelectedFile};
+use crate::dom::{
+ forms::InputType,
+ native::{Node, SelectedFile},
+};
use crate::native_bridge::element::{
TouchEventPoint, activate_handle_via_click,
activate_handle_via_click_with_detail_and_modifiers, cache_input_files_from_selected_files,
@@ -1723,7 +1726,7 @@ impl ScriptVm {
let Some(element) = runtime.dom_host().node(handle).and_then(Node::as_element) else {
return Ok(false);
};
- if !element.is_html_input() || element.input_type() != "file" {
+ if !element.is_html_input() || element.input_type() != InputType::File {
return Ok(false);
}
let multiple = element.attribute("multiple").is_some();
diff --git a/moli-renderer-v8/src/script_vm/inspector/input_state.rs b/moli-renderer-v8/src/script_vm/inspector/input_state.rs
index c76b00ad4..9f16232bd 100644
--- a/moli-renderer-v8/src/script_vm/inspector/input_state.rs
+++ b/moli-renderer-v8/src/script_vm/inspector/input_state.rs
@@ -1,4 +1,8 @@
-use crate::{document_runtime::DomHandle, dom::native::Node, native_bridge::JsContextHost};
+use crate::{
+ document_runtime::DomHandle,
+ dom::{forms::InputType, native::Node},
+ native_bridge::JsContextHost,
+};
#[derive(Clone, Copy)]
pub(in crate::script_vm) struct KeyTargetInfo {
@@ -27,18 +31,17 @@ pub(in crate::script_vm) fn key_target_info(
};
};
let local_name = element.local_name();
- let input_type = if element.is_html_input() {
- element.input_type()
- } else {
- String::new()
- };
- let is_checkbox = element.is_html_input() && input_type == "checkbox";
- let is_radio = element.is_html_input() && input_type == "radio";
+ let input_type = element.input_type();
+ let is_checkbox = element.is_html_input() && input_type == InputType::Checkbox;
+ let is_radio = element.is_html_input() && input_type == InputType::Radio;
let is_textarea = element.is_html_textarea();
let is_select = element.is_html_select();
let is_button_like = local_name == "button"
|| (element.is_html_input()
- && matches!(input_type.as_str(), "button" | "submit" | "reset"));
+ && matches!(
+ input_type,
+ InputType::Button | InputType::Submit | InputType::Reset
+ ));
let is_anchor_like = local_name == "a"
&& element
.attribute("href")
@@ -46,8 +49,12 @@ pub(in crate::script_vm) fn key_target_info(
let is_text_control = is_textarea
|| (element.is_html_input()
&& !matches!(
- input_type.as_str(),
- "checkbox" | "radio" | "button" | "submit" | "reset"
+ input_type,
+ InputType::Checkbox
+ | InputType::Radio
+ | InputType::Button
+ | InputType::Submit
+ | InputType::Reset
));
KeyTargetInfo {
is_checkbox,
@@ -90,7 +97,7 @@ pub(in crate::script_vm) fn radio_group_members(
.and_then(Node::as_element)
.is_some_and(|candidate_element| {
candidate_element.is_html_input()
- && candidate_element.input_type() == "radio"
+ && candidate_element.input_type() == InputType::Radio
&& candidate_element.attribute("name") == Some(name)
&& !candidate_element.has_attribute("disabled")
&& runtime
diff --git a/moli-renderer-v8/src/script_vm/tests/dom_xhr/forms.rs b/moli-renderer-v8/src/script_vm/tests/dom_xhr/forms.rs
index 68d46a61d..3ec889f4c 100644
--- a/moli-renderer-v8/src/script_vm/tests/dom_xhr/forms.rs
+++ b/moli-renderer-v8/src/script_vm/tests/dom_xhr/forms.rs
@@ -30,6 +30,34 @@ fn object_set_custom_validity_updates_validity_state() {
assert_eq!(result, "false:true|true:false|false:true");
}
+#[test]
+fn input_type_enumerated_attribute_preserves_raw_value_and_exposes_canonical_state() {
+ let mut vm = new_storage_test_vm("https://input-type-enumerated-attribute.test/");
+
+ let result = vm
+ .eval(
+ r#"
+(() => {
+ const input = document.createElement('input');
+ const results = [];
+ for (const value of ['EMAIL', ' datetime-local ', 'unknown', 'datetime-local']) {
+ input.type = value;
+ results.push(`${input.type}/${input.getAttribute('type')}`);
+ }
+ input.removeAttribute('type');
+ results.push(`${input.type}/${input.getAttribute('type')}`);
+ return results.join('|');
+})()
+"#,
+ )
+ .expect("input type enumerated attribute should evaluate");
+
+ assert_eq!(
+ result,
+ "email/EMAIL|text/ datetime-local |text/unknown|datetime-local/datetime-local|text/null"
+ );
+}
+
#[test]
fn readonly_controls_match_validity_pseudo_without_will_validate() {
let mut vm = new_storage_test_vm("https://readonly-validity-pseudo.test/");
@@ -4410,7 +4438,7 @@ picker.click();
.and_then(crate::dom::native::Node::as_element)
.expect("the detached source input should retain its native node identity");
assert!(retained_picker.is_html_input());
- assert_eq!(retained_picker.input_type(), expected_type);
+ assert_eq!(retained_picker.input_type().as_ref(), expected_type);
assert_eq!(
retained_picker.attribute("multiple").is_some(),
expected_multiple
diff --git a/moli-selector/src/stylo/query/pseudo.rs b/moli-selector/src/stylo/query/pseudo.rs
index 32a99d52c..a63649686 100644
--- a/moli-selector/src/stylo/query/pseudo.rs
+++ b/moli-selector/src/stylo/query/pseudo.rs
@@ -5,7 +5,7 @@ use crate::{
dom::{
NodeId,
forms::{
- form_control_type_supports_intrinsic_validation, input_range_overflow,
+ InputType, form_control_type_supports_intrinsic_validation, input_range_overflow,
input_range_underflow, parse_input_numeric_value, parse_non_negative_integer_prefix,
},
native::{DomHost, Element, Node},
@@ -177,15 +177,16 @@ impl<'a> QueryElement<'a> {
}
if self.matches_required_pseudo() {
let ty = self.input_type();
- if matches!(ty.as_str(), "checkbox" | "radio") {
+ if ty.is_checkable() {
return !self.element().checked();
}
return self.element().input_value().is_empty();
}
if self.element().local_name() == "input"
- && self.input_type() == "number"
+ && self.input_type() == InputType::Number
&& !self.element().input_value().is_empty()
- && parse_input_numeric_value("number", &self.element().input_value()).is_none()
+ && parse_input_numeric_value(InputType::Number, &self.element().input_value())
+ .is_none()
{
return true;
}
@@ -195,7 +196,7 @@ impl<'a> QueryElement<'a> {
}
}
- pub(super) fn input_type(self) -> String {
+ pub(super) fn input_type(self) -> InputType {
self.element().input_type()
}
@@ -328,10 +329,7 @@ impl<'a> QueryElement<'a> {
pub(super) fn can_match_required_pseudo(self) -> bool {
match self.element().local_name() {
"select" | "textarea" => true,
- "input" => !matches!(
- self.input_type().as_str(),
- "hidden" | "button" | "submit" | "reset" | "image"
- ),
+ "input" => self.input_type().supports_required(),
_ => false,
}
}
@@ -358,21 +356,7 @@ impl<'a> QueryElement<'a> {
match self.element().local_name() {
"textarea" => !self.element().has_attribute("readonly"),
"input" => {
- matches!(
- self.input_type().as_str(),
- "text"
- | "search"
- | "url"
- | "tel"
- | "email"
- | "password"
- | "date"
- | "month"
- | "week"
- | "time"
- | "datetime-local"
- | "number"
- ) && !self.element().has_attribute("readonly")
+ self.input_type().supports_readonly() && !self.element().has_attribute("readonly")
}
_ => self.is_editable(),
}
@@ -404,10 +388,7 @@ impl<'a> QueryElement<'a> {
}
match self.element().local_name() {
"textarea" => true,
- "input" => matches!(
- self.input_type().as_str(),
- "text" | "search" | "url" | "tel" | "email" | "password"
- ),
+ "input" => self.input_type().supports_placeholder(),
_ => false,
}
}
@@ -415,10 +396,7 @@ impl<'a> QueryElement<'a> {
pub(super) fn matches_checked_pseudo(self) -> bool {
match self.element().local_name() {
"option" => self.element().selected(),
- "input" => {
- matches!(self.input_type().as_str(), "checkbox" | "radio")
- && self.element().checked()
- }
+ "input" => self.input_type().is_checkable() && self.element().checked(),
_ => false,
}
}
@@ -426,8 +404,10 @@ impl<'a> QueryElement<'a> {
pub(super) fn matches_indeterminate_pseudo(self) -> bool {
match self.element().local_name() {
"progress" => !self.element().has_attribute("value"),
- "input" if self.input_type() == "checkbox" => self.element().indeterminate(),
- "input" if self.input_type() == "radio" => !self.radio_group_has_checked_input(),
+ "input" if self.input_type() == InputType::Checkbox => self.element().indeterminate(),
+ "input" if self.input_type() == InputType::Radio => {
+ !self.radio_group_has_checked_input()
+ }
_ => false,
}
}
@@ -442,7 +422,7 @@ impl<'a> QueryElement<'a> {
stack.extend(self.host.child_handles_reversed(handle));
if let Some(element) = self.host.node(handle).and_then(Node::as_element)
&& element.local_name() == "input"
- && element.input_type() == "radio"
+ && element.input_type() == InputType::Radio
&& element.attribute("name").unwrap_or_default() == name
&& element.checked()
{
@@ -458,7 +438,9 @@ impl<'a> QueryElement<'a> {
}
form_control_type_supports_intrinsic_validation(
self.element().local_name(),
- self.element().attribute("type"),
+ self.element()
+ .is_html_input()
+ .then(|| self.element().input_type()),
self.element().attribute("type"),
)
}
@@ -483,19 +465,19 @@ impl<'a> QueryElement<'a> {
return None;
}
let input_type = self.input_type();
- let value = parse_input_numeric_value(&input_type, &self.element().input_value())?;
- if input_type != "range" {
+ let value = parse_input_numeric_value(input_type, &self.element().input_value())?;
+ if input_type != InputType::Range {
return Some(value);
}
let min = self
.element()
.attribute("min")
- .and_then(|value| parse_input_numeric_value("range", value))
+ .and_then(|value| parse_input_numeric_value(InputType::Range, value))
.unwrap_or(0.0);
let max = self
.element()
.attribute("max")
- .and_then(|value| parse_input_numeric_value("range", value))
+ .and_then(|value| parse_input_numeric_value(InputType::Range, value))
.unwrap_or(100.0);
Some(if min <= max {
value.clamp(min, max)
@@ -508,19 +490,17 @@ impl<'a> QueryElement<'a> {
if self.element().local_name() != "input" {
return false;
}
- matches!(
- self.input_type().as_str(),
- "date" | "time" | "datetime-local" | "month" | "week" | "number" | "range"
- ) && (self.input_type() == "range"
- || self.element().attribute("min").is_some()
- || self.element().attribute("max").is_some())
+ self.input_type().supports_value_as_number()
+ && (self.input_type() == InputType::Range
+ || self.element().attribute("min").is_some()
+ || self.element().attribute("max").is_some())
}
pub(super) fn matches_range_underflow_pseudo(self) -> bool {
self.has_range_limitations()
&& self.numeric_input_value().is_some_and(|value| {
input_range_underflow(
- &self.input_type(),
+ self.input_type(),
value,
self.element().attribute("min"),
self.element().attribute("max"),
@@ -532,7 +512,7 @@ impl<'a> QueryElement<'a> {
self.has_range_limitations()
&& self.numeric_input_value().is_some_and(|value| {
input_range_overflow(
- &self.input_type(),
+ self.input_type(),
value,
self.element().attribute("min"),
self.element().attribute("max"),
@@ -554,10 +534,8 @@ impl<'a> QueryElement<'a> {
pub(super) fn matches_default_pseudo(self) -> bool {
match self.element().local_name() {
"option" => self.element().selected(),
- "input" if matches!(self.input_type().as_str(), "checkbox" | "radio") => {
- self.element().has_attribute("checked")
- }
- "input" if matches!(self.input_type().as_str(), "submit" | "image") => {
+ "input" if self.input_type().is_checkable() => self.element().has_attribute("checked"),
+ "input" if self.input_type().is_submit_button() => {
self.is_first_default_submit_button()
}
"button" => {
@@ -627,7 +605,7 @@ pub(crate) fn html_directionality(host: &DomHost, handle: NodeId) -> CssDirectio
{
return auto_direction_for_element(host, handle).unwrap_or(CssDirection::Ltr);
}
- if element.is_html_input() && element.input_type() == "tel" {
+ if element.is_html_input() && element.input_type() == InputType::Tel {
return CssDirection::Ltr;
}
}
@@ -681,27 +659,13 @@ fn descendant_is_directionally_isolated_for_auto(element: &Element) -> bool {
}
fn input_auto_direction(element: &Element) -> Option<CssDirection> {
- input_type_uses_value_for_auto_direction(&element.input_type())
+ element
+ .input_type()
+ .uses_value_for_auto_direction()
.then(|| first_strong_text_direction(&element.input_value()))
.flatten()
}
-fn input_type_uses_value_for_auto_direction(input_type: &str) -> bool {
- matches!(
- input_type,
- "hidden"
- | "text"
- | "search"
- | "tel"
- | "url"
- | "email"
- | "password"
- | "submit"
- | "reset"
- | "button"
- )
-}
-
fn default_submit_button_element(element: &Element) -> bool {
match element.local_name() {
"button" => {
@@ -712,7 +676,7 @@ fn default_submit_button_element(element: &Element) -> bool {
.to_ascii_lowercase();
!matches!(ty.as_str(), "button" | "reset")
}
- "input" => matches!(element.input_type().as_str(), "submit" | "image"),
+ "input" => element.input_type().is_submit_button(),
_ => false,
}
}