1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
use std::convert::TryFrom;
use std::ops::{Bound, RangeBounds};

use delegate::delegate;
use wasm_bindgen::JsCast;

use crate::error::{InvalidStateError, RangeError, SetTextRangeError};
use crate::html::{
    AutoComplete, FormMethod, GenericHtmlElement, HtmlDataListElement, HtmlElement,
    HtmlFormElement, Labels,
};
use crate::{
    Element, GenericElement, GenericNode, GlobalEventHandlers, InvalidCast, Node,
    SelectionDirection,
};

pub use web_sys::ValidityState;

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum InputType {
    Hidden,
    Text,
    Search,
    Tel,
    Url,
    Email,
    Password,
    Date,
    Month,
    Week,
    Time,
    DatetimeLocal,
    Number,
    Range,
    Color,
    Checkbox,
    Radio,
    File,
    Submit,
    Image,
    Reset,
    Button,
}

impl Default for InputType {
    fn default() -> Self {
        InputType::Text
    }
}

#[derive(Clone)]
pub struct HtmlInputElement {
    inner: web_sys::HtmlInputElement,
}

impl HtmlInputElement {
    // TODO: input_mode. I can't seem to find it in the WHATWG spec and the MDN documentation on
    // input_mode is very sparse. Feels like there should be some enum somewhere for all available
    // modes.

    delegate! {
        target self.inner {
            pub fn name(&self) -> String;

            pub fn set_name(&self, name: &str);

            pub fn value(&self) -> String;

            pub fn set_value(&self, value: &str);

            pub fn value_as_number(&self) -> f64;

            pub fn set_value_as_number(&self, value_as_number: f64);

            pub fn default_value(&self) -> String;

            pub fn set_default_value(&self, default_value: &str);

            pub fn accept(&self) -> String;

            pub fn set_accept(&self, accept: &str);

            pub fn alt(&self) -> String;

            pub fn set_alt(&self, alt: &str);

            pub fn autofocus(&self) -> bool;

            pub fn set_autofocus(&self, autofocus: bool);

            pub fn default_checked(&self) -> bool;

            pub fn set_default_checked(&self, default_checked: bool);

            pub fn checked(&self) -> bool;

            pub fn set_checked(&self, checked: bool);

            pub fn disabled(&self) -> bool;

            pub fn set_disabled(&self, disabled: bool);

            pub fn form_action(&self) -> String;

            pub fn set_form_action(&self, form_action: &str);

            pub fn form_no_validate(&self) -> bool;

            pub fn set_form_no_validate(&self, form_no_validate: bool);

            pub fn form_target(&self) -> String;

            pub fn set_form_target(&self, form_target: &str);

            pub fn width(&self) -> u32;

            pub fn set_width(&self, width: u32);

            pub fn height(&self) -> u32;

            pub fn set_height(&self, height: u32);

            pub fn indeterminate(&self) -> bool;

            pub fn set_indeterminate(&self, indeterminate: bool);

            pub fn min(&self) -> String;

            pub fn set_min(&self, min: &str);

            pub fn max(&self) -> String;

            pub fn set_max(&self, max: &str);

            pub fn multiple(&self) -> bool;

            pub fn set_multiple(&self, multiple: bool);

            pub fn pattern(&self) -> String;

            pub fn set_pattern(&self, pattern: &str);

            pub fn placeholder(&self) -> String;

            pub fn set_placeholder(&self, placeholder: &str);

            pub fn read_only(&self) -> bool;

            pub fn set_read_only(&self, read_only: bool);

            pub fn required(&self) -> bool;

            pub fn set_required(&self, required: bool);

            pub fn size(&self) -> u32;

            pub fn set_size(&self, size: u32);

            pub fn src(&self) -> String;

            pub fn set_src(&self, src: &str);

            pub fn step(&self) -> String;

            pub fn set_step(&self, step: &str);

            pub fn will_validate(&self) -> bool;

            pub fn check_validity(&self) -> bool;

            pub fn report_validity(&self) -> bool;

            pub fn set_custom_validity(&self, error: &str);

            pub fn validity(&self) -> ValidityState;

            pub fn select(&self);
        }
    }

    pub fn input_type(&self) -> InputType {
        match &*self.inner.type_() {
            "hidden" => InputType::Hidden,
            "search" => InputType::Search,
            "tel" => InputType::Tel,
            "url" => InputType::Url,
            "email" => InputType::Email,
            "password" => InputType::Password,
            "date" => InputType::Date,
            "month" => InputType::Month,
            "week" => InputType::Week,
            "time" => InputType::Time,
            "datetime-local" => InputType::DatetimeLocal,
            "number" => InputType::Number,
            "range" => InputType::Range,
            "color" => InputType::Color,
            "checkbox" => InputType::Checkbox,
            "radio" => InputType::Radio,
            "file" => InputType::File,
            "submit" => InputType::Submit,
            "image" => InputType::Image,
            "reset" => InputType::Reset,
            "button" => InputType::Button,
            _ => InputType::Text,
        }
    }

    pub fn set_input_type(&self, input_type: InputType) {
        let input_type = match input_type {
            InputType::Hidden => "hidden",
            InputType::Text => "text",
            InputType::Search => "search",
            InputType::Tel => "tel",
            InputType::Url => "url",
            InputType::Email => "email",
            InputType::Password => "password",
            InputType::Date => "date",
            InputType::Month => "month",
            InputType::Week => "week",
            InputType::Time => "time",
            InputType::DatetimeLocal => "datetime-local",
            InputType::Number => "number",
            InputType::Range => "range",
            InputType::Color => "color",
            InputType::Checkbox => "checkbox",
            InputType::Radio => "radio",
            InputType::File => "file",
            InputType::Submit => "submit",
            InputType::Image => "image",
            InputType::Reset => "reset",
            InputType::Button => "button",
        };

        self.inner.set_type(input_type);
    }

    pub fn autocomplete(&self) -> AutoComplete {
        match &*self.inner.autocomplete() {
            "off" => AutoComplete::Off,
            _ => AutoComplete::On,
        }
    }

    pub fn set_autocomplete(&self, autocomplete: AutoComplete) {
        let autocomplete = match autocomplete {
            AutoComplete::On => "on",
            AutoComplete::Off => "off",
        };

        self.inner.set_autocomplete(autocomplete);
    }

    pub fn max_length(&self) -> u32 {
        self.inner.max_length() as u32
    }

    pub fn set_max_length(&self, max_length: u32) {
        self.inner.set_max_length(max_length as i32);
    }

    pub fn min_length(&self) -> u32 {
        self.inner.min_length() as u32
    }

    pub fn set_min_length(&self, min_length: u32) {
        self.inner.set_min_length(min_length as i32);
    }

    pub fn form(&self) -> Option<HtmlFormElement> {
        self.inner.form().map(|form| form.into())
    }

    pub fn form_encoding(&self) -> String {
        self.inner.form_enctype()
    }

    pub fn set_form_encoding(&self, encoding: &str) {
        self.inner.set_form_enctype(encoding);
    }

    pub fn form_method(&self) -> FormMethod {
        match &*self.inner.form_method() {
            "post" => FormMethod::Post,
            "dialog" => FormMethod::Dialog,
            _ => FormMethod::Get,
        }
    }

    pub fn set_form_method(&self, method: FormMethod) {
        let method = match method {
            FormMethod::Get => "get",
            FormMethod::Post => "post",
            FormMethod::Dialog => "dialog",
        };

        self.inner.set_form_method(method);
    }

    // TODO: files

    pub fn list(&self) -> Option<HtmlDataListElement> {
        self.inner.list().map(|e| {
            let list: web_sys::HtmlDataListElement = e.unchecked_into();

            list.into()
        })
    }

    pub fn validation_message(&self) -> String {
        // There's no indication in the spec that this can actually fail, unwrap for now.
        self.inner.validation_message().unwrap()
    }

    pub fn selection_start(&self) -> Option<u32> {
        self.inner.selection_start().ok().flatten()
    }

    pub fn selection_end(&self) -> Option<u32> {
        self.inner.selection_end().ok().flatten()
    }

    pub fn selection_direction(&self) -> Option<SelectionDirection> {
        self.inner
            .selection_direction()
            .ok()
            .flatten()
            .map(|direction| match &*direction {
                "forward" => SelectionDirection::Forward,
                "backward" => SelectionDirection::Backward,
                _ => SelectionDirection::None,
            })
    }

    // TODO: set_selection_start, set_selection_end, set_selection_direction or rely on
    // set_selection_range?

    pub fn labels(&self) -> Option<Labels> {
        self.inner.labels().map(|inner| Labels::new(inner))
    }

    pub fn set_text_range<R>(&self, range: R, text: &str) -> Result<(), SetTextRangeError>
    where
        R: RangeBounds<u32>,
    {
        let start = match range.start_bound() {
            Bound::Included(start) => *start,
            Bound::Excluded(start) => *start + 1,
            Bound::Unbounded => self.selection_end().unwrap_or(0),
        };

        let end = match range.end_bound() {
            Bound::Included(end) => *end + 1,
            Bound::Excluded(end) => *end,
            Bound::Unbounded => self.selection_end().unwrap_or(0),
        };

        self.inner
            .set_range_text_with_start_and_end(text, start, end)
            .map_err(|err| {
                let err: web_sys::DomException = err.unchecked_into();

                match &*err.name() {
                    "IndexSizeError" => RangeError::new(err).into(),
                    "RangeError" => RangeError::new(err).into(),
                    "InvalidStateError" => InvalidStateError::new(err).into(),
                    _ => unreachable!(),
                }
            })
    }

    pub fn set_selection_range<R>(
        &self,
        range: R,
        direction: SelectionDirection,
    ) -> Result<(), InvalidStateError>
    where
        R: RangeBounds<u32>,
    {
        let start = match range.start_bound() {
            Bound::Included(start) => *start,
            Bound::Excluded(start) => *start + 1,
            Bound::Unbounded => self.selection_end().unwrap_or(0),
        };

        let end = match range.end_bound() {
            Bound::Included(end) => *end + 1,
            Bound::Excluded(end) => *end,
            Bound::Unbounded => self.selection_end().unwrap_or(0),
        };

        let direction = match direction {
            SelectionDirection::Forward => "forward",
            SelectionDirection::Backward => "backward",
            SelectionDirection::None => "none",
        };

        self.inner
            .set_selection_range_with_direction(start, end, direction)
            .map_err(|err| InvalidStateError::new(err.unchecked_into()))
    }
}

impl_html_common_traits!(HtmlInputElement);