diff --git a/servo/components/script/dom/activation.rs b/servo/components/script/dom/activation.rs new file mode 100644 index 000000000000..e4a54112e585 --- /dev/null +++ b/servo/components/script/dom/activation.rs @@ -0,0 +1,65 @@ +/* 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 http://mozilla.org/MPL/2.0/. */ + +use dom::bindings::codegen::Bindings::EventBinding::EventMethods; +use dom::bindings::codegen::InheritTypes::{EventCast, EventTargetCast}; +use dom::bindings::js::{JSRef, Temporary, OptionalRootable}; +use dom::element::{Element, ActivationElementHelpers}; +use dom::event::{Event, EventHelpers}; +use dom::eventtarget::{EventTarget, EventTargetHelpers}; +use dom::mouseevent::MouseEvent; +use dom::node::window_from_node; + + +/// Trait for elements with defined activation behavior +pub trait Activatable : Copy { + fn as_element(&self) -> Temporary; + + // https://html.spec.whatwg.org/multipage/interaction.html#run-pre-click-activation-steps + fn pre_click_activation(&self); + + // https://html.spec.whatwg.org/multipage/interaction.html#run-canceled-activation-steps + fn canceled_activation(&self); + + // https://html.spec.whatwg.org/multipage/interaction.html#run-post-click-activation-steps + fn activation_behavior(&self); + + // https://html.spec.whatwg.org/multipage/forms.html#implicit-submission + fn implicit_submission(&self, ctrlKey: bool, shiftKey: bool, altKey: bool, metaKey: bool); + + // https://html.spec.whatwg.org/multipage/interaction.html#run-synthetic-click-activation-steps + fn synthetic_click_activation(&self, ctrlKey: bool, shiftKey: bool, altKey: bool, metaKey: bool) { + let element = self.as_element().root(); + // Step 1 + if element.click_in_progress() { + return; + } + // Step 2 + element.set_click_in_progress(true); + // Step 3 + self.pre_click_activation(); + + // Step 4 + // https://html.spec.whatwg.org/multipage/webappapis.html#fire-a-synthetic-mouse-event + let win = window_from_node(*element).root(); + let target: JSRef = EventTargetCast::from_ref(*element); + let mouse = MouseEvent::new(*win, "click".to_string(), false, false, Some(*win), 1, + 0, 0, 0, 0, ctrlKey, shiftKey, altKey, metaKey, + 0, None).root(); + let event: JSRef = EventCast::from_ref(*mouse); + event.set_trusted(true); + target.dispatch_event_with_target(None, event).ok(); + + // Step 5 + if event.DefaultPrevented() { + self.canceled_activation(); + } else { + // post click activation + self.activation_behavior(); + } + + // Step 6 + element.set_click_in_progress(false); + } +} diff --git a/servo/components/script/dom/bindings/js.rs b/servo/components/script/dom/bindings/js.rs index f24115a349a9..c9f3e157b75c 100644 --- a/servo/components/script/dom/bindings/js.rs +++ b/servo/components/script/dom/bindings/js.rs @@ -575,3 +575,24 @@ impl<'a, T: Reflectable> Reflectable for JSRef<'a, T> { self.deref().reflector() } } + +/// A trait for comparing smart pointers ignoring the lifetimes +pub trait Comparable { + fn equals(&self, other: T) -> bool; +} + +impl<'a, 'b, T> Comparable> for JSRef<'b, T> { + fn equals(&self, other: JSRef<'a, T>) -> bool { + self.ptr == other.ptr + } +} + +impl<'a, 'b, T> Comparable>> for Option> { + fn equals(&self, other: Option>) -> bool { + match (*self, other) { + (Some(x), Some(y)) => x.ptr == y.ptr, + (None, None) => true, + _ => false + } + } +} diff --git a/servo/components/script/dom/document.rs b/servo/components/script/dom/document.rs index f282aa3b483c..fad44638f646 100644 --- a/servo/components/script/dom/document.rs +++ b/servo/components/script/dom/document.rs @@ -966,7 +966,6 @@ impl<'a> DocumentMethods for JSRef<'a, Document> { self.ready_state.get() } - event_handler!(click, GetOnclick, SetOnclick) - event_handler!(load, GetOnload, SetOnload) + global_event_handlers!() event_handler!(readystatechange, GetOnreadystatechange, SetOnreadystatechange) } diff --git a/servo/components/script/dom/element.rs b/servo/components/script/dom/element.rs index 36ce1102eb59..ec06678e50c6 100644 --- a/servo/components/script/dom/element.rs +++ b/servo/components/script/dom/element.rs @@ -4,6 +4,7 @@ //! Element nodes. +use dom::activation::Activatable; use dom::attr::{Attr, ReplacedAttr, FirstSetAttr, AttrHelpers, AttrHelpersForLayout}; use dom::attr::{AttrValue, StringAttrValue, UIntAttrValue, AtomAttrValue}; use dom::namednodemap::NamedNodeMap; @@ -11,9 +12,10 @@ use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::AttrBinding::AttrMethods; use dom::bindings::codegen::Bindings::ElementBinding; use dom::bindings::codegen::Bindings::ElementBinding::ElementMethods; +use dom::bindings::codegen::Bindings::EventBinding::EventMethods; use dom::bindings::codegen::Bindings::NamedNodeMapBinding::NamedNodeMapMethods; -use dom::bindings::codegen::InheritTypes::{ElementDerived, HTMLInputElementDerived}; -use dom::bindings::codegen::InheritTypes::{HTMLTableCellElementDerived, NodeCast}; +use dom::bindings::codegen::InheritTypes::{ElementDerived, HTMLInputElementDerived, HTMLTableCellElementDerived}; +use dom::bindings::codegen::InheritTypes::{HTMLInputElementCast, NodeCast, EventTargetCast, ElementCast}; use dom::bindings::js::{MutNullableJS, JS, JSRef, Temporary, TemporaryPushable}; use dom::bindings::js::{OptionalSettable, OptionalRootable, Root}; use dom::bindings::utils::{Reflectable, Reflector}; @@ -24,12 +26,13 @@ use dom::domrect::DOMRect; use dom::domrectlist::DOMRectList; use dom::document::{Document, DocumentHelpers, LayoutDocumentHelpers}; use dom::domtokenlist::DOMTokenList; -use dom::eventtarget::{EventTarget, NodeTargetTypeId}; +use dom::event::Event; +use dom::eventtarget::{EventTarget, NodeTargetTypeId, EventTargetHelpers}; use dom::htmlcollection::HTMLCollection; use dom::htmlinputelement::{HTMLInputElement, RawLayoutHTMLInputElementHelpers}; use dom::htmlserializer::serialize; use dom::htmltablecellelement::{HTMLTableCellElement, HTMLTableCellElementHelpers}; -use dom::node::{ElementNodeTypeId, Node, NodeHelpers, NodeIterator, document_from_node}; +use dom::node::{ElementNodeTypeId, Node, NodeHelpers, NodeIterator, document_from_node, CLICK_IN_PROGRESS}; use dom::node::{window_from_node, LayoutNodeHelpers}; use dom::nodelist::NodeList; use dom::virtualmethods::{VirtualMethods, vtable_for}; @@ -1184,3 +1187,92 @@ impl<'a> style::TElement<'a> for JSRef<'a, Element> { } } } + +pub trait ActivationElementHelpers<'a> { + fn as_maybe_activatable(&'a self) -> Option<&'a Activatable + 'a>; + fn click_in_progress(self) -> bool; + fn set_click_in_progress(self, click: bool); + fn nearest_activable_element(self) -> Option>; + fn authentic_click_activation<'b>(self, event: JSRef<'b, Event>); +} + +impl<'a> ActivationElementHelpers<'a> for JSRef<'a, Element> { + fn as_maybe_activatable(&'a self) -> Option<&'a Activatable + 'a> { + let node: JSRef = NodeCast::from_ref(*self); + match node.type_id() { + ElementNodeTypeId(HTMLInputElementTypeId) => { + let element: &'a JSRef<'a, HTMLInputElement> = HTMLInputElementCast::to_borrowed_ref(self).unwrap(); + Some(element as &'a Activatable + 'a) + }, + _ => { + None + } + } + } + + fn click_in_progress(self) -> bool { + let node: JSRef = NodeCast::from_ref(self); + node.get_flag(CLICK_IN_PROGRESS) + } + + fn set_click_in_progress(self, click: bool) { + let node: JSRef = NodeCast::from_ref(self); + node.set_flag(CLICK_IN_PROGRESS, click) + } + + // https://html.spec.whatwg.org/multipage/interaction.html#nearest-activatable-element + fn nearest_activable_element(self) -> Option> { + match self.as_maybe_activatable() { + Some(el) => Some(Temporary::from_rooted(*el.as_element().root())), + None => { + let node: JSRef = NodeCast::from_ref(self); + node.ancestors() + .filter_map(|node| ElementCast::to_ref(node)) + .filter(|e| e.as_maybe_activatable().is_some()).next() + .map(|r| Temporary::from_rooted(r)) + } + } + } + + /// Please call this method *only* for real click events + /// + /// https://html.spec.whatwg.org/multipage/interaction.html#run-authentic-click-activation-steps + /// + /// Use an element's synthetic click activation (or handle_event) for any script-triggered clicks. + /// If the spec says otherwise, check with Manishearth first + fn authentic_click_activation<'b>(self, event: JSRef<'b, Event>) { + // Not explicitly part of the spec, however this helps enforce the invariants + // required to save state between pre-activation and post-activation + // since we cannot nest authentic clicks (unlike synthetic click activation, where + // the script can generate more click events from the handler) + assert!(!self.click_in_progress()); + + let target: JSRef = EventTargetCast::from_ref(self); + // Step 2 (requires canvas support) + // Step 3 + self.set_click_in_progress(true); + // Step 4 + let e = self.nearest_activable_element().root(); + match e { + Some(el) => match el.as_maybe_activatable() { + Some(elem) => { + // Step 5-6 + elem.pre_click_activation(); + target.dispatch_event_with_target(None, event).ok(); + if !event.DefaultPrevented() { + // post click activation + elem.activation_behavior(); + } else { + elem.canceled_activation(); + } + } + // Step 6 + None => {target.dispatch_event_with_target(None, event).ok();} + }, + // Step 6 + None => {target.dispatch_event_with_target(None, event).ok();} + } + // Step 7 + self.set_click_in_progress(false); + } +} diff --git a/servo/components/script/dom/event.rs b/servo/components/script/dom/event.rs index 637bd259035d..6d7ce64bf5e6 100644 --- a/servo/components/script/dom/event.rs +++ b/servo/components/script/dom/event.rs @@ -245,3 +245,13 @@ impl Reflectable for Event { &self.reflector_ } } + +pub trait EventHelpers { + fn set_trusted(self, trusted: bool); +} + +impl<'a> EventHelpers for JSRef<'a, Event> { + fn set_trusted(self, trusted: bool) { + self.trusted.set(trusted); + } +} diff --git a/servo/components/script/dom/htmlelement.rs b/servo/components/script/dom/htmlelement.rs index 75ad910ee2eb..010946fabc4d 100644 --- a/servo/components/script/dom/htmlelement.rs +++ b/servo/components/script/dom/htmlelement.rs @@ -7,14 +7,15 @@ use dom::attr::AttrHelpers; use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull; use dom::bindings::codegen::Bindings::HTMLElementBinding; use dom::bindings::codegen::Bindings::HTMLElementBinding::HTMLElementMethods; +use dom::bindings::codegen::Bindings::HTMLInputElementBinding::HTMLInputElementMethods; use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; use dom::bindings::codegen::InheritTypes::{ElementCast, HTMLFrameSetElementDerived}; -use dom::bindings::codegen::InheritTypes::EventTargetCast; +use dom::bindings::codegen::InheritTypes::{EventTargetCast, HTMLInputElementCast}; use dom::bindings::codegen::InheritTypes::{HTMLElementDerived, HTMLBodyElementDerived}; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; -use dom::element::{Element, ElementTypeId, ElementTypeId_, HTMLElementTypeId}; +use dom::element::{Element, ElementTypeId, ElementTypeId_, HTMLElementTypeId, ActivationElementHelpers}; use dom::eventtarget::{EventTarget, EventTargetHelpers, NodeTargetTypeId}; use dom::node::{Node, ElementNodeTypeId, window_from_node}; use dom::virtualmethods::VirtualMethods; @@ -74,7 +75,7 @@ impl<'a> HTMLElementMethods for JSRef<'a, HTMLElement> { make_bool_getter!(Hidden) make_bool_setter!(SetHidden, "hidden") - event_handler!(click, GetOnclick, SetOnclick) + global_event_handlers!(NoOnload) fn GetOnload(self) -> Option { if self.is_body_or_frameset() { @@ -91,6 +92,18 @@ impl<'a> HTMLElementMethods for JSRef<'a, HTMLElement> { win.SetOnload(listener) } } + + // https://html.spec.whatwg.org/multipage/interaction.html#dom-click + fn Click(self) { + let maybe_input = HTMLInputElementCast::to_ref(self); + match maybe_input { + Some(i) if i.Disabled() => return, + _ => () + } + let element: JSRef = ElementCast::from_ref(self); + // https://www.w3.org/Bugs/Public/show_bug.cgi?id=27430 ? + element.as_maybe_activatable().map(|a| a.synthetic_click_activation(false, false, false, false)); + } } impl<'a> VirtualMethods for JSRef<'a, HTMLElement> { diff --git a/servo/components/script/dom/htmlformelement.rs b/servo/components/script/dom/htmlformelement.rs index a8461618db95..1d12bdebf39b 100644 --- a/servo/components/script/dom/htmlformelement.rs +++ b/servo/components/script/dom/htmlformelement.rs @@ -15,7 +15,7 @@ use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::{Document, DocumentHelpers}; use dom::element::{Element, AttributeHandlers, HTMLFormElementTypeId, HTMLTextAreaElementTypeId, HTMLDataListElementTypeId}; use dom::element::{HTMLInputElementTypeId, HTMLButtonElementTypeId, HTMLObjectElementTypeId, HTMLSelectElementTypeId}; -use dom::event::{Event, Bubbles, Cancelable}; +use dom::event::{Event, EventHelpers, Bubbles, Cancelable}; use dom::eventtarget::{EventTarget, NodeTargetTypeId}; use dom::htmlelement::HTMLElement; use dom::htmlinputelement::HTMLInputElement; @@ -142,6 +142,7 @@ impl<'a> HTMLFormElementHelpers for JSRef<'a, HTMLFormElement> { let event = Event::new(Window(*win), "submit".to_string(), Bubbles, Cancelable).root(); + event.set_trusted(true); let target: JSRef = EventTargetCast::from_ref(self); target.DispatchEvent(*event).ok(); if event.DefaultPrevented() { @@ -410,7 +411,7 @@ impl<'a> FormSubmitter<'a> { } } -pub trait FormOwner<'a> : Copy { +pub trait FormControl<'a> : Copy { fn form_owner(self) -> Option>; fn get_form_attribute(self, attr: &Atom, @@ -423,4 +424,6 @@ pub trait FormOwner<'a> : Copy { } } fn to_element(self) -> JSRef<'a, Element>; + // https://html.spec.whatwg.org/multipage/forms.html#concept-fe-mutable + fn mutable(self) -> bool; } diff --git a/servo/components/script/dom/htmlinputelement.rs b/servo/components/script/dom/htmlinputelement.rs index 20227cd397ee..a736a7a8f3da 100644 --- a/servo/components/script/dom/htmlinputelement.rs +++ b/servo/components/script/dom/htmlinputelement.rs @@ -2,28 +2,31 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +use dom::activation::Activatable; use dom::attr::{Attr, AttrValue, UIntAttrValue}; use dom::attr::AttrHelpers; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::AttrBinding::AttrMethods; use dom::bindings::codegen::Bindings::DocumentBinding::DocumentMethods; use dom::bindings::codegen::Bindings::EventBinding::EventMethods; +use dom::bindings::codegen::Bindings::EventTargetBinding::EventTargetMethods; use dom::bindings::codegen::Bindings::HTMLInputElementBinding; use dom::bindings::codegen::Bindings::HTMLInputElementBinding::HTMLInputElementMethods; -use dom::bindings::codegen::Bindings::NodeListBinding::NodeListMethods; use dom::bindings::codegen::InheritTypes::{ElementCast, HTMLElementCast, HTMLFormElementCast, HTMLInputElementCast, NodeCast}; -use dom::bindings::codegen::InheritTypes::{HTMLInputElementDerived, HTMLFieldSetElementDerived}; +use dom::bindings::codegen::InheritTypes::{HTMLInputElementDerived, HTMLFieldSetElementDerived, EventTargetCast}; use dom::bindings::codegen::InheritTypes::KeyboardEventCast; -use dom::bindings::js::{JS, JSRef, Temporary, OptionalRootable, ResultRootable}; +use dom::bindings::global::Window; +use dom::bindings::js::{Comparable, JS, JSRef, Root, Temporary, OptionalRootable}; +use dom::bindings::js::{ResultRootable, RootedReference, MutNullableJS}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::{Document, DocumentHelpers}; use dom::element::{AttributeHandlers, Element, HTMLInputElementTypeId}; -use dom::element::RawLayoutElementHelpers; -use dom::event::Event; +use dom::element::{RawLayoutElementHelpers, ActivationElementHelpers}; +use dom::event::{Event, Bubbles, NotCancelable, EventHelpers}; use dom::eventtarget::{EventTarget, NodeTargetTypeId}; use dom::htmlelement::HTMLElement; use dom::keyboardevent::KeyboardEvent; -use dom::htmlformelement::{InputElement, FormOwner, HTMLFormElement, HTMLFormElementHelpers, NotFromFormSubmitMethod}; +use dom::htmlformelement::{InputElement, FormControl, HTMLFormElement, HTMLFormElementHelpers, NotFromFormSubmitMethod}; use dom::node::{DisabledStateHelpers, Node, NodeHelpers, ElementNodeTypeId, document_from_node, window_from_node}; use dom::virtualmethods::VirtualMethods; use textinput::{Single, TextInput, TriggerDefaultAction, DispatchInput, Nothing}; @@ -33,6 +36,7 @@ use string_cache::Atom; use std::ascii::OwnedAsciiExt; use std::cell::Cell; +use std::default::Default; const DEFAULT_SUBMIT_VALUE: &'static str = "Submit"; const DEFAULT_RESET_VALUE: &'static str = "Reset"; @@ -41,7 +45,9 @@ const DEFAULT_RESET_VALUE: &'static str = "Reset"; #[deriving(PartialEq)] #[allow(dead_code)] enum InputType { - InputButton(Option<&'static str>), + InputSubmit, + InputReset, + InputButton, InputText, InputFile, InputImage, @@ -55,8 +61,34 @@ pub struct HTMLInputElement { htmlelement: HTMLElement, input_type: Cell, checked: Cell, + indeterminate: Cell, size: Cell, textinput: DOMRefCell, + activation_state: DOMRefCell, +} + +#[jstraceable] +#[must_root] +struct InputActivationState { + indeterminate: bool, + checked: bool, + checked_radio: MutNullableJS, + // In case mutability changed + was_mutable: bool, + // In case the type changed + old_type: InputType, +} + +impl InputActivationState { + fn new() -> InputActivationState { + InputActivationState { + indeterminate: false, + checked: false, + checked_radio: Default::default(), + was_mutable: false, + old_type: InputText + } + } } impl HTMLInputElementDerived for EventTarget { @@ -73,8 +105,10 @@ impl HTMLInputElement { htmlelement: HTMLElement::new_inherited(HTMLInputElementTypeId, localName, prefix, document), input_type: Cell::new(InputText), checked: Cell::new(false), + indeterminate: Cell::new(false), size: Cell::new(DEFAULT_INPUT_SIZE), textinput: DOMRefCell::new(TextInput::new(Single, "".to_string())), + activation_state: DOMRefCell::new(InputActivationState::new()) } } @@ -110,9 +144,9 @@ impl LayoutHTMLInputElementHelpers for JS { match (*self.unsafe_get()).input_type.get() { InputCheckbox | InputRadio => "".to_string(), InputFile | InputImage => "".to_string(), - InputButton(ref default) => get_raw_attr_value(self) - .or_else(|| default.map(|v| v.to_string())) - .unwrap_or_else(|| "".to_string()), + InputButton => get_raw_attr_value(self).unwrap_or_else(|| "".to_string()), + InputSubmit => get_raw_attr_value(self).unwrap_or_else(|| DEFAULT_SUBMIT_VALUE.to_string()), + InputReset => get_raw_attr_value(self).unwrap_or_else(|| DEFAULT_RESET_VALUE.to_string()), InputPassword => { let raw = get_raw_textinput_value(self); String::from_char(raw.char_len(), '●') @@ -149,6 +183,12 @@ impl<'a> HTMLInputElementMethods for JSRef<'a, HTMLInputElement> { // https://html.spec.whatwg.org/multipage/forms.html#dom-input-checked make_bool_setter!(SetChecked, "checked") + // https://html.spec.whatwg.org/multipage/forms.html#dom-input-readonly + make_bool_getter!(ReadOnly) + + // https://html.spec.whatwg.org/multipage/forms.html#dom-input-readonly + make_bool_setter!(SetReadOnly, "readonly") + // https://html.spec.whatwg.org/multipage/forms.html#dom-input-size make_uint_getter!(Size) @@ -194,7 +234,7 @@ impl<'a> HTMLInputElementMethods for JSRef<'a, HTMLInputElement> { make_setter!(SetFormEnctype, "formenctype") // https://html.spec.whatwg.org/multipage/forms.html#dom-input-formmethod - make_enumerated_getter!(FormMethod, "get", "post" | "dialog") + make_enumerated_getter!(FormMethod, "get", "post" | "dialog") // https://html.spec.whatwg.org/multipage/forms.html#dom-input-formmethod make_setter!(SetFormMethod, "formmethod") @@ -204,34 +244,59 @@ impl<'a> HTMLInputElementMethods for JSRef<'a, HTMLInputElement> { // https://html.spec.whatwg.org/multipage/forms.html#dom-input-formtarget make_setter!(SetFormTarget, "formtarget") + + // https://html.spec.whatwg.org/multipage/forms.html#dom-input-indeterminate + fn Indeterminate(self) -> bool { + self.indeterminate.get() + } + + // https://html.spec.whatwg.org/multipage/forms.html#dom-input-indeterminate + fn SetIndeterminate(self, val: bool) { + // FIXME #4079 this should change the appearance + self.indeterminate.set(val) + } } pub trait HTMLInputElementHelpers { fn force_relayout(self); fn radio_group_updated(self, group: Option<&str>); - fn get_radio_group(self) -> Option; + fn get_radio_group_name(self) -> Option; fn update_checked_state(self, checked: bool); fn get_size(&self) -> u32; } fn broadcast_radio_checked(broadcaster: JSRef, group: Option<&str>) { //TODO: if not in document, use root ancestor instead of document + let owner = broadcaster.form_owner().root(); let doc = document_from_node(broadcaster).root(); - let radios = doc.QuerySelectorAll("input[type=\"radio\"]".to_string()).unwrap().root(); - let mut i = 0; - while i < radios.Length() { - let node = radios.Item(i).unwrap().root(); - let radio: JSRef = HTMLInputElementCast::to_ref(*node).unwrap(); - if radio != broadcaster { - //TODO: determine form owner - let other_group = radio.get_radio_group(); - //TODO: ensure compatibility caseless match (https://html.spec.whatwg.org/multipage/infrastructure.html#compatibility-caseless) - let group_matches = other_group.as_ref().map(|group| group.as_slice()) == group.as_ref().map(|&group| &*group); - if group_matches && radio.Checked() { - radio.SetChecked(false); - } + let doc_node: JSRef = NodeCast::from_ref(*doc); + + // There is no DOM tree manipulation here, so this is safe + let mut iter = unsafe { + doc_node.query_selector_iter("input[type=radio]".to_string()).unwrap() + .filter_map(|t| HTMLInputElementCast::to_ref(t)) + .filter(|&r| in_same_group(r, owner.root_ref(), group) && broadcaster != r) + }; + for r in iter { + if r.Checked() { + r.SetChecked(false); } - i += 1; + } +} + +fn in_same_group<'a,'b>(other: JSRef<'a, HTMLInputElement>, + owner: Option>, + group: Option<&str>) -> bool { + let other_owner = other.form_owner().root(); + let other_owner = other_owner.root_ref(); + other.input_type.get() == InputRadio && + // TODO Both a and b are in the same home subtree. + other_owner.equals(owner) && + // TODO should be a unicode compatibility caseless match + match (other.get_radio_group_name(), group) { + (Some(ref s1), Some(s2)) => s1.as_slice() == s2, + (None, None) => true, + _ => false } } @@ -248,8 +313,7 @@ impl<'a> HTMLInputElementHelpers for JSRef<'a, HTMLInputElement> { } } - // https://html.spec.whatwg.org/multipage/forms.html#radio-button-group - fn get_radio_group(self) -> Option { + fn get_radio_group_name(self) -> Option { //TODO: determine form owner let elem: JSRef = ElementCast::from_ref(self); elem.get_attribute(ns!(""), &atom!("name")) @@ -261,7 +325,7 @@ impl<'a> HTMLInputElementHelpers for JSRef<'a, HTMLInputElement> { self.checked.set(checked); if self.input_type.get() == InputRadio && checked { broadcast_radio_checked(self, - self.get_radio_group() + self.get_radio_group_name() .as_ref() .map(|group| group.as_slice())); } @@ -305,9 +369,9 @@ impl<'a> VirtualMethods for JSRef<'a, HTMLInputElement> { &atom!("type") => { let value = attr.value(); self.input_type.set(match value.as_slice() { - "button" => InputButton(None), - "submit" => InputButton(Some(DEFAULT_SUBMIT_VALUE)), - "reset" => InputButton(Some(DEFAULT_RESET_VALUE)), + "button" => InputButton, + "submit" => InputSubmit, + "reset" => InputReset, "file" => InputFile, "radio" => InputRadio, "checkbox" => InputCheckbox, @@ -315,7 +379,7 @@ impl<'a> VirtualMethods for JSRef<'a, HTMLInputElement> { _ => InputText, }); if self.input_type.get() == InputRadio { - self.radio_group_updated(self.get_radio_group() + self.radio_group_updated(self.get_radio_group_name() .as_ref() .map(|group| group.as_slice())); } @@ -358,7 +422,7 @@ impl<'a> VirtualMethods for JSRef<'a, HTMLInputElement> { &atom!("type") => { if self.input_type.get() == InputRadio { broadcast_radio_checked(*self, - self.get_radio_group() + self.get_radio_group_name() .as_ref() .map(|group| group.as_slice())); } @@ -419,16 +483,13 @@ impl<'a> VirtualMethods for JSRef<'a, HTMLInputElement> { if "click" == event.Type().as_slice() && !event.DefaultPrevented() { match self.input_type.get() { - InputCheckbox => self.SetChecked(!self.checked.get()), InputRadio => self.SetChecked(true), - InputButton(Some(DEFAULT_SUBMIT_VALUE)) => { - self.form_owner().map(|o| { - o.root().submit(NotFromFormSubmitMethod, InputElement(self.clone())) - }); - } _ => {} } + // TODO: Dispatch events for non activatable inputs + // https://html.spec.whatwg.org/multipage/forms.html#common-input-element-events + //TODO: set the editing position for text inputs let doc = document_from_node(*self).root(); @@ -455,7 +516,7 @@ impl Reflectable for HTMLInputElement { } } -impl<'a> FormOwner<'a> for JSRef<'a, HTMLInputElement> { +impl<'a> FormControl<'a> for JSRef<'a, HTMLInputElement> { // FIXME: This is wrong (https://github.com/servo/servo/issues/3553) // but we need html5ever to do it correctly fn form_owner(self) -> Option> { @@ -483,4 +544,168 @@ impl<'a> FormOwner<'a> for JSRef<'a, HTMLInputElement> { fn to_element(self) -> JSRef<'a, Element> { ElementCast::from_ref(self) } + + // https://html.spec.whatwg.org/multipage/forms.html#concept-fe-mutable + fn mutable(self) -> bool { + // https://html.spec.whatwg.org/multipage/forms.html#the-input-element:concept-fe-mutable + // https://html.spec.whatwg.org/multipage/forms.html#the-readonly-attribute:concept-fe-mutable + !(self.Disabled() || self.ReadOnly()) + } +} + + +impl<'a> Activatable for JSRef<'a, HTMLInputElement> { + fn as_element(&self) -> Temporary { + Temporary::from_rooted(ElementCast::from_ref(*self)) + } + + // https://html.spec.whatwg.org/multipage/interaction.html#run-pre-click-activation-steps + fn pre_click_activation(&self) { + let mut cache = self.activation_state.borrow_mut(); + let ty = self.input_type.get(); + cache.old_type = ty; + cache.was_mutable = self.mutable(); + if cache.was_mutable { + match ty { + // https://html.spec.whatwg.org/multipage/forms.html#submit-button-state-(type=submit):activation-behavior + // InputSubmit => (), // No behavior defined + InputCheckbox => { + // https://html.spec.whatwg.org/multipage/forms.html#checkbox-state-(type=checkbox):pre-click-activation-steps + // cache current values of `checked` and `indeterminate` + // we may need to restore them later + cache.indeterminate = self.Indeterminate(); + cache.checked = self.Checked(); + self.SetIndeterminate(false); + self.SetChecked(!cache.checked); + }, + // https://html.spec.whatwg.org/multipage/forms.html#radio-button-state-(type=radio):pre-click-activation-steps + InputRadio => { + //TODO: if not in document, use root ancestor instead of document + let owner = self.form_owner().root(); + let doc = document_from_node(*self).root(); + let doc_node: JSRef = NodeCast::from_ref(*doc); + let group = self.get_radio_group_name();; + + // Safe since we only manipulate the DOM tree after finding an element + let checked_member = unsafe { + doc_node.query_selector_iter("input[type=radio]".to_string()).unwrap() + .filter_map(|t| HTMLInputElementCast::to_ref(t)) + .filter(|&r| in_same_group(r, owner.root_ref(), + group.as_ref().map(|gr| gr.as_slice()))) + .find(|r| r.Checked()) + }; + cache.checked_radio.assign(checked_member); + self.SetChecked(true); + } + _ => () + } + } + } + + // https://html.spec.whatwg.org/multipage/interaction.html#run-canceled-activation-steps + fn canceled_activation(&self) { + let cache = self.activation_state.borrow(); + let ty = self.input_type.get(); + if cache.old_type != ty { + // Type changed, abandon ship + // https://www.w3.org/Bugs/Public/show_bug.cgi?id=27414 + return; + } + match ty { + // https://html.spec.whatwg.org/multipage/forms.html#submit-button-state-(type=submit):activation-behavior + // InputSubmit => (), // No behavior defined + // https://html.spec.whatwg.org/multipage/forms.html#checkbox-state-(type=checkbox):canceled-activation-steps + InputCheckbox => { + // We want to restore state only if the element had been changed in the first place + if cache.was_mutable { + self.SetIndeterminate(cache.indeterminate); + self.SetChecked(cache.checked); + } + }, + // https://html.spec.whatwg.org/multipage/forms.html#radio-button-state-(type=radio):canceled-activation-steps + InputRadio => { + // We want to restore state only if the element had been changed in the first place + if cache.was_mutable { + let old_checked: Option> = cache.checked_radio.get().root(); + let name = self.get_radio_group_name(); + match old_checked { + Some(o) => { + // Avoiding iterating through the whole tree here, instead + // we can check if the conditions for radio group siblings apply + if name == o.get_radio_group_name() && // TODO should be compatibility caseless + self.form_owner() == o.form_owner() && + // TODO Both a and b are in the same home subtree + o.input_type.get() == InputRadio { + o.SetChecked(true); + } else { + self.SetChecked(false); + } + }, + None => self.SetChecked(false) + }; + } + } + _ => () + } + } + + // https://html.spec.whatwg.org/multipage/interaction.html#run-post-click-activation-steps + fn activation_behavior(&self) { + let ty = self.input_type.get(); + if self.activation_state.borrow().old_type != ty { + // Type changed, abandon ship + // https://www.w3.org/Bugs/Public/show_bug.cgi?id=27414 + return; + } + match ty { + InputSubmit => { + // https://html.spec.whatwg.org/multipage/forms.html#submit-button-state-(type=submit):activation-behavior + // FIXME (Manishearth): support document owners (needs ability to get parent browsing context) + if self.mutable() /* and document owner is fully active */ { + self.form_owner().map(|o| { + o.root().submit(NotFromFormSubmitMethod, InputElement(self.clone())) + }); + } + }, + InputCheckbox | InputRadio => { + // https://html.spec.whatwg.org/multipage/forms.html#checkbox-state-(type=checkbox):activation-behavior + // https://html.spec.whatwg.org/multipage/forms.html#radio-button-state-(type=radio):activation-behavior + if self.mutable() { + let win = window_from_node(*self).root(); + let event = Event::new(Window(*win), + "input".to_string(), + Bubbles, NotCancelable).root(); + event.set_trusted(true); + let target: JSRef = EventTargetCast::from_ref(*self); + target.DispatchEvent(*event).ok(); + + let event = Event::new(Window(*win), + "change".to_string(), + Bubbles, NotCancelable).root(); + event.set_trusted(true); + let target: JSRef = EventTargetCast::from_ref(*self); + target.DispatchEvent(*event).ok(); + } + }, + _ => () + } + } + + // https://html.spec.whatwg.org/multipage/forms.html#implicit-submission + fn implicit_submission(&self, ctrlKey: bool, shiftKey: bool, altKey: bool, metaKey: bool) { + let doc = document_from_node(*self).root(); + let node: JSRef = NodeCast::from_ref(*doc); + let owner = self.form_owner(); + if owner.is_none() || ElementCast::from_ref(*self).click_in_progress() { + return; + } + // This is safe because we are stopping after finding the first element + // and only then performing actions which may modify the DOM tree + unsafe { + node.query_selector_iter("input[type=submit]".to_string()).unwrap() + .filter_map(|t| HTMLInputElementCast::to_ref(t)) + .find(|r| r.form_owner() == owner) + .map(|s| s.synthetic_click_activation(ctrlKey, shiftKey, altKey, metaKey)); + } + } } diff --git a/servo/components/script/dom/macros.rs b/servo/components/script/dom/macros.rs index 630a112c0320..a5789a5cc61a 100644 --- a/servo/components/script/dom/macros.rs +++ b/servo/components/script/dom/macros.rs @@ -211,3 +211,19 @@ macro_rules! error_event_handler( define_event_handler!(OnErrorEventHandlerNonNull, $event_type, $getter, $setter) ) ) + +// https://html.spec.whatwg.org/multipage/webappapis.html#globaleventhandlers +// see webidls/EventHandler.webidl +// As more methods get added, just update them here. +macro_rules! global_event_handlers( + () => ( + event_handler!(load, GetOnload, SetOnload) + global_event_handlers!(NoOnload) + + ); + (NoOnload) => ( + event_handler!(click, GetOnclick, SetOnclick) + event_handler!(input, GetOninput, SetOninput) + event_handler!(change, GetOnchange, SetOnchange) + ) +) diff --git a/servo/components/script/dom/node.rs b/servo/components/script/dom/node.rs index 2c02ebc9b1ec..ef655cc1bc36 100644 --- a/servo/components/script/dom/node.rs +++ b/servo/components/script/dom/node.rs @@ -50,7 +50,7 @@ use devtools_traits::NodeInfo; use script_traits::UntrustedNodeAddress; use servo_util::geometry::Au; use servo_util::str::{DOMString, null_str_as_empty}; -use style::{parse_selector_list_from_str, matches}; +use style::{parse_selector_list_from_str, matches, SelectorList}; use js::jsapi::{JSContext, JSObject, JSTracer, JSRuntime}; use js::jsfriendapi; @@ -124,7 +124,7 @@ impl NodeDerived for EventTarget { bitflags! { #[doc = "Flags for node items."] #[jstraceable] - flags NodeFlags: u8 { + flags NodeFlags: u16 { #[doc = "Specifies whether this node is in a document."] const IS_IN_DOC = 0x01, #[doc = "Specifies whether this node is in hover state."] @@ -143,6 +143,12 @@ bitflags! { #[doc = "Specifies whether this node has descendants (inclusive of itself) which \ have changed since the last reflow."] const HAS_DIRTY_DESCENDANTS = 0x80, + // TODO: find a better place to keep this (#4105) + // https://critic.hoppipolla.co.uk/showcomment?chain=8873 + // Perhaps using a Set in Document? + #[doc = "Specifies whether or not there is an authentic click in progress on \ + this element."] + const CLICK_IN_PROGRESS = 0x100, } } @@ -377,6 +383,29 @@ impl<'a> PrivateNodeHelpers for JSRef<'a, Node> { } } +pub struct QuerySelectorIterator<'a> { + selectors: SelectorList, + iterator: TreeIterator<'a>, +} + +impl<'a> QuerySelectorIterator<'a> { + unsafe fn new(iter: TreeIterator<'a>, selectors: SelectorList) -> QuerySelectorIterator<'a> { + QuerySelectorIterator { + selectors: selectors, + iterator: iter, + } + } +} + +impl<'a> Iterator> for QuerySelectorIterator<'a> { + fn next(&mut self) -> Option> { + let selectors = &self.selectors; + // TODO(cgaebel): Is it worth it to build a bloom filter here + // (instead of passing `None`)? Probably. + self.iterator.find(|node| node.is_element() && matches(selectors, node, &mut None)) + } +} + pub trait NodeHelpers<'a> { fn ancestors(self) -> AncestorIterator<'a>; fn children(self) -> NodeChildrenIterator<'a>; @@ -449,6 +478,7 @@ pub trait NodeHelpers<'a> { fn get_content_boxes(self) -> Vec>; fn query_selector(self, selectors: DOMString) -> Fallible>>; + unsafe fn query_selector_iter(self, selectors: DOMString) -> Fallible>; fn query_selector_all(self, selectors: DOMString) -> Fallible>; fn remove_self(self); @@ -719,8 +749,10 @@ impl<'a> NodeHelpers<'a> for JSRef<'a, Node> { Ok(None) } - // http://dom.spec.whatwg.org/#dom-parentnode-queryselectorall - fn query_selector_all(self, selectors: DOMString) -> Fallible> { + /// Get an iterator over all nodes which match a set of selectors + /// Be careful not to do anything which may manipulate the DOM tree whilst iterating, otherwise + /// the iterator may be invalidated + unsafe fn query_selector_iter(self, selectors: DOMString) -> Fallible> { // Step 1. let nodes; let root = self.ancestors().last().unwrap_or(self.clone()); @@ -728,17 +760,25 @@ impl<'a> NodeHelpers<'a> for JSRef<'a, Node> { // Step 2. Err(()) => return Err(Syntax), // Step 3. - Ok(ref selectors) => { - nodes = root.traverse_preorder().filter( - // TODO(cgaebel): Is it worth it to build a bloom filter here - // (instead of passing `None`)? Probably. - |node| node.is_element() && matches(selectors, node, &mut None)).collect() + Ok(selectors) => { + nodes = QuerySelectorIterator::new(root.traverse_preorder(), selectors); } - } - let window = window_from_node(self).root(); - Ok(NodeList::new_simple_list(*window, nodes)) + }; + Ok(nodes) } + // http://dom.spec.whatwg.org/#dom-parentnode-queryselectorall + fn query_selector_all(self, selectors: DOMString) -> Fallible> { + // Step 1. + unsafe { + self.query_selector_iter(selectors).map(|mut iter| { + let window = window_from_node(self).root(); + NodeList::new_simple_list(*window, iter.collect()) + }) + } + } + + fn ancestors(self) -> AncestorIterator<'a> { AncestorIterator { current: self.parent_node.get().map(|node| (*node.root()).clone()), diff --git a/servo/components/script/dom/webidls/EventHandler.webidl b/servo/components/script/dom/webidls/EventHandler.webidl index 1278d7467fd6..de4914553023 100644 --- a/servo/components/script/dom/webidls/EventHandler.webidl +++ b/servo/components/script/dom/webidls/EventHandler.webidl @@ -23,6 +23,8 @@ typedef OnErrorEventHandlerNonNull? OnErrorEventHandler; interface GlobalEventHandlers { attribute EventHandler onclick; attribute EventHandler onload; + attribute EventHandler oninput; + attribute EventHandler onchange; }; [NoInterfaceObject] diff --git a/servo/components/script/dom/webidls/HTMLElement.webidl b/servo/components/script/dom/webidls/HTMLElement.webidl index 10be66c62e3d..359ef11f0a77 100644 --- a/servo/components/script/dom/webidls/HTMLElement.webidl +++ b/servo/components/script/dom/webidls/HTMLElement.webidl @@ -23,7 +23,7 @@ interface HTMLElement : Element { // user interaction attribute boolean hidden; - //void click(); + void click(); // attribute long tabIndex; //void focus(); //void blur(); diff --git a/servo/components/script/dom/webidls/HTMLInputElement.webidl b/servo/components/script/dom/webidls/HTMLInputElement.webidl index b69d8fcf4ff6..434da309f210 100644 --- a/servo/components/script/dom/webidls/HTMLInputElement.webidl +++ b/servo/components/script/dom/webidls/HTMLInputElement.webidl @@ -21,7 +21,7 @@ interface HTMLInputElement : HTMLElement { // attribute boolean formNoValidate; attribute DOMString formTarget; // attribute unsigned long height; - // attribute boolean indeterminate; + attribute boolean indeterminate; // attribute DOMString inputMode; //readonly attribute HTMLElement? list; // attribute DOMString max; @@ -32,7 +32,7 @@ interface HTMLInputElement : HTMLElement { attribute DOMString name; // attribute DOMString pattern; // attribute DOMString placeholder; - // attribute boolean readOnly; + attribute boolean readOnly; // attribute boolean required; attribute unsigned long size; // attribute DOMString src; diff --git a/servo/components/script/dom/window.rs b/servo/components/script/dom/window.rs index 0e6e00ed2006..da0cc228b0a6 100644 --- a/servo/components/script/dom/window.rs +++ b/servo/components/script/dom/window.rs @@ -270,8 +270,7 @@ impl<'a> WindowMethods for JSRef<'a, Window> { self.performance.or_init(|| Performance::new(self)) } - event_handler!(click, GetOnclick, SetOnclick) - event_handler!(load, GetOnload, SetOnload) + global_event_handlers!() event_handler!(unload, GetOnunload, SetOnunload) error_event_handler!(error, GetOnerror, SetOnerror) diff --git a/servo/components/script/lib.rs b/servo/components/script/lib.rs index 6edcb72ae45f..de1ddbe59879 100644 --- a/servo/components/script/lib.rs +++ b/servo/components/script/lib.rs @@ -82,6 +82,7 @@ pub mod dom { #[path="bindings/codegen/InterfaceTypes.rs"] pub mod types; + pub mod activation; pub mod attr; pub mod blob; pub mod browsercontext; diff --git a/servo/components/script/script_task.rs b/servo/components/script/script_task.rs index fdd4795ab252..28c7c2e8a0b9 100644 --- a/servo/components/script/script_task.rs +++ b/servo/components/script/script_task.rs @@ -10,7 +10,7 @@ use dom::bindings::codegen::Bindings::DocumentBinding::{DocumentMethods, Documen use dom::bindings::codegen::Bindings::EventBinding::EventMethods; use dom::bindings::codegen::Bindings::EventTargetBinding::EventTargetMethods; use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; -use dom::bindings::codegen::InheritTypes::{EventTargetCast, NodeCast, EventCast}; +use dom::bindings::codegen::InheritTypes::{ElementCast, EventTargetCast, NodeCast, EventCast}; use dom::bindings::conversions::{FromJSValConvertible, Empty}; use dom::bindings::global; use dom::bindings::js::{JS, JSRef, RootCollection, Temporary, OptionalRootable}; @@ -18,8 +18,8 @@ use dom::bindings::trace::JSTraceable; use dom::bindings::utils::{wrap_for_same_compartment, pre_wrap}; use dom::document::{Document, HTMLDocument, DocumentHelpers, FromParser}; use dom::element::{Element, HTMLButtonElementTypeId, HTMLInputElementTypeId}; -use dom::element::{HTMLSelectElementTypeId, HTMLTextAreaElementTypeId, HTMLOptionElementTypeId}; -use dom::event::{Event, Bubbles, DoesNotBubble, Cancelable, NotCancelable}; +use dom::element::{HTMLSelectElementTypeId, HTMLTextAreaElementTypeId, HTMLOptionElementTypeId, ActivationElementHelpers}; +use dom::event::{Event, EventHelpers, Bubbles, DoesNotBubble, Cancelable, NotCancelable}; use dom::uievent::UIEvent; use dom::eventtarget::{EventTarget, EventTargetHelpers}; use dom::keyboardevent::KeyboardEvent; @@ -893,9 +893,10 @@ impl ScriptTask { None, props.key_code).root(); let event = EventCast::from_ref(*keyevent); let _ = target.DispatchEvent(event); + let mut prevented = event.DefaultPrevented(); // https://dvcs.w3.org/hg/dom3events/raw-file/tip/html/DOM3-Events.html#keys-cancelable-keys - if state != Released && props.is_printable() && !event.DefaultPrevented() { + if state != Released && props.is_printable() && !prevented { // https://dvcs.w3.org/hg/dom3events/raw-file/tip/html/DOM3-Events.html#keypress-event-order let event = KeyboardEvent::new(*window, "keypress".to_string(), true, true, Some(*window), 0, props.key.to_string(), props.code.to_string(), @@ -904,9 +905,28 @@ impl ScriptTask { props.char_code, 0).root(); let _ = target.DispatchEvent(EventCast::from_ref(*event)); + let ev = EventCast::from_ref(*event); + prevented = ev.DefaultPrevented(); // TODO: if keypress event is canceled, prevent firing input events } + // This behavior is unspecced + // We are supposed to dispatch synthetic click activation for Space and/or Return, + // however *when* we do it is up to us + // I'm dispatching it after the key event so the script has a chance to cancel it + // https://www.w3.org/Bugs/Public/show_bug.cgi?id=27337 + match key { + Key::KeySpace if !prevented && state == Released => { + let maybe_elem: Option> = ElementCast::to_ref(target); + maybe_elem.map(|el| el.as_maybe_activatable().map(|a| a.synthetic_click_activation(ctrl, alt, shift, meta))); + } + Key::KeyEnter if !prevented && state == Released => { + let maybe_elem: Option> = ElementCast::to_ref(target); + maybe_elem.map(|el| el.as_maybe_activatable().map(|a| a.implicit_submission(ctrl, alt, shift, meta))); + } + _ => () + } + window.flush_layout(); } @@ -1018,8 +1038,11 @@ impl ScriptTask { Event::new(global::Window(*window), "click".to_string(), Bubbles, Cancelable).root(); - let eventtarget: JSRef = EventTargetCast::from_ref(node); - let _ = eventtarget.dispatch_event_with_target(None, *event); + // https://dvcs.w3.org/hg/dom3events/raw-file/tip/html/DOM3-Events.html#trusted-events + event.set_trusted(true); + // https://html.spec.whatwg.org/multipage/interaction.html#run-authentic-click-activation-steps + let el = ElementCast::to_ref(node).unwrap(); // is_element() check already exists above + el.authentic_click_activation(*event); doc.commit_focus_transaction(); window.flush_layout(); diff --git a/servo/tests/html/test-synthetic-click-activation.html b/servo/tests/html/test-synthetic-click-activation.html new file mode 100644 index 000000000000..011914895a7a --- /dev/null +++ b/servo/tests/html/test-synthetic-click-activation.html @@ -0,0 +1,31 @@ + +
+
+
+
+
+
group 1 +
+
+
+
group 2 +
+
+
+
+
+Use the buttons below to shift "fake" focus and trigger click events. The first form widget is initually focused. +
+
+
+
+ + +