Skip to main content

script/dom/html/input_element/
input_type.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4use embedder_traits::InputMethodType;
5use js::context::JSContext;
6use script_bindings::codegen::GenericBindings::HTMLInputElementBinding::HTMLInputElementMethods;
7use script_bindings::domstring::DOMString;
8use script_bindings::root::DomRoot;
9use stylo_atoms::Atom;
10use time::OffsetDateTime;
11
12use crate::dom::element::AttributeMutation;
13use crate::dom::element::attributes::storage::AttrRef;
14use crate::dom::event::Event;
15use crate::dom::eventtarget::EventTarget;
16use crate::dom::filelist::FileList;
17use crate::dom::htmlformelement::HTMLFormElement;
18use crate::dom::input_element::button_input_type::ButtonInputType;
19use crate::dom::input_element::checkbox_input_type::CheckboxInputType;
20use crate::dom::input_element::color_input_type::ColorInputType;
21use crate::dom::input_element::date_input_type::DateInputType;
22use crate::dom::input_element::datetime_local_input_type::DatetimeLocalInputType;
23use crate::dom::input_element::email_input_type::EmailInputType;
24use crate::dom::input_element::file_input_type::FileInputType;
25use crate::dom::input_element::hidden_input_type::HiddenInputType;
26use crate::dom::input_element::image_input_type::ImageInputType;
27use crate::dom::input_element::month_input_type::MonthInputType;
28use crate::dom::input_element::number_input_type::NumberInputType;
29use crate::dom::input_element::password_input_type::PasswordInputType;
30use crate::dom::input_element::radio_input_type::RadioInputType;
31use crate::dom::input_element::range_input_type::RangeInputType;
32use crate::dom::input_element::reset_input_type::ResetInputType;
33use crate::dom::input_element::search_input_type::SearchInputType;
34use crate::dom::input_element::submit_input_type::SubmitInputType;
35use crate::dom::input_element::tel_input_type::TelInputType;
36use crate::dom::input_element::text_input_type::TextInputType;
37use crate::dom::input_element::time_input_type::TimeInputType;
38use crate::dom::input_element::url_input_type::UrlInputType;
39use crate::dom::input_element::week_input_type::WeekInputType;
40use crate::dom::input_element::{HTMLInputElement, InputActivationState, ValueMode};
41use crate::dom::node::{BindContext, UnbindContext};
42
43/// <https://html.spec.whatwg.org/multipage/#attr-input-type>
44#[derive(JSTraceable, MallocSizeOf, PartialEq)]
45#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
46pub(crate) enum InputType {
47    /// <https://html.spec.whatwg.org/multipage/#button-state-(type=button)>
48    Button(ButtonInputType),
49
50    /// <https://html.spec.whatwg.org/multipage/#checkbox-state-(type=checkbox)>
51    Checkbox(CheckboxInputType),
52
53    /// <https://html.spec.whatwg.org/multipage/#color-state-(type=color)>
54    Color(ColorInputType),
55
56    /// <https://html.spec.whatwg.org/multipage/#date-state-(type=date)>
57    Date(DateInputType),
58
59    /// <https://html.spec.whatwg.org/multipage/#local-date-and-time-state-(type=datetime-local)>
60    DatetimeLocal(DatetimeLocalInputType),
61
62    /// <https://html.spec.whatwg.org/multipage/#email-state-(type=email)>
63    Email(EmailInputType),
64
65    /// <https://html.spec.whatwg.org/multipage/#file-upload-state-(type=file)>
66    File(FileInputType),
67
68    /// <https://html.spec.whatwg.org/multipage/#hidden-state-(type=hidden)>
69    Hidden(HiddenInputType),
70
71    /// <https://html.spec.whatwg.org/multipage/#image-button-state-(type=image)>
72    Image(ImageInputType),
73
74    /// <https://html.spec.whatwg.org/multipage/#month-state-(type=month)>
75    Month(MonthInputType),
76
77    /// <https://html.spec.whatwg.org/multipage/#number-state-(type=number)>
78    Number(NumberInputType),
79
80    /// <https://html.spec.whatwg.org/multipage/#password-state-(type=password)>
81    Password(PasswordInputType),
82
83    /// <https://html.spec.whatwg.org/multipage/#radio-button-state-(type=radio)>
84    Radio(RadioInputType),
85
86    /// <https://html.spec.whatwg.org/multipage/#range-state-(type=range)>
87    Range(RangeInputType),
88
89    /// <https://html.spec.whatwg.org/multipage/#reset-button-state-(type=reset)>
90    Reset(ResetInputType),
91
92    /// <https://html.spec.whatwg.org/multipage/#text-(type=text)-state-and-search-state-(type=search)>
93    Search(SearchInputType),
94
95    /// <https://html.spec.whatwg.org/multipage/#submit-button-state-(type=submit)>
96    Submit(SubmitInputType),
97
98    /// <https://html.spec.whatwg.org/multipage/#telephone-state-(type=tel)>
99    Tel(TelInputType),
100
101    /// <https://html.spec.whatwg.org/multipage/#text-(type=text)-state-and-search-state-(type=search)>
102    Text(TextInputType),
103
104    /// <https://html.spec.whatwg.org/multipage/#time-state-(type=time)>
105    Time(TimeInputType),
106
107    /// <https://html.spec.whatwg.org/multipage/#url-state-(type=url)>
108    Url(UrlInputType),
109
110    /// <https://html.spec.whatwg.org/multipage/#week-state-(type=week)>
111    Week(WeekInputType),
112}
113
114impl InputType {
115    pub(crate) fn new_from_atom(value: &Atom) -> Self {
116        match value.to_ascii_lowercase() {
117            atom!("button") => InputType::Button(Default::default()),
118            atom!("checkbox") => InputType::Checkbox(Default::default()),
119            atom!("color") => InputType::Color(Default::default()),
120            atom!("date") => InputType::Date(Default::default()),
121            atom!("datetime-local") => InputType::DatetimeLocal(Default::default()),
122            atom!("email") => InputType::Email(Default::default()),
123            atom!("file") => InputType::File(Default::default()),
124            atom!("hidden") => InputType::Hidden(Default::default()),
125            atom!("image") => InputType::Image(Default::default()),
126            atom!("month") => InputType::Month(Default::default()),
127            atom!("number") => InputType::Number(Default::default()),
128            atom!("password") => InputType::Password(Default::default()),
129            atom!("radio") => InputType::Radio(Default::default()),
130            atom!("range") => InputType::Range(Default::default()),
131            atom!("reset") => InputType::Reset(Default::default()),
132            atom!("search") => InputType::Search(Default::default()),
133            atom!("submit") => InputType::Submit(Default::default()),
134            atom!("tel") => InputType::Tel(Default::default()),
135            atom!("text") => InputType::Text(Default::default()),
136            atom!("time") => InputType::Time(Default::default()),
137            atom!("url") => InputType::Url(Default::default()),
138            atom!("week") => InputType::Week(Default::default()),
139            _ => InputType::Text(Default::default()),
140        }
141    }
142
143    pub(crate) fn new_text() -> Self {
144        Self::Text(TextInputType::default())
145    }
146
147    pub(crate) fn as_specific(&self) -> &dyn SpecificInputType {
148        match self {
149            Self::Button(input_type) => input_type as &dyn SpecificInputType,
150            Self::Checkbox(input_type) => input_type as &dyn SpecificInputType,
151            Self::Color(input_type) => input_type as &dyn SpecificInputType,
152            Self::Date(input_type) => input_type as &dyn SpecificInputType,
153            Self::DatetimeLocal(input_type) => input_type as &dyn SpecificInputType,
154            Self::Email(input_type) => input_type as &dyn SpecificInputType,
155            Self::File(input_type) => input_type as &dyn SpecificInputType,
156            Self::Hidden(input_type) => input_type as &dyn SpecificInputType,
157            Self::Image(input_type) => input_type as &dyn SpecificInputType,
158            Self::Month(input_type) => input_type as &dyn SpecificInputType,
159            Self::Number(input_type) => input_type as &dyn SpecificInputType,
160            Self::Password(input_type) => input_type as &dyn SpecificInputType,
161            Self::Radio(input_type) => input_type as &dyn SpecificInputType,
162            Self::Range(input_type) => input_type as &dyn SpecificInputType,
163            Self::Reset(input_type) => input_type as &dyn SpecificInputType,
164            Self::Search(input_type) => input_type as &dyn SpecificInputType,
165            Self::Submit(input_type) => input_type as &dyn SpecificInputType,
166            Self::Tel(input_type) => input_type as &dyn SpecificInputType,
167            Self::Text(input_type) => input_type as &dyn SpecificInputType,
168            Self::Time(input_type) => input_type as &dyn SpecificInputType,
169            Self::Url(input_type) => input_type as &dyn SpecificInputType,
170            Self::Week(input_type) => input_type as &dyn SpecificInputType,
171        }
172    }
173
174    /// Defines which input type that should perform like a text input,
175    /// specifically when it is interacting with JS. Note that Password
176    /// is not included here since it is handled slightly differently,
177    /// with placeholder characters shown rather than the underlying value.
178    pub(crate) fn is_textual(&self) -> bool {
179        matches!(
180            *self,
181            Self::Date(_) |
182                Self::DatetimeLocal(_) |
183                Self::Email(_) |
184                Self::Hidden(_) |
185                Self::Month(_) |
186                Self::Number(_) |
187                Self::Search(_) |
188                Self::Tel(_) |
189                Self::Text(_) |
190                Self::Time(_) |
191                Self::Url(_) |
192                Self::Week(_)
193        )
194    }
195
196    pub(crate) fn is_textual_or_password(&self) -> bool {
197        self.is_textual() || matches!(self, Self::Password(_))
198    }
199
200    /// <https://html.spec.whatwg.org/multipage/#has-a-periodic-domain>
201    pub(crate) fn has_periodic_domain(&self) -> bool {
202        matches!(self, Self::Time(_))
203    }
204
205    pub(crate) fn as_str(&self) -> &str {
206        match *self {
207            InputType::Button(_) => "button",
208            InputType::Checkbox(_) => "checkbox",
209            InputType::Color(_) => "color",
210            InputType::Date(_) => "date",
211            InputType::DatetimeLocal(_) => "datetime-local",
212            InputType::Email(_) => "email",
213            InputType::File(_) => "file",
214            InputType::Hidden(_) => "hidden",
215            InputType::Image(_) => "image",
216            InputType::Month(_) => "month",
217            InputType::Number(_) => "number",
218            InputType::Password(_) => "password",
219            InputType::Radio(_) => "radio",
220            InputType::Range(_) => "range",
221            InputType::Reset(_) => "reset",
222            InputType::Search(_) => "search",
223            InputType::Submit(_) => "submit",
224            InputType::Tel(_) => "tel",
225            InputType::Text(_) => "text",
226            InputType::Time(_) => "time",
227            InputType::Url(_) => "url",
228            InputType::Week(_) => "week",
229        }
230    }
231}
232
233impl TryFrom<&InputType> for InputMethodType {
234    type Error = &'static str;
235
236    fn try_from(input_type: &InputType) -> Result<Self, Self::Error> {
237        match input_type {
238            InputType::Color(_) => Ok(InputMethodType::Color),
239            InputType::Date(_) => Ok(InputMethodType::Date),
240            InputType::DatetimeLocal(_) => Ok(InputMethodType::DatetimeLocal),
241            InputType::Email(_) => Ok(InputMethodType::Email),
242            InputType::Month(_) => Ok(InputMethodType::Month),
243            InputType::Number(_) => Ok(InputMethodType::Number),
244            InputType::Password(_) => Ok(InputMethodType::Password),
245            InputType::Search(_) => Ok(InputMethodType::Search),
246            InputType::Tel(_) => Ok(InputMethodType::Tel),
247            InputType::Text(_) => Ok(InputMethodType::Text),
248            InputType::Time(_) => Ok(InputMethodType::Time),
249            InputType::Url(_) => Ok(InputMethodType::Url),
250            InputType::Week(_) => Ok(InputMethodType::Week),
251            _ => Err("Input does not support IME."),
252        }
253    }
254}
255
256pub(crate) trait SpecificInputType {
257    fn sanitize_value(&self, _input: &HTMLInputElement, _value: &mut DOMString) {}
258
259    fn convert_string_to_number(&self, _value: &str) -> Option<f64> {
260        None
261    }
262
263    fn convert_number_to_string(&self, _value: f64) -> Option<DOMString> {
264        unreachable!("Should not have called convert_number_to_string for non-Date types")
265    }
266
267    /// <https://html.spec.whatwg.org/multipage/#concept-input-value-string-date>
268    /// This does the safe Rust part of conversion; the unsafe JS Date part
269    /// is in GetValueAsDate
270    fn convert_string_to_naive_datetime(&self, _value: DOMString) -> Option<OffsetDateTime> {
271        None
272    }
273
274    /// <https://html.spec.whatwg.org/multipage/#concept-input-value-date-string>
275    /// This does the safe Rust part of conversion; the unsafe JS Date part
276    /// is in SetValueAsDate
277    fn convert_datetime_to_dom_string(&self, _value: OffsetDateTime) -> DOMString {
278        unreachable!("Should not have called convert_datetime_to_string for non-Date types")
279    }
280
281    /// <https://html.spec.whatwg.org/multipage/#the-required-attribute%3Asuffering-from-being-missing>
282    fn suffers_from_being_missing(&self, input: &HTMLInputElement, value: &DOMString) -> bool {
283        input.Required() &&
284            input.value_mode() == ValueMode::Value &&
285            input.is_mutable() &&
286            value.is_empty()
287    }
288
289    fn suffers_from_bad_input(&self, _value: &DOMString) -> bool {
290        false
291    }
292
293    fn suffers_from_type_mismatch(&self, _input: &HTMLInputElement, _value: &DOMString) -> bool {
294        false
295    }
296
297    fn value_for_shadow_dom(&self, _input: &HTMLInputElement) -> DOMString {
298        "".into()
299    }
300
301    /// <https://html.spec.whatwg.org/multipage/#signal-a-type-change>
302    fn signal_type_change(&self, _cx: &mut js::context::JSContext, _input: &HTMLInputElement) {}
303
304    fn activation_behavior(
305        &self,
306        _cx: &mut js::context::JSContext,
307        _input: &HTMLInputElement,
308        _event: &Event,
309        _target: &EventTarget,
310    ) {
311    }
312
313    fn legacy_pre_activation_behavior(
314        &self,
315        _cx: &mut JSContext,
316        _input: &HTMLInputElement,
317    ) -> Option<InputActivationState> {
318        None
319    }
320
321    fn legacy_canceled_activation_behavior(
322        &self,
323        _cx: &mut JSContext,
324        _input: &HTMLInputElement,
325        _cache: InputActivationState,
326    ) {
327    }
328
329    fn show_the_picker_if_applicable(&self, _input: &HTMLInputElement) {}
330
331    fn select_files(&self, _input: &HTMLInputElement, _test_paths: Option<Vec<DOMString>>) {}
332
333    fn get_files(&self) -> Option<DomRoot<FileList>> {
334        None
335    }
336
337    fn set_files(&self, _filelist: &FileList) {}
338
339    fn update_shadow_tree(&self, _cx: &mut JSContext, _input: &HTMLInputElement) {}
340
341    fn update_placeholder_contents(&self, _cx: &mut JSContext, _input: &HTMLInputElement) {}
342
343    fn attribute_mutated(
344        &self,
345        _cx: &mut JSContext,
346        _input: &HTMLInputElement,
347        _attr: AttrRef<'_>,
348        _mutation: AttributeMutation,
349    ) {
350    }
351
352    fn bind_to_tree(&self, _cx: &mut JSContext, _input: &HTMLInputElement, _context: &BindContext) {
353    }
354
355    fn unbind_from_tree(
356        &self,
357        _cx: &mut JSContext,
358        _input: &HTMLInputElement,
359        _form_owner: Option<DomRoot<HTMLFormElement>>,
360        _context: &UnbindContext,
361    ) {
362    }
363}