Backed out changeset 2450366cf7ca (bug 1891629) for causing win msix mochitest failures
[gecko.git] / dom / base / nsINode.h
blobd2a2fd008d15b5aa4534df1d7298108980bff41d
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 nsIHTMLCollection;
49 class nsMultiMutationObserver;
50 class nsINode;
51 class nsINodeList;
52 class nsIPrincipal;
53 class nsIURI;
54 class nsNodeSupportsWeakRefTearoff;
55 class nsDOMMutationObserver;
56 class nsRange;
57 class nsWindowSizes;
59 namespace mozilla {
60 class EventListenerManager;
61 struct StyleSelectorList;
62 template <typename T>
63 class Maybe;
64 class PresShell;
65 class TextEditor;
66 namespace dom {
67 /**
68 * @return true if aChar is what the WHATWG defines as a 'ascii whitespace'.
69 * https://infra.spec.whatwg.org/#ascii-whitespace
71 inline bool IsSpaceCharacter(char16_t aChar) {
72 return aChar == ' ' || aChar == '\t' || aChar == '\n' || aChar == '\r' ||
73 aChar == '\f';
75 inline bool IsSpaceCharacter(char aChar) {
76 return aChar == ' ' || aChar == '\t' || aChar == '\n' || aChar == '\r' ||
77 aChar == '\f';
79 class AbstractRange;
80 class AccessibleNode;
81 template <typename T>
82 class AncestorsOfTypeIterator;
83 struct BoxQuadOptions;
84 struct ConvertCoordinateOptions;
85 class DocGroup;
86 class Document;
87 class DocumentFragment;
88 class DocumentOrShadowRoot;
89 class DOMPoint;
90 class DOMQuad;
91 class DOMRectReadOnly;
92 class Element;
93 class EventHandlerNonNull;
94 template <typename T>
95 class FlatTreeAncestorsOfTypeIterator;
96 template <typename T>
97 class InclusiveAncestorsOfTypeIterator;
98 template <typename T>
99 class InclusiveFlatTreeAncestorsOfTypeIterator;
100 class LinkStyle;
101 class MutationObservers;
102 template <typename T>
103 class Optional;
104 class OwningNodeOrString;
105 template <typename>
106 class Sequence;
107 class ShadowRoot;
108 class SVGUseElement;
109 class Text;
110 class TextOrElementOrDocument;
111 struct DOMPointInit;
112 struct GetRootNodeOptions;
113 enum class CallerType : uint32_t;
114 } // namespace dom
115 } // namespace mozilla
117 #define NODE_FLAG_BIT(n_) \
118 (nsWrapperCache::FlagsType(1U) << (WRAPPER_CACHE_FLAGS_BITS_USED + (n_)))
120 enum : uint32_t {
121 // This bit will be set if the node has a listener manager.
122 NODE_HAS_LISTENERMANAGER = NODE_FLAG_BIT(0),
124 // Whether this node has had any properties set on it
125 NODE_HAS_PROPERTIES = NODE_FLAG_BIT(1),
127 // Whether the node has some ancestor, possibly itself, that is native
128 // anonymous. This includes ancestors crossing XBL scopes, in cases when an
129 // XBL binding is attached to an element which has a native anonymous
130 // ancestor. This flag is set-once: once a node has it, it must not be
131 // removed.
132 // NOTE: Should only be used on nsIContent nodes
133 NODE_IS_IN_NATIVE_ANONYMOUS_SUBTREE = NODE_FLAG_BIT(2),
135 // Whether this node is the root of a native anonymous (from the perspective
136 // of its parent) subtree. This flag is set-once: once a node has it, it
137 // must not be removed.
138 // NOTE: Should only be used on nsIContent nodes
139 NODE_IS_NATIVE_ANONYMOUS_ROOT = NODE_FLAG_BIT(3),
141 NODE_IS_EDITABLE = NODE_FLAG_BIT(4),
143 // Whether the node participates in a shadow tree.
144 NODE_IS_IN_SHADOW_TREE = NODE_FLAG_BIT(5),
146 // This node needs to go through frame construction to get a frame (or
147 // undisplayed entry).
148 NODE_NEEDS_FRAME = NODE_FLAG_BIT(6),
150 // At least one descendant in the flattened tree has NODE_NEEDS_FRAME set.
151 // This should be set on every node on the flattened tree path between the
152 // node(s) with NODE_NEEDS_FRAME and the root content.
153 NODE_DESCENDANTS_NEED_FRAMES = NODE_FLAG_BIT(7),
155 // Set if the node has the accesskey attribute set.
156 NODE_HAS_ACCESSKEY = NODE_FLAG_BIT(8),
158 NODE_HAS_BEEN_IN_UA_WIDGET = NODE_FLAG_BIT(9),
160 // Set if the node has a nonce value and a header delivered CSP.
161 NODE_HAS_NONCE_AND_HEADER_CSP = NODE_FLAG_BIT(10),
163 NODE_KEEPS_DOMARENA = NODE_FLAG_BIT(11),
165 NODE_MAY_HAVE_ELEMENT_CHILDREN = NODE_FLAG_BIT(12),
167 // Remaining bits are node type specific.
168 NODE_TYPE_SPECIFIC_BITS_OFFSET = 13
171 // Flags for selectors that persist to the DOM node.
172 enum class NodeSelectorFlags : uint32_t {
173 // Node has an :empty or :-moz-only-whitespace selector
174 HasEmptySelector = 1 << 0,
176 /// A child of the node has a selector such that any insertion,
177 /// removal, or appending of children requires restyling the parent, if the
178 /// parent is an element. If the parent is the shadow root, the child's
179 /// siblings are restyled.
180 HasSlowSelector = 1 << 1,
182 /// A child of the node has a :first-child, :-moz-first-node,
183 /// :only-child, :last-child or :-moz-last-node selector.
184 HasEdgeChildSelector = 1 << 2,
186 /// A child of the node has a selector such that any insertion or
187 /// removal of children requires restyling later siblings of that
188 /// element. Additionally (in this manner it is stronger than
189 /// NODE_HAS_SLOW_SELECTOR), if a child's style changes due to any
190 /// other content tree changes (e.g., the child changes to or from
191 /// matching :empty due to a grandchild insertion or removal), the
192 /// child's later siblings must also be restyled.
193 HasSlowSelectorLaterSiblings = 1 << 3,
195 /// HasSlowSelector* was set by the presence of :nth (But not of).
196 HasSlowSelectorNth = 1 << 4,
198 /// A child of this node might be matched by :nth-child(.. of <selector>) or
199 /// :nth-last-child(.. of <selector>). If a DOM mutation may have caused the
200 /// selector to either match or no longer match that child, the child's
201 /// siblings are restyled.
202 HasSlowSelectorNthOf = 1 << 5,
204 /// All instances of :nth flags.
205 HasSlowSelectorNthAll = HasSlowSelectorNthOf | HasSlowSelectorNth,
207 /// Set of selector flags that may trigger a restyle on DOM append, with
208 /// restyle on siblings or a single parent (And perhaps their subtrees).
209 AllSimpleRestyleFlagsForAppend = HasEmptySelector | HasSlowSelector |
210 HasEdgeChildSelector | HasSlowSelectorNthAll,
212 /// Set of selector flags that may trigger a restyle as a result of any
213 /// DOM mutation.
214 AllSimpleRestyleFlags =
215 AllSimpleRestyleFlagsForAppend | HasSlowSelectorLaterSiblings,
217 // This node was evaluated as an anchor for a relative selector.
218 RelativeSelectorAnchor = 1 << 6,
220 // This node was evaluated as an anchor for a relative selector, and that
221 // relative selector was not the subject of the overall selector.
222 RelativeSelectorAnchorNonSubject = 1 << 7,
224 // This node's sibling(s) performed a relative selector search to this node.
225 RelativeSelectorSearchDirectionSibling = 1 << 8,
227 // This node's ancestor(s) performed a relative selector search to this node.
228 RelativeSelectorSearchDirectionAncestor = 1 << 9,
230 // This node's sibling(s) and ancestor(s), and/or this node's ancestor's
231 // sibling(s) performed a relative selector search to this node.
232 RelativeSelectorSearchDirectionAncestorSibling =
233 RelativeSelectorSearchDirectionSibling |
234 RelativeSelectorSearchDirectionAncestor,
237 MOZ_MAKE_ENUM_CLASS_BITWISE_OPERATORS(NodeSelectorFlags);
239 // Make sure we have space for our bits
240 #define ASSERT_NODE_FLAGS_SPACE(n) \
241 static_assert(WRAPPER_CACHE_FLAGS_BITS_USED + (n) <= \
242 sizeof(nsWrapperCache::FlagsType) * 8, \
243 "Not enough space for our bits")
244 ASSERT_NODE_FLAGS_SPACE(NODE_TYPE_SPECIFIC_BITS_OFFSET);
247 * Class used to detect unexpected mutations. To use the class create an
248 * nsMutationGuard on the stack before unexpected mutations could occur.
249 * You can then at any time call Mutated to check if any unexpected mutations
250 * have occurred.
252 class nsMutationGuard {
253 public:
254 nsMutationGuard() { mStartingGeneration = sGeneration; }
257 * Returns true if any unexpected mutations have occurred. You can pass in
258 * an 8-bit ignore count to ignore a number of expected mutations.
260 * We don't need to care about overflow because subtraction of uint64_t's is
261 * finding the difference between two elements of the group Z < 2^64. Once
262 * we know the difference between two elements we only need to check that is
263 * less than the given number of mutations to know less than that many
264 * mutations occured. Assuming constant 1ns mutations it would take 584
265 * years for sGeneration to fully wrap around so we can ignore a guard living
266 * through a full wrap around.
268 bool Mutated(uint8_t aIgnoreCount) {
269 return (sGeneration - mStartingGeneration) > aIgnoreCount;
272 // This function should be called whenever a mutation that we want to keep
273 // track of happen. For now this is only done when children are added or
274 // removed, but we might do it for attribute changes too in the future.
275 static void DidMutate() { sGeneration++; }
277 private:
278 // This is the value sGeneration had when the guard was constructed.
279 uint64_t mStartingGeneration;
281 // This value is incremented on every mutation, for the life of the process.
282 static uint64_t sGeneration;
286 * A class that implements nsIWeakReference
288 class nsNodeWeakReference final : public nsIWeakReference {
289 public:
290 explicit nsNodeWeakReference(nsINode* aNode);
292 // nsISupports
293 NS_DECL_ISUPPORTS
295 // nsIWeakReference
296 NS_DECL_NSIWEAKREFERENCE
298 void NoticeNodeDestruction() { mObject = nullptr; }
300 private:
301 ~nsNodeWeakReference();
304 // This should be used for any nsINode sub-class that has fields of its own
305 // that it needs to measure; any sub-class that doesn't use it will inherit
306 // AddSizeOfExcludingThis from its super-class. AddSizeOfIncludingThis() need
307 // not be defined, it is inherited from nsINode.
308 #define NS_DECL_ADDSIZEOFEXCLUDINGTHIS \
309 virtual void AddSizeOfExcludingThis(nsWindowSizes& aSizes, \
310 size_t* aNodeSize) const override;
312 // IID for the nsINode interface
313 // Must be kept in sync with xpcom/rust/xpcom/src/interfaces/nonidl.rs
314 #define NS_INODE_IID \
316 0x70ba4547, 0x7699, 0x44fc, { \
317 0xb3, 0x20, 0x52, 0xdb, 0xe3, 0xd1, 0xf9, 0x0a \
322 * An internal interface that abstracts some DOMNode-related parts that both
323 * nsIContent and Document share. An instance of this interface has a list
324 * of nsIContent children and provides access to them.
326 class nsINode : public mozilla::dom::EventTarget {
327 #ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
328 void AssertInvariantsOnNodeInfoChange();
329 #endif
330 public:
331 using BoxQuadOptions = mozilla::dom::BoxQuadOptions;
332 using ConvertCoordinateOptions = mozilla::dom::ConvertCoordinateOptions;
333 using DocGroup = mozilla::dom::DocGroup;
334 using Document = mozilla::dom::Document;
335 using DOMPoint = mozilla::dom::DOMPoint;
336 using DOMPointInit = mozilla::dom::DOMPointInit;
337 using DOMQuad = mozilla::dom::DOMQuad;
338 using DOMRectReadOnly = mozilla::dom::DOMRectReadOnly;
339 using OwningNodeOrString = mozilla::dom::OwningNodeOrString;
340 using TextOrElementOrDocument = mozilla::dom::TextOrElementOrDocument;
341 using CallerType = mozilla::dom::CallerType;
342 using ErrorResult = mozilla::ErrorResult;
344 // XXXbz Maybe we should codegen a class holding these constants and
345 // inherit from it...
346 static const auto ELEMENT_NODE = mozilla::dom::Node_Binding::ELEMENT_NODE;
347 static const auto ATTRIBUTE_NODE = mozilla::dom::Node_Binding::ATTRIBUTE_NODE;
348 static const auto TEXT_NODE = mozilla::dom::Node_Binding::TEXT_NODE;
349 static const auto CDATA_SECTION_NODE =
350 mozilla::dom::Node_Binding::CDATA_SECTION_NODE;
351 static const auto ENTITY_REFERENCE_NODE =
352 mozilla::dom::Node_Binding::ENTITY_REFERENCE_NODE;
353 static const auto ENTITY_NODE = mozilla::dom::Node_Binding::ENTITY_NODE;
354 static const auto PROCESSING_INSTRUCTION_NODE =
355 mozilla::dom::Node_Binding::PROCESSING_INSTRUCTION_NODE;
356 static const auto COMMENT_NODE = mozilla::dom::Node_Binding::COMMENT_NODE;
357 static const auto DOCUMENT_NODE = mozilla::dom::Node_Binding::DOCUMENT_NODE;
358 static const auto DOCUMENT_TYPE_NODE =
359 mozilla::dom::Node_Binding::DOCUMENT_TYPE_NODE;
360 static const auto DOCUMENT_FRAGMENT_NODE =
361 mozilla::dom::Node_Binding::DOCUMENT_FRAGMENT_NODE;
362 static const auto NOTATION_NODE = mozilla::dom::Node_Binding::NOTATION_NODE;
363 static const auto MAX_NODE_TYPE = NOTATION_NODE;
365 void* operator new(size_t aSize, nsNodeInfoManager* aManager);
366 void* operator new(size_t aSize) = delete;
367 void operator delete(void* aPtr);
369 template <class T>
370 using Sequence = mozilla::dom::Sequence<T>;
372 NS_DECLARE_STATIC_IID_ACCESSOR(NS_INODE_IID)
374 // The |aNodeSize| outparam on this function is where the actual node size
375 // value is put. It gets added to the appropriate value within |aSizes| by
376 // AddSizeOfNodeTree().
378 // Among the sub-classes that inherit (directly or indirectly) from nsINode,
379 // measurement of the following members may be added later if DMD finds it is
380 // worthwhile:
381 // - nsGenericHTMLElement: mForm, mFieldSet
382 // - nsGenericHTMLFrameElement: mFrameLoader (bug 672539)
383 // - HTMLBodyElement: mContentStyleRule
384 // - HTMLDataListElement: mOptions
385 // - HTMLFieldSetElement: mElements, mDependentElements, mFirstLegend
386 // - HTMLFormElement: many!
387 // - HTMLFrameSetElement: mRowSpecs, mColSpecs
388 // - HTMLInputElement: mInputData, mFiles, mFileList, mStaticDocfileList
389 // - nsHTMLMapElement: mAreas
390 // - HTMLMediaElement: many!
391 // - nsHTMLOutputElement: mDefaultValue, mTokenList
392 // - nsHTMLRowElement: mCells
393 // - nsHTMLSelectElement: mOptions, mRestoreState
394 // - nsHTMLTableElement: mTBodies, mRows, mTableInheritedAttributes
395 // - nsHTMLTableSectionElement: mRows
396 // - nsHTMLTextAreaElement: mControllers, mState
398 // The following members don't need to be measured:
399 // - nsIContent: mPrimaryFrame, because it's non-owning and measured elsewhere
401 virtual void AddSizeOfExcludingThis(nsWindowSizes& aSizes,
402 size_t* aNodeSize) const;
404 // SizeOfIncludingThis doesn't need to be overridden by sub-classes because
405 // sub-classes of nsINode are guaranteed to be laid out in memory in such a
406 // way that |this| points to the start of the allocated object, even in
407 // methods of nsINode's sub-classes, so aSizes.mState.mMallocSizeOf(this) is
408 // always safe to call no matter which object it was invoked on.
409 void AddSizeOfIncludingThis(nsWindowSizes& aSizes, size_t* aNodeSize) const;
411 friend class nsNodeWeakReference;
412 friend class nsNodeSupportsWeakRefTearoff;
413 friend class AttrArray;
415 #ifdef MOZILLA_INTERNAL_API
416 explicit nsINode(already_AddRefed<mozilla::dom::NodeInfo>&& aNodeInfo);
417 #endif
419 virtual ~nsINode();
421 bool IsContainerNode() const {
422 return IsElement() || IsDocument() || IsDocumentFragment();
426 * Returns true if the node is a HTMLTemplate element.
428 bool IsTemplateElement() const { return IsHTMLElement(nsGkAtoms::_template); }
430 bool IsSlotable() const { return IsElement() || IsText(); }
433 * Returns true if this is a document node.
435 bool IsDocument() const {
436 // One less pointer-chase than checking NodeType().
437 return !GetParentNode() && IsInUncomposedDoc();
441 * Return this node as a document. Asserts IsDocument().
443 * This is defined inline in Document.h.
445 inline Document* AsDocument();
446 inline const Document* AsDocument() const;
449 * Returns true if this is a document fragment node.
451 bool IsDocumentFragment() const {
452 return NodeType() == DOCUMENT_FRAGMENT_NODE;
455 virtual bool IsHTMLFormControlElement() const { return false; }
458 * https://dom.spec.whatwg.org/#concept-tree-inclusive-descendant
460 * @param aNode must not be nullptr.
462 bool IsInclusiveDescendantOf(const nsINode* aNode) const;
465 * https://dom.spec.whatwg.org/#concept-shadow-including-inclusive-descendant
467 * @param aNode must not be nullptr.
469 bool IsShadowIncludingInclusiveDescendantOf(const nsINode* aNode) const;
472 * Returns true if the given node is this node or one of its descendants
473 * in the "flat tree."
475 * @param aNode must not be nullptr.
477 bool IsInclusiveFlatTreeDescendantOf(const nsINode* aNode) const;
480 * Return this node as a document fragment. Asserts IsDocumentFragment().
482 * This is defined inline in DocumentFragment.h.
484 inline mozilla::dom::DocumentFragment* AsDocumentFragment();
485 inline const mozilla::dom::DocumentFragment* AsDocumentFragment() const;
487 JSObject* WrapObject(JSContext*, JS::Handle<JSObject*> aGivenProto) final;
490 * Hook for constructing JS::ubi::Concrete specializations for memory
491 * reporting. Specializations are defined in NodeUbiReporting.h.
493 virtual void ConstructUbiNode(void* storage) = 0;
496 * returns true if we are in priviliged code or
497 * layout.css.getBoxQuads.enabled == true.
499 static bool HasBoxQuadsSupport(JSContext* aCx, JSObject* /* unused */);
501 protected:
503 * WrapNode is called from WrapObject to actually wrap this node, WrapObject
504 * does some additional checks and fix-up that's common to all nodes. WrapNode
505 * should just call the DOM binding's Wrap function.
507 * aGivenProto is the prototype to use (or null if the default one should be
508 * used) and should just be passed directly on to the DOM binding's Wrap
509 * function.
511 virtual JSObject* WrapNode(JSContext* aCx,
512 JS::Handle<JSObject*> aGivenProto) = 0;
514 public:
515 mozilla::dom::ParentObject GetParentObject()
516 const; // Implemented in Document.h
519 * Returns the first child of a node or the first child of
520 * a template element's content if the provided node is a
521 * template element.
523 nsIContent* GetFirstChildOfTemplateOrNode();
526 * Return the scope chain parent for this node, for use in things
527 * like event handler compilation. Returning null means to use the
528 * global object as the scope chain parent.
530 virtual nsINode* GetScopeChainParent() const;
532 MOZ_CAN_RUN_SCRIPT mozilla::dom::Element* GetParentFlexElement();
535 * Returns the nearest inclusive open popover for a given node, see
536 * https://html.spec.whatwg.org/multipage/popover.html#nearest-inclusive-open-popover
538 mozilla::dom::Element* GetNearestInclusiveOpenPopover() const;
541 * https://html.spec.whatwg.org/multipage/popover.html#nearest-inclusive-target-popover-for-invoker
543 mozilla::dom::Element* GetNearestInclusiveTargetPopoverForInvoker() const;
546 * https://html.spec.whatwg.org/multipage/popover.html#popover-target-element
548 nsGenericHTMLElement* GetEffectivePopoverTargetElement() const;
551 * https://html.spec.whatwg.org/multipage/popover.html#topmost-clicked-popover
553 mozilla::dom::Element* GetTopmostClickedPopover() const;
555 bool IsNode() const final { return true; }
557 NS_IMPL_FROMEVENTTARGET_HELPER(nsINode, IsNode())
560 * Return whether the node is an Element node. Faster than using `NodeType()`.
562 bool IsElement() const { return GetBoolFlag(NodeIsElement); }
564 virtual bool IsTextControlElement() const { return false; }
565 virtual bool IsGenericHTMLFormControlElementWithState() const {
566 return false;
569 // Returns non-null if this element subclasses `LinkStyle`.
570 virtual const mozilla::dom::LinkStyle* AsLinkStyle() const { return nullptr; }
571 mozilla::dom::LinkStyle* AsLinkStyle() {
572 return const_cast<mozilla::dom::LinkStyle*>(
573 static_cast<const nsINode*>(this)->AsLinkStyle());
577 * Return this node as an Element. Should only be used for nodes
578 * for which IsElement() is true. This is defined inline in Element.h.
580 inline mozilla::dom::Element* AsElement();
581 inline const mozilla::dom::Element* AsElement() const;
584 * Return whether the node is an nsStyledElement instance or not.
586 virtual bool IsStyledElement() const { return false; }
589 * Return this node as nsIContent. Should only be used for nodes for which
590 * IsContent() is true.
592 * The assertion in nsIContent's constructor makes this safe.
594 nsIContent* AsContent() {
595 MOZ_ASSERT(IsContent());
596 return reinterpret_cast<nsIContent*>(this);
598 const nsIContent* AsContent() const {
599 MOZ_ASSERT(IsContent());
600 return reinterpret_cast<const nsIContent*>(this);
604 * Return whether the node is a Text node (which might be an actual
605 * textnode, or might be a CDATA section).
607 bool IsText() const {
608 uint32_t nodeType = NodeType();
609 return nodeType == TEXT_NODE || nodeType == CDATA_SECTION_NODE;
613 * Return this node as Text if it is one, otherwise null. This is defined
614 * inline in Text.h.
616 inline mozilla::dom::Text* GetAsText();
617 inline const mozilla::dom::Text* GetAsText() const;
620 * Return this node as Text. Asserts IsText(). This is defined inline in
621 * Text.h.
623 inline mozilla::dom::Text* AsText();
624 inline const mozilla::dom::Text* AsText() const;
627 * Return whether the node is a ProcessingInstruction node.
629 bool IsProcessingInstruction() const {
630 return NodeType() == PROCESSING_INSTRUCTION_NODE;
634 * Return whether the node is a CharacterData node (text, cdata,
635 * comment, processing instruction)
637 bool IsCharacterData() const {
638 uint32_t nodeType = NodeType();
639 return nodeType == TEXT_NODE || nodeType == CDATA_SECTION_NODE ||
640 nodeType == PROCESSING_INSTRUCTION_NODE || nodeType == COMMENT_NODE;
644 * Return whether the node is a Comment node.
646 bool IsComment() const { return NodeType() == COMMENT_NODE; }
649 * Return whether the node is an Attr node.
651 bool IsAttr() const { return NodeType() == ATTRIBUTE_NODE; }
654 * Return if this node has any children.
656 bool HasChildren() const { return !!mFirstChild; }
659 * Get the number of children
660 * @return the number of children
662 uint32_t GetChildCount() const { return mChildCount; }
665 * NOTE: this function is going to be removed soon (hopefully!) Don't use it
666 * in new code.
668 * Get a child by index
669 * @param aIndex the index of the child to get
670 * @return the child, or null if index out of bounds
672 nsIContent* GetChildAt_Deprecated(uint32_t aIndex) const;
675 * Get the index of a child within this content.
677 * @param aPossibleChild the child to get the index of.
678 * @return the index of the child, or Nothing if not a child. Be aware that
679 * anonymous children (e.g. a <div> child of an <input> element) will
680 * result in Nothing.
682 * If the return value is Some, then calling GetChildAt_Deprecated() with
683 * that value will return aPossibleChild.
685 mozilla::Maybe<uint32_t> ComputeIndexOf(const nsINode* aPossibleChild) const;
688 * Get the index of a child within this content's flat tree children.
690 * @param aPossibleChild the child to get the index of.
691 * @return the index of the child, or Nothing if not a child. Be aware that
692 * anonymous children (e.g. a <div> child of an <input> element) will
693 * result in Nothing.
695 mozilla::Maybe<uint32_t> ComputeFlatTreeIndexOf(
696 const nsINode* aPossibleChild) const;
699 * Get the index of this within parent node (ComputeIndexInParentNode) or
700 * parent content (nsIContent) node (ComputeIndexInParentContent).
702 * @return the index of this node in the parent, or Nothing there is no
703 * parent (content) node or the parent does not have this node anymore
704 * (e.g., being removed from the parent). Be aware that anonymous
705 * children (e.g. a <div> child of an <input> element) will result in
706 * Nothing.
708 * If the return value is Some, then calling GetChildAt_Deprecated() with
709 * that value will return this.
711 mozilla::Maybe<uint32_t> ComputeIndexInParentNode() const;
712 mozilla::Maybe<uint32_t> ComputeIndexInParentContent() const;
715 * Get the index of a child within this content.
717 * @param aPossibleChild the child to get the index of.
718 * @return the index of the child, or -1 if not a child. Be aware that
719 * anonymous children (e.g. a <div> child of an <input> element) will
720 * result in -1.
722 * If the return value is not -1, then calling GetChildAt_Deprecated() with
723 * that value will return aPossibleChild.
725 int32_t ComputeIndexOf_Deprecated(const nsINode* aPossibleChild) const;
728 * Returns the "node document" of this node.
730 * https://dom.spec.whatwg.org/#concept-node-document
732 * Note that in the case that this node is a document node this method
733 * will return |this|. That is different to the Node.ownerDocument DOM
734 * attribute (implemented by nsINode::GetOwnerDocument) which is specified to
735 * be null in that case:
737 * https://dom.spec.whatwg.org/#dom-node-ownerdocument
739 * For all other cases OwnerDoc and GetOwnerDocument behave identically.
741 Document* OwnerDoc() const MOZ_NONNULL_RETURN {
742 return mNodeInfo->GetDocument();
746 * Return the "owner document" of this node as an nsINode*. Implemented
747 * in Document.h.
749 inline nsINode* OwnerDocAsNode() const MOZ_NONNULL_RETURN;
752 * Returns true if the content has an ancestor that is a document.
754 * @return whether this content is in a document tree
756 bool IsInUncomposedDoc() const { return GetBoolFlag(IsInDocument); }
759 * Get the document that this content is currently in, if any. This will be
760 * null if the content has no ancestor that is a document.
762 * @return the current document
765 Document* GetUncomposedDoc() const {
766 return IsInUncomposedDoc() ? OwnerDoc() : nullptr;
770 * Returns true if we're connected, and thus GetComposedDoc() would return a
771 * non-null value.
773 bool IsInComposedDoc() const { return GetBoolFlag(IsConnected); }
776 * This method returns the owner document if the node is connected to it
777 * (as defined in the DOM spec), otherwise it returns null.
778 * In other words, returns non-null even in the case the node is in
779 * Shadow DOM, if there is a possibly shadow boundary crossing path from
780 * the node to its owner document.
782 Document* GetComposedDoc() const {
783 return IsInComposedDoc() ? OwnerDoc() : nullptr;
787 * Returns OwnerDoc() if the node is in uncomposed document and ShadowRoot if
788 * the node is in Shadow DOM.
790 mozilla::dom::DocumentOrShadowRoot* GetContainingDocumentOrShadowRoot() const;
793 * Returns OwnerDoc() if the node is in uncomposed document and ShadowRoot if
794 * the node is in Shadow DOM and is in composed document.
796 mozilla::dom::DocumentOrShadowRoot* GetUncomposedDocOrConnectedShadowRoot()
797 const;
800 * To be called when reference count of the node drops to zero.
802 void LastRelease();
805 * The values returned by this function are the ones defined for
806 * Node.nodeType
808 uint16_t NodeType() const { return mNodeInfo->NodeType(); }
809 const nsString& NodeName() const { return mNodeInfo->NodeName(); }
810 const nsString& LocalName() const { return mNodeInfo->LocalName(); }
813 * Get the NodeInfo for this element
814 * @return the nodes node info
816 inline mozilla::dom::NodeInfo* NodeInfo() const { return mNodeInfo; }
819 * Called when we have been adopted, and the information of the
820 * node has been changed.
822 * The new document can be reached via OwnerDoc().
824 * If you override this method,
825 * please call up to the parent NodeInfoChanged.
827 * If you change this, change also the similar method in Link.
829 virtual void NodeInfoChanged(Document* aOldDoc) {
830 #ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
831 AssertInvariantsOnNodeInfoChange();
832 #endif
835 inline bool IsInNamespace(int32_t aNamespace) const {
836 return mNodeInfo->NamespaceID() == aNamespace;
840 * Returns the DocGroup of the "node document" of this node.
842 DocGroup* GetDocGroup() const;
845 * Print a debugger friendly descriptor of this element. This will describe
846 * the position of this element in the document.
848 friend std::ostream& operator<<(std::ostream& aStream, const nsINode& aNode);
850 protected:
851 // These 2 methods are useful for the recursive templates IsHTMLElement,
852 // IsSVGElement, etc.
853 inline bool IsNodeInternal() const { return false; }
855 template <typename First, typename... Args>
856 inline bool IsNodeInternal(First aFirst, Args... aArgs) const {
857 return mNodeInfo->Equals(aFirst) || IsNodeInternal(aArgs...);
860 public:
861 inline bool IsHTMLElement() const {
862 return IsElement() && IsInNamespace(kNameSpaceID_XHTML);
865 inline bool IsHTMLElement(const nsAtom* aTag) const {
866 return IsElement() && mNodeInfo->Equals(aTag, kNameSpaceID_XHTML);
869 template <typename First, typename... Args>
870 inline bool IsAnyOfHTMLElements(First aFirst, Args... aArgs) const {
871 return IsHTMLElement() && IsNodeInternal(aFirst, aArgs...);
874 inline bool IsSVGElement() const {
875 return IsElement() && IsInNamespace(kNameSpaceID_SVG);
878 inline bool IsSVGElement(const nsAtom* aTag) const {
879 return IsElement() && mNodeInfo->Equals(aTag, kNameSpaceID_SVG);
882 template <typename First, typename... Args>
883 inline bool IsAnyOfSVGElements(First aFirst, Args... aArgs) const {
884 return IsSVGElement() && IsNodeInternal(aFirst, aArgs...);
887 virtual bool IsSVGAnimationElement() const { return false; }
888 virtual bool IsSVGComponentTransferFunctionElement() const { return false; }
889 virtual bool IsSVGFilterPrimitiveElement() const { return false; }
890 virtual bool IsSVGFilterPrimitiveChildElement() const { return false; }
891 virtual bool IsSVGGeometryElement() const { return false; }
892 virtual bool IsSVGGraphicsElement() const { return false; }
894 inline bool IsXULElement() const {
895 return IsElement() && IsInNamespace(kNameSpaceID_XUL);
898 inline bool IsXULElement(const nsAtom* aTag) const {
899 return IsElement() && mNodeInfo->Equals(aTag, kNameSpaceID_XUL);
902 template <typename First, typename... Args>
903 inline bool IsAnyOfXULElements(First aFirst, Args... aArgs) const {
904 return IsXULElement() && IsNodeInternal(aFirst, aArgs...);
907 inline bool IsMathMLElement() const {
908 return IsElement() && IsInNamespace(kNameSpaceID_MathML);
911 inline bool IsMathMLElement(const nsAtom* aTag) const {
912 return IsElement() && mNodeInfo->Equals(aTag, kNameSpaceID_MathML);
915 template <typename First, typename... Args>
916 inline bool IsAnyOfMathMLElements(First aFirst, Args... aArgs) const {
917 return IsMathMLElement() && IsNodeInternal(aFirst, aArgs...);
920 bool IsShadowRoot() const {
921 const bool isShadowRoot = IsInShadowTree() && !GetParentNode();
922 MOZ_ASSERT_IF(isShadowRoot, IsDocumentFragment());
923 return isShadowRoot;
926 bool IsHTMLHeadingElement() const {
927 return IsAnyOfHTMLElements(nsGkAtoms::h1, nsGkAtoms::h2, nsGkAtoms::h3,
928 nsGkAtoms::h4, nsGkAtoms::h5, nsGkAtoms::h6);
932 * Check whether the conditional processing attributes other than
933 * systemLanguage "return true" if they apply to and are specified
934 * on the given SVG element. Returns true if this element should be
935 * rendered, false if it should not.
937 virtual bool PassesConditionalProcessingTests() const { return true; }
940 * Insert a content node before another or at the end.
941 * This method handles calling BindToTree on the child appropriately.
943 * @param aKid the content to insert
944 * @param aBeforeThis an existing node. Use nullptr if you want to
945 * add aKid at the end.
946 * @param aNotify whether to notify the document (current document for
947 * nsIContent, and |this| for Document) that the insert has occurred
948 * @param aRv The error, if any.
949 * Throw NS_ERROR_DOM_HIERARCHY_REQUEST_ERR if one attempts to have
950 * more than one element node as a child of a document. Doing this
951 * will also assert -- you shouldn't be doing it! Check with
952 * Document::GetRootElement() first if you're not sure. Apart from
953 * this one constraint, this doesn't do any checking on whether aKid is
954 * a valid child of |this|.
955 * Throw NS_ERROR_OUT_OF_MEMORY in some cases (from BindToTree).
957 virtual void InsertChildBefore(nsIContent* aKid, nsIContent* aBeforeThis,
958 bool aNotify, mozilla::ErrorResult& aRv);
961 * Append a content node to the end of the child list. This method handles
962 * calling BindToTree on the child appropriately.
964 * @param aKid the content to append
965 * @param aNotify whether to notify the document (current document for
966 * nsIContent, and |this| for Document) that the append has occurred
967 * @param aRv The error, if any.
968 * Throw NS_ERROR_DOM_HIERARCHY_REQUEST_ERR if one attempts to have
969 * more than one element node as a child of a document. Doing this
970 * will also assert -- you shouldn't be doing it! Check with
971 * Document::GetRootElement() first if you're not sure. Apart from
972 * this one constraint, this doesn't do any checking on whether aKid is
973 * a valid child of |this|.
974 * Throw NS_ERROR_OUT_OF_MEMORY in some cases (from BindToTree).
976 void AppendChildTo(nsIContent* aKid, bool aNotify,
977 mozilla::ErrorResult& aRv) {
978 InsertChildBefore(aKid, nullptr, aNotify, aRv);
982 * Remove a child from this node. This method handles calling UnbindFromTree
983 * on the child appropriately.
985 * @param aKid the content to remove
986 * @param aNotify whether to notify the document (current document for
987 * nsIContent, and |this| for Document) that the remove has occurred
989 virtual void RemoveChildNode(nsIContent* aKid, bool aNotify);
992 * Get a property associated with this node.
994 * @param aPropertyName name of property to get.
995 * @param aStatus out parameter for storing resulting status.
996 * Set to NS_PROPTABLE_PROP_NOT_THERE if the property
997 * is not set.
998 * @return the property. Null if the property is not set
999 * (though a null return value does not imply the
1000 * property was not set, i.e. it can be set to null).
1002 void* GetProperty(const nsAtom* aPropertyName,
1003 nsresult* aStatus = nullptr) const;
1006 * Set a property to be associated with this node. This will overwrite an
1007 * existing value if one exists. The existing value is destroyed using the
1008 * destructor function given when that value was set.
1010 * @param aPropertyName name of property to set.
1011 * @param aValue new value of property.
1012 * @param aDtor destructor function to be used when this property
1013 * is destroyed.
1014 * @param aTransfer if true the property will not be deleted when the
1015 * ownerDocument of the node changes, if false it
1016 * will be deleted.
1018 * @return NS_PROPTABLE_PROP_OVERWRITTEN (success value) if the property
1019 * was already set
1020 * @throws NS_ERROR_OUT_OF_MEMORY if that occurs
1022 nsresult SetProperty(nsAtom* aPropertyName, void* aValue,
1023 NSPropertyDtorFunc aDtor = nullptr,
1024 bool aTransfer = false);
1027 * A generic destructor for property values allocated with new.
1029 template <class T>
1030 static void DeleteProperty(void*, nsAtom*, void* aPropertyValue, void*) {
1031 delete static_cast<T*>(aPropertyValue);
1035 * Removes a property associated with this node. The value is destroyed using
1036 * the destruction function given when that value was set.
1038 * @param aPropertyName name of property to destroy.
1040 void RemoveProperty(const nsAtom* aPropertyName);
1043 * Take a property associated with this node. The value will not be destroyed
1044 * but rather returned. It is the caller's responsibility to destroy the value
1045 * after that point.
1047 * @param aPropertyName name of property to unset.
1048 * @param aStatus out parameter for storing resulting status.
1049 * Set to NS_PROPTABLE_PROP_NOT_THERE if the property
1050 * is not set.
1051 * @return the property. Null if the property is not set
1052 * (though a null return value does not imply the
1053 * property was not set, i.e. it can be set to null).
1055 void* TakeProperty(const nsAtom* aPropertyName, nsresult* aStatus = nullptr);
1057 bool HasProperties() const { return HasFlag(NODE_HAS_PROPERTIES); }
1060 * Return the principal of this node. This is guaranteed to never be a null
1061 * pointer.
1063 nsIPrincipal* NodePrincipal() const {
1064 return mNodeInfo->NodeInfoManager()->DocumentPrincipal();
1068 * Return the CSP of this node's document, if any.
1070 nsIContentSecurityPolicy* GetCsp() const;
1073 * Get the parent nsIContent for this node.
1074 * @return the parent, or null if no parent or the parent is not an nsIContent
1076 nsIContent* GetParent() const {
1077 return MOZ_LIKELY(GetBoolFlag(ParentIsContent)) ? mParent->AsContent()
1078 : nullptr;
1082 * Get the parent nsINode for this node. This can be either an nsIContent, a
1083 * Document or an Attr.
1084 * @return the parent node
1086 nsINode* GetParentNode() const { return mParent; }
1088 private:
1089 nsIContent* DoGetShadowHost() const;
1091 public:
1092 nsINode* GetParentOrShadowHostNode() const {
1093 if (MOZ_LIKELY(mParent)) {
1094 return mParent;
1096 // We could put this in nsIContentInlines.h or such to avoid this
1097 // reinterpret_cast, but it doesn't seem worth it.
1098 return IsInShadowTree() ? reinterpret_cast<nsINode*>(DoGetShadowHost())
1099 : nullptr;
1102 enum FlattenedParentType { eNormal, eForStyle, eForSelection };
1105 * Returns the node that is the parent of this node in the flattened
1106 * tree. This differs from the normal parent if the node is filtered
1107 * into an insertion point, or if the node is a direct child of a
1108 * shadow root.
1110 * @return the flattened tree parent
1112 inline nsINode* GetFlattenedTreeParentNode() const;
1114 nsINode* GetFlattenedTreeParentNodeNonInline() const;
1117 * Like GetFlattenedTreeParentNode, but returns the document for any native
1118 * anonymous content that was generated for ancestor frames of the document
1119 * element's primary frame, such as scrollbar elements created by the root
1120 * scroll frame.
1122 inline nsINode* GetFlattenedTreeParentNodeForStyle() const;
1125 * Similar to GetFlattenedTreeParentNode, it does two things differently
1126 * 1. For contents that are not in the flattened tree, use its
1127 * parent rather than nullptr.
1128 * 2. For contents that are slotted into a UA shadow tree, use its
1129 * parent rather than the slot element.
1131 inline nsIContent* GetFlattenedTreeParentNodeForSelection() const;
1133 inline mozilla::dom::Element* GetFlattenedTreeParentElement() const;
1134 inline mozilla::dom::Element* GetFlattenedTreeParentElementForStyle() const;
1137 * Get the parent nsINode for this node if it is an Element.
1139 * Defined inline in Element.h
1141 * @return the parent node
1143 inline mozilla::dom::Element* GetParentElement() const;
1146 * Get the parent Element of this node, traversing over a ShadowRoot
1147 * to its host if necessary.
1149 mozilla::dom::Element* GetParentElementCrossingShadowRoot() const;
1152 * Get closest element node for the node. Meaning that if the node is an
1153 * element node, returns itself. Otherwise, returns parent element or null.
1155 inline mozilla::dom::Element* GetAsElementOrParentElement() const;
1158 * Get the root of the subtree this node belongs to. This never returns
1159 * null. It may return 'this' (e.g. for document nodes, and nodes that
1160 * are the roots of disconnected subtrees).
1162 nsINode* SubtreeRoot() const;
1165 * Get context object's shadow-including root if options's composed is true,
1166 * and context object's root otherwise.
1168 nsINode* GetRootNode(const mozilla::dom::GetRootNodeOptions& aOptions);
1170 virtual mozilla::EventListenerManager* GetExistingListenerManager()
1171 const override;
1172 virtual mozilla::EventListenerManager* GetOrCreateListenerManager() override;
1174 mozilla::Maybe<mozilla::dom::EventCallbackDebuggerNotificationType>
1175 GetDebuggerNotificationType() const override;
1177 bool ComputeDefaultWantsUntrusted(mozilla::ErrorResult& aRv) final;
1179 virtual bool IsApzAware() const override;
1181 virtual nsPIDOMWindowOuter* GetOwnerGlobalForBindingsInternal() override;
1182 virtual nsIGlobalObject* GetOwnerGlobal() const override;
1184 using mozilla::dom::EventTarget::DispatchEvent;
1185 // TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230)
1186 MOZ_CAN_RUN_SCRIPT_BOUNDARY bool DispatchEvent(
1187 mozilla::dom::Event& aEvent, mozilla::dom::CallerType aCallerType,
1188 mozilla::ErrorResult& aRv) override;
1190 MOZ_CAN_RUN_SCRIPT
1191 nsresult PostHandleEvent(mozilla::EventChainPostVisitor& aVisitor) override;
1194 * Adds a mutation observer to be notified when this node, or any of its
1195 * descendants, are modified. The node will hold a weak reference to the
1196 * observer, which means that it is the responsibility of the observer to
1197 * remove itself in case it dies before the node. If an observer is added
1198 * while observers are being notified, it may also be notified. In general,
1199 * adding observers while inside a notification is not a good idea. An
1200 * observer that is already observing the node must not be added without
1201 * being removed first.
1203 * For mutation observers that implement nsIAnimationObserver, use
1204 * AddAnimationObserver instead.
1206 void AddMutationObserver(nsIMutationObserver* aMutationObserver) {
1207 nsSlots* s = Slots();
1208 if (aMutationObserver) {
1209 NS_ASSERTION(!s->mMutationObservers.contains(aMutationObserver),
1210 "Observer already in the list");
1212 s->mMutationObservers.pushBack(aMutationObserver);
1216 void AddMutationObserver(nsMultiMutationObserver* aMultiMutationObserver);
1219 * Same as above, but only adds the observer if its not observing
1220 * the node already.
1222 * For mutation observers that implement nsIAnimationObserver, use
1223 * AddAnimationObserverUnlessExists instead.
1225 void AddMutationObserverUnlessExists(nsIMutationObserver* aMutationObserver) {
1226 nsSlots* s = Slots();
1227 if (aMutationObserver &&
1228 !s->mMutationObservers.contains(aMutationObserver)) {
1229 s->mMutationObservers.pushBack(aMutationObserver);
1233 void AddMutationObserverUnlessExists(
1234 nsMultiMutationObserver* aMultiMutationObserver);
1236 * Same as AddMutationObserver, but for nsIAnimationObservers. This
1237 * additionally records on the document that animation observers have
1238 * been registered, which is used to determine whether notifications
1239 * must be fired when animations are added, removed or changed.
1241 void AddAnimationObserver(nsIAnimationObserver* aAnimationObserver);
1244 * Same as above, but only adds the observer if its not observing
1245 * the node already.
1247 void AddAnimationObserverUnlessExists(
1248 nsIAnimationObserver* aAnimationObserver);
1251 * Removes a mutation observer.
1253 void RemoveMutationObserver(nsIMutationObserver* aMutationObserver) {
1254 nsSlots* s = GetExistingSlots();
1255 if (s) {
1256 s->mMutationObservers.remove(aMutationObserver);
1260 void RemoveMutationObserver(nsMultiMutationObserver* aMultiMutationObserver);
1262 mozilla::SafeDoublyLinkedList<nsIMutationObserver>* GetMutationObservers();
1265 * Helper methods to access ancestor node(s) of type T.
1266 * The implementations of the methods are in mozilla/dom/AncestorIterator.h.
1268 template <typename T>
1269 inline mozilla::dom::AncestorsOfTypeIterator<T> AncestorsOfType() const;
1271 template <typename T>
1272 inline mozilla::dom::InclusiveAncestorsOfTypeIterator<T>
1273 InclusiveAncestorsOfType() const;
1275 template <typename T>
1276 inline mozilla::dom::FlatTreeAncestorsOfTypeIterator<T>
1277 FlatTreeAncestorsOfType() const;
1279 template <typename T>
1280 inline mozilla::dom::InclusiveFlatTreeAncestorsOfTypeIterator<T>
1281 InclusiveFlatTreeAncestorsOfType() const;
1283 template <typename T>
1284 T* FirstAncestorOfType() const;
1286 private:
1288 * Walks aNode, its attributes and, if aDeep is true, its descendant nodes.
1289 * If aClone is true the nodes will be cloned. If aNewNodeInfoManager is
1290 * not null, it is used to create new nodeinfos for the nodes. Also reparents
1291 * the XPConnect wrappers for the nodes into aReparentScope if non-null.
1293 * @param aNode Node to adopt/clone.
1294 * @param aClone If true the node will be cloned and the cloned node will
1295 * be returned.
1296 * @param aDeep If true the function will be called recursively on
1297 * descendants of the node
1298 * @param aNewNodeInfoManager The nodeinfo manager to use to create new
1299 * nodeinfos for aNode and its attributes and
1300 * descendants. May be null if the nodeinfos
1301 * shouldn't be changed.
1302 * @param aReparentScope Scope into which wrappers should be reparented, or
1303 * null if no reparenting should be done.
1304 * @param aParent If aClone is true the cloned node will be appended to
1305 * aParent's children. May be null. If not null then aNode
1306 * must be an nsIContent.
1307 * @param aError The error, if any.
1309 * @return If aClone is true then the cloned node will be returned,
1310 * unless an error occurred. In error conditions, null
1311 * will be returned.
1313 static already_AddRefed<nsINode> CloneAndAdopt(
1314 nsINode* aNode, bool aClone, bool aDeep,
1315 nsNodeInfoManager* aNewNodeInfoManager,
1316 JS::Handle<JSObject*> aReparentScope, nsINode* aParent,
1317 mozilla::ErrorResult& aError);
1319 public:
1321 * Walks the node, its attributes and descendant nodes. If aNewNodeInfoManager
1322 * is not null, it is used to create new nodeinfos for the nodes. Also
1323 * reparents the XPConnect wrappers for the nodes into aReparentScope if
1324 * non-null.
1326 * @param aNewNodeInfoManager The nodeinfo manager to use to create new
1327 * nodeinfos for the node and its attributes and
1328 * descendants. May be null if the nodeinfos
1329 * shouldn't be changed.
1330 * @param aReparentScope New scope for the wrappers, or null if no reparenting
1331 * should be done.
1332 * @param aError The error, if any.
1334 void Adopt(nsNodeInfoManager* aNewNodeInfoManager,
1335 JS::Handle<JSObject*> aReparentScope,
1336 mozilla::ErrorResult& aError);
1339 * Clones the node, its attributes and, if aDeep is true, its descendant nodes
1340 * If aNewNodeInfoManager is not null, it is used to create new nodeinfos for
1341 * the clones.
1343 * @param aDeep If true the function will be called recursively on
1344 * descendants of the node
1345 * @param aNewNodeInfoManager The nodeinfo manager to use to create new
1346 * nodeinfos for the node and its attributes and
1347 * descendants. May be null if the nodeinfos
1348 * shouldn't be changed.
1349 * @param aError The error, if any.
1351 * @return The newly created node. Null in error conditions.
1353 already_AddRefed<nsINode> Clone(bool aDeep,
1354 nsNodeInfoManager* aNewNodeInfoManager,
1355 mozilla::ErrorResult& aError);
1358 * Clones this node. This needs to be overriden by all node classes. aNodeInfo
1359 * should be identical to this node's nodeInfo, except for the document which
1360 * may be different. When cloning an element, all attributes of the element
1361 * will be cloned. The children of the node will not be cloned.
1363 * @param aNodeInfo the nodeinfo to use for the clone
1364 * @param aResult the clone
1366 virtual nsresult Clone(mozilla::dom::NodeInfo*, nsINode** aResult) const = 0;
1368 // This class can be extended by subclasses that wish to store more
1369 // information in the slots.
1370 class nsSlots {
1371 public:
1372 nsSlots();
1374 // If needed we could remove the vtable pointer this dtor causes by
1375 // putting a DestroySlots function on nsINode
1376 virtual ~nsSlots();
1378 virtual void Traverse(nsCycleCollectionTraversalCallback&);
1379 virtual void Unlink(nsINode&);
1382 * A list of mutation observers
1384 mozilla::SafeDoublyLinkedList<nsIMutationObserver> mMutationObservers;
1387 * An object implementing NodeList for this content (childNodes)
1388 * @see NodeList
1389 * @see nsGenericHTMLElement::GetChildNodes
1391 RefPtr<nsAttrChildContentList> mChildNodes;
1394 * Weak reference to this node. This is cleared by the destructor of
1395 * nsNodeWeakReference.
1397 nsNodeWeakReference* MOZ_NON_OWNING_REF mWeakReference;
1400 * A set of ranges which are in the selection and which have this node as
1401 * their endpoints' closest common inclusive ancestor
1402 * (https://dom.spec.whatwg.org/#concept-tree-inclusive-ancestor). This is
1403 * a UniquePtr instead of just a LinkedList, because that prevents us from
1404 * pushing DOMSlots up to the next allocation bucket size, at the cost of
1405 * some complexity.
1407 mozilla::UniquePtr<mozilla::LinkedList<mozilla::dom::AbstractRange>>
1408 mClosestCommonInclusiveAncestorRanges;
1412 * Functions for managing flags and slots
1414 #ifdef DEBUG
1415 nsSlots* DebugGetSlots() { return Slots(); }
1416 #endif
1418 void SetFlags(FlagsType aFlagsToSet) {
1419 NS_ASSERTION(
1420 !(aFlagsToSet &
1421 (NODE_IS_NATIVE_ANONYMOUS_ROOT | NODE_IS_IN_NATIVE_ANONYMOUS_SUBTREE |
1422 NODE_DESCENDANTS_NEED_FRAMES | NODE_NEEDS_FRAME |
1423 NODE_HAS_BEEN_IN_UA_WIDGET)) ||
1424 IsContent(),
1425 "Flag only permitted on nsIContent nodes");
1426 nsWrapperCache::SetFlags(aFlagsToSet);
1429 void UnsetFlags(FlagsType aFlagsToUnset) {
1430 NS_ASSERTION(!(aFlagsToUnset & (NODE_HAS_BEEN_IN_UA_WIDGET |
1431 NODE_IS_NATIVE_ANONYMOUS_ROOT)),
1432 "Trying to unset write-only flags");
1433 nsWrapperCache::UnsetFlags(aFlagsToUnset);
1436 void SetEditableFlag(bool aEditable) {
1437 if (aEditable) {
1438 SetFlags(NODE_IS_EDITABLE);
1439 } else {
1440 UnsetFlags(NODE_IS_EDITABLE);
1444 inline bool IsEditable() const;
1447 * Check if this node is an editing host. For avoiding confusion, this always
1448 * returns false if the node is in the design mode document.
1450 inline bool IsEditingHost() const;
1453 * Check if this node is in design mode or not. When this returns true and:
1454 * - if this is a Document node, it's the design mode root.
1455 * - if this is a content node, it's connected, it's not in a shadow tree
1456 * (except shadow tree for UI widget and native anonymous subtree) and its
1457 * uncomposed document is in design mode.
1458 * Note that returning true does NOT mean the node or its children is
1459 * editable. E.g., when this node is in a shadow tree of a UA widget and its
1460 * host is in design mode.
1462 inline bool IsInDesignMode() const;
1465 * Returns true if |this| or any of its ancestors is native anonymous.
1467 bool IsInNativeAnonymousSubtree() const {
1468 return HasFlag(NODE_IS_IN_NATIVE_ANONYMOUS_SUBTREE);
1472 * If |this| or any ancestor is native anonymous, return the root of the
1473 * native anonymous subtree. Note that in case of nested native anonymous
1474 * content, this returns the innermost root, not the outermost.
1476 nsIContent* GetClosestNativeAnonymousSubtreeRoot() const {
1477 if (!IsInNativeAnonymousSubtree()) {
1478 MOZ_ASSERT(!HasBeenInUAWidget(), "UA widget implies anonymous");
1479 return nullptr;
1481 MOZ_ASSERT(IsContent(), "How did non-content end up in NAC?");
1482 if (HasBeenInUAWidget()) {
1483 // reinterpret_cast because in this header we don't know ShadowRoot is an
1484 // nsIContent. ShadowRoot constructor asserts this is correct.
1485 return reinterpret_cast<nsIContent*>(GetContainingShadow());
1487 for (const nsINode* node = this; node; node = node->GetParentNode()) {
1488 if (node->IsRootOfNativeAnonymousSubtree()) {
1489 return const_cast<nsINode*>(node)->AsContent();
1492 // FIXME(emilio): This should not happen, usually, but editor removes nodes
1493 // in native anonymous subtrees, and we don't clean nodes from the current
1494 // event content stack from ContentRemoved, so it can actually happen, see
1495 // bug 1510208.
1496 NS_WARNING("GetClosestNativeAnonymousSubtreeRoot on disconnected NAC!");
1497 return nullptr;
1501 * If |this| or any ancestor is native anonymous, return the parent of the
1502 * native anonymous subtree. Note that in case of nested native anonymous
1503 * content, this returns the parent or host of the innermost root, not the
1504 * outermost.
1506 nsIContent* GetClosestNativeAnonymousSubtreeRootParentOrHost() const {
1507 // We could put this in nsIContentInlines.h or such to avoid this
1508 // reinterpret_cast, but it doesn't seem worth it.
1509 const auto* root = reinterpret_cast<const nsINode*>(
1510 GetClosestNativeAnonymousSubtreeRoot());
1511 if (!root) {
1512 return nullptr;
1514 if (nsIContent* parent = root->GetParent()) {
1515 return parent;
1517 if (MOZ_UNLIKELY(root->IsInShadowTree())) {
1518 return root->DoGetShadowHost();
1520 return nullptr;
1524 * Gets the root of the node tree for this content if it is in a shadow tree.
1526 mozilla::dom::ShadowRoot* GetContainingShadow() const;
1528 * Gets the shadow host if this content is in a shadow tree. That is, the host
1529 * of |GetContainingShadow|, if its not null.
1531 * @return The shadow host, if this is in shadow tree, or null.
1533 mozilla::dom::Element* GetContainingShadowHost() const;
1535 bool IsInSVGUseShadowTree() const {
1536 return !!GetContainingSVGUseShadowHost();
1539 mozilla::dom::SVGUseElement* GetContainingSVGUseShadowHost() const {
1540 if (!IsInShadowTree()) {
1541 return nullptr;
1543 return DoGetContainingSVGUseShadowHost();
1546 // Whether this node has ever been part of a UA widget shadow tree.
1547 bool HasBeenInUAWidget() const { return HasFlag(NODE_HAS_BEEN_IN_UA_WIDGET); }
1549 // True for native anonymous content and for content in UA widgets.
1550 // Only nsIContent can fulfill this condition.
1551 bool ChromeOnlyAccess() const { return IsInNativeAnonymousSubtree(); }
1553 const nsIContent* GetChromeOnlyAccessSubtreeRootParent() const {
1554 return GetClosestNativeAnonymousSubtreeRootParentOrHost();
1557 bool IsInShadowTree() const { return HasFlag(NODE_IS_IN_SHADOW_TREE); }
1560 * Get whether this node is C++-generated anonymous content
1561 * @see nsIAnonymousContentCreator
1562 * @return whether this content is anonymous
1564 bool IsRootOfNativeAnonymousSubtree() const {
1565 NS_ASSERTION(
1566 !HasFlag(NODE_IS_NATIVE_ANONYMOUS_ROOT) || IsInNativeAnonymousSubtree(),
1567 "Some flags seem to be missing!");
1568 return HasFlag(NODE_IS_NATIVE_ANONYMOUS_ROOT);
1571 // Whether this node is the root of a ChromeOnlyAccess DOM subtree.
1572 bool IsRootOfChromeAccessOnlySubtree() const {
1573 return IsRootOfNativeAnonymousSubtree();
1576 /** Whether this is the container of a ::before pseudo-element. */
1577 bool IsGeneratedContentContainerForBefore() const {
1578 return IsRootOfNativeAnonymousSubtree() &&
1579 mNodeInfo->NameAtom() == nsGkAtoms::mozgeneratedcontentbefore;
1582 /** Whether this is the container of an ::after pseudo-element. */
1583 bool IsGeneratedContentContainerForAfter() const {
1584 return IsRootOfNativeAnonymousSubtree() &&
1585 mNodeInfo->NameAtom() == nsGkAtoms::mozgeneratedcontentafter;
1588 /** Whether this is the container of a ::marker pseudo-element. */
1589 bool IsGeneratedContentContainerForMarker() const {
1590 return IsRootOfNativeAnonymousSubtree() &&
1591 mNodeInfo->NameAtom() == nsGkAtoms::mozgeneratedcontentmarker;
1595 * Returns true if |this| node is the closest common inclusive ancestor
1596 * (https://dom.spec.whatwg.org/#concept-tree-inclusive-ancestor) of the
1597 * start/end nodes of a Range in a Selection or a descendant of such a common
1598 * ancestor. This node is definitely not selected when |false| is returned,
1599 * but it may or may not be selected when |true| is returned.
1601 bool IsMaybeSelected() const {
1602 return IsDescendantOfClosestCommonInclusiveAncestorForRangeInSelection() ||
1603 IsClosestCommonInclusiveAncestorForRangeInSelection();
1607 * Return true if any part of (this, aStartOffset) .. (this, aEndOffset)
1608 * overlaps any nsRange in
1609 * GetClosestCommonInclusiveAncestorForRangeInSelection ranges (i.e.
1610 * where this is a descendant of a range's common inclusive ancestor node).
1611 * If a nsRange starts in (this, aEndOffset) or if it ends in
1612 * (this, aStartOffset) then it is non-overlapping and the result is false
1613 * for that nsRange. Collapsed ranges always counts as non-overlapping.
1615 * @param aStartOffset has to be less or equal to aEndOffset.
1617 bool IsSelected(uint32_t aStartOffset, uint32_t aEndOffset) const;
1620 * Get the root element of the text editor associated with this node or the
1621 * root element of the text editor of the ancestor 'TextControlElement' if
1622 * this is in its native anonymous subtree. I.e., this returns anonymous
1623 * `<div>` element of a `TextEditor`. Note that this can be used only for
1624 * getting root content of `<input>` or `<textarea>`. I.e., this method
1625 * doesn't support HTML editors. Note that this may create a `TextEditor`
1626 * instance, and it means that the `TextEditor` may modify its native
1627 * anonymous subtree and may run selection listeners.
1629 MOZ_CAN_RUN_SCRIPT mozilla::dom::Element* GetAnonymousRootElementOfTextEditor(
1630 mozilla::TextEditor** aTextEditor = nullptr);
1633 * Get the nearest selection root, ie. the node that will be selected if the
1634 * user does "Select All" while the focus is in this node. Note that if this
1635 * node is not in an editor, the result comes from the nsFrameSelection that
1636 * is related to aPresShell, so the result might not be the ancestor of this
1637 * node. Be aware that if this node and the computed selection limiter are
1638 * not in same subtree, this returns the root content of the closeset subtree.
1640 MOZ_CAN_RUN_SCRIPT nsIContent* GetSelectionRootContent(
1641 mozilla::PresShell* aPresShell, bool aAllowCrossShadowBoundary = false);
1643 nsINodeList* ChildNodes();
1645 nsIContent* GetFirstChild() const { return mFirstChild; }
1647 nsIContent* GetLastChild() const;
1650 * Implementation is in Document.h, because it needs to cast from
1651 * Document* to nsINode*.
1653 Document* GetOwnerDocument() const;
1655 // TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230)
1656 MOZ_CAN_RUN_SCRIPT_BOUNDARY void Normalize();
1659 * Get the base URI for any relative URIs within this piece of
1660 * content. Generally, this is the document's base URI, but certain
1661 * content carries a local base for backward compatibility.
1663 * @return the base URI. May return null.
1665 virtual nsIURI* GetBaseURI(bool aTryUseXHRDocBaseURI = false) const = 0;
1666 nsIURI* GetBaseURIObject() const;
1669 * Return true if the node may be apz aware. There are two cases. One is that
1670 * the node is apz aware (such as HTMLInputElement with number type). The
1671 * other is that the node has apz aware listeners. This is a non-virtual
1672 * function which calls IsNodeApzAwareInternal only when the MayBeApzAware is
1673 * set. We check the details in IsNodeApzAwareInternal which may be overriden
1674 * by child classes
1676 bool IsNodeApzAware() const {
1677 return NodeMayBeApzAware() ? IsNodeApzAwareInternal() : false;
1681 * Override this function and set the flag MayBeApzAware in case the node has
1682 * to let APZC be aware of it. It's used when the node may handle the apz
1683 * aware events and may do preventDefault to stop APZC to do default actions.
1685 * For example, instead of scrolling page by APZ, we handle mouse wheel event
1686 * in HTMLInputElement with number type as increasing / decreasing its value.
1688 virtual bool IsNodeApzAwareInternal() const;
1690 void GetTextContent(nsAString& aTextContent, mozilla::OOMReporter& aError) {
1691 GetTextContentInternal(aTextContent, aError);
1693 void SetTextContent(const nsAString& aTextContent,
1694 nsIPrincipal* aSubjectPrincipal,
1695 mozilla::ErrorResult& aError) {
1696 SetTextContentInternal(aTextContent, aSubjectPrincipal, aError);
1698 void SetTextContent(const nsAString& aTextContent,
1699 mozilla::ErrorResult& aError) {
1700 SetTextContentInternal(aTextContent, nullptr, aError);
1703 mozilla::dom::Element* QuerySelector(const nsACString& aSelector,
1704 mozilla::ErrorResult& aResult);
1705 already_AddRefed<nsINodeList> QuerySelectorAll(const nsACString& aSelector,
1706 mozilla::ErrorResult& aResult);
1708 protected:
1709 // Document and ShadowRoot override this with its own (faster) version.
1710 // This should really only be called for elements and document fragments.
1711 mozilla::dom::Element* GetElementById(const nsAString& aId);
1713 void AppendChildToChildList(nsIContent* aKid);
1714 void InsertChildToChildList(nsIContent* aKid, nsIContent* aNextSibling);
1715 void DisconnectChild(nsIContent* aKid);
1717 public:
1718 void LookupPrefix(const nsAString& aNamespace, nsAString& aResult);
1719 bool IsDefaultNamespace(const nsAString& aNamespaceURI) {
1720 nsAutoString defaultNamespace;
1721 LookupNamespaceURI(u""_ns, defaultNamespace);
1722 return aNamespaceURI.Equals(defaultNamespace);
1724 void LookupNamespaceURI(const nsAString& aNamespacePrefix,
1725 nsAString& aNamespaceURI);
1727 nsIContent* GetNextSibling() const { return mNextSibling; }
1728 nsIContent* GetPreviousSibling() const;
1731 * Return true if the node is being removed from the parent, it means that
1732 * the node still knows the container which it's disconnected from, but the
1733 * node has already been removed from the child node chain of the container.
1734 * I.e., Return true between a call of DisconnectChild of the parent and
1735 * a call of UnbindFromTree of the node.
1737 bool IsBeingRemoved() const {
1738 return mParent && !mNextSibling && !mPreviousOrLastSibling;
1742 * Get the next node in the pre-order tree traversal of the DOM. If
1743 * aRoot is non-null, then it must be an ancestor of |this|
1744 * (possibly equal to |this|) and only nodes that are descendants of
1745 * aRoot, not including aRoot itself, will be returned. Returns
1746 * null if there are no more nodes to traverse.
1748 nsIContent* GetNextNode(const nsINode* aRoot = nullptr) const {
1749 return GetNextNodeImpl(aRoot, false);
1753 * Get the next node in the pre-order tree traversal of the DOM but ignoring
1754 * the children of this node. If aRoot is non-null, then it must be an
1755 * ancestor of |this| (possibly equal to |this|) and only nodes that are
1756 * descendants of aRoot, not including aRoot itself, will be returned.
1757 * Returns null if there are no more nodes to traverse.
1759 nsIContent* GetNextNonChildNode(const nsINode* aRoot = nullptr) const {
1760 return GetNextNodeImpl(aRoot, true);
1764 * Returns true if 'this' is either document or element or
1765 * document fragment and aOther is a descendant in the same
1766 * anonymous tree.
1768 bool Contains(const nsINode* aOther) const;
1770 bool UnoptimizableCCNode() const;
1773 * Fire a DOMNodeRemoved mutation event for all children of this node
1774 * TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230)
1776 MOZ_CAN_RUN_SCRIPT_BOUNDARY void FireNodeRemovedForChildren();
1778 void QueueDevtoolsAnonymousEvent(bool aIsRemove);
1780 private:
1781 mozilla::dom::SVGUseElement* DoGetContainingSVGUseShadowHost() const;
1783 nsIContent* GetNextNodeImpl(const nsINode* aRoot,
1784 const bool aSkipChildren) const {
1785 #ifdef DEBUG
1786 if (aRoot) {
1787 // TODO: perhaps nsINode::IsInclusiveDescendantOf could be used instead.
1788 const nsINode* cur = this;
1789 for (; cur; cur = cur->GetParentNode())
1790 if (cur == aRoot) break;
1791 NS_ASSERTION(cur, "aRoot not an ancestor of |this|?");
1793 #endif
1794 if (!aSkipChildren) {
1795 nsIContent* kid = GetFirstChild();
1796 if (kid) {
1797 return kid;
1800 if (this == aRoot) {
1801 return nullptr;
1803 const nsINode* cur = this;
1804 while (1) {
1805 nsIContent* next = cur->GetNextSibling();
1806 if (next) {
1807 return next;
1809 nsINode* parent = cur->GetParentNode();
1810 if (parent == aRoot) {
1811 return nullptr;
1813 cur = parent;
1815 MOZ_ASSERT_UNREACHABLE("How did we get here?");
1818 public:
1820 * Get the previous nsIContent in the pre-order tree traversal of the DOM. If
1821 * aRoot is non-null, then it must be an ancestor of |this|
1822 * (possibly equal to |this|) and only nsIContents that are descendants of
1823 * aRoot, including aRoot itself, will be returned. Returns
1824 * null if there are no more nsIContents to traverse.
1826 nsIContent* GetPrevNode(const nsINode* aRoot = nullptr) const {
1827 #ifdef DEBUG
1828 if (aRoot) {
1829 // TODO: perhaps nsINode::IsInclusiveDescendantOf could be used instead.
1830 const nsINode* cur = this;
1831 for (; cur; cur = cur->GetParentNode())
1832 if (cur == aRoot) break;
1833 NS_ASSERTION(cur, "aRoot not an ancestor of |this|?");
1835 #endif
1837 if (this == aRoot) {
1838 return nullptr;
1840 nsIContent* cur = this->GetParent();
1841 nsIContent* iter = this->GetPreviousSibling();
1842 while (iter) {
1843 cur = iter;
1844 iter = reinterpret_cast<nsINode*>(iter)->GetLastChild();
1846 return cur;
1850 * Boolean flags
1852 private:
1853 enum BooleanFlag {
1854 // Set if we're being used from -moz-element
1855 NodeHasRenderingObservers,
1856 // Set if our parent chain (including this node itself) terminates
1857 // in a document
1858 IsInDocument,
1859 // Set if we're part of the composed doc.
1860 // https://dom.spec.whatwg.org/#connected
1861 IsConnected,
1862 // Set if mParent is an nsIContent
1863 ParentIsContent,
1864 // Set if this node is an Element
1865 NodeIsElement,
1866 // Set if the element has a non-empty id attribute. This can in rare
1867 // cases lie for nsXMLElement, such as when the node has been moved between
1868 // documents with different id mappings.
1869 ElementHasID,
1870 // Set if the element might have a class.
1871 ElementMayHaveClass,
1872 // Set if the element might have inline style.
1873 ElementMayHaveStyle,
1874 // Set if the element has a name attribute set.
1875 ElementHasName,
1876 // Set if the element has a part attribute set.
1877 ElementHasPart,
1878 // Set if the element might have a contenteditable attribute set.
1879 ElementMayHaveContentEditableAttr,
1880 // Set if the node is the closest common inclusive ancestor of the start/end
1881 // nodes of a Range that is in a Selection.
1882 NodeIsClosestCommonInclusiveAncestorForRangeInSelection,
1883 // Set if the node is a descendant of a node with the above bit set.
1884 NodeIsDescendantOfClosestCommonInclusiveAncestorForRangeInSelection,
1885 // Set if CanSkipInCC check has been done for this subtree root.
1886 NodeIsCCMarkedRoot,
1887 // Maybe set if this node is in black subtree.
1888 NodeIsCCBlackTree,
1889 // Maybe set if the node is a root of a subtree
1890 // which needs to be kept in the purple buffer.
1891 NodeIsPurpleRoot,
1892 // Set if the element has some style states locked
1893 ElementHasLockedStyleStates,
1894 // Set if element has pointer locked
1895 ElementHasPointerLock,
1896 // Set if the node may have DOMMutationObserver attached to it.
1897 NodeMayHaveDOMMutationObserver,
1898 // Set if node is Content
1899 NodeIsContent,
1900 // Set if the node has animations or transitions
1901 ElementHasAnimations,
1902 // Set if node has a dir attribute with a valid value (ltr, rtl, or auto).
1903 // Note that we cannot compute this from the dir attribute event state
1904 // flags, because we can't use those to distinguish
1905 // <bdi dir="some-invalid-value"> and <bdi dir="auto">.
1906 NodeHasValidDirAttribute,
1907 // Set if this node, which must be a text node, might be responsible for
1908 // setting the directionality of a dir="auto" ancestor.
1909 NodeMaySetDirAuto,
1910 // Set if a node in the node's parent chain has dir=auto.
1911 NodeAncestorHasDirAuto,
1912 // Set if the node is handling a click.
1913 NodeHandlingClick,
1914 // Set if the element has a parser insertion mode other than "in body",
1915 // per the HTML5 "Parse state" section.
1916 ElementHasWeirdParserInsertionMode,
1917 // Parser sets this flag if it has notified about the node.
1918 ParserHasNotified,
1919 // Sets if the node is apz aware or we have apz aware listeners.
1920 MayBeApzAware,
1921 // Set if the element might have any kind of anonymous content children,
1922 // which would not be found through the element's children list.
1923 ElementMayHaveAnonymousChildren,
1924 // Set if element has CustomElementData.
1925 ElementHasCustomElementData,
1926 // Set if the element was created from prototype cache and
1927 // its l10n attributes haven't been changed.
1928 ElementCreatedFromPrototypeAndHasUnmodifiedL10n,
1929 // Guard value
1930 BooleanFlagCount
1933 void SetBoolFlag(BooleanFlag name, bool value) {
1934 static_assert(BooleanFlagCount <= 8 * sizeof(mBoolFlags),
1935 "Too many boolean flags");
1936 mBoolFlags = (mBoolFlags & ~(1 << name)) | (value << name);
1939 void SetBoolFlag(BooleanFlag name) {
1940 static_assert(BooleanFlagCount <= 8 * sizeof(mBoolFlags),
1941 "Too many boolean flags");
1942 mBoolFlags |= (1 << name);
1945 void ClearBoolFlag(BooleanFlag name) {
1946 static_assert(BooleanFlagCount <= 8 * sizeof(mBoolFlags),
1947 "Too many boolean flags");
1948 mBoolFlags &= ~(1 << name);
1951 bool GetBoolFlag(BooleanFlag name) const {
1952 static_assert(BooleanFlagCount <= 8 * sizeof(mBoolFlags),
1953 "Too many boolean flags");
1954 return mBoolFlags & (1 << name);
1957 public:
1958 bool HasRenderingObservers() const {
1959 return GetBoolFlag(NodeHasRenderingObservers);
1961 void SetHasRenderingObservers(bool aValue) {
1962 SetBoolFlag(NodeHasRenderingObservers, aValue);
1964 bool IsContent() const { return GetBoolFlag(NodeIsContent); }
1965 bool HasID() const { return GetBoolFlag(ElementHasID); }
1966 bool MayHaveClass() const { return GetBoolFlag(ElementMayHaveClass); }
1967 void SetMayHaveClass() { SetBoolFlag(ElementMayHaveClass); }
1968 bool MayHaveStyle() const { return GetBoolFlag(ElementMayHaveStyle); }
1969 bool HasName() const { return GetBoolFlag(ElementHasName); }
1970 bool HasPartAttribute() const { return GetBoolFlag(ElementHasPart); }
1971 bool MayHaveContentEditableAttr() const {
1972 return GetBoolFlag(ElementMayHaveContentEditableAttr);
1975 * https://dom.spec.whatwg.org/#concept-tree-inclusive-ancestor
1977 bool IsClosestCommonInclusiveAncestorForRangeInSelection() const {
1978 return GetBoolFlag(NodeIsClosestCommonInclusiveAncestorForRangeInSelection);
1981 * https://dom.spec.whatwg.org/#concept-tree-inclusive-ancestor
1983 void SetClosestCommonInclusiveAncestorForRangeInSelection() {
1984 SetBoolFlag(NodeIsClosestCommonInclusiveAncestorForRangeInSelection);
1987 * https://dom.spec.whatwg.org/#concept-tree-inclusive-ancestor
1989 void ClearClosestCommonInclusiveAncestorForRangeInSelection() {
1990 ClearBoolFlag(NodeIsClosestCommonInclusiveAncestorForRangeInSelection);
1993 * https://dom.spec.whatwg.org/#concept-tree-inclusive-ancestor
1995 bool IsDescendantOfClosestCommonInclusiveAncestorForRangeInSelection() const {
1996 return GetBoolFlag(
1997 NodeIsDescendantOfClosestCommonInclusiveAncestorForRangeInSelection);
2000 * https://dom.spec.whatwg.org/#concept-tree-inclusive-ancestor
2002 void SetDescendantOfClosestCommonInclusiveAncestorForRangeInSelection() {
2003 SetBoolFlag(
2004 NodeIsDescendantOfClosestCommonInclusiveAncestorForRangeInSelection);
2007 * https://dom.spec.whatwg.org/#concept-tree-inclusive-ancestor
2009 void ClearDescendantOfClosestCommonInclusiveAncestorForRangeInSelection() {
2010 ClearBoolFlag(
2011 NodeIsDescendantOfClosestCommonInclusiveAncestorForRangeInSelection);
2014 void SetCCMarkedRoot(bool aValue) { SetBoolFlag(NodeIsCCMarkedRoot, aValue); }
2015 bool CCMarkedRoot() const { return GetBoolFlag(NodeIsCCMarkedRoot); }
2016 void SetInCCBlackTree(bool aValue) { SetBoolFlag(NodeIsCCBlackTree, aValue); }
2017 bool InCCBlackTree() const { return GetBoolFlag(NodeIsCCBlackTree); }
2018 void SetIsPurpleRoot(bool aValue) { SetBoolFlag(NodeIsPurpleRoot, aValue); }
2019 bool IsPurpleRoot() const { return GetBoolFlag(NodeIsPurpleRoot); }
2020 bool MayHaveDOMMutationObserver() {
2021 return GetBoolFlag(NodeMayHaveDOMMutationObserver);
2023 void SetMayHaveDOMMutationObserver() {
2024 SetBoolFlag(NodeMayHaveDOMMutationObserver, true);
2026 bool HasListenerManager() { return HasFlag(NODE_HAS_LISTENERMANAGER); }
2027 bool HasPointerLock() const { return GetBoolFlag(ElementHasPointerLock); }
2028 void SetPointerLock() { SetBoolFlag(ElementHasPointerLock); }
2029 void ClearPointerLock() { ClearBoolFlag(ElementHasPointerLock); }
2030 bool MayHaveAnimations() const { return GetBoolFlag(ElementHasAnimations); }
2031 void SetMayHaveAnimations() { SetBoolFlag(ElementHasAnimations); }
2032 void ClearMayHaveAnimations() { ClearBoolFlag(ElementHasAnimations); }
2033 void SetHasValidDir() { SetBoolFlag(NodeHasValidDirAttribute); }
2034 void ClearHasValidDir() { ClearBoolFlag(NodeHasValidDirAttribute); }
2035 bool HasValidDir() const { return GetBoolFlag(NodeHasValidDirAttribute); }
2036 void SetMaySetDirAuto() {
2037 // FIXME(bug 1881225): dir=auto should probably work on CDATA too.
2038 MOZ_ASSERT(NodeType() == TEXT_NODE);
2039 SetBoolFlag(NodeMaySetDirAuto);
2041 bool MaySetDirAuto() const {
2042 MOZ_ASSERT(NodeType() == TEXT_NODE);
2043 return GetBoolFlag(NodeMaySetDirAuto);
2045 void ClearMaySetDirAuto() {
2046 MOZ_ASSERT(NodeType() == TEXT_NODE);
2047 ClearBoolFlag(NodeMaySetDirAuto);
2049 void SetAncestorHasDirAuto() { SetBoolFlag(NodeAncestorHasDirAuto); }
2050 void ClearAncestorHasDirAuto() { ClearBoolFlag(NodeAncestorHasDirAuto); }
2051 bool AncestorHasDirAuto() const {
2052 return GetBoolFlag(NodeAncestorHasDirAuto);
2055 // Implemented in nsIContentInlines.h.
2056 inline bool NodeOrAncestorHasDirAuto() const;
2058 void SetParserHasNotified() { SetBoolFlag(ParserHasNotified); };
2059 bool HasParserNotified() { return GetBoolFlag(ParserHasNotified); }
2061 void SetMayBeApzAware() { SetBoolFlag(MayBeApzAware); }
2062 bool NodeMayBeApzAware() const { return GetBoolFlag(MayBeApzAware); }
2064 void SetMayHaveAnonymousChildren() {
2065 SetBoolFlag(ElementMayHaveAnonymousChildren);
2067 bool MayHaveAnonymousChildren() const {
2068 return GetBoolFlag(ElementMayHaveAnonymousChildren);
2071 void SetHasCustomElementData() { SetBoolFlag(ElementHasCustomElementData); }
2072 bool HasCustomElementData() const {
2073 return GetBoolFlag(ElementHasCustomElementData);
2076 void SetElementCreatedFromPrototypeAndHasUnmodifiedL10n() {
2077 SetBoolFlag(ElementCreatedFromPrototypeAndHasUnmodifiedL10n);
2079 bool HasElementCreatedFromPrototypeAndHasUnmodifiedL10n() {
2080 return GetBoolFlag(ElementCreatedFromPrototypeAndHasUnmodifiedL10n);
2082 void ClearElementCreatedFromPrototypeAndHasUnmodifiedL10n() {
2083 ClearBoolFlag(ElementCreatedFromPrototypeAndHasUnmodifiedL10n);
2086 mozilla::dom::ShadowRoot* GetShadowRoot() const;
2088 // Return the shadow root of the node if it is a shadow host and
2089 // it meets the requirements for being a shadow host of a selection.
2090 // For example, <details>, <video> and <use> elements are not valid
2091 // shadow host for selection.
2092 mozilla::dom::ShadowRoot* GetShadowRootForSelection() const;
2094 protected:
2095 void SetParentIsContent(bool aValue) { SetBoolFlag(ParentIsContent, aValue); }
2096 void SetIsInDocument() { SetBoolFlag(IsInDocument); }
2097 void ClearInDocument() { ClearBoolFlag(IsInDocument); }
2098 void SetIsConnected(bool aConnected) { SetBoolFlag(IsConnected, aConnected); }
2099 void SetNodeIsContent() { SetBoolFlag(NodeIsContent); }
2100 void SetIsElement() { SetBoolFlag(NodeIsElement); }
2101 void SetHasID() { SetBoolFlag(ElementHasID); }
2102 void ClearHasID() { ClearBoolFlag(ElementHasID); }
2103 void SetMayHaveStyle() { SetBoolFlag(ElementMayHaveStyle); }
2104 void SetHasName() { SetBoolFlag(ElementHasName); }
2105 void ClearHasName() { ClearBoolFlag(ElementHasName); }
2106 void SetHasPartAttribute(bool aPart) { SetBoolFlag(ElementHasPart, aPart); }
2107 void SetMayHaveContentEditableAttr() {
2108 SetBoolFlag(ElementMayHaveContentEditableAttr);
2110 void SetHasLockedStyleStates() { SetBoolFlag(ElementHasLockedStyleStates); }
2111 void ClearHasLockedStyleStates() {
2112 ClearBoolFlag(ElementHasLockedStyleStates);
2114 bool HasLockedStyleStates() const {
2115 return GetBoolFlag(ElementHasLockedStyleStates);
2117 void SetHasWeirdParserInsertionMode() {
2118 SetBoolFlag(ElementHasWeirdParserInsertionMode);
2120 bool HasWeirdParserInsertionMode() const {
2121 return GetBoolFlag(ElementHasWeirdParserInsertionMode);
2123 bool HandlingClick() const { return GetBoolFlag(NodeHandlingClick); }
2124 void SetHandlingClick() { SetBoolFlag(NodeHandlingClick); }
2125 void ClearHandlingClick() { ClearBoolFlag(NodeHandlingClick); }
2127 void SetSubtreeRootPointer(nsINode* aSubtreeRoot) {
2128 NS_ASSERTION(aSubtreeRoot, "aSubtreeRoot can never be null!");
2129 NS_ASSERTION(!(IsContent() && IsInUncomposedDoc()) && !IsInShadowTree(),
2130 "Shouldn't be here!");
2131 mSubtreeRoot = aSubtreeRoot;
2134 void ClearSubtreeRootPointer() { mSubtreeRoot = nullptr; }
2136 public:
2137 // Makes nsINode object to keep aObject alive.
2138 void BindObject(nsISupports* aObject);
2139 // After calling UnbindObject nsINode object doesn't keep
2140 // aObject alive anymore.
2141 void UnbindObject(nsISupports* aObject);
2143 void GenerateXPath(nsAString& aResult);
2145 already_AddRefed<mozilla::dom::AccessibleNode> GetAccessibleNode();
2148 * Returns the length of this node, as specified at
2149 * <http://dvcs.w3.org/hg/domcore/raw-file/tip/Overview.html#concept-node-length>
2151 uint32_t Length() const;
2153 void GetNodeName(mozilla::dom::DOMString& aNodeName) {
2154 const nsString& nodeName = NodeName();
2155 aNodeName.SetKnownLiveString(nodeName);
2157 [[nodiscard]] nsresult GetBaseURI(nsAString& aBaseURI) const;
2158 // Return the base URI for the document.
2159 // The returned value may differ if the document is loaded via XHR, and
2160 // when accessed from chrome privileged script and
2161 // from content privileged script for compatibility.
2162 void GetBaseURIFromJS(nsAString& aBaseURI, CallerType aCallerType,
2163 ErrorResult& aRv) const;
2164 bool HasChildNodes() const { return HasChildren(); }
2166 // See nsContentUtils::PositionIsBefore for aThisIndex and aOtherIndex usage.
2167 uint16_t CompareDocumentPosition(
2168 nsINode& aOther, mozilla::Maybe<uint32_t>* aThisIndex = nullptr,
2169 mozilla::Maybe<uint32_t>* aOtherIndex = nullptr) const;
2170 void GetNodeValue(nsAString& aNodeValue) { GetNodeValueInternal(aNodeValue); }
2171 void SetNodeValue(const nsAString& aNodeValue, mozilla::ErrorResult& aError) {
2172 SetNodeValueInternal(aNodeValue, aError);
2174 virtual void GetNodeValueInternal(nsAString& aNodeValue);
2175 virtual void SetNodeValueInternal(const nsAString& aNodeValue,
2176 mozilla::ErrorResult& aError) {
2177 // The DOM spec says that when nodeValue is defined to be null "setting it
2178 // has no effect", so we don't throw an exception.
2180 void EnsurePreInsertionValidity(nsINode& aNewChild, nsINode* aRefChild,
2181 mozilla::ErrorResult& aError);
2182 nsINode* InsertBefore(nsINode& aNode, nsINode* aChild,
2183 mozilla::ErrorResult& aError) {
2184 return ReplaceOrInsertBefore(false, &aNode, aChild, aError);
2188 * See <https://dom.spec.whatwg.org/#dom-node-appendchild>.
2190 nsINode* AppendChild(nsINode& aNode, mozilla::ErrorResult& aError) {
2191 return InsertBefore(aNode, nullptr, aError);
2194 nsINode* ReplaceChild(nsINode& aNode, nsINode& aChild,
2195 mozilla::ErrorResult& aError) {
2196 return ReplaceOrInsertBefore(true, &aNode, &aChild, aError);
2198 // TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230)
2199 MOZ_CAN_RUN_SCRIPT_BOUNDARY nsINode* RemoveChild(
2200 nsINode& aChild, mozilla::ErrorResult& aError);
2201 already_AddRefed<nsINode> CloneNode(bool aDeep, mozilla::ErrorResult& aError);
2202 bool IsSameNode(nsINode* aNode);
2203 bool IsEqualNode(nsINode* aNode);
2204 void GetNamespaceURI(nsAString& aNamespaceURI) const {
2205 mNodeInfo->GetNamespaceURI(aNamespaceURI);
2207 #ifdef MOZILLA_INTERNAL_API
2208 void GetPrefix(nsAString& aPrefix) { mNodeInfo->GetPrefix(aPrefix); }
2209 #endif
2210 void GetLocalName(mozilla::dom::DOMString& aLocalName) const {
2211 const nsString& localName = LocalName();
2212 aLocalName.SetKnownLiveString(localName);
2215 nsDOMAttributeMap* GetAttributes();
2217 // Helper method to remove this node from its parent. This is not exposed
2218 // through WebIDL.
2219 // Only call this if the node has a parent node.
2220 nsresult RemoveFromParent() {
2221 nsINode* parent = GetParentNode();
2222 mozilla::ErrorResult rv;
2223 parent->RemoveChild(*this, rv);
2224 return rv.StealNSResult();
2227 // ChildNode methods
2228 inline mozilla::dom::Element* GetPreviousElementSibling() const;
2229 inline mozilla::dom::Element* GetNextElementSibling() const;
2231 MOZ_CAN_RUN_SCRIPT void Before(const Sequence<OwningNodeOrString>& aNodes,
2232 ErrorResult& aRv);
2233 MOZ_CAN_RUN_SCRIPT void After(const Sequence<OwningNodeOrString>& aNodes,
2234 ErrorResult& aRv);
2235 MOZ_CAN_RUN_SCRIPT void ReplaceWith(
2236 const Sequence<OwningNodeOrString>& aNodes, ErrorResult& aRv);
2238 * Remove this node from its parent, if any.
2240 void Remove();
2242 // ParentNode methods
2243 mozilla::dom::Element* GetFirstElementChild() const;
2244 mozilla::dom::Element* GetLastElementChild() const;
2246 already_AddRefed<nsIHTMLCollection> GetElementsByAttribute(
2247 const nsAString& aAttribute, const nsAString& aValue);
2248 already_AddRefed<nsIHTMLCollection> GetElementsByAttributeNS(
2249 const nsAString& aNamespaceURI, const nsAString& aAttribute,
2250 const nsAString& aValue, ErrorResult& aRv);
2252 MOZ_CAN_RUN_SCRIPT void Prepend(const Sequence<OwningNodeOrString>& aNodes,
2253 ErrorResult& aRv);
2254 MOZ_CAN_RUN_SCRIPT void Append(const Sequence<OwningNodeOrString>& aNodes,
2255 ErrorResult& aRv);
2256 MOZ_CAN_RUN_SCRIPT void ReplaceChildren(
2257 const Sequence<OwningNodeOrString>& aNodes, ErrorResult& aRv);
2258 MOZ_CAN_RUN_SCRIPT void ReplaceChildren(nsINode* aNode, ErrorResult& aRv);
2260 void GetBoxQuads(const BoxQuadOptions& aOptions,
2261 nsTArray<RefPtr<DOMQuad>>& aResult, CallerType aCallerType,
2262 ErrorResult& aRv);
2264 void GetBoxQuadsFromWindowOrigin(const BoxQuadOptions& aOptions,
2265 nsTArray<RefPtr<DOMQuad>>& aResult,
2266 ErrorResult& aRv);
2268 already_AddRefed<DOMQuad> ConvertQuadFromNode(
2269 DOMQuad& aQuad, const TextOrElementOrDocument& aFrom,
2270 const ConvertCoordinateOptions& aOptions, CallerType aCallerType,
2271 ErrorResult& aRv);
2272 already_AddRefed<DOMQuad> ConvertRectFromNode(
2273 DOMRectReadOnly& aRect, const TextOrElementOrDocument& aFrom,
2274 const ConvertCoordinateOptions& aOptions, CallerType aCallerType,
2275 ErrorResult& aRv);
2276 already_AddRefed<DOMPoint> ConvertPointFromNode(
2277 const DOMPointInit& aPoint, const TextOrElementOrDocument& aFrom,
2278 const ConvertCoordinateOptions& aOptions, CallerType aCallerType,
2279 ErrorResult& aRv);
2282 * See nsSlots::mClosestCommonInclusiveAncestorRanges.
2284 const mozilla::LinkedList<mozilla::dom::AbstractRange>*
2285 GetExistingClosestCommonInclusiveAncestorRanges() const {
2286 if (!HasSlots()) {
2287 return nullptr;
2289 return GetExistingSlots()->mClosestCommonInclusiveAncestorRanges.get();
2293 * See nsSlots::mClosestCommonInclusiveAncestorRanges.
2295 mozilla::LinkedList<mozilla::dom::AbstractRange>*
2296 GetExistingClosestCommonInclusiveAncestorRanges() {
2297 if (!HasSlots()) {
2298 return nullptr;
2300 return GetExistingSlots()->mClosestCommonInclusiveAncestorRanges.get();
2304 * See nsSlots::mClosestCommonInclusiveAncestorRanges.
2306 mozilla::UniquePtr<mozilla::LinkedList<mozilla::dom::AbstractRange>>&
2307 GetClosestCommonInclusiveAncestorRangesPtr() {
2308 return Slots()->mClosestCommonInclusiveAncestorRanges;
2311 nsIWeakReference* GetExistingWeakReference() {
2312 return HasSlots() ? GetExistingSlots()->mWeakReference : nullptr;
2315 protected:
2316 // Override this function to create a custom slots class.
2317 // Must not return null.
2318 virtual nsINode::nsSlots* CreateSlots();
2320 bool HasSlots() const { return mSlots != nullptr; }
2322 nsSlots* GetExistingSlots() const { return mSlots; }
2324 nsSlots* Slots() {
2325 if (!HasSlots()) {
2326 mSlots = CreateSlots();
2327 MOZ_ASSERT(mSlots);
2329 return GetExistingSlots();
2333 * Invalidate cached child array inside mChildNodes
2334 * of type nsParentNodeChildContentList.
2336 void InvalidateChildNodes();
2338 virtual void GetTextContentInternal(nsAString& aTextContent,
2339 mozilla::OOMReporter& aError);
2340 virtual void SetTextContentInternal(const nsAString& aTextContent,
2341 nsIPrincipal* aSubjectPrincipal,
2342 mozilla::ErrorResult& aError) {}
2344 void EnsurePreInsertionValidity1(mozilla::ErrorResult& aError);
2345 void EnsurePreInsertionValidity2(bool aReplace, nsINode& aNewChild,
2346 nsINode* aRefChild,
2347 mozilla::ErrorResult& aError);
2348 // TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230)
2349 MOZ_CAN_RUN_SCRIPT_BOUNDARY nsINode* ReplaceOrInsertBefore(
2350 bool aReplace, nsINode* aNewChild, nsINode* aRefChild,
2351 mozilla::ErrorResult& aError);
2354 * Returns the Element that should be used for resolving namespaces
2355 * on this node (ie the ownerElement for attributes, the documentElement for
2356 * documents, the node itself for elements and for other nodes the parentNode
2357 * if it is an element).
2359 virtual mozilla::dom::Element* GetNameSpaceElement() = 0;
2362 * Parse the given selector string into a servo SelectorList.
2364 * Never returns null if aRv is not failing.
2366 * Note that the selector list returned here is owned by the owner doc's
2367 * selector cache.
2369 const mozilla::StyleSelectorList* ParseSelectorList(
2370 const nsACString& aSelectorString, mozilla::ErrorResult&);
2372 public:
2373 /* Event stuff that documents and elements share.
2375 Note that we include DOCUMENT_ONLY_EVENT events here so that we
2376 can forward all the document stuff to this implementation.
2378 #define EVENT(name_, id_, type_, struct_) \
2379 mozilla::dom::EventHandlerNonNull* GetOn##name_() { \
2380 return GetEventHandler(nsGkAtoms::on##name_); \
2382 void SetOn##name_(mozilla::dom::EventHandlerNonNull* handler) { \
2383 SetEventHandler(nsGkAtoms::on##name_, handler); \
2385 #define TOUCH_EVENT EVENT
2386 #define DOCUMENT_ONLY_EVENT EVENT
2387 #include "mozilla/EventNameList.h"
2388 #undef DOCUMENT_ONLY_EVENT
2389 #undef TOUCH_EVENT
2390 #undef EVENT
2392 NodeSelectorFlags GetSelectorFlags() const {
2393 return static_cast<NodeSelectorFlags>(mSelectorFlags.Get());
2396 protected:
2397 static bool Traverse(nsINode* tmp, nsCycleCollectionTraversalCallback& cb);
2398 static void Unlink(nsINode* tmp);
2400 RefPtr<mozilla::dom::NodeInfo> mNodeInfo;
2402 // mParent is an owning ref most of the time, except for the case of document
2403 // nodes, so it cannot be represented by nsCOMPtr, so mark is as
2404 // MOZ_OWNING_REF.
2405 nsINode* MOZ_OWNING_REF mParent;
2407 private:
2408 #ifndef BOOL_FLAGS_ON_WRAPPER_CACHE
2409 // Boolean flags.
2410 uint32_t mBoolFlags;
2411 #endif
2413 mozilla::RustCell<uint32_t> mSelectorFlags{0};
2415 uint32_t mChildCount;
2417 protected:
2418 // mNextSibling and mFirstChild are strong references while
2419 // mPreviousOrLastSibling is a weak ref. |mFirstChild->mPreviousOrLastSibling|
2420 // points to the last child node.
2421 nsCOMPtr<nsIContent> mFirstChild;
2422 nsCOMPtr<nsIContent> mNextSibling;
2423 nsIContent* MOZ_NON_OWNING_REF mPreviousOrLastSibling;
2425 union {
2426 // Pointer to our primary frame. Might be null.
2427 nsIFrame* mPrimaryFrame;
2429 // Pointer to the root of our subtree. Might be null.
2430 // This reference is non-owning and safe, since it either points to the
2431 // object itself, or is reset by ClearSubtreeRootPointer.
2432 nsINode* MOZ_NON_OWNING_REF mSubtreeRoot;
2435 // Storage for more members that are usually not needed; allocated lazily.
2436 nsSlots* mSlots;
2439 NON_VIRTUAL_ADDREF_RELEASE(nsINode)
2441 inline nsINode* mozilla::dom::EventTarget::GetAsNode() {
2442 return IsNode() ? AsNode() : nullptr;
2445 inline const nsINode* mozilla::dom::EventTarget::GetAsNode() const {
2446 return const_cast<mozilla::dom::EventTarget*>(this)->GetAsNode();
2449 inline nsINode* mozilla::dom::EventTarget::AsNode() {
2450 MOZ_DIAGNOSTIC_ASSERT(IsNode());
2451 return static_cast<nsINode*>(this);
2454 inline const nsINode* mozilla::dom::EventTarget::AsNode() const {
2455 MOZ_DIAGNOSTIC_ASSERT(IsNode());
2456 return static_cast<const nsINode*>(this);
2459 // Useful inline function for getting a node given an nsIContent and a Document.
2460 // Returns the first argument cast to nsINode if it is non-null, otherwise
2461 // returns the second (which may be null). We use type variables instead of
2462 // nsIContent* and Document* because the actual types must be
2463 // known for the cast to work.
2464 template <class C, class D>
2465 inline nsINode* NODE_FROM(C& aContent, D& aDocument) {
2466 if (aContent) return static_cast<nsINode*>(aContent);
2467 return static_cast<nsINode*>(aDocument);
2470 NS_DEFINE_STATIC_IID_ACCESSOR(nsINode, NS_INODE_IID)
2472 inline nsISupports* ToSupports(nsINode* aPointer) { return aPointer; }
2474 // Some checks are faster to do on nsIContent or Element than on
2475 // nsINode, so spit out FromNode versions taking those types too.
2476 #define NS_IMPL_FROMNODE_GENERIC(_class, _check, _const) \
2477 template <typename T> \
2478 static auto FromNode(_const T& aNode) \
2479 -> decltype(static_cast<_const _class*>(&aNode)) { \
2480 return aNode._check ? static_cast<_const _class*>(&aNode) : nullptr; \
2482 template <typename T> \
2483 static _const _class* FromNode(_const T* aNode) { \
2484 return FromNode(*aNode); \
2486 template <typename T> \
2487 static _const _class* FromNodeOrNull(_const T* aNode) { \
2488 return aNode ? FromNode(*aNode) : nullptr; \
2490 template <typename T> \
2491 static auto FromEventTarget(_const T& aEventTarget) \
2492 -> decltype(static_cast<_const _class*>(&aEventTarget)) { \
2493 return aEventTarget.IsNode() && aEventTarget.AsNode()->_check \
2494 ? static_cast<_const _class*>(&aEventTarget) \
2495 : nullptr; \
2497 template <typename T> \
2498 static _const _class* FromEventTarget(_const T* aEventTarget) { \
2499 return FromEventTarget(*aEventTarget); \
2501 template <typename T> \
2502 static _const _class* FromEventTargetOrNull(_const T* aEventTarget) { \
2503 return aEventTarget ? FromEventTarget(*aEventTarget) : nullptr; \
2506 #define NS_IMPL_FROMNODE_HELPER(_class, _check) \
2507 NS_IMPL_FROMNODE_GENERIC(_class, _check, ) \
2508 NS_IMPL_FROMNODE_GENERIC(_class, _check, const) \
2510 template <typename T> \
2511 static _class* FromNode(T&& aNode) { \
2512 /* We need the double-cast in case aNode is a smartptr. Those */ \
2513 /* can cast to superclasses of the type they're templated on, */ \
2514 /* but not directly to subclasses. */ \
2515 return aNode->_check ? static_cast<_class*>(static_cast<nsINode*>(aNode)) \
2516 : nullptr; \
2518 template <typename T> \
2519 static _class* FromNodeOrNull(T&& aNode) { \
2520 return aNode ? FromNode(aNode) : nullptr; \
2522 template <typename T> \
2523 static _class* FromEventTarget(T&& aEventTarget) { \
2524 /* We need the double-cast in case aEventTarget is a smartptr. Those */ \
2525 /* can cast to superclasses of the type they're templated on, */ \
2526 /* but not directly to subclasses. */ \
2527 return aEventTarget->IsNode() && aEventTarget->AsNode()->_check \
2528 ? static_cast<_class*>(static_cast<EventTarget*>(aEventTarget)) \
2529 : nullptr; \
2531 template <typename T> \
2532 static _class* FromEventTargetOrNull(T&& aEventTarget) { \
2533 return aEventTarget ? FromEventTarget(aEventTarget) : nullptr; \
2536 #define NS_IMPL_FROMNODE(_class, _nsid) \
2537 NS_IMPL_FROMNODE_HELPER(_class, IsInNamespace(_nsid))
2539 #define NS_IMPL_FROMNODE_WITH_TAG(_class, _nsid, _tag) \
2540 NS_IMPL_FROMNODE_HELPER(_class, NodeInfo()->Equals(nsGkAtoms::_tag, _nsid))
2542 #define NS_IMPL_FROMNODE_HTML_WITH_TAG(_class, _tag) \
2543 NS_IMPL_FROMNODE_WITH_TAG(_class, kNameSpaceID_XHTML, _tag)
2545 #endif /* nsINode_h___ */