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
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */

//! This is an abstraction used by `HTMLInputElement` and `HTMLTextAreaElement` to implement the
//! text control selection DOM API.
//!
//! <https://html.spec.whatwg.org/multipage/#textFieldSelection>

use script_traits::ScriptToConstellationChan;

use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::HTMLFormElementBinding::SelectionMode;
use crate::dom::bindings::conversions::DerivedFrom;
use crate::dom::bindings::error::{Error, ErrorResult};
use crate::dom::bindings::str::DOMString;
use crate::dom::event::{EventBubbles, EventCancelable};
use crate::dom::eventtarget::EventTarget;
use crate::dom::node::{window_from_node, Node, NodeDamage};
use crate::textinput::{SelectionDirection, SelectionState, TextInput, UTF8Bytes};

pub trait TextControlElement: DerivedFrom<EventTarget> + DerivedFrom<Node> {
    fn selection_api_applies(&self) -> bool;
    fn has_selectable_text(&self) -> bool;
    fn set_dirty_value_flag(&self, value: bool);
}

pub struct TextControlSelection<'a, E: TextControlElement> {
    element: &'a E,
    textinput: &'a DomRefCell<TextInput<ScriptToConstellationChan>>,
}

impl<'a, E: TextControlElement> TextControlSelection<'a, E> {
    pub fn new(
        element: &'a E,
        textinput: &'a DomRefCell<TextInput<ScriptToConstellationChan>>,
    ) -> Self {
        TextControlSelection { element, textinput }
    }

    // https://html.spec.whatwg.org/multipage/#dom-textarea/input-select
    pub fn dom_select(&self) {
        // Step 1
        if !self.element.has_selectable_text() {
            return;
        }

        // Step 2
        self.set_range(Some(0), Some(u32::MAX), None, None);
    }

    // https://html.spec.whatwg.org/multipage/#dom-textarea/input-selectionstart
    pub fn dom_start(&self) -> Option<u32> {
        // Step 1
        if !self.element.selection_api_applies() {
            return None;
        }

        // Steps 2-3
        Some(self.start())
    }

    // https://html.spec.whatwg.org/multipage/#dom-textarea/input-selectionstart
    pub fn set_dom_start(&self, start: Option<u32>) -> ErrorResult {
        // Step 1
        if !self.element.selection_api_applies() {
            return Err(Error::InvalidState);
        }

        // Step 2
        let mut end = self.end();

        // Step 3
        if let Some(s) = start {
            if end < s {
                end = s;
            }
        }

        // Step 4
        self.set_range(start, Some(end), Some(self.direction()), None);
        Ok(())
    }

    // https://html.spec.whatwg.org/multipage/#dom-textarea/input-selectionend
    pub fn dom_end(&self) -> Option<u32> {
        // Step 1
        if !self.element.selection_api_applies() {
            return None;
        }

        // Steps 2-3
        Some(self.end())
    }

    // https://html.spec.whatwg.org/multipage/#dom-textarea/input-selectionend
    pub fn set_dom_end(&self, end: Option<u32>) -> ErrorResult {
        // Step 1
        if !self.element.selection_api_applies() {
            return Err(Error::InvalidState);
        }

        // Step 2
        self.set_range(Some(self.start()), end, Some(self.direction()), None);
        Ok(())
    }

    // https://html.spec.whatwg.org/multipage/#dom-textarea/input-selectiondirection
    pub fn dom_direction(&self) -> Option<DOMString> {
        // Step 1
        if !self.element.selection_api_applies() {
            return None;
        }

        Some(DOMString::from(self.direction()))
    }

    // https://html.spec.whatwg.org/multipage/#dom-textarea/input-selectiondirection
    pub fn set_dom_direction(&self, direction: Option<DOMString>) -> ErrorResult {
        // Step 1
        if !self.element.selection_api_applies() {
            return Err(Error::InvalidState);
        }

        // Step 2
        self.set_range(
            Some(self.start()),
            Some(self.end()),
            direction.map(SelectionDirection::from),
            None,
        );
        Ok(())
    }

    // https://html.spec.whatwg.org/multipage/#dom-textarea/input-setselectionrange
    pub fn set_dom_range(&self, start: u32, end: u32, direction: Option<DOMString>) -> ErrorResult {
        // Step 1
        if !self.element.selection_api_applies() {
            return Err(Error::InvalidState);
        }

        // Step 2
        self.set_range(
            Some(start),
            Some(end),
            direction.map(SelectionDirection::from),
            None,
        );
        Ok(())
    }

    // https://html.spec.whatwg.org/multipage/#dom-textarea/input-setrangetext
    pub fn set_dom_range_text(
        &self,
        replacement: DOMString,
        start: Option<u32>,
        end: Option<u32>,
        selection_mode: SelectionMode,
    ) -> ErrorResult {
        // Step 1
        if !self.element.selection_api_applies() {
            return Err(Error::InvalidState);
        }

        // Step 2
        self.element.set_dirty_value_flag(true);

        // Step 3
        let mut start = start.unwrap_or_else(|| self.start());
        let mut end = end.unwrap_or_else(|| self.end());

        // Step 4
        if start > end {
            return Err(Error::IndexSize);
        }

        // Save the original selection state to later pass to set_selection_range, because we will
        // change the selection state in order to replace the text in the range.
        let original_selection_state = self.textinput.borrow().selection_state();

        let UTF8Bytes(content_length) = self.textinput.borrow().len_utf8();
        let content_length = content_length as u32;

        // Step 5
        if start > content_length {
            start = content_length;
        }

        // Step 6
        if end > content_length {
            end = content_length;
        }

        // Step 7
        let mut selection_start = self.start();

        // Step 8
        let mut selection_end = self.end();

        // Step 11
        // Must come before the textinput.replace_selection() call, as replacement gets moved in
        // that call.
        let new_length = replacement.len() as u32;

        {
            let mut textinput = self.textinput.borrow_mut();

            // Steps 9-10
            textinput.set_selection_range(start, end, SelectionDirection::None);
            textinput.replace_selection(replacement);
        }

        // Step 12
        let new_end = start + new_length;

        // Step 13
        match selection_mode {
            SelectionMode::Select => {
                selection_start = start;
                selection_end = new_end;
            },

            SelectionMode::Start => {
                selection_start = start;
                selection_end = start;
            },

            SelectionMode::End => {
                selection_start = new_end;
                selection_end = new_end;
            },

            SelectionMode::Preserve => {
                // Sub-step 1
                let old_length = end - start;

                // Sub-step 2
                let delta = (new_length as isize) - (old_length as isize);

                // Sub-step 3
                if selection_start > end {
                    selection_start = ((selection_start as isize) + delta) as u32;
                } else if selection_start > start {
                    selection_start = start;
                }

                // Sub-step 4
                if selection_end > end {
                    selection_end = ((selection_end as isize) + delta) as u32;
                } else if selection_end > start {
                    selection_end = new_end;
                }
            },
        }

        // Step 14
        self.set_range(
            Some(selection_start),
            Some(selection_end),
            None,
            Some(original_selection_state),
        );
        Ok(())
    }

    fn start(&self) -> u32 {
        let UTF8Bytes(offset) = self.textinput.borrow().selection_start_offset();
        offset as u32
    }

    fn end(&self) -> u32 {
        let UTF8Bytes(offset) = self.textinput.borrow().selection_end_offset();
        offset as u32
    }

    fn direction(&self) -> SelectionDirection {
        self.textinput.borrow().selection_direction()
    }

    // https://html.spec.whatwg.org/multipage/#set-the-selection-range
    fn set_range(
        &self,
        start: Option<u32>,
        end: Option<u32>,
        direction: Option<SelectionDirection>,
        original_selection_state: Option<SelectionState>,
    ) {
        let mut textinput = self.textinput.borrow_mut();
        let original_selection_state =
            original_selection_state.unwrap_or_else(|| textinput.selection_state());

        // Step 1
        let start = start.unwrap_or(0);

        // Step 2
        let end = end.unwrap_or(0);

        // Steps 3-5
        textinput.set_selection_range(start, end, direction.unwrap_or(SelectionDirection::None));

        // Step 6
        if textinput.selection_state() != original_selection_state {
            let window = window_from_node(self.element);
            window
                .task_manager()
                .user_interaction_task_source()
                .queue_event(
                    self.element.upcast::<EventTarget>(),
                    atom!("select"),
                    EventBubbles::Bubbles,
                    EventCancelable::NotCancelable,
                    &window,
                );
        }

        self.element
            .upcast::<Node>()
            .dirty(NodeDamage::OtherNodeDamage);
    }
}