Bug 1883706: part 3) Implement `createHTML`, `createScript` and `createScriptURL...
[gecko.git] / editor / libeditor / HTMLEditUtils.cpp
blob8c3d09c1e219a7ddfa0bf3a9dbdd5478a8b19027
1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* This Source Code Form is subject to the terms of the Mozilla Public
3 * License, v. 2.0. If a copy of the MPL was not distributed with this
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 #include "HTMLEditUtils.h"
8 #include "AutoRangeArray.h" // for AutoRangeArray
9 #include "CSSEditUtils.h" // for CSSEditUtils
10 #include "EditAction.h" // for EditAction
11 #include "EditorBase.h" // for EditorBase, EditorType
12 #include "EditorDOMPoint.h" // for EditorDOMPoint, etc.
13 #include "EditorForwards.h" // for CollectChildrenOptions
14 #include "EditorUtils.h" // for EditorUtils
15 #include "HTMLEditHelpers.h" // for EditorInlineStyle
16 #include "WSRunObject.h" // for WSRunScanner
18 #include "mozilla/ArrayUtils.h" // for ArrayLength
19 #include "mozilla/Assertions.h" // for MOZ_ASSERT, etc.
20 #include "mozilla/Attributes.h"
21 #include "mozilla/StaticPrefs_editor.h" // for StaticPrefs::editor_
22 #include "mozilla/RangeUtils.h" // for RangeUtils
23 #include "mozilla/dom/DocumentInlines.h" // for GetBodyElement()
24 #include "mozilla/dom/Element.h" // for Element, nsINode
25 #include "mozilla/dom/HTMLAnchorElement.h"
26 #include "mozilla/dom/HTMLBodyElement.h"
27 #include "mozilla/dom/HTMLInputElement.h"
28 #include "mozilla/ServoCSSParser.h" // for ServoCSSParser
29 #include "mozilla/dom/StaticRange.h"
30 #include "mozilla/dom/Text.h" // for Text
32 #include "nsAString.h" // for nsAString::IsEmpty
33 #include "nsAtom.h" // for nsAtom
34 #include "nsAttrValue.h" // nsAttrValue
35 #include "nsCaseTreatment.h"
36 #include "nsCOMPtr.h" // for nsCOMPtr, operator==, etc.
37 #include "nsComputedDOMStyle.h" // for nsComputedDOMStyle
38 #include "nsDebug.h" // for NS_ASSERTION, etc.
39 #include "nsElementTable.h" // for nsHTMLElement
40 #include "nsError.h" // for NS_SUCCEEDED
41 #include "nsGkAtoms.h" // for nsGkAtoms, nsGkAtoms::a, etc.
42 #include "nsHTMLTags.h"
43 #include "nsIFrameInlines.h" // for nsIFrame::IsFlexOrGridItem()
44 #include "nsLiteralString.h" // for NS_LITERAL_STRING
45 #include "nsNameSpaceManager.h" // for kNameSpaceID_None
46 #include "nsPrintfCString.h" // nsPringfCString
47 #include "nsString.h" // for nsAutoString
48 #include "nsStyledElement.h"
49 #include "nsStyleStruct.h" // for StyleDisplay
50 #include "nsStyleUtil.h" // for nsStyleUtil
51 #include "nsTextFragment.h" // for nsTextFragment
52 #include "nsTextFrame.h" // for nsTextFrame
54 namespace mozilla {
56 using namespace dom;
57 using EditorType = EditorBase::EditorType;
59 template nsIContent* HTMLEditUtils::GetPreviousContent(
60 const EditorDOMPoint& aPoint, const WalkTreeOptions& aOptions,
61 BlockInlineCheck aBlockInlineCheck, const Element* aAncestorLimiter);
62 template nsIContent* HTMLEditUtils::GetPreviousContent(
63 const EditorRawDOMPoint& aPoint, const WalkTreeOptions& aOptions,
64 BlockInlineCheck aBlockInlineCheck, const Element* aAncestorLimiter);
65 template nsIContent* HTMLEditUtils::GetPreviousContent(
66 const EditorDOMPointInText& aPoint, const WalkTreeOptions& aOptions,
67 BlockInlineCheck aBlockInlineCheck, const Element* aAncestorLimiter);
68 template nsIContent* HTMLEditUtils::GetPreviousContent(
69 const EditorRawDOMPointInText& aPoint, const WalkTreeOptions& aOptions,
70 BlockInlineCheck aBlockInlineCheck, const Element* aAncestorLimiter);
71 template nsIContent* HTMLEditUtils::GetNextContent(
72 const EditorDOMPoint& aPoint, const WalkTreeOptions& aOptions,
73 BlockInlineCheck aBlockInlineCheck, const Element* aAncestorLimiter);
74 template nsIContent* HTMLEditUtils::GetNextContent(
75 const EditorRawDOMPoint& aPoint, const WalkTreeOptions& aOptions,
76 BlockInlineCheck aBlockInlineCheck, const Element* aAncestorLimiter);
77 template nsIContent* HTMLEditUtils::GetNextContent(
78 const EditorDOMPointInText& aPoint, const WalkTreeOptions& aOptions,
79 BlockInlineCheck aBlockInlineCheck, const Element* aAncestorLimiter);
80 template nsIContent* HTMLEditUtils::GetNextContent(
81 const EditorRawDOMPointInText& aPoint, const WalkTreeOptions& aOptions,
82 BlockInlineCheck aBlockInlineCheck, const Element* aAncestorLimiter);
84 template EditorDOMPoint HTMLEditUtils::GetPreviousEditablePoint(
85 nsIContent& aContent, const Element* aAncestorLimiter,
86 InvisibleWhiteSpaces aInvisibleWhiteSpaces,
87 TableBoundary aHowToTreatTableBoundary);
88 template EditorRawDOMPoint HTMLEditUtils::GetPreviousEditablePoint(
89 nsIContent& aContent, const Element* aAncestorLimiter,
90 InvisibleWhiteSpaces aInvisibleWhiteSpaces,
91 TableBoundary aHowToTreatTableBoundary);
92 template EditorDOMPoint HTMLEditUtils::GetNextEditablePoint(
93 nsIContent& aContent, const Element* aAncestorLimiter,
94 InvisibleWhiteSpaces aInvisibleWhiteSpaces,
95 TableBoundary aHowToTreatTableBoundary);
96 template EditorRawDOMPoint HTMLEditUtils::GetNextEditablePoint(
97 nsIContent& aContent, const Element* aAncestorLimiter,
98 InvisibleWhiteSpaces aInvisibleWhiteSpaces,
99 TableBoundary aHowToTreatTableBoundary);
101 template nsIContent* HTMLEditUtils::GetContentToPreserveInlineStyles(
102 const EditorDOMPoint& aPoint, const Element& aEditingHost);
103 template nsIContent* HTMLEditUtils::GetContentToPreserveInlineStyles(
104 const EditorRawDOMPoint& aPoint, const Element& aEditingHost);
106 template EditorDOMPoint HTMLEditUtils::GetBetterInsertionPointFor(
107 const nsIContent& aContentToInsert, const EditorDOMPoint& aPointToInsert,
108 const Element& aEditingHost);
109 template EditorRawDOMPoint HTMLEditUtils::GetBetterInsertionPointFor(
110 const nsIContent& aContentToInsert, const EditorRawDOMPoint& aPointToInsert,
111 const Element& aEditingHost);
112 template EditorDOMPoint HTMLEditUtils::GetBetterInsertionPointFor(
113 const nsIContent& aContentToInsert, const EditorRawDOMPoint& aPointToInsert,
114 const Element& aEditingHost);
115 template EditorRawDOMPoint HTMLEditUtils::GetBetterInsertionPointFor(
116 const nsIContent& aContentToInsert, const EditorDOMPoint& aPointToInsert,
117 const Element& aEditingHost);
119 template EditorDOMPoint HTMLEditUtils::GetBetterCaretPositionToInsertText(
120 const EditorDOMPoint& aPoint, const Element& aEditingHost);
121 template EditorDOMPoint HTMLEditUtils::GetBetterCaretPositionToInsertText(
122 const EditorRawDOMPoint& aPoint, const Element& aEditingHost);
123 template EditorRawDOMPoint HTMLEditUtils::GetBetterCaretPositionToInsertText(
124 const EditorDOMPoint& aPoint, const Element& aEditingHost);
125 template EditorRawDOMPoint HTMLEditUtils::GetBetterCaretPositionToInsertText(
126 const EditorRawDOMPoint& aPoint, const Element& aEditingHost);
128 template Result<EditorDOMPoint, nsresult>
129 HTMLEditUtils::ComputePointToPutCaretInElementIfOutside(
130 const Element& aElement, const EditorDOMPoint& aCurrentPoint);
131 template Result<EditorRawDOMPoint, nsresult>
132 HTMLEditUtils::ComputePointToPutCaretInElementIfOutside(
133 const Element& aElement, const EditorDOMPoint& aCurrentPoint);
134 template Result<EditorDOMPoint, nsresult>
135 HTMLEditUtils::ComputePointToPutCaretInElementIfOutside(
136 const Element& aElement, const EditorRawDOMPoint& aCurrentPoint);
137 template Result<EditorRawDOMPoint, nsresult>
138 HTMLEditUtils::ComputePointToPutCaretInElementIfOutside(
139 const Element& aElement, const EditorRawDOMPoint& aCurrentPoint);
141 template bool HTMLEditUtils::IsSameCSSColorValue(const nsAString& aColorA,
142 const nsAString& aColorB);
143 template bool HTMLEditUtils::IsSameCSSColorValue(const nsACString& aColorA,
144 const nsACString& aColorB);
146 bool HTMLEditUtils::CanContentsBeJoined(const nsIContent& aLeftContent,
147 const nsIContent& aRightContent) {
148 if (aLeftContent.NodeInfo()->NameAtom() !=
149 aRightContent.NodeInfo()->NameAtom()) {
150 return false;
153 if (!aLeftContent.IsElement()) {
154 return true; // can join text nodes, etc
156 MOZ_ASSERT(aRightContent.IsElement());
158 if (aLeftContent.NodeInfo()->NameAtom() == nsGkAtoms::font) {
159 const nsAttrValue* const leftSize =
160 aLeftContent.AsElement()->GetParsedAttr(nsGkAtoms::size);
161 const nsAttrValue* const rightSize =
162 aRightContent.AsElement()->GetParsedAttr(nsGkAtoms::size);
163 if (!leftSize ^ !rightSize || (leftSize && !leftSize->Equals(*rightSize))) {
164 return false;
167 const nsAttrValue* const leftColor =
168 aLeftContent.AsElement()->GetParsedAttr(nsGkAtoms::color);
169 const nsAttrValue* const rightColor =
170 aRightContent.AsElement()->GetParsedAttr(nsGkAtoms::color);
171 if (!leftColor ^ !rightColor ||
172 (leftColor && !leftColor->Equals(*rightColor))) {
173 return false;
176 const nsAttrValue* const leftFace =
177 aLeftContent.AsElement()->GetParsedAttr(nsGkAtoms::face);
178 const nsAttrValue* const rightFace =
179 aRightContent.AsElement()->GetParsedAttr(nsGkAtoms::face);
180 if (!leftFace ^ !rightFace || (leftFace && !leftFace->Equals(*rightFace))) {
181 return false;
184 nsStyledElement* leftStyledElement =
185 nsStyledElement::FromNode(const_cast<nsIContent*>(&aLeftContent));
186 if (!leftStyledElement) {
187 return false;
189 nsStyledElement* rightStyledElement =
190 nsStyledElement::FromNode(const_cast<nsIContent*>(&aRightContent));
191 if (!rightStyledElement) {
192 return false;
194 return CSSEditUtils::DoStyledElementsHaveSameStyle(*leftStyledElement,
195 *rightStyledElement);
198 static bool IsHTMLBlockElementByDefault(const nsIContent& aContent) {
199 if (!aContent.IsHTMLElement()) {
200 return false;
202 if (aContent.IsHTMLElement(nsGkAtoms::br)) { // shortcut for TextEditor
203 MOZ_ASSERT(!nsHTMLElement::IsBlock(
204 nsHTMLTags::CaseSensitiveAtomTagToId(nsGkAtoms::br)));
205 return false;
207 // We want to treat these as block nodes even though nsHTMLElement says
208 // they're not.
209 if (aContent.IsAnyOfHTMLElements(
210 nsGkAtoms::body, nsGkAtoms::head, nsGkAtoms::tbody, nsGkAtoms::thead,
211 nsGkAtoms::tfoot, nsGkAtoms::tr, nsGkAtoms::th, nsGkAtoms::td,
212 nsGkAtoms::dt, nsGkAtoms::dd)) {
213 return true;
216 return nsHTMLElement::IsBlock(
217 nsHTMLTags::CaseSensitiveAtomTagToId(aContent.NodeInfo()->NameAtom()));
220 bool HTMLEditUtils::IsBlockElement(const nsIContent& aContent,
221 BlockInlineCheck aBlockInlineCheck) {
222 MOZ_ASSERT(aBlockInlineCheck != BlockInlineCheck::Unused);
224 if (MOZ_UNLIKELY(!aContent.IsElement())) {
225 return false;
227 // If it's a <br>, we should always treat it as an inline element because
228 // its preceding collapse white-spaces and another <br> works same as usual
229 // even if you set its style to `display:block`.
230 if (aContent.IsHTMLElement(nsGkAtoms::br)) {
231 return false;
233 if (!StaticPrefs::editor_block_inline_check_use_computed_style() ||
234 aBlockInlineCheck == BlockInlineCheck::UseHTMLDefaultStyle) {
235 return IsHTMLBlockElementByDefault(aContent);
237 // Let's treat the document element and the body element is a block to avoid
238 // complicated things which may be detected by fuzzing.
239 if (aContent.OwnerDoc()->GetDocumentElement() == &aContent ||
240 (aContent.IsHTMLElement(nsGkAtoms::body) &&
241 aContent.OwnerDoc()->GetBodyElement() == &aContent)) {
242 return true;
244 RefPtr<const ComputedStyle> elementStyle =
245 nsComputedDOMStyle::GetComputedStyleNoFlush(aContent.AsElement());
246 if (MOZ_UNLIKELY(!elementStyle)) { // If aContent is not in the composed tree
247 return IsHTMLBlockElementByDefault(aContent);
249 const nsStyleDisplay* styleDisplay = elementStyle->StyleDisplay();
250 if (MOZ_UNLIKELY(styleDisplay->mDisplay == StyleDisplay::None)) {
251 // Typically, we should not keep handling editing in invisible nodes, but if
252 // we reach here, let's fallback to the default style for protecting the
253 // structure as far as possible.
254 return IsHTMLBlockElementByDefault(aContent);
256 // Both Blink and WebKit treat ruby style as a block, see IsEnclosingBlock()
257 // in Chromium or isBlock() in WebKit.
258 if (styleDisplay->IsRubyDisplayType()) {
259 return true;
261 // If the outside is not inline, treat it as block.
262 if (!styleDisplay->IsInlineOutsideStyle()) {
263 return true;
265 // If we're checking display-inside, inline-block, etc should be a block too.
266 return aBlockInlineCheck == BlockInlineCheck::UseComputedDisplayStyle &&
267 styleDisplay->DisplayInside() == StyleDisplayInside::FlowRoot &&
268 // Treat widgets as inline since they won't hide collapsible
269 // white-spaces around them.
270 styleDisplay->EffectiveAppearance() == StyleAppearance::None;
273 bool HTMLEditUtils::IsInlineContent(const nsIContent& aContent,
274 BlockInlineCheck aBlockInlineCheck) {
275 MOZ_ASSERT(aBlockInlineCheck != BlockInlineCheck::Unused);
277 if (!aContent.IsElement()) {
278 return true;
280 // If it's a <br>, we should always treat it as an inline element because
281 // its preceding collapse white-spaces and another <br> works same as usual
282 // even if you set its style to `display:block`.
283 if (aContent.IsHTMLElement(nsGkAtoms::br)) {
284 return true;
286 if (!StaticPrefs::editor_block_inline_check_use_computed_style() ||
287 aBlockInlineCheck == BlockInlineCheck::UseHTMLDefaultStyle) {
288 return !IsHTMLBlockElementByDefault(aContent);
290 // Let's treat the document element and the body element is a block to avoid
291 // complicated things which may be detected by fuzzing.
292 if (aContent.OwnerDoc()->GetDocumentElement() == &aContent ||
293 (aContent.IsHTMLElement(nsGkAtoms::body) &&
294 aContent.OwnerDoc()->GetBodyElement() == &aContent)) {
295 return false;
297 RefPtr<const ComputedStyle> elementStyle =
298 nsComputedDOMStyle::GetComputedStyleNoFlush(aContent.AsElement());
299 if (MOZ_UNLIKELY(!elementStyle)) { // If aContent is not in the composed tree
300 return !IsHTMLBlockElementByDefault(aContent);
302 const nsStyleDisplay* styleDisplay = elementStyle->StyleDisplay();
303 if (MOZ_UNLIKELY(styleDisplay->mDisplay == StyleDisplay::None)) {
304 // Similar to IsBlockElement, let's fallback to refer the default style.
305 // Note that if you change here, you may need to check the parent element
306 // style if aContent.
307 return !IsHTMLBlockElementByDefault(aContent);
309 // Different block IsBlockElement, when the display-outside is inline, it's
310 // simply an inline element.
311 return styleDisplay->IsInlineOutsideStyle() ||
312 styleDisplay->IsRubyDisplayType();
315 bool HTMLEditUtils::IsFlexOrGridItem(const Element& aElement) {
316 nsIFrame* frame = aElement.GetPrimaryFrame();
317 return frame && frame->IsFlexOrGridItem();
320 bool HTMLEditUtils::IsInclusiveAncestorCSSDisplayNone(
321 const nsIContent& aContent) {
322 if (NS_WARN_IF(!aContent.IsInComposedDoc())) {
323 return true;
325 for (const Element* element :
326 aContent.InclusiveFlatTreeAncestorsOfType<Element>()) {
327 RefPtr<const ComputedStyle> elementStyle =
328 nsComputedDOMStyle::GetComputedStyleNoFlush(element);
329 if (NS_WARN_IF(!elementStyle)) {
330 continue;
332 const nsStyleDisplay* styleDisplay = elementStyle->StyleDisplay();
333 if (MOZ_UNLIKELY(styleDisplay->mDisplay == StyleDisplay::None)) {
334 return true;
337 return false;
340 bool HTMLEditUtils::IsVisibleElementEvenIfLeafNode(const nsIContent& aContent) {
341 if (!aContent.IsElement()) {
342 return false;
344 // Assume non-HTML element is visible.
345 if (!aContent.IsHTMLElement()) {
346 return true;
348 // XXX Should we return false if the element is display:none?
349 if (HTMLEditUtils::IsBlockElement(
350 aContent, BlockInlineCheck::UseComputedDisplayStyle)) {
351 return true;
353 if (aContent.IsAnyOfHTMLElements(nsGkAtoms::applet, nsGkAtoms::iframe,
354 nsGkAtoms::img, nsGkAtoms::meter,
355 nsGkAtoms::progress, nsGkAtoms::select,
356 nsGkAtoms::textarea)) {
357 return true;
359 if (const HTMLInputElement* inputElement =
360 HTMLInputElement::FromNode(&aContent)) {
361 return inputElement->ControlType() != FormControlType::InputHidden;
363 // Maybe, empty inline element such as <span>.
364 return false;
368 * IsInlineStyle() returns true if aNode is an inline style.
370 bool HTMLEditUtils::IsInlineStyle(nsINode* aNode) {
371 MOZ_ASSERT(aNode);
372 return aNode->IsAnyOfHTMLElements(
373 nsGkAtoms::b, nsGkAtoms::i, nsGkAtoms::u, nsGkAtoms::tt, nsGkAtoms::s,
374 nsGkAtoms::strike, nsGkAtoms::big, nsGkAtoms::small, nsGkAtoms::sub,
375 nsGkAtoms::sup, nsGkAtoms::font);
378 bool HTMLEditUtils::IsDisplayOutsideInline(const Element& aElement) {
379 RefPtr<const ComputedStyle> elementStyle =
380 nsComputedDOMStyle::GetComputedStyleNoFlush(&aElement);
381 if (!elementStyle) {
382 return false;
384 return elementStyle->StyleDisplay()->DisplayOutside() ==
385 StyleDisplayOutside::Inline;
388 bool HTMLEditUtils::IsDisplayInsideFlowRoot(const Element& aElement) {
389 RefPtr<const ComputedStyle> elementStyle =
390 nsComputedDOMStyle::GetComputedStyleNoFlush(&aElement);
391 if (!elementStyle) {
392 return false;
394 return elementStyle->StyleDisplay()->DisplayInside() ==
395 StyleDisplayInside::FlowRoot;
398 bool HTMLEditUtils::IsRemovableInlineStyleElement(Element& aElement) {
399 if (!aElement.IsHTMLElement()) {
400 return false;
402 // https://w3c.github.io/editing/execCommand.html#removeformat-candidate
403 if (aElement.IsAnyOfHTMLElements(
404 nsGkAtoms::abbr, // Chrome ignores, but does not make sense.
405 nsGkAtoms::acronym, nsGkAtoms::b,
406 nsGkAtoms::bdi, // Chrome ignores, but does not make sense.
407 nsGkAtoms::bdo, nsGkAtoms::big, nsGkAtoms::cite, nsGkAtoms::code,
408 // nsGkAtoms::del, Chrome ignores, but does not make sense but
409 // execCommand unofficial draft excludes this. Spec issue:
410 // https://github.com/w3c/editing/issues/192
411 nsGkAtoms::dfn, nsGkAtoms::em, nsGkAtoms::font, nsGkAtoms::i,
412 nsGkAtoms::ins, nsGkAtoms::kbd,
413 nsGkAtoms::mark, // Chrome ignores, but does not make sense.
414 nsGkAtoms::nobr, nsGkAtoms::q, nsGkAtoms::s, nsGkAtoms::samp,
415 nsGkAtoms::small, nsGkAtoms::span, nsGkAtoms::strike,
416 nsGkAtoms::strong, nsGkAtoms::sub, nsGkAtoms::sup, nsGkAtoms::tt,
417 nsGkAtoms::u, nsGkAtoms::var)) {
418 return true;
420 // If it's a <blink> element, we can remove it.
421 nsAutoString tagName;
422 aElement.GetTagName(tagName);
423 return tagName.LowerCaseEqualsASCII("blink");
427 * IsNodeThatCanOutdent() returns true if aNode is a list, list item or
428 * blockquote.
430 bool HTMLEditUtils::IsNodeThatCanOutdent(nsINode* aNode) {
431 MOZ_ASSERT(aNode);
432 return aNode->IsAnyOfHTMLElements(nsGkAtoms::ul, nsGkAtoms::ol, nsGkAtoms::dl,
433 nsGkAtoms::li, nsGkAtoms::dd, nsGkAtoms::dt,
434 nsGkAtoms::blockquote);
438 * IsHeader() returns true if aNode is an html header.
440 bool HTMLEditUtils::IsHeader(nsINode& aNode) {
441 return aNode.IsAnyOfHTMLElements(nsGkAtoms::h1, nsGkAtoms::h2, nsGkAtoms::h3,
442 nsGkAtoms::h4, nsGkAtoms::h5, nsGkAtoms::h6);
446 * IsListItem() returns true if aNode is an html list item.
448 bool HTMLEditUtils::IsListItem(const nsINode* aNode) {
449 MOZ_ASSERT(aNode);
450 return aNode->IsAnyOfHTMLElements(nsGkAtoms::li, nsGkAtoms::dd,
451 nsGkAtoms::dt);
455 * IsAnyTableElement() returns true if aNode is an html table, td, tr, ...
457 bool HTMLEditUtils::IsAnyTableElement(const nsINode* aNode) {
458 MOZ_ASSERT(aNode);
459 return aNode->IsAnyOfHTMLElements(
460 nsGkAtoms::table, nsGkAtoms::tr, nsGkAtoms::td, nsGkAtoms::th,
461 nsGkAtoms::thead, nsGkAtoms::tfoot, nsGkAtoms::tbody, nsGkAtoms::caption);
465 * IsAnyTableElementButNotTable() returns true if aNode is an html td, tr, ...
466 * (doesn't include table)
468 bool HTMLEditUtils::IsAnyTableElementButNotTable(nsINode* aNode) {
469 MOZ_ASSERT(aNode);
470 return aNode->IsAnyOfHTMLElements(nsGkAtoms::tr, nsGkAtoms::td, nsGkAtoms::th,
471 nsGkAtoms::thead, nsGkAtoms::tfoot,
472 nsGkAtoms::tbody, nsGkAtoms::caption);
476 * IsTable() returns true if aNode is an html table.
478 bool HTMLEditUtils::IsTable(nsINode* aNode) {
479 return aNode && aNode->IsHTMLElement(nsGkAtoms::table);
483 * IsTableRow() returns true if aNode is an html tr.
485 bool HTMLEditUtils::IsTableRow(nsINode* aNode) {
486 return aNode && aNode->IsHTMLElement(nsGkAtoms::tr);
490 * IsTableCell() returns true if aNode is an html td or th.
492 bool HTMLEditUtils::IsTableCell(const nsINode* aNode) {
493 MOZ_ASSERT(aNode);
494 return aNode->IsAnyOfHTMLElements(nsGkAtoms::td, nsGkAtoms::th);
498 * IsTableCellOrCaption() returns true if aNode is an html td or th or caption.
500 bool HTMLEditUtils::IsTableCellOrCaption(nsINode& aNode) {
501 return aNode.IsAnyOfHTMLElements(nsGkAtoms::td, nsGkAtoms::th,
502 nsGkAtoms::caption);
506 * IsAnyListElement() returns true if aNode is an html list.
508 bool HTMLEditUtils::IsAnyListElement(const nsINode* aNode) {
509 MOZ_ASSERT(aNode);
510 return aNode->IsAnyOfHTMLElements(nsGkAtoms::ul, nsGkAtoms::ol,
511 nsGkAtoms::dl);
515 * IsPre() returns true if aNode is an html pre node.
517 bool HTMLEditUtils::IsPre(const nsINode* aNode) {
518 return aNode && aNode->IsHTMLElement(nsGkAtoms::pre);
522 * IsImage() returns true if aNode is an html image node.
524 bool HTMLEditUtils::IsImage(nsINode* aNode) {
525 return aNode && aNode->IsHTMLElement(nsGkAtoms::img);
528 bool HTMLEditUtils::IsLink(const nsINode* aNode) {
529 MOZ_ASSERT(aNode);
531 if (!aNode->IsContent()) {
532 return false;
535 RefPtr<const dom::HTMLAnchorElement> anchor =
536 dom::HTMLAnchorElement::FromNodeOrNull(aNode->AsContent());
537 if (!anchor) {
538 return false;
541 nsAutoString tmpText;
542 anchor->GetHref(tmpText);
543 return !tmpText.IsEmpty();
546 bool HTMLEditUtils::IsNamedAnchor(const nsINode* aNode) {
547 MOZ_ASSERT(aNode);
548 if (!aNode->IsHTMLElement(nsGkAtoms::a)) {
549 return false;
552 nsAutoString text;
553 return aNode->AsElement()->GetAttr(nsGkAtoms::name, text) && !text.IsEmpty();
557 * IsMozDiv() returns true if aNode is an html div node with |type = _moz|.
559 bool HTMLEditUtils::IsMozDiv(nsINode* aNode) {
560 MOZ_ASSERT(aNode);
561 return aNode->IsHTMLElement(nsGkAtoms::div) &&
562 aNode->AsElement()->AttrValueIs(kNameSpaceID_None, nsGkAtoms::type,
563 u"_moz"_ns, eIgnoreCase);
567 * IsMailCite() returns true if aNode is an html blockquote with |type=cite|.
569 bool HTMLEditUtils::IsMailCite(const Element& aElement) {
570 // don't ask me why, but our html mailcites are id'd by "type=cite"...
571 if (aElement.AttrValueIs(kNameSpaceID_None, nsGkAtoms::type, u"cite"_ns,
572 eIgnoreCase)) {
573 return true;
576 // ... but our plaintext mailcites by "_moz_quote=true". go figure.
577 if (aElement.AttrValueIs(kNameSpaceID_None, nsGkAtoms::mozquote, u"true"_ns,
578 eIgnoreCase)) {
579 return true;
582 return false;
586 * IsFormWidget() returns true if aNode is a form widget of some kind.
588 bool HTMLEditUtils::IsFormWidget(const nsINode* aNode) {
589 MOZ_ASSERT(aNode);
590 return aNode->IsAnyOfHTMLElements(nsGkAtoms::textarea, nsGkAtoms::select,
591 nsGkAtoms::button, nsGkAtoms::output,
592 nsGkAtoms::progress, nsGkAtoms::meter,
593 nsGkAtoms::input);
596 bool HTMLEditUtils::SupportsAlignAttr(nsINode& aNode) {
597 return aNode.IsAnyOfHTMLElements(
598 nsGkAtoms::hr, nsGkAtoms::table, nsGkAtoms::tbody, nsGkAtoms::tfoot,
599 nsGkAtoms::thead, nsGkAtoms::tr, nsGkAtoms::td, nsGkAtoms::th,
600 nsGkAtoms::div, nsGkAtoms::p, nsGkAtoms::h1, nsGkAtoms::h2, nsGkAtoms::h3,
601 nsGkAtoms::h4, nsGkAtoms::h5, nsGkAtoms::h6);
604 bool HTMLEditUtils::IsVisibleTextNode(const Text& aText) {
605 if (!aText.TextDataLength()) {
606 return false;
609 Maybe<uint32_t> visibleCharOffset =
610 HTMLEditUtils::GetInclusiveNextNonCollapsibleCharOffset(
611 EditorDOMPointInText(&aText, 0));
612 if (visibleCharOffset.isSome()) {
613 return true;
616 // Now, all characters in aText is collapsible white-spaces. The node is
617 // invisible if next to block boundary.
618 return !HTMLEditUtils::GetElementOfImmediateBlockBoundary(
619 aText, WalkTreeDirection::Forward) &&
620 !HTMLEditUtils::GetElementOfImmediateBlockBoundary(
621 aText, WalkTreeDirection::Backward);
624 bool HTMLEditUtils::IsInVisibleTextFrames(nsPresContext* aPresContext,
625 const Text& aText) {
626 // TODO(dholbert): aPresContext is now unused; maybe we can remove it, here
627 // and in IsEmptyNode? We do use it as a signal (implicitly here,
628 // more-explicitly in IsEmptyNode) that we are in a "SafeToAskLayout" case...
629 // If/when we remove it, we should be sure we're not losing that signal of
630 // strictness, since this function here does absolutely need to query layout.
631 MOZ_ASSERT(aPresContext);
633 if (!aText.TextDataLength()) {
634 return false;
637 nsTextFrame* textFrame = do_QueryFrame(aText.GetPrimaryFrame());
638 if (!textFrame) {
639 return false;
642 return textFrame->HasVisibleText();
645 Element* HTMLEditUtils::GetElementOfImmediateBlockBoundary(
646 const nsIContent& aContent, const WalkTreeDirection aDirection) {
647 MOZ_ASSERT(aContent.IsHTMLElement(nsGkAtoms::br) || aContent.IsText());
649 // First, we get a block container. This is not designed for reaching
650 // no block boundaries in the tree.
651 Element* maybeNonEditableAncestorBlock = HTMLEditUtils::GetAncestorElement(
652 aContent, HTMLEditUtils::ClosestBlockElement,
653 BlockInlineCheck::UseComputedDisplayStyle);
654 if (NS_WARN_IF(!maybeNonEditableAncestorBlock)) {
655 return nullptr;
658 auto getNextContent = [&aDirection, &maybeNonEditableAncestorBlock](
659 const nsIContent& aContent) -> nsIContent* {
660 return aDirection == WalkTreeDirection::Forward
661 ? HTMLEditUtils::GetNextContent(
662 aContent,
663 {WalkTreeOption::IgnoreDataNodeExceptText,
664 WalkTreeOption::StopAtBlockBoundary},
665 BlockInlineCheck::UseComputedDisplayStyle,
666 maybeNonEditableAncestorBlock)
667 : HTMLEditUtils::GetPreviousContent(
668 aContent,
669 {WalkTreeOption::IgnoreDataNodeExceptText,
670 WalkTreeOption::StopAtBlockBoundary},
671 BlockInlineCheck::UseComputedDisplayStyle,
672 maybeNonEditableAncestorBlock);
675 // Then, scan block element boundary while we don't see visible things.
676 const bool isBRElement = aContent.IsHTMLElement(nsGkAtoms::br);
677 for (nsIContent* nextContent = getNextContent(aContent); nextContent;
678 nextContent = getNextContent(*nextContent)) {
679 if (nextContent->IsElement()) {
680 // Break is right before a child block, it's not visible
681 if (HTMLEditUtils::IsBlockElement(
682 *nextContent, BlockInlineCheck::UseComputedDisplayStyle)) {
683 return nextContent->AsElement();
686 // XXX How about other non-HTML elements? Assume they are styled as
687 // blocks for now.
688 if (!nextContent->IsHTMLElement()) {
689 return nextContent->AsElement();
692 // If there is a visible content which generates something visible,
693 // stop scanning.
694 if (HTMLEditUtils::IsVisibleElementEvenIfLeafNode(*nextContent)) {
695 return nullptr;
698 if (nextContent->IsHTMLElement(nsGkAtoms::br)) {
699 // If aContent is a <br> element, another <br> element prevents the
700 // block boundary special handling.
701 if (isBRElement) {
702 return nullptr;
705 MOZ_ASSERT(aContent.IsText());
706 // Following <br> element always hides its following block boundary.
707 // I.e., white-spaces is at end of the text node is visible.
708 if (aDirection == WalkTreeDirection::Forward) {
709 return nullptr;
711 // Otherwise, if text node follows <br> element, its white-spaces at
712 // start of the text node are invisible. In this case, we return
713 // the found <br> element.
714 return nextContent->AsElement();
717 continue;
720 switch (nextContent->NodeType()) {
721 case nsINode::TEXT_NODE:
722 case nsINode::CDATA_SECTION_NODE:
723 break;
724 default:
725 continue;
728 Text* textNode = Text::FromNode(nextContent);
729 MOZ_ASSERT(textNode);
730 if (!textNode->TextLength()) {
731 continue; // empty invisible text node, keep scanning next one.
733 if (HTMLEditUtils::IsInclusiveAncestorCSSDisplayNone(*textNode)) {
734 continue; // Styled as invisible.
736 if (!textNode->TextIsOnlyWhitespace()) {
737 return nullptr; // found a visible text node.
739 const nsTextFragment& textFragment = textNode->TextFragment();
740 const bool isWhiteSpacePreformatted =
741 EditorUtils::IsWhiteSpacePreformatted(*textNode);
742 const bool isNewLinePreformatted =
743 EditorUtils::IsNewLinePreformatted(*textNode);
744 if (!isWhiteSpacePreformatted && !isNewLinePreformatted) {
745 // if the white-space only text node is not preformatted, ignore it.
746 continue;
748 for (uint32_t i = 0; i < textFragment.GetLength(); i++) {
749 if (textFragment.CharAt(i) == HTMLEditUtils::kNewLine) {
750 if (isNewLinePreformatted) {
751 return nullptr; // found a visible text node.
753 continue;
755 if (isWhiteSpacePreformatted) {
756 return nullptr; // found a visible text node.
759 // All white-spaces in the text node is invisible, keep scanning next one.
762 // There is no visible content and reached current block boundary. Then,
763 // the <br> element is the last content in the block and invisible.
764 // XXX Should we treat it visible if it's the only child of a block?
765 return maybeNonEditableAncestorBlock;
768 nsIContent* HTMLEditUtils::GetUnnecessaryLineBreakContent(
769 const Element& aBlockElement, ScanLineBreak aScanLineBreak) {
770 auto* lastLineBreakContent = [&]() -> nsIContent* {
771 const LeafNodeTypes leafNodeOrNonEditableNode{
772 LeafNodeType::LeafNodeOrNonEditableNode};
773 const WalkTreeOptions onlyPrecedingLine{
774 WalkTreeOption::StopAtBlockBoundary};
775 for (nsIContent* content =
776 aScanLineBreak == ScanLineBreak::AtEndOfBlock
777 ? HTMLEditUtils::GetLastLeafContent(aBlockElement,
778 leafNodeOrNonEditableNode)
779 : HTMLEditUtils::GetPreviousContent(
780 aBlockElement, onlyPrecedingLine,
781 BlockInlineCheck::UseComputedDisplayStyle,
782 aBlockElement.GetParentElement());
783 content;
784 content =
785 aScanLineBreak == ScanLineBreak::AtEndOfBlock
786 ? HTMLEditUtils::GetPreviousLeafContentOrPreviousBlockElement(
787 *content, aBlockElement, leafNodeOrNonEditableNode,
788 BlockInlineCheck::UseComputedDisplayStyle)
789 : HTMLEditUtils::GetPreviousContent(
790 *content, onlyPrecedingLine,
791 BlockInlineCheck::UseComputedDisplayStyle,
792 aBlockElement.GetParentElement())) {
793 // If we're scanning preceding <br> element of aBlockElement, we don't
794 // need to look for a line break in another block because the caller
795 // needs to handle only preceding <br> element of aBlockElement.
796 if (aScanLineBreak == ScanLineBreak::BeforeBlock &&
797 HTMLEditUtils::IsBlockElement(
798 *content, BlockInlineCheck::UseComputedDisplayStyle)) {
799 return nullptr;
801 if (Text* textNode = Text::FromNode(content)) {
802 if (!textNode->TextLength()) {
803 continue; // ignore empty text node
805 const nsTextFragment& textFragment = textNode->TextFragment();
806 if (EditorUtils::IsNewLinePreformatted(*textNode) &&
807 textFragment.CharAt(textFragment.GetLength() - 1u) ==
808 HTMLEditUtils::kNewLine) {
809 // If the text node ends with a preserved line break, it's unnecessary
810 // unless it follows another preformatted line break.
811 if (textFragment.GetLength() == 1u) {
812 return textNode; // Need to scan previous leaf.
814 return textFragment.CharAt(textFragment.GetLength() - 2u) ==
815 HTMLEditUtils::kNewLine
816 ? nullptr
817 : textNode;
819 if (HTMLEditUtils::IsVisibleTextNode(*textNode)) {
820 return nullptr;
822 continue;
824 if (content->IsCharacterData()) {
825 continue; // ignore hidden character data nodes like comment
827 if (content->IsHTMLElement(nsGkAtoms::br)) {
828 return content;
830 // If found element is empty block or visible element, there is no
831 // unnecessary line break.
832 if (HTMLEditUtils::IsVisibleElementEvenIfLeafNode(*content)) {
833 return nullptr;
835 // Otherwise, e.g., empty <b>, we should keep scanning.
837 return nullptr;
838 }();
839 if (!lastLineBreakContent) {
840 return nullptr;
843 // If the found node is a text node and contains only one preformatted new
844 // line break, we need to keep scanning previous one, but if it has 2 or more
845 // characters, we know it has redundant line break.
846 Text* lastLineBreakText = Text::FromNode(lastLineBreakContent);
847 if (lastLineBreakText && lastLineBreakText->TextDataLength() != 1u) {
848 return lastLineBreakText;
851 // Scan previous leaf content, but now, we can stop at child block boundary.
852 const LeafNodeTypes leafNodeOrNonEditableNodeOrChildBlock{
853 LeafNodeType::LeafNodeOrNonEditableNode,
854 LeafNodeType::LeafNodeOrChildBlock};
855 const Element* blockElement = HTMLEditUtils::GetAncestorElement(
856 *lastLineBreakContent, HTMLEditUtils::ClosestBlockElement,
857 BlockInlineCheck::UseComputedDisplayStyle);
858 for (nsIContent* content =
859 HTMLEditUtils::GetPreviousLeafContentOrPreviousBlockElement(
860 *lastLineBreakContent, *blockElement,
861 leafNodeOrNonEditableNodeOrChildBlock,
862 BlockInlineCheck::UseComputedDisplayStyle);
863 content;
864 content = HTMLEditUtils::GetPreviousLeafContentOrPreviousBlockElement(
865 *content, *blockElement, leafNodeOrNonEditableNodeOrChildBlock,
866 BlockInlineCheck::UseComputedDisplayStyle)) {
867 if (HTMLEditUtils::IsBlockElement(
868 *content, BlockInlineCheck::UseComputedDisplayStyle) ||
869 (content->IsElement() && !content->IsHTMLElement())) {
870 // Now, must found <div>...<div>...</div><br></div>
871 // ^^^^
872 // In this case, the <br> element is necessary to make a following empty
873 // line of the inner <div> visible.
874 return nullptr;
876 if (Text* textNode = Text::FromNode(content)) {
877 if (!textNode->TextLength()) {
878 continue; // ignore empty text node
880 const nsTextFragment& textFragment = textNode->TextFragment();
881 if (EditorUtils::IsNewLinePreformatted(*textNode) &&
882 textFragment.CharAt(textFragment.GetLength() - 1u) ==
883 HTMLEditUtils::kNewLine) {
884 // So, we are here because the preformatted line break is followed by
885 // lastLineBreakContent which is <br> or a text node containing only
886 // one. In this case, even if their parents are different,
887 // lastLineBreakContent is necessary to make the last line visible.
888 return nullptr;
890 if (!HTMLEditUtils::IsVisibleTextNode(*textNode)) {
891 continue;
893 if (EditorUtils::IsWhiteSpacePreformatted(*textNode)) {
894 // If the white-space is preserved, neither following <br> nor a
895 // preformatted line break is not necessary.
896 return lastLineBreakContent;
898 // Otherwise, only if the last character is a collapsible white-space,
899 // we need lastLineBreakContent to make the trailing white-space visible.
900 switch (textFragment.CharAt(textFragment.GetLength() - 1u)) {
901 case HTMLEditUtils::kSpace:
902 case HTMLEditUtils::kCarriageReturn:
903 case HTMLEditUtils::kTab:
904 case HTMLEditUtils::kNBSP:
905 return nullptr;
906 default:
907 return lastLineBreakContent;
910 if (content->IsCharacterData()) {
911 continue; // ignore hidden character data nodes like comment
913 // If lastLineBreakContent follows a <br> element in same block, it's
914 // necessary to make the empty last line visible.
915 if (content->IsHTMLElement(nsGkAtoms::br)) {
916 return nullptr;
918 // If it follows a visible element, it's unnecessary line break.
919 if (HTMLEditUtils::IsVisibleElementEvenIfLeafNode(*content)) {
920 return lastLineBreakContent;
922 // Otherwise, ignore empty inline elements such as <b>.
924 // If the block is empty except invisible data nodes and lastLineBreakContent,
925 // lastLineBreakContent is necessary to make the block visible.
926 return nullptr;
929 bool HTMLEditUtils::IsEmptyNode(nsPresContext* aPresContext,
930 const nsINode& aNode,
931 const EmptyCheckOptions& aOptions /* = {} */,
932 bool* aSeenBR /* = nullptr */) {
933 MOZ_ASSERT_IF(aOptions.contains(EmptyCheckOption::SafeToAskLayout),
934 aPresContext);
936 if (aSeenBR) {
937 *aSeenBR = false;
940 if (const Text* text = Text::FromNode(&aNode)) {
941 return aOptions.contains(EmptyCheckOption::SafeToAskLayout)
942 ? !IsInVisibleTextFrames(aPresContext, *text)
943 : !IsVisibleTextNode(*text);
946 if (!aNode.IsElement()) {
947 return false;
950 if (
951 // If it's not a container such as an <hr> or <br>, etc, it should be
952 // treated as not empty.
953 !IsContainerNode(*aNode.AsContent()) ||
954 // If it's a named anchor, we shouldn't treat it as empty because it
955 // has special meaning even if invisible.
956 IsNamedAnchor(&aNode) ||
957 // Form widgets should be treated as not empty because they have special
958 // meaning even if invisible.
959 IsFormWidget(&aNode)) {
960 return false;
963 const auto [isListItem, isTableCell, hasAppearance] =
964 [&]() MOZ_NEVER_INLINE_DEBUG -> std::tuple<bool, bool, bool> {
965 if (!StaticPrefs::editor_block_inline_check_use_computed_style()) {
966 return {IsListItem(&aNode), IsTableCell(&aNode), false};
968 // Let's stop treating the document element and the <body> as a list item
969 // nor a table cell to avoid tricky cases.
970 if (aNode.OwnerDoc()->GetDocumentElement() == &aNode ||
971 (aNode.IsHTMLElement(nsGkAtoms::body) &&
972 aNode.OwnerDoc()->GetBodyElement() == &aNode)) {
973 return {false, false, false};
976 RefPtr<const ComputedStyle> elementStyle =
977 nsComputedDOMStyle::GetComputedStyleNoFlush(aNode.AsElement());
978 // If there is no style information like in a document fragment, let's refer
979 // the default style.
980 if (MOZ_UNLIKELY(!elementStyle)) {
981 return {IsListItem(&aNode), IsTableCell(&aNode), false};
983 const nsStyleDisplay* styleDisplay = elementStyle->StyleDisplay();
984 if (NS_WARN_IF(!styleDisplay)) {
985 return {IsListItem(&aNode), IsTableCell(&aNode), false};
987 if (styleDisplay->mDisplay != StyleDisplay::None &&
988 styleDisplay->HasAppearance()) {
989 return {false, false, true};
991 if (styleDisplay->IsListItem()) {
992 return {true, false, false};
994 if (styleDisplay->mDisplay == StyleDisplay::TableCell) {
995 return {false, true, false};
997 // The default display of <dt> and <dd> is block. Therefore, we need
998 // special handling for them.
999 return {styleDisplay->mDisplay == StyleDisplay::Block &&
1000 aNode.IsAnyOfHTMLElements(nsGkAtoms::dd, nsGkAtoms::dt),
1001 false, false};
1002 }();
1004 // The web author created native widget without form control elements. Let's
1005 // treat it as visible.
1006 if (hasAppearance) {
1007 return false;
1010 if (isListItem &&
1011 aOptions.contains(EmptyCheckOption::TreatListItemAsVisible)) {
1012 return false;
1014 if (isTableCell &&
1015 aOptions.contains(EmptyCheckOption::TreatTableCellAsVisible)) {
1016 return false;
1019 bool seenBR = aSeenBR && *aSeenBR;
1020 for (nsIContent* childContent = aNode.GetFirstChild(); childContent;
1021 childContent = childContent->GetNextSibling()) {
1022 // Is the child editable and non-empty? if so, return false
1023 if (aOptions.contains(
1024 EmptyCheckOption::TreatNonEditableContentAsInvisible) &&
1025 !EditorUtils::IsEditableContent(*childContent, EditorType::HTML)) {
1026 continue;
1029 if (Text* text = Text::FromNode(childContent)) {
1030 // break out if we find we aren't empty
1031 if (aOptions.contains(EmptyCheckOption::SafeToAskLayout)
1032 ? IsInVisibleTextFrames(aPresContext, *text)
1033 : IsVisibleTextNode(*text)) {
1034 return false;
1036 continue;
1039 MOZ_ASSERT(childContent != &aNode);
1041 if (!aOptions.contains(EmptyCheckOption::TreatSingleBRElementAsVisible) &&
1042 !seenBR && childContent->IsHTMLElement(nsGkAtoms::br)) {
1043 // Ignore first <br> element in it if caller wants so because it's
1044 // typically a padding <br> element of for a parent block.
1045 seenBR = true;
1046 if (aSeenBR) {
1047 *aSeenBR = true;
1049 continue;
1052 // Note: list items or table cells are not considered empty
1053 // if they contain other lists or tables
1054 EmptyCheckOptions options(aOptions);
1055 if (childContent->IsElement() && (isListItem || isTableCell)) {
1056 options += {EmptyCheckOption::TreatListItemAsVisible,
1057 EmptyCheckOption::TreatTableCellAsVisible};
1059 if (!IsEmptyNode(aPresContext, *childContent, options, &seenBR)) {
1060 if (aSeenBR) {
1061 *aSeenBR = seenBR;
1063 return false;
1067 if (aSeenBR) {
1068 *aSeenBR = seenBR;
1070 return true;
1073 bool HTMLEditUtils::ShouldInsertLinefeedCharacter(
1074 const EditorDOMPoint& aPointToInsert, const Element& aEditingHost) {
1075 MOZ_ASSERT(aPointToInsert.IsSetAndValid());
1077 if (!aPointToInsert.IsInContentNode()) {
1078 return false;
1081 // closestEditableBlockElement can be nullptr if aEditingHost is an inline
1082 // element.
1083 Element* closestEditableBlockElement =
1084 HTMLEditUtils::GetInclusiveAncestorElement(
1085 *aPointToInsert.ContainerAs<nsIContent>(),
1086 HTMLEditUtils::ClosestEditableBlockElement,
1087 BlockInlineCheck::UseComputedDisplayOutsideStyle);
1089 // If and only if the nearest block is the editing host or its parent,
1090 // and new line character is preformatted, we should insert a linefeed.
1091 return (!closestEditableBlockElement ||
1092 closestEditableBlockElement == &aEditingHost) &&
1093 EditorUtils::IsNewLinePreformatted(
1094 *aPointToInsert.ContainerAs<nsIContent>());
1097 // We use bitmasks to test containment of elements. Elements are marked to be
1098 // in certain groups by setting the mGroup member of the `ElementInfo` struct
1099 // to the corresponding GROUP_ values (OR'ed together). Similarly, elements are
1100 // marked to allow containment of certain groups by setting the
1101 // mCanContainGroups member of the `ElementInfo` struct to the corresponding
1102 // GROUP_ values (OR'ed together).
1103 // Testing containment then simply consists of checking whether the
1104 // mCanContainGroups bitmask of an element and the mGroup bitmask of a
1105 // potential child overlap.
1107 #define GROUP_NONE 0
1109 // body, head, html
1110 #define GROUP_TOPLEVEL (1 << 1)
1112 // base, link, meta, script, style, title
1113 #define GROUP_HEAD_CONTENT (1 << 2)
1115 // b, big, i, s, small, strike, tt, u
1116 #define GROUP_FONTSTYLE (1 << 3)
1118 // abbr, acronym, cite, code, datalist, del, dfn, em, ins, kbd, mark, rb, rp
1119 // rt, rtc, ruby, samp, strong, var
1120 #define GROUP_PHRASE (1 << 4)
1122 // a, applet, basefont, bdi, bdo, br, font, iframe, img, map, meter, object,
1123 // output, picture, progress, q, script, span, sub, sup
1124 #define GROUP_SPECIAL (1 << 5)
1126 // button, form, input, label, select, textarea
1127 #define GROUP_FORMCONTROL (1 << 6)
1129 // address, applet, article, aside, blockquote, button, center, del, details,
1130 // dialog, dir, div, dl, fieldset, figure, footer, form, h1, h2, h3, h4, h5,
1131 // h6, header, hgroup, hr, iframe, ins, main, map, menu, nav, noframes,
1132 // noscript, object, ol, p, pre, table, search, section, summary, ul
1133 #define GROUP_BLOCK (1 << 7)
1135 // frame, frameset
1136 #define GROUP_FRAME (1 << 8)
1138 // col, tbody
1139 #define GROUP_TABLE_CONTENT (1 << 9)
1141 // tr
1142 #define GROUP_TBODY_CONTENT (1 << 10)
1144 // td, th
1145 #define GROUP_TR_CONTENT (1 << 11)
1147 // col
1148 #define GROUP_COLGROUP_CONTENT (1 << 12)
1150 // param
1151 #define GROUP_OBJECT_CONTENT (1 << 13)
1153 // li
1154 #define GROUP_LI (1 << 14)
1156 // area
1157 #define GROUP_MAP_CONTENT (1 << 15)
1159 // optgroup, option
1160 #define GROUP_SELECT_CONTENT (1 << 16)
1162 // option
1163 #define GROUP_OPTIONS (1 << 17)
1165 // dd, dt
1166 #define GROUP_DL_CONTENT (1 << 18)
1168 // p
1169 #define GROUP_P (1 << 19)
1171 // text, white-space, newline, comment
1172 #define GROUP_LEAF (1 << 20)
1174 // XXX This is because the editor does sublists illegally.
1175 // ol, ul
1176 #define GROUP_OL_UL (1 << 21)
1178 // h1, h2, h3, h4, h5, h6
1179 #define GROUP_HEADING (1 << 22)
1181 // figcaption
1182 #define GROUP_FIGCAPTION (1 << 23)
1184 // picture members (img, source)
1185 #define GROUP_PICTURE_CONTENT (1 << 24)
1187 #define GROUP_INLINE_ELEMENT \
1188 (GROUP_FONTSTYLE | GROUP_PHRASE | GROUP_SPECIAL | GROUP_FORMCONTROL | \
1189 GROUP_LEAF)
1191 #define GROUP_FLOW_ELEMENT (GROUP_INLINE_ELEMENT | GROUP_BLOCK)
1193 struct ElementInfo final {
1194 #ifdef DEBUG
1195 nsHTMLTag mTag;
1196 #endif
1197 // See `GROUP_NONE`'s comment.
1198 uint32_t mGroup;
1199 // See `GROUP_NONE`'s comment.
1200 uint32_t mCanContainGroups;
1201 bool mIsContainer;
1202 bool mCanContainSelf;
1205 #ifdef DEBUG
1206 # define ELEM(_tag, _isContainer, _canContainSelf, _group, _canContainGroups) \
1208 eHTMLTag_##_tag, _group, _canContainGroups, _isContainer, \
1209 _canContainSelf \
1211 #else
1212 # define ELEM(_tag, _isContainer, _canContainSelf, _group, _canContainGroups) \
1213 { _group, _canContainGroups, _isContainer, _canContainSelf }
1214 #endif
1216 static const ElementInfo kElements[eHTMLTag_userdefined] = {
1217 ELEM(a, true, false, GROUP_SPECIAL, GROUP_INLINE_ELEMENT),
1218 ELEM(abbr, true, true, GROUP_PHRASE, GROUP_INLINE_ELEMENT),
1219 ELEM(acronym, true, true, GROUP_PHRASE, GROUP_INLINE_ELEMENT),
1220 ELEM(address, true, true, GROUP_BLOCK, GROUP_INLINE_ELEMENT | GROUP_P),
1221 // While applet is no longer a valid tag, removing it here breaks the editor
1222 // (compiles, but causes many tests to fail in odd ways). This list is
1223 // tracked against the main HTML Tag list, so any changes will require more
1224 // than just removing entries.
1225 ELEM(applet, true, true, GROUP_SPECIAL | GROUP_BLOCK,
1226 GROUP_FLOW_ELEMENT | GROUP_OBJECT_CONTENT),
1227 ELEM(area, false, false, GROUP_MAP_CONTENT, GROUP_NONE),
1228 ELEM(article, true, true, GROUP_BLOCK, GROUP_FLOW_ELEMENT),
1229 ELEM(aside, true, true, GROUP_BLOCK, GROUP_FLOW_ELEMENT),
1230 ELEM(audio, false, false, GROUP_NONE, GROUP_NONE),
1231 ELEM(b, true, true, GROUP_FONTSTYLE, GROUP_INLINE_ELEMENT),
1232 ELEM(base, false, false, GROUP_HEAD_CONTENT, GROUP_NONE),
1233 ELEM(basefont, false, false, GROUP_SPECIAL, GROUP_NONE),
1234 ELEM(bdi, true, true, GROUP_SPECIAL, GROUP_INLINE_ELEMENT),
1235 ELEM(bdo, true, true, GROUP_SPECIAL, GROUP_INLINE_ELEMENT),
1236 ELEM(bgsound, false, false, GROUP_NONE, GROUP_NONE),
1237 ELEM(big, true, true, GROUP_FONTSTYLE, GROUP_INLINE_ELEMENT),
1238 ELEM(blockquote, true, true, GROUP_BLOCK, GROUP_FLOW_ELEMENT),
1239 ELEM(body, true, true, GROUP_TOPLEVEL, GROUP_FLOW_ELEMENT),
1240 ELEM(br, false, false, GROUP_SPECIAL, GROUP_NONE),
1241 ELEM(button, true, true, GROUP_FORMCONTROL | GROUP_BLOCK,
1242 GROUP_FLOW_ELEMENT),
1243 ELEM(canvas, false, false, GROUP_NONE, GROUP_NONE),
1244 ELEM(caption, true, true, GROUP_NONE, GROUP_INLINE_ELEMENT),
1245 ELEM(center, true, true, GROUP_BLOCK, GROUP_FLOW_ELEMENT),
1246 ELEM(cite, true, true, GROUP_PHRASE, GROUP_INLINE_ELEMENT),
1247 ELEM(code, true, true, GROUP_PHRASE, GROUP_INLINE_ELEMENT),
1248 ELEM(col, false, false, GROUP_TABLE_CONTENT | GROUP_COLGROUP_CONTENT,
1249 GROUP_NONE),
1250 ELEM(colgroup, true, false, GROUP_NONE, GROUP_COLGROUP_CONTENT),
1251 ELEM(data, true, false, GROUP_PHRASE, GROUP_INLINE_ELEMENT),
1252 ELEM(datalist, true, false, GROUP_PHRASE,
1253 GROUP_OPTIONS | GROUP_INLINE_ELEMENT),
1254 ELEM(dd, true, false, GROUP_DL_CONTENT, GROUP_FLOW_ELEMENT),
1255 ELEM(del, true, true, GROUP_PHRASE | GROUP_BLOCK, GROUP_FLOW_ELEMENT),
1256 ELEM(details, true, true, GROUP_BLOCK, GROUP_FLOW_ELEMENT),
1257 ELEM(dfn, true, true, GROUP_PHRASE, GROUP_INLINE_ELEMENT),
1258 ELEM(dialog, true, true, GROUP_BLOCK, GROUP_FLOW_ELEMENT),
1259 ELEM(dir, true, false, GROUP_BLOCK, GROUP_LI),
1260 ELEM(div, true, true, GROUP_BLOCK, GROUP_FLOW_ELEMENT),
1261 ELEM(dl, true, false, GROUP_BLOCK, GROUP_DL_CONTENT),
1262 ELEM(dt, true, true, GROUP_DL_CONTENT, GROUP_INLINE_ELEMENT),
1263 ELEM(em, true, true, GROUP_PHRASE, GROUP_INLINE_ELEMENT),
1264 ELEM(embed, false, false, GROUP_NONE, GROUP_NONE),
1265 ELEM(fieldset, true, true, GROUP_BLOCK, GROUP_FLOW_ELEMENT),
1266 ELEM(figcaption, true, false, GROUP_FIGCAPTION, GROUP_FLOW_ELEMENT),
1267 ELEM(figure, true, true, GROUP_BLOCK,
1268 GROUP_FLOW_ELEMENT | GROUP_FIGCAPTION),
1269 ELEM(font, true, true, GROUP_SPECIAL, GROUP_INLINE_ELEMENT),
1270 ELEM(footer, true, true, GROUP_BLOCK, GROUP_FLOW_ELEMENT),
1271 ELEM(form, true, true, GROUP_BLOCK, GROUP_FLOW_ELEMENT),
1272 ELEM(frame, false, false, GROUP_FRAME, GROUP_NONE),
1273 ELEM(frameset, true, true, GROUP_FRAME, GROUP_FRAME),
1274 ELEM(h1, true, false, GROUP_BLOCK | GROUP_HEADING, GROUP_INLINE_ELEMENT),
1275 ELEM(h2, true, false, GROUP_BLOCK | GROUP_HEADING, GROUP_INLINE_ELEMENT),
1276 ELEM(h3, true, false, GROUP_BLOCK | GROUP_HEADING, GROUP_INLINE_ELEMENT),
1277 ELEM(h4, true, false, GROUP_BLOCK | GROUP_HEADING, GROUP_INLINE_ELEMENT),
1278 ELEM(h5, true, false, GROUP_BLOCK | GROUP_HEADING, GROUP_INLINE_ELEMENT),
1279 ELEM(h6, true, false, GROUP_BLOCK | GROUP_HEADING, GROUP_INLINE_ELEMENT),
1280 ELEM(head, true, false, GROUP_TOPLEVEL, GROUP_HEAD_CONTENT),
1281 ELEM(header, true, true, GROUP_BLOCK, GROUP_FLOW_ELEMENT),
1282 ELEM(hgroup, true, false, GROUP_BLOCK, GROUP_HEADING),
1283 ELEM(hr, false, false, GROUP_BLOCK, GROUP_NONE),
1284 ELEM(html, true, false, GROUP_TOPLEVEL, GROUP_TOPLEVEL),
1285 ELEM(i, true, true, GROUP_FONTSTYLE, GROUP_INLINE_ELEMENT),
1286 ELEM(iframe, true, true, GROUP_SPECIAL | GROUP_BLOCK, GROUP_FLOW_ELEMENT),
1287 ELEM(image, false, false, GROUP_NONE, GROUP_NONE),
1288 ELEM(img, false, false, GROUP_SPECIAL | GROUP_PICTURE_CONTENT, GROUP_NONE),
1289 ELEM(input, false, false, GROUP_FORMCONTROL, GROUP_NONE),
1290 ELEM(ins, true, true, GROUP_PHRASE | GROUP_BLOCK, GROUP_FLOW_ELEMENT),
1291 ELEM(kbd, true, true, GROUP_PHRASE, GROUP_INLINE_ELEMENT),
1292 ELEM(keygen, false, false, GROUP_NONE, GROUP_NONE),
1293 ELEM(label, true, false, GROUP_FORMCONTROL, GROUP_INLINE_ELEMENT),
1294 ELEM(legend, true, true, GROUP_NONE, GROUP_INLINE_ELEMENT),
1295 ELEM(li, true, false, GROUP_LI, GROUP_FLOW_ELEMENT),
1296 ELEM(link, false, false, GROUP_HEAD_CONTENT, GROUP_NONE),
1297 ELEM(listing, true, true, GROUP_BLOCK, GROUP_INLINE_ELEMENT),
1298 ELEM(main, true, true, GROUP_BLOCK, GROUP_FLOW_ELEMENT),
1299 ELEM(map, true, true, GROUP_SPECIAL, GROUP_BLOCK | GROUP_MAP_CONTENT),
1300 ELEM(mark, true, true, GROUP_PHRASE, GROUP_INLINE_ELEMENT),
1301 ELEM(marquee, true, false, GROUP_NONE, GROUP_NONE),
1302 ELEM(menu, true, true, GROUP_BLOCK, GROUP_LI | GROUP_FLOW_ELEMENT),
1303 ELEM(meta, false, false, GROUP_HEAD_CONTENT, GROUP_NONE),
1304 ELEM(meter, true, false, GROUP_SPECIAL, GROUP_FLOW_ELEMENT),
1305 ELEM(multicol, false, false, GROUP_NONE, GROUP_NONE),
1306 ELEM(nav, true, true, GROUP_BLOCK, GROUP_FLOW_ELEMENT),
1307 ELEM(nobr, true, false, GROUP_NONE, GROUP_NONE),
1308 ELEM(noembed, false, false, GROUP_NONE, GROUP_NONE),
1309 ELEM(noframes, true, true, GROUP_BLOCK, GROUP_FLOW_ELEMENT),
1310 ELEM(noscript, true, true, GROUP_BLOCK, GROUP_FLOW_ELEMENT),
1311 ELEM(object, true, true, GROUP_SPECIAL | GROUP_BLOCK,
1312 GROUP_FLOW_ELEMENT | GROUP_OBJECT_CONTENT),
1313 // XXX Can contain self and ul because editor does sublists illegally.
1314 ELEM(ol, true, true, GROUP_BLOCK | GROUP_OL_UL, GROUP_LI | GROUP_OL_UL),
1315 ELEM(optgroup, true, false, GROUP_SELECT_CONTENT, GROUP_OPTIONS),
1316 ELEM(option, true, false, GROUP_SELECT_CONTENT | GROUP_OPTIONS, GROUP_LEAF),
1317 ELEM(output, true, true, GROUP_SPECIAL, GROUP_INLINE_ELEMENT),
1318 ELEM(p, true, false, GROUP_BLOCK | GROUP_P, GROUP_INLINE_ELEMENT),
1319 ELEM(param, false, false, GROUP_OBJECT_CONTENT, GROUP_NONE),
1320 ELEM(picture, true, false, GROUP_SPECIAL, GROUP_PICTURE_CONTENT),
1321 ELEM(plaintext, false, false, GROUP_NONE, GROUP_NONE),
1322 ELEM(pre, true, true, GROUP_BLOCK, GROUP_INLINE_ELEMENT),
1323 ELEM(progress, true, false, GROUP_SPECIAL, GROUP_FLOW_ELEMENT),
1324 ELEM(q, true, true, GROUP_SPECIAL, GROUP_INLINE_ELEMENT),
1325 ELEM(rb, true, true, GROUP_PHRASE, GROUP_INLINE_ELEMENT),
1326 ELEM(rp, true, true, GROUP_PHRASE, GROUP_INLINE_ELEMENT),
1327 ELEM(rt, true, true, GROUP_PHRASE, GROUP_INLINE_ELEMENT),
1328 ELEM(rtc, true, true, GROUP_PHRASE, GROUP_INLINE_ELEMENT),
1329 ELEM(ruby, true, true, GROUP_PHRASE, GROUP_INLINE_ELEMENT),
1330 ELEM(s, true, true, GROUP_FONTSTYLE, GROUP_INLINE_ELEMENT),
1331 ELEM(samp, true, true, GROUP_PHRASE, GROUP_INLINE_ELEMENT),
1332 ELEM(script, true, false, GROUP_HEAD_CONTENT | GROUP_SPECIAL, GROUP_LEAF),
1333 ELEM(search, true, true, GROUP_BLOCK, GROUP_FLOW_ELEMENT),
1334 ELEM(section, true, true, GROUP_BLOCK, GROUP_FLOW_ELEMENT),
1335 ELEM(select, true, false, GROUP_FORMCONTROL, GROUP_SELECT_CONTENT),
1336 ELEM(small, true, true, GROUP_FONTSTYLE, GROUP_INLINE_ELEMENT),
1337 ELEM(slot, true, false, GROUP_NONE, GROUP_FLOW_ELEMENT),
1338 ELEM(source, false, false, GROUP_PICTURE_CONTENT, GROUP_NONE),
1339 ELEM(span, true, true, GROUP_SPECIAL, GROUP_INLINE_ELEMENT),
1340 ELEM(strike, true, true, GROUP_FONTSTYLE, GROUP_INLINE_ELEMENT),
1341 ELEM(strong, true, true, GROUP_PHRASE, GROUP_INLINE_ELEMENT),
1342 ELEM(style, true, false, GROUP_HEAD_CONTENT, GROUP_LEAF),
1343 ELEM(sub, true, true, GROUP_SPECIAL, GROUP_INLINE_ELEMENT),
1344 ELEM(summary, true, true, GROUP_BLOCK, GROUP_FLOW_ELEMENT),
1345 ELEM(sup, true, true, GROUP_SPECIAL, GROUP_INLINE_ELEMENT),
1346 ELEM(table, true, false, GROUP_BLOCK, GROUP_TABLE_CONTENT),
1347 ELEM(tbody, true, false, GROUP_TABLE_CONTENT, GROUP_TBODY_CONTENT),
1348 ELEM(td, true, false, GROUP_TR_CONTENT, GROUP_FLOW_ELEMENT),
1349 ELEM(textarea, true, false, GROUP_FORMCONTROL, GROUP_LEAF),
1350 ELEM(tfoot, true, false, GROUP_NONE, GROUP_TBODY_CONTENT),
1351 ELEM(th, true, false, GROUP_TR_CONTENT, GROUP_FLOW_ELEMENT),
1352 ELEM(thead, true, false, GROUP_NONE, GROUP_TBODY_CONTENT),
1353 ELEM(template, false, false, GROUP_NONE, GROUP_NONE),
1354 ELEM(time, true, false, GROUP_PHRASE, GROUP_INLINE_ELEMENT),
1355 ELEM(title, true, false, GROUP_HEAD_CONTENT, GROUP_LEAF),
1356 ELEM(tr, true, false, GROUP_TBODY_CONTENT, GROUP_TR_CONTENT),
1357 ELEM(track, false, false, GROUP_NONE, GROUP_NONE),
1358 ELEM(tt, true, true, GROUP_FONTSTYLE, GROUP_INLINE_ELEMENT),
1359 ELEM(u, true, true, GROUP_FONTSTYLE, GROUP_INLINE_ELEMENT),
1360 // XXX Can contain self and ol because editor does sublists illegally.
1361 ELEM(ul, true, true, GROUP_BLOCK | GROUP_OL_UL, GROUP_LI | GROUP_OL_UL),
1362 ELEM(var, true, true, GROUP_PHRASE, GROUP_INLINE_ELEMENT),
1363 ELEM(video, false, false, GROUP_NONE, GROUP_NONE),
1364 ELEM(wbr, false, false, GROUP_NONE, GROUP_NONE),
1365 ELEM(xmp, true, false, GROUP_BLOCK, GROUP_NONE),
1367 // These aren't elements.
1368 ELEM(text, false, false, GROUP_LEAF, GROUP_NONE),
1369 ELEM(whitespace, false, false, GROUP_LEAF, GROUP_NONE),
1370 ELEM(newline, false, false, GROUP_LEAF, GROUP_NONE),
1371 ELEM(comment, false, false, GROUP_LEAF, GROUP_NONE),
1372 ELEM(entity, false, false, GROUP_NONE, GROUP_NONE),
1373 ELEM(doctypeDecl, false, false, GROUP_NONE, GROUP_NONE),
1374 ELEM(markupDecl, false, false, GROUP_NONE, GROUP_NONE),
1375 ELEM(instruction, false, false, GROUP_NONE, GROUP_NONE),
1377 ELEM(userdefined, true, false, GROUP_NONE, GROUP_FLOW_ELEMENT)};
1379 bool HTMLEditUtils::CanNodeContain(nsHTMLTag aParentTagId,
1380 nsHTMLTag aChildTagId) {
1381 NS_ASSERTION(
1382 aParentTagId > eHTMLTag_unknown && aParentTagId <= eHTMLTag_userdefined,
1383 "aParentTagId out of range!");
1384 NS_ASSERTION(
1385 aChildTagId > eHTMLTag_unknown && aChildTagId <= eHTMLTag_userdefined,
1386 "aChildTagId out of range!");
1388 #ifdef DEBUG
1389 static bool checked = false;
1390 if (!checked) {
1391 checked = true;
1392 int32_t i;
1393 for (i = 1; i <= eHTMLTag_userdefined; ++i) {
1394 NS_ASSERTION(kElements[i - 1].mTag == i,
1395 "You need to update kElements (missing tags).");
1398 #endif
1400 // Special-case button.
1401 if (aParentTagId == eHTMLTag_button) {
1402 static const nsHTMLTag kButtonExcludeKids[] = {
1403 eHTMLTag_a, eHTMLTag_fieldset, eHTMLTag_form, eHTMLTag_iframe,
1404 eHTMLTag_input, eHTMLTag_select, eHTMLTag_textarea};
1406 uint32_t j;
1407 for (j = 0; j < ArrayLength(kButtonExcludeKids); ++j) {
1408 if (kButtonExcludeKids[j] == aChildTagId) {
1409 return false;
1414 // Deprecated elements.
1415 if (aChildTagId == eHTMLTag_bgsound) {
1416 return false;
1419 // Bug #67007, dont strip userdefined tags.
1420 if (aChildTagId == eHTMLTag_userdefined) {
1421 return true;
1424 const ElementInfo& parent = kElements[aParentTagId - 1];
1425 if (aParentTagId == aChildTagId) {
1426 return parent.mCanContainSelf;
1429 const ElementInfo& child = kElements[aChildTagId - 1];
1430 return !!(parent.mCanContainGroups & child.mGroup);
1433 bool HTMLEditUtils::ContentIsInert(const nsIContent& aContent) {
1434 for (nsIContent* content :
1435 aContent.InclusiveFlatTreeAncestorsOfType<nsIContent>()) {
1436 if (nsIFrame* frame = content->GetPrimaryFrame()) {
1437 return frame->StyleUI()->IsInert();
1439 // If it doesn't have primary frame, we need to check its ancestors.
1440 // This may occur if it's an invisible text node or element nodes whose
1441 // display is an invisible value.
1442 if (!content->IsElement()) {
1443 continue;
1445 if (content->AsElement()->State().HasState(dom::ElementState::INERT)) {
1446 return true;
1449 return false;
1452 bool HTMLEditUtils::IsContainerNode(nsHTMLTag aTagId) {
1453 NS_ASSERTION(aTagId > eHTMLTag_unknown && aTagId <= eHTMLTag_userdefined,
1454 "aTagId out of range!");
1456 return kElements[aTagId - 1].mIsContainer;
1459 bool HTMLEditUtils::IsNonListSingleLineContainer(const nsINode& aNode) {
1460 return aNode.IsAnyOfHTMLElements(
1461 nsGkAtoms::address, nsGkAtoms::div, nsGkAtoms::h1, nsGkAtoms::h2,
1462 nsGkAtoms::h3, nsGkAtoms::h4, nsGkAtoms::h5, nsGkAtoms::h6,
1463 nsGkAtoms::listing, nsGkAtoms::p, nsGkAtoms::pre, nsGkAtoms::xmp);
1466 bool HTMLEditUtils::IsSingleLineContainer(const nsINode& aNode) {
1467 return IsNonListSingleLineContainer(aNode) ||
1468 aNode.IsAnyOfHTMLElements(nsGkAtoms::li, nsGkAtoms::dt, nsGkAtoms::dd);
1471 // static
1472 template <typename PT, typename CT>
1473 nsIContent* HTMLEditUtils::GetPreviousContent(
1474 const EditorDOMPointBase<PT, CT>& aPoint, const WalkTreeOptions& aOptions,
1475 BlockInlineCheck aBlockInlineCheck,
1476 const Element* aAncestorLimiter /* = nullptr */) {
1477 MOZ_ASSERT(aPoint.IsSetAndValid());
1478 NS_WARNING_ASSERTION(
1479 !aPoint.IsInDataNode() || aPoint.IsInTextNode(),
1480 "GetPreviousContent() doesn't assume that the start point is a "
1481 "data node except text node");
1483 // If we are at the beginning of the node, or it is a text node, then just
1484 // look before it.
1485 if (aPoint.IsStartOfContainer() || aPoint.IsInTextNode()) {
1486 if (aOptions.contains(WalkTreeOption::StopAtBlockBoundary) &&
1487 aPoint.IsInContentNode() &&
1488 HTMLEditUtils::IsBlockElement(
1489 *aPoint.template ContainerAs<nsIContent>(), aBlockInlineCheck)) {
1490 // If we aren't allowed to cross blocks, don't look before this block.
1491 return nullptr;
1493 return HTMLEditUtils::GetPreviousContent(
1494 *aPoint.GetContainer(), aOptions, aBlockInlineCheck, aAncestorLimiter);
1497 // else look before the child at 'aOffset'
1498 if (aPoint.GetChild()) {
1499 return HTMLEditUtils::GetPreviousContent(
1500 *aPoint.GetChild(), aOptions, aBlockInlineCheck, aAncestorLimiter);
1503 // unless there isn't one, in which case we are at the end of the node
1504 // and want the deep-right child.
1505 nsIContent* lastLeafContent = HTMLEditUtils::GetLastLeafContent(
1506 *aPoint.GetContainer(),
1507 {aOptions.contains(WalkTreeOption::StopAtBlockBoundary)
1508 ? LeafNodeType::LeafNodeOrChildBlock
1509 : LeafNodeType::OnlyLeafNode},
1510 aBlockInlineCheck);
1511 if (!lastLeafContent) {
1512 return nullptr;
1515 if (!HTMLEditUtils::IsContentIgnored(*lastLeafContent, aOptions)) {
1516 return lastLeafContent;
1519 // restart the search from the non-editable node we just found
1520 return HTMLEditUtils::GetPreviousContent(*lastLeafContent, aOptions,
1521 aBlockInlineCheck, aAncestorLimiter);
1524 // static
1525 template <typename PT, typename CT>
1526 nsIContent* HTMLEditUtils::GetNextContent(
1527 const EditorDOMPointBase<PT, CT>& aPoint, const WalkTreeOptions& aOptions,
1528 BlockInlineCheck aBlockInlineCheck,
1529 const Element* aAncestorLimiter /* = nullptr */) {
1530 MOZ_ASSERT(aPoint.IsSetAndValid());
1531 NS_WARNING_ASSERTION(
1532 !aPoint.IsInDataNode() || aPoint.IsInTextNode(),
1533 "GetNextContent() doesn't assume that the start point is a "
1534 "data node except text node");
1536 auto point = aPoint.template To<EditorRawDOMPoint>();
1538 // if the container is a text node, use its location instead
1539 if (point.IsInTextNode()) {
1540 point.SetAfter(point.GetContainer());
1541 if (NS_WARN_IF(!point.IsSet())) {
1542 return nullptr;
1546 if (point.GetChild()) {
1547 if (aOptions.contains(WalkTreeOption::StopAtBlockBoundary) &&
1548 HTMLEditUtils::IsBlockElement(*point.GetChild(), aBlockInlineCheck)) {
1549 return point.GetChild();
1552 nsIContent* firstLeafContent = HTMLEditUtils::GetFirstLeafContent(
1553 *point.GetChild(),
1554 {aOptions.contains(WalkTreeOption::StopAtBlockBoundary)
1555 ? LeafNodeType::LeafNodeOrChildBlock
1556 : LeafNodeType::OnlyLeafNode},
1557 aBlockInlineCheck);
1558 if (!firstLeafContent) {
1559 return point.GetChild();
1562 // XXX Why do we need to do this check? The leaf node must be a descendant
1563 // of `point.GetChild()`.
1564 if (aAncestorLimiter &&
1565 (firstLeafContent == aAncestorLimiter ||
1566 !firstLeafContent->IsInclusiveDescendantOf(aAncestorLimiter))) {
1567 return nullptr;
1570 if (!HTMLEditUtils::IsContentIgnored(*firstLeafContent, aOptions)) {
1571 return firstLeafContent;
1574 // restart the search from the non-editable node we just found
1575 return HTMLEditUtils::GetNextContent(*firstLeafContent, aOptions,
1576 aBlockInlineCheck, aAncestorLimiter);
1579 // unless there isn't one, in which case we are at the end of the node
1580 // and want the next one.
1581 if (aOptions.contains(WalkTreeOption::StopAtBlockBoundary) &&
1582 point.IsInContentNode() &&
1583 HTMLEditUtils::IsBlockElement(*point.template ContainerAs<nsIContent>(),
1584 aBlockInlineCheck)) {
1585 // don't cross out of parent block
1586 return nullptr;
1589 return HTMLEditUtils::GetNextContent(*point.GetContainer(), aOptions,
1590 aBlockInlineCheck, aAncestorLimiter);
1593 // static
1594 nsIContent* HTMLEditUtils::GetAdjacentLeafContent(
1595 const nsINode& aNode, WalkTreeDirection aWalkTreeDirection,
1596 const WalkTreeOptions& aOptions, BlockInlineCheck aBlockInlineCheck,
1597 const Element* aAncestorLimiter /* = nullptr */) {
1598 // called only by GetPriorNode so we don't need to check params.
1599 MOZ_ASSERT(&aNode != aAncestorLimiter);
1600 MOZ_ASSERT_IF(aAncestorLimiter,
1601 aAncestorLimiter->IsInclusiveDescendantOf(aAncestorLimiter));
1603 const nsINode* node = &aNode;
1604 for (;;) {
1605 // if aNode has a sibling in the right direction, return
1606 // that sibling's closest child (or itself if it has no children)
1607 nsIContent* sibling = aWalkTreeDirection == WalkTreeDirection::Forward
1608 ? node->GetNextSibling()
1609 : node->GetPreviousSibling();
1610 if (sibling) {
1611 // XXX If `sibling` belongs to siblings of inclusive ancestors of aNode,
1612 // perhaps, we need to use
1613 // IgnoreInsideBlockBoundary(aBlockInlineCheck) here.
1614 if (aOptions.contains(WalkTreeOption::StopAtBlockBoundary) &&
1615 HTMLEditUtils::IsBlockElement(*sibling, aBlockInlineCheck)) {
1616 // don't look inside previous sibling, since it is a block
1617 return sibling;
1619 const LeafNodeTypes leafNodeTypes = {
1620 aOptions.contains(WalkTreeOption::StopAtBlockBoundary)
1621 ? LeafNodeType::LeafNodeOrChildBlock
1622 : LeafNodeType::OnlyLeafNode};
1623 nsIContent* leafContent =
1624 aWalkTreeDirection == WalkTreeDirection::Forward
1625 ? HTMLEditUtils::GetFirstLeafContent(*sibling, leafNodeTypes,
1626 aBlockInlineCheck)
1627 : HTMLEditUtils::GetLastLeafContent(*sibling, leafNodeTypes,
1628 aBlockInlineCheck);
1629 return leafContent ? leafContent : sibling;
1632 nsIContent* parent = node->GetParent();
1633 if (!parent) {
1634 return nullptr;
1637 if (parent == aAncestorLimiter ||
1638 (aOptions.contains(WalkTreeOption::StopAtBlockBoundary) &&
1639 HTMLEditUtils::IsBlockElement(*parent, aBlockInlineCheck))) {
1640 return nullptr;
1643 node = parent;
1646 MOZ_ASSERT_UNREACHABLE("What part of for(;;) do you not understand?");
1647 return nullptr;
1650 // static
1651 nsIContent* HTMLEditUtils::GetAdjacentContent(
1652 const nsINode& aNode, WalkTreeDirection aWalkTreeDirection,
1653 const WalkTreeOptions& aOptions, BlockInlineCheck aBlockInlineCheck,
1654 const Element* aAncestorLimiter /* = nullptr */) {
1655 if (&aNode == aAncestorLimiter) {
1656 // Don't allow traversal above the root node! This helps
1657 // prevent us from accidentally editing browser content
1658 // when the editor is in a text widget.
1659 return nullptr;
1662 nsIContent* leafContent = HTMLEditUtils::GetAdjacentLeafContent(
1663 aNode, aWalkTreeDirection, aOptions, aBlockInlineCheck, aAncestorLimiter);
1664 if (!leafContent) {
1665 return nullptr;
1668 if (!HTMLEditUtils::IsContentIgnored(*leafContent, aOptions)) {
1669 return leafContent;
1672 return HTMLEditUtils::GetAdjacentContent(*leafContent, aWalkTreeDirection,
1673 aOptions, aBlockInlineCheck,
1674 aAncestorLimiter);
1677 // static
1678 template <typename EditorDOMPointType>
1679 EditorDOMPointType HTMLEditUtils::GetPreviousEditablePoint(
1680 nsIContent& aContent, const Element* aAncestorLimiter,
1681 InvisibleWhiteSpaces aInvisibleWhiteSpaces,
1682 TableBoundary aHowToTreatTableBoundary) {
1683 MOZ_ASSERT(HTMLEditUtils::IsSimplyEditableNode(aContent));
1684 NS_ASSERTION(!HTMLEditUtils::IsAnyTableElement(&aContent) ||
1685 HTMLEditUtils::IsTableCellOrCaption(aContent),
1686 "HTMLEditUtils::GetPreviousEditablePoint() may return a point "
1687 "between table structure elements");
1689 if (&aContent == aAncestorLimiter) {
1690 return EditorDOMPointType();
1693 // First, look for previous content.
1694 nsIContent* previousContent = aContent.GetPreviousSibling();
1695 if (!previousContent) {
1696 if (!aContent.GetParentElement()) {
1697 return EditorDOMPointType();
1699 nsIContent* inclusiveAncestor = &aContent;
1700 for (Element* parentElement : aContent.AncestorsOfType<Element>()) {
1701 if (parentElement == aAncestorLimiter ||
1702 !HTMLEditUtils::IsSimplyEditableNode(*parentElement) ||
1703 !HTMLEditUtils::CanCrossContentBoundary(*parentElement,
1704 aHowToTreatTableBoundary)) {
1705 // If cannot cross the parent element boundary, return the point of
1706 // last inclusive ancestor point.
1707 return EditorDOMPointType(inclusiveAncestor);
1710 // Start of the parent element is a next editable point if it's an
1711 // element which is not a table structure element.
1712 if (!HTMLEditUtils::IsAnyTableElement(parentElement) ||
1713 HTMLEditUtils::IsTableCellOrCaption(*parentElement)) {
1714 inclusiveAncestor = parentElement;
1717 previousContent = parentElement->GetPreviousSibling();
1718 if (!previousContent) {
1719 continue; // Keep looking for previous sibling of an ancestor.
1722 // XXX Should we ignore data node like CDATA, Comment, etc?
1724 // If previous content is not editable, let's return the point after it.
1725 if (!HTMLEditUtils::IsSimplyEditableNode(*previousContent)) {
1726 return EditorDOMPointType::After(*previousContent);
1729 // If cannot cross previous content boundary, return start of last
1730 // inclusive ancestor.
1731 if (!HTMLEditUtils::CanCrossContentBoundary(*previousContent,
1732 aHowToTreatTableBoundary)) {
1733 return inclusiveAncestor == &aContent
1734 ? EditorDOMPointType(inclusiveAncestor)
1735 : EditorDOMPointType(inclusiveAncestor, 0);
1737 break;
1739 if (!previousContent) {
1740 return EditorDOMPointType(inclusiveAncestor);
1742 } else if (!HTMLEditUtils::IsSimplyEditableNode(*previousContent)) {
1743 return EditorDOMPointType::After(*previousContent);
1744 } else if (!HTMLEditUtils::CanCrossContentBoundary(
1745 *previousContent, aHowToTreatTableBoundary)) {
1746 return EditorDOMPointType(&aContent);
1749 // Next, look for end of the previous content.
1750 nsIContent* leafContent = previousContent;
1751 if (previousContent->GetChildCount() &&
1752 HTMLEditUtils::IsContainerNode(*previousContent)) {
1753 for (nsIContent* maybeLeafContent = previousContent->GetLastChild();
1754 maybeLeafContent;
1755 maybeLeafContent = maybeLeafContent->GetLastChild()) {
1756 // If it's not an editable content or cannot cross the boundary,
1757 // return the point after the content. Note that in this case,
1758 // the content must not be any table elements except `<table>`
1759 // because we've climbed down the tree.
1760 if (!HTMLEditUtils::IsSimplyEditableNode(*maybeLeafContent) ||
1761 !HTMLEditUtils::CanCrossContentBoundary(*maybeLeafContent,
1762 aHowToTreatTableBoundary)) {
1763 return EditorDOMPointType::After(*maybeLeafContent);
1765 leafContent = maybeLeafContent;
1766 if (!HTMLEditUtils::IsContainerNode(*leafContent)) {
1767 break;
1772 if (leafContent->IsText()) {
1773 Text* textNode = leafContent->AsText();
1774 if (aInvisibleWhiteSpaces == InvisibleWhiteSpaces::Preserve) {
1775 return EditorDOMPointType::AtEndOf(*textNode);
1777 // There may be invisible trailing white-spaces which should be
1778 // ignored. Let's scan its start.
1779 return WSRunScanner::GetAfterLastVisiblePoint<EditorDOMPointType>(
1780 *textNode, aAncestorLimiter);
1783 // If it's a container element, return end of it. Otherwise, return
1784 // the point after the non-container element.
1785 return HTMLEditUtils::IsContainerNode(*leafContent)
1786 ? EditorDOMPointType::AtEndOf(*leafContent)
1787 : EditorDOMPointType::After(*leafContent);
1790 // static
1791 template <typename EditorDOMPointType>
1792 EditorDOMPointType HTMLEditUtils::GetNextEditablePoint(
1793 nsIContent& aContent, const Element* aAncestorLimiter,
1794 InvisibleWhiteSpaces aInvisibleWhiteSpaces,
1795 TableBoundary aHowToTreatTableBoundary) {
1796 MOZ_ASSERT(HTMLEditUtils::IsSimplyEditableNode(aContent));
1797 NS_ASSERTION(!HTMLEditUtils::IsAnyTableElement(&aContent) ||
1798 HTMLEditUtils::IsTableCellOrCaption(aContent),
1799 "HTMLEditUtils::GetPreviousEditablePoint() may return a point "
1800 "between table structure elements");
1802 if (&aContent == aAncestorLimiter) {
1803 return EditorDOMPointType();
1806 // First, look for next content.
1807 nsIContent* nextContent = aContent.GetNextSibling();
1808 if (!nextContent) {
1809 if (!aContent.GetParentElement()) {
1810 return EditorDOMPointType();
1812 nsIContent* inclusiveAncestor = &aContent;
1813 for (Element* parentElement : aContent.AncestorsOfType<Element>()) {
1814 if (parentElement == aAncestorLimiter ||
1815 !HTMLEditUtils::IsSimplyEditableNode(*parentElement) ||
1816 !HTMLEditUtils::CanCrossContentBoundary(*parentElement,
1817 aHowToTreatTableBoundary)) {
1818 // If cannot cross the parent element boundary, return the point of
1819 // last inclusive ancestor point.
1820 return EditorDOMPointType(inclusiveAncestor);
1823 // End of the parent element is a next editable point if it's an
1824 // element which is not a table structure element.
1825 if (!HTMLEditUtils::IsAnyTableElement(parentElement) ||
1826 HTMLEditUtils::IsTableCellOrCaption(*parentElement)) {
1827 inclusiveAncestor = parentElement;
1830 nextContent = parentElement->GetNextSibling();
1831 if (!nextContent) {
1832 continue; // Keep looking for next sibling of an ancestor.
1835 // XXX Should we ignore data node like CDATA, Comment, etc?
1837 // If next content is not editable, let's return the point after
1838 // the last inclusive ancestor.
1839 if (!HTMLEditUtils::IsSimplyEditableNode(*nextContent)) {
1840 return EditorDOMPointType::After(*parentElement);
1843 // If cannot cross next content boundary, return after the last
1844 // inclusive ancestor.
1845 if (!HTMLEditUtils::CanCrossContentBoundary(*nextContent,
1846 aHowToTreatTableBoundary)) {
1847 return EditorDOMPointType::After(*inclusiveAncestor);
1849 break;
1851 if (!nextContent) {
1852 return EditorDOMPointType::After(*inclusiveAncestor);
1854 } else if (!HTMLEditUtils::IsSimplyEditableNode(*nextContent)) {
1855 return EditorDOMPointType::After(aContent);
1856 } else if (!HTMLEditUtils::CanCrossContentBoundary(
1857 *nextContent, aHowToTreatTableBoundary)) {
1858 return EditorDOMPointType::After(aContent);
1861 // Next, look for start of the next content.
1862 nsIContent* leafContent = nextContent;
1863 if (nextContent->GetChildCount() &&
1864 HTMLEditUtils::IsContainerNode(*nextContent)) {
1865 for (nsIContent* maybeLeafContent = nextContent->GetFirstChild();
1866 maybeLeafContent;
1867 maybeLeafContent = maybeLeafContent->GetFirstChild()) {
1868 // If it's not an editable content or cannot cross the boundary,
1869 // return the point at the content (i.e., start of its parent). Note
1870 // that in this case, the content must not be any table elements except
1871 // `<table>` because we've climbed down the tree.
1872 if (!HTMLEditUtils::IsSimplyEditableNode(*maybeLeafContent) ||
1873 !HTMLEditUtils::CanCrossContentBoundary(*maybeLeafContent,
1874 aHowToTreatTableBoundary)) {
1875 return EditorDOMPointType(maybeLeafContent);
1877 leafContent = maybeLeafContent;
1878 if (!HTMLEditUtils::IsContainerNode(*leafContent)) {
1879 break;
1884 if (leafContent->IsText()) {
1885 Text* textNode = leafContent->AsText();
1886 if (aInvisibleWhiteSpaces == InvisibleWhiteSpaces::Preserve) {
1887 return EditorDOMPointType(textNode, 0);
1889 // There may be invisible leading white-spaces which should be
1890 // ignored. Let's scan its start.
1891 return WSRunScanner::GetFirstVisiblePoint<EditorDOMPointType>(
1892 *textNode, aAncestorLimiter);
1895 // If it's a container element, return start of it. Otherwise, return
1896 // the point at the non-container element (i.e., start of its parent).
1897 return HTMLEditUtils::IsContainerNode(*leafContent)
1898 ? EditorDOMPointType(leafContent, 0)
1899 : EditorDOMPointType(leafContent);
1902 // static
1903 Element* HTMLEditUtils::GetAncestorElement(
1904 const nsIContent& aContent, const AncestorTypes& aAncestorTypes,
1905 BlockInlineCheck aBlockInlineCheck,
1906 const Element* aAncestorLimiter /* = nullptr */) {
1907 MOZ_ASSERT(
1908 aAncestorTypes.contains(AncestorType::ClosestBlockElement) ||
1909 aAncestorTypes.contains(AncestorType::MostDistantInlineElementInBlock) ||
1910 aAncestorTypes.contains(AncestorType::ButtonElement));
1912 if (&aContent == aAncestorLimiter) {
1913 return nullptr;
1916 const Element* theBodyElement = aContent.OwnerDoc()->GetBody();
1917 const Element* theDocumentElement = aContent.OwnerDoc()->GetDocumentElement();
1918 Element* lastAncestorElement = nullptr;
1919 const bool editableElementOnly =
1920 aAncestorTypes.contains(AncestorType::EditableElement);
1921 const bool lookingForClosestBlockElement =
1922 aAncestorTypes.contains(AncestorType::ClosestBlockElement);
1923 const bool lookingForMostDistantInlineElementInBlock =
1924 aAncestorTypes.contains(AncestorType::MostDistantInlineElementInBlock);
1925 const bool ignoreHRElement =
1926 aAncestorTypes.contains(AncestorType::IgnoreHRElement);
1927 const bool lookingForButtonElement =
1928 aAncestorTypes.contains(AncestorType::ButtonElement);
1929 auto IsSearchingElementType = [&](const nsIContent& aContent) -> bool {
1930 if (!aContent.IsElement() ||
1931 (ignoreHRElement && aContent.IsHTMLElement(nsGkAtoms::hr))) {
1932 return false;
1934 if (editableElementOnly &&
1935 !EditorUtils::IsEditableContent(aContent, EditorType::HTML)) {
1936 return false;
1938 return (lookingForClosestBlockElement &&
1939 HTMLEditUtils::IsBlockElement(aContent, aBlockInlineCheck)) ||
1940 (lookingForMostDistantInlineElementInBlock &&
1941 HTMLEditUtils::IsInlineContent(aContent, aBlockInlineCheck)) ||
1942 (lookingForButtonElement &&
1943 aContent.IsHTMLElement(nsGkAtoms::button));
1945 for (Element* element : aContent.AncestorsOfType<Element>()) {
1946 if (editableElementOnly &&
1947 !EditorUtils::IsEditableContent(*element, EditorType::HTML)) {
1948 return lastAncestorElement && IsSearchingElementType(*lastAncestorElement)
1949 ? lastAncestorElement // editing host (can be inline element)
1950 : nullptr;
1952 if (ignoreHRElement && element->IsHTMLElement(nsGkAtoms::hr)) {
1953 if (element == aAncestorLimiter) {
1954 break;
1956 continue;
1958 if (lookingForButtonElement && element->IsHTMLElement(nsGkAtoms::button)) {
1959 return element; // closest button element
1961 if (HTMLEditUtils::IsBlockElement(*element, aBlockInlineCheck)) {
1962 if (lookingForClosestBlockElement) {
1963 return element; // closest block element
1965 MOZ_ASSERT_IF(lastAncestorElement,
1966 HTMLEditUtils::IsInlineContent(*lastAncestorElement,
1967 aBlockInlineCheck));
1968 return lastAncestorElement; // the last inline element which we found
1970 if (element == aAncestorLimiter || element == theBodyElement ||
1971 element == theDocumentElement) {
1972 break;
1974 lastAncestorElement = element;
1976 return lastAncestorElement && IsSearchingElementType(*lastAncestorElement)
1977 ? lastAncestorElement
1978 : nullptr;
1981 // static
1982 Element* HTMLEditUtils::GetInclusiveAncestorElement(
1983 const nsIContent& aContent, const AncestorTypes& aAncestorTypes,
1984 BlockInlineCheck aBlockInlineCheck,
1985 const Element* aAncestorLimiter /* = nullptr */) {
1986 MOZ_ASSERT(
1987 aAncestorTypes.contains(AncestorType::ClosestBlockElement) ||
1988 aAncestorTypes.contains(AncestorType::MostDistantInlineElementInBlock) ||
1989 aAncestorTypes.contains(AncestorType::ButtonElement));
1991 const Element* theBodyElement = aContent.OwnerDoc()->GetBody();
1992 const Element* theDocumentElement = aContent.OwnerDoc()->GetDocumentElement();
1993 const bool editableElementOnly =
1994 aAncestorTypes.contains(AncestorType::EditableElement);
1995 const bool lookingForClosestBlockElement =
1996 aAncestorTypes.contains(AncestorType::ClosestBlockElement);
1997 const bool lookingForMostDistantInlineElementInBlock =
1998 aAncestorTypes.contains(AncestorType::MostDistantInlineElementInBlock);
1999 const bool lookingForButtonElement =
2000 aAncestorTypes.contains(AncestorType::ButtonElement);
2001 const bool ignoreHRElement =
2002 aAncestorTypes.contains(AncestorType::IgnoreHRElement);
2003 auto IsSearchingElementType = [&](const nsIContent& aContent) -> bool {
2004 if (!aContent.IsElement() ||
2005 (ignoreHRElement && aContent.IsHTMLElement(nsGkAtoms::hr))) {
2006 return false;
2008 if (editableElementOnly &&
2009 !EditorUtils::IsEditableContent(aContent, EditorType::HTML)) {
2010 return false;
2012 return (lookingForClosestBlockElement &&
2013 HTMLEditUtils::IsBlockElement(aContent, aBlockInlineCheck)) ||
2014 (lookingForMostDistantInlineElementInBlock &&
2015 HTMLEditUtils::IsInlineContent(aContent, aBlockInlineCheck)) ||
2016 (lookingForButtonElement &&
2017 aContent.IsHTMLElement(nsGkAtoms::button));
2020 // If aContent is the body element or the document element, we shouldn't climb
2021 // up to its parent.
2022 if (editableElementOnly &&
2023 (&aContent == theBodyElement || &aContent == theDocumentElement)) {
2024 return IsSearchingElementType(aContent)
2025 ? const_cast<Element*>(aContent.AsElement())
2026 : nullptr;
2029 if (lookingForButtonElement && aContent.IsHTMLElement(nsGkAtoms::button)) {
2030 return const_cast<Element*>(aContent.AsElement());
2033 // If aContent is a block element, we don't need to climb up the tree.
2034 // Consider the result right now.
2035 if ((lookingForClosestBlockElement ||
2036 lookingForMostDistantInlineElementInBlock) &&
2037 HTMLEditUtils::IsBlockElement(aContent, aBlockInlineCheck) &&
2038 !(ignoreHRElement && aContent.IsHTMLElement(nsGkAtoms::hr))) {
2039 return IsSearchingElementType(aContent)
2040 ? const_cast<Element*>(aContent.AsElement())
2041 : nullptr;
2044 // If aContent is the last element to search range because of the parent
2045 // element type, consider the result before calling GetAncestorElement()
2046 // because it won't return aContent.
2047 if (!aContent.GetParent() ||
2048 (editableElementOnly && !EditorUtils::IsEditableContent(
2049 *aContent.GetParent(), EditorType::HTML)) ||
2050 (!lookingForClosestBlockElement &&
2051 HTMLEditUtils::IsBlockElement(*aContent.GetParent(),
2052 aBlockInlineCheck) &&
2053 !(ignoreHRElement &&
2054 aContent.GetParent()->IsHTMLElement(nsGkAtoms::hr)))) {
2055 return IsSearchingElementType(aContent)
2056 ? const_cast<Element*>(aContent.AsElement())
2057 : nullptr;
2060 if (&aContent == aAncestorLimiter) {
2061 return nullptr;
2064 return HTMLEditUtils::GetAncestorElement(aContent, aAncestorTypes,
2065 aBlockInlineCheck, aAncestorLimiter);
2068 // static
2069 Element* HTMLEditUtils::GetClosestAncestorAnyListElement(
2070 const nsIContent& aContent) {
2071 for (Element* element : aContent.AncestorsOfType<Element>()) {
2072 if (HTMLEditUtils::IsAnyListElement(element)) {
2073 return element;
2076 return nullptr;
2079 // static
2080 Element* HTMLEditUtils::GetClosestInclusiveAncestorAnyListElement(
2081 const nsIContent& aContent) {
2082 for (Element* element : aContent.InclusiveAncestorsOfType<Element>()) {
2083 if (HTMLEditUtils::IsAnyListElement(element)) {
2084 return element;
2087 return nullptr;
2090 EditAction HTMLEditUtils::GetEditActionForInsert(const nsAtom& aTagName) {
2091 // This method may be in a hot path. So, return only necessary
2092 // EditAction::eInsert*Element.
2093 if (&aTagName == nsGkAtoms::ul) {
2094 // For InputEvent.inputType, "insertUnorderedList".
2095 return EditAction::eInsertUnorderedListElement;
2097 if (&aTagName == nsGkAtoms::ol) {
2098 // For InputEvent.inputType, "insertOrderedList".
2099 return EditAction::eInsertOrderedListElement;
2101 if (&aTagName == nsGkAtoms::hr) {
2102 // For InputEvent.inputType, "insertHorizontalRule".
2103 return EditAction::eInsertHorizontalRuleElement;
2105 return EditAction::eInsertNode;
2108 EditAction HTMLEditUtils::GetEditActionForRemoveList(const nsAtom& aTagName) {
2109 // This method may be in a hot path. So, return only necessary
2110 // EditAction::eRemove*Element.
2111 if (&aTagName == nsGkAtoms::ul) {
2112 // For InputEvent.inputType, "insertUnorderedList".
2113 return EditAction::eRemoveUnorderedListElement;
2115 if (&aTagName == nsGkAtoms::ol) {
2116 // For InputEvent.inputType, "insertOrderedList".
2117 return EditAction::eRemoveOrderedListElement;
2119 return EditAction::eRemoveListElement;
2122 EditAction HTMLEditUtils::GetEditActionForInsert(const Element& aElement) {
2123 return GetEditActionForInsert(*aElement.NodeInfo()->NameAtom());
2126 EditAction HTMLEditUtils::GetEditActionForFormatText(const nsAtom& aProperty,
2127 const nsAtom* aAttribute,
2128 bool aToSetStyle) {
2129 // This method may be in a hot path. So, return only necessary
2130 // EditAction::eSet*Property or EditAction::eRemove*Property.
2131 if (&aProperty == nsGkAtoms::b) {
2132 return aToSetStyle ? EditAction::eSetFontWeightProperty
2133 : EditAction::eRemoveFontWeightProperty;
2135 if (&aProperty == nsGkAtoms::i) {
2136 return aToSetStyle ? EditAction::eSetTextStyleProperty
2137 : EditAction::eRemoveTextStyleProperty;
2139 if (&aProperty == nsGkAtoms::u) {
2140 return aToSetStyle ? EditAction::eSetTextDecorationPropertyUnderline
2141 : EditAction::eRemoveTextDecorationPropertyUnderline;
2143 if (&aProperty == nsGkAtoms::strike) {
2144 return aToSetStyle ? EditAction::eSetTextDecorationPropertyLineThrough
2145 : EditAction::eRemoveTextDecorationPropertyLineThrough;
2147 if (&aProperty == nsGkAtoms::sup) {
2148 return aToSetStyle ? EditAction::eSetVerticalAlignPropertySuper
2149 : EditAction::eRemoveVerticalAlignPropertySuper;
2151 if (&aProperty == nsGkAtoms::sub) {
2152 return aToSetStyle ? EditAction::eSetVerticalAlignPropertySub
2153 : EditAction::eRemoveVerticalAlignPropertySub;
2155 if (&aProperty == nsGkAtoms::font) {
2156 if (aAttribute == nsGkAtoms::face) {
2157 return aToSetStyle ? EditAction::eSetFontFamilyProperty
2158 : EditAction::eRemoveFontFamilyProperty;
2160 if (aAttribute == nsGkAtoms::color) {
2161 return aToSetStyle ? EditAction::eSetColorProperty
2162 : EditAction::eRemoveColorProperty;
2164 if (aAttribute == nsGkAtoms::bgcolor) {
2165 return aToSetStyle ? EditAction::eSetBackgroundColorPropertyInline
2166 : EditAction::eRemoveBackgroundColorPropertyInline;
2169 return aToSetStyle ? EditAction::eSetInlineStyleProperty
2170 : EditAction::eRemoveInlineStyleProperty;
2173 EditAction HTMLEditUtils::GetEditActionForAlignment(
2174 const nsAString& aAlignType) {
2175 // This method may be in a hot path. So, return only necessary
2176 // EditAction::eAlign*.
2177 if (aAlignType.EqualsLiteral("left")) {
2178 return EditAction::eAlignLeft;
2180 if (aAlignType.EqualsLiteral("right")) {
2181 return EditAction::eAlignRight;
2183 if (aAlignType.EqualsLiteral("center")) {
2184 return EditAction::eAlignCenter;
2186 if (aAlignType.EqualsLiteral("justify")) {
2187 return EditAction::eJustify;
2189 return EditAction::eSetAlignment;
2192 // static
2193 template <typename EditorDOMPointType>
2194 nsIContent* HTMLEditUtils::GetContentToPreserveInlineStyles(
2195 const EditorDOMPointType& aPoint, const Element& aEditingHost) {
2196 MOZ_ASSERT(aPoint.IsSetAndValid());
2197 if (MOZ_UNLIKELY(!aPoint.IsInContentNode())) {
2198 return nullptr;
2200 // If it points middle of a text node, use it. Otherwise, scan next visible
2201 // thing and use the style of following text node if there is.
2202 if (aPoint.IsInTextNode() && !aPoint.IsEndOfContainer()) {
2203 return aPoint.template ContainerAs<nsIContent>();
2205 for (auto point = aPoint.template To<EditorRawDOMPoint>(); point.IsSet();) {
2206 WSScanResult nextVisibleThing =
2207 WSRunScanner::ScanNextVisibleNodeOrBlockBoundary(
2208 &aEditingHost, point,
2209 BlockInlineCheck::UseComputedDisplayOutsideStyle);
2210 if (nextVisibleThing.InVisibleOrCollapsibleCharacters()) {
2211 return nextVisibleThing.TextPtr();
2213 // Ignore empty inline container elements because it's not visible for
2214 // users so that using the style will appear suddenly from point of
2215 // view of users.
2216 if (nextVisibleThing.ReachedSpecialContent() &&
2217 nextVisibleThing.IsContentEditable() &&
2218 nextVisibleThing.GetContent()->IsElement() &&
2219 !nextVisibleThing.GetContent()->HasChildNodes() &&
2220 HTMLEditUtils::IsContainerNode(*nextVisibleThing.ElementPtr())) {
2221 point.SetAfter(nextVisibleThing.ElementPtr());
2222 continue;
2224 // Otherwise, we should use style of the container of the start point.
2225 break;
2227 return aPoint.template ContainerAs<nsIContent>();
2230 template <typename EditorDOMPointType, typename EditorDOMPointTypeInput>
2231 EditorDOMPointType HTMLEditUtils::GetBetterInsertionPointFor(
2232 const nsIContent& aContentToInsert,
2233 const EditorDOMPointTypeInput& aPointToInsert,
2234 const Element& aEditingHost) {
2235 if (NS_WARN_IF(!aPointToInsert.IsSet())) {
2236 return EditorDOMPointType();
2239 auto pointToInsert =
2240 aPointToInsert.template GetNonAnonymousSubtreePoint<EditorDOMPointType>();
2241 if (MOZ_UNLIKELY(
2242 NS_WARN_IF(!pointToInsert.IsSet()) ||
2243 NS_WARN_IF(!pointToInsert.GetContainer()->IsInclusiveDescendantOf(
2244 &aEditingHost)))) {
2245 // Cannot insert aContentToInsert into this DOM tree.
2246 return EditorDOMPointType();
2249 // If the node to insert is not a block level element, we can insert it
2250 // at any point.
2251 if (!HTMLEditUtils::IsBlockElement(
2252 aContentToInsert, BlockInlineCheck::UseComputedDisplayStyle)) {
2253 return pointToInsert;
2256 WSRunScanner wsScannerForPointToInsert(
2257 const_cast<Element*>(&aEditingHost), pointToInsert,
2258 BlockInlineCheck::UseComputedDisplayStyle);
2260 // If the insertion position is after the last visible item in a line,
2261 // i.e., the insertion position is just before a visible line break <br>,
2262 // we want to skip to the position just after the line break (see bug 68767).
2263 WSScanResult forwardScanFromPointToInsertResult =
2264 wsScannerForPointToInsert.ScanNextVisibleNodeOrBlockBoundaryFrom(
2265 pointToInsert);
2266 // So, if the next visible node isn't a <br> element, we can insert the block
2267 // level element to the point.
2268 if (!forwardScanFromPointToInsertResult.GetContent() ||
2269 !forwardScanFromPointToInsertResult.ReachedBRElement()) {
2270 return pointToInsert;
2273 // However, we must not skip next <br> element when the caret appears to be
2274 // positioned at the beginning of a block, in that case skipping the <br>
2275 // would not insert the <br> at the caret position, but after the current
2276 // empty line.
2277 WSScanResult backwardScanFromPointToInsertResult =
2278 wsScannerForPointToInsert.ScanPreviousVisibleNodeOrBlockBoundaryFrom(
2279 pointToInsert);
2280 // So, if there is no previous visible node,
2281 // or, if both nodes of the insertion point is <br> elements,
2282 // or, if the previous visible node is different block,
2283 // we need to skip the following <br>. So, otherwise, we can insert the
2284 // block at the insertion point.
2285 if (!backwardScanFromPointToInsertResult.GetContent() ||
2286 backwardScanFromPointToInsertResult.ReachedBRElement() ||
2287 backwardScanFromPointToInsertResult.ReachedCurrentBlockBoundary()) {
2288 return pointToInsert;
2291 return forwardScanFromPointToInsertResult
2292 .template PointAfterContent<EditorDOMPointType>();
2295 // static
2296 template <typename EditorDOMPointType, typename EditorDOMPointTypeInput>
2297 EditorDOMPointType HTMLEditUtils::GetBetterCaretPositionToInsertText(
2298 const EditorDOMPointTypeInput& aPoint, const Element& aEditingHost) {
2299 MOZ_ASSERT(aPoint.IsSetAndValid());
2300 MOZ_ASSERT(
2301 aPoint.GetContainer()->IsInclusiveFlatTreeDescendantOf(&aEditingHost));
2303 if (aPoint.IsInTextNode()) {
2304 return aPoint.template To<EditorDOMPointType>();
2306 if (!aPoint.IsEndOfContainer() && aPoint.GetChild() &&
2307 aPoint.GetChild()->IsText()) {
2308 return EditorDOMPointType(aPoint.GetChild(), 0u);
2310 if (aPoint.IsEndOfContainer()) {
2311 WSRunScanner scanner(&aEditingHost, aPoint,
2312 BlockInlineCheck::UseComputedDisplayStyle);
2313 WSScanResult previousThing =
2314 scanner.ScanPreviousVisibleNodeOrBlockBoundaryFrom(aPoint);
2315 if (previousThing.InVisibleOrCollapsibleCharacters()) {
2316 return EditorDOMPointType::AtEndOf(*previousThing.TextPtr());
2319 if (HTMLEditUtils::CanNodeContain(*aPoint.GetContainer(),
2320 *nsGkAtoms::textTagName)) {
2321 return aPoint.template To<EditorDOMPointType>();
2323 if (MOZ_UNLIKELY(aPoint.GetContainer() == &aEditingHost ||
2324 !aPoint.template GetContainerParentAs<nsIContent>() ||
2325 !HTMLEditUtils::CanNodeContain(
2326 *aPoint.template ContainerParentAs<nsIContent>(),
2327 *nsGkAtoms::textTagName))) {
2328 return EditorDOMPointType();
2330 return aPoint.ParentPoint().template To<EditorDOMPointType>();
2333 // static
2334 template <typename EditorDOMPointType, typename EditorDOMPointTypeInput>
2335 Result<EditorDOMPointType, nsresult>
2336 HTMLEditUtils::ComputePointToPutCaretInElementIfOutside(
2337 const Element& aElement, const EditorDOMPointTypeInput& aCurrentPoint) {
2338 MOZ_ASSERT(aCurrentPoint.IsSet());
2340 // FYI: This was moved from
2341 // https://searchfox.org/mozilla-central/rev/d3c2f51d89c3ca008ff0cb5a057e77ccd973443e/editor/libeditor/HTMLEditSubActionHandler.cpp#9193
2343 // Use range boundaries and RangeUtils::CompareNodeToRange() to compare
2344 // selection start to new block.
2345 bool nodeBefore, nodeAfter;
2346 nsresult rv = RangeUtils::CompareNodeToRangeBoundaries(
2347 const_cast<Element*>(&aElement), aCurrentPoint.ToRawRangeBoundary(),
2348 aCurrentPoint.ToRawRangeBoundary(), &nodeBefore, &nodeAfter);
2349 if (NS_FAILED(rv)) {
2350 NS_WARNING("RangeUtils::CompareNodeToRange() failed");
2351 return Err(rv);
2354 if (nodeBefore && nodeAfter) {
2355 return EditorDOMPointType(); // aCurrentPoint is in aElement
2358 if (nodeBefore) {
2359 // selection is after block. put at end of block.
2360 const nsIContent* lastEditableContent = HTMLEditUtils::GetLastChild(
2361 aElement, {WalkTreeOption::IgnoreNonEditableNode});
2362 if (!lastEditableContent) {
2363 lastEditableContent = &aElement;
2365 if (lastEditableContent->IsText() ||
2366 HTMLEditUtils::IsContainerNode(*lastEditableContent)) {
2367 return EditorDOMPointType::AtEndOf(*lastEditableContent);
2369 MOZ_ASSERT(lastEditableContent->GetParentNode());
2370 return EditorDOMPointType::After(*lastEditableContent);
2373 // selection is before block. put at start of block.
2374 const nsIContent* firstEditableContent = HTMLEditUtils::GetFirstChild(
2375 aElement, {WalkTreeOption::IgnoreNonEditableNode});
2376 if (!firstEditableContent) {
2377 firstEditableContent = &aElement;
2379 if (firstEditableContent->IsText() ||
2380 HTMLEditUtils::IsContainerNode(*firstEditableContent)) {
2381 MOZ_ASSERT(firstEditableContent->GetParentNode());
2382 // XXX Shouldn't this be EditorDOMPointType(firstEditableContent, 0u)?
2383 return EditorDOMPointType(firstEditableContent);
2385 // XXX And shouldn't this be EditorDOMPointType(firstEditableContent)?
2386 return EditorDOMPointType(firstEditableContent, 0u);
2389 // static
2390 bool HTMLEditUtils::IsInlineStyleSetByElement(
2391 const nsIContent& aContent, const EditorInlineStyle& aStyle,
2392 const nsAString* aValue, nsAString* aOutValue /* = nullptr */) {
2393 for (Element* element : aContent.InclusiveAncestorsOfType<Element>()) {
2394 if (aStyle.mHTMLProperty != element->NodeInfo()->NameAtom()) {
2395 continue;
2397 if (!aStyle.mAttribute) {
2398 return true;
2400 nsAutoString value;
2401 element->GetAttr(aStyle.mAttribute, value);
2402 if (aOutValue) {
2403 *aOutValue = value;
2405 if (!value.IsEmpty()) {
2406 if (!aValue) {
2407 return true;
2409 if (aValue->Equals(value, nsCaseInsensitiveStringComparator)) {
2410 return true;
2412 // We found the prop with the attribute, but the value doesn't match.
2413 return false;
2416 return false;
2419 // static
2420 size_t HTMLEditUtils::CollectChildren(
2421 const nsINode& aNode,
2422 nsTArray<OwningNonNull<nsIContent>>& aOutArrayOfContents,
2423 size_t aIndexToInsertChildren, const CollectChildrenOptions& aOptions) {
2424 // FYI: This was moved from
2425 // https://searchfox.org/mozilla-central/rev/4bce7d85ba4796dd03c5dcc7cfe8eee0e4c07b3b/editor/libeditor/HTMLEditSubActionHandler.cpp#6261
2427 size_t numberOfFoundChildren = 0;
2428 for (nsIContent* content =
2429 GetFirstChild(aNode, {WalkTreeOption::IgnoreNonEditableNode});
2430 content; content = content->GetNextSibling()) {
2431 if ((aOptions.contains(CollectChildrenOption::CollectListChildren) &&
2432 (HTMLEditUtils::IsAnyListElement(content) ||
2433 HTMLEditUtils::IsListItem(content))) ||
2434 (aOptions.contains(CollectChildrenOption::CollectTableChildren) &&
2435 HTMLEditUtils::IsAnyTableElement(content))) {
2436 numberOfFoundChildren += HTMLEditUtils::CollectChildren(
2437 *content, aOutArrayOfContents,
2438 aIndexToInsertChildren + numberOfFoundChildren, aOptions);
2439 continue;
2442 if (aOptions.contains(CollectChildrenOption::IgnoreNonEditableChildren) &&
2443 !EditorUtils::IsEditableContent(*content, EditorType::HTML)) {
2444 continue;
2446 if (aOptions.contains(CollectChildrenOption::IgnoreInvisibleTextNodes) &&
2447 content->IsText() &&
2448 !HTMLEditUtils::IsVisibleTextNode(*content->AsText())) {
2449 continue;
2451 aOutArrayOfContents.InsertElementAt(
2452 aIndexToInsertChildren + numberOfFoundChildren++, *content);
2454 return numberOfFoundChildren;
2457 // static
2458 size_t HTMLEditUtils::CollectEmptyInlineContainerDescendants(
2459 const nsINode& aNode,
2460 nsTArray<OwningNonNull<nsIContent>>& aOutArrayOfContents,
2461 const EmptyCheckOptions& aOptions, BlockInlineCheck aBlockInlineCheck) {
2462 size_t numberOfFoundElements = 0;
2463 for (Element* element = aNode.GetFirstElementChild(); element;) {
2464 if (HTMLEditUtils::IsEmptyInlineContainer(*element, aOptions,
2465 aBlockInlineCheck)) {
2466 aOutArrayOfContents.AppendElement(*element);
2467 numberOfFoundElements++;
2468 nsIContent* nextContent = element->GetNextNonChildNode(&aNode);
2469 element = nullptr;
2470 for (; nextContent; nextContent = nextContent->GetNextNode(&aNode)) {
2471 if (nextContent->IsElement()) {
2472 element = nextContent->AsElement();
2473 break;
2476 continue;
2479 nsIContent* nextContent = element->GetNextNode(&aNode);
2480 element = nullptr;
2481 for (; nextContent; nextContent = nextContent->GetNextNode(&aNode)) {
2482 if (nextContent->IsElement()) {
2483 element = nextContent->AsElement();
2484 break;
2488 return numberOfFoundElements;
2491 // static
2492 bool HTMLEditUtils::ElementHasAttributeExcept(const Element& aElement,
2493 const nsAtom& aAttribute1,
2494 const nsAtom& aAttribute2,
2495 const nsAtom& aAttribute3) {
2496 // FYI: This was moved from
2497 // https://searchfox.org/mozilla-central/rev/0b1543e85d13c30a13c57e959ce9815a3f0fa1d3/editor/libeditor/HTMLStyleEditor.cpp#1626
2498 for (auto i : IntegerRange<uint32_t>(aElement.GetAttrCount())) {
2499 const nsAttrName* name = aElement.GetAttrNameAt(i);
2500 if (!name->NamespaceEquals(kNameSpaceID_None)) {
2501 return true;
2504 if (name->LocalName() == &aAttribute1 ||
2505 name->LocalName() == &aAttribute2 ||
2506 name->LocalName() == &aAttribute3) {
2507 continue; // Ignore the given attribute
2510 // Ignore empty style, class and id attributes because those attributes are
2511 // not meaningful with empty value.
2512 if (name->LocalName() == nsGkAtoms::style ||
2513 name->LocalName() == nsGkAtoms::_class ||
2514 name->LocalName() == nsGkAtoms::id) {
2515 if (aElement.HasNonEmptyAttr(name->LocalName())) {
2516 return true;
2518 continue;
2521 // Ignore special _moz attributes
2522 nsAutoString attrString;
2523 name->LocalName()->ToString(attrString);
2524 if (!StringBeginsWith(attrString, u"_moz"_ns)) {
2525 return true;
2528 // if we made it through all of them without finding a real attribute
2529 // other than aAttribute, then return true
2530 return false;
2533 bool HTMLEditUtils::GetNormalizedHTMLColorValue(const nsAString& aColorValue,
2534 nsAString& aNormalizedValue) {
2535 nsAttrValue value;
2536 if (!value.ParseColor(aColorValue)) {
2537 aNormalizedValue = aColorValue;
2538 return false;
2540 nscolor color = NS_RGB(0, 0, 0);
2541 MOZ_ALWAYS_TRUE(value.GetColorValue(color));
2542 aNormalizedValue = NS_ConvertASCIItoUTF16(nsPrintfCString(
2543 "#%02x%02x%02x", NS_GET_R(color), NS_GET_G(color), NS_GET_B(color)));
2544 return true;
2547 bool HTMLEditUtils::IsSameHTMLColorValue(
2548 const nsAString& aColorA, const nsAString& aColorB,
2549 TransparentKeyword aTransparentKeyword) {
2550 if (aTransparentKeyword == TransparentKeyword::Allowed) {
2551 const bool isATransparent = aColorA.LowerCaseEqualsLiteral("transparent");
2552 const bool isBTransparent = aColorB.LowerCaseEqualsLiteral("transparent");
2553 if (isATransparent || isBTransparent) {
2554 return isATransparent && isBTransparent;
2557 nsAttrValue valueA, valueB;
2558 if (!valueA.ParseColor(aColorA) || !valueB.ParseColor(aColorB)) {
2559 return false;
2561 nscolor colorA = NS_RGB(0, 0, 0), colorB = NS_RGB(0, 0, 0);
2562 MOZ_ALWAYS_TRUE(valueA.GetColorValue(colorA));
2563 MOZ_ALWAYS_TRUE(valueB.GetColorValue(colorB));
2564 return colorA == colorB;
2567 bool HTMLEditUtils::MaybeCSSSpecificColorValue(const nsAString& aColorValue) {
2568 if (aColorValue.IsEmpty() || aColorValue.First() == '#') {
2569 return false; // Quick return for the most cases.
2572 nsAutoString colorValue(aColorValue);
2573 colorValue.CompressWhitespace(true, true);
2574 if (colorValue.LowerCaseEqualsASCII("transparent")) {
2575 return true;
2577 nscolor color = NS_RGB(0, 0, 0);
2578 if (colorValue.IsEmpty() || colorValue.First() == '#') {
2579 return false;
2581 const NS_ConvertUTF16toUTF8 colorU8(colorValue);
2582 if (Servo_ColorNameToRgb(&colorU8, &color)) {
2583 return false;
2585 if (colorValue.LowerCaseEqualsASCII("initial") ||
2586 colorValue.LowerCaseEqualsASCII("inherit") ||
2587 colorValue.LowerCaseEqualsASCII("unset") ||
2588 colorValue.LowerCaseEqualsASCII("revert") ||
2589 colorValue.LowerCaseEqualsASCII("currentcolor")) {
2590 return true;
2592 return ServoCSSParser::IsValidCSSColor(colorU8);
2595 static bool ComputeColor(const nsAString& aColorValue, nscolor* aColor,
2596 bool* aIsCurrentColor) {
2597 return ServoCSSParser::ComputeColor(nullptr, NS_RGB(0, 0, 0),
2598 NS_ConvertUTF16toUTF8(aColorValue),
2599 aColor, aIsCurrentColor);
2602 static bool ComputeColor(const nsACString& aColorValue, nscolor* aColor,
2603 bool* aIsCurrentColor) {
2604 return ServoCSSParser::ComputeColor(nullptr, NS_RGB(0, 0, 0), aColorValue,
2605 aColor, aIsCurrentColor);
2608 bool HTMLEditUtils::CanConvertToHTMLColorValue(const nsAString& aColorValue) {
2609 bool isCurrentColor = false;
2610 nscolor color = NS_RGB(0, 0, 0);
2611 return ComputeColor(aColorValue, &color, &isCurrentColor) &&
2612 !isCurrentColor && NS_GET_A(color) == 0xFF;
2615 bool HTMLEditUtils::ConvertToNormalizedHTMLColorValue(
2616 const nsAString& aColorValue, nsAString& aNormalizedValue) {
2617 bool isCurrentColor = false;
2618 nscolor color = NS_RGB(0, 0, 0);
2619 if (!ComputeColor(aColorValue, &color, &isCurrentColor) || isCurrentColor ||
2620 NS_GET_A(color) != 0xFF) {
2621 aNormalizedValue = aColorValue;
2622 return false;
2624 aNormalizedValue.Truncate();
2625 aNormalizedValue.AppendPrintf("#%02x%02x%02x", NS_GET_R(color),
2626 NS_GET_G(color), NS_GET_B(color));
2627 return true;
2630 bool HTMLEditUtils::GetNormalizedCSSColorValue(const nsAString& aColorValue,
2631 ZeroAlphaColor aZeroAlphaColor,
2632 nsAString& aNormalizedValue) {
2633 bool isCurrentColor = false;
2634 nscolor color = NS_RGB(0, 0, 0);
2635 if (!ComputeColor(aColorValue, &color, &isCurrentColor)) {
2636 aNormalizedValue = aColorValue;
2637 return false;
2640 // If it's currentcolor, let's return it as-is since we cannot resolve it
2641 // without ancestors.
2642 if (isCurrentColor) {
2643 aNormalizedValue = aColorValue;
2644 return true;
2647 if (aZeroAlphaColor == ZeroAlphaColor::TransparentKeyword &&
2648 NS_GET_A(color) == 0) {
2649 aNormalizedValue.AssignLiteral("transparent");
2650 return true;
2653 // Get serialized color value (i.e., "rgb()" or "rgba()").
2654 aNormalizedValue.Truncate();
2655 nsStyleUtil::GetSerializedColorValue(color, aNormalizedValue);
2656 return true;
2659 template <typename CharType>
2660 bool HTMLEditUtils::IsSameCSSColorValue(const nsTSubstring<CharType>& aColorA,
2661 const nsTSubstring<CharType>& aColorB) {
2662 bool isACurrentColor = false;
2663 nscolor colorA = NS_RGB(0, 0, 0);
2664 if (!ComputeColor(aColorA, &colorA, &isACurrentColor)) {
2665 return false;
2667 bool isBCurrentColor = false;
2668 nscolor colorB = NS_RGB(0, 0, 0);
2669 if (!ComputeColor(aColorB, &colorB, &isBCurrentColor)) {
2670 return false;
2672 if (isACurrentColor || isBCurrentColor) {
2673 return isACurrentColor && isBCurrentColor;
2675 return colorA == colorB;
2678 /******************************************************************************
2679 * SelectedTableCellScanner
2680 ******************************************************************************/
2682 SelectedTableCellScanner::SelectedTableCellScanner(
2683 const AutoRangeArray& aRanges) {
2684 if (aRanges.Ranges().IsEmpty()) {
2685 return;
2687 Element* firstSelectedCellElement =
2688 HTMLEditUtils::GetTableCellElementIfOnlyOneSelected(
2689 aRanges.FirstRangeRef());
2690 if (!firstSelectedCellElement) {
2691 return; // We're not in table cell selection mode.
2693 mSelectedCellElements.SetCapacity(aRanges.Ranges().Length());
2694 mSelectedCellElements.AppendElement(*firstSelectedCellElement);
2695 for (uint32_t i = 1; i < aRanges.Ranges().Length(); i++) {
2696 nsRange* range = aRanges.Ranges()[i];
2697 if (NS_WARN_IF(!range) || NS_WARN_IF(!range->IsPositioned())) {
2698 continue; // Shouldn't occur in normal conditions.
2700 // Just ignore selection ranges which do not select only one table
2701 // cell element. This is possible case if web apps sets multiple
2702 // selections and first range selects a table cell element.
2703 if (Element* selectedCellElement =
2704 HTMLEditUtils::GetTableCellElementIfOnlyOneSelected(*range)) {
2705 mSelectedCellElements.AppendElement(*selectedCellElement);
2710 } // namespace mozilla