Skip to main content

script/dom/execcommand/
basecommand.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 js::context::JSContext;
6use script_bindings::inheritance::Castable;
7use style::attr::parse_legacy_color;
8use style::color::ColorFlags;
9use style::properties::PropertyDeclarationId;
10use style::properties::generated::{LonghandId, ShorthandId};
11use style::values::specified::text::TextDecorationLine;
12use style_traits::ToCss;
13
14use crate::dom::bindings::codegen::Bindings::CSSStyleDeclarationBinding::CSSStyleDeclarationMethods;
15use crate::dom::bindings::codegen::Bindings::DocumentBinding::DocumentMethods;
16use crate::dom::bindings::codegen::Bindings::HTMLElementBinding::HTMLElementMethods;
17use crate::dom::bindings::codegen::Bindings::HTMLFontElementBinding::HTMLFontElementMethods;
18use crate::dom::bindings::str::DOMString;
19use crate::dom::document::Document;
20use crate::dom::element::Element;
21use crate::dom::execcommand::commands::backcolor::execute_backcolor_command;
22use crate::dom::execcommand::commands::bold::execute_bold_command;
23use crate::dom::execcommand::commands::createlink::execute_createlink_command;
24use crate::dom::execcommand::commands::defaultparagraphseparator::execute_default_paragraph_separator_command;
25use crate::dom::execcommand::commands::delete::execute_delete_command;
26use crate::dom::execcommand::commands::fontname::execute_fontname_command;
27use crate::dom::execcommand::commands::fontsize::{
28    execute_fontsize_command, font_size_loosely_equivalent, value_for_fontsize_command,
29};
30use crate::dom::execcommand::commands::forecolor::execute_forecolor_command;
31use crate::dom::execcommand::commands::forwarddelete::execute_forward_delete_command;
32use crate::dom::execcommand::commands::hilitecolor::execute_hilitecolor_command;
33use crate::dom::execcommand::commands::indent::execute_indent_command;
34use crate::dom::execcommand::commands::inserthorizontalrule::execute_insert_horizontal_rule_command;
35use crate::dom::execcommand::commands::insertimage::execute_insert_image_command;
36use crate::dom::execcommand::commands::insertlinebreak::execute_insert_line_break_command;
37use crate::dom::execcommand::commands::insertparagraph::execute_insert_paragraph_command;
38use crate::dom::execcommand::commands::inserttext::execute_insert_text_command;
39use crate::dom::execcommand::commands::italic::execute_italic_command;
40use crate::dom::execcommand::commands::outdent::execute_outdent_command;
41use crate::dom::execcommand::commands::removeformat::execute_removeformat_command;
42use crate::dom::execcommand::commands::strikethrough::execute_strikethrough_command;
43use crate::dom::execcommand::commands::stylewithcss::execute_style_with_css_command;
44use crate::dom::execcommand::commands::subscript::execute_subscript_command;
45use crate::dom::execcommand::commands::superscript::execute_superscript_command;
46use crate::dom::execcommand::commands::underline::execute_underline_command;
47use crate::dom::execcommand::commands::unlink::execute_unlink_command;
48use crate::dom::html::htmlelement::HTMLElement;
49use crate::dom::html::htmlfontelement::HTMLFontElement;
50use crate::dom::iterators::ShadowIncluding;
51use crate::dom::node::{Node, NodeTraits};
52use crate::dom::range::Range;
53use crate::dom::selection::Selection;
54
55#[derive(Default, Clone, Copy, MallocSizeOf)]
56pub(crate) enum DefaultSingleLineContainerName {
57    #[default]
58    Div,
59    Paragraph,
60}
61
62impl DefaultSingleLineContainerName {
63    pub(crate) fn str(&self) -> &str {
64        match self {
65            DefaultSingleLineContainerName::Div => "div",
66            DefaultSingleLineContainerName::Paragraph => "p",
67        }
68    }
69}
70
71impl From<DefaultSingleLineContainerName> for DOMString {
72    fn from(default_single_line_container_name: DefaultSingleLineContainerName) -> Self {
73        match default_single_line_container_name {
74            DefaultSingleLineContainerName::Div => DOMString::from_static("div"),
75            DefaultSingleLineContainerName::Paragraph => DOMString::from_static("p"),
76        }
77    }
78}
79
80pub(crate) enum BoolOrOptionalString {
81    Bool(bool),
82    OptionalString(Option<DOMString>),
83}
84
85impl From<Option<DOMString>> for BoolOrOptionalString {
86    fn from(optional_string: Option<DOMString>) -> Self {
87        Self::OptionalString(optional_string)
88    }
89}
90
91impl From<bool> for BoolOrOptionalString {
92    fn from(bool_: bool) -> Self {
93        Self::Bool(bool_)
94    }
95}
96
97pub(crate) struct RecordedStateOfCommand {
98    pub(crate) command: CommandName,
99    pub(crate) value: BoolOrOptionalString,
100}
101
102impl RecordedStateOfCommand {
103    pub(crate) fn for_command_node(cx: &mut JSContext, command: CommandName, node: &Node) -> Self {
104        let value = node.effective_command_value(cx, &command).into();
105        Self { command, value }
106    }
107
108    pub(crate) fn for_command_node_with_inline_activated_values(
109        cx: &mut JSContext,
110        command: CommandName,
111        node: &Node,
112    ) -> Self {
113        let effective_command_value = node.effective_command_value(cx, &command);
114        let value = effective_command_value
115            .is_some_and(|effective_command_value| {
116                command
117                    .inline_command_activated_values()
118                    .contains(&effective_command_value.str().as_ref())
119            })
120            .into();
121        Self { command, value }
122    }
123
124    pub(crate) fn for_command_node_with_value(
125        cx: &mut JSContext,
126        command: CommandName,
127        document: &Document,
128    ) -> Self {
129        let value = command.current_value(cx, document).into();
130        Self { command, value }
131    }
132
133    fn for_command_state_override(command: CommandName, document: &Document) -> Option<Self> {
134        let value = document.state_override(&command)?.into();
135        Some(Self { command, value })
136    }
137
138    fn for_command_value_override(command: CommandName, document: &Document) -> Option<Self> {
139        let value_override = document.value_override(&command)?;
140        let value = Some(value_override).into();
141        Some(Self { command, value })
142    }
143}
144
145/// <https://w3c.github.io/editing/docs/execCommand/#relevant-css-property>
146#[derive(Clone, Copy, Eq, PartialEq)]
147pub(crate) enum CssPropertyName {
148    BackgroundColor,
149    Color,
150    FontFamily,
151    FontSize,
152    FontWeight,
153    FontStyle,
154    TextDecoration,
155    TextDecorationLine,
156}
157
158impl CssPropertyName {
159    pub(crate) fn resolved_value_for_node(
160        &self,
161        cx: &mut JSContext,
162        element: &Element,
163    ) -> Option<DOMString> {
164        let style = element.style(cx)?;
165
166        Some(
167            match self {
168                CssPropertyName::BackgroundColor => {
169                    let background_color = style.get_background_color();
170                    if let Some(absolute_color) = background_color.as_absolute() {
171                        // Used as an early-exit when figuring out on which element to resolve
172                        // the style in `effective_command_value`
173                        if absolute_color.is_transparent() {
174                            return None;
175                        }
176                        // Requires legacy SRGB syntax, which is what all tests expect.
177                        // E.g. it should use `rgba()` instead of `rgb()`, even if the alpha
178                        // is zero.
179                        let mut absolute_color = *absolute_color;
180                        absolute_color.flags.insert(ColorFlags::IS_LEGACY_SRGB);
181                        return Some(absolute_color.to_css_string().into());
182                    }
183                    background_color.to_css_string()
184                },
185                CssPropertyName::Color => {
186                    // Detached font elements (e.g. does created with `document.createElement`
187                    // and not yet present in DOM) dont have a computed style for `color`.
188                    // Since we create detached parent elements and compute "effective command
189                    // value" for these elements, we need to special case this. Otherwise, we
190                    // would add both a `color` attribute and `color` style declaration
191                    // to a parent font element.
192                    if let Some(ancestor_font) = element.downcast::<HTMLFontElement>() {
193                        let color = ancestor_font.Color();
194                        if !color.is_empty() {
195                            return Some(color);
196                        }
197                    }
198                    style.get_color().to_css_string()
199                },
200                CssPropertyName::FontFamily => {
201                    // Detached font elements (e.g. does created with `document.createElement`
202                    // and not yet present in DOM) dont have a computed style for `fontFamily`.
203                    // Since we create detached parent elements and compute "effective command
204                    // value" for these elements, we need to special case this. Otherwise, we
205                    // would add both a `face` attribute and `font-family` style declaration
206                    // to a parent font element.
207                    if let Some(ancestor_font) = element.downcast::<HTMLFontElement>() {
208                        let face = ancestor_font.Face();
209                        if !face.is_empty() {
210                            return Some(face);
211                        }
212                    }
213                    style.get_font_family().to_css_string()
214                },
215                CssPropertyName::FontSize => {
216                    // Font size is special, in that it can't use the resolved styles to compute
217                    // values. That's because it is influenced by other factors as well, and it
218                    // should also take into account size attributes of font elements.
219                    //
220                    // Therefore, we do a manual traversal up the chain to mimic what style
221                    // resolution would have done. This also allows us to later check for
222                    // loose equivalence for font elements, since we would return the size as an
223                    // integer, without a size indicator (e.g. `px`).
224                    //
225                    // However, if no such relevant declaration exists, then we should fallback
226                    // to pixels after all. For the effective command value, this essentially means
227                    // we will overwrite it. For the value of the "fontsize" command, we would then
228                    // need to convert it using [`legacy_font_size_for`].
229                    return element
230                        .upcast::<Node>()
231                        .inclusive_ancestors(ShadowIncluding::No)
232                        .find_map(|ancestor| {
233                            if let Some(ancestor_font) = ancestor.downcast::<HTMLFontElement>() {
234                                Some(ancestor_font.Size())
235                            } else {
236                                self.value_set_for_style(ancestor.downcast::<Element>()?)
237                            }
238                        })
239                        .or_else(|| {
240                            let pixels = style.get_font().font_size.computed_size().px();
241                            Some(format!("{}px", pixels).into())
242                        });
243                },
244                CssPropertyName::FontWeight => style.get_font_weight().to_css_string(),
245                CssPropertyName::FontStyle => style.get_font_style().to_css_string(),
246                CssPropertyName::TextDecoration => unreachable!("Should use longhands instead"),
247                CssPropertyName::TextDecorationLine => {
248                    let text_decoration_line = style.get_text().text_decoration_line;
249                    if text_decoration_line == TextDecorationLine::NONE {
250                        return None;
251                    }
252                    text_decoration_line.to_css_string()
253                },
254            }
255            .into(),
256        )
257    }
258
259    /// Retrieves a respective css longhand value from the style declarations of an
260    /// element. Note that this is different than the computed values, since this is
261    /// only relevant when the author specified rules on the specific element.
262    pub(crate) fn value_set_for_style(&self, element: &Element) -> Option<DOMString> {
263        let style_attribute = element.style_attribute().borrow();
264        let declarations = style_attribute.as_ref()?;
265        let document = element.owner_document();
266        let shared_lock = document.style_shared_author_lock();
267        let read_lock = shared_lock.read();
268        let style = declarations.read_with(&read_lock);
269
270        let longhand_id = match self {
271            CssPropertyName::BackgroundColor => LonghandId::BackgroundColor,
272            CssPropertyName::Color => LonghandId::Color,
273            CssPropertyName::FontFamily => LonghandId::FontFamily,
274            CssPropertyName::FontSize => LonghandId::FontSize,
275            CssPropertyName::FontWeight => LonghandId::FontWeight,
276            CssPropertyName::FontStyle => LonghandId::FontStyle,
277            CssPropertyName::TextDecoration => {
278                let mut dest = String::new();
279                style
280                    .shorthand_to_css(ShorthandId::TextDecoration, &mut dest)
281                    .ok()?;
282                return Some(dest.into());
283            },
284            CssPropertyName::TextDecorationLine => LonghandId::TextDecorationLine,
285        };
286        style
287            .get(PropertyDeclarationId::Longhand(longhand_id))
288            .and_then(|value| {
289                let mut dest = String::new();
290                value.0.to_css(&mut dest).ok()?;
291                Some(dest.into())
292            })
293    }
294
295    fn property_name(&self) -> DOMString {
296        match self {
297            CssPropertyName::BackgroundColor => "background-color",
298            CssPropertyName::Color => "color",
299            CssPropertyName::FontFamily => "font-family",
300            CssPropertyName::FontSize => "font-size",
301            CssPropertyName::FontWeight => "font-weight",
302            CssPropertyName::FontStyle => "font-style",
303            CssPropertyName::TextDecoration => "text-decoration",
304            CssPropertyName::TextDecorationLine => "text-decoration-line",
305        }
306        .into()
307    }
308
309    pub(crate) fn set_for_element(
310        &self,
311        cx: &mut JSContext,
312        element: &HTMLElement,
313        new_value: DOMString,
314    ) {
315        let style = element.Style(cx);
316
317        let _ = style.SetProperty(cx, self.property_name(), new_value, DOMString::new());
318    }
319
320    pub(crate) fn remove_from_element(&self, cx: &mut JSContext, element: &HTMLElement) {
321        let _ = element.Style(cx).RemoveProperty(cx, self.property_name());
322    }
323}
324
325#[derive(Clone, Copy, Eq, Hash, MallocSizeOf, PartialEq)]
326#[expect(unused)] // TODO(25005): implement all commands
327pub(crate) enum CommandName {
328    BackColor,
329    Bold,
330    Copy,
331    CreateLink,
332    Cut,
333    DefaultParagraphSeparator,
334    Delete,
335    FontName,
336    FontSize,
337    ForeColor,
338    FormatBlock,
339    ForwardDelete,
340    HiliteColor,
341    Indent,
342    InsertHorizontalRule,
343    InsertHtml,
344    InsertImage,
345    InsertLineBreak,
346    InsertOrderedList,
347    InsertParagraph,
348    InsertText,
349    InsertUnorderedList,
350    Italic,
351    JustifyCenter,
352    JustifyFull,
353    JustifyLeft,
354    JustifyRight,
355    Outdent,
356    Paste,
357    Redo,
358    RemoveFormat,
359    SelectAll,
360    Strikethrough,
361    StyleWithCss,
362    Subscript,
363    Superscript,
364    Underline,
365    Undo,
366    Unlink,
367    Usecss,
368}
369
370impl CommandName {
371    /// <https://w3c.github.io/editing/docs/execCommand/#indeterminate>
372    pub(crate) fn is_indeterminate(&self, cx: &mut JSContext, document: &Document) -> bool {
373        if !self.is_standard_inline_value_command() {
374            return false;
375        }
376        // https://w3c.github.io/editing/docs/execCommand/#standard-inline-value-command
377        // > it is indeterminate if among formattable nodes that are effectively contained in the active range,
378        // > there are two that have distinct effective command values.
379        let Some(selection) = document.GetSelection(cx) else {
380            return false;
381        };
382        let Some(active_range) = selection.active_range(cx) else {
383            return false;
384        };
385        let mut at_least_two_different_effective_values = false;
386        let mut previous_effective_value: Option<DOMString> = None;
387        active_range.for_each_effectively_contained_child(cx, |cx, node| {
388            if at_least_two_different_effective_values || !node.is_formattable(cx) {
389                return;
390            }
391            if let Some(effective_command_value) = node.effective_command_value(cx, self) {
392                // https://w3c.github.io/editing/docs/execCommand/#the-subscript-command
393                // https://w3c.github.io/editing/docs/execCommand/#the-superscript-command
394                // > or if there is some formattable node effectively contained in
395                // > the active range with effective command value "mixed".
396                if matches!(self, CommandName::Subscript | CommandName::Superscript) &&
397                    effective_command_value == "mixed"
398                {
399                    at_least_two_different_effective_values = true;
400                }
401                if let Some(previous_effective_value) = &previous_effective_value {
402                    if &effective_command_value != previous_effective_value {
403                        at_least_two_different_effective_values = true;
404                    }
405                } else {
406                    previous_effective_value = Some(effective_command_value);
407                }
408            }
409        });
410        at_least_two_different_effective_values
411    }
412
413    /// <https://w3c.github.io/editing/docs/execCommand/#state>
414    pub(crate) fn current_state(&self, cx: &mut JSContext, document: &Document) -> Option<bool> {
415        Some(match self {
416            CommandName::StyleWithCss => {
417                // https://w3c.github.io/editing/docs/execCommand/#the-stylewithcss-command
418                // > True if the CSS styling flag is true, otherwise false.
419                document.css_styling_flag()
420            },
421            _ => {
422                // https://w3c.github.io/editing/docs/execCommand/#inline-formatting-command-definitions
423                // > If a command has inline command activated values defined, its state is true if either
424                // > no formattable node is effectively contained in the active range,
425                // > and the active range's start node's effective command value is one of the given values;
426                // > or if there is at least one formattable node effectively contained in the active range,
427                // > and all of them have an effective command value equal to one of the given values.
428                let inline_command_activated_values = self.inline_command_activated_values();
429                if inline_command_activated_values.is_empty() {
430                    return None;
431                }
432                let selection = document.GetSelection(cx)?;
433                let active_range = selection.active_range(cx)?;
434                let mut at_least_one_child_is_formattable = false;
435                let mut all_children_have_matching_command_values = true;
436                active_range.for_each_effectively_contained_child(cx, |cx, node| {
437                    if !node.is_formattable(cx) {
438                        return;
439                    }
440                    at_least_one_child_is_formattable = true;
441                    all_children_have_matching_command_values &= node
442                        .effective_command_value(cx, self)
443                        .is_some_and(|effective_value| {
444                            inline_command_activated_values.contains(&&*effective_value.str())
445                        });
446                });
447                if at_least_one_child_is_formattable {
448                    all_children_have_matching_command_values
449                } else {
450                    active_range
451                        .start_container()
452                        .effective_command_value(cx, self)
453                        .is_some_and(|effective_value| {
454                            inline_command_activated_values.contains(&&*effective_value.str())
455                        })
456                }
457            },
458        })
459    }
460
461    /// <https://w3c.github.io/editing/docs/execCommand/#value>
462    pub(crate) fn current_value(
463        &self,
464        cx: &mut JSContext,
465        document: &Document,
466    ) -> Option<DOMString> {
467        Some(match self {
468            CommandName::DefaultParagraphSeparator => {
469                // https://w3c.github.io/editing/docs/execCommand/#the-defaultparagraphseparator-command
470                // > Return the context object's default single-line container name.
471                document.default_single_line_container_name().into()
472            },
473            CommandName::FontSize => value_for_fontsize_command(cx, document)?,
474            _ if self.is_standard_inline_value_command() => {
475                // https://w3c.github.io/editing/docs/execCommand/#standard-inline-value-command
476                // > Its value is the effective command value of the first formattable node that
477                // > is effectively contained in the active range; or if there is no such node,
478                // > the effective command value of the active range's start node;
479                // > or if that is null, the empty string.
480                let selection = document.GetSelection(cx)?;
481                let active_range = selection.active_range(cx)?;
482
483                active_range
484                    .first_formattable_contained_node(cx)
485                    .unwrap_or_else(|| active_range.start_container())
486                    .effective_command_value(cx, self)
487                    .unwrap_or_default()
488            },
489            _ => return None,
490        })
491    }
492
493    /// <https://w3c.github.io/editing/docs/execCommand/#equivalent-values>
494    pub(crate) fn are_equivalent_values(
495        &self,
496        first: Option<&DOMString>,
497        second: Option<&DOMString>,
498    ) -> bool {
499        match (first, second) {
500            // > Two quantities are equivalent values for a command if either both are null,
501            (None, None) => true,
502            (Some(first_str), Some(second_str)) => {
503                // > or both are strings and the command defines equivalent values and they match the definition.
504                match self {
505                    CommandName::Bold => {
506                        // https://w3c.github.io/editing/docs/execCommand/#the-bold-command
507                        // > Either the two strings are equal, or one is "bold" and the other is "700",
508                        // > or one is "normal" and the other is "400".
509                        first_str == second_str ||
510                            matches!(
511                                (first_str.str().as_ref(), second_str.str().as_ref()),
512                                ("bold", "700") |
513                                    ("700", "bold") |
514                                    ("normal", "400") |
515                                    ("400", "normal")
516                            )
517                    },
518                    CommandName::BackColor | CommandName::ForeColor | CommandName::HiliteColor => {
519                        // https://w3c.github.io/editing/docs/execCommand/#the-backcolor-command
520                        // https://w3c.github.io/editing/docs/execCommand/#the-forecolor-command
521                        // https://w3c.github.io/editing/docs/execCommand/#the-hilitecolor-command
522                        // > Either both strings are valid CSS colors and have the same red, green, blue, and alpha components,
523                        // > or neither string is a valid CSS color.
524                        match (
525                            parse_legacy_color(&first_str.str()),
526                            parse_legacy_color(&second_str.str()),
527                        ) {
528                            (Ok(first_legacy_color), Ok(second_legacy_color)) => {
529                                first_legacy_color == second_legacy_color
530                            },
531                            (Err(_), Err(_)) => true,
532                            _ => false,
533                        }
534                    },
535                    // > or both are strings and they're equal and the command does not define any equivalent values,
536                    _ => first_str == second_str,
537                }
538            },
539            _ => false,
540        }
541    }
542
543    /// <https://w3c.github.io/editing/docs/execCommand/#loosely-equivalent-values>
544    pub(crate) fn are_loosely_equivalent_values(
545        &self,
546        first: Option<&DOMString>,
547        second: Option<&DOMString>,
548    ) -> bool {
549        // > Two quantities are loosely equivalent values for a command if either they are equivalent values for the command,
550        if self.are_equivalent_values(first, second) {
551            return true;
552        }
553        // > or if the command is the fontSize command;
554        // > one of the quantities is one of "x-small", "small", "medium", "large", "x-large", "xx-large", or "xxx-large";
555        // > and the other quantity is the resolved value of "font-size" on a font element whose size attribute
556        // > has the corresponding value set ("1" through "7" respectively).
557        if let (CommandName::FontSize, Some(first), Some(second)) = (self, first, second) {
558            font_size_loosely_equivalent(first, second)
559        } else {
560            false
561        }
562    }
563
564    /// <https://w3c.github.io/editing/docs/execCommand/#record-current-overrides>
565    pub(crate) fn record_current_overrides(document: &Document) -> Vec<RecordedStateOfCommand> {
566        // Step 1. Let overrides be a list of (string, string or boolean) ordered pairs, initially empty.
567        let mut overrides = vec![];
568        // Step 2. If there is a value override for "createLink",
569        // add ("createLink", value override for "createLink") to overrides.
570        if let Some(value_override) =
571            RecordedStateOfCommand::for_command_value_override(CommandName::CreateLink, document)
572        {
573            overrides.push(value_override);
574        }
575        // Step 3. For each command in the list "bold", "italic", "strikethrough",
576        // "subscript", "superscript", "underline", in order:
577        // if there is a state override for command, add (command, command's state override) to overrides.
578        for command in [
579            CommandName::Bold,
580            CommandName::Italic,
581            CommandName::Strikethrough,
582            CommandName::Subscript,
583            CommandName::Superscript,
584            CommandName::Underline,
585        ] {
586            if let Some(state_override) =
587                RecordedStateOfCommand::for_command_state_override(command, document)
588            {
589                overrides.push(state_override);
590            }
591        }
592        // Step 4. For each command in the list "fontName", "fontSize", "foreColor", "hiliteColor",
593        // in order: if there is a value override for command,
594        // add (command, command's value override) to overrides.
595        for command in [
596            CommandName::FontName,
597            CommandName::FontSize,
598            CommandName::ForeColor,
599            CommandName::HiliteColor,
600        ] {
601            if let Some(value_override) =
602                RecordedStateOfCommand::for_command_value_override(command, document)
603            {
604                overrides.push(value_override);
605            }
606        }
607        // Step 5. Return overrides.
608        overrides
609    }
610
611    /// <https://w3c.github.io/editing/docs/execCommand/#relevant-css-property>
612    pub(crate) fn relevant_css_property(&self) -> Option<CssPropertyName> {
613        // > This is defined for certain inline formatting commands, and is used in algorithms specific to those commands.
614        // > It is an implementation detail, and is not exposed to authors.
615        Some(match self {
616            CommandName::BackColor => CssPropertyName::BackgroundColor,
617            CommandName::Bold => CssPropertyName::FontWeight,
618            CommandName::FontName => CssPropertyName::FontFamily,
619            CommandName::FontSize => CssPropertyName::FontSize,
620            CommandName::ForeColor => CssPropertyName::Color,
621            CommandName::HiliteColor => CssPropertyName::BackgroundColor,
622            CommandName::Italic => CssPropertyName::FontStyle,
623            // > If a command does not have a relevant CSS property specified, it defaults to null.
624            _ => return None,
625        })
626    }
627
628    pub(crate) fn resolved_value_for_node(
629        &self,
630        cx: &mut JSContext,
631        element: &Element,
632    ) -> Option<DOMString> {
633        let property = self.relevant_css_property()?;
634        property.resolved_value_for_node(cx, element)
635    }
636
637    /// <https://w3c.github.io/editing/docs/execCommand/#standard-inline-value-command>
638    pub(crate) fn is_standard_inline_value_command(&self) -> bool {
639        matches!(
640            self,
641            CommandName::BackColor |
642                CommandName::FontName |
643                CommandName::ForeColor |
644                CommandName::HiliteColor
645        )
646    }
647
648    pub(crate) fn is_enabled(&self, cx: &JSContext, range: &Range, editing_host: &Node) -> bool {
649        match self {
650            // The delete command is not enabled in the situation that the cursor is inside the
651            // editing host at the start, where a backspace would do nothing. However, if the
652            // editing host itself is selected then it is enabled.
653            //
654            // Therefore, start at the start_container and traverse its ancestors up to editing
655            // host. If the index remains 0, then there is no effective character to delete and
656            // the command is disabled.
657            CommandName::Delete => {
658                if !range.collapsed() {
659                    return true;
660                }
661                let start_container = range.start_container();
662                if *start_container == *editing_host {
663                    // TODO: This should return true. However, that crashes deletes at the start
664                    // of the editing host. There currently is no way to distinguish between a
665                    // range that is collapsed to a full node and set to before a node. Chromium
666                    // tracks this with a concept of "anchor position before/after node":
667                    // https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/renderer/core/editing/position.h;l=39;drc=a5c6d7b223bfc6028ecae4b1f17d711374238c0d
668                    return false;
669                }
670                let mut current_offset = range.start_offset();
671                for current_ancestor in
672                    start_container.inclusive_ancestors_unrooted(cx, ShadowIncluding::Yes)
673                {
674                    if current_offset != 0 {
675                        return true;
676                    }
677                    if *current_ancestor == editing_host {
678                        return false;
679                    }
680                    current_offset = current_ancestor.index();
681                }
682                false
683            },
684            _ => true,
685        }
686    }
687
688    pub(crate) fn is_enabled_in_plaintext_only_state(&self) -> bool {
689        matches!(
690            self,
691            CommandName::Copy |
692                CommandName::Cut |
693                CommandName::DefaultParagraphSeparator |
694                CommandName::FormatBlock |
695                CommandName::ForwardDelete |
696                CommandName::InsertHtml |
697                CommandName::InsertLineBreak |
698                CommandName::InsertParagraph |
699                CommandName::InsertText |
700                CommandName::Paste |
701                CommandName::Redo |
702                CommandName::StyleWithCss |
703                CommandName::Undo |
704                CommandName::Usecss |
705                CommandName::Delete
706        )
707    }
708
709    /// <https://w3c.github.io/editing/docs/execCommand/#preserves-overrides>
710    fn preserves_overrides(&self) -> bool {
711        matches!(
712            self,
713            CommandName::Delete |
714                CommandName::FormatBlock |
715                CommandName::ForwardDelete |
716                CommandName::Indent |
717                CommandName::InsertHorizontalRule |
718                CommandName::InsertHtml |
719                CommandName::InsertImage |
720                CommandName::InsertLineBreak |
721                CommandName::InsertOrderedList |
722                CommandName::InsertParagraph |
723                CommandName::InsertUnorderedList |
724                CommandName::JustifyCenter |
725                CommandName::JustifyFull |
726                CommandName::JustifyLeft |
727                CommandName::JustifyRight |
728                CommandName::Outdent
729        )
730    }
731
732    /// <https://w3c.github.io/editing/docs/execCommand/#action>
733    pub(crate) fn execute(
734        &self,
735        cx: &mut JSContext,
736        document: &Document,
737        selection: &Selection,
738        value: DOMString,
739    ) -> bool {
740        // https://w3c.github.io/editing/docs/execCommand/#preserves-overrides
741        // > If a command preserves overrides, then before taking its action,
742        // > the user agent must record current overrides.
743        let overrides = if self.preserves_overrides() {
744            Self::record_current_overrides(document)
745        } else {
746            vec![]
747        };
748        let result = match self {
749            CommandName::BackColor => execute_backcolor_command(cx, document, selection, value),
750            CommandName::Bold => execute_bold_command(cx, document, selection),
751            CommandName::CreateLink => execute_createlink_command(cx, document, selection, value),
752            CommandName::DefaultParagraphSeparator => {
753                execute_default_paragraph_separator_command(document, value)
754            },
755            CommandName::Delete => execute_delete_command(cx, document, selection),
756            CommandName::FontName => execute_fontname_command(cx, document, selection, value),
757            CommandName::FontSize => execute_fontsize_command(cx, document, selection, value),
758            CommandName::ForeColor => execute_forecolor_command(cx, document, selection, value),
759            CommandName::ForwardDelete => execute_forward_delete_command(cx, document, selection),
760            CommandName::HiliteColor => execute_hilitecolor_command(cx, document, selection, value),
761            CommandName::Indent => execute_indent_command(cx, document, selection),
762            CommandName::InsertHorizontalRule => {
763                execute_insert_horizontal_rule_command(cx, document, selection)
764            },
765            CommandName::InsertImage => {
766                execute_insert_image_command(cx, document, selection, value)
767            },
768            CommandName::InsertLineBreak => {
769                execute_insert_line_break_command(cx, document, selection)
770            },
771            CommandName::InsertParagraph => {
772                execute_insert_paragraph_command(cx, document, selection)
773            },
774            CommandName::InsertText => execute_insert_text_command(cx, document, selection, value),
775            CommandName::Italic => execute_italic_command(cx, document, selection),
776            CommandName::Outdent => execute_outdent_command(cx, document, selection),
777            CommandName::RemoveFormat => execute_removeformat_command(cx, document, selection),
778            CommandName::Strikethrough => execute_strikethrough_command(cx, document, selection),
779            CommandName::StyleWithCss => execute_style_with_css_command(document, value),
780            CommandName::Subscript => execute_subscript_command(cx, document, selection),
781            CommandName::Superscript => execute_superscript_command(cx, document, selection),
782            CommandName::Underline => execute_underline_command(cx, document, selection),
783            CommandName::Unlink => execute_unlink_command(cx, selection),
784            _ => false,
785        };
786
787        // https://w3c.github.io/editing/docs/execCommand/#preserves-overrides
788        // > After taking the action, if the active range is collapsed,
789        // > it must restore states and values from the recorded list.
790        if let Some(active_range) = selection
791            .active_range(cx)
792            .filter(|active_range| active_range.collapsed())
793        {
794            active_range.restore_states_and_values(cx, selection, document, overrides);
795        }
796
797        result
798    }
799
800    /// <https://w3c.github.io/editing/docs/execCommand/#inline-command-activated-values>
801    pub(crate) fn inline_command_activated_values(&self) -> Vec<&str> {
802        match self {
803            // https://w3c.github.io/editing/docs/execCommand/#the-bold-command
804            CommandName::Bold => vec!["bold", "600", "700", "800", "900"],
805            // https://w3c.github.io/editing/docs/execCommand/#the-italic-command
806            CommandName::Italic => vec!["italic", "oblique"],
807            // https://w3c.github.io/editing/docs/execCommand/#the-strikethrough-command
808            CommandName::Strikethrough => vec!["line-through"],
809            // https://w3c.github.io/editing/docs/execCommand/#the-subscript-command
810            CommandName::Subscript => vec!["subscript"],
811            // https://w3c.github.io/editing/docs/execCommand/#the-superscript-command
812            CommandName::Superscript => vec!["superscript"],
813            // https://w3c.github.io/editing/docs/execCommand/#the-underline-command
814            CommandName::Underline => vec!["underline"],
815            _ => vec![],
816        }
817    }
818}