Skip to main content

script/dom/execcommand/contenteditable/
element.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 html5ever::{LocalName, local_name, ns};
6use js::context::JSContext;
7use script_bindings::inheritance::Castable;
8use style::attr::AttrValue;
9use style::properties::{LonghandId, PropertyDeclaration, PropertyDeclarationId, ShorthandId};
10use style::values::specified::TextDecorationLine;
11use style::values::specified::box_::DisplayOutside;
12
13use crate::dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
14use crate::dom::bindings::inheritance::{ElementTypeId, HTMLElementTypeId, NodeTypeId};
15use crate::dom::bindings::root::DomRoot;
16use crate::dom::bindings::str::DOMString;
17use crate::dom::element::Element;
18use crate::dom::execcommand::basecommand::{CommandName, CssPropertyName};
19use crate::dom::execcommand::commands::fontsize::font_size_to_css_font;
20use crate::dom::execcommand::contenteditable::node::move_preserving_ranges;
21use crate::dom::html::htmlanchorelement::HTMLAnchorElement;
22use crate::dom::html::htmlfontelement::HTMLFontElement;
23use crate::dom::node::node::{Node, NodeTraits};
24
25impl Element {
26    pub(crate) fn resolved_display_value(&self, cx: &mut JSContext) -> Option<DisplayOutside> {
27        self.style(cx)
28            .map(|style| style.get_box().display.outside())
29    }
30
31    /// <https://w3c.github.io/editing/docs/execCommand/#specified-command-value>
32    pub(crate) fn specified_command_value(
33        &self,
34        cx: &mut JSContext,
35        command: &CommandName,
36    ) -> Option<DOMString> {
37        match command {
38            // Step 1. If command is "backColor" or "hiliteColor" and the Element's display property does not have resolved value "inline", return null.
39            CommandName::BackColor | CommandName::HiliteColor
40                if self
41                    .resolved_display_value(cx)
42                    .is_none_or(|display| display != DisplayOutside::Inline) =>
43            {
44                return None;
45            },
46            // Step 2. If command is "createLink" or "unlink":
47            CommandName::CreateLink | CommandName::Unlink => {
48                // Step 2.1. If element is an a element and has an href attribute,
49                // return the value of that attribute.
50                if let Some(anchor) = self.downcast::<HTMLAnchorElement>() {
51                    return anchor
52                        .upcast::<Element>()
53                        .get_attribute_string_value(&local_name!("href"))
54                        .map(|value| value.into());
55                }
56
57                // Step 2.2. Return null.
58                return None;
59            },
60            // Step 3. If command is "subscript" or "superscript":
61            CommandName::Subscript | CommandName::Superscript => {
62                // Step 3.1. If element is a sup, return "superscript".
63                if matches!(*self.local_name(), local_name!("sup")) {
64                    return Some(DOMString::from_static("superscript"));
65                }
66                // Step 3.2. If element is a sub, return "subscript".
67                if matches!(*self.local_name(), local_name!("sub")) {
68                    return Some(DOMString::from_static("subscript"));
69                }
70                // Step 3.3. Return null.
71                return None;
72            },
73            CommandName::Strikethrough => {
74                // Step 4. If command is "strikethrough", and element has a style attribute set, and that attribute sets "text-decoration":
75                if let Some(value) = CssPropertyName::TextDecorationLine.value_set_for_style(self) {
76                    // Step 4.1. If element's style attribute sets "text-decoration" to a value containing "line-through", return "line-through".
77                    // Step 4.2. Return null.
78                    return value
79                        .contains("line-through")
80                        .then_some(DOMString::from_static("line-through"));
81                }
82                // Step 5. If command is "strikethrough" and element is an s or strike element, return "line-through".
83                if matches!(*self.local_name(), local_name!("s") | local_name!("strike")) {
84                    return Some(DOMString::from_static("line-through"));
85                }
86            },
87            CommandName::Underline => {
88                // Step 6. If command is "underline", and element has a style attribute set, and that attribute sets "text-decoration":
89                if let Some(value) = CssPropertyName::TextDecorationLine.value_set_for_style(self) {
90                    // Step 6.1. If element's style attribute sets "text-decoration" to a value containing "underline", return "underline".
91                    // Step 6.2. Return null.
92                    return value
93                        .contains("underline")
94                        .then_some(DOMString::from_static("underline"));
95                }
96                // Step 7. If command is "underline" and element is a u element, return "underline".
97                if *self.local_name() == local_name!("u") {
98                    return Some(DOMString::from_static("underline"));
99                }
100            },
101            _ => {},
102        };
103        // Step 8. Let property be the relevant CSS property for command.
104        // Step 9. If property is null, return null.
105        let property = command.relevant_css_property()?;
106        // Step 10. If element has a style attribute set, and that attribute has the effect of setting property,
107        // return the value that it sets property to.
108        if let Some(value) = property.value_set_for_style(self) {
109            return Some(value);
110        }
111        // Step 11. If element is a font element that has an attribute whose effect is to create a presentational hint for property,
112        // return the value that the hint sets property to. (For a size of 7, this will be the non-CSS value "xxx-large".)
113        if self.is::<HTMLFontElement>() &&
114            let Some(font_size) = self
115                .with_attribute(&ns!(), &local_name!("size"), |attribute| {
116                    if let AttrValue::UInt(_, value) = *attribute.value() {
117                        Some(value)
118                    } else {
119                        None
120                    }
121                })
122                .flatten()
123        {
124            return Some(font_size_to_css_font(&font_size).into());
125        }
126
127        // Step 12. If element is in the following list, and property is equal to the CSS property name listed for it,
128        // return the string listed for it.
129        let element_name = self.local_name();
130        match property {
131            CssPropertyName::FontWeight
132                if element_name == &local_name!("b") || element_name == &local_name!("strong") =>
133            {
134                Some(DOMString::from_static("bold"))
135            },
136            CssPropertyName::FontStyle
137                if element_name == &local_name!("i") || element_name == &local_name!("em") =>
138            {
139                Some(DOMString::from_static("italic"))
140            },
141            // Step 13. Return null.
142            _ => None,
143        }
144    }
145
146    /// <https://w3c.github.io/editing/docs/execCommand/#modifiable-element>
147    pub(crate) fn is_modifiable_element(&self) -> bool {
148        let attrs = self.attrs().borrow();
149        let mut attrs = attrs.iter();
150        let type_id = self.upcast::<Node>().type_id();
151
152        // > A modifiable element is a b, em, i, s, span, strike, strong, sub, sup, or u element
153        // > with no attributes except possibly style;
154        if matches!(
155            type_id,
156            NodeTypeId::Element(ElementTypeId::HTMLElement(
157                HTMLElementTypeId::HTMLSpanElement,
158            ))
159        ) || matches!(
160            *self.local_name(),
161            local_name!("b") |
162                local_name!("em") |
163                local_name!("i") |
164                local_name!("s") |
165                local_name!("strike") |
166                local_name!("strong") |
167                local_name!("sub") |
168                local_name!("sup") |
169                local_name!("u")
170        ) {
171            return attrs.all(|attr| attr.local_name() == &local_name!("style"));
172        }
173
174        // > or a font element with no attributes except possibly style, color, face, and/or size;
175        if matches!(
176            type_id,
177            NodeTypeId::Element(ElementTypeId::HTMLElement(
178                HTMLElementTypeId::HTMLFontElement,
179            ))
180        ) {
181            return attrs.all(|attr| {
182                matches!(
183                    *attr.local_name(),
184                    local_name!("style") |
185                        local_name!("color") |
186                        local_name!("face") |
187                        local_name!("size")
188                )
189            });
190        }
191
192        // > or an a element with no attributes except possibly style and/or href.
193        if matches!(
194            type_id,
195            NodeTypeId::Element(ElementTypeId::HTMLElement(
196                HTMLElementTypeId::HTMLAnchorElement,
197            ))
198        ) {
199            return attrs.all(|attr| {
200                matches!(
201                    *attr.local_name(),
202                    local_name!("style") | local_name!("href")
203                )
204            });
205        }
206
207        false
208    }
209
210    // <https://w3c.github.io/editing/docs/execCommand/#indentation-element>
211    pub(crate) fn is_indentation_element(&self) -> bool {
212        // > An indentation element is either a blockquote, or a div
213        if !matches!(
214            *self.local_name(),
215            local_name!("blockquote") | local_name!("div")
216        ) {
217            return false;
218        }
219
220        // > that has a style attribute that sets "margin" or some subproperty of it.
221        let style_attribute = self.style_attribute().borrow();
222        let Some(declarations) = style_attribute.as_ref() else {
223            return false;
224        };
225        let document = self.owner_document();
226        let shared_lock = document.style_shared_author_lock();
227        let read_lock = shared_lock.read();
228        let style = declarations.read_with(&read_lock);
229
230        ShorthandId::Margin
231            .longhands()
232            .any(|longhand| style.contains(PropertyDeclarationId::Longhand(longhand)))
233    }
234
235    pub(crate) fn has_empty_style_attribute(&self) -> bool {
236        let style_attribute = self.style_attribute().borrow();
237        style_attribute.as_ref().is_some_and(|declarations| {
238            let document = self.owner_document();
239            let shared_lock = document.style_shared_author_lock();
240            let read_lock = shared_lock.read();
241            let style = declarations.read_with(&read_lock);
242
243            style.is_empty()
244        })
245    }
246
247    /// <https://w3c.github.io/editing/docs/execCommand/#non-list-single-line-container>
248    pub(crate) fn is_non_list_single_line_container(&self) -> bool {
249        // > A non-list single-line container is an HTML element with local name
250        // > "address", "div", "h1", "h2", "h3", "h4", "h5", "h6", "listing", "p", "pre", or "xmp".
251        matches!(
252            *self.local_name(),
253            local_name!("address") |
254                local_name!("div") |
255                local_name!("h1") |
256                local_name!("h2") |
257                local_name!("h3") |
258                local_name!("h4") |
259                local_name!("h5") |
260                local_name!("h6") |
261                local_name!("listing") |
262                local_name!("p") |
263                local_name!("pre") |
264                local_name!("xmp")
265        )
266    }
267
268    /// <https://w3c.github.io/editing/docs/execCommand/#simple-modifiable-element>
269    pub(crate) fn is_simple_modifiable_element(&self) -> bool {
270        let attrs = self.attrs().borrow();
271        let attr_count = attrs.len();
272        let type_id = self.upcast::<Node>().type_id();
273
274        if matches!(
275            type_id,
276            NodeTypeId::Element(ElementTypeId::HTMLElement(
277                HTMLElementTypeId::HTMLAnchorElement,
278            )) | NodeTypeId::Element(ElementTypeId::HTMLElement(
279                HTMLElementTypeId::HTMLFontElement,
280            )) | NodeTypeId::Element(ElementTypeId::HTMLElement(
281                HTMLElementTypeId::HTMLSpanElement,
282            ))
283        ) || matches!(
284            *self.local_name(),
285            local_name!("b") |
286                local_name!("em") |
287                local_name!("i") |
288                local_name!("s") |
289                local_name!("strike") |
290                local_name!("strong") |
291                local_name!("sub") |
292                local_name!("sup") |
293                local_name!("u")
294        ) {
295            // > It is an a, b, em, font, i, s, span, strike, strong, sub, sup, or u element with no attributes.
296            if attr_count == 0 {
297                return true;
298            }
299
300            // > It is an a, b, em, font, i, s, span, strike, strong, sub, sup, or u element
301            // > with exactly one attribute, which is style,
302            // > which sets no CSS properties (including invalid or unrecognized properties).
303            if attr_count == 1 &&
304                attrs.first().expect("Size is 1").local_name() == &local_name!("style") &&
305                self.has_empty_style_attribute()
306            {
307                return true;
308            }
309        }
310
311        if attr_count != 1 {
312            return false;
313        }
314
315        let first_attr = attrs.first().expect("Size is 1");
316        let only_attribute = first_attr.local_name();
317
318        // > It is an a element with exactly one attribute, which is href.
319        if matches!(
320            type_id,
321            NodeTypeId::Element(ElementTypeId::HTMLElement(
322                HTMLElementTypeId::HTMLAnchorElement,
323            ))
324        ) {
325            return only_attribute == &local_name!("href");
326        }
327
328        // > It is a font element with exactly one attribute, which is either color, face, or size.
329        if matches!(
330            type_id,
331            NodeTypeId::Element(ElementTypeId::HTMLElement(
332                HTMLElementTypeId::HTMLFontElement,
333            ))
334        ) {
335            return only_attribute == &local_name!("color") ||
336                only_attribute == &local_name!("face") ||
337                only_attribute == &local_name!("size");
338        }
339
340        if only_attribute != &local_name!("style") {
341            return false;
342        }
343        let style_attribute = self.style_attribute().borrow();
344        let Some(declarations) = style_attribute.as_ref() else {
345            return false;
346        };
347        let document = self.owner_document();
348        let shared_lock = document.style_shared_author_lock();
349        let read_lock = shared_lock.read();
350        let style = declarations.read_with(&read_lock);
351
352        // > It is a b or strong element with exactly one attribute, which is style,
353        // > and the style attribute sets exactly one CSS property
354        // > (including invalid or unrecognized properties), which is "font-weight".
355        if matches!(*self.local_name(), local_name!("b") | local_name!("strong")) {
356            return style.len() == 1 &&
357                style.contains(PropertyDeclarationId::Longhand(LonghandId::FontWeight));
358        }
359
360        // > It is an i or em element with exactly one attribute, which is style,
361        // > and the style attribute sets exactly one CSS property (including invalid or unrecognized properties),
362        // > which is "font-style".
363        if matches!(*self.local_name(), local_name!("i") | local_name!("em")) {
364            return style.len() == 1 &&
365                style.contains(PropertyDeclarationId::Longhand(LonghandId::FontStyle));
366        }
367
368        let a_font_or_span = matches!(
369            type_id,
370            NodeTypeId::Element(ElementTypeId::HTMLElement(
371                HTMLElementTypeId::HTMLAnchorElement,
372            )) | NodeTypeId::Element(ElementTypeId::HTMLElement(
373                HTMLElementTypeId::HTMLFontElement,
374            )) | NodeTypeId::Element(ElementTypeId::HTMLElement(
375                HTMLElementTypeId::HTMLSpanElement,
376            ))
377        );
378        let s_strike_or_u = matches!(
379            *self.local_name(),
380            local_name!("s") | local_name!("strike") | local_name!("u")
381        );
382        if a_font_or_span || s_strike_or_u {
383            // Note that the shorthand "text-decoration" expands to N longhands (4 at time of writing).
384            // Hence we check if the length is equal to N here, instead of 1.
385            if style.len() == ShorthandId::TextDecoration.longhands().count() &&
386                style
387                    .shorthand_to_css(ShorthandId::TextDecoration, &mut String::new())
388                    .is_ok()
389            {
390                if let Some((text_decoration, _)) = style.get(PropertyDeclarationId::Longhand(
391                    LonghandId::TextDecorationLine,
392                )) {
393                    // > It is an a, font, s, span, strike, or u element with exactly one attribute,
394                    // > which is style, and the style attribute sets exactly one CSS property
395                    // > (including invalid or unrecognized properties), which is "text-decoration",
396                    // > which is set to "line-through" or "underline" or "overline" or "none".
397                    return matches!(
398                        text_decoration,
399                        PropertyDeclaration::TextDecorationLine(
400                            TextDecorationLine::LINE_THROUGH |
401                                TextDecorationLine::UNDERLINE |
402                                TextDecorationLine::OVERLINE |
403                                TextDecorationLine::NONE
404                        )
405                    );
406                }
407            } else if a_font_or_span {
408                // > It is an a, font, or span element with exactly one attribute, which is style,
409                // > and the style attribute sets exactly one CSS property (including invalid or unrecognized properties),
410                // > and that property is not "text-decoration".
411                return style.len() == 1;
412            }
413        }
414
415        false
416    }
417
418    pub(crate) fn is_simple_indentation_element(&self) -> bool {
419        // > A simple indentation element is an indentation element
420        if !self.is_indentation_element() {
421            return false;
422        }
423
424        // > that has no attributes except possibly
425        let attrs = self.attrs().borrow();
426        let mut attrs = attrs.iter();
427        attrs.all(|attr| {
428            // - a style attribute that sets no properties other than "margin", "border", "padding", or subproperties of those; and/or
429            if matches!(*attr.local_name(), local_name!("style")) {
430                let style_attribute = self.style_attribute().borrow();
431                let Some(declarations) = style_attribute.as_ref() else {
432                    return false;
433                };
434                let document = self.owner_document();
435                let shared_lock = document.style_shared_author_lock();
436                let read_lock = shared_lock.read();
437                let style = declarations.read_with(&read_lock);
438
439                let properties: Vec<_> = ShorthandId::Margin
440                    .longhands()
441                    .chain(ShorthandId::Border.longhands())
442                    .chain(ShorthandId::Padding.longhands())
443                    .collect();
444                return style.declarations().iter().all(|declaration| {
445                    declaration
446                        .id()
447                        .as_longhand()
448                        .is_some_and(|longhand| properties.contains(&longhand))
449                });
450            }
451
452            // - a dir attribute
453            if matches!(*attr.local_name(), local_name!("dir")) {
454                return true;
455            }
456
457            false
458        })
459    }
460
461    /// <https://w3c.github.io/editing/docs/execCommand/#set-the-tag-name>
462    pub(crate) fn set_the_tag_name(&self, cx: &mut JSContext, new_name: &str) -> DomRoot<Node> {
463        // Step 1. If element is an HTML element with local name equal to new name, return element.
464        if self.local_name() == &LocalName::from(new_name) {
465            return DomRoot::upcast(DomRoot::from_ref(self));
466        }
467        // Step 2. If element's parent is null, return element.
468        let node = self.upcast::<Node>();
469        let Some(parent) = node.GetParentNode() else {
470            return DomRoot::upcast(DomRoot::from_ref(self));
471        };
472        // Step 3. Let replacement element be the result of calling createElement(new name) on the ownerDocument of element.
473        let document = node.owner_document();
474        let replacement = document.create_element(cx, new_name);
475        let replacement_node = replacement.upcast::<Node>();
476        // Step 4. Insert replacement element into element's parent immediately before element.
477        if parent
478            .InsertBefore(cx, replacement_node, Some(node))
479            .is_err()
480        {
481            unreachable!("Must always be able to insert");
482        }
483        // Step 5. Copy all attributes of element to replacement element, in order.
484        self.copy_all_attributes_to_other_element(cx, &replacement);
485        // Step 6. While element has children, append the first child of element as the last child of replacement element, preserving ranges.
486        for child in node.children() {
487            move_preserving_ranges(cx, &child, |cx| replacement_node.AppendChild(cx, &child));
488        }
489        // Step 7. Remove element from its parent.
490        node.remove_self(cx);
491        // Step 8. Return replacement element.
492        DomRoot::upcast(replacement)
493    }
494}