Skip to main content

script/dom/mathml/
mathmlelement.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/. */
4
5use dom_struct::dom_struct;
6use html5ever::{LocalName, Prefix, local_name, ns};
7use js::context::JSContext;
8use js::rust::HandleObject;
9use script_bindings::codegen::GenericBindings::ElementBinding::ScrollLogicalPosition;
10use script_bindings::codegen::GenericBindings::WindowBinding::ScrollBehavior;
11use script_bindings::str::DOMString;
12use style::parser::ParserContext;
13use style::properties::{PropertyDeclaration, longhands};
14use style::stylesheets::{CssRuleType, Origin, UrlExtraData};
15use style::values::specified::FontSize;
16use style_traits::ParsingMode;
17use stylo_dom::ElementState;
18
19use crate::dom::bindings::codegen::Bindings::HTMLOrSVGOrMathMLElementBinding::FocusOptions;
20use crate::dom::bindings::codegen::Bindings::MathMLElementBinding::MathMLElementMethods;
21use crate::dom::bindings::inheritance::Castable;
22use crate::dom::bindings::root::{DomRoot, LayoutDom, MutNullableDom};
23use crate::dom::document::Document;
24use crate::dom::document::focus::FocusableArea;
25use crate::dom::domstringmap::DOMStringMap;
26use crate::dom::element::attributes::storage::AttrRef;
27use crate::dom::element::{AttributeMutation, Element};
28use crate::dom::node::focus::FocusTrigger;
29use crate::dom::node::virtualmethods::VirtualMethods;
30use crate::dom::node::{Node, NodeTraits};
31use crate::dom::window::scrolling_box::{ScrollAxisState, ScrollRequirement};
32
33#[dom_struct]
34pub(crate) struct MathMLElement {
35    element: Element,
36    dataset: MutNullableDom<DOMStringMap>,
37}
38
39/// <https://w3c.github.io/mathml-core/#dom-mathmlelement>
40impl MathMLElement {
41    pub(crate) fn new_inherited(
42        tag_name: LocalName,
43        prefix: Option<Prefix>,
44        document: &Document,
45    ) -> MathMLElement {
46        MathMLElement {
47            element: Element::new_inherited_with_state(
48                ElementState::empty(),
49                tag_name,
50                ns!(mathml),
51                prefix,
52                document,
53            ),
54            dataset: Default::default(),
55        }
56    }
57
58    pub(crate) fn new(
59        cx: &mut JSContext,
60        tag_name: LocalName,
61        prefix: Option<Prefix>,
62        document: &Document,
63        proto: Option<HandleObject>,
64    ) -> DomRoot<MathMLElement> {
65        Node::reflect_node_with_proto(
66            cx,
67            Box::new(MathMLElement::new_inherited(tag_name, prefix, document)),
68            document,
69            proto,
70        )
71    }
72
73    fn as_element(&self) -> &Element {
74        self.upcast::<Element>()
75    }
76}
77
78impl VirtualMethods for MathMLElement {
79    fn super_type(&self) -> Option<&dyn VirtualMethods> {
80        Some(self.as_element() as &dyn VirtualMethods)
81    }
82
83    fn attribute_mutated(
84        &self,
85        cx: &mut JSContext,
86        attr: AttrRef<'_>,
87        mutation: AttributeMutation,
88    ) {
89        self.super_type()
90            .unwrap()
91            .attribute_mutated(cx, attr, mutation);
92
93        let element = self.as_element();
94        if let (&local_name!("nonce"), mutation) = (attr.local_name(), mutation) {
95            match mutation {
96                AttributeMutation::Set(..) => {
97                    let nonce = &**attr.value();
98                    element.update_nonce_internal_slot(nonce.to_owned(), cx.no_gc());
99                },
100                AttributeMutation::Removed => {
101                    element.update_nonce_internal_slot(String::new(), cx.no_gc());
102                },
103            }
104        }
105    }
106
107    fn attribute_affects_presentational_hints(&self, attr: AttrRef<'_>) -> bool {
108        // TODO(tannal) Add `displaystyle` and `scriptlevel`.
109        match attr.local_name() {
110            &local_name!("mathcolor") |
111            &local_name!("mathbackground") |
112            &local_name!("mathsize") |
113            &local_name!("dir") => true,
114            _ => self
115                .super_type()
116                .unwrap()
117                .attribute_affects_presentational_hints(attr),
118        }
119    }
120}
121
122impl<'dom> LayoutDom<'dom, MathMLElement> {
123    /// Synthesizes presentational hints for MathML attributes that map directly to CSS properties.
124    /// <https://w3c.github.io/mathml-core/#css-styling>
125    /// <https://w3c.github.io/mathml-core/#global-attributes>
126    pub(crate) fn synthesize_presentational_hints(
127        self,
128        document: LayoutDom<'dom, Document>,
129        push: &mut impl FnMut(PropertyDeclaration),
130    ) {
131        let url_data = UrlExtraData(document.url_for_layout().get_arc());
132        let parsing_mode =
133            ParsingMode::ALLOW_UNITLESS_LENGTH | ParsingMode::ALLOW_ALL_NUMERIC_VALUES;
134
135        let parser_context = ParserContext::new(
136            Origin::Author,
137            &url_data,
138            Some(CssRuleType::Style),
139            parsing_mode,
140            document.quirks_mode(),
141            Default::default(),
142            None,
143            None,
144            Default::default(),
145        );
146
147        // Standard MathML Core presentational hints
148        // TODO(tannal) Add `displaystyle` and `scriptlevel`.
149        // https://w3c.github.io/mathml-core/#dfn-mathcolor
150        // https://w3c.github.io/mathml-core/#dfn-mathbackground
151        // > In that case, the user agent is expected to treat
152        // > these attributes as a presentational hint setting the element's
153        // > color and background-color properties to the corresponding values.
154        self.parse_mathml_attribute(
155            &parser_context,
156            "mathcolor",
157            longhands::color::parse_declared,
158            push,
159        );
160        self.parse_mathml_attribute(
161            &parser_context,
162            "mathbackground",
163            longhands::background_color::parse_declared,
164            push,
165        );
166
167        // https://w3c.github.io/mathml-core/#dfn-mathsize
168        // > In that case, the user agent is expected to treat
169        // > the attribute as a presentational hint setting the element's
170        // > font-size property to the corresponding value.
171        // We should only accept <length-percentage> value.
172        self.parse_mathml_attribute_matching(
173            &parser_context,
174            "mathsize",
175            |decl| {
176                matches!(
177                    decl,
178                    PropertyDeclaration::FontSize(size)
179                        if matches!(size, FontSize::Length(..))
180                )
181            },
182            longhands::font_size::parse_declared,
183            push,
184        );
185        // https://w3c.github.io/mathml-core/#dfn-dir
186        // > if present, must be an ASCII case-insensitive match to ltr or rtl.
187        // > In that case, the user agent is expected to treat
188        // > the attribute as a presentational hint setting the element's
189        // > direction property to the corresponding value.
190        self.parse_mathml_attribute(
191            &parser_context,
192            "dir",
193            longhands::direction::parse_declared,
194            push,
195        );
196    }
197
198    fn parse_mathml_attribute<F>(
199        self,
200        parser_context: &ParserContext,
201        attr_name: &str,
202        parse: F,
203        push: &mut impl FnMut(PropertyDeclaration),
204    ) where
205        F: for<'i> FnOnce(
206            &ParserContext,
207            &mut cssparser::Parser<'i>,
208        ) -> Result<PropertyDeclaration, style_traits::ParseError>,
209    {
210        self.parse_mathml_attribute_matching(parser_context, attr_name, |_| true, parse, push)
211    }
212
213    fn parse_mathml_attribute_matching<P, F>(
214        self,
215        parser_context: &ParserContext,
216        attr_name: &str,
217        predicate: P,
218        parse: F,
219        push: &mut impl FnMut(PropertyDeclaration),
220    ) where
221        P: FnOnce(&PropertyDeclaration) -> bool,
222        F: for<'i> FnOnce(
223            &ParserContext,
224            &mut cssparser::Parser<'i>,
225        ) -> Result<PropertyDeclaration, style_traits::ParseError>,
226    {
227        let element = self.upcast::<Element>();
228        if let Some(value) = element.get_attr_val_for_layout(&ns!(), &LocalName::from(attr_name)) {
229            let mut parser = cssparser::Parser::new(value);
230            if let Ok(property) =
231                parser.parse_entirely(|parse_input| parse(parser_context, parse_input)) &&
232                predicate(&property)
233            {
234                push(property);
235            }
236        }
237    }
238}
239
240impl MathMLElementMethods<crate::DomTypeHolder> for MathMLElement {
241    global_event_handlers!();
242
243    /// <https://html.spec.whatwg.org/multipage/#dom-dataset>
244    fn Dataset(&self, cx: &mut JSContext) -> DomRoot<DOMStringMap> {
245        self.dataset
246            .or_init(|| DOMStringMap::new(cx, self.upcast()))
247    }
248
249    /// <https://html.spec.whatwg.org/multipage/#dom-noncedelement-nonce>
250    fn Nonce(&self) -> DOMString {
251        self.as_element().nonce_value().into()
252    }
253
254    /// <https://html.spec.whatwg.org/multipage/#dom-noncedelement-nonce>
255    fn SetNonce(&self, cx: &mut JSContext, value: DOMString) {
256        self.as_element()
257            .update_nonce_internal_slot(String::from(value), cx.no_gc());
258    }
259
260    // <https://html.spec.whatwg.org/multipage/#dom-fe-autofocus>
261    make_bool_getter!(Autofocus, "autofocus");
262
263    // <https://html.spec.whatwg.org/multipage/#dom-fe-autofocus>
264    make_bool_setter!(SetAutofocus, "autofocus");
265
266    /// <https://html.spec.whatwg.org/multipage/#dom-focus>
267    fn Focus(&self, cx: &mut JSContext, options: &FocusOptions) {
268        if !self
269            .upcast::<Node>()
270            .run_the_focusing_steps(cx, None, FocusTrigger::Script)
271        {
272            return;
273        }
274
275        if !options.preventScroll {
276            let scroll_axis = ScrollAxisState {
277                position: ScrollLogicalPosition::Center,
278                requirement: ScrollRequirement::IfNotVisible,
279            };
280            self.upcast::<Element>().scroll_into_view_with_options(
281                cx,
282                ScrollBehavior::Smooth,
283                scroll_axis,
284                scroll_axis,
285                None,
286                None,
287            );
288        }
289    }
290
291    /// <https://html.spec.whatwg.org/multipage/#dom-blur>
292    fn Blur(&self, cx: &mut JSContext) {
293        if !self.as_element().focus_state() {
294            return;
295        }
296        self.owner_document().focus_handler().focus(
297            cx,
298            &FocusableArea::Viewport,
299            FocusTrigger::Script,
300        );
301    }
302
303    /// <https://html.spec.whatwg.org/multipage/#dom-tabindex>
304    fn TabIndex(&self) -> i32 {
305        self.element.tab_index()
306    }
307
308    /// <https://html.spec.whatwg.org/multipage/#dom-tabindex>
309    fn SetTabIndex(&self, cx: &mut JSContext, tab_index: i32) {
310        self.element
311            .set_attribute(cx, &local_name!("tabindex"), tab_index.into());
312    }
313}