Backed out changeset b462e7b742d8 (bug 1908261) for causing multiple reftest failures...
[gecko.git] / dom / base / nsINode.h
blob35943995eee107ca97fc814fb13373c29fcc7897
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #ifndef nsINode_h___
8 #define nsINode_h___
10 #include "mozilla/DoublyLinkedList.h"
11 #include "mozilla/Likely.h"
12 #include "mozilla/UniquePtr.h"
13 #include "nsCOMPtr.h" // for member, local
14 #include "nsGkAtoms.h" // for nsGkAtoms::baseURIProperty
15 #include "mozilla/dom/NodeInfo.h" // member (in nsCOMPtr)
16 #include "nsIWeakReference.h"
17 #include "nsIMutationObserver.h"
18 #include "nsNodeInfoManager.h" // for use in NodePrincipal()
19 #include "nsPropertyTable.h" // for typedefs
20 #include "mozilla/ErrorResult.h"
21 #include "mozilla/LinkedList.h"
22 #include "mozilla/MemoryReporting.h"
23 #include "mozilla/dom/EventTarget.h" // for base class
24 #include "js/TypeDecls.h" // for Handle, Value, JSObject, JSContext
25 #include "mozilla/dom/DOMString.h"
26 #include "mozilla/dom/BindingDeclarations.h"
27 #include "mozilla/dom/NodeBinding.h"
28 #include "nsTHashtable.h"
29 #include <iosfwd>
31 // Including 'windows.h' will #define GetClassInfo to something else.
32 #ifdef XP_WIN
33 # ifdef GetClassInfo
34 # undef GetClassInfo
35 # endif
36 #endif
38 class AttrArray;
39 class nsAttrChildContentList;
40 template <typename T>
41 class nsCOMArray;
42 class nsDOMAttributeMap;
43 class nsGenericHTMLElement;
44 class nsIAnimationObserver;
45 class nsIContent;
46 class nsIContentSecurityPolicy;
47 class nsIFrame;
48 class nsIFormControl;
49 class nsIHTMLCollection;
50 class nsMultiMutationObserver;
51 class nsINode;
52 class nsINodeList;
53 class nsIPrincipal;
54 class nsIURI;
55 class nsNodeSupportsWeakRefTearoff;
56 class nsDOMMutationObserver;
57 class nsRange;
58 class nsWindowSizes;
60 namespace mozilla {
61 class EventListenerManager;
62 struct StyleSelectorList;
63 template <typename T>
64 class Maybe;
65 class PresShell;
66 class TextEditor;
67 namespace dom {
68 /**
69 * @return true if aChar is what the WHATWG defines as a 'ascii whitespace'.
70 * https://infra.spec.whatwg.org/#ascii-whitespace
72 inline bool IsSpaceCharacter(char16_t aChar) {
73 return aChar == ' ' || aChar == '\t' || aChar == '\n' || aChar == '\r' ||
74 aChar == '\f';
76 inline bool IsSpaceCharacter(char aChar) {
77 return aChar == ' ' || aChar == '\t' || aChar == '\n' || aChar == '\r' ||
78 aChar == '\f';
80 class AbstractRange;
81 class AccessibleNode;
82 template <typename T>
83 class AncestorsOfTypeIterator;
84 struct BoxQuadOptions;
85 struct ConvertCoordinateOptions;
86 class DocGroup;
87 class Document;
88 class DocumentFragment;
89 class DocumentOrShadowRoot;
90 class DOMPoint;
91 class DOMQuad;
92 class DOMRectReadOnly;
93 class Element;
94 class EventHandlerNonNull;
95 template <typename T>
96 class FlatTreeAncestorsOfTypeIterator;
97 template <typename T>
98 class InclusiveAncestorsOfTypeIterator;
99 template <typename T>
100 class InclusiveFlatTreeAncestorsOfTypeIterator;
101 class LinkStyle;
102 class MutationObservers;
103 template <typename T>
104 class Optional;
105 class OwningNodeOrString;
106 class SelectionNodeCache;
107 template <typename>
108 class Sequence;
109 class ShadowRoot;
110 class SVGUseElement;
111 class Text;
112 class TextOrElementOrDocument;
113 struct DOMPointInit;
114 struct GetRootNodeOptions;
115 enum class CallerType : uint32_t;
116 } // namespace dom
117 } // namespace mozilla
119 #define NODE_FLAG_BIT(n_) \
120 (nsWrapperCache::FlagsType(1U) << (WRAPPER_CACHE_FLAGS_BITS_USED + (n_)))
122 enum : uint32_t {
123 // This bit will be set if the node has a listener manager.
124 NODE_HAS_LISTENERMANAGER = NODE_FLAG_BIT(0),
126 // Whether this node has had any properties set on it
127 NODE_HAS_PROPERTIES = NODE_FLAG_BIT(1),
129 // Whether the node has some ancestor, possibly itself, that is native
130 // anonymous. This includes ancestors crossing XBL scopes, in cases when an
131 // XBL binding is attached to an element which has a native anonymous
132 // ancestor. This flag is set-once: once a node has it, it must not be
133 // removed.
134 // NOTE: Should only be used on nsIContent nodes
135 NODE_IS_IN_NATIVE_ANONYMOUS_SUBTREE = NODE_FLAG_BIT(2),
137 // Whether this node is the root of a native anonymous (from the perspective
138 // of its parent) subtree. This flag is set-once: once a node has it, it
139 // must not be removed.
140 // NOTE: Should only be used on nsIContent nodes
141 NODE_IS_NATIVE_ANONYMOUS_ROOT = NODE_FLAG_BIT(3),
143 NODE_IS_EDITABLE = NODE_FLAG_BIT(4),
145 // Whether the node participates in a shadow tree.
146 NODE_IS_IN_SHADOW_TREE = NODE_FLAG_BIT(5),
148 // This node needs to go through frame construction to get a frame (or
149 // undisplayed entry).
150 NODE_NEEDS_FRAME = NODE_FLAG_BIT(6),
152 // At least one descendant in the flattened tree has NODE_NEEDS_FRAME set.
153 // This should be set on every node on the flattened tree path between the
154 // node(s) with NODE_NEEDS_FRAME and the root content.
155 NODE_DESCENDANTS_NEED_FRAMES = NODE_FLAG_BIT(7),
157 // Set if the node has the accesskey attribute set.
158 NODE_HAS_ACCESSKEY = NODE_FLAG_BIT(8),
160 NODE_HAS_BEEN_IN_UA_WIDGET = NODE_FLAG_BIT(9),
162 // Set if the node has a nonce value and a header delivered CSP.
163 NODE_HAS_NONCE_AND_HEADER_CSP = NODE_FLAG_BIT(10),
165 NODE_KEEPS_DOMARENA = NODE_FLAG_BIT(11),
167 NODE_MAY_HAVE_ELEMENT_CHILDREN = NODE_FLAG_BIT(12),
169 NODE_HAS_SCHEDULED_SELECTION_CHANGE_EVENT = NODE_FLAG_BIT(13),
171 // Remaining bits are node type specific.
172 NODE_TYPE_SPECIFIC_BITS_OFFSET = 14
175 // Flags for selectors that persist to the DOM node.
176 enum class NodeSelectorFlags : uint32_t {
177 // Node has an :empty or :-moz-only-whitespace selector
178 HasEmptySelector = 1 << 0,
180 /// A child of the node has a selector such that any insertion,
181 /// removal, or appending of children requires restyling the parent, if the
182 /// parent is an element. If the parent is the shadow root, the child's
183 /// siblings are restyled.
184 HasSlowSelector = 1 << 1,
186 /// A child of the node has a :first-child, :-moz-first-node,
187 /// :only-child, :last-child or :-moz-last-node selector.
188 HasEdgeChildSelector = 1 << 2,
190 /// A child of the node has a selector such that any insertion or
191 /// removal of children requires restyling later siblings of that
192 /// element. Additionally (in this manner it is stronger than
193 /// NODE_HAS_SLOW_SELECTOR), if a child's style changes due to any
194 /// other content tree changes (e.g., the child changes to or from
195 /// matching :empty due to a grandchild insertion or removal), the
196 /// child's later siblings must also be restyled.
197 HasSlowSelectorLaterSiblings = 1 << 3,
199 /// HasSlowSelector* was set by the presence of :nth (But not of).
200 HasSlowSelectorNth = 1 << 4,
202 /// A child of this node might be matched by :nth-child(.. of <selector>) or
203 /// :nth-last-child(.. of <selector>). If a DOM mutation may have caused the
204 /// selector to either match or no longer match that child, the child's
205 /// siblings are restyled.
206 HasSlowSelectorNthOf = 1 << 5,
208 /// All instances of :nth flags.
209 HasSlowSelectorNthAll = HasSlowSelectorNthOf | HasSlowSelectorNth,
211 /// Set of selector flags that may trigger a restyle on DOM append, with
212 /// restyle on siblings or a single parent (And perhaps their subtrees).
213 AllSimpleRestyleFlagsForAppend = HasEmptySelector | HasSlowSelector |
214 HasEdgeChildSelector | HasSlowSelectorNthAll,
216 /// Set of selector flags that may trigger a restyle as a result of any
217 /// DOM mutation.
218 AllSimpleRestyleFlags =
219 AllSimpleRestyleFlagsForAppend | HasSlowSelectorLaterSiblings,
221 // This node was evaluated as an anchor for a relative selector.
222 RelativeSelectorAnchor = 1 << 6,
224 // This node was evaluated as an anchor for a relative selector, and that
225 // relative selector was not the subject of the overall selector.
226 RelativeSelectorAnchorNonSubject = 1 << 7,
228 // This node's sibling(s) performed a relative selector search to this node.
229 RelativeSelectorSearchDirectionSibling = 1 << 8,
231 // This node's ancestor(s) performed a relative selector search to this node.
232 RelativeSelectorSearchDirectionAncestor = 1 << 9,
234 // This node's sibling(s) and ancestor(s), and/or this node's ancestor's
235 // sibling(s) performed a relative selector search to this node.
236 RelativeSelectorSearchDirectionAncestorSibling =
237 RelativeSelectorSearchDirectionSibling |
238 RelativeSelectorSearchDirectionAncestor,
241 MOZ_MAKE_ENUM_CLASS_BITWISE_OPERATORS(NodeSelectorFlags);
243 enum class BatchRemovalOrder {
244 FrontToBack,
245 BackToFront,
248 struct BatchRemovalState {
249 bool mIsFirst = true;
252 // Make sure we have space for our bits
253 #define ASSERT_NODE_FLAGS_SPACE(n) \
254 static_assert(WRAPPER_CACHE_FLAGS_BITS_USED + (n) <= \
255 sizeof(nsWrapperCache::FlagsType) * 8, \
256 "Not enough space for our bits")
257 ASSERT_NODE_FLAGS_SPACE(NODE_TYPE_SPECIFIC_BITS_OFFSET);
260 * Class used to detect unexpected mutations. To use the class create an
261 * nsMutationGuard on the stack before unexpected mutations could occur.
262 * You can then at any time call Mutated to check if any unexpected mutations
263 * have occurred.
265 class nsMutationGuard {
266 public:
267 nsMutationGuard() { mStartingGeneration = sGeneration; }
270 * Returns true if any unexpected mutations have occurred. You can pass in
271 * an 8-bit ignore count to ignore a number of expected mutations.
273 * We don't need to care about overflow because subtraction of uint64_t's is
274 * finding the difference between two elements of the group Z < 2^64. Once
275 * we know the difference between two elements we only need to check that is
276 * less than the given number of mutations to know less than that many
277 * mutations occured. Assuming constant 1ns mutations it would take 584
278 * years for sGeneration to fully wrap around so we can ignore a guard living
279 * through a full wrap around.
281 bool Mutated(uint8_t aIgnoreCount) {
282 return (sGeneration - mStartingGeneration) > aIgnoreCount;
285 // This function should be called whenever a mutation that we want to keep
286 // track of happen. For now this is only done when children are added or
287 // removed, but we might do it for attribute changes too in the future.
288 static void DidMutate() { sGeneration++; }
290 private:
291 // This is the value sGeneration had when the guard was constructed.
292 uint64_t mStartingGeneration;
294 // This value is incremented on every mutation, for the life of the process.
295 static uint64_t sGeneration;
299 * A class that implements nsIWeakReference
301 class nsNodeWeakReference final : public nsIWeakReference {
302 public:
303 explicit nsNodeWeakReference(nsINode* aNode);
305 // nsISupports
306 NS_DECL_ISUPPORTS
308 // nsIWeakReference
309 NS_DECL_NSIWEAKREFERENCE
311 void NoticeNodeDestruction() { mObject = nullptr; }
313 private:
314 ~nsNodeWeakReference();
317 // This should be used for any nsINode sub-class that has fields of its own
318 // that it needs to measure; any sub-class that doesn't use it will inherit
319 // AddSizeOfExcludingThis from its super-class. AddSizeOfIncludingThis() need
320 // not be defined, it is inherited from nsINode.
321 #define NS_DECL_ADDSIZEOFEXCLUDINGTHIS \
322 virtual void AddSizeOfExcludingThis(nsWindowSizes& aSizes, \
323 size_t* aNodeSize) const override;
325 // IID for the nsINode interface
326 // Must be kept in sync with xpcom/rust/xpcom/src/interfaces/nonidl.rs
327 #define NS_INODE_IID \
328 {0x70ba4547, 0x7699, 0x44fc, {0xb3, 0x20, 0x52, 0xdb, 0xe3, 0xd1, 0xf9, 0x0a}}
331 * An internal interface that abstracts some DOMNode-related parts that both
332 * nsIContent and Document share. An instance of this interface has a list
333 * of nsIContent children and provides access to them.
335 class nsINode : public mozilla::dom::EventTarget {
336 #ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
337 void AssertInvariantsOnNodeInfoChange();
338 #endif
339 public:
340 using BoxQuadOptions = mozilla::dom::BoxQuadOptions;
341 using ConvertCoordinateOptions = mozilla::dom::ConvertCoordinateOptions;
342 using DocGroup = mozilla::dom::DocGroup;
343 using Document = mozilla::dom::Document;
344 using DOMPoint = mozilla::dom::DOMPoint;
345 using DOMPointInit = mozilla::dom::DOMPointInit;
346 using DOMQuad = mozilla::dom::DOMQuad;
347 using DOMRectReadOnly = mozilla::dom::DOMRectReadOnly;
348 using OwningNodeOrString = mozilla::dom::OwningNodeOrString;
349 using TextOrElementOrDocument = mozilla::dom::TextOrElementOrDocument;
350 using CallerType = mozilla::dom::CallerType;
351 using ErrorResult = mozilla::ErrorResult;
353 // XXXbz Maybe we should codegen a class holding these constants and
354 // inherit from it...
355 static const auto ELEMENT_NODE = mozilla::dom::Node_Binding::ELEMENT_NODE;
356 static const auto ATTRIBUTE_NODE = mozilla::dom::Node_Binding::ATTRIBUTE_NODE;
357 static const auto TEXT_NODE = mozilla::dom::Node_Binding::TEXT_NODE;
358 static const auto CDATA_SECTION_NODE =
359 mozilla::dom::Node_Binding::CDATA_SECTION_NODE;
360 static const auto ENTITY_REFERENCE_NODE =
361 mozilla::dom::Node_Binding::ENTITY_REFERENCE_NODE;
362 static const auto ENTITY_NODE = mozilla::dom::Node_Binding::ENTITY_NODE;
363 static const auto PROCESSING_INSTRUCTION_NODE =
364 mozilla::dom::Node_Binding::PROCESSING_INSTRUCTION_NODE;
365 static const auto COMMENT_NODE = mozilla::dom::Node_Binding::COMMENT_NODE;
366 static const auto DOCUMENT_NODE = mozilla::dom::Node_Binding::DOCUMENT_NODE;
367 static const auto DOCUMENT_TYPE_NODE =
368 mozilla::dom::Node_Binding::DOCUMENT_TYPE_NODE;
369 static const auto DOCUMENT_FRAGMENT_NODE =
370 mozilla::dom::Node_Binding::DOCUMENT_FRAGMENT_NODE;
371 static const auto NOTATION_NODE = mozilla::dom::Node_Binding::NOTATION_NODE;
372 static const auto MAX_NODE_TYPE = NOTATION_NODE;
374 void* operator new(size_t aSize, nsNodeInfoManager* aManager);
375 void* operator new(size_t aSize) = delete;
376 void operator delete(void* aPtr);
378 template <class T>
379 using Sequence = mozilla::dom::Sequence<T>;
381 NS_DECLARE_STATIC_IID_ACCESSOR(NS_INODE_IID)
383 // The |aNodeSize| outparam on this function is where the actual node size
384 // value is put. It gets added to the appropriate value within |aSizes| by
385 // AddSizeOfNodeTree().
387 // Among the sub-classes that inherit (directly or indirectly) from nsINode,
388 // measurement of the following members may be added later if DMD finds it is
389 // worthwhile:
390 // - nsGenericHTMLElement: mForm, mFieldSet
391 // - nsGenericHTMLFrameElement: mFrameLoader (bug 672539)
392 // - HTMLBodyElement: mContentStyleRule
393 // - HTMLDataListElement: mOptions
394 // - HTMLFieldSetElement: mElements, mDependentElements, mFirstLegend
395 // - HTMLFormElement: many!
396 // - HTMLFrameSetElement: mRowSpecs, mColSpecs
397 // - HTMLInputElement: mInputData, mFiles, mFileList, mStaticDocfileList
398 // - nsHTMLMapElement: mAreas
399 // - HTMLMediaElement: many!
400 // - nsHTMLOutputElement: mDefaultValue, mTokenList
401 // - nsHTMLRowElement: mCells
402 // - nsHTMLSelectElement: mOptions, mRestoreState
403 // - nsHTMLTableElement: mTBodies, mRows, mTableInheritedAttributes
404 // - nsHTMLTableSectionElement: mRows
405 // - nsHTMLTextAreaElement: mControllers, mState
407 // The following members don't need to be measured:
408 // - nsIContent: mPrimaryFrame, because it's non-owning and measured elsewhere
410 virtual void AddSizeOfExcludingThis(nsWindowSizes& aSizes,
411 size_t* aNodeSize) const;
413 // SizeOfIncludingThis doesn't need to be overridden by sub-classes because
414 // sub-classes of nsINode are guaranteed to be laid out in memory in such a
415 // way that |this| points to the start of the allocated object, even in
416 // methods of nsINode's sub-classes, so aSizes.mState.mMallocSizeOf(this) is
417 // always safe to call no matter which object it was invoked on.
418 void AddSizeOfIncludingThis(nsWindowSizes& aSizes, size_t* aNodeSize) const;
420 friend class nsNodeWeakReference;
421 friend class nsNodeSupportsWeakRefTearoff;
422 friend class AttrArray;
424 #ifdef MOZILLA_INTERNAL_API
425 explicit nsINode(already_AddRefed<mozilla::dom::NodeInfo>&& aNodeInfo);
426 #endif
428 virtual ~nsINode();
430 bool IsContainerNode() const {
431 return IsElement() || IsDocument() || IsDocumentFragment();
435 * Returns true if the node is a HTMLTemplate element.
437 bool IsTemplateElement() const { return IsHTMLElement(nsGkAtoms::_template); }
439 bool IsSlotable() const { return IsElement() || IsText(); }
442 * Returns true if this is a document node.
444 bool IsDocument() const {
445 // One less pointer-chase than checking NodeType().
446 return !GetParentNode() && IsInUncomposedDoc();
450 * Return this node as a document. Asserts IsDocument().
452 * This is defined inline in Document.h.
454 inline Document* AsDocument();
455 inline const Document* AsDocument() const;
458 * Returns true if this is a document fragment node.
460 bool IsDocumentFragment() const {
461 return NodeType() == DOCUMENT_FRAGMENT_NODE;
464 virtual bool IsHTMLFormControlElement() const { return false; }
467 * https://dom.spec.whatwg.org/#concept-tree-inclusive-descendant
469 * @param aNode must not be nullptr.
471 bool IsInclusiveDescendantOf(const nsINode* aNode) const;
474 * https://dom.spec.whatwg.org/#concept-shadow-including-inclusive-descendant
476 * @param aNode must not be nullptr.
478 bool IsShadowIncludingInclusiveDescendantOf(const nsINode* aNode) const;
481 * Returns true if the given node is this node or one of its descendants
482 * in the "flat tree."
484 * @param aNode must not be nullptr.
486 bool IsInclusiveFlatTreeDescendantOf(const nsINode* aNode) const;
489 * Return this node as a document fragment. Asserts IsDocumentFragment().
491 * This is defined inline in DocumentFragment.h.
493 inline mozilla::dom::DocumentFragment* AsDocumentFragment();
494 inline const mozilla::dom::DocumentFragment* AsDocumentFragment() const;
496 JSObject* WrapObject(JSContext*, JS::Handle<JSObject*> aGivenProto) final;
499 * Hook for constructing JS::ubi::Concrete specializations for memory
500 * reporting. Specializations are defined in NodeUbiReporting.h.
502 virtual void ConstructUbiNode(void* storage) = 0;
505 * returns true if we are in priviliged code or
506 * layout.css.getBoxQuads.enabled == true.
508 static bool HasBoxQuadsSupport(JSContext* aCx, JSObject* /* unused */);
510 protected:
512 * WrapNode is called from WrapObject to actually wrap this node, WrapObject
513 * does some additional checks and fix-up that's common to all nodes. WrapNode
514 * should just call the DOM binding's Wrap function.
516 * aGivenProto is the prototype to use (or null if the default one should be
517 * used) and should just be passed directly on to the DOM binding's Wrap
518 * function.
520 virtual JSObject* WrapNode(JSContext* aCx,
521 JS::Handle<JSObject*> aGivenProto) = 0;
523 public:
524 mozilla::dom::ParentObject GetParentObject()
525 const; // Implemented in Document.h
528 * Returns the first child of a node or the first child of
529 * a template element's content if the provided node is a
530 * template element.
532 nsIContent* GetFirstChildOfTemplateOrNode();
535 * Return the scope chain parent for this node, for use in things
536 * like event handler compilation. Returning null means to use the
537 * global object as the scope chain parent.
539 virtual nsINode* GetScopeChainParent() const;
541 MOZ_CAN_RUN_SCRIPT mozilla::dom::Element* GetParentFlexElement();
544 * Returns the nearest inclusive open popover for a given node, see
545 * https://html.spec.whatwg.org/multipage/popover.html#nearest-inclusive-open-popover
547 mozilla::dom::Element* GetNearestInclusiveOpenPopover() const;
550 * https://html.spec.whatwg.org/multipage/popover.html#nearest-inclusive-target-popover-for-invoker
552 mozilla::dom::Element* GetNearestInclusiveTargetPopoverForInvoker() const;
554 nsGenericHTMLElement* GetEffectiveInvokeTargetElement() const;
557 * https://html.spec.whatwg.org/multipage/popover.html#popover-target-element
559 nsGenericHTMLElement* GetEffectivePopoverTargetElement() const;
562 * https://html.spec.whatwg.org/multipage/popover.html#topmost-clicked-popover
564 mozilla::dom::Element* GetTopmostClickedPopover() const;
566 bool IsNode() const final { return true; }
568 NS_IMPL_FROMEVENTTARGET_HELPER(nsINode, IsNode())
571 * Return whether the node is an Element node. Faster than using `NodeType()`.
573 bool IsElement() const { return GetBoolFlag(NodeIsElement); }
575 virtual bool IsTextControlElement() const { return false; }
576 virtual bool IsGenericHTMLFormControlElementWithState() const {
577 return false;
580 // Returns non-null if this element subclasses `LinkStyle`.
581 virtual const mozilla::dom::LinkStyle* AsLinkStyle() const { return nullptr; }
582 mozilla::dom::LinkStyle* AsLinkStyle() {
583 return const_cast<mozilla::dom::LinkStyle*>(
584 static_cast<const nsINode*>(this)->AsLinkStyle());
588 * Return this node as an Element. Should only be used for nodes
589 * for which IsElement() is true. This is defined inline in Element.h.
591 inline mozilla::dom::Element* AsElement();
592 inline const mozilla::dom::Element* AsElement() const;
595 * Return whether the node is an nsStyledElement instance or not.
597 virtual bool IsStyledElement() const { return false; }
600 * Return this node as nsIContent. Should only be used for nodes for which
601 * IsContent() is true.
603 * The assertion in nsIContent's constructor makes this safe.
605 nsIContent* AsContent() {
606 MOZ_ASSERT(IsContent());
607 return reinterpret_cast<nsIContent*>(this);
609 const nsIContent* AsContent() const {
610 MOZ_ASSERT(IsContent());
611 return reinterpret_cast<const nsIContent*>(this);
615 * Return whether the node is a Text node (which might be an actual
616 * textnode, or might be a CDATA section).
618 bool IsText() const {
619 uint32_t nodeType = NodeType();
620 return nodeType == TEXT_NODE || nodeType == CDATA_SECTION_NODE;
624 * Return this node as Text if it is one, otherwise null. This is defined
625 * inline in Text.h.
627 inline mozilla::dom::Text* GetAsText();
628 inline const mozilla::dom::Text* GetAsText() const;
631 * Return this node as Text. Asserts IsText(). This is defined inline in
632 * Text.h.
634 inline mozilla::dom::Text* AsText();
635 inline const mozilla::dom::Text* AsText() const;
638 * Return this node if the instance type inherits nsIFormControl, or an
639 * nsIFormControl instance which ia associated with this node. Otherwise,
640 * returns nullptr.
642 [[nodiscard]] virtual nsIFormControl* GetAsFormControl() { return nullptr; }
643 [[nodiscard]] virtual const nsIFormControl* GetAsFormControl() const {
644 return nullptr;
648 * Return whether the node is a ProcessingInstruction node.
650 bool IsProcessingInstruction() const {
651 return NodeType() == PROCESSING_INSTRUCTION_NODE;
655 * Return whether the node is a CharacterData node (text, cdata,
656 * comment, processing instruction)
658 bool IsCharacterData() const {
659 uint32_t nodeType = NodeType();
660 return nodeType == TEXT_NODE || nodeType == CDATA_SECTION_NODE ||
661 nodeType == PROCESSING_INSTRUCTION_NODE || nodeType == COMMENT_NODE;
665 * Return whether the node is a Comment node.
667 bool IsComment() const { return NodeType() == COMMENT_NODE; }
670 * Return whether the node is an Attr node.
672 bool IsAttr() const { return NodeType() == ATTRIBUTE_NODE; }
675 * Return if this node has any children.
677 bool HasChildren() const { return !!mFirstChild; }
680 * Get the number of children
681 * @return the number of children
683 uint32_t GetChildCount() const { return mChildCount; }
686 * NOTE: this function is going to be removed soon (hopefully!) Don't use it
687 * in new code.
689 * Get a child by index
690 * @param aIndex the index of the child to get
691 * @return the child, or null if index out of bounds
693 nsIContent* GetChildAt_Deprecated(uint32_t aIndex) const;
696 * Get the index of a child within this content.
698 * @param aPossibleChild the child to get the index of.
699 * @return the index of the child, or Nothing if not a child. Be aware that
700 * anonymous children (e.g. a <div> child of an <input> element) will
701 * result in Nothing.
703 * If the return value is Some, then calling GetChildAt_Deprecated() with
704 * that value will return aPossibleChild.
706 mozilla::Maybe<uint32_t> ComputeIndexOf(const nsINode* aPossibleChild) const;
709 * Get the index of a child within this content's flat tree children.
711 * @param aPossibleChild the child to get the index of.
712 * @return the index of the child, or Nothing if not a child. Be aware that
713 * anonymous children (e.g. a <div> child of an <input> element) will
714 * result in Nothing.
716 mozilla::Maybe<uint32_t> ComputeFlatTreeIndexOf(
717 const nsINode* aPossibleChild) const;
720 * Get the index of this within parent node (ComputeIndexInParentNode) or
721 * parent content (nsIContent) node (ComputeIndexInParentContent).
723 * @return the index of this node in the parent, or Nothing there is no
724 * parent (content) node or the parent does not have this node anymore
725 * (e.g., being removed from the parent). Be aware that anonymous
726 * children (e.g. a <div> child of an <input> element) will result in
727 * Nothing.
729 * If the return value is Some, then calling GetChildAt_Deprecated() with
730 * that value will return this.
732 mozilla::Maybe<uint32_t> ComputeIndexInParentNode() const;
733 mozilla::Maybe<uint32_t> ComputeIndexInParentContent() const;
736 * Get the index of a child within this content.
738 * @param aPossibleChild the child to get the index of.
739 * @return the index of the child, or -1 if not a child. Be aware that
740 * anonymous children (e.g. a <div> child of an <input> element) will
741 * result in -1.
743 * If the return value is not -1, then calling GetChildAt_Deprecated() with
744 * that value will return aPossibleChild.
746 int32_t ComputeIndexOf_Deprecated(const nsINode* aPossibleChild) const;
749 * Returns the "node document" of this node.
751 * https://dom.spec.whatwg.org/#concept-node-document
753 * Note that in the case that this node is a document node this method
754 * will return |this|. That is different to the Node.ownerDocument DOM
755 * attribute (implemented by nsINode::GetOwnerDocument) which is specified to
756 * be null in that case:
758 * https://dom.spec.whatwg.org/#dom-node-ownerdocument
760 * For all other cases OwnerDoc and GetOwnerDocument behave identically.
762 Document* OwnerDoc() const MOZ_NONNULL_RETURN {
763 return mNodeInfo->GetDocument();
767 * Return the "owner document" of this node as an nsINode*. Implemented
768 * in Document.h.
770 inline nsINode* OwnerDocAsNode() const MOZ_NONNULL_RETURN;
773 * Returns true if the content has an ancestor that is a document.
775 * @return whether this content is in a document tree
777 bool IsInUncomposedDoc() const { return GetBoolFlag(IsInDocument); }
780 * Get the document that this content is currently in, if any. This will be
781 * null if the content has no ancestor that is a document.
783 * @return the current document
786 Document* GetUncomposedDoc() const {
787 return IsInUncomposedDoc() ? OwnerDoc() : nullptr;
791 * Returns true if we're connected, and thus GetComposedDoc() would return a
792 * non-null value.
794 bool IsInComposedDoc() const { return GetBoolFlag(IsConnected); }
797 * This method returns the owner document if the node is connected to it
798 * (as defined in the DOM spec), otherwise it returns null.
799 * In other words, returns non-null even in the case the node is in
800 * Shadow DOM, if there is a possibly shadow boundary crossing path from
801 * the node to its owner document.
803 Document* GetComposedDoc() const {
804 return IsInComposedDoc() ? OwnerDoc() : nullptr;
808 * Returns OwnerDoc() if the node is in uncomposed document and ShadowRoot if
809 * the node is in Shadow DOM.
811 mozilla::dom::DocumentOrShadowRoot* GetContainingDocumentOrShadowRoot() const;
814 * Returns OwnerDoc() if the node is in uncomposed document and ShadowRoot if
815 * the node is in Shadow DOM and is in composed document.
817 mozilla::dom::DocumentOrShadowRoot* GetUncomposedDocOrConnectedShadowRoot()
818 const;
821 * To be called when reference count of the node drops to zero.
823 void LastRelease();
826 * The values returned by this function are the ones defined for
827 * Node.nodeType
829 uint16_t NodeType() const { return mNodeInfo->NodeType(); }
830 const nsString& NodeName() const { return mNodeInfo->NodeName(); }
831 const nsString& LocalName() const { return mNodeInfo->LocalName(); }
834 * Get the NodeInfo for this element
835 * @return the nodes node info
837 inline mozilla::dom::NodeInfo* NodeInfo() const { return mNodeInfo; }
840 * Called when we have been adopted, and the information of the
841 * node has been changed.
843 * The new document can be reached via OwnerDoc().
845 * If you override this method,
846 * please call up to the parent NodeInfoChanged.
848 * If you change this, change also the similar method in Link.
850 virtual void NodeInfoChanged(Document* aOldDoc) {
851 #ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
852 AssertInvariantsOnNodeInfoChange();
853 #endif
856 inline bool IsInNamespace(int32_t aNamespace) const {
857 return mNodeInfo->NamespaceID() == aNamespace;
861 * Returns the DocGroup of the "node document" of this node.
863 DocGroup* GetDocGroup() const;
866 * Print a debugger friendly descriptor of this element. This will describe
867 * the position of this element in the document.
869 friend std::ostream& operator<<(std::ostream& aStream, const nsINode& aNode);
871 protected:
872 // These 2 methods are useful for the recursive templates IsHTMLElement,
873 // IsSVGElement, etc.
874 inline bool IsNodeInternal() const { return false; }
876 template <typename First, typename... Args>
877 inline bool IsNodeInternal(First aFirst, Args... aArgs) const {
878 return mNodeInfo->Equals(aFirst) || IsNodeInternal(aArgs...);
881 public:
882 inline bool IsHTMLElement() const {
883 return IsElement() && IsInNamespace(kNameSpaceID_XHTML);
886 inline bool IsHTMLElement(const nsAtom* aTag) const {
887 return IsElement() && mNodeInfo->Equals(aTag, kNameSpaceID_XHTML);
890 template <typename First, typename... Args>
891 inline bool IsAnyOfHTMLElements(First aFirst, Args... aArgs) const {
892 return IsHTMLElement() && IsNodeInternal(aFirst, aArgs...);
895 inline bool IsSVGElement() const {
896 return IsElement() && IsInNamespace(kNameSpaceID_SVG);
899 inline bool IsSVGElement(const nsAtom* aTag) const {
900 return IsElement() && mNodeInfo->Equals(aTag, kNameSpaceID_SVG);
903 template <typename First, typename... Args>
904 inline bool IsAnyOfSVGElements(First aFirst, Args... aArgs) const {
905 return IsSVGElement() && IsNodeInternal(aFirst, aArgs...);
908 virtual bool IsSVGAnimationElement() const { return false; }
909 virtual bool IsSVGComponentTransferFunctionElement() const { return false; }
910 virtual bool IsSVGFilterPrimitiveElement() const { return false; }
911 virtual bool IsSVGFilterPrimitiveChildElement() const { return false; }
912 virtual bool IsSVGGeometryElement() const { return false; }
913 virtual bool IsSVGGraphicsElement() const { return false; }
915 inline bool IsXULElement() const {
916 return IsElement() && IsInNamespace(kNameSpaceID_XUL);
919 inline bool IsXULElement(const nsAtom* aTag) const {
920 return IsElement() && mNodeInfo->Equals(aTag, kNameSpaceID_XUL);
923 template <typename First, typename... Args>
924 inline bool IsAnyOfXULElements(First aFirst, Args... aArgs) const {
925 return IsXULElement() && IsNodeInternal(aFirst, aArgs...);
928 inline bool IsMathMLElement() const {
929 return IsElement() && IsInNamespace(kNameSpaceID_MathML);
932 inline bool IsMathMLElement(const nsAtom* aTag) const {
933 return IsElement() && mNodeInfo->Equals(aTag, kNameSpaceID_MathML);
936 template <typename First, typename... Args>
937 inline bool IsAnyOfMathMLElements(First aFirst, Args... aArgs) const {
938 return IsMathMLElement() && IsNodeInternal(aFirst, aArgs...);
941 bool IsShadowRoot() const {
942 const bool isShadowRoot = IsInShadowTree() && !GetParentNode();
943 MOZ_ASSERT_IF(isShadowRoot, IsDocumentFragment());
944 return isShadowRoot;
947 bool IsHTMLHeadingElement() const {
948 return IsAnyOfHTMLElements(nsGkAtoms::h1, nsGkAtoms::h2, nsGkAtoms::h3,
949 nsGkAtoms::h4, nsGkAtoms::h5, nsGkAtoms::h6);
953 * Check whether the conditional processing attributes other than
954 * systemLanguage "return true" if they apply to and are specified
955 * on the given SVG element. Returns true if this element should be
956 * rendered, false if it should not.
958 virtual bool PassesConditionalProcessingTests() const { return true; }
961 * Insert a content node before another or at the end.
962 * This method handles calling BindToTree on the child appropriately.
964 * @param aKid the content to insert
965 * @param aBeforeThis an existing node. Use nullptr if you want to
966 * add aKid at the end.
967 * @param aNotify whether to notify the document (current document for
968 * nsIContent, and |this| for Document) that the insert has occurred
969 * @param aRv The error, if any.
970 * Throw NS_ERROR_DOM_HIERARCHY_REQUEST_ERR if one attempts to have
971 * more than one element node as a child of a document. Doing this
972 * will also assert -- you shouldn't be doing it! Check with
973 * Document::GetRootElement() first if you're not sure. Apart from
974 * this one constraint, this doesn't do any checking on whether aKid is
975 * a valid child of |this|.
976 * Throw NS_ERROR_OUT_OF_MEMORY in some cases (from BindToTree).
978 virtual void InsertChildBefore(nsIContent* aKid, nsIContent* aBeforeThis,
979 bool aNotify, mozilla::ErrorResult& aRv);
982 * Append a content node to the end of the child list. This method handles
983 * calling BindToTree on the child appropriately.
985 * @param aKid the content to append
986 * @param aNotify whether to notify the document (current document for
987 * nsIContent, and |this| for Document) that the append has occurred
988 * @param aRv The error, if any.
989 * Throw NS_ERROR_DOM_HIERARCHY_REQUEST_ERR if one attempts to have
990 * more than one element node as a child of a document. Doing this
991 * will also assert -- you shouldn't be doing it! Check with
992 * Document::GetRootElement() first if you're not sure. Apart from
993 * this one constraint, this doesn't do any checking on whether aKid is
994 * a valid child of |this|.
995 * Throw NS_ERROR_OUT_OF_MEMORY in some cases (from BindToTree).
997 void AppendChildTo(nsIContent* aKid, bool aNotify,
998 mozilla::ErrorResult& aRv) {
999 InsertChildBefore(aKid, nullptr, aNotify, aRv);
1002 template <BatchRemovalOrder aOrder = BatchRemovalOrder::FrontToBack>
1003 void RemoveAllChildren(bool aNotify) {
1004 if (!HasChildren()) {
1005 return;
1007 BatchRemovalState state{};
1008 do {
1009 nsIContent* nodeToRemove = aOrder == BatchRemovalOrder::FrontToBack
1010 ? GetFirstChild()
1011 : GetLastChild();
1012 RemoveChildNode(nodeToRemove, aNotify, &state);
1013 state.mIsFirst = false;
1014 } while (HasChildren());
1018 * Remove a child from this node. This method handles calling UnbindFromTree
1019 * on the child appropriately.
1021 * @param aKid the content to remove
1022 * @param aNotify whether to notify the document (current document for
1023 * nsIContent, and |this| for Document) that the remove has occurred
1024 * @param BatchRemovalState The current state of our batch removal.
1026 virtual void RemoveChildNode(nsIContent* aKid, bool aNotify,
1027 const BatchRemovalState* = nullptr);
1030 * Get a property associated with this node.
1032 * @param aPropertyName name of property to get.
1033 * @param aStatus out parameter for storing resulting status.
1034 * Set to NS_PROPTABLE_PROP_NOT_THERE if the property
1035 * is not set.
1036 * @return the property. Null if the property is not set
1037 * (though a null return value does not imply the
1038 * property was not set, i.e. it can be set to null).
1040 void* GetProperty(const nsAtom* aPropertyName,
1041 nsresult* aStatus = nullptr) const;
1044 * Set a property to be associated with this node. This will overwrite an
1045 * existing value if one exists. The existing value is destroyed using the
1046 * destructor function given when that value was set.
1048 * @param aPropertyName name of property to set.
1049 * @param aValue new value of property.
1050 * @param aDtor destructor function to be used when this property
1051 * is destroyed.
1052 * @param aTransfer if true the property will not be deleted when the
1053 * ownerDocument of the node changes, if false it
1054 * will be deleted.
1056 * @return NS_PROPTABLE_PROP_OVERWRITTEN (success value) if the property
1057 * was already set
1058 * @throws NS_ERROR_OUT_OF_MEMORY if that occurs
1060 nsresult SetProperty(nsAtom* aPropertyName, void* aValue,
1061 NSPropertyDtorFunc aDtor = nullptr,
1062 bool aTransfer = false);
1065 * A generic destructor for property values allocated with new.
1067 template <class T>
1068 static void DeleteProperty(void*, nsAtom*, void* aPropertyValue, void*) {
1069 delete static_cast<T*>(aPropertyValue);
1073 * Removes a property associated with this node. The value is destroyed using
1074 * the destruction function given when that value was set.
1076 * @param aPropertyName name of property to destroy.
1078 void RemoveProperty(const nsAtom* aPropertyName);
1081 * Take a property associated with this node. The value will not be destroyed
1082 * but rather returned. It is the caller's responsibility to destroy the value
1083 * after that point.
1085 * @param aPropertyName name of property to unset.
1086 * @param aStatus out parameter for storing resulting status.
1087 * Set to NS_PROPTABLE_PROP_NOT_THERE if the property
1088 * is not set.
1089 * @return the property. Null if the property is not set
1090 * (though a null return value does not imply the
1091 * property was not set, i.e. it can be set to null).
1093 void* TakeProperty(const nsAtom* aPropertyName, nsresult* aStatus = nullptr);
1095 bool HasProperties() const { return HasFlag(NODE_HAS_PROPERTIES); }
1098 * Return the principal of this node. This is guaranteed to never be a null
1099 * pointer.
1101 nsIPrincipal* NodePrincipal() const {
1102 return mNodeInfo->NodeInfoManager()->DocumentPrincipal();
1106 * Return the CSP of this node's document, if any.
1108 nsIContentSecurityPolicy* GetCsp() const;
1111 * Get the parent nsIContent for this node.
1112 * @return the parent, or null if no parent or the parent is not an nsIContent
1114 nsIContent* GetParent() const {
1115 return MOZ_LIKELY(GetBoolFlag(ParentIsContent)) ? mParent->AsContent()
1116 : nullptr;
1120 * Get the parent nsINode for this node. This can be either an nsIContent, a
1121 * Document or an Attr.
1122 * @return the parent node
1124 nsINode* GetParentNode() const { return mParent; }
1126 private:
1127 nsIContent* DoGetShadowHost() const;
1129 public:
1130 nsINode* GetParentOrShadowHostNode() const {
1131 if (MOZ_LIKELY(mParent)) {
1132 return mParent;
1134 // We could put this in nsIContentInlines.h or such to avoid this
1135 // reinterpret_cast, but it doesn't seem worth it.
1136 return IsInShadowTree() ? reinterpret_cast<nsINode*>(DoGetShadowHost())
1137 : nullptr;
1140 enum FlattenedParentType { eNormal, eForStyle, eForSelection };
1143 * Returns the node that is the parent of this node in the flattened
1144 * tree. This differs from the normal parent if the node is filtered
1145 * into an insertion point, or if the node is a direct child of a
1146 * shadow root.
1148 * @return the flattened tree parent
1150 inline nsINode* GetFlattenedTreeParentNode() const;
1152 nsINode* GetFlattenedTreeParentNodeNonInline() const;
1155 * Like GetFlattenedTreeParentNode, but returns the document for any native
1156 * anonymous content that was generated for ancestor frames of the document
1157 * element's primary frame, such as scrollbar elements created by the root
1158 * scroll frame.
1160 inline nsINode* GetFlattenedTreeParentNodeForStyle() const;
1163 * Similar to GetFlattenedTreeParentNode, it does two things differently
1164 * 1. For contents that are not in the flattened tree, use its
1165 * parent rather than nullptr.
1166 * 2. For contents that are slotted into a UA shadow tree, use its
1167 * parent rather than the slot element.
1169 inline nsIContent* GetFlattenedTreeParentNodeForSelection() const;
1171 inline mozilla::dom::Element* GetFlattenedTreeParentElement() const;
1172 inline mozilla::dom::Element* GetFlattenedTreeParentElementForStyle() const;
1175 * Get the parent nsINode for this node if it is an Element.
1177 * Defined inline in Element.h
1179 * @return the parent node
1181 inline mozilla::dom::Element* GetParentElement() const;
1184 * Get the parent Element of this node, traversing over a ShadowRoot
1185 * to its host if necessary.
1187 mozilla::dom::Element* GetParentElementCrossingShadowRoot() const;
1190 * Get closest element node for the node. Meaning that if the node is an
1191 * element node, returns itself. Otherwise, returns parent element or null.
1193 inline mozilla::dom::Element* GetAsElementOrParentElement() const;
1196 * Get inclusive ancestor element in the flattened tree.
1198 inline mozilla::dom::Element* GetInclusiveFlattenedTreeAncestorElement()
1199 const;
1202 * Get the root of the subtree this node belongs to. This never returns
1203 * null. It may return 'this' (e.g. for document nodes, and nodes that
1204 * are the roots of disconnected subtrees).
1206 nsINode* SubtreeRoot() const;
1209 * Get context object's shadow-including root if options's composed is true,
1210 * and context object's root otherwise.
1212 nsINode* GetRootNode(const mozilla::dom::GetRootNodeOptions& aOptions);
1214 virtual mozilla::EventListenerManager* GetExistingListenerManager()
1215 const override;
1216 virtual mozilla::EventListenerManager* GetOrCreateListenerManager() override;
1218 mozilla::Maybe<mozilla::dom::EventCallbackDebuggerNotificationType>
1219 GetDebuggerNotificationType() const override;
1221 bool ComputeDefaultWantsUntrusted(mozilla::ErrorResult& aRv) final;
1223 virtual bool IsApzAware() const override;
1225 virtual nsPIDOMWindowOuter* GetOwnerGlobalForBindingsInternal() override;
1226 virtual nsIGlobalObject* GetOwnerGlobal() const override;
1228 using mozilla::dom::EventTarget::DispatchEvent;
1229 // TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230)
1230 MOZ_CAN_RUN_SCRIPT_BOUNDARY bool DispatchEvent(
1231 mozilla::dom::Event& aEvent, mozilla::dom::CallerType aCallerType,
1232 mozilla::ErrorResult& aRv) override;
1234 MOZ_CAN_RUN_SCRIPT
1235 nsresult PostHandleEvent(mozilla::EventChainPostVisitor& aVisitor) override;
1238 * Adds a mutation observer to be notified when this node, or any of its
1239 * descendants, are modified. The node will hold a weak reference to the
1240 * observer, which means that it is the responsibility of the observer to
1241 * remove itself in case it dies before the node. If an observer is added
1242 * while observers are being notified, it may also be notified. In general,
1243 * adding observers while inside a notification is not a good idea. An
1244 * observer that is already observing the node must not be added without
1245 * being removed first.
1247 * For mutation observers that implement nsIAnimationObserver, use
1248 * AddAnimationObserver instead.
1250 void AddMutationObserver(nsIMutationObserver* aMutationObserver) {
1251 nsSlots* s = Slots();
1252 if (aMutationObserver) {
1253 NS_ASSERTION(!s->mMutationObservers.contains(aMutationObserver),
1254 "Observer already in the list");
1256 s->mMutationObservers.pushBack(aMutationObserver);
1260 void AddMutationObserver(nsMultiMutationObserver* aMultiMutationObserver);
1263 * Same as above, but only adds the observer if its not observing
1264 * the node already.
1266 * For mutation observers that implement nsIAnimationObserver, use
1267 * AddAnimationObserverUnlessExists instead.
1269 void AddMutationObserverUnlessExists(nsIMutationObserver* aMutationObserver) {
1270 nsSlots* s = Slots();
1271 if (aMutationObserver &&
1272 !s->mMutationObservers.contains(aMutationObserver)) {
1273 s->mMutationObservers.pushBack(aMutationObserver);
1277 void AddMutationObserverUnlessExists(
1278 nsMultiMutationObserver* aMultiMutationObserver);
1280 * Same as AddMutationObserver, but for nsIAnimationObservers. This
1281 * additionally records on the document that animation observers have
1282 * been registered, which is used to determine whether notifications
1283 * must be fired when animations are added, removed or changed.
1285 void AddAnimationObserver(nsIAnimationObserver* aAnimationObserver);
1288 * Same as above, but only adds the observer if its not observing
1289 * the node already.
1291 void AddAnimationObserverUnlessExists(
1292 nsIAnimationObserver* aAnimationObserver);
1295 * Removes a mutation observer.
1297 void RemoveMutationObserver(nsIMutationObserver* aMutationObserver) {
1298 nsSlots* s = GetExistingSlots();
1299 if (s) {
1300 s->mMutationObservers.remove(aMutationObserver);
1304 void RemoveMutationObserver(nsMultiMutationObserver* aMultiMutationObserver);
1306 mozilla::SafeDoublyLinkedList<nsIMutationObserver>* GetMutationObservers();
1309 * Helper methods to access ancestor node(s) of type T.
1310 * The implementations of the methods are in mozilla/dom/AncestorIterator.h.
1312 template <typename T>
1313 inline mozilla::dom::AncestorsOfTypeIterator<T> AncestorsOfType() const;
1315 template <typename T>
1316 inline mozilla::dom::InclusiveAncestorsOfTypeIterator<T>
1317 InclusiveAncestorsOfType() const;
1319 template <typename T>
1320 inline mozilla::dom::FlatTreeAncestorsOfTypeIterator<T>
1321 FlatTreeAncestorsOfType() const;
1323 template <typename T>
1324 inline mozilla::dom::InclusiveFlatTreeAncestorsOfTypeIterator<T>
1325 InclusiveFlatTreeAncestorsOfType() const;
1327 template <typename T>
1328 T* FirstAncestorOfType() const;
1330 private:
1332 * Walks aNode, its attributes and, if aDeep is true, its descendant nodes.
1333 * If aClone is true the nodes will be cloned. If aNewNodeInfoManager is
1334 * not null, it is used to create new nodeinfos for the nodes. Also reparents
1335 * the XPConnect wrappers for the nodes into aReparentScope if non-null.
1337 * @param aNode Node to adopt/clone.
1338 * @param aClone If true the node will be cloned and the cloned node will
1339 * be returned.
1340 * @param aDeep If true the function will be called recursively on
1341 * descendants of the node
1342 * @param aNewNodeInfoManager The nodeinfo manager to use to create new
1343 * nodeinfos for aNode and its attributes and
1344 * descendants. May be null if the nodeinfos
1345 * shouldn't be changed.
1346 * @param aReparentScope Scope into which wrappers should be reparented, or
1347 * null if no reparenting should be done.
1348 * @param aParent If aClone is true the cloned node will be appended to
1349 * aParent's children. May be null. If not null then aNode
1350 * must be an nsIContent.
1351 * @param aError The error, if any.
1353 * @return If aClone is true then the cloned node will be returned,
1354 * unless an error occurred. In error conditions, null
1355 * will be returned.
1357 static already_AddRefed<nsINode> CloneAndAdopt(
1358 nsINode* aNode, bool aClone, bool aDeep,
1359 nsNodeInfoManager* aNewNodeInfoManager,
1360 JS::Handle<JSObject*> aReparentScope, nsINode* aParent,
1361 mozilla::ErrorResult& aError);
1363 public:
1365 * Walks the node, its attributes and descendant nodes. If aNewNodeInfoManager
1366 * is not null, it is used to create new nodeinfos for the nodes. Also
1367 * reparents the XPConnect wrappers for the nodes into aReparentScope if
1368 * non-null.
1370 * @param aNewNodeInfoManager The nodeinfo manager to use to create new
1371 * nodeinfos for the node and its attributes and
1372 * descendants. May be null if the nodeinfos
1373 * shouldn't be changed.
1374 * @param aReparentScope New scope for the wrappers, or null if no reparenting
1375 * should be done.
1376 * @param aError The error, if any.
1378 void Adopt(nsNodeInfoManager* aNewNodeInfoManager,
1379 JS::Handle<JSObject*> aReparentScope,
1380 mozilla::ErrorResult& aError);
1383 * Clones the node, its attributes and, if aDeep is true, its descendant nodes
1384 * If aNewNodeInfoManager is not null, it is used to create new nodeinfos for
1385 * the clones.
1387 * @param aDeep If true the function will be called recursively on
1388 * descendants of the node
1389 * @param aNewNodeInfoManager The nodeinfo manager to use to create new
1390 * nodeinfos for the node and its attributes and
1391 * descendants. May be null if the nodeinfos
1392 * shouldn't be changed.
1393 * @param aError The error, if any.
1395 * @return The newly created node. Null in error conditions.
1397 already_AddRefed<nsINode> Clone(bool aDeep,
1398 nsNodeInfoManager* aNewNodeInfoManager,
1399 mozilla::ErrorResult& aError);
1402 * Clones this node. This needs to be overriden by all node classes. aNodeInfo
1403 * should be identical to this node's nodeInfo, except for the document which
1404 * may be different. When cloning an element, all attributes of the element
1405 * will be cloned. The children of the node will not be cloned.
1407 * @param aNodeInfo the nodeinfo to use for the clone
1408 * @param aResult the clone
1410 virtual nsresult Clone(mozilla::dom::NodeInfo*, nsINode** aResult) const = 0;
1412 // A callback that gets called when we are forcefully unbound from a node (due
1413 // to the node going away). You shouldn't take a strong ref to the node from
1414 // the callback.
1415 using UnbindCallback = void (*)(nsISupports*, nsINode*);
1416 // We should keep alive these objects.
1417 struct BoundObject {
1418 nsCOMPtr<nsISupports> mObject;
1419 UnbindCallback mDtor = nullptr;
1421 BoundObject(nsISupports* aObject, UnbindCallback aDtor)
1422 : mObject(aObject), mDtor(aDtor) {}
1424 bool operator==(nsISupports* aOther) const {
1425 return mObject.get() == aOther;
1429 // This class can be extended by subclasses that wish to store more
1430 // information in the slots.
1431 class nsSlots {
1432 public:
1433 nsSlots();
1435 // If needed we could remove the vtable pointer this dtor causes by
1436 // putting a DestroySlots function on nsINode
1437 virtual ~nsSlots();
1439 virtual void Traverse(nsCycleCollectionTraversalCallback&);
1440 virtual void Unlink(nsINode&);
1443 * A list of mutation observers
1445 mozilla::SafeDoublyLinkedList<nsIMutationObserver> mMutationObservers;
1448 * An object implementing NodeList for this content (childNodes)
1449 * @see NodeList
1450 * @see nsGenericHTMLElement::GetChildNodes
1452 RefPtr<nsAttrChildContentList> mChildNodes;
1455 * Weak reference to this node. This is cleared by the destructor of
1456 * nsNodeWeakReference.
1458 nsNodeWeakReference* MOZ_NON_OWNING_REF mWeakReference;
1460 /** A list of objects that we should keep alive. See Bind/UnbindObject. */
1461 nsTArray<BoundObject> mBoundObjects;
1464 * A set of ranges which are in the selection and which have this node as
1465 * their endpoints' closest common inclusive ancestor
1466 * (https://dom.spec.whatwg.org/#concept-tree-inclusive-ancestor). This is
1467 * a UniquePtr instead of just a LinkedList, because that prevents us from
1468 * pushing DOMSlots up to the next allocation bucket size, at the cost of
1469 * some complexity.
1471 mozilla::UniquePtr<mozilla::LinkedList<mozilla::dom::AbstractRange>>
1472 mClosestCommonInclusiveAncestorRanges;
1476 * Functions for managing flags and slots
1478 #ifdef DEBUG
1479 nsSlots* DebugGetSlots() { return Slots(); }
1480 #endif
1482 void SetFlags(FlagsType aFlagsToSet) {
1483 NS_ASSERTION(
1484 !(aFlagsToSet &
1485 (NODE_IS_NATIVE_ANONYMOUS_ROOT | NODE_IS_IN_NATIVE_ANONYMOUS_SUBTREE |
1486 NODE_DESCENDANTS_NEED_FRAMES | NODE_NEEDS_FRAME |
1487 NODE_HAS_BEEN_IN_UA_WIDGET)) ||
1488 IsContent(),
1489 "Flag only permitted on nsIContent nodes");
1490 nsWrapperCache::SetFlags(aFlagsToSet);
1493 void UnsetFlags(FlagsType aFlagsToUnset) {
1494 NS_ASSERTION(!(aFlagsToUnset & (NODE_HAS_BEEN_IN_UA_WIDGET |
1495 NODE_IS_NATIVE_ANONYMOUS_ROOT)),
1496 "Trying to unset write-only flags");
1497 nsWrapperCache::UnsetFlags(aFlagsToUnset);
1500 void SetEditableFlag(bool aEditable) {
1501 if (aEditable) {
1502 SetFlags(NODE_IS_EDITABLE);
1503 } else {
1504 UnsetFlags(NODE_IS_EDITABLE);
1508 inline bool IsEditable() const;
1511 * Check if this node is an editing host. For avoiding confusion, this always
1512 * returns false if the node is in the design mode document.
1514 inline bool IsEditingHost() const;
1517 * Check if this node is in design mode or not. When this returns true and:
1518 * - if this is a Document node, it's the design mode root.
1519 * - if this is a content node, it's connected, it's not in a shadow tree
1520 * (except shadow tree for UI widget and native anonymous subtree) and its
1521 * uncomposed document is in design mode.
1522 * Note that returning true does NOT mean the node or its children is
1523 * editable. E.g., when this node is in a shadow tree of a UA widget and its
1524 * host is in design mode.
1526 inline bool IsInDesignMode() const;
1529 * Returns true if |this| or any of its ancestors is native anonymous.
1531 bool IsInNativeAnonymousSubtree() const {
1532 return HasFlag(NODE_IS_IN_NATIVE_ANONYMOUS_SUBTREE);
1536 * If |this| or any ancestor is native anonymous, return the root of the
1537 * native anonymous subtree. Note that in case of nested native anonymous
1538 * content, this returns the innermost root, not the outermost.
1540 nsIContent* GetClosestNativeAnonymousSubtreeRoot() const {
1541 if (!IsInNativeAnonymousSubtree()) {
1542 MOZ_ASSERT(!HasBeenInUAWidget(), "UA widget implies anonymous");
1543 return nullptr;
1545 MOZ_ASSERT(IsContent(), "How did non-content end up in NAC?");
1546 if (HasBeenInUAWidget()) {
1547 // reinterpret_cast because in this header we don't know ShadowRoot is an
1548 // nsIContent. ShadowRoot constructor asserts this is correct.
1549 return reinterpret_cast<nsIContent*>(GetContainingShadow());
1551 for (const nsINode* node = this; node; node = node->GetParentNode()) {
1552 if (node->IsRootOfNativeAnonymousSubtree()) {
1553 return const_cast<nsINode*>(node)->AsContent();
1556 // FIXME(emilio): This should not happen, usually, but editor removes nodes
1557 // in native anonymous subtrees, and we don't clean nodes from the current
1558 // event content stack from ContentRemoved, so it can actually happen, see
1559 // bug 1510208.
1560 NS_WARNING("GetClosestNativeAnonymousSubtreeRoot on disconnected NAC!");
1561 return nullptr;
1565 * If |this| or any ancestor is native anonymous, return the parent of the
1566 * native anonymous subtree. Note that in case of nested native anonymous
1567 * content, this returns the parent or host of the innermost root, not the
1568 * outermost.
1570 nsIContent* GetClosestNativeAnonymousSubtreeRootParentOrHost() const {
1571 // We could put this in nsIContentInlines.h or such to avoid this
1572 // reinterpret_cast, but it doesn't seem worth it.
1573 const auto* root = reinterpret_cast<const nsINode*>(
1574 GetClosestNativeAnonymousSubtreeRoot());
1575 if (!root) {
1576 return nullptr;
1578 if (nsIContent* parent = root->GetParent()) {
1579 return parent;
1581 if (MOZ_UNLIKELY(root->IsInShadowTree())) {
1582 return root->DoGetShadowHost();
1584 return nullptr;
1588 * Gets the root of the node tree for this content if it is in a shadow tree.
1590 mozilla::dom::ShadowRoot* GetContainingShadow() const;
1592 * Gets the shadow host if this content is in a shadow tree. That is, the host
1593 * of |GetContainingShadow|, if its not null.
1595 * @return The shadow host, if this is in shadow tree, or null.
1597 mozilla::dom::Element* GetContainingShadowHost() const;
1599 bool IsInSVGUseShadowTree() const {
1600 return !!GetContainingSVGUseShadowHost();
1603 mozilla::dom::SVGUseElement* GetContainingSVGUseShadowHost() const {
1604 if (!IsInShadowTree()) {
1605 return nullptr;
1607 return DoGetContainingSVGUseShadowHost();
1610 // Whether this node has ever been part of a UA widget shadow tree.
1611 bool HasBeenInUAWidget() const { return HasFlag(NODE_HAS_BEEN_IN_UA_WIDGET); }
1613 // True for native anonymous content and for content in UA widgets.
1614 // Only nsIContent can fulfill this condition.
1615 bool ChromeOnlyAccess() const { return IsInNativeAnonymousSubtree(); }
1617 // Whether we're chrome-only for event targeting. UA widgets can use regular
1618 // shadow DOM retargeting for these.
1619 bool ChromeOnlyAccessForEvents() const {
1620 return ChromeOnlyAccess() && !HasBeenInUAWidget();
1623 const nsIContent* GetChromeOnlyAccessSubtreeRootParent() const {
1624 return GetClosestNativeAnonymousSubtreeRootParentOrHost();
1627 bool IsInShadowTree() const { return HasFlag(NODE_IS_IN_SHADOW_TREE); }
1630 * Get whether this node is C++-generated anonymous content
1631 * @see nsIAnonymousContentCreator
1632 * @return whether this content is anonymous
1634 bool IsRootOfNativeAnonymousSubtree() const {
1635 NS_ASSERTION(
1636 !HasFlag(NODE_IS_NATIVE_ANONYMOUS_ROOT) || IsInNativeAnonymousSubtree(),
1637 "Some flags seem to be missing!");
1638 return HasFlag(NODE_IS_NATIVE_ANONYMOUS_ROOT);
1641 // Whether this node is the root of a ChromeOnlyAccess DOM subtree.
1642 bool IsRootOfChromeAccessOnlySubtree() const {
1643 return IsRootOfNativeAnonymousSubtree();
1646 /** Whether this is the container of a ::before pseudo-element. */
1647 bool IsGeneratedContentContainerForBefore() const {
1648 return IsRootOfNativeAnonymousSubtree() &&
1649 mNodeInfo->NameAtom() == nsGkAtoms::mozgeneratedcontentbefore;
1652 /** Whether this is the container of an ::after pseudo-element. */
1653 bool IsGeneratedContentContainerForAfter() const {
1654 return IsRootOfNativeAnonymousSubtree() &&
1655 mNodeInfo->NameAtom() == nsGkAtoms::mozgeneratedcontentafter;
1658 /** Whether this is the container of a ::marker pseudo-element. */
1659 bool IsGeneratedContentContainerForMarker() const {
1660 return IsRootOfNativeAnonymousSubtree() &&
1661 mNodeInfo->NameAtom() == nsGkAtoms::mozgeneratedcontentmarker;
1665 * Returns true if |this| node is the closest common inclusive ancestor
1666 * (https://dom.spec.whatwg.org/#concept-tree-inclusive-ancestor) of the
1667 * start/end nodes of a Range in a Selection or a descendant of such a common
1668 * ancestor. This node is definitely not selected when |false| is returned,
1669 * but it may or may not be selected when |true| is returned.
1671 bool IsMaybeSelected() const {
1672 return IsDescendantOfClosestCommonInclusiveAncestorForRangeInSelection() ||
1673 IsClosestCommonInclusiveAncestorForRangeInSelection();
1677 * Return true if any part of (this, aStartOffset) .. (this, aEndOffset)
1678 * overlaps any nsRange in
1679 * GetClosestCommonInclusiveAncestorForRangeInSelection ranges (i.e.
1680 * where this is a descendant of a range's common inclusive ancestor node).
1681 * If a nsRange starts in (this, aEndOffset) or if it ends in
1682 * (this, aStartOffset) then it is non-overlapping and the result is false
1683 * for that nsRange. Collapsed ranges always counts as non-overlapping.
1685 * @param aStartOffset has to be less or equal to aEndOffset.
1686 * @param aCache A cache which contains all fully selected nodes for each
1687 * selection. If present, this provides a fast path to check if
1688 * a node is fully selected.
1690 bool IsSelected(uint32_t aStartOffset, uint32_t aEndOffset,
1691 mozilla::dom::SelectionNodeCache* aCache = nullptr) const;
1693 #ifdef DEBUG
1694 void AssertIsRootElementSlow(bool) const;
1695 #endif
1697 /** Returns whether we're the root element of our document. */
1698 bool IsRootElement() const {
1699 // This should be faster than pointer-chasing in the common cases.
1700 const bool isRoot = !GetParent() && IsInUncomposedDoc() && IsElement();
1701 #ifdef DEBUG
1702 AssertIsRootElementSlow(isRoot);
1703 #endif
1704 return isRoot;
1708 * Get the root element of the text editor associated with this node or the
1709 * root element of the text editor of the ancestor 'TextControlElement' if
1710 * this is in its native anonymous subtree. I.e., this returns anonymous
1711 * `<div>` element of a `TextEditor`. Note that this can be used only for
1712 * getting root content of `<input>` or `<textarea>`. I.e., this method
1713 * doesn't support HTML editors. Note that this may create a `TextEditor`
1714 * instance, and it means that the `TextEditor` may modify its native
1715 * anonymous subtree and may run selection listeners.
1717 MOZ_CAN_RUN_SCRIPT mozilla::dom::Element* GetAnonymousRootElementOfTextEditor(
1718 mozilla::TextEditor** aTextEditor = nullptr);
1721 * Get the nearest selection root, ie. the node that will be selected if the
1722 * user does "Select All" while the focus is in this node. Note that if this
1723 * node is not in an editor, the result comes from the nsFrameSelection that
1724 * is related to aPresShell, so the result might not be the ancestor of this
1725 * node. Be aware that if this node and the computed selection limiter are
1726 * not in same subtree, this returns the root content of the closeset subtree.
1728 MOZ_CAN_RUN_SCRIPT nsIContent* GetSelectionRootContent(
1729 mozilla::PresShell* aPresShell, bool aAllowCrossShadowBoundary = false);
1731 bool HasScheduledSelectionChangeEvent() {
1732 return HasFlag(NODE_HAS_SCHEDULED_SELECTION_CHANGE_EVENT);
1735 void SetHasScheduledSelectionChangeEvent() {
1736 SetFlags(NODE_HAS_SCHEDULED_SELECTION_CHANGE_EVENT);
1739 void ClearHasScheduledSelectionChangeEvent() {
1740 UnsetFlags(NODE_HAS_SCHEDULED_SELECTION_CHANGE_EVENT);
1743 nsINodeList* ChildNodes();
1745 nsIContent* GetFirstChild() const { return mFirstChild; }
1747 nsIContent* GetLastChild() const;
1750 * Implementation is in Document.h, because it needs to cast from
1751 * Document* to nsINode*.
1753 Document* GetOwnerDocument() const;
1755 // TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230)
1756 MOZ_CAN_RUN_SCRIPT_BOUNDARY void Normalize();
1759 * Get the base URI for any relative URIs within this piece of
1760 * content. Generally, this is the document's base URI, but certain
1761 * content carries a local base for backward compatibility.
1763 * @return the base URI. May return null.
1765 virtual nsIURI* GetBaseURI(bool aTryUseXHRDocBaseURI = false) const = 0;
1766 nsIURI* GetBaseURIObject() const;
1769 * Return true if the node may be apz aware. There are two cases. One is that
1770 * the node is apz aware (such as HTMLInputElement with number type). The
1771 * other is that the node has apz aware listeners. This is a non-virtual
1772 * function which calls IsNodeApzAwareInternal only when the MayBeApzAware is
1773 * set. We check the details in IsNodeApzAwareInternal which may be overriden
1774 * by child classes
1776 bool IsNodeApzAware() const {
1777 return NodeMayBeApzAware() ? IsNodeApzAwareInternal() : false;
1781 * Override this function and set the flag MayBeApzAware in case the node has
1782 * to let APZC be aware of it. It's used when the node may handle the apz
1783 * aware events and may do preventDefault to stop APZC to do default actions.
1785 * For example, instead of scrolling page by APZ, we handle mouse wheel event
1786 * in HTMLInputElement with number type as increasing / decreasing its value.
1788 virtual bool IsNodeApzAwareInternal() const;
1790 void GetTextContent(nsAString& aTextContent, mozilla::OOMReporter& aError) {
1791 GetTextContentInternal(aTextContent, aError);
1793 void SetTextContent(const nsAString& aTextContent,
1794 nsIPrincipal* aSubjectPrincipal,
1795 mozilla::ErrorResult& aError) {
1796 SetTextContentInternal(aTextContent, aSubjectPrincipal, aError);
1798 void SetTextContent(const nsAString& aTextContent,
1799 mozilla::ErrorResult& aError) {
1800 SetTextContentInternal(aTextContent, nullptr, aError);
1803 mozilla::dom::Element* QuerySelector(const nsACString& aSelector,
1804 mozilla::ErrorResult& aResult);
1805 already_AddRefed<nsINodeList> QuerySelectorAll(const nsACString& aSelector,
1806 mozilla::ErrorResult& aResult);
1808 protected:
1809 // Document and ShadowRoot override this with its own (faster) version.
1810 // This should really only be called for elements and document fragments.
1811 mozilla::dom::Element* GetElementById(const nsAString& aId);
1813 void AppendChildToChildList(nsIContent* aKid);
1814 void InsertChildToChildList(nsIContent* aKid, nsIContent* aNextSibling);
1815 void DisconnectChild(nsIContent* aKid);
1817 public:
1818 void LookupPrefix(const nsAString& aNamespace, nsAString& aResult);
1819 bool IsDefaultNamespace(const nsAString& aNamespaceURI) {
1820 nsAutoString defaultNamespace;
1821 LookupNamespaceURI(u""_ns, defaultNamespace);
1822 return aNamespaceURI.Equals(defaultNamespace);
1824 void LookupNamespaceURI(const nsAString& aNamespacePrefix,
1825 nsAString& aNamespaceURI);
1827 nsIContent* GetNextSibling() const { return mNextSibling; }
1828 nsIContent* GetPreviousSibling() const;
1831 * Return true if the node is being removed from the parent, it means that
1832 * the node still knows the container which it's disconnected from, but the
1833 * node has already been removed from the child node chain of the container.
1834 * I.e., Return true between a call of DisconnectChild of the parent and
1835 * a call of UnbindFromTree of the node.
1837 bool IsBeingRemoved() const {
1838 return mParent && !mNextSibling && !mPreviousOrLastSibling;
1842 * Get the next node in the pre-order tree traversal of the DOM. If
1843 * aRoot is non-null, then it must be an ancestor of |this|
1844 * (possibly equal to |this|) and only nodes that are descendants of
1845 * aRoot, not including aRoot itself, will be returned. Returns
1846 * null if there are no more nodes to traverse.
1848 nsIContent* GetNextNode(const nsINode* aRoot = nullptr) const {
1849 return GetNextNodeImpl(aRoot, false);
1853 * Get the next node in the pre-order tree traversal of the DOM but ignoring
1854 * the children of this node. If aRoot is non-null, then it must be an
1855 * ancestor of |this| (possibly equal to |this|) and only nodes that are
1856 * descendants of aRoot, not including aRoot itself, will be returned.
1857 * Returns null if there are no more nodes to traverse.
1859 nsIContent* GetNextNonChildNode(const nsINode* aRoot = nullptr) const {
1860 return GetNextNodeImpl(aRoot, true);
1864 * Returns true if 'this' is either document or element or
1865 * document fragment and aOther is a descendant in the same
1866 * anonymous tree.
1868 bool Contains(const nsINode* aOther) const;
1870 bool UnoptimizableCCNode() const;
1873 * Fire a DOMNodeRemoved mutation event for all children of this node
1874 * TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230)
1876 MOZ_CAN_RUN_SCRIPT_BOUNDARY void FireNodeRemovedForChildren();
1878 void QueueDevtoolsAnonymousEvent(bool aIsRemove);
1880 private:
1881 mozilla::dom::SVGUseElement* DoGetContainingSVGUseShadowHost() const;
1883 nsIContent* GetNextNodeImpl(const nsINode* aRoot,
1884 const bool aSkipChildren) const {
1885 #ifdef DEBUG
1886 if (aRoot) {
1887 // TODO: perhaps nsINode::IsInclusiveDescendantOf could be used instead.
1888 const nsINode* cur = this;
1889 for (; cur; cur = cur->GetParentNode())
1890 if (cur == aRoot) break;
1891 NS_ASSERTION(cur, "aRoot not an ancestor of |this|?");
1893 #endif
1894 if (!aSkipChildren) {
1895 nsIContent* kid = GetFirstChild();
1896 if (kid) {
1897 return kid;
1900 if (this == aRoot) {
1901 return nullptr;
1903 const nsINode* cur = this;
1904 while (1) {
1905 nsIContent* next = cur->GetNextSibling();
1906 if (next) {
1907 return next;
1909 nsINode* parent = cur->GetParentNode();
1910 if (parent == aRoot) {
1911 return nullptr;
1913 cur = parent;
1915 MOZ_ASSERT_UNREACHABLE("How did we get here?");
1918 public:
1920 * Get the previous nsIContent in the pre-order tree traversal of the DOM. If
1921 * aRoot is non-null, then it must be an ancestor of |this|
1922 * (possibly equal to |this|) and only nsIContents that are descendants of
1923 * aRoot, including aRoot itself, will be returned. Returns
1924 * null if there are no more nsIContents to traverse.
1926 nsIContent* GetPrevNode(const nsINode* aRoot = nullptr) const {
1927 #ifdef DEBUG
1928 if (aRoot) {
1929 // TODO: perhaps nsINode::IsInclusiveDescendantOf could be used instead.
1930 const nsINode* cur = this;
1931 for (; cur; cur = cur->GetParentNode())
1932 if (cur == aRoot) break;
1933 NS_ASSERTION(cur, "aRoot not an ancestor of |this|?");
1935 #endif
1937 if (this == aRoot) {
1938 return nullptr;
1940 nsIContent* cur = this->GetParent();
1941 nsIContent* iter = this->GetPreviousSibling();
1942 while (iter) {
1943 cur = iter;
1944 iter = reinterpret_cast<nsINode*>(iter)->GetLastChild();
1946 return cur;
1950 * Boolean flags
1952 private:
1953 enum BooleanFlag {
1954 // Set if we're being used from -moz-element or observed via a mask,
1955 // clipPath, filter or use element.
1956 NodeHasDirectRenderingObservers,
1957 // Set if our parent chain (including this node itself) terminates
1958 // in a document
1959 IsInDocument,
1960 // Set if we're part of the composed doc.
1961 // https://dom.spec.whatwg.org/#connected
1962 IsConnected,
1963 // Set if mParent is an nsIContent
1964 ParentIsContent,
1965 // Set if this node is an Element
1966 NodeIsElement,
1967 // Set if the element has a non-empty id attribute. This can in rare
1968 // cases lie for nsXMLElement, such as when the node has been moved between
1969 // documents with different id mappings.
1970 ElementHasID,
1971 // Set if the element might have a class.
1972 ElementMayHaveClass,
1973 // Set if the element might have inline style.
1974 ElementMayHaveStyle,
1975 // Set if the element has a name attribute set.
1976 ElementHasName,
1977 // Set if the element has a part attribute set.
1978 ElementHasPart,
1979 // Set if the element might have a contenteditable attribute set.
1980 ElementMayHaveContentEditableAttr,
1981 // Set if the element has a contenteditable attribute whose value makes the
1982 // element editable.
1983 ElementHasContentEditableAttrTrueOrPlainTextOnly,
1984 // Set if the node is the closest common inclusive ancestor of the start/end
1985 // nodes of a Range that is in a Selection.
1986 NodeIsClosestCommonInclusiveAncestorForRangeInSelection,
1987 // Set if the node is a descendant of a node with the above bit set.
1988 NodeIsDescendantOfClosestCommonInclusiveAncestorForRangeInSelection,
1989 // Set if CanSkipInCC check has been done for this subtree root.
1990 NodeIsCCMarkedRoot,
1991 // Maybe set if this node is in black subtree.
1992 NodeIsCCBlackTree,
1993 // Maybe set if the node is a root of a subtree
1994 // which needs to be kept in the purple buffer.
1995 NodeIsPurpleRoot,
1996 // Set if the element has some style states locked
1997 ElementHasLockedStyleStates,
1998 // Set if element has pointer locked
1999 ElementHasPointerLock,
2000 // Set if the node may have DOMMutationObserver attached to it.
2001 NodeMayHaveDOMMutationObserver,
2002 // Set if node is Content
2003 NodeIsContent,
2004 // Set if the node has animations or transitions
2005 ElementHasAnimations,
2006 // Set if node has a dir attribute with a valid value (ltr, rtl, or auto).
2007 // Note that we cannot compute this from the dir attribute event state
2008 // flags, because we can't use those to distinguish
2009 // <bdi dir="some-invalid-value"> and <bdi dir="auto">.
2010 NodeHasValidDirAttribute,
2011 // Set if a node in the node's parent chain has dir=auto and nothing
2012 // inbetween nor the node itself establishes its own direction.
2013 NodeAncestorHasDirAuto,
2014 // Set if the node or an ancestor is assigned to a dir=auto slot and
2015 // nothing between nor the node itself establishes its own direction.
2016 // Except for when the node assigned to the dir=auto slot establishes
2017 // its own direction, then the flag is still set.
2018 NodeAffectsDirAutoSlot,
2019 // Set if the node is handling a click.
2020 NodeHandlingClick,
2021 // Set if the element has a parser insertion mode other than "in body",
2022 // per the HTML5 "Parse state" section.
2023 ElementHasWeirdParserInsertionMode,
2024 // Parser sets this flag if it has notified about the node.
2025 ParserHasNotified,
2026 // Sets if the node is apz aware or we have apz aware listeners.
2027 MayBeApzAware,
2028 // Set if the element might have any kind of anonymous content children,
2029 // which would not be found through the element's children list.
2030 ElementMayHaveAnonymousChildren,
2031 // Set if element has CustomElementData.
2032 ElementHasCustomElementData,
2033 // Set if the element was created from prototype cache and
2034 // its l10n attributes haven't been changed.
2035 ElementCreatedFromPrototypeAndHasUnmodifiedL10n,
2036 // Guard value
2037 BooleanFlagCount
2040 void SetBoolFlag(BooleanFlag name, bool value) {
2041 static_assert(BooleanFlagCount <= 8 * sizeof(mBoolFlags),
2042 "Too many boolean flags");
2043 mBoolFlags = (mBoolFlags & ~(1 << name)) | (value << name);
2046 void SetBoolFlag(BooleanFlag name) {
2047 static_assert(BooleanFlagCount <= 8 * sizeof(mBoolFlags),
2048 "Too many boolean flags");
2049 mBoolFlags |= (1 << name);
2052 void ClearBoolFlag(BooleanFlag name) {
2053 static_assert(BooleanFlagCount <= 8 * sizeof(mBoolFlags),
2054 "Too many boolean flags");
2055 mBoolFlags &= ~(1 << name);
2058 bool GetBoolFlag(BooleanFlag name) const {
2059 static_assert(BooleanFlagCount <= 8 * sizeof(mBoolFlags),
2060 "Too many boolean flags");
2061 return mBoolFlags & (1 << name);
2064 public:
2065 bool HasDirectRenderingObservers() const {
2066 return GetBoolFlag(NodeHasDirectRenderingObservers);
2068 void SetHasDirectRenderingObservers(bool aValue) {
2069 SetBoolFlag(NodeHasDirectRenderingObservers, aValue);
2071 bool IsContent() const { return GetBoolFlag(NodeIsContent); }
2072 bool HasID() const { return GetBoolFlag(ElementHasID); }
2073 bool MayHaveClass() const { return GetBoolFlag(ElementMayHaveClass); }
2074 void SetMayHaveClass() { SetBoolFlag(ElementMayHaveClass); }
2075 bool MayHaveStyle() const { return GetBoolFlag(ElementMayHaveStyle); }
2076 bool HasName() const { return GetBoolFlag(ElementHasName); }
2077 bool HasPartAttribute() const { return GetBoolFlag(ElementHasPart); }
2078 bool MayHaveContentEditableAttr() const {
2079 return GetBoolFlag(ElementMayHaveContentEditableAttr);
2082 * HasContentEditableAttrTrueOrPlainTextOnly() should not be called between
2083 * nsGenericHTMLElement::BeforeSetAttr and nsGenericHTMLElement::AfterSetAttr
2084 * because this is set and cleared by nsGenericHTMLElement::AfterSetAttr.
2086 bool HasContentEditableAttrTrueOrPlainTextOnly() const {
2087 return GetBoolFlag(ElementHasContentEditableAttrTrueOrPlainTextOnly);
2090 * https://dom.spec.whatwg.org/#concept-tree-inclusive-ancestor
2092 bool IsClosestCommonInclusiveAncestorForRangeInSelection() const {
2093 return GetBoolFlag(NodeIsClosestCommonInclusiveAncestorForRangeInSelection);
2096 * https://dom.spec.whatwg.org/#concept-tree-inclusive-ancestor
2098 void SetClosestCommonInclusiveAncestorForRangeInSelection() {
2099 SetBoolFlag(NodeIsClosestCommonInclusiveAncestorForRangeInSelection);
2102 * https://dom.spec.whatwg.org/#concept-tree-inclusive-ancestor
2104 void ClearClosestCommonInclusiveAncestorForRangeInSelection() {
2105 ClearBoolFlag(NodeIsClosestCommonInclusiveAncestorForRangeInSelection);
2108 * https://dom.spec.whatwg.org/#concept-tree-inclusive-ancestor
2110 bool IsDescendantOfClosestCommonInclusiveAncestorForRangeInSelection() const {
2111 return GetBoolFlag(
2112 NodeIsDescendantOfClosestCommonInclusiveAncestorForRangeInSelection);
2115 * https://dom.spec.whatwg.org/#concept-tree-inclusive-ancestor
2117 void SetDescendantOfClosestCommonInclusiveAncestorForRangeInSelection() {
2118 SetBoolFlag(
2119 NodeIsDescendantOfClosestCommonInclusiveAncestorForRangeInSelection);
2122 * https://dom.spec.whatwg.org/#concept-tree-inclusive-ancestor
2124 void ClearDescendantOfClosestCommonInclusiveAncestorForRangeInSelection() {
2125 ClearBoolFlag(
2126 NodeIsDescendantOfClosestCommonInclusiveAncestorForRangeInSelection);
2129 void SetCCMarkedRoot(bool aValue) { SetBoolFlag(NodeIsCCMarkedRoot, aValue); }
2130 bool CCMarkedRoot() const { return GetBoolFlag(NodeIsCCMarkedRoot); }
2131 void SetInCCBlackTree(bool aValue) { SetBoolFlag(NodeIsCCBlackTree, aValue); }
2132 bool InCCBlackTree() const { return GetBoolFlag(NodeIsCCBlackTree); }
2133 void SetIsPurpleRoot(bool aValue) { SetBoolFlag(NodeIsPurpleRoot, aValue); }
2134 bool IsPurpleRoot() const { return GetBoolFlag(NodeIsPurpleRoot); }
2135 bool MayHaveDOMMutationObserver() {
2136 return GetBoolFlag(NodeMayHaveDOMMutationObserver);
2138 void SetMayHaveDOMMutationObserver() {
2139 SetBoolFlag(NodeMayHaveDOMMutationObserver, true);
2141 bool HasListenerManager() { return HasFlag(NODE_HAS_LISTENERMANAGER); }
2142 bool HasPointerLock() const { return GetBoolFlag(ElementHasPointerLock); }
2143 void SetPointerLock() { SetBoolFlag(ElementHasPointerLock); }
2144 void ClearPointerLock() { ClearBoolFlag(ElementHasPointerLock); }
2145 bool MayHaveAnimations() const { return GetBoolFlag(ElementHasAnimations); }
2146 void SetMayHaveAnimations() { SetBoolFlag(ElementHasAnimations); }
2147 void ClearMayHaveAnimations() { ClearBoolFlag(ElementHasAnimations); }
2148 void SetHasValidDir() { SetBoolFlag(NodeHasValidDirAttribute); }
2149 void ClearHasValidDir() { ClearBoolFlag(NodeHasValidDirAttribute); }
2150 bool HasValidDir() const { return GetBoolFlag(NodeHasValidDirAttribute); }
2151 void SetAncestorHasDirAuto() { SetBoolFlag(NodeAncestorHasDirAuto); }
2152 void ClearAncestorHasDirAuto() { ClearBoolFlag(NodeAncestorHasDirAuto); }
2153 bool AncestorHasDirAuto() const {
2154 return GetBoolFlag(NodeAncestorHasDirAuto);
2156 void SetAffectsDirAutoSlot() { SetBoolFlag(NodeAffectsDirAutoSlot); }
2157 void ClearAffectsDirAutoSlot() { ClearBoolFlag(NodeAffectsDirAutoSlot); }
2159 // Set if the node or an ancestor is assigned to a dir=auto slot.
2160 bool AffectsDirAutoSlot() const {
2161 return GetBoolFlag(NodeAffectsDirAutoSlot);
2164 // Implemented in nsIContentInlines.h.
2165 inline bool NodeOrAncestorHasDirAuto() const;
2167 void SetParserHasNotified() { SetBoolFlag(ParserHasNotified); };
2168 bool HasParserNotified() { return GetBoolFlag(ParserHasNotified); }
2170 void SetMayBeApzAware() { SetBoolFlag(MayBeApzAware); }
2171 bool NodeMayBeApzAware() const { return GetBoolFlag(MayBeApzAware); }
2173 void SetMayHaveAnonymousChildren() {
2174 SetBoolFlag(ElementMayHaveAnonymousChildren);
2176 bool MayHaveAnonymousChildren() const {
2177 return GetBoolFlag(ElementMayHaveAnonymousChildren);
2180 void SetHasCustomElementData() { SetBoolFlag(ElementHasCustomElementData); }
2181 bool HasCustomElementData() const {
2182 return GetBoolFlag(ElementHasCustomElementData);
2185 void SetElementCreatedFromPrototypeAndHasUnmodifiedL10n() {
2186 SetBoolFlag(ElementCreatedFromPrototypeAndHasUnmodifiedL10n);
2188 bool HasElementCreatedFromPrototypeAndHasUnmodifiedL10n() {
2189 return GetBoolFlag(ElementCreatedFromPrototypeAndHasUnmodifiedL10n);
2191 void ClearElementCreatedFromPrototypeAndHasUnmodifiedL10n() {
2192 ClearBoolFlag(ElementCreatedFromPrototypeAndHasUnmodifiedL10n);
2195 mozilla::dom::ShadowRoot* GetShadowRoot() const;
2197 // Return the shadow root of the node if it is a shadow host and
2198 // it meets the requirements for being a shadow host of a selection.
2199 // For example, <details>, <video> and <use> elements are not valid
2200 // shadow host for selection.
2201 mozilla::dom::ShadowRoot* GetShadowRootForSelection() const;
2203 protected:
2204 void SetParentIsContent(bool aValue) { SetBoolFlag(ParentIsContent, aValue); }
2205 void SetIsInDocument() { SetBoolFlag(IsInDocument); }
2206 void ClearInDocument() { ClearBoolFlag(IsInDocument); }
2207 void SetIsConnected(bool aConnected) { SetBoolFlag(IsConnected, aConnected); }
2208 void SetNodeIsContent() { SetBoolFlag(NodeIsContent); }
2209 void SetIsElement() { SetBoolFlag(NodeIsElement); }
2210 void SetHasID() { SetBoolFlag(ElementHasID); }
2211 void ClearHasID() { ClearBoolFlag(ElementHasID); }
2212 void SetMayHaveStyle() { SetBoolFlag(ElementMayHaveStyle); }
2213 void SetHasName() { SetBoolFlag(ElementHasName); }
2214 void ClearHasName() { ClearBoolFlag(ElementHasName); }
2215 void SetHasPartAttribute(bool aPart) { SetBoolFlag(ElementHasPart, aPart); }
2216 void SetMayHaveContentEditableAttr() {
2217 SetBoolFlag(ElementMayHaveContentEditableAttr);
2219 void ClearMayHaveContentEditableAttr() {
2220 ClearBoolFlag(ElementMayHaveContentEditableAttr);
2222 void SetHasContentEditableAttrTrueOrPlainTextOnly() {
2223 SetBoolFlag(ElementHasContentEditableAttrTrueOrPlainTextOnly);
2225 void ClearHasContentEditableAttrTrueOrPlainTextOnly() {
2226 ClearBoolFlag(ElementHasContentEditableAttrTrueOrPlainTextOnly);
2228 void SetHasLockedStyleStates() { SetBoolFlag(ElementHasLockedStyleStates); }
2229 void ClearHasLockedStyleStates() {
2230 ClearBoolFlag(ElementHasLockedStyleStates);
2232 bool HasLockedStyleStates() const {
2233 return GetBoolFlag(ElementHasLockedStyleStates);
2235 void SetHasWeirdParserInsertionMode() {
2236 SetBoolFlag(ElementHasWeirdParserInsertionMode);
2238 bool HasWeirdParserInsertionMode() const {
2239 return GetBoolFlag(ElementHasWeirdParserInsertionMode);
2241 bool HandlingClick() const { return GetBoolFlag(NodeHandlingClick); }
2242 void SetHandlingClick() { SetBoolFlag(NodeHandlingClick); }
2243 void ClearHandlingClick() { ClearBoolFlag(NodeHandlingClick); }
2245 void SetSubtreeRootPointer(nsINode* aSubtreeRoot) {
2246 NS_ASSERTION(aSubtreeRoot, "aSubtreeRoot can never be null!");
2247 NS_ASSERTION(!(IsContent() && IsInUncomposedDoc()) && !IsInShadowTree(),
2248 "Shouldn't be here!");
2249 mSubtreeRoot = aSubtreeRoot;
2252 void ClearSubtreeRootPointer() { mSubtreeRoot = nullptr; }
2254 public:
2255 // Makes nsINode object keep aObject alive. If a callback is provided, it's
2256 // called before deleting the node.
2257 void BindObject(nsISupports* aObject, UnbindCallback = nullptr);
2258 // After calling UnbindObject nsINode, object doesn't keep aObject alive
2259 // anymore.
2260 void UnbindObject(nsISupports* aObject);
2262 void GenerateXPath(nsAString& aResult);
2264 already_AddRefed<mozilla::dom::AccessibleNode> GetAccessibleNode();
2267 * Returns the length of this node, as specified at
2268 * <http://dvcs.w3.org/hg/domcore/raw-file/tip/Overview.html#concept-node-length>
2270 uint32_t Length() const;
2272 void GetNodeName(mozilla::dom::DOMString& aNodeName) {
2273 const nsString& nodeName = NodeName();
2274 aNodeName.SetKnownLiveString(nodeName);
2276 [[nodiscard]] nsresult GetBaseURI(nsAString& aBaseURI) const;
2277 // Return the base URI for the document.
2278 // The returned value may differ if the document is loaded via XHR, and
2279 // when accessed from chrome privileged script and
2280 // from content privileged script for compatibility.
2281 void GetBaseURIFromJS(nsAString& aBaseURI, CallerType aCallerType,
2282 ErrorResult& aRv) const;
2283 bool HasChildNodes() const { return HasChildren(); }
2285 // See nsContentUtils::PositionIsBefore for aThisIndex and aOtherIndex usage.
2286 uint16_t CompareDocumentPosition(
2287 nsINode& aOther, mozilla::Maybe<uint32_t>* aThisIndex = nullptr,
2288 mozilla::Maybe<uint32_t>* aOtherIndex = nullptr) const;
2289 void GetNodeValue(nsAString& aNodeValue) { GetNodeValueInternal(aNodeValue); }
2290 void SetNodeValue(const nsAString& aNodeValue, mozilla::ErrorResult& aError) {
2291 SetNodeValueInternal(aNodeValue, aError);
2293 virtual void GetNodeValueInternal(nsAString& aNodeValue);
2294 virtual void SetNodeValueInternal(const nsAString& aNodeValue,
2295 mozilla::ErrorResult& aError) {
2296 // The DOM spec says that when nodeValue is defined to be null "setting it
2297 // has no effect", so we don't throw an exception.
2299 void EnsurePreInsertionValidity(nsINode& aNewChild, nsINode* aRefChild,
2300 mozilla::ErrorResult& aError);
2301 nsINode* InsertBefore(nsINode& aNode, nsINode* aChild,
2302 mozilla::ErrorResult& aError) {
2303 return ReplaceOrInsertBefore(false, &aNode, aChild, aError);
2307 * See <https://dom.spec.whatwg.org/#dom-node-appendchild>.
2309 nsINode* AppendChild(nsINode& aNode, mozilla::ErrorResult& aError) {
2310 return InsertBefore(aNode, nullptr, aError);
2313 nsINode* ReplaceChild(nsINode& aNode, nsINode& aChild,
2314 mozilla::ErrorResult& aError) {
2315 return ReplaceOrInsertBefore(true, &aNode, &aChild, aError);
2317 // TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230)
2318 MOZ_CAN_RUN_SCRIPT_BOUNDARY nsINode* RemoveChild(
2319 nsINode& aChild, mozilla::ErrorResult& aError);
2320 already_AddRefed<nsINode> CloneNode(bool aDeep, mozilla::ErrorResult& aError);
2321 bool IsSameNode(nsINode* aNode);
2322 bool IsEqualNode(nsINode* aNode);
2323 void GetNamespaceURI(nsAString& aNamespaceURI) const {
2324 mNodeInfo->GetNamespaceURI(aNamespaceURI);
2326 #ifdef MOZILLA_INTERNAL_API
2327 void GetPrefix(nsAString& aPrefix) { mNodeInfo->GetPrefix(aPrefix); }
2328 #endif
2329 void GetLocalName(mozilla::dom::DOMString& aLocalName) const {
2330 const nsString& localName = LocalName();
2331 aLocalName.SetKnownLiveString(localName);
2334 nsDOMAttributeMap* GetAttributes();
2336 // Helper method to remove this node from its parent. This is not exposed
2337 // through WebIDL.
2338 // Only call this if the node has a parent node.
2339 nsresult RemoveFromParent() {
2340 nsINode* parent = GetParentNode();
2341 mozilla::ErrorResult rv;
2342 parent->RemoveChild(*this, rv);
2343 return rv.StealNSResult();
2346 // ChildNode methods
2347 inline mozilla::dom::Element* GetPreviousElementSibling() const;
2348 inline mozilla::dom::Element* GetNextElementSibling() const;
2350 MOZ_CAN_RUN_SCRIPT void Before(const Sequence<OwningNodeOrString>& aNodes,
2351 ErrorResult& aRv);
2352 MOZ_CAN_RUN_SCRIPT void After(const Sequence<OwningNodeOrString>& aNodes,
2353 ErrorResult& aRv);
2354 MOZ_CAN_RUN_SCRIPT void ReplaceWith(
2355 const Sequence<OwningNodeOrString>& aNodes, ErrorResult& aRv);
2357 * Remove this node from its parent, if any.
2359 void Remove();
2361 // ParentNode methods
2362 mozilla::dom::Element* GetFirstElementChild() const;
2363 mozilla::dom::Element* GetLastElementChild() const;
2365 already_AddRefed<nsIHTMLCollection> GetElementsByAttribute(
2366 const nsAString& aAttribute, const nsAString& aValue);
2367 already_AddRefed<nsIHTMLCollection> GetElementsByAttributeNS(
2368 const nsAString& aNamespaceURI, const nsAString& aAttribute,
2369 const nsAString& aValue, ErrorResult& aRv);
2371 MOZ_CAN_RUN_SCRIPT void Prepend(const Sequence<OwningNodeOrString>& aNodes,
2372 ErrorResult& aRv);
2373 MOZ_CAN_RUN_SCRIPT void Append(const Sequence<OwningNodeOrString>& aNodes,
2374 ErrorResult& aRv);
2375 MOZ_CAN_RUN_SCRIPT void ReplaceChildren(
2376 const Sequence<OwningNodeOrString>& aNodes, ErrorResult& aRv);
2377 MOZ_CAN_RUN_SCRIPT void ReplaceChildren(nsINode* aNode, ErrorResult& aRv);
2379 void GetBoxQuads(const BoxQuadOptions& aOptions,
2380 nsTArray<RefPtr<DOMQuad>>& aResult, CallerType aCallerType,
2381 ErrorResult& aRv);
2383 void GetBoxQuadsFromWindowOrigin(const BoxQuadOptions& aOptions,
2384 nsTArray<RefPtr<DOMQuad>>& aResult,
2385 ErrorResult& aRv);
2387 already_AddRefed<DOMQuad> ConvertQuadFromNode(
2388 DOMQuad& aQuad, const TextOrElementOrDocument& aFrom,
2389 const ConvertCoordinateOptions& aOptions, CallerType aCallerType,
2390 ErrorResult& aRv);
2391 already_AddRefed<DOMQuad> ConvertRectFromNode(
2392 DOMRectReadOnly& aRect, const TextOrElementOrDocument& aFrom,
2393 const ConvertCoordinateOptions& aOptions, CallerType aCallerType,
2394 ErrorResult& aRv);
2395 already_AddRefed<DOMPoint> ConvertPointFromNode(
2396 const DOMPointInit& aPoint, const TextOrElementOrDocument& aFrom,
2397 const ConvertCoordinateOptions& aOptions, CallerType aCallerType,
2398 ErrorResult& aRv);
2401 * See nsSlots::mClosestCommonInclusiveAncestorRanges.
2403 const mozilla::LinkedList<mozilla::dom::AbstractRange>*
2404 GetExistingClosestCommonInclusiveAncestorRanges() const {
2405 if (!HasSlots()) {
2406 return nullptr;
2408 return GetExistingSlots()->mClosestCommonInclusiveAncestorRanges.get();
2412 * See nsSlots::mClosestCommonInclusiveAncestorRanges.
2414 mozilla::LinkedList<mozilla::dom::AbstractRange>*
2415 GetExistingClosestCommonInclusiveAncestorRanges() {
2416 if (!HasSlots()) {
2417 return nullptr;
2419 return GetExistingSlots()->mClosestCommonInclusiveAncestorRanges.get();
2423 * See nsSlots::mClosestCommonInclusiveAncestorRanges.
2425 mozilla::UniquePtr<mozilla::LinkedList<mozilla::dom::AbstractRange>>&
2426 GetClosestCommonInclusiveAncestorRangesPtr() {
2427 return Slots()->mClosestCommonInclusiveAncestorRanges;
2430 nsIWeakReference* GetExistingWeakReference() {
2431 return HasSlots() ? GetExistingSlots()->mWeakReference : nullptr;
2434 protected:
2435 // Override this function to create a custom slots class.
2436 // Must not return null.
2437 virtual nsINode::nsSlots* CreateSlots();
2439 bool HasSlots() const { return mSlots != nullptr; }
2441 nsSlots* GetExistingSlots() const { return mSlots; }
2443 nsSlots* Slots() {
2444 if (!HasSlots()) {
2445 mSlots = CreateSlots();
2446 MOZ_ASSERT(mSlots);
2448 return GetExistingSlots();
2452 * Invalidate cached child array inside mChildNodes
2453 * of type nsParentNodeChildContentList.
2455 void InvalidateChildNodes();
2457 virtual void GetTextContentInternal(nsAString& aTextContent,
2458 mozilla::OOMReporter& aError);
2459 virtual void SetTextContentInternal(const nsAString& aTextContent,
2460 nsIPrincipal* aSubjectPrincipal,
2461 mozilla::ErrorResult& aError) {}
2463 void EnsurePreInsertionValidity1(mozilla::ErrorResult& aError);
2464 void EnsurePreInsertionValidity2(bool aReplace, nsINode& aNewChild,
2465 nsINode* aRefChild,
2466 mozilla::ErrorResult& aError);
2467 // TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230)
2468 MOZ_CAN_RUN_SCRIPT_BOUNDARY nsINode* ReplaceOrInsertBefore(
2469 bool aReplace, nsINode* aNewChild, nsINode* aRefChild,
2470 mozilla::ErrorResult& aError);
2473 * Returns the Element that should be used for resolving namespaces
2474 * on this node (ie the ownerElement for attributes, the documentElement for
2475 * documents, the node itself for elements and for other nodes the parentNode
2476 * if it is an element).
2478 virtual mozilla::dom::Element* GetNameSpaceElement() = 0;
2481 * Parse the given selector string into a servo SelectorList.
2483 * Never returns null if aRv is not failing.
2485 * Note that the selector list returned here is owned by the owner doc's
2486 * selector cache.
2488 const mozilla::StyleSelectorList* ParseSelectorList(
2489 const nsACString& aSelectorString, mozilla::ErrorResult&);
2491 public:
2492 /* Event stuff that documents and elements share.
2494 Note that we include DOCUMENT_ONLY_EVENT events here so that we
2495 can forward all the document stuff to this implementation.
2497 #define EVENT(name_, id_, type_, struct_) \
2498 mozilla::dom::EventHandlerNonNull* GetOn##name_() { \
2499 return GetEventHandler(nsGkAtoms::on##name_); \
2501 void SetOn##name_(mozilla::dom::EventHandlerNonNull* handler) { \
2502 SetEventHandler(nsGkAtoms::on##name_, handler); \
2504 #define TOUCH_EVENT EVENT
2505 #define DOCUMENT_ONLY_EVENT EVENT
2506 #include "mozilla/EventNameList.h"
2507 #undef DOCUMENT_ONLY_EVENT
2508 #undef TOUCH_EVENT
2509 #undef EVENT
2511 NodeSelectorFlags GetSelectorFlags() const {
2512 return static_cast<NodeSelectorFlags>(mSelectorFlags.Get());
2515 protected:
2516 static bool Traverse(nsINode* tmp, nsCycleCollectionTraversalCallback& cb);
2517 static void Unlink(nsINode* tmp);
2519 RefPtr<mozilla::dom::NodeInfo> mNodeInfo;
2521 // mParent is an owning ref most of the time, except for the case of document
2522 // nodes, so it cannot be represented by nsCOMPtr, so mark is as
2523 // MOZ_OWNING_REF.
2524 nsINode* MOZ_OWNING_REF mParent;
2526 private:
2527 #ifndef BOOL_FLAGS_ON_WRAPPER_CACHE
2528 // Boolean flags.
2529 uint32_t mBoolFlags;
2530 #endif
2532 mozilla::RustCell<uint32_t> mSelectorFlags{0};
2534 uint32_t mChildCount;
2536 protected:
2537 // mNextSibling and mFirstChild are strong references while
2538 // mPreviousOrLastSibling is a weak ref. |mFirstChild->mPreviousOrLastSibling|
2539 // points to the last child node.
2540 nsCOMPtr<nsIContent> mFirstChild;
2541 nsCOMPtr<nsIContent> mNextSibling;
2542 nsIContent* MOZ_NON_OWNING_REF mPreviousOrLastSibling;
2544 union {
2545 // Pointer to our primary frame. Might be null.
2546 nsIFrame* mPrimaryFrame;
2548 // Pointer to the root of our subtree. Might be null.
2549 // This reference is non-owning and safe, since it either points to the
2550 // object itself, or is reset by ClearSubtreeRootPointer.
2551 nsINode* MOZ_NON_OWNING_REF mSubtreeRoot;
2554 // Storage for more members that are usually not needed; allocated lazily.
2555 nsSlots* mSlots;
2558 NON_VIRTUAL_ADDREF_RELEASE(nsINode)
2560 inline nsINode* mozilla::dom::EventTarget::GetAsNode() {
2561 return IsNode() ? AsNode() : nullptr;
2564 inline const nsINode* mozilla::dom::EventTarget::GetAsNode() const {
2565 return const_cast<mozilla::dom::EventTarget*>(this)->GetAsNode();
2568 inline nsINode* mozilla::dom::EventTarget::AsNode() {
2569 MOZ_DIAGNOSTIC_ASSERT(IsNode());
2570 return static_cast<nsINode*>(this);
2573 inline const nsINode* mozilla::dom::EventTarget::AsNode() const {
2574 MOZ_DIAGNOSTIC_ASSERT(IsNode());
2575 return static_cast<const nsINode*>(this);
2578 // Useful inline function for getting a node given an nsIContent and a Document.
2579 // Returns the first argument cast to nsINode if it is non-null, otherwise
2580 // returns the second (which may be null). We use type variables instead of
2581 // nsIContent* and Document* because the actual types must be
2582 // known for the cast to work.
2583 template <class C, class D>
2584 inline nsINode* NODE_FROM(C& aContent, D& aDocument) {
2585 if (aContent) return static_cast<nsINode*>(aContent);
2586 return static_cast<nsINode*>(aDocument);
2589 NS_DEFINE_STATIC_IID_ACCESSOR(nsINode, NS_INODE_IID)
2591 inline nsISupports* ToSupports(nsINode* aPointer) { return aPointer; }
2593 // Some checks are faster to do on nsIContent or Element than on
2594 // nsINode, so spit out FromNode versions taking those types too.
2595 #define NS_IMPL_FROMNODE_GENERIC(_class, _check, _const) \
2596 template <typename T> \
2597 static auto FromNode(_const T& aNode) \
2598 -> decltype(static_cast<_const _class*>(&aNode)) { \
2599 return aNode._check ? static_cast<_const _class*>(&aNode) : nullptr; \
2601 template <typename T> \
2602 static _const _class* FromNode(_const T* aNode) { \
2603 return FromNode(*aNode); \
2605 template <typename T> \
2606 static _const _class* FromNodeOrNull(_const T* aNode) { \
2607 return aNode ? FromNode(*aNode) : nullptr; \
2609 template <typename T> \
2610 static auto FromEventTarget(_const T& aEventTarget) \
2611 -> decltype(static_cast<_const _class*>(&aEventTarget)) { \
2612 return aEventTarget.IsNode() && aEventTarget.AsNode()->_check \
2613 ? static_cast<_const _class*>(&aEventTarget) \
2614 : nullptr; \
2616 template <typename T> \
2617 static _const _class* FromEventTarget(_const T* aEventTarget) { \
2618 return FromEventTarget(*aEventTarget); \
2620 template <typename T> \
2621 static _const _class* FromEventTargetOrNull(_const T* aEventTarget) { \
2622 return aEventTarget ? FromEventTarget(*aEventTarget) : nullptr; \
2625 #define NS_IMPL_FROMNODE_HELPER(_class, _check) \
2626 NS_IMPL_FROMNODE_GENERIC(_class, _check, ) \
2627 NS_IMPL_FROMNODE_GENERIC(_class, _check, const) \
2629 template <typename T> \
2630 static _class* FromNode(T&& aNode) { \
2631 /* We need the double-cast in case aNode is a smartptr. Those */ \
2632 /* can cast to superclasses of the type they're templated on, */ \
2633 /* but not directly to subclasses. */ \
2634 return aNode->_check ? static_cast<_class*>(static_cast<nsINode*>(aNode)) \
2635 : nullptr; \
2637 template <typename T> \
2638 static _class* FromNodeOrNull(T&& aNode) { \
2639 return aNode ? FromNode(aNode) : nullptr; \
2641 template <typename T> \
2642 static _class* FromEventTarget(T&& aEventTarget) { \
2643 /* We need the double-cast in case aEventTarget is a smartptr. Those */ \
2644 /* can cast to superclasses of the type they're templated on, */ \
2645 /* but not directly to subclasses. */ \
2646 return aEventTarget->IsNode() && aEventTarget->AsNode()->_check \
2647 ? static_cast<_class*>(static_cast<EventTarget*>(aEventTarget)) \
2648 : nullptr; \
2650 template <typename T> \
2651 static _class* FromEventTargetOrNull(T&& aEventTarget) { \
2652 return aEventTarget ? FromEventTarget(aEventTarget) : nullptr; \
2655 #define NS_IMPL_FROMNODE(_class, _nsid) \
2656 NS_IMPL_FROMNODE_HELPER(_class, IsInNamespace(_nsid))
2658 #define NS_IMPL_FROMNODE_WITH_TAG(_class, _nsid, _tag) \
2659 NS_IMPL_FROMNODE_HELPER(_class, NodeInfo()->Equals(nsGkAtoms::_tag, _nsid))
2661 #define NS_IMPL_FROMNODE_HTML_WITH_TAG(_class, _tag) \
2662 NS_IMPL_FROMNODE_WITH_TAG(_class, kNameSpaceID_XHTML, _tag)
2664 #endif /* nsINode_h___ */