Bug 1852740: add tests for the `fetchpriority` attribute in Link headers. r=necko...
[gecko.git] / dom / base / nsINode.h
blobbf84562635cf6655567a3e9fb1640178193f0507
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 /// A child of this node might be matched by :nth-child(.. of <selector>) or
196 /// :nth-last-child(.. of <selector>). If a DOM mutation may have caused the
197 /// selector to either match or no longer match that child, the child's
198 /// siblings are restyled.
199 HasSlowSelectorNthOf = 1 << 4,
201 /// Set of selector flags that may trigger a restyle on DOM append, with
202 /// restyle on siblings or a single parent (And perhaps their subtrees).
203 AllSimpleRestyleFlagsForAppend = HasEmptySelector | HasSlowSelector |
204 HasEdgeChildSelector | HasSlowSelectorNthOf,
206 /// Set of selector flags that may trigger a restyle as a result of any
207 /// DOM mutation.
208 AllSimpleRestyleFlags =
209 AllSimpleRestyleFlagsForAppend | HasSlowSelectorLaterSiblings,
211 // This node was evaluated as an anchor for a relative selector.
212 RelativeSelectorAnchor = 1 << 5,
214 // This node was evaluated as an anchor for a relative selector, and that
215 // relative selector was not the subject of the overall selector.
216 RelativeSelectorAnchorNonSubject = 1 << 6,
218 // This node's sibling(s) performed a relative selector search to this node.
219 RelativeSelectorSearchDirectionSibling = 1 << 7,
221 // This node's ancestor(s) performed a relative selector search to this node.
222 RelativeSelectorSearchDirectionAncestor = 1 << 8,
224 // This node's sibling(s) and ancestor(s), and/or this node's ancestor's
225 // sibling(s) performed a relative selector search to this node.
226 RelativeSelectorSearchDirectionAncestorSibling =
227 RelativeSelectorSearchDirectionSibling |
228 RelativeSelectorSearchDirectionAncestor,
231 MOZ_MAKE_ENUM_CLASS_BITWISE_OPERATORS(NodeSelectorFlags);
233 // Make sure we have space for our bits
234 #define ASSERT_NODE_FLAGS_SPACE(n) \
235 static_assert(WRAPPER_CACHE_FLAGS_BITS_USED + (n) <= \
236 sizeof(nsWrapperCache::FlagsType) * 8, \
237 "Not enough space for our bits")
238 ASSERT_NODE_FLAGS_SPACE(NODE_TYPE_SPECIFIC_BITS_OFFSET);
241 * Class used to detect unexpected mutations. To use the class create an
242 * nsMutationGuard on the stack before unexpected mutations could occur.
243 * You can then at any time call Mutated to check if any unexpected mutations
244 * have occurred.
246 class nsMutationGuard {
247 public:
248 nsMutationGuard() { mStartingGeneration = sGeneration; }
251 * Returns true if any unexpected mutations have occurred. You can pass in
252 * an 8-bit ignore count to ignore a number of expected mutations.
254 * We don't need to care about overflow because subtraction of uint64_t's is
255 * finding the difference between two elements of the group Z < 2^64. Once
256 * we know the difference between two elements we only need to check that is
257 * less than the given number of mutations to know less than that many
258 * mutations occured. Assuming constant 1ns mutations it would take 584
259 * years for sGeneration to fully wrap around so we can ignore a guard living
260 * through a full wrap around.
262 bool Mutated(uint8_t aIgnoreCount) {
263 return (sGeneration - mStartingGeneration) > aIgnoreCount;
266 // This function should be called whenever a mutation that we want to keep
267 // track of happen. For now this is only done when children are added or
268 // removed, but we might do it for attribute changes too in the future.
269 static void DidMutate() { sGeneration++; }
271 private:
272 // This is the value sGeneration had when the guard was constructed.
273 uint64_t mStartingGeneration;
275 // This value is incremented on every mutation, for the life of the process.
276 static uint64_t sGeneration;
280 * A class that implements nsIWeakReference
282 class nsNodeWeakReference final : public nsIWeakReference {
283 public:
284 explicit nsNodeWeakReference(nsINode* aNode);
286 // nsISupports
287 NS_DECL_ISUPPORTS
289 // nsIWeakReference
290 NS_DECL_NSIWEAKREFERENCE
292 void NoticeNodeDestruction() { mObject = nullptr; }
294 private:
295 ~nsNodeWeakReference();
298 // This should be used for any nsINode sub-class that has fields of its own
299 // that it needs to measure; any sub-class that doesn't use it will inherit
300 // AddSizeOfExcludingThis from its super-class. AddSizeOfIncludingThis() need
301 // not be defined, it is inherited from nsINode.
302 #define NS_DECL_ADDSIZEOFEXCLUDINGTHIS \
303 virtual void AddSizeOfExcludingThis(nsWindowSizes& aSizes, \
304 size_t* aNodeSize) const override;
306 // IID for the nsINode interface
307 // Must be kept in sync with xpcom/rust/xpcom/src/interfaces/nonidl.rs
308 #define NS_INODE_IID \
310 0x70ba4547, 0x7699, 0x44fc, { \
311 0xb3, 0x20, 0x52, 0xdb, 0xe3, 0xd1, 0xf9, 0x0a \
316 * An internal interface that abstracts some DOMNode-related parts that both
317 * nsIContent and Document share. An instance of this interface has a list
318 * of nsIContent children and provides access to them.
320 class nsINode : public mozilla::dom::EventTarget {
321 #ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
322 void AssertInvariantsOnNodeInfoChange();
323 #endif
324 public:
325 using BoxQuadOptions = mozilla::dom::BoxQuadOptions;
326 using ConvertCoordinateOptions = mozilla::dom::ConvertCoordinateOptions;
327 using DocGroup = mozilla::dom::DocGroup;
328 using Document = mozilla::dom::Document;
329 using DOMPoint = mozilla::dom::DOMPoint;
330 using DOMPointInit = mozilla::dom::DOMPointInit;
331 using DOMQuad = mozilla::dom::DOMQuad;
332 using DOMRectReadOnly = mozilla::dom::DOMRectReadOnly;
333 using OwningNodeOrString = mozilla::dom::OwningNodeOrString;
334 using TextOrElementOrDocument = mozilla::dom::TextOrElementOrDocument;
335 using CallerType = mozilla::dom::CallerType;
336 using ErrorResult = mozilla::ErrorResult;
338 // XXXbz Maybe we should codegen a class holding these constants and
339 // inherit from it...
340 static const auto ELEMENT_NODE = mozilla::dom::Node_Binding::ELEMENT_NODE;
341 static const auto ATTRIBUTE_NODE = mozilla::dom::Node_Binding::ATTRIBUTE_NODE;
342 static const auto TEXT_NODE = mozilla::dom::Node_Binding::TEXT_NODE;
343 static const auto CDATA_SECTION_NODE =
344 mozilla::dom::Node_Binding::CDATA_SECTION_NODE;
345 static const auto ENTITY_REFERENCE_NODE =
346 mozilla::dom::Node_Binding::ENTITY_REFERENCE_NODE;
347 static const auto ENTITY_NODE = mozilla::dom::Node_Binding::ENTITY_NODE;
348 static const auto PROCESSING_INSTRUCTION_NODE =
349 mozilla::dom::Node_Binding::PROCESSING_INSTRUCTION_NODE;
350 static const auto COMMENT_NODE = mozilla::dom::Node_Binding::COMMENT_NODE;
351 static const auto DOCUMENT_NODE = mozilla::dom::Node_Binding::DOCUMENT_NODE;
352 static const auto DOCUMENT_TYPE_NODE =
353 mozilla::dom::Node_Binding::DOCUMENT_TYPE_NODE;
354 static const auto DOCUMENT_FRAGMENT_NODE =
355 mozilla::dom::Node_Binding::DOCUMENT_FRAGMENT_NODE;
356 static const auto NOTATION_NODE = mozilla::dom::Node_Binding::NOTATION_NODE;
357 static const auto MAX_NODE_TYPE = NOTATION_NODE;
359 void* operator new(size_t aSize, nsNodeInfoManager* aManager);
360 void* operator new(size_t aSize) = delete;
361 void operator delete(void* aPtr);
363 template <class T>
364 using Sequence = mozilla::dom::Sequence<T>;
366 NS_DECLARE_STATIC_IID_ACCESSOR(NS_INODE_IID)
368 // The |aNodeSize| outparam on this function is where the actual node size
369 // value is put. It gets added to the appropriate value within |aSizes| by
370 // AddSizeOfNodeTree().
372 // Among the sub-classes that inherit (directly or indirectly) from nsINode,
373 // measurement of the following members may be added later if DMD finds it is
374 // worthwhile:
375 // - nsGenericHTMLElement: mForm, mFieldSet
376 // - nsGenericHTMLFrameElement: mFrameLoader (bug 672539)
377 // - HTMLBodyElement: mContentStyleRule
378 // - HTMLDataListElement: mOptions
379 // - HTMLFieldSetElement: mElements, mDependentElements, mFirstLegend
380 // - HTMLFormElement: many!
381 // - HTMLFrameSetElement: mRowSpecs, mColSpecs
382 // - HTMLInputElement: mInputData, mFiles, mFileList, mStaticDocfileList
383 // - nsHTMLMapElement: mAreas
384 // - HTMLMediaElement: many!
385 // - nsHTMLOutputElement: mDefaultValue, mTokenList
386 // - nsHTMLRowElement: mCells
387 // - nsHTMLSelectElement: mOptions, mRestoreState
388 // - nsHTMLTableElement: mTBodies, mRows, mTableInheritedAttributes
389 // - nsHTMLTableSectionElement: mRows
390 // - nsHTMLTextAreaElement: mControllers, mState
392 // The following members don't need to be measured:
393 // - nsIContent: mPrimaryFrame, because it's non-owning and measured elsewhere
395 virtual void AddSizeOfExcludingThis(nsWindowSizes& aSizes,
396 size_t* aNodeSize) const;
398 // SizeOfIncludingThis doesn't need to be overridden by sub-classes because
399 // sub-classes of nsINode are guaranteed to be laid out in memory in such a
400 // way that |this| points to the start of the allocated object, even in
401 // methods of nsINode's sub-classes, so aSizes.mState.mMallocSizeOf(this) is
402 // always safe to call no matter which object it was invoked on.
403 void AddSizeOfIncludingThis(nsWindowSizes& aSizes, size_t* aNodeSize) const;
405 friend class nsNodeWeakReference;
406 friend class nsNodeSupportsWeakRefTearoff;
407 friend class AttrArray;
409 #ifdef MOZILLA_INTERNAL_API
410 explicit nsINode(already_AddRefed<mozilla::dom::NodeInfo>&& aNodeInfo);
411 #endif
413 virtual ~nsINode();
415 bool IsContainerNode() const {
416 return IsElement() || IsDocument() || IsDocumentFragment();
420 * Returns true if the node is a HTMLTemplate element.
422 bool IsTemplateElement() const { return IsHTMLElement(nsGkAtoms::_template); }
424 bool IsSlotable() const { return IsElement() || IsText(); }
427 * Returns true if this is a document node.
429 bool IsDocument() const {
430 // One less pointer-chase than checking NodeType().
431 return !GetParentNode() && IsInUncomposedDoc();
435 * Return this node as a document. Asserts IsDocument().
437 * This is defined inline in Document.h.
439 inline Document* AsDocument();
440 inline const Document* AsDocument() const;
443 * Returns true if this is a document fragment node.
445 bool IsDocumentFragment() const {
446 return NodeType() == DOCUMENT_FRAGMENT_NODE;
449 virtual bool IsHTMLFormControlElement() const { return false; }
452 * https://dom.spec.whatwg.org/#concept-tree-inclusive-descendant
454 * @param aNode must not be nullptr.
456 bool IsInclusiveDescendantOf(const nsINode* aNode) const;
459 * https://dom.spec.whatwg.org/#concept-shadow-including-inclusive-descendant
461 * @param aNode must not be nullptr.
463 bool IsShadowIncludingInclusiveDescendantOf(const nsINode* aNode) const;
466 * Returns true if the given node is this node or one of its descendants
467 * in the "flat tree."
469 * @param aNode must not be nullptr.
471 bool IsInclusiveFlatTreeDescendantOf(const nsINode* aNode) const;
474 * Return this node as a document fragment. Asserts IsDocumentFragment().
476 * This is defined inline in DocumentFragment.h.
478 inline mozilla::dom::DocumentFragment* AsDocumentFragment();
479 inline const mozilla::dom::DocumentFragment* AsDocumentFragment() const;
481 JSObject* WrapObject(JSContext*, JS::Handle<JSObject*> aGivenProto) final;
484 * Hook for constructing JS::ubi::Concrete specializations for memory
485 * reporting. Specializations are defined in NodeUbiReporting.h.
487 virtual void ConstructUbiNode(void* storage) = 0;
490 * returns true if we are in priviliged code or
491 * layout.css.getBoxQuads.enabled == true.
493 static bool HasBoxQuadsSupport(JSContext* aCx, JSObject* /* unused */);
495 protected:
497 * WrapNode is called from WrapObject to actually wrap this node, WrapObject
498 * does some additional checks and fix-up that's common to all nodes. WrapNode
499 * should just call the DOM binding's Wrap function.
501 * aGivenProto is the prototype to use (or null if the default one should be
502 * used) and should just be passed directly on to the DOM binding's Wrap
503 * function.
505 virtual JSObject* WrapNode(JSContext* aCx,
506 JS::Handle<JSObject*> aGivenProto) = 0;
508 public:
509 mozilla::dom::ParentObject GetParentObject()
510 const; // Implemented in Document.h
513 * Returns the first child of a node or the first child of
514 * a template element's content if the provided node is a
515 * template element.
517 nsIContent* GetFirstChildOfTemplateOrNode();
520 * Return the scope chain parent for this node, for use in things
521 * like event handler compilation. Returning null means to use the
522 * global object as the scope chain parent.
524 virtual nsINode* GetScopeChainParent() const;
526 MOZ_CAN_RUN_SCRIPT mozilla::dom::Element* GetParentFlexElement();
529 * Returns the nearest inclusive open popover for a given node, see
530 * https://html.spec.whatwg.org/multipage/popover.html#nearest-inclusive-open-popover
532 mozilla::dom::Element* GetNearestInclusiveOpenPopover() const;
535 * https://html.spec.whatwg.org/multipage/popover.html#nearest-inclusive-target-popover-for-invoker
537 mozilla::dom::Element* GetNearestInclusiveTargetPopoverForInvoker() const;
540 * https://html.spec.whatwg.org/multipage/popover.html#popover-target-element
542 nsGenericHTMLElement* GetEffectivePopoverTargetElement() const;
545 * https://html.spec.whatwg.org/multipage/popover.html#topmost-clicked-popover
547 mozilla::dom::Element* GetTopmostClickedPopover() const;
549 bool IsNode() const final { return true; }
551 NS_IMPL_FROMEVENTTARGET_HELPER(nsINode, IsNode())
554 * Return whether the node is an Element node. Faster than using `NodeType()`.
556 bool IsElement() const { return GetBoolFlag(NodeIsElement); }
558 virtual bool IsTextControlElement() const { return false; }
559 virtual bool IsGenericHTMLFormControlElementWithState() const {
560 return false;
563 // Returns non-null if this element subclasses `LinkStyle`.
564 virtual const mozilla::dom::LinkStyle* AsLinkStyle() const { return nullptr; }
565 mozilla::dom::LinkStyle* AsLinkStyle() {
566 return const_cast<mozilla::dom::LinkStyle*>(
567 static_cast<const nsINode*>(this)->AsLinkStyle());
571 * Return this node as an Element. Should only be used for nodes
572 * for which IsElement() is true. This is defined inline in Element.h.
574 inline mozilla::dom::Element* AsElement();
575 inline const mozilla::dom::Element* AsElement() const;
578 * Return whether the node is an nsStyledElement instance or not.
580 virtual bool IsStyledElement() const { return false; }
583 * Return this node as nsIContent. Should only be used for nodes for which
584 * IsContent() is true.
586 * The assertion in nsIContent's constructor makes this safe.
588 nsIContent* AsContent() {
589 MOZ_ASSERT(IsContent());
590 return reinterpret_cast<nsIContent*>(this);
592 const nsIContent* AsContent() const {
593 MOZ_ASSERT(IsContent());
594 return reinterpret_cast<const nsIContent*>(this);
598 * Return whether the node is a Text node (which might be an actual
599 * textnode, or might be a CDATA section).
601 bool IsText() const {
602 uint32_t nodeType = NodeType();
603 return nodeType == TEXT_NODE || nodeType == CDATA_SECTION_NODE;
607 * Return this node as Text if it is one, otherwise null. This is defined
608 * inline in Text.h.
610 inline mozilla::dom::Text* GetAsText();
611 inline const mozilla::dom::Text* GetAsText() const;
614 * Return this node as Text. Asserts IsText(). This is defined inline in
615 * Text.h.
617 inline mozilla::dom::Text* AsText();
618 inline const mozilla::dom::Text* AsText() const;
621 * Return whether the node is a ProcessingInstruction node.
623 bool IsProcessingInstruction() const {
624 return NodeType() == PROCESSING_INSTRUCTION_NODE;
628 * Return whether the node is a CharacterData node (text, cdata,
629 * comment, processing instruction)
631 bool IsCharacterData() const {
632 uint32_t nodeType = NodeType();
633 return nodeType == TEXT_NODE || nodeType == CDATA_SECTION_NODE ||
634 nodeType == PROCESSING_INSTRUCTION_NODE || nodeType == COMMENT_NODE;
638 * Return whether the node is a Comment node.
640 bool IsComment() const { return NodeType() == COMMENT_NODE; }
643 * Return whether the node is an Attr node.
645 bool IsAttr() const { return NodeType() == ATTRIBUTE_NODE; }
648 * Return if this node has any children.
650 bool HasChildren() const { return !!mFirstChild; }
653 * Get the number of children
654 * @return the number of children
656 uint32_t GetChildCount() const { return mChildCount; }
659 * NOTE: this function is going to be removed soon (hopefully!) Don't use it
660 * in new code.
662 * Get a child by index
663 * @param aIndex the index of the child to get
664 * @return the child, or null if index out of bounds
666 nsIContent* GetChildAt_Deprecated(uint32_t aIndex) const;
669 * Get the index of a child within this content.
671 * @param aPossibleChild the child to get the index of.
672 * @return the index of the child, or Nothing if not a child. Be aware that
673 * anonymous children (e.g. a <div> child of an <input> element) will
674 * result in Nothing.
676 * If the return value is Some, then calling GetChildAt_Deprecated() with
677 * that value will return aPossibleChild.
679 mozilla::Maybe<uint32_t> ComputeIndexOf(const nsINode* aPossibleChild) const;
682 * Get the index of this within parent node (ComputeIndexInParentNode) or
683 * parent content (nsIContent) node (ComputeIndexInParentContent).
685 * @return the index of this node in the parent, or Nothing there is no
686 * parent (content) node or the parent does not have this node anymore
687 * (e.g., being removed from the parent). Be aware that anonymous
688 * children (e.g. a <div> child of an <input> element) will result in
689 * Nothing.
691 * If the return value is Some, then calling GetChildAt_Deprecated() with
692 * that value will return this.
694 mozilla::Maybe<uint32_t> ComputeIndexInParentNode() const;
695 mozilla::Maybe<uint32_t> ComputeIndexInParentContent() const;
698 * Get the index of a child within this content.
700 * @param aPossibleChild the child to get the index of.
701 * @return the index of the child, or -1 if not a child. Be aware that
702 * anonymous children (e.g. a <div> child of an <input> element) will
703 * result in -1.
705 * If the return value is not -1, then calling GetChildAt_Deprecated() with
706 * that value will return aPossibleChild.
708 int32_t ComputeIndexOf_Deprecated(const nsINode* aPossibleChild) const;
711 * Returns the "node document" of this node.
713 * https://dom.spec.whatwg.org/#concept-node-document
715 * Note that in the case that this node is a document node this method
716 * will return |this|. That is different to the Node.ownerDocument DOM
717 * attribute (implemented by nsINode::GetOwnerDocument) which is specified to
718 * be null in that case:
720 * https://dom.spec.whatwg.org/#dom-node-ownerdocument
722 * For all other cases OwnerDoc and GetOwnerDocument behave identically.
724 Document* OwnerDoc() const MOZ_NONNULL_RETURN {
725 return mNodeInfo->GetDocument();
729 * Return the "owner document" of this node as an nsINode*. Implemented
730 * in Document.h.
732 inline nsINode* OwnerDocAsNode() const MOZ_NONNULL_RETURN;
735 * Returns true if the content has an ancestor that is a document.
737 * @return whether this content is in a document tree
739 bool IsInUncomposedDoc() const { return GetBoolFlag(IsInDocument); }
742 * Get the document that this content is currently in, if any. This will be
743 * null if the content has no ancestor that is a document.
745 * @return the current document
748 Document* GetUncomposedDoc() const {
749 return IsInUncomposedDoc() ? OwnerDoc() : nullptr;
753 * Returns true if we're connected, and thus GetComposedDoc() would return a
754 * non-null value.
756 bool IsInComposedDoc() const { return GetBoolFlag(IsConnected); }
759 * This method returns the owner document if the node is connected to it
760 * (as defined in the DOM spec), otherwise it returns null.
761 * In other words, returns non-null even in the case the node is in
762 * Shadow DOM, if there is a possibly shadow boundary crossing path from
763 * the node to its owner document.
765 Document* GetComposedDoc() const {
766 return IsInComposedDoc() ? OwnerDoc() : nullptr;
770 * Returns OwnerDoc() if the node is in uncomposed document and ShadowRoot if
771 * the node is in Shadow DOM.
773 mozilla::dom::DocumentOrShadowRoot* GetContainingDocumentOrShadowRoot() const;
776 * Returns OwnerDoc() if the node is in uncomposed document and ShadowRoot if
777 * the node is in Shadow DOM and is in composed document.
779 mozilla::dom::DocumentOrShadowRoot* GetUncomposedDocOrConnectedShadowRoot()
780 const;
783 * To be called when reference count of the node drops to zero.
785 void LastRelease();
788 * The values returned by this function are the ones defined for
789 * Node.nodeType
791 uint16_t NodeType() const { return mNodeInfo->NodeType(); }
792 const nsString& NodeName() const { return mNodeInfo->NodeName(); }
793 const nsString& LocalName() const { return mNodeInfo->LocalName(); }
796 * Get the NodeInfo for this element
797 * @return the nodes node info
799 inline mozilla::dom::NodeInfo* NodeInfo() const { return mNodeInfo; }
802 * Called when we have been adopted, and the information of the
803 * node has been changed.
805 * The new document can be reached via OwnerDoc().
807 * If you override this method,
808 * please call up to the parent NodeInfoChanged.
810 * If you change this, change also the similar method in Link.
812 virtual void NodeInfoChanged(Document* aOldDoc) {
813 #ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
814 AssertInvariantsOnNodeInfoChange();
815 #endif
818 inline bool IsInNamespace(int32_t aNamespace) const {
819 return mNodeInfo->NamespaceID() == aNamespace;
823 * Returns the DocGroup of the "node document" of this node.
825 DocGroup* GetDocGroup() const;
828 * Print a debugger friendly descriptor of this element. This will describe
829 * the position of this element in the document.
831 friend std::ostream& operator<<(std::ostream& aStream, const nsINode& aNode);
833 protected:
834 // These 2 methods are useful for the recursive templates IsHTMLElement,
835 // IsSVGElement, etc.
836 inline bool IsNodeInternal() const { return false; }
838 template <typename First, typename... Args>
839 inline bool IsNodeInternal(First aFirst, Args... aArgs) const {
840 return mNodeInfo->Equals(aFirst) || IsNodeInternal(aArgs...);
843 public:
844 inline bool IsHTMLElement() const {
845 return IsElement() && IsInNamespace(kNameSpaceID_XHTML);
848 inline bool IsHTMLElement(const nsAtom* aTag) const {
849 return IsElement() && mNodeInfo->Equals(aTag, kNameSpaceID_XHTML);
852 template <typename First, typename... Args>
853 inline bool IsAnyOfHTMLElements(First aFirst, Args... aArgs) const {
854 return IsHTMLElement() && IsNodeInternal(aFirst, aArgs...);
857 inline bool IsSVGElement() const {
858 return IsElement() && IsInNamespace(kNameSpaceID_SVG);
861 inline bool IsSVGElement(const nsAtom* aTag) const {
862 return IsElement() && mNodeInfo->Equals(aTag, kNameSpaceID_SVG);
865 template <typename First, typename... Args>
866 inline bool IsAnyOfSVGElements(First aFirst, Args... aArgs) const {
867 return IsSVGElement() && IsNodeInternal(aFirst, aArgs...);
870 virtual bool IsSVGAnimationElement() const { return false; }
871 virtual bool IsSVGComponentTransferFunctionElement() const { return false; }
872 virtual bool IsSVGFilterPrimitiveElement() const { return false; }
873 virtual bool IsSVGFilterPrimitiveChildElement() const { return false; }
874 virtual bool IsSVGGeometryElement() const { return false; }
875 virtual bool IsSVGGraphicsElement() const { return false; }
877 inline bool IsXULElement() const {
878 return IsElement() && IsInNamespace(kNameSpaceID_XUL);
881 inline bool IsXULElement(const nsAtom* aTag) const {
882 return IsElement() && mNodeInfo->Equals(aTag, kNameSpaceID_XUL);
885 template <typename First, typename... Args>
886 inline bool IsAnyOfXULElements(First aFirst, Args... aArgs) const {
887 return IsXULElement() && IsNodeInternal(aFirst, aArgs...);
890 inline bool IsMathMLElement() const {
891 return IsElement() && IsInNamespace(kNameSpaceID_MathML);
894 inline bool IsMathMLElement(const nsAtom* aTag) const {
895 return IsElement() && mNodeInfo->Equals(aTag, kNameSpaceID_MathML);
898 template <typename First, typename... Args>
899 inline bool IsAnyOfMathMLElements(First aFirst, Args... aArgs) const {
900 return IsMathMLElement() && IsNodeInternal(aFirst, aArgs...);
903 bool IsShadowRoot() const {
904 const bool isShadowRoot = IsInShadowTree() && !GetParentNode();
905 MOZ_ASSERT_IF(isShadowRoot, IsDocumentFragment());
906 return isShadowRoot;
909 bool IsHTMLHeadingElement() const {
910 return IsAnyOfHTMLElements(nsGkAtoms::h1, nsGkAtoms::h2, nsGkAtoms::h3,
911 nsGkAtoms::h4, nsGkAtoms::h5, nsGkAtoms::h6);
915 * Check whether the conditional processing attributes other than
916 * systemLanguage "return true" if they apply to and are specified
917 * on the given SVG element. Returns true if this element should be
918 * rendered, false if it should not.
920 virtual bool PassesConditionalProcessingTests() const { return true; }
923 * Insert a content node before another or at the end.
924 * This method handles calling BindToTree on the child appropriately.
926 * @param aKid the content to insert
927 * @param aBeforeThis an existing node. Use nullptr if you want to
928 * add aKid at the end.
929 * @param aNotify whether to notify the document (current document for
930 * nsIContent, and |this| for Document) that the insert has occurred
931 * @param aRv The error, if any.
932 * Throw NS_ERROR_DOM_HIERARCHY_REQUEST_ERR if one attempts to have
933 * more than one element node as a child of a document. Doing this
934 * will also assert -- you shouldn't be doing it! Check with
935 * Document::GetRootElement() first if you're not sure. Apart from
936 * this one constraint, this doesn't do any checking on whether aKid is
937 * a valid child of |this|.
938 * Throw NS_ERROR_OUT_OF_MEMORY in some cases (from BindToTree).
940 virtual void InsertChildBefore(nsIContent* aKid, nsIContent* aBeforeThis,
941 bool aNotify, mozilla::ErrorResult& aRv);
944 * Append a content node to the end of the child list. This method handles
945 * calling BindToTree on the child appropriately.
947 * @param aKid the content to append
948 * @param aNotify whether to notify the document (current document for
949 * nsIContent, and |this| for Document) that the append has occurred
950 * @param aRv The error, if any.
951 * Throw NS_ERROR_DOM_HIERARCHY_REQUEST_ERR if one attempts to have
952 * more than one element node as a child of a document. Doing this
953 * will also assert -- you shouldn't be doing it! Check with
954 * Document::GetRootElement() first if you're not sure. Apart from
955 * this one constraint, this doesn't do any checking on whether aKid is
956 * a valid child of |this|.
957 * Throw NS_ERROR_OUT_OF_MEMORY in some cases (from BindToTree).
959 void AppendChildTo(nsIContent* aKid, bool aNotify,
960 mozilla::ErrorResult& aRv) {
961 InsertChildBefore(aKid, nullptr, aNotify, aRv);
965 * Remove a child from this node. This method handles calling UnbindFromTree
966 * on the child appropriately.
968 * @param aKid the content to remove
969 * @param aNotify whether to notify the document (current document for
970 * nsIContent, and |this| for Document) that the remove has occurred
972 virtual void RemoveChildNode(nsIContent* aKid, bool aNotify);
975 * Get a property associated with this node.
977 * @param aPropertyName name of property to get.
978 * @param aStatus out parameter for storing resulting status.
979 * Set to NS_PROPTABLE_PROP_NOT_THERE if the property
980 * is not set.
981 * @return the property. Null if the property is not set
982 * (though a null return value does not imply the
983 * property was not set, i.e. it can be set to null).
985 void* GetProperty(const nsAtom* aPropertyName,
986 nsresult* aStatus = nullptr) const;
989 * Set a property to be associated with this node. This will overwrite an
990 * existing value if one exists. The existing value is destroyed using the
991 * destructor function given when that value was set.
993 * @param aPropertyName name of property to set.
994 * @param aValue new value of property.
995 * @param aDtor destructor function to be used when this property
996 * is destroyed.
997 * @param aTransfer if true the property will not be deleted when the
998 * ownerDocument of the node changes, if false it
999 * will be deleted.
1001 * @return NS_PROPTABLE_PROP_OVERWRITTEN (success value) if the property
1002 * was already set
1003 * @throws NS_ERROR_OUT_OF_MEMORY if that occurs
1005 nsresult SetProperty(nsAtom* aPropertyName, void* aValue,
1006 NSPropertyDtorFunc aDtor = nullptr,
1007 bool aTransfer = false);
1010 * A generic destructor for property values allocated with new.
1012 template <class T>
1013 static void DeleteProperty(void*, nsAtom*, void* aPropertyValue, void*) {
1014 delete static_cast<T*>(aPropertyValue);
1018 * Removes a property associated with this node. The value is destroyed using
1019 * the destruction function given when that value was set.
1021 * @param aPropertyName name of property to destroy.
1023 void RemoveProperty(const nsAtom* aPropertyName);
1026 * Take a property associated with this node. The value will not be destroyed
1027 * but rather returned. It is the caller's responsibility to destroy the value
1028 * after that point.
1030 * @param aPropertyName name of property to unset.
1031 * @param aStatus out parameter for storing resulting status.
1032 * Set to NS_PROPTABLE_PROP_NOT_THERE if the property
1033 * is not set.
1034 * @return the property. Null if the property is not set
1035 * (though a null return value does not imply the
1036 * property was not set, i.e. it can be set to null).
1038 void* TakeProperty(const nsAtom* aPropertyName, nsresult* aStatus = nullptr);
1040 bool HasProperties() const { return HasFlag(NODE_HAS_PROPERTIES); }
1043 * Return the principal of this node. This is guaranteed to never be a null
1044 * pointer.
1046 nsIPrincipal* NodePrincipal() const {
1047 return mNodeInfo->NodeInfoManager()->DocumentPrincipal();
1051 * Return the CSP of this node's document, if any.
1053 nsIContentSecurityPolicy* GetCsp() const;
1056 * Get the parent nsIContent for this node.
1057 * @return the parent, or null if no parent or the parent is not an nsIContent
1059 nsIContent* GetParent() const {
1060 return MOZ_LIKELY(GetBoolFlag(ParentIsContent)) ? mParent->AsContent()
1061 : nullptr;
1065 * Get the parent nsINode for this node. This can be either an nsIContent, a
1066 * Document or an Attr.
1067 * @return the parent node
1069 nsINode* GetParentNode() const { return mParent; }
1071 private:
1072 nsIContent* DoGetShadowHost() const;
1074 public:
1075 nsINode* GetParentOrShadowHostNode() const {
1076 if (MOZ_LIKELY(mParent)) {
1077 return mParent;
1079 // We could put this in nsIContentInlines.h or such to avoid this
1080 // reinterpret_cast, but it doesn't seem worth it.
1081 return IsInShadowTree() ? reinterpret_cast<nsINode*>(DoGetShadowHost())
1082 : nullptr;
1085 enum FlattenedParentType { eNotForStyle, eForStyle };
1088 * Returns the node that is the parent of this node in the flattened
1089 * tree. This differs from the normal parent if the node is filtered
1090 * into an insertion point, or if the node is a direct child of a
1091 * shadow root.
1093 * @return the flattened tree parent
1095 inline nsINode* GetFlattenedTreeParentNode() const;
1097 nsINode* GetFlattenedTreeParentNodeNonInline() const;
1100 * Like GetFlattenedTreeParentNode, but returns the document for any native
1101 * anonymous content that was generated for ancestor frames of the document
1102 * element's primary frame, such as scrollbar elements created by the root
1103 * scroll frame.
1105 inline nsINode* GetFlattenedTreeParentNodeForStyle() const;
1107 inline mozilla::dom::Element* GetFlattenedTreeParentElement() const;
1108 inline mozilla::dom::Element* GetFlattenedTreeParentElementForStyle() const;
1111 * Get the parent nsINode for this node if it is an Element.
1113 * Defined inline in Element.h
1115 * @return the parent node
1117 inline mozilla::dom::Element* GetParentElement() const;
1120 * Get the parent Element of this node, traversing over a ShadowRoot
1121 * to its host if necessary.
1123 mozilla::dom::Element* GetParentElementCrossingShadowRoot() const;
1126 * Get closest element node for the node. Meaning that if the node is an
1127 * element node, returns itself. Otherwise, returns parent element or null.
1129 inline mozilla::dom::Element* GetAsElementOrParentElement() const;
1132 * Get the root of the subtree this node belongs to. This never returns
1133 * null. It may return 'this' (e.g. for document nodes, and nodes that
1134 * are the roots of disconnected subtrees).
1136 nsINode* SubtreeRoot() const;
1139 * Get context object's shadow-including root if options's composed is true,
1140 * and context object's root otherwise.
1142 nsINode* GetRootNode(const mozilla::dom::GetRootNodeOptions& aOptions);
1144 virtual mozilla::EventListenerManager* GetExistingListenerManager()
1145 const override;
1146 virtual mozilla::EventListenerManager* GetOrCreateListenerManager() override;
1148 mozilla::Maybe<mozilla::dom::EventCallbackDebuggerNotificationType>
1149 GetDebuggerNotificationType() const override;
1151 bool ComputeDefaultWantsUntrusted(mozilla::ErrorResult& aRv) final;
1153 virtual bool IsApzAware() const override;
1155 virtual nsPIDOMWindowOuter* GetOwnerGlobalForBindingsInternal() override;
1156 virtual nsIGlobalObject* GetOwnerGlobal() const override;
1158 using mozilla::dom::EventTarget::DispatchEvent;
1159 // TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230)
1160 MOZ_CAN_RUN_SCRIPT_BOUNDARY bool DispatchEvent(
1161 mozilla::dom::Event& aEvent, mozilla::dom::CallerType aCallerType,
1162 mozilla::ErrorResult& aRv) override;
1164 MOZ_CAN_RUN_SCRIPT
1165 nsresult PostHandleEvent(mozilla::EventChainPostVisitor& aVisitor) override;
1168 * Adds a mutation observer to be notified when this node, or any of its
1169 * descendants, are modified. The node will hold a weak reference to the
1170 * observer, which means that it is the responsibility of the observer to
1171 * remove itself in case it dies before the node. If an observer is added
1172 * while observers are being notified, it may also be notified. In general,
1173 * adding observers while inside a notification is not a good idea. An
1174 * observer that is already observing the node must not be added without
1175 * being removed first.
1177 * For mutation observers that implement nsIAnimationObserver, use
1178 * AddAnimationObserver instead.
1180 void AddMutationObserver(nsIMutationObserver* aMutationObserver) {
1181 nsSlots* s = Slots();
1182 if (aMutationObserver) {
1183 NS_ASSERTION(!s->mMutationObservers.contains(aMutationObserver),
1184 "Observer already in the list");
1186 s->mMutationObservers.pushBack(aMutationObserver);
1190 void AddMutationObserver(nsMultiMutationObserver* aMultiMutationObserver);
1193 * Same as above, but only adds the observer if its not observing
1194 * the node already.
1196 * For mutation observers that implement nsIAnimationObserver, use
1197 * AddAnimationObserverUnlessExists instead.
1199 void AddMutationObserverUnlessExists(nsIMutationObserver* aMutationObserver) {
1200 nsSlots* s = Slots();
1201 if (aMutationObserver &&
1202 !s->mMutationObservers.contains(aMutationObserver)) {
1203 s->mMutationObservers.pushBack(aMutationObserver);
1207 void AddMutationObserverUnlessExists(
1208 nsMultiMutationObserver* aMultiMutationObserver);
1210 * Same as AddMutationObserver, but for nsIAnimationObservers. This
1211 * additionally records on the document that animation observers have
1212 * been registered, which is used to determine whether notifications
1213 * must be fired when animations are added, removed or changed.
1215 void AddAnimationObserver(nsIAnimationObserver* aAnimationObserver);
1218 * Same as above, but only adds the observer if its not observing
1219 * the node already.
1221 void AddAnimationObserverUnlessExists(
1222 nsIAnimationObserver* aAnimationObserver);
1225 * Removes a mutation observer.
1227 void RemoveMutationObserver(nsIMutationObserver* aMutationObserver) {
1228 nsSlots* s = GetExistingSlots();
1229 if (s) {
1230 s->mMutationObservers.remove(aMutationObserver);
1234 void RemoveMutationObserver(nsMultiMutationObserver* aMultiMutationObserver);
1236 mozilla::SafeDoublyLinkedList<nsIMutationObserver>* GetMutationObservers();
1239 * Helper methods to access ancestor node(s) of type T.
1240 * The implementations of the methods are in mozilla/dom/AncestorIterator.h.
1242 template <typename T>
1243 inline mozilla::dom::AncestorsOfTypeIterator<T> AncestorsOfType() const;
1245 template <typename T>
1246 inline mozilla::dom::InclusiveAncestorsOfTypeIterator<T>
1247 InclusiveAncestorsOfType() const;
1249 template <typename T>
1250 inline mozilla::dom::FlatTreeAncestorsOfTypeIterator<T>
1251 FlatTreeAncestorsOfType() const;
1253 template <typename T>
1254 inline mozilla::dom::InclusiveFlatTreeAncestorsOfTypeIterator<T>
1255 InclusiveFlatTreeAncestorsOfType() const;
1257 template <typename T>
1258 T* FirstAncestorOfType() const;
1260 private:
1262 * Walks aNode, its attributes and, if aDeep is true, its descendant nodes.
1263 * If aClone is true the nodes will be cloned. If aNewNodeInfoManager is
1264 * not null, it is used to create new nodeinfos for the nodes. Also reparents
1265 * the XPConnect wrappers for the nodes into aReparentScope if non-null.
1267 * @param aNode Node to adopt/clone.
1268 * @param aClone If true the node will be cloned and the cloned node will
1269 * be returned.
1270 * @param aDeep If true the function will be called recursively on
1271 * descendants of the node
1272 * @param aNewNodeInfoManager The nodeinfo manager to use to create new
1273 * nodeinfos for aNode and its attributes and
1274 * descendants. May be null if the nodeinfos
1275 * shouldn't be changed.
1276 * @param aReparentScope Scope into which wrappers should be reparented, or
1277 * null if no reparenting should be done.
1278 * @param aParent If aClone is true the cloned node will be appended to
1279 * aParent's children. May be null. If not null then aNode
1280 * must be an nsIContent.
1281 * @param aError The error, if any.
1283 * @return If aClone is true then the cloned node will be returned,
1284 * unless an error occurred. In error conditions, null
1285 * will be returned.
1287 static already_AddRefed<nsINode> CloneAndAdopt(
1288 nsINode* aNode, bool aClone, bool aDeep,
1289 nsNodeInfoManager* aNewNodeInfoManager,
1290 JS::Handle<JSObject*> aReparentScope, nsINode* aParent,
1291 mozilla::ErrorResult& aError);
1293 public:
1295 * Walks the node, its attributes and descendant nodes. If aNewNodeInfoManager
1296 * is not null, it is used to create new nodeinfos for the nodes. Also
1297 * reparents the XPConnect wrappers for the nodes into aReparentScope if
1298 * non-null.
1300 * @param aNewNodeInfoManager The nodeinfo manager to use to create new
1301 * nodeinfos for the node and its attributes and
1302 * descendants. May be null if the nodeinfos
1303 * shouldn't be changed.
1304 * @param aReparentScope New scope for the wrappers, or null if no reparenting
1305 * should be done.
1306 * @param aError The error, if any.
1308 void Adopt(nsNodeInfoManager* aNewNodeInfoManager,
1309 JS::Handle<JSObject*> aReparentScope,
1310 mozilla::ErrorResult& aError);
1313 * Clones the node, its attributes and, if aDeep is true, its descendant nodes
1314 * If aNewNodeInfoManager is not null, it is used to create new nodeinfos for
1315 * the clones.
1317 * @param aDeep If true the function will be called recursively on
1318 * descendants of the node
1319 * @param aNewNodeInfoManager The nodeinfo manager to use to create new
1320 * nodeinfos for the node and its attributes and
1321 * descendants. May be null if the nodeinfos
1322 * shouldn't be changed.
1323 * @param aError The error, if any.
1325 * @return The newly created node. Null in error conditions.
1327 already_AddRefed<nsINode> Clone(bool aDeep,
1328 nsNodeInfoManager* aNewNodeInfoManager,
1329 mozilla::ErrorResult& aError);
1332 * Clones this node. This needs to be overriden by all node classes. aNodeInfo
1333 * should be identical to this node's nodeInfo, except for the document which
1334 * may be different. When cloning an element, all attributes of the element
1335 * will be cloned. The children of the node will not be cloned.
1337 * @param aNodeInfo the nodeinfo to use for the clone
1338 * @param aResult the clone
1340 virtual nsresult Clone(mozilla::dom::NodeInfo*, nsINode** aResult) const = 0;
1342 // This class can be extended by subclasses that wish to store more
1343 // information in the slots.
1344 class nsSlots {
1345 public:
1346 nsSlots();
1348 // If needed we could remove the vtable pointer this dtor causes by
1349 // putting a DestroySlots function on nsINode
1350 virtual ~nsSlots();
1352 virtual void Traverse(nsCycleCollectionTraversalCallback&);
1353 virtual void Unlink(nsINode&);
1356 * A list of mutation observers
1358 mozilla::SafeDoublyLinkedList<nsIMutationObserver> mMutationObservers;
1361 * An object implementing NodeList for this content (childNodes)
1362 * @see NodeList
1363 * @see nsGenericHTMLElement::GetChildNodes
1365 RefPtr<nsAttrChildContentList> mChildNodes;
1368 * Weak reference to this node. This is cleared by the destructor of
1369 * nsNodeWeakReference.
1371 nsNodeWeakReference* MOZ_NON_OWNING_REF mWeakReference;
1374 * A set of ranges which are in the selection and which have this node as
1375 * their endpoints' closest common inclusive ancestor
1376 * (https://dom.spec.whatwg.org/#concept-tree-inclusive-ancestor). This is
1377 * a UniquePtr instead of just a LinkedList, because that prevents us from
1378 * pushing DOMSlots up to the next allocation bucket size, at the cost of
1379 * some complexity.
1381 mozilla::UniquePtr<mozilla::LinkedList<mozilla::dom::AbstractRange>>
1382 mClosestCommonInclusiveAncestorRanges;
1386 * Functions for managing flags and slots
1388 #ifdef DEBUG
1389 nsSlots* DebugGetSlots() { return Slots(); }
1390 #endif
1392 void SetFlags(FlagsType aFlagsToSet) {
1393 NS_ASSERTION(
1394 !(aFlagsToSet &
1395 (NODE_IS_NATIVE_ANONYMOUS_ROOT | NODE_IS_IN_NATIVE_ANONYMOUS_SUBTREE |
1396 NODE_DESCENDANTS_NEED_FRAMES | NODE_NEEDS_FRAME |
1397 NODE_HAS_BEEN_IN_UA_WIDGET)) ||
1398 IsContent(),
1399 "Flag only permitted on nsIContent nodes");
1400 nsWrapperCache::SetFlags(aFlagsToSet);
1403 void UnsetFlags(FlagsType aFlagsToUnset) {
1404 NS_ASSERTION(!(aFlagsToUnset & (NODE_HAS_BEEN_IN_UA_WIDGET |
1405 NODE_IS_NATIVE_ANONYMOUS_ROOT)),
1406 "Trying to unset write-only flags");
1407 nsWrapperCache::UnsetFlags(aFlagsToUnset);
1410 void SetEditableFlag(bool aEditable) {
1411 if (aEditable) {
1412 SetFlags(NODE_IS_EDITABLE);
1413 } else {
1414 UnsetFlags(NODE_IS_EDITABLE);
1418 inline bool IsEditable() const;
1421 * Check if this node is in design mode or not. When this returns true and:
1422 * - if this is a Document node, it's the design mode root.
1423 * - if this is a content node, it's connected, it's not in a shadow tree
1424 * (except shadow tree for UI widget and native anonymous subtree) and its
1425 * uncomposed document is in design mode.
1426 * Note that returning true does NOT mean the node or its children is
1427 * editable. E.g., when this node is in a shadow tree of a UA widget and its
1428 * host is in design mode.
1430 inline bool IsInDesignMode() const;
1433 * Returns true if |this| or any of its ancestors is native anonymous.
1435 bool IsInNativeAnonymousSubtree() const {
1436 return HasFlag(NODE_IS_IN_NATIVE_ANONYMOUS_SUBTREE);
1440 * If |this| or any ancestor is native anonymous, return the root of the
1441 * native anonymous subtree. Note that in case of nested native anonymous
1442 * content, this returns the innermost root, not the outermost.
1444 nsIContent* GetClosestNativeAnonymousSubtreeRoot() const {
1445 if (!IsInNativeAnonymousSubtree()) {
1446 MOZ_ASSERT(!HasBeenInUAWidget(), "UA widget implies anonymous");
1447 return nullptr;
1449 MOZ_ASSERT(IsContent(), "How did non-content end up in NAC?");
1450 if (HasBeenInUAWidget()) {
1451 // reinterpret_cast because in this header we don't know ShadowRoot is an
1452 // nsIContent. ShadowRoot constructor asserts this is correct.
1453 return reinterpret_cast<nsIContent*>(GetContainingShadow());
1455 for (const nsINode* node = this; node; node = node->GetParentNode()) {
1456 if (node->IsRootOfNativeAnonymousSubtree()) {
1457 return const_cast<nsINode*>(node)->AsContent();
1460 // FIXME(emilio): This should not happen, usually, but editor removes nodes
1461 // in native anonymous subtrees, and we don't clean nodes from the current
1462 // event content stack from ContentRemoved, so it can actually happen, see
1463 // bug 1510208.
1464 NS_WARNING("GetClosestNativeAnonymousSubtreeRoot on disconnected NAC!");
1465 return nullptr;
1469 * If |this| or any ancestor is native anonymous, return the parent of the
1470 * native anonymous subtree. Note that in case of nested native anonymous
1471 * content, this returns the parent or host of the innermost root, not the
1472 * outermost.
1474 nsIContent* GetClosestNativeAnonymousSubtreeRootParentOrHost() const {
1475 // We could put this in nsIContentInlines.h or such to avoid this
1476 // reinterpret_cast, but it doesn't seem worth it.
1477 const auto* root = reinterpret_cast<const nsINode*>(
1478 GetClosestNativeAnonymousSubtreeRoot());
1479 if (!root) {
1480 return nullptr;
1482 if (nsIContent* parent = root->GetParent()) {
1483 return parent;
1485 if (MOZ_UNLIKELY(root->IsInShadowTree())) {
1486 return root->DoGetShadowHost();
1488 return nullptr;
1492 * Gets the root of the node tree for this content if it is in a shadow tree.
1494 mozilla::dom::ShadowRoot* GetContainingShadow() const;
1496 * Gets the shadow host if this content is in a shadow tree. That is, the host
1497 * of |GetContainingShadow|, if its not null.
1499 * @return The shadow host, if this is in shadow tree, or null.
1501 nsIContent* GetContainingShadowHost() const;
1503 bool IsInSVGUseShadowTree() const {
1504 return !!GetContainingSVGUseShadowHost();
1507 mozilla::dom::SVGUseElement* GetContainingSVGUseShadowHost() const {
1508 if (!IsInShadowTree()) {
1509 return nullptr;
1511 return DoGetContainingSVGUseShadowHost();
1514 // Whether this node has ever been part of a UA widget shadow tree.
1515 bool HasBeenInUAWidget() const { return HasFlag(NODE_HAS_BEEN_IN_UA_WIDGET); }
1517 // True for native anonymous content and for content in UA widgets.
1518 // Only nsIContent can fulfill this condition.
1519 bool ChromeOnlyAccess() const { return IsInNativeAnonymousSubtree(); }
1521 const nsIContent* GetChromeOnlyAccessSubtreeRootParent() const {
1522 return GetClosestNativeAnonymousSubtreeRootParentOrHost();
1525 bool IsInShadowTree() const { return HasFlag(NODE_IS_IN_SHADOW_TREE); }
1528 * Get whether this node is C++-generated anonymous content
1529 * @see nsIAnonymousContentCreator
1530 * @return whether this content is anonymous
1532 bool IsRootOfNativeAnonymousSubtree() const {
1533 NS_ASSERTION(
1534 !HasFlag(NODE_IS_NATIVE_ANONYMOUS_ROOT) || IsInNativeAnonymousSubtree(),
1535 "Some flags seem to be missing!");
1536 return HasFlag(NODE_IS_NATIVE_ANONYMOUS_ROOT);
1539 // Whether this node is the root of a ChromeOnlyAccess DOM subtree.
1540 bool IsRootOfChromeAccessOnlySubtree() const {
1541 return IsRootOfNativeAnonymousSubtree();
1545 * Returns true if |this| node is the closest common inclusive ancestor
1546 * (https://dom.spec.whatwg.org/#concept-tree-inclusive-ancestor) of the
1547 * start/end nodes of a Range in a Selection or a descendant of such a common
1548 * ancestor. This node is definitely not selected when |false| is returned,
1549 * but it may or may not be selected when |true| is returned.
1551 bool IsMaybeSelected() const {
1552 return IsDescendantOfClosestCommonInclusiveAncestorForRangeInSelection() ||
1553 IsClosestCommonInclusiveAncestorForRangeInSelection();
1557 * Return true if any part of (this, aStartOffset) .. (this, aEndOffset)
1558 * overlaps any nsRange in
1559 * GetClosestCommonInclusiveAncestorForRangeInSelection ranges (i.e.
1560 * where this is a descendant of a range's common inclusive ancestor node).
1561 * If a nsRange starts in (this, aEndOffset) or if it ends in
1562 * (this, aStartOffset) then it is non-overlapping and the result is false
1563 * for that nsRange. Collapsed ranges always counts as non-overlapping.
1565 * @param aStartOffset has to be less or equal to aEndOffset.
1567 bool IsSelected(uint32_t aStartOffset, uint32_t aEndOffset) const;
1570 * Get the root element of the text editor associated with this node or the
1571 * root element of the text editor of the ancestor 'TextControlElement' if
1572 * this is in its native anonymous subtree. I.e., this returns anonymous
1573 * `<div>` element of a `TextEditor`. Note that this can be used only for
1574 * getting root content of `<input>` or `<textarea>`. I.e., this method
1575 * doesn't support HTML editors. Note that this may create a `TextEditor`
1576 * instance, and it means that the `TextEditor` may modify its native
1577 * anonymous subtree and may run selection listeners.
1579 MOZ_CAN_RUN_SCRIPT mozilla::dom::Element* GetAnonymousRootElementOfTextEditor(
1580 mozilla::TextEditor** aTextEditor = nullptr);
1583 * Get the nearest selection root, ie. the node that will be selected if the
1584 * user does "Select All" while the focus is in this node. Note that if this
1585 * node is not in an editor, the result comes from the nsFrameSelection that
1586 * is related to aPresShell, so the result might not be the ancestor of this
1587 * node. Be aware that if this node and the computed selection limiter are
1588 * not in same subtree, this returns the root content of the closeset subtree.
1590 MOZ_CAN_RUN_SCRIPT nsIContent* GetSelectionRootContent(
1591 mozilla::PresShell* aPresShell);
1593 nsINodeList* ChildNodes();
1595 nsIContent* GetFirstChild() const { return mFirstChild; }
1597 nsIContent* GetLastChild() const;
1600 * Implementation is in Document.h, because it needs to cast from
1601 * Document* to nsINode*.
1603 Document* GetOwnerDocument() const;
1605 // TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230)
1606 MOZ_CAN_RUN_SCRIPT_BOUNDARY void Normalize();
1609 * Get the base URI for any relative URIs within this piece of
1610 * content. Generally, this is the document's base URI, but certain
1611 * content carries a local base for backward compatibility.
1613 * @return the base URI. May return null.
1615 virtual nsIURI* GetBaseURI(bool aTryUseXHRDocBaseURI = false) const = 0;
1616 nsIURI* GetBaseURIObject() const;
1619 * Return true if the node may be apz aware. There are two cases. One is that
1620 * the node is apz aware (such as HTMLInputElement with number type). The
1621 * other is that the node has apz aware listeners. This is a non-virtual
1622 * function which calls IsNodeApzAwareInternal only when the MayBeApzAware is
1623 * set. We check the details in IsNodeApzAwareInternal which may be overriden
1624 * by child classes
1626 bool IsNodeApzAware() const {
1627 return NodeMayBeApzAware() ? IsNodeApzAwareInternal() : false;
1631 * Override this function and set the flag MayBeApzAware in case the node has
1632 * to let APZC be aware of it. It's used when the node may handle the apz
1633 * aware events and may do preventDefault to stop APZC to do default actions.
1635 * For example, instead of scrolling page by APZ, we handle mouse wheel event
1636 * in HTMLInputElement with number type as increasing / decreasing its value.
1638 virtual bool IsNodeApzAwareInternal() const;
1640 void GetTextContent(nsAString& aTextContent, mozilla::OOMReporter& aError) {
1641 GetTextContentInternal(aTextContent, aError);
1643 void SetTextContent(const nsAString& aTextContent,
1644 nsIPrincipal* aSubjectPrincipal,
1645 mozilla::ErrorResult& aError) {
1646 SetTextContentInternal(aTextContent, aSubjectPrincipal, aError);
1648 void SetTextContent(const nsAString& aTextContent,
1649 mozilla::ErrorResult& aError) {
1650 SetTextContentInternal(aTextContent, nullptr, aError);
1653 mozilla::dom::Element* QuerySelector(const nsACString& aSelector,
1654 mozilla::ErrorResult& aResult);
1655 already_AddRefed<nsINodeList> QuerySelectorAll(const nsACString& aSelector,
1656 mozilla::ErrorResult& aResult);
1658 protected:
1659 // Document and ShadowRoot override this with its own (faster) version.
1660 // This should really only be called for elements and document fragments.
1661 mozilla::dom::Element* GetElementById(const nsAString& aId);
1663 void AppendChildToChildList(nsIContent* aKid);
1664 void InsertChildToChildList(nsIContent* aKid, nsIContent* aNextSibling);
1665 void DisconnectChild(nsIContent* aKid);
1667 public:
1668 void LookupPrefix(const nsAString& aNamespace, nsAString& aResult);
1669 bool IsDefaultNamespace(const nsAString& aNamespaceURI) {
1670 nsAutoString defaultNamespace;
1671 LookupNamespaceURI(u""_ns, defaultNamespace);
1672 return aNamespaceURI.Equals(defaultNamespace);
1674 void LookupNamespaceURI(const nsAString& aNamespacePrefix,
1675 nsAString& aNamespaceURI);
1677 nsIContent* GetNextSibling() const { return mNextSibling; }
1678 nsIContent* GetPreviousSibling() const;
1681 * Return true if the node is being removed from the parent, it means that
1682 * the node still knows the container which it's disconnected from, but the
1683 * node has already been removed from the child node chain of the container.
1684 * I.e., Return true between a call of DisconnectChild of the parent and
1685 * a call of UnbindFromTree of the node.
1687 bool IsBeingRemoved() const {
1688 return mParent && !mNextSibling && !mPreviousOrLastSibling;
1692 * Get the next node in the pre-order tree traversal of the DOM. If
1693 * aRoot is non-null, then it must be an ancestor of |this|
1694 * (possibly equal to |this|) and only nodes that are descendants of
1695 * aRoot, not including aRoot itself, will be returned. Returns
1696 * null if there are no more nodes to traverse.
1698 nsIContent* GetNextNode(const nsINode* aRoot = nullptr) const {
1699 return GetNextNodeImpl(aRoot, false);
1703 * Get the next node in the pre-order tree traversal of the DOM but ignoring
1704 * the children of this node. If aRoot is non-null, then it must be an
1705 * ancestor of |this| (possibly equal to |this|) and only nodes that are
1706 * descendants of aRoot, not including aRoot itself, will be returned.
1707 * Returns null if there are no more nodes to traverse.
1709 nsIContent* GetNextNonChildNode(const nsINode* aRoot = nullptr) const {
1710 return GetNextNodeImpl(aRoot, true);
1714 * Returns true if 'this' is either document or element or
1715 * document fragment and aOther is a descendant in the same
1716 * anonymous tree.
1718 bool Contains(const nsINode* aOther) const;
1720 bool UnoptimizableCCNode() const;
1723 * Fire a DOMNodeRemoved mutation event for all children of this node
1724 * TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230)
1726 MOZ_CAN_RUN_SCRIPT_BOUNDARY void FireNodeRemovedForChildren();
1728 void QueueDevtoolsAnonymousEvent(bool aIsRemove);
1730 private:
1731 mozilla::dom::SVGUseElement* DoGetContainingSVGUseShadowHost() const;
1733 nsIContent* GetNextNodeImpl(const nsINode* aRoot,
1734 const bool aSkipChildren) const {
1735 #ifdef DEBUG
1736 if (aRoot) {
1737 // TODO: perhaps nsINode::IsInclusiveDescendantOf could be used instead.
1738 const nsINode* cur = this;
1739 for (; cur; cur = cur->GetParentNode())
1740 if (cur == aRoot) break;
1741 NS_ASSERTION(cur, "aRoot not an ancestor of |this|?");
1743 #endif
1744 if (!aSkipChildren) {
1745 nsIContent* kid = GetFirstChild();
1746 if (kid) {
1747 return kid;
1750 if (this == aRoot) {
1751 return nullptr;
1753 const nsINode* cur = this;
1754 while (1) {
1755 nsIContent* next = cur->GetNextSibling();
1756 if (next) {
1757 return next;
1759 nsINode* parent = cur->GetParentNode();
1760 if (parent == aRoot) {
1761 return nullptr;
1763 cur = parent;
1765 MOZ_ASSERT_UNREACHABLE("How did we get here?");
1768 public:
1770 * Get the previous nsIContent in the pre-order tree traversal of the DOM. If
1771 * aRoot is non-null, then it must be an ancestor of |this|
1772 * (possibly equal to |this|) and only nsIContents that are descendants of
1773 * aRoot, including aRoot itself, will be returned. Returns
1774 * null if there are no more nsIContents to traverse.
1776 nsIContent* GetPreviousContent(const nsINode* aRoot = nullptr) const {
1777 #ifdef DEBUG
1778 if (aRoot) {
1779 // TODO: perhaps nsINode::IsInclusiveDescendantOf could be used instead.
1780 const nsINode* cur = this;
1781 for (; cur; cur = cur->GetParentNode())
1782 if (cur == aRoot) break;
1783 NS_ASSERTION(cur, "aRoot not an ancestor of |this|?");
1785 #endif
1787 if (this == aRoot) {
1788 return nullptr;
1790 nsIContent* cur = this->GetParent();
1791 nsIContent* iter = this->GetPreviousSibling();
1792 while (iter) {
1793 cur = iter;
1794 iter = reinterpret_cast<nsINode*>(iter)->GetLastChild();
1796 return cur;
1800 * Boolean flags
1802 private:
1803 enum BooleanFlag {
1804 // Set if we're being used from -moz-element
1805 NodeHasRenderingObservers,
1806 // Set if our parent chain (including this node itself) terminates
1807 // in a document
1808 IsInDocument,
1809 // Set if we're part of the composed doc.
1810 // https://dom.spec.whatwg.org/#connected
1811 IsConnected,
1812 // Set if mParent is an nsIContent
1813 ParentIsContent,
1814 // Set if this node is an Element
1815 NodeIsElement,
1816 // Set if the element has a non-empty id attribute. This can in rare
1817 // cases lie for nsXMLElement, such as when the node has been moved between
1818 // documents with different id mappings.
1819 ElementHasID,
1820 // Set if the element might have a class.
1821 ElementMayHaveClass,
1822 // Set if the element might have inline style.
1823 ElementMayHaveStyle,
1824 // Set if the element has a name attribute set.
1825 ElementHasName,
1826 // Set if the element has a part attribute set.
1827 ElementHasPart,
1828 // Set if the element might have a contenteditable attribute set.
1829 ElementMayHaveContentEditableAttr,
1830 // Set if the node is the closest common inclusive ancestor of the start/end
1831 // nodes of a Range that is in a Selection.
1832 NodeIsClosestCommonInclusiveAncestorForRangeInSelection,
1833 // Set if the node is a descendant of a node with the above bit set.
1834 NodeIsDescendantOfClosestCommonInclusiveAncestorForRangeInSelection,
1835 // Set if CanSkipInCC check has been done for this subtree root.
1836 NodeIsCCMarkedRoot,
1837 // Maybe set if this node is in black subtree.
1838 NodeIsCCBlackTree,
1839 // Maybe set if the node is a root of a subtree
1840 // which needs to be kept in the purple buffer.
1841 NodeIsPurpleRoot,
1842 // Set if the element has some style states locked
1843 ElementHasLockedStyleStates,
1844 // Set if element has pointer locked
1845 ElementHasPointerLock,
1846 // Set if the node may have DOMMutationObserver attached to it.
1847 NodeMayHaveDOMMutationObserver,
1848 // Set if node is Content
1849 NodeIsContent,
1850 // Set if the node has animations or transitions
1851 ElementHasAnimations,
1852 // Set if node has a dir attribute with a valid value (ltr, rtl, or auto).
1853 // Note that we cannot compute this from the dir attribute event state
1854 // flags, because we can't use those to distinguish
1855 // <bdi dir="some-invalid-value"> and <bdi dir="auto">.
1856 NodeHasValidDirAttribute,
1857 // Set if the node has dir=auto and has a property pointing to the text
1858 // node that determines its direction
1859 NodeHasDirAutoSet,
1860 // Set if the node is a text node descendant of a node with dir=auto
1861 // and has a TextNodeDirectionalityMap property listing the elements whose
1862 // direction it determines.
1863 NodeHasTextNodeDirectionalityMap,
1864 // Set if a node in the node's parent chain has dir=auto.
1865 NodeAncestorHasDirAuto,
1866 // Set if the node is handling a click.
1867 NodeHandlingClick,
1868 // Set if the element has a parser insertion mode other than "in body",
1869 // per the HTML5 "Parse state" section.
1870 ElementHasWeirdParserInsertionMode,
1871 // Parser sets this flag if it has notified about the node.
1872 ParserHasNotified,
1873 // Sets if the node is apz aware or we have apz aware listeners.
1874 MayBeApzAware,
1875 // Set if the element might have any kind of anonymous content children,
1876 // which would not be found through the element's children list.
1877 ElementMayHaveAnonymousChildren,
1878 // Set if element has CustomElementData.
1879 ElementHasCustomElementData,
1880 // Set if the element was created from prototype cache and
1881 // its l10n attributes haven't been changed.
1882 ElementCreatedFromPrototypeAndHasUnmodifiedL10n,
1883 // Guard value
1884 BooleanFlagCount
1887 void SetBoolFlag(BooleanFlag name, bool value) {
1888 static_assert(BooleanFlagCount <= 8 * sizeof(mBoolFlags),
1889 "Too many boolean flags");
1890 mBoolFlags = (mBoolFlags & ~(1 << name)) | (value << name);
1893 void SetBoolFlag(BooleanFlag name) {
1894 static_assert(BooleanFlagCount <= 8 * sizeof(mBoolFlags),
1895 "Too many boolean flags");
1896 mBoolFlags |= (1 << name);
1899 void ClearBoolFlag(BooleanFlag name) {
1900 static_assert(BooleanFlagCount <= 8 * sizeof(mBoolFlags),
1901 "Too many boolean flags");
1902 mBoolFlags &= ~(1 << name);
1905 bool GetBoolFlag(BooleanFlag name) const {
1906 static_assert(BooleanFlagCount <= 8 * sizeof(mBoolFlags),
1907 "Too many boolean flags");
1908 return mBoolFlags & (1 << name);
1911 public:
1912 bool HasRenderingObservers() const {
1913 return GetBoolFlag(NodeHasRenderingObservers);
1915 void SetHasRenderingObservers(bool aValue) {
1916 SetBoolFlag(NodeHasRenderingObservers, aValue);
1918 bool IsContent() const { return GetBoolFlag(NodeIsContent); }
1919 bool HasID() const { return GetBoolFlag(ElementHasID); }
1920 bool MayHaveClass() const { return GetBoolFlag(ElementMayHaveClass); }
1921 void SetMayHaveClass() { SetBoolFlag(ElementMayHaveClass); }
1922 bool MayHaveStyle() const { return GetBoolFlag(ElementMayHaveStyle); }
1923 bool HasName() const { return GetBoolFlag(ElementHasName); }
1924 bool HasPartAttribute() const { return GetBoolFlag(ElementHasPart); }
1925 bool MayHaveContentEditableAttr() const {
1926 return GetBoolFlag(ElementMayHaveContentEditableAttr);
1929 * https://dom.spec.whatwg.org/#concept-tree-inclusive-ancestor
1931 bool IsClosestCommonInclusiveAncestorForRangeInSelection() const {
1932 return GetBoolFlag(NodeIsClosestCommonInclusiveAncestorForRangeInSelection);
1935 * https://dom.spec.whatwg.org/#concept-tree-inclusive-ancestor
1937 void SetClosestCommonInclusiveAncestorForRangeInSelection() {
1938 SetBoolFlag(NodeIsClosestCommonInclusiveAncestorForRangeInSelection);
1941 * https://dom.spec.whatwg.org/#concept-tree-inclusive-ancestor
1943 void ClearClosestCommonInclusiveAncestorForRangeInSelection() {
1944 ClearBoolFlag(NodeIsClosestCommonInclusiveAncestorForRangeInSelection);
1947 * https://dom.spec.whatwg.org/#concept-tree-inclusive-ancestor
1949 bool IsDescendantOfClosestCommonInclusiveAncestorForRangeInSelection() const {
1950 return GetBoolFlag(
1951 NodeIsDescendantOfClosestCommonInclusiveAncestorForRangeInSelection);
1954 * https://dom.spec.whatwg.org/#concept-tree-inclusive-ancestor
1956 void SetDescendantOfClosestCommonInclusiveAncestorForRangeInSelection() {
1957 SetBoolFlag(
1958 NodeIsDescendantOfClosestCommonInclusiveAncestorForRangeInSelection);
1961 * https://dom.spec.whatwg.org/#concept-tree-inclusive-ancestor
1963 void ClearDescendantOfClosestCommonInclusiveAncestorForRangeInSelection() {
1964 ClearBoolFlag(
1965 NodeIsDescendantOfClosestCommonInclusiveAncestorForRangeInSelection);
1968 void SetCCMarkedRoot(bool aValue) { SetBoolFlag(NodeIsCCMarkedRoot, aValue); }
1969 bool CCMarkedRoot() const { return GetBoolFlag(NodeIsCCMarkedRoot); }
1970 void SetInCCBlackTree(bool aValue) { SetBoolFlag(NodeIsCCBlackTree, aValue); }
1971 bool InCCBlackTree() const { return GetBoolFlag(NodeIsCCBlackTree); }
1972 void SetIsPurpleRoot(bool aValue) { SetBoolFlag(NodeIsPurpleRoot, aValue); }
1973 bool IsPurpleRoot() const { return GetBoolFlag(NodeIsPurpleRoot); }
1974 bool MayHaveDOMMutationObserver() {
1975 return GetBoolFlag(NodeMayHaveDOMMutationObserver);
1977 void SetMayHaveDOMMutationObserver() {
1978 SetBoolFlag(NodeMayHaveDOMMutationObserver, true);
1980 bool HasListenerManager() { return HasFlag(NODE_HAS_LISTENERMANAGER); }
1981 bool HasPointerLock() const { return GetBoolFlag(ElementHasPointerLock); }
1982 void SetPointerLock() { SetBoolFlag(ElementHasPointerLock); }
1983 void ClearPointerLock() { ClearBoolFlag(ElementHasPointerLock); }
1984 bool MayHaveAnimations() const { return GetBoolFlag(ElementHasAnimations); }
1985 void SetMayHaveAnimations() { SetBoolFlag(ElementHasAnimations); }
1986 void ClearMayHaveAnimations() { ClearBoolFlag(ElementHasAnimations); }
1987 void SetHasValidDir() { SetBoolFlag(NodeHasValidDirAttribute); }
1988 void ClearHasValidDir() { ClearBoolFlag(NodeHasValidDirAttribute); }
1989 bool HasValidDir() const { return GetBoolFlag(NodeHasValidDirAttribute); }
1990 void SetHasDirAutoSet() {
1991 MOZ_ASSERT(NodeType() != TEXT_NODE, "SetHasDirAutoSet on text node");
1992 SetBoolFlag(NodeHasDirAutoSet);
1994 void ClearHasDirAutoSet() {
1995 MOZ_ASSERT(NodeType() != TEXT_NODE, "ClearHasDirAutoSet on text node");
1996 ClearBoolFlag(NodeHasDirAutoSet);
1998 bool HasDirAutoSet() const { return GetBoolFlag(NodeHasDirAutoSet); }
1999 void SetHasTextNodeDirectionalityMap() {
2000 MOZ_ASSERT(NodeType() == TEXT_NODE,
2001 "SetHasTextNodeDirectionalityMap on non-text node");
2002 SetBoolFlag(NodeHasTextNodeDirectionalityMap);
2004 void ClearHasTextNodeDirectionalityMap() {
2005 MOZ_ASSERT(NodeType() == TEXT_NODE,
2006 "ClearHasTextNodeDirectionalityMap on non-text node");
2007 ClearBoolFlag(NodeHasTextNodeDirectionalityMap);
2009 bool HasTextNodeDirectionalityMap() const {
2010 MOZ_ASSERT(NodeType() == TEXT_NODE,
2011 "HasTextNodeDirectionalityMap on non-text node");
2012 return GetBoolFlag(NodeHasTextNodeDirectionalityMap);
2015 void SetAncestorHasDirAuto() { SetBoolFlag(NodeAncestorHasDirAuto); }
2016 void ClearAncestorHasDirAuto() { ClearBoolFlag(NodeAncestorHasDirAuto); }
2017 bool AncestorHasDirAuto() const {
2018 return GetBoolFlag(NodeAncestorHasDirAuto);
2021 // Implemented in nsIContentInlines.h.
2022 inline bool NodeOrAncestorHasDirAuto() const;
2024 void SetParserHasNotified() { SetBoolFlag(ParserHasNotified); };
2025 bool HasParserNotified() { return GetBoolFlag(ParserHasNotified); }
2027 void SetMayBeApzAware() { SetBoolFlag(MayBeApzAware); }
2028 bool NodeMayBeApzAware() const { return GetBoolFlag(MayBeApzAware); }
2030 void SetMayHaveAnonymousChildren() {
2031 SetBoolFlag(ElementMayHaveAnonymousChildren);
2033 bool MayHaveAnonymousChildren() const {
2034 return GetBoolFlag(ElementMayHaveAnonymousChildren);
2037 void SetHasCustomElementData() { SetBoolFlag(ElementHasCustomElementData); }
2038 bool HasCustomElementData() const {
2039 return GetBoolFlag(ElementHasCustomElementData);
2042 void SetElementCreatedFromPrototypeAndHasUnmodifiedL10n() {
2043 SetBoolFlag(ElementCreatedFromPrototypeAndHasUnmodifiedL10n);
2045 bool HasElementCreatedFromPrototypeAndHasUnmodifiedL10n() {
2046 return GetBoolFlag(ElementCreatedFromPrototypeAndHasUnmodifiedL10n);
2048 void ClearElementCreatedFromPrototypeAndHasUnmodifiedL10n() {
2049 ClearBoolFlag(ElementCreatedFromPrototypeAndHasUnmodifiedL10n);
2052 protected:
2053 void SetParentIsContent(bool aValue) { SetBoolFlag(ParentIsContent, aValue); }
2054 void SetIsInDocument() { SetBoolFlag(IsInDocument); }
2055 void ClearInDocument() { ClearBoolFlag(IsInDocument); }
2056 void SetIsConnected(bool aConnected) { SetBoolFlag(IsConnected, aConnected); }
2057 void SetNodeIsContent() { SetBoolFlag(NodeIsContent); }
2058 void SetIsElement() { SetBoolFlag(NodeIsElement); }
2059 void SetHasID() { SetBoolFlag(ElementHasID); }
2060 void ClearHasID() { ClearBoolFlag(ElementHasID); }
2061 void SetMayHaveStyle() { SetBoolFlag(ElementMayHaveStyle); }
2062 void SetHasName() { SetBoolFlag(ElementHasName); }
2063 void ClearHasName() { ClearBoolFlag(ElementHasName); }
2064 void SetHasPartAttribute(bool aPart) { SetBoolFlag(ElementHasPart, aPart); }
2065 void SetMayHaveContentEditableAttr() {
2066 SetBoolFlag(ElementMayHaveContentEditableAttr);
2068 void SetHasLockedStyleStates() { SetBoolFlag(ElementHasLockedStyleStates); }
2069 void ClearHasLockedStyleStates() {
2070 ClearBoolFlag(ElementHasLockedStyleStates);
2072 bool HasLockedStyleStates() const {
2073 return GetBoolFlag(ElementHasLockedStyleStates);
2075 void SetHasWeirdParserInsertionMode() {
2076 SetBoolFlag(ElementHasWeirdParserInsertionMode);
2078 bool HasWeirdParserInsertionMode() const {
2079 return GetBoolFlag(ElementHasWeirdParserInsertionMode);
2081 bool HandlingClick() const { return GetBoolFlag(NodeHandlingClick); }
2082 void SetHandlingClick() { SetBoolFlag(NodeHandlingClick); }
2083 void ClearHandlingClick() { ClearBoolFlag(NodeHandlingClick); }
2085 void SetSubtreeRootPointer(nsINode* aSubtreeRoot) {
2086 NS_ASSERTION(aSubtreeRoot, "aSubtreeRoot can never be null!");
2087 NS_ASSERTION(!(IsContent() && IsInUncomposedDoc()) && !IsInShadowTree(),
2088 "Shouldn't be here!");
2089 mSubtreeRoot = aSubtreeRoot;
2092 void ClearSubtreeRootPointer() { mSubtreeRoot = nullptr; }
2094 public:
2095 // Makes nsINode object to keep aObject alive.
2096 void BindObject(nsISupports* aObject);
2097 // After calling UnbindObject nsINode object doesn't keep
2098 // aObject alive anymore.
2099 void UnbindObject(nsISupports* aObject);
2101 void GenerateXPath(nsAString& aResult);
2103 already_AddRefed<mozilla::dom::AccessibleNode> GetAccessibleNode();
2106 * Returns the length of this node, as specified at
2107 * <http://dvcs.w3.org/hg/domcore/raw-file/tip/Overview.html#concept-node-length>
2109 uint32_t Length() const;
2111 void GetNodeName(mozilla::dom::DOMString& aNodeName) {
2112 const nsString& nodeName = NodeName();
2113 aNodeName.SetKnownLiveString(nodeName);
2115 [[nodiscard]] nsresult GetBaseURI(nsAString& aBaseURI) const;
2116 // Return the base URI for the document.
2117 // The returned value may differ if the document is loaded via XHR, and
2118 // when accessed from chrome privileged script and
2119 // from content privileged script for compatibility.
2120 void GetBaseURIFromJS(nsAString& aBaseURI, CallerType aCallerType,
2121 ErrorResult& aRv) const;
2122 bool HasChildNodes() const { return HasChildren(); }
2124 // See nsContentUtils::PositionIsBefore for aThisIndex and aOtherIndex usage.
2125 uint16_t CompareDocumentPosition(
2126 nsINode& aOther, mozilla::Maybe<uint32_t>* aThisIndex = nullptr,
2127 mozilla::Maybe<uint32_t>* aOtherIndex = nullptr) const;
2128 void GetNodeValue(nsAString& aNodeValue) { GetNodeValueInternal(aNodeValue); }
2129 void SetNodeValue(const nsAString& aNodeValue, mozilla::ErrorResult& aError) {
2130 SetNodeValueInternal(aNodeValue, aError);
2132 virtual void GetNodeValueInternal(nsAString& aNodeValue);
2133 virtual void SetNodeValueInternal(const nsAString& aNodeValue,
2134 mozilla::ErrorResult& aError) {
2135 // The DOM spec says that when nodeValue is defined to be null "setting it
2136 // has no effect", so we don't throw an exception.
2138 void EnsurePreInsertionValidity(nsINode& aNewChild, nsINode* aRefChild,
2139 mozilla::ErrorResult& aError);
2140 nsINode* InsertBefore(nsINode& aNode, nsINode* aChild,
2141 mozilla::ErrorResult& aError) {
2142 return ReplaceOrInsertBefore(false, &aNode, aChild, aError);
2146 * See <https://dom.spec.whatwg.org/#dom-node-appendchild>.
2148 nsINode* AppendChild(nsINode& aNode, mozilla::ErrorResult& aError) {
2149 return InsertBefore(aNode, nullptr, aError);
2152 nsINode* ReplaceChild(nsINode& aNode, nsINode& aChild,
2153 mozilla::ErrorResult& aError) {
2154 return ReplaceOrInsertBefore(true, &aNode, &aChild, aError);
2156 // TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230)
2157 MOZ_CAN_RUN_SCRIPT_BOUNDARY nsINode* RemoveChild(
2158 nsINode& aChild, mozilla::ErrorResult& aError);
2159 already_AddRefed<nsINode> CloneNode(bool aDeep, mozilla::ErrorResult& aError);
2160 bool IsSameNode(nsINode* aNode);
2161 bool IsEqualNode(nsINode* aNode);
2162 void GetNamespaceURI(nsAString& aNamespaceURI) const {
2163 mNodeInfo->GetNamespaceURI(aNamespaceURI);
2165 #ifdef MOZILLA_INTERNAL_API
2166 void GetPrefix(nsAString& aPrefix) { mNodeInfo->GetPrefix(aPrefix); }
2167 #endif
2168 void GetLocalName(mozilla::dom::DOMString& aLocalName) const {
2169 const nsString& localName = LocalName();
2170 aLocalName.SetKnownLiveString(localName);
2173 nsDOMAttributeMap* GetAttributes();
2175 // Helper method to remove this node from its parent. This is not exposed
2176 // through WebIDL.
2177 // Only call this if the node has a parent node.
2178 nsresult RemoveFromParent() {
2179 nsINode* parent = GetParentNode();
2180 mozilla::ErrorResult rv;
2181 parent->RemoveChild(*this, rv);
2182 return rv.StealNSResult();
2185 // ChildNode methods
2186 inline mozilla::dom::Element* GetPreviousElementSibling() const;
2187 inline mozilla::dom::Element* GetNextElementSibling() const;
2189 MOZ_CAN_RUN_SCRIPT void Before(const Sequence<OwningNodeOrString>& aNodes,
2190 ErrorResult& aRv);
2191 MOZ_CAN_RUN_SCRIPT void After(const Sequence<OwningNodeOrString>& aNodes,
2192 ErrorResult& aRv);
2193 MOZ_CAN_RUN_SCRIPT void ReplaceWith(
2194 const Sequence<OwningNodeOrString>& aNodes, ErrorResult& aRv);
2196 * Remove this node from its parent, if any.
2198 void Remove();
2200 // ParentNode methods
2201 mozilla::dom::Element* GetFirstElementChild() const;
2202 mozilla::dom::Element* GetLastElementChild() const;
2204 already_AddRefed<nsIHTMLCollection> GetElementsByAttribute(
2205 const nsAString& aAttribute, const nsAString& aValue);
2206 already_AddRefed<nsIHTMLCollection> GetElementsByAttributeNS(
2207 const nsAString& aNamespaceURI, const nsAString& aAttribute,
2208 const nsAString& aValue, ErrorResult& aRv);
2210 MOZ_CAN_RUN_SCRIPT void Prepend(const Sequence<OwningNodeOrString>& aNodes,
2211 ErrorResult& aRv);
2212 MOZ_CAN_RUN_SCRIPT void Append(const Sequence<OwningNodeOrString>& aNodes,
2213 ErrorResult& aRv);
2214 MOZ_CAN_RUN_SCRIPT void ReplaceChildren(
2215 const Sequence<OwningNodeOrString>& aNodes, ErrorResult& aRv);
2216 MOZ_CAN_RUN_SCRIPT void ReplaceChildren(nsINode* aNode, ErrorResult& aRv);
2218 void GetBoxQuads(const BoxQuadOptions& aOptions,
2219 nsTArray<RefPtr<DOMQuad>>& aResult, CallerType aCallerType,
2220 ErrorResult& aRv);
2222 void GetBoxQuadsFromWindowOrigin(const BoxQuadOptions& aOptions,
2223 nsTArray<RefPtr<DOMQuad>>& aResult,
2224 ErrorResult& aRv);
2226 already_AddRefed<DOMQuad> ConvertQuadFromNode(
2227 DOMQuad& aQuad, const TextOrElementOrDocument& aFrom,
2228 const ConvertCoordinateOptions& aOptions, CallerType aCallerType,
2229 ErrorResult& aRv);
2230 already_AddRefed<DOMQuad> ConvertRectFromNode(
2231 DOMRectReadOnly& aRect, const TextOrElementOrDocument& aFrom,
2232 const ConvertCoordinateOptions& aOptions, CallerType aCallerType,
2233 ErrorResult& aRv);
2234 already_AddRefed<DOMPoint> ConvertPointFromNode(
2235 const DOMPointInit& aPoint, const TextOrElementOrDocument& aFrom,
2236 const ConvertCoordinateOptions& aOptions, CallerType aCallerType,
2237 ErrorResult& aRv);
2240 * See nsSlots::mClosestCommonInclusiveAncestorRanges.
2242 const mozilla::LinkedList<mozilla::dom::AbstractRange>*
2243 GetExistingClosestCommonInclusiveAncestorRanges() const {
2244 if (!HasSlots()) {
2245 return nullptr;
2247 return GetExistingSlots()->mClosestCommonInclusiveAncestorRanges.get();
2251 * See nsSlots::mClosestCommonInclusiveAncestorRanges.
2253 mozilla::LinkedList<mozilla::dom::AbstractRange>*
2254 GetExistingClosestCommonInclusiveAncestorRanges() {
2255 if (!HasSlots()) {
2256 return nullptr;
2258 return GetExistingSlots()->mClosestCommonInclusiveAncestorRanges.get();
2262 * See nsSlots::mClosestCommonInclusiveAncestorRanges.
2264 mozilla::UniquePtr<mozilla::LinkedList<mozilla::dom::AbstractRange>>&
2265 GetClosestCommonInclusiveAncestorRangesPtr() {
2266 return Slots()->mClosestCommonInclusiveAncestorRanges;
2269 nsIWeakReference* GetExistingWeakReference() {
2270 return HasSlots() ? GetExistingSlots()->mWeakReference : nullptr;
2273 protected:
2274 // Override this function to create a custom slots class.
2275 // Must not return null.
2276 virtual nsINode::nsSlots* CreateSlots();
2278 bool HasSlots() const { return mSlots != nullptr; }
2280 nsSlots* GetExistingSlots() const { return mSlots; }
2282 nsSlots* Slots() {
2283 if (!HasSlots()) {
2284 mSlots = CreateSlots();
2285 MOZ_ASSERT(mSlots);
2287 return GetExistingSlots();
2291 * Invalidate cached child array inside mChildNodes
2292 * of type nsParentNodeChildContentList.
2294 void InvalidateChildNodes();
2296 virtual void GetTextContentInternal(nsAString& aTextContent,
2297 mozilla::OOMReporter& aError);
2298 virtual void SetTextContentInternal(const nsAString& aTextContent,
2299 nsIPrincipal* aSubjectPrincipal,
2300 mozilla::ErrorResult& aError) {}
2302 void EnsurePreInsertionValidity1(mozilla::ErrorResult& aError);
2303 void EnsurePreInsertionValidity2(bool aReplace, nsINode& aNewChild,
2304 nsINode* aRefChild,
2305 mozilla::ErrorResult& aError);
2306 // TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230)
2307 MOZ_CAN_RUN_SCRIPT_BOUNDARY nsINode* ReplaceOrInsertBefore(
2308 bool aReplace, nsINode* aNewChild, nsINode* aRefChild,
2309 mozilla::ErrorResult& aError);
2312 * Returns the Element that should be used for resolving namespaces
2313 * on this node (ie the ownerElement for attributes, the documentElement for
2314 * documents, the node itself for elements and for other nodes the parentNode
2315 * if it is an element).
2317 virtual mozilla::dom::Element* GetNameSpaceElement() = 0;
2320 * Parse the given selector string into a servo SelectorList.
2322 * Never returns null if aRv is not failing.
2324 * Note that the selector list returned here is owned by the owner doc's
2325 * selector cache.
2327 const mozilla::StyleSelectorList* ParseSelectorList(
2328 const nsACString& aSelectorString, mozilla::ErrorResult&);
2330 public:
2331 /* Event stuff that documents and elements share.
2333 Note that we include DOCUMENT_ONLY_EVENT events here so that we
2334 can forward all the document stuff to this implementation.
2336 #define EVENT(name_, id_, type_, struct_) \
2337 mozilla::dom::EventHandlerNonNull* GetOn##name_() { \
2338 return GetEventHandler(nsGkAtoms::on##name_); \
2340 void SetOn##name_(mozilla::dom::EventHandlerNonNull* handler) { \
2341 SetEventHandler(nsGkAtoms::on##name_, handler); \
2343 #define TOUCH_EVENT EVENT
2344 #define DOCUMENT_ONLY_EVENT EVENT
2345 #include "mozilla/EventNameList.h"
2346 #undef DOCUMENT_ONLY_EVENT
2347 #undef TOUCH_EVENT
2348 #undef EVENT
2350 NodeSelectorFlags GetSelectorFlags() const {
2351 return static_cast<NodeSelectorFlags>(mSelectorFlags.Get());
2354 protected:
2355 static bool Traverse(nsINode* tmp, nsCycleCollectionTraversalCallback& cb);
2356 static void Unlink(nsINode* tmp);
2358 RefPtr<mozilla::dom::NodeInfo> mNodeInfo;
2360 // mParent is an owning ref most of the time, except for the case of document
2361 // nodes, so it cannot be represented by nsCOMPtr, so mark is as
2362 // MOZ_OWNING_REF.
2363 nsINode* MOZ_OWNING_REF mParent;
2365 private:
2366 #ifndef BOOL_FLAGS_ON_WRAPPER_CACHE
2367 // Boolean flags.
2368 uint32_t mBoolFlags;
2369 #endif
2371 mozilla::RustCell<uint32_t> mSelectorFlags{0};
2373 uint32_t mChildCount;
2375 protected:
2376 // mNextSibling and mFirstChild are strong references while
2377 // mPreviousOrLastSibling is a weak ref. |mFirstChild->mPreviousOrLastSibling|
2378 // points to the last child node.
2379 nsCOMPtr<nsIContent> mFirstChild;
2380 nsCOMPtr<nsIContent> mNextSibling;
2381 nsIContent* MOZ_NON_OWNING_REF mPreviousOrLastSibling;
2383 union {
2384 // Pointer to our primary frame. Might be null.
2385 nsIFrame* mPrimaryFrame;
2387 // Pointer to the root of our subtree. Might be null.
2388 // This reference is non-owning and safe, since it either points to the
2389 // object itself, or is reset by ClearSubtreeRootPointer.
2390 nsINode* MOZ_NON_OWNING_REF mSubtreeRoot;
2393 // Storage for more members that are usually not needed; allocated lazily.
2394 nsSlots* mSlots;
2397 NON_VIRTUAL_ADDREF_RELEASE(nsINode)
2399 inline nsINode* mozilla::dom::EventTarget::GetAsNode() {
2400 return IsNode() ? AsNode() : nullptr;
2403 inline const nsINode* mozilla::dom::EventTarget::GetAsNode() const {
2404 return const_cast<mozilla::dom::EventTarget*>(this)->GetAsNode();
2407 inline nsINode* mozilla::dom::EventTarget::AsNode() {
2408 MOZ_DIAGNOSTIC_ASSERT(IsNode());
2409 return static_cast<nsINode*>(this);
2412 inline const nsINode* mozilla::dom::EventTarget::AsNode() const {
2413 MOZ_DIAGNOSTIC_ASSERT(IsNode());
2414 return static_cast<const nsINode*>(this);
2417 // Useful inline function for getting a node given an nsIContent and a Document.
2418 // Returns the first argument cast to nsINode if it is non-null, otherwise
2419 // returns the second (which may be null). We use type variables instead of
2420 // nsIContent* and Document* because the actual types must be
2421 // known for the cast to work.
2422 template <class C, class D>
2423 inline nsINode* NODE_FROM(C& aContent, D& aDocument) {
2424 if (aContent) return static_cast<nsINode*>(aContent);
2425 return static_cast<nsINode*>(aDocument);
2428 NS_DEFINE_STATIC_IID_ACCESSOR(nsINode, NS_INODE_IID)
2430 inline nsISupports* ToSupports(nsINode* aPointer) { return aPointer; }
2432 // Some checks are faster to do on nsIContent or Element than on
2433 // nsINode, so spit out FromNode versions taking those types too.
2434 #define NS_IMPL_FROMNODE_GENERIC(_class, _check, _const) \
2435 template <typename T> \
2436 static auto FromNode(_const T& aNode) \
2437 -> decltype(static_cast<_const _class*>(&aNode)) { \
2438 return aNode._check ? static_cast<_const _class*>(&aNode) : nullptr; \
2440 template <typename T> \
2441 static _const _class* FromNode(_const T* aNode) { \
2442 return FromNode(*aNode); \
2444 template <typename T> \
2445 static _const _class* FromNodeOrNull(_const T* aNode) { \
2446 return aNode ? FromNode(*aNode) : nullptr; \
2448 template <typename T> \
2449 static auto FromEventTarget(_const T& aEventTarget) \
2450 -> decltype(static_cast<_const _class*>(&aEventTarget)) { \
2451 return aEventTarget.IsNode() && aEventTarget.AsNode()->_check \
2452 ? static_cast<_const _class*>(&aEventTarget) \
2453 : nullptr; \
2455 template <typename T> \
2456 static _const _class* FromEventTarget(_const T* aEventTarget) { \
2457 return FromEventTarget(*aEventTarget); \
2459 template <typename T> \
2460 static _const _class* FromEventTargetOrNull(_const T* aEventTarget) { \
2461 return aEventTarget ? FromEventTarget(*aEventTarget) : nullptr; \
2464 #define NS_IMPL_FROMNODE_HELPER(_class, _check) \
2465 NS_IMPL_FROMNODE_GENERIC(_class, _check, ) \
2466 NS_IMPL_FROMNODE_GENERIC(_class, _check, const) \
2468 template <typename T> \
2469 static _class* FromNode(T&& aNode) { \
2470 /* We need the double-cast in case aNode is a smartptr. Those */ \
2471 /* can cast to superclasses of the type they're templated on, */ \
2472 /* but not directly to subclasses. */ \
2473 return aNode->_check ? static_cast<_class*>(static_cast<nsINode*>(aNode)) \
2474 : nullptr; \
2476 template <typename T> \
2477 static _class* FromNodeOrNull(T&& aNode) { \
2478 return aNode ? FromNode(aNode) : nullptr; \
2480 template <typename T> \
2481 static _class* FromEventTarget(T&& aEventTarget) { \
2482 /* We need the double-cast in case aEventTarget is a smartptr. Those */ \
2483 /* can cast to superclasses of the type they're templated on, */ \
2484 /* but not directly to subclasses. */ \
2485 return aEventTarget->IsNode() && aEventTarget->AsNode()->_check \
2486 ? static_cast<_class*>(static_cast<EventTarget*>(aEventTarget)) \
2487 : nullptr; \
2489 template <typename T> \
2490 static _class* FromEventTargetOrNull(T&& aEventTarget) { \
2491 return aEventTarget ? FromEventTarget(aEventTarget) : nullptr; \
2494 #define NS_IMPL_FROMNODE(_class, _nsid) \
2495 NS_IMPL_FROMNODE_HELPER(_class, IsInNamespace(_nsid))
2497 #define NS_IMPL_FROMNODE_WITH_TAG(_class, _nsid, _tag) \
2498 NS_IMPL_FROMNODE_HELPER(_class, NodeInfo()->Equals(nsGkAtoms::_tag, _nsid))
2500 #define NS_IMPL_FROMNODE_HTML_WITH_TAG(_class, _tag) \
2501 NS_IMPL_FROMNODE_WITH_TAG(_class, kNameSpaceID_XHTML, _tag)
2503 #endif /* nsINode_h___ */