Skip to main content

script/dom/svg/
svgelement.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::attr::AttrValue;
13use style::parser::ParserContext;
14use style::properties::{PropertyDeclaration, longhands};
15use style::stylesheets::{CssRuleType, Origin, UrlExtraData};
16use style::values::generics::NonNegative;
17use style::values::specified;
18use style_traits::ParsingMode;
19use stylo_dom::ElementState;
20
21use crate::dom::bindings::codegen::Bindings::HTMLOrSVGOrMathMLElementBinding::FocusOptions;
22use crate::dom::bindings::codegen::Bindings::SVGElementBinding::SVGElementMethods;
23use crate::dom::bindings::inheritance::Castable;
24use crate::dom::bindings::root::{Dom, DomRoot, LayoutDom, MutNullableDom};
25use crate::dom::css::cssstyledeclaration::{
26    CSSModificationAccess, CSSStyleDeclaration, CSSStyleOwner,
27};
28use crate::dom::document::Document;
29use crate::dom::document::focus::FocusableArea;
30use crate::dom::domstringmap::DOMStringMap;
31use crate::dom::element::attributes::storage::AttrRef;
32use crate::dom::element::{AttributeMutation, Element};
33use crate::dom::node::focus::FocusTrigger;
34use crate::dom::node::virtualmethods::VirtualMethods;
35use crate::dom::node::{Node, NodeTraits};
36use crate::dom::svg::svgcircleelement::SVGCircleElement;
37use crate::dom::svg::svgellipseelement::SVGEllipseElement;
38use crate::dom::svg::svgimageelement::SVGImageElement;
39use crate::dom::svg::svgpathelement::SVGPathElement;
40use crate::dom::svg::svgrectelement::SVGRectElement;
41use crate::dom::svg::svgsvgelement::SVGSVGElement;
42use crate::dom::window::scrolling_box::{ScrollAxisState, ScrollRequirement};
43
44#[dom_struct]
45pub(crate) struct SVGElement {
46    element: Element,
47    style_decl: MutNullableDom<CSSStyleDeclaration>,
48    dataset: MutNullableDom<DOMStringMap>,
49}
50
51impl SVGElement {
52    fn new_inherited(
53        tag_name: LocalName,
54        prefix: Option<Prefix>,
55        document: &Document,
56    ) -> SVGElement {
57        SVGElement::new_inherited_with_state(ElementState::empty(), tag_name, prefix, document)
58    }
59
60    pub(crate) fn new_inherited_with_state(
61        state: ElementState,
62        tag_name: LocalName,
63        prefix: Option<Prefix>,
64        document: &Document,
65    ) -> SVGElement {
66        SVGElement {
67            element: Element::new_inherited_with_state(state, tag_name, ns!(svg), prefix, document),
68            style_decl: Default::default(),
69            dataset: Default::default(),
70        }
71    }
72
73    pub(crate) fn new(
74        cx: &mut js::context::JSContext,
75        tag_name: LocalName,
76        prefix: Option<Prefix>,
77        document: &Document,
78        proto: Option<HandleObject>,
79    ) -> DomRoot<SVGElement> {
80        Node::reflect_node_with_proto(
81            cx,
82            Box::new(SVGElement::new_inherited(tag_name, prefix, document)),
83            document,
84            proto,
85        )
86    }
87
88    fn as_element(&self) -> &Element {
89        self.upcast::<Element>()
90    }
91}
92
93impl VirtualMethods for SVGElement {
94    fn super_type(&self) -> Option<&dyn VirtualMethods> {
95        Some(self.as_element() as &dyn VirtualMethods)
96    }
97
98    fn attribute_mutated(
99        &self,
100        cx: &mut js::context::JSContext,
101        attr: AttrRef<'_>,
102        mutation: AttributeMutation,
103    ) {
104        self.super_type()
105            .unwrap()
106            .attribute_mutated(cx, attr, mutation);
107        let element = self.as_element();
108        if let (&local_name!("nonce"), mutation) = (attr.local_name(), mutation) {
109            match mutation {
110                AttributeMutation::Set(_) => {
111                    let nonce = &**attr.value();
112                    element.update_nonce_internal_slot(nonce.to_owned(), cx.no_gc());
113                },
114                AttributeMutation::Removed => {
115                    element.update_nonce_internal_slot(String::new(), cx.no_gc());
116                },
117            }
118        }
119    }
120
121    fn attribute_affects_presentational_hints(&self, attr: AttrRef<'_>) -> bool {
122        matches!(
123            attr.local_name(),
124            &local_name!("fill") |
125                &local_name!("fill-opacity") |
126                &local_name!("fill-rule") |
127                &local_name!("stroke") |
128                &local_name!("stroke-width") |
129                &local_name!("stroke-linecap") |
130                &local_name!("stroke-linejoin") |
131                &local_name!("stroke-dasharray") |
132                &local_name!("stroke-dashoffset") |
133                &local_name!("stroke-miterlimit") |
134                &local_name!("stroke-opacity") |
135                &local_name!("display") |
136                &local_name!("visibility") |
137                &local_name!("opacity") |
138                &local_name!("cx") |
139                &local_name!("cy") |
140                &local_name!("r") |
141                &local_name!("rx") |
142                &local_name!("ry") |
143                &local_name!("x") |
144                &local_name!("y") |
145                &local_name!("width") |
146                &local_name!("height") |
147                &local_name!("d")
148        ) || self
149            .super_type()
150            .unwrap()
151            .attribute_affects_presentational_hints(attr)
152    }
153}
154
155impl SVGElementMethods<crate::DomTypeHolder> for SVGElement {
156    /// <https://html.spec.whatwg.org/multipage/#the-style-attribute>
157    fn Style(&self, cx: &mut JSContext) -> DomRoot<CSSStyleDeclaration> {
158        self.style_decl.or_init(|| {
159            let global = self.owner_window();
160            CSSStyleDeclaration::new(
161                cx,
162                &global,
163                CSSStyleOwner::Element(Dom::from_ref(self.upcast())),
164                None,
165                CSSModificationAccess::ReadWrite,
166            )
167        })
168    }
169
170    // https://html.spec.whatwg.org/multipage/#globaleventhandlers
171    global_event_handlers!();
172
173    /// <https://html.spec.whatwg.org/multipage/#dom-dataset>
174    fn Dataset(&self, cx: &mut JSContext) -> DomRoot<DOMStringMap> {
175        self.dataset
176            .or_init(|| DOMStringMap::new(cx, self.upcast()))
177    }
178
179    /// <https://html.spec.whatwg.org/multipage/#dom-noncedelement-nonce>
180    fn Nonce(&self) -> DOMString {
181        self.as_element().nonce_value().into()
182    }
183
184    /// <https://html.spec.whatwg.org/multipage/#dom-noncedelement-nonce>
185    fn SetNonce(&self, cx: &mut JSContext, value: DOMString) {
186        self.as_element()
187            .update_nonce_internal_slot(String::from(value), cx.no_gc())
188    }
189
190    /// <https://html.spec.whatwg.org/multipage/#dom-fe-autofocus>
191    fn Autofocus(&self) -> bool {
192        self.element.has_attribute(&local_name!("autofocus"))
193    }
194
195    /// <https://html.spec.whatwg.org/multipage/#dom-fe-autofocus>
196    fn SetAutofocus(&self, cx: &mut JSContext, autofocus: bool) {
197        self.element
198            .set_bool_attribute(cx, &local_name!("autofocus"), autofocus);
199    }
200
201    /// <https://html.spec.whatwg.org/multipage/#dom-focus>
202    fn Focus(&self, cx: &mut js::context::JSContext, options: &FocusOptions) {
203        // 1. If the allow focus steps given this's node document return false, then return.
204        // TODO: Implement this.
205
206        // 2. Run the focusing steps for this.
207        if !self
208            .upcast::<Node>()
209            .run_the_focusing_steps(cx, None, FocusTrigger::Script)
210        {
211            // The specification seems to imply we should scroll into view even if this element
212            // is not a focusable area. No browser does this, so we return early in that case.
213            // See https://github.com/whatwg/html/issues/12231.
214            return;
215        }
216
217        // > 3. If options["focusVisible"] is true, or does not exist but in an
218        // >    implementation-defined  way the user agent determines it would be best to do so,
219        // >    then indicate focus. TODO: Implement this.
220        // TODO: Implement this.
221
222        // > 4. If options["preventScroll"] is false, then scroll a target into view given this,
223        // >    "auto", "center", and "center".
224        if !options.preventScroll {
225            let scroll_axis = ScrollAxisState {
226                position: ScrollLogicalPosition::Center,
227                requirement: ScrollRequirement::IfNotVisible,
228            };
229            self.upcast::<Element>().scroll_into_view_with_options(
230                cx,
231                ScrollBehavior::Smooth,
232                scroll_axis,
233                scroll_axis,
234                None,
235                None,
236            );
237        }
238    }
239
240    /// <https://html.spec.whatwg.org/multipage/#dom-blur>
241    fn Blur(&self, cx: &mut js::context::JSContext) {
242        // TODO: Run the unfocusing steps. Focus the top-level document, not
243        //       the current document.
244        if !self.as_element().focus_state() {
245            return;
246        }
247        // <https://html.spec.whatwg.org/multipage/#unfocusing-steps>
248        self.owner_document().focus_handler().focus(
249            cx,
250            &FocusableArea::Viewport,
251            FocusTrigger::Script,
252        );
253    }
254
255    /// <https://html.spec.whatwg.org/multipage/#dom-tabindex>
256    fn TabIndex(&self) -> i32 {
257        self.element.tab_index()
258    }
259
260    /// <https://html.spec.whatwg.org/multipage/#dom-tabindex>
261    fn SetTabIndex(&self, cx: &mut JSContext, tab_index: i32) {
262        self.element
263            .set_attribute(cx, &local_name!("tabindex"), tab_index.into());
264    }
265}
266
267impl<'dom> LayoutDom<'dom, SVGElement> {
268    pub(crate) fn synthesize_presentational_hints(
269        self,
270        document: LayoutDom<'dom, Document>,
271        push: &mut impl FnMut(PropertyDeclaration),
272    ) {
273        let element = self.upcast::<Element>();
274
275        if element.is::<SVGSVGElement>() {
276            if let Some(width) = element
277                .get_attr_for_layout(&ns!(), &local_name!("width"))
278                .and_then(AttrValue::as_length_percentage)
279            {
280                push(PropertyDeclaration::Width(
281                    specified::Size::LengthPercentage(NonNegative(width.clone())),
282                ));
283            }
284            if let Some(height) = element
285                .get_attr_for_layout(&ns!(), &local_name!("height"))
286                .and_then(AttrValue::as_length_percentage)
287            {
288                push(PropertyDeclaration::Height(
289                    specified::Size::LengthPercentage(NonNegative(height.clone())),
290                ));
291            }
292        }
293        let url_data = UrlExtraData(document.url_for_layout().get_arc());
294        let parsing_mode =
295            ParsingMode::ALLOW_UNITLESS_LENGTH | ParsingMode::ALLOW_ALL_NUMERIC_VALUES;
296        let parser_context = ParserContext::new(
297            Origin::Author,
298            &url_data,
299            Some(CssRuleType::Style),
300            parsing_mode,
301            document.quirks_mode(),
302            Default::default(),
303            None,
304            None,
305            Default::default(),
306        );
307
308        self.parse_svg_attribute(
309            &parser_context,
310            "fill",
311            longhands::fill::parse_declared,
312            push,
313        );
314        self.parse_svg_attribute(
315            &parser_context,
316            "fill-opacity",
317            longhands::fill_opacity::parse_declared,
318            push,
319        );
320        self.parse_svg_attribute(
321            &parser_context,
322            "fill-rule",
323            longhands::fill_rule::parse_declared,
324            push,
325        );
326
327        self.parse_svg_attribute(
328            &parser_context,
329            "stroke",
330            longhands::stroke::parse_declared,
331            push,
332        );
333        self.parse_svg_attribute(
334            &parser_context,
335            "stroke-width",
336            longhands::stroke_width::parse_declared,
337            push,
338        );
339        self.parse_svg_attribute(
340            &parser_context,
341            "stroke-linecap",
342            longhands::stroke_linecap::parse_declared,
343            push,
344        );
345        self.parse_svg_attribute(
346            &parser_context,
347            "stroke-linejoin",
348            longhands::stroke_linejoin::parse_declared,
349            push,
350        );
351        self.parse_svg_attribute(
352            &parser_context,
353            "stroke-dasharray",
354            longhands::stroke_dasharray::parse_declared,
355            push,
356        );
357        self.parse_svg_attribute(
358            &parser_context,
359            "stroke-dashoffset",
360            longhands::stroke_dashoffset::parse_declared,
361            push,
362        );
363        self.parse_svg_attribute(
364            &parser_context,
365            "stroke-miterlimit",
366            longhands::stroke_miterlimit::parse_declared,
367            push,
368        );
369        self.parse_svg_attribute(
370            &parser_context,
371            "stroke-opacity",
372            longhands::stroke_opacity::parse_declared,
373            push,
374        );
375        self.parse_svg_attribute(
376            &parser_context,
377            "display",
378            longhands::display::parse_declared,
379            push,
380        );
381        self.parse_svg_attribute(
382            &parser_context,
383            "visibility",
384            longhands::visibility::parse_declared,
385            push,
386        );
387        self.parse_svg_attribute(
388            &parser_context,
389            "opacity",
390            longhands::opacity::parse_declared,
391            push,
392        );
393
394        // Parse geometry attributes based on element type
395        // <circle>: https://svgwg.org/svg2-draft/shapes.html#CircleElement
396        if element.downcast::<SVGCircleElement>().is_some() {
397            self.parse_svg_attribute(&parser_context, "cx", longhands::cx::parse_declared, push);
398            self.parse_svg_attribute(&parser_context, "cy", longhands::cy::parse_declared, push);
399            self.parse_svg_attribute(&parser_context, "r", longhands::r::parse_declared, push);
400        }
401        // <ellipse>: https://svgwg.org/svg2-draft/shapes.html#EllipseElement
402        if element.downcast::<SVGEllipseElement>().is_some() {
403            self.parse_svg_attribute(&parser_context, "cx", longhands::cx::parse_declared, push);
404            self.parse_svg_attribute(&parser_context, "cy", longhands::cy::parse_declared, push);
405            self.parse_svg_attribute(&parser_context, "rx", longhands::rx::parse_declared, push);
406            self.parse_svg_attribute(&parser_context, "ry", longhands::ry::parse_declared, push);
407        }
408        // <rect>: https://svgwg.org/svg2-draft/shapes.html#RectElement
409        if element.downcast::<SVGRectElement>().is_some() {
410            self.parse_svg_attribute(&parser_context, "x", longhands::x::parse_declared, push);
411            self.parse_svg_attribute(&parser_context, "y", longhands::y::parse_declared, push);
412            self.parse_svg_attribute(
413                &parser_context,
414                "width",
415                longhands::width::parse_declared,
416                push,
417            );
418            self.parse_svg_attribute(
419                &parser_context,
420                "height",
421                longhands::height::parse_declared,
422                push,
423            );
424            self.parse_svg_attribute(&parser_context, "rx", longhands::rx::parse_declared, push);
425            self.parse_svg_attribute(&parser_context, "ry", longhands::ry::parse_declared, push);
426        }
427        // <image>: https://svgwg.org/svg2-draft/embedded.html#ImageElement
428        if element.downcast::<SVGImageElement>().is_some() {
429            self.parse_svg_attribute(&parser_context, "x", longhands::x::parse_declared, push);
430            self.parse_svg_attribute(&parser_context, "y", longhands::y::parse_declared, push);
431            self.parse_svg_attribute(
432                &parser_context,
433                "width",
434                longhands::width::parse_declared,
435                push,
436            );
437            self.parse_svg_attribute(
438                &parser_context,
439                "height",
440                longhands::height::parse_declared,
441                push,
442            );
443        }
444        // <path>: https://svgwg.org/svg2-draft/paths.html#PathElement
445        if element.downcast::<SVGPathElement>().is_some() {
446            // The d CSS property only accepts `none` or `path(<string>)`,
447            // but the SVG presentation attribute uses raw path data (e.g. "M0,0 L1,1").
448            // Wrap the raw path data in `path("...")` so the CSS parser can handle it.
449            if let Some(value) = element.get_attr_val_for_layout(&ns!(), &local_name!("d")) {
450                if value.eq_ignore_ascii_case("none") {
451                    let mut parser = cssparser::Parser::new(value);
452                    if let Ok(property) =
453                        parser.parse_entirely(|i| longhands::d::parse_declared(&parser_context, i))
454                    {
455                        push(property);
456                    }
457                } else {
458                    let wrapped = format!("path(\"{}\")", value);
459                    let mut parser = cssparser::Parser::new(&wrapped);
460                    if let Ok(property) = parser.parse_entirely(|parse_input| {
461                        longhands::d::parse_declared(&parser_context, parse_input)
462                    }) {
463                        push(property);
464                    }
465                }
466            }
467        }
468    }
469
470    fn parse_svg_attribute<F>(
471        self,
472        parser_context: &ParserContext,
473        attr_name: &str,
474        parse: F,
475        push: &mut impl FnMut(PropertyDeclaration),
476    ) where
477        F: for<'i> FnOnce(
478            &ParserContext,
479            &mut cssparser::Parser<'i>,
480        ) -> Result<PropertyDeclaration, style_traits::ParseError>,
481    {
482        let element = self.upcast::<Element>();
483        if let Some(value) = element.get_attr_val_for_layout(&ns!(), &LocalName::from(attr_name)) {
484            let mut parser = cssparser::Parser::new(value);
485            if let Ok(property) =
486                parser.parse_entirely(|parse_input| parse(parser_context, parse_input))
487            {
488                push(property);
489            }
490        }
491    }
492}