1use 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#[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 if absolute_color.is_transparent() {
174 return None;
175 }
176 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 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 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 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 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)] pub(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 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 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 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 pub(crate) fn current_state(&self, cx: &mut JSContext, document: &Document) -> Option<bool> {
415 Some(match self {
416 CommandName::StyleWithCss => {
417 document.css_styling_flag()
420 },
421 _ => {
422 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 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 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 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 pub(crate) fn are_equivalent_values(
495 &self,
496 first: Option<&DOMString>,
497 second: Option<&DOMString>,
498 ) -> bool {
499 match (first, second) {
500 (None, None) => true,
502 (Some(first_str), Some(second_str)) => {
503 match self {
505 CommandName::Bold => {
506 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 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 _ => first_str == second_str,
537 }
538 },
539 _ => false,
540 }
541 }
542
543 pub(crate) fn are_loosely_equivalent_values(
545 &self,
546 first: Option<&DOMString>,
547 second: Option<&DOMString>,
548 ) -> bool {
549 if self.are_equivalent_values(first, second) {
551 return true;
552 }
553 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 pub(crate) fn record_current_overrides(document: &Document) -> Vec<RecordedStateOfCommand> {
566 let mut overrides = vec![];
568 if let Some(value_override) =
571 RecordedStateOfCommand::for_command_value_override(CommandName::CreateLink, document)
572 {
573 overrides.push(value_override);
574 }
575 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 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 overrides
609 }
610
611 pub(crate) fn relevant_css_property(&self) -> Option<CssPropertyName> {
613 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 _ => 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 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 CommandName::Delete => {
658 if !range.collapsed() {
659 return true;
660 }
661 let start_container = range.start_container();
662 if *start_container == *editing_host {
663 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 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 pub(crate) fn execute(
734 &self,
735 cx: &mut JSContext,
736 document: &Document,
737 selection: &Selection,
738 value: DOMString,
739 ) -> bool {
740 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 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 pub(crate) fn inline_command_activated_values(&self) -> Vec<&str> {
802 match self {
803 CommandName::Bold => vec!["bold", "600", "700", "800", "900"],
805 CommandName::Italic => vec!["italic", "oblique"],
807 CommandName::Strikethrough => vec!["line-through"],
809 CommandName::Subscript => vec!["subscript"],
811 CommandName::Superscript => vec!["superscript"],
813 CommandName::Underline => vec!["underline"],
815 _ => vec![],
816 }
817 }
818}