Bug 1750871 - run mochitest-remote on fission everywhere. r=releng-reviewers,aki
[gecko.git] / dom / base / nsINode.h
blob3991f8007498f04a07b7a46b82fb41c944330ffa
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/Likely.h"
11 #include "mozilla/UniquePtr.h"
12 #include "nsCOMPtr.h" // for member, local
13 #include "nsGkAtoms.h" // for nsGkAtoms::baseURIProperty
14 #include "mozilla/dom/NodeInfo.h" // member (in nsCOMPtr)
15 #include "nsIWeakReference.h"
16 #include "nsNodeInfoManager.h" // for use in NodePrincipal()
17 #include "nsPropertyTable.h" // for typedefs
18 #include "nsTObserverArray.h" // for member
19 #include "mozilla/ErrorResult.h"
20 #include "mozilla/LinkedList.h"
21 #include "mozilla/MemoryReporting.h"
22 #include "mozilla/dom/EventTarget.h" // for base class
23 #include "js/TypeDecls.h" // for Handle, Value, JSObject, JSContext
24 #include "mozilla/dom/DOMString.h"
25 #include "mozilla/dom/BindingDeclarations.h"
26 #include "mozilla/dom/NodeBinding.h"
27 #include "nsTHashtable.h"
28 #include <iosfwd>
30 // Including 'windows.h' will #define GetClassInfo to something else.
31 #ifdef XP_WIN
32 # ifdef GetClassInfo
33 # undef GetClassInfo
34 # endif
35 #endif
37 class AttrArray;
38 class nsAttrChildContentList;
39 template <typename T>
40 class nsCOMArray;
41 class nsDOMAttributeMap;
42 class nsIAnimationObserver;
43 class nsIContent;
44 class nsIContentSecurityPolicy;
45 class nsIFrame;
46 class nsIHTMLCollection;
47 class nsIMutationObserver;
48 class nsINode;
49 class nsINodeList;
50 class nsIPrincipal;
51 class nsIURI;
52 class nsNodeSupportsWeakRefTearoff;
53 class nsDOMMutationObserver;
54 class nsRange;
55 class nsWindowSizes;
56 struct RawServoSelectorList;
58 namespace mozilla {
59 class EventListenerManager;
60 template <typename T>
61 class Maybe;
62 class PresShell;
63 class TextEditor;
64 namespace dom {
65 /**
66 * @return true if aChar is what the WHATWG defines as a 'ascii whitespace'.
67 * https://infra.spec.whatwg.org/#ascii-whitespace
69 inline bool IsSpaceCharacter(char16_t aChar) {
70 return aChar == ' ' || aChar == '\t' || aChar == '\n' || aChar == '\r' ||
71 aChar == '\f';
73 inline bool IsSpaceCharacter(char aChar) {
74 return aChar == ' ' || aChar == '\t' || aChar == '\n' || aChar == '\r' ||
75 aChar == '\f';
77 class AccessibleNode;
78 template <typename T>
79 class AncestorsOfTypeIterator;
80 struct BoxQuadOptions;
81 struct ConvertCoordinateOptions;
82 class DocGroup;
83 class Document;
84 class DocumentFragment;
85 class DocumentOrShadowRoot;
86 class DOMPoint;
87 class DOMQuad;
88 class DOMRectReadOnly;
89 class Element;
90 class EventHandlerNonNull;
91 template <typename T>
92 class FlatTreeAncestorsOfTypeIterator;
93 template <typename T>
94 class InclusiveAncestorsOfTypeIterator;
95 template <typename T>
96 class InclusiveFlatTreeAncestorsOfTypeIterator;
97 class LinkStyle;
98 class MutationObservers;
99 template <typename T>
100 class Optional;
101 class OwningNodeOrString;
102 template <typename>
103 class Sequence;
104 class ShadowRoot;
105 class SVGUseElement;
106 class Text;
107 class TextOrElementOrDocument;
108 struct DOMPointInit;
109 struct GetRootNodeOptions;
110 enum class CallerType : uint32_t;
111 } // namespace dom
112 } // namespace mozilla
114 #define NODE_FLAG_BIT(n_) \
115 (nsWrapperCache::FlagsType(1U) << (WRAPPER_CACHE_FLAGS_BITS_USED + (n_)))
117 enum {
118 // This bit will be set if the node has a listener manager.
119 NODE_HAS_LISTENERMANAGER = NODE_FLAG_BIT(0),
121 // Whether this node has had any properties set on it
122 NODE_HAS_PROPERTIES = NODE_FLAG_BIT(1),
124 // Whether the node has some ancestor, possibly itself, that is native
125 // anonymous. This includes ancestors crossing XBL scopes, in cases when an
126 // XBL binding is attached to an element which has a native anonymous
127 // ancestor. This flag is set-once: once a node has it, it must not be
128 // removed.
129 // NOTE: Should only be used on nsIContent nodes
130 NODE_IS_IN_NATIVE_ANONYMOUS_SUBTREE = NODE_FLAG_BIT(2),
132 // Whether this node is the root of a native anonymous (from the perspective
133 // of its parent) subtree. This flag is set-once: once a node has it, it
134 // must not be removed.
135 // NOTE: Should only be used on nsIContent nodes
136 NODE_IS_NATIVE_ANONYMOUS_ROOT = NODE_FLAG_BIT(3),
138 NODE_IS_EDITABLE = NODE_FLAG_BIT(4),
140 // Whether the node participates in a shadow tree.
141 NODE_IS_IN_SHADOW_TREE = NODE_FLAG_BIT(5),
143 // Node has an :empty or :-moz-only-whitespace selector
144 NODE_HAS_EMPTY_SELECTOR = NODE_FLAG_BIT(6),
146 // A child of the node has a selector such that any insertion,
147 // removal, or appending of children requires restyling the parent.
148 NODE_HAS_SLOW_SELECTOR = NODE_FLAG_BIT(7),
150 // A child of the node has a :first-child, :-moz-first-node,
151 // :only-child, :last-child or :-moz-last-node selector.
152 NODE_HAS_EDGE_CHILD_SELECTOR = NODE_FLAG_BIT(8),
154 // A child of the node has a selector such that any insertion or
155 // removal of children requires restyling later siblings of that
156 // element. Additionally (in this manner it is stronger than
157 // NODE_HAS_SLOW_SELECTOR), if a child's style changes due to any
158 // other content tree changes (e.g., the child changes to or from
159 // matching :empty due to a grandchild insertion or removal), the
160 // child's later siblings must also be restyled.
161 NODE_HAS_SLOW_SELECTOR_LATER_SIBLINGS = NODE_FLAG_BIT(9),
163 NODE_ALL_SELECTOR_FLAGS = NODE_HAS_EMPTY_SELECTOR | NODE_HAS_SLOW_SELECTOR |
164 NODE_HAS_EDGE_CHILD_SELECTOR |
165 NODE_HAS_SLOW_SELECTOR_LATER_SIBLINGS,
167 // This node needs to go through frame construction to get a frame (or
168 // undisplayed entry).
169 NODE_NEEDS_FRAME = NODE_FLAG_BIT(10),
171 // At least one descendant in the flattened tree has NODE_NEEDS_FRAME set.
172 // This should be set on every node on the flattened tree path between the
173 // node(s) with NODE_NEEDS_FRAME and the root content.
174 NODE_DESCENDANTS_NEED_FRAMES = NODE_FLAG_BIT(11),
176 // Set if the node has the accesskey attribute set.
177 NODE_HAS_ACCESSKEY = NODE_FLAG_BIT(12),
179 // Set if the node has right-to-left directionality
180 NODE_HAS_DIRECTION_RTL = NODE_FLAG_BIT(13),
182 // Set if the node has left-to-right directionality
183 NODE_HAS_DIRECTION_LTR = NODE_FLAG_BIT(14),
185 NODE_ALL_DIRECTION_FLAGS = NODE_HAS_DIRECTION_LTR | NODE_HAS_DIRECTION_RTL,
187 NODE_HAS_BEEN_IN_UA_WIDGET = NODE_FLAG_BIT(15),
189 // Set if the node has a nonce value and a header delivered CSP.
190 NODE_HAS_NONCE_AND_HEADER_CSP = NODE_FLAG_BIT(16),
192 NODE_KEEPS_DOMARENA = NODE_FLAG_BIT(17),
193 // Remaining bits are node type specific.
194 NODE_TYPE_SPECIFIC_BITS_OFFSET = 18
197 // Make sure we have space for our bits
198 #define ASSERT_NODE_FLAGS_SPACE(n) \
199 static_assert(WRAPPER_CACHE_FLAGS_BITS_USED + (n) <= \
200 sizeof(nsWrapperCache::FlagsType) * 8, \
201 "Not enough space for our bits")
202 ASSERT_NODE_FLAGS_SPACE(NODE_TYPE_SPECIFIC_BITS_OFFSET);
205 * Class used to detect unexpected mutations. To use the class create an
206 * nsMutationGuard on the stack before unexpected mutations could occur.
207 * You can then at any time call Mutated to check if any unexpected mutations
208 * have occurred.
210 class nsMutationGuard {
211 public:
212 nsMutationGuard() { mStartingGeneration = sGeneration; }
215 * Returns true if any unexpected mutations have occurred. You can pass in
216 * an 8-bit ignore count to ignore a number of expected mutations.
218 * We don't need to care about overflow because subtraction of uint64_t's is
219 * finding the difference between two elements of the group Z < 2^64. Once
220 * we know the difference between two elements we only need to check that is
221 * less than the given number of mutations to know less than that many
222 * mutations occured. Assuming constant 1ns mutations it would take 584
223 * years for sGeneration to fully wrap around so we can ignore a guard living
224 * through a full wrap around.
226 bool Mutated(uint8_t aIgnoreCount) {
227 return (sGeneration - mStartingGeneration) > aIgnoreCount;
230 // This function should be called whenever a mutation that we want to keep
231 // track of happen. For now this is only done when children are added or
232 // removed, but we might do it for attribute changes too in the future.
233 static void DidMutate() { sGeneration++; }
235 private:
236 // This is the value sGeneration had when the guard was constructed.
237 uint64_t mStartingGeneration;
239 // This value is incremented on every mutation, for the life of the process.
240 static uint64_t sGeneration;
244 * A class that implements nsIWeakReference
246 class nsNodeWeakReference final : public nsIWeakReference {
247 public:
248 explicit nsNodeWeakReference(nsINode* aNode);
250 // nsISupports
251 NS_DECL_ISUPPORTS
253 // nsIWeakReference
254 NS_DECL_NSIWEAKREFERENCE
255 size_t SizeOfOnlyThis(mozilla::MallocSizeOf aMallocSizeOf) const override;
257 void NoticeNodeDestruction() { mObject = nullptr; }
259 private:
260 ~nsNodeWeakReference();
263 // This should be used for any nsINode sub-class that has fields of its own
264 // that it needs to measure; any sub-class that doesn't use it will inherit
265 // AddSizeOfExcludingThis from its super-class. AddSizeOfIncludingThis() need
266 // not be defined, it is inherited from nsINode.
267 #define NS_DECL_ADDSIZEOFEXCLUDINGTHIS \
268 virtual void AddSizeOfExcludingThis(nsWindowSizes& aSizes, \
269 size_t* aNodeSize) const override;
271 // IID for the nsINode interface
272 // Must be kept in sync with xpcom/rust/xpcom/src/interfaces/nonidl.rs
273 #define NS_INODE_IID \
275 0x70ba4547, 0x7699, 0x44fc, { \
276 0xb3, 0x20, 0x52, 0xdb, 0xe3, 0xd1, 0xf9, 0x0a \
281 * An internal interface that abstracts some DOMNode-related parts that both
282 * nsIContent and Document share. An instance of this interface has a list
283 * of nsIContent children and provides access to them.
285 class nsINode : public mozilla::dom::EventTarget {
286 #ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
287 void AssertInvariantsOnNodeInfoChange();
288 #endif
289 public:
290 using BoxQuadOptions = mozilla::dom::BoxQuadOptions;
291 using ConvertCoordinateOptions = mozilla::dom::ConvertCoordinateOptions;
292 using DocGroup = mozilla::dom::DocGroup;
293 using Document = mozilla::dom::Document;
294 using DOMPoint = mozilla::dom::DOMPoint;
295 using DOMPointInit = mozilla::dom::DOMPointInit;
296 using DOMQuad = mozilla::dom::DOMQuad;
297 using DOMRectReadOnly = mozilla::dom::DOMRectReadOnly;
298 using OwningNodeOrString = mozilla::dom::OwningNodeOrString;
299 using TextOrElementOrDocument = mozilla::dom::TextOrElementOrDocument;
300 using CallerType = mozilla::dom::CallerType;
301 using ErrorResult = mozilla::ErrorResult;
303 // XXXbz Maybe we should codegen a class holding these constants and
304 // inherit from it...
305 static const auto ELEMENT_NODE = mozilla::dom::Node_Binding::ELEMENT_NODE;
306 static const auto ATTRIBUTE_NODE = mozilla::dom::Node_Binding::ATTRIBUTE_NODE;
307 static const auto TEXT_NODE = mozilla::dom::Node_Binding::TEXT_NODE;
308 static const auto CDATA_SECTION_NODE =
309 mozilla::dom::Node_Binding::CDATA_SECTION_NODE;
310 static const auto ENTITY_REFERENCE_NODE =
311 mozilla::dom::Node_Binding::ENTITY_REFERENCE_NODE;
312 static const auto ENTITY_NODE = mozilla::dom::Node_Binding::ENTITY_NODE;
313 static const auto PROCESSING_INSTRUCTION_NODE =
314 mozilla::dom::Node_Binding::PROCESSING_INSTRUCTION_NODE;
315 static const auto COMMENT_NODE = mozilla::dom::Node_Binding::COMMENT_NODE;
316 static const auto DOCUMENT_NODE = mozilla::dom::Node_Binding::DOCUMENT_NODE;
317 static const auto DOCUMENT_TYPE_NODE =
318 mozilla::dom::Node_Binding::DOCUMENT_TYPE_NODE;
319 static const auto DOCUMENT_FRAGMENT_NODE =
320 mozilla::dom::Node_Binding::DOCUMENT_FRAGMENT_NODE;
321 static const auto NOTATION_NODE = mozilla::dom::Node_Binding::NOTATION_NODE;
322 static const auto MAX_NODE_TYPE = NOTATION_NODE;
324 void* operator new(size_t aSize, nsNodeInfoManager* aManager);
325 void* operator new(size_t aSize) = delete;
326 void operator delete(void* aPtr);
328 template <class T>
329 using Sequence = mozilla::dom::Sequence<T>;
331 NS_DECLARE_STATIC_IID_ACCESSOR(NS_INODE_IID)
333 // The |aNodeSize| outparam on this function is where the actual node size
334 // value is put. It gets added to the appropriate value within |aSizes| by
335 // AddSizeOfNodeTree().
337 // Among the sub-classes that inherit (directly or indirectly) from nsINode,
338 // measurement of the following members may be added later if DMD finds it is
339 // worthwhile:
340 // - nsGenericHTMLElement: mForm, mFieldSet
341 // - nsGenericHTMLFrameElement: mFrameLoader (bug 672539)
342 // - HTMLBodyElement: mContentStyleRule
343 // - HTMLDataListElement: mOptions
344 // - HTMLFieldSetElement: mElements, mDependentElements, mFirstLegend
345 // - HTMLFormElement: many!
346 // - HTMLFrameSetElement: mRowSpecs, mColSpecs
347 // - HTMLInputElement: mInputData, mFiles, mFileList, mStaticDocfileList
348 // - nsHTMLMapElement: mAreas
349 // - HTMLMediaElement: many!
350 // - nsHTMLOutputElement: mDefaultValue, mTokenList
351 // - nsHTMLRowElement: mCells
352 // - nsHTMLSelectElement: mOptions, mRestoreState
353 // - nsHTMLTableElement: mTBodies, mRows, mTableInheritedAttributes
354 // - nsHTMLTableSectionElement: mRows
355 // - nsHTMLTextAreaElement: mControllers, mState
357 // The following members don't need to be measured:
358 // - nsIContent: mPrimaryFrame, because it's non-owning and measured elsewhere
360 virtual void AddSizeOfExcludingThis(nsWindowSizes& aSizes,
361 size_t* aNodeSize) const;
363 // SizeOfIncludingThis doesn't need to be overridden by sub-classes because
364 // sub-classes of nsINode are guaranteed to be laid out in memory in such a
365 // way that |this| points to the start of the allocated object, even in
366 // methods of nsINode's sub-classes, so aSizes.mState.mMallocSizeOf(this) is
367 // always safe to call no matter which object it was invoked on.
368 void AddSizeOfIncludingThis(nsWindowSizes& aSizes, size_t* aNodeSize) const;
370 friend class nsNodeWeakReference;
371 friend class nsNodeSupportsWeakRefTearoff;
372 friend class AttrArray;
374 #ifdef MOZILLA_INTERNAL_API
375 explicit nsINode(already_AddRefed<mozilla::dom::NodeInfo>&& aNodeInfo);
376 #endif
378 virtual ~nsINode();
381 * Bit-flags to pass (or'ed together) to IsNodeOfType()
383 enum {
384 /** form control elements */
385 eHTML_FORM_CONTROL = 1 << 6,
386 /** SVG use targets */
387 eUSE_TARGET = 1 << 9,
388 /** SVG shapes such as lines and polygons, but not images */
389 eSHAPE = 1 << 12
393 * API for doing a quick check if a content is of a given
394 * type, such as Text, Document, Comment ... Use this when you can instead of
395 * checking the tag.
397 * @param aFlags what types you want to test for (see above)
398 * @return whether the content matches ALL flags passed in
400 virtual bool IsNodeOfType(uint32_t aFlags) const = 0;
402 bool IsContainerNode() const {
403 return IsElement() || IsDocument() || IsDocumentFragment();
407 * Returns true if the node is a HTMLTemplate element.
409 bool IsTemplateElement() const { return IsHTMLElement(nsGkAtoms::_template); }
411 bool IsSlotable() const { return IsElement() || IsText(); }
414 * Returns true if this is a document node.
416 bool IsDocument() const {
417 // One less pointer-chase than checking NodeType().
418 return !GetParentNode() && IsInUncomposedDoc();
422 * Return this node as a document. Asserts IsDocument().
424 * This is defined inline in Document.h.
426 inline Document* AsDocument();
427 inline const Document* AsDocument() const;
430 * Returns true if this is a document fragment node.
432 bool IsDocumentFragment() const {
433 return NodeType() == DOCUMENT_FRAGMENT_NODE;
437 * https://dom.spec.whatwg.org/#concept-tree-inclusive-descendant
439 * @param aNode must not be nullptr.
441 bool IsInclusiveDescendantOf(const nsINode* aNode) const;
444 * https://dom.spec.whatwg.org/#concept-shadow-including-inclusive-descendant
446 * @param aNode must not be nullptr.
448 bool IsShadowIncludingInclusiveDescendantOf(const nsINode* aNode) const;
451 * Return this node as a document fragment. Asserts IsDocumentFragment().
453 * This is defined inline in DocumentFragment.h.
455 inline mozilla::dom::DocumentFragment* AsDocumentFragment();
456 inline const mozilla::dom::DocumentFragment* AsDocumentFragment() const;
458 JSObject* WrapObject(JSContext*, JS::Handle<JSObject*> aGivenProto) final;
461 * Hook for constructing JS::ubi::Concrete specializations for memory
462 * reporting. Specializations are defined in NodeUbiReporting.h.
464 virtual void ConstructUbiNode(void* storage) = 0;
467 * returns true if we are in priviliged code or
468 * layout.css.getBoxQuads.enabled == true.
470 static bool HasBoxQuadsSupport(JSContext* aCx, JSObject* /* unused */);
472 protected:
474 * WrapNode is called from WrapObject to actually wrap this node, WrapObject
475 * does some additional checks and fix-up that's common to all nodes. WrapNode
476 * should just call the DOM binding's Wrap function.
478 * aGivenProto is the prototype to use (or null if the default one should be
479 * used) and should just be passed directly on to the DOM binding's Wrap
480 * function.
482 virtual JSObject* WrapNode(JSContext* aCx,
483 JS::Handle<JSObject*> aGivenProto) = 0;
485 public:
486 mozilla::dom::ParentObject GetParentObject()
487 const; // Implemented in Document.h
490 * Returns the first child of a node or the first child of
491 * a template element's content if the provided node is a
492 * template element.
494 nsIContent* GetFirstChildOfTemplateOrNode();
497 * Return the scope chain parent for this node, for use in things
498 * like event handler compilation. Returning null means to use the
499 * global object as the scope chain parent.
501 virtual nsINode* GetScopeChainParent() const;
503 MOZ_CAN_RUN_SCRIPT mozilla::dom::Element* GetParentFlexElement();
505 bool IsNode() const final { return true; }
507 NS_IMPL_FROMEVENTTARGET_HELPER(nsINode, IsNode())
510 * Return whether the node is an Element node. Faster than using `NodeType()`.
512 bool IsElement() const { return GetBoolFlag(NodeIsElement); }
514 virtual bool IsTextControlElement() const { return false; }
516 // Returns non-null if this element subclasses `LinkStyle`.
517 virtual const mozilla::dom::LinkStyle* AsLinkStyle() const { return nullptr; }
518 mozilla::dom::LinkStyle* AsLinkStyle() {
519 return const_cast<mozilla::dom::LinkStyle*>(
520 static_cast<const nsINode*>(this)->AsLinkStyle());
524 * Return this node as an Element. Should only be used for nodes
525 * for which IsElement() is true. This is defined inline in Element.h.
527 inline mozilla::dom::Element* AsElement();
528 inline const mozilla::dom::Element* AsElement() const;
531 * Return whether the node is an nsStyledElement instance or not.
533 virtual bool IsStyledElement() const { return false; }
536 * Return this node as nsIContent. Should only be used for nodes for which
537 * IsContent() is true.
539 * The assertion in nsIContent's constructor makes this safe.
541 nsIContent* AsContent() {
542 MOZ_ASSERT(IsContent());
543 return reinterpret_cast<nsIContent*>(this);
545 const nsIContent* AsContent() const {
546 MOZ_ASSERT(IsContent());
547 return reinterpret_cast<const nsIContent*>(this);
551 * Return whether the node is a Text node (which might be an actual
552 * textnode, or might be a CDATA section).
554 bool IsText() const {
555 uint32_t nodeType = NodeType();
556 return nodeType == TEXT_NODE || nodeType == CDATA_SECTION_NODE;
560 * Return this node as Text if it is one, otherwise null. This is defined
561 * inline in Text.h.
563 inline mozilla::dom::Text* GetAsText();
564 inline const mozilla::dom::Text* GetAsText() const;
567 * Return this node as Text. Asserts IsText(). This is defined inline in
568 * Text.h.
570 inline mozilla::dom::Text* AsText();
571 inline const mozilla::dom::Text* AsText() const;
574 * Return whether the node is a ProcessingInstruction node.
576 bool IsProcessingInstruction() const {
577 return NodeType() == PROCESSING_INSTRUCTION_NODE;
581 * Return whether the node is a CharacterData node (text, cdata,
582 * comment, processing instruction)
584 bool IsCharacterData() const {
585 uint32_t nodeType = NodeType();
586 return nodeType == TEXT_NODE || nodeType == CDATA_SECTION_NODE ||
587 nodeType == PROCESSING_INSTRUCTION_NODE || nodeType == COMMENT_NODE;
591 * Return whether the node is a Comment node.
593 bool IsComment() const { return NodeType() == COMMENT_NODE; }
596 * Return whether the node is an Attr node.
598 bool IsAttr() const { return NodeType() == ATTRIBUTE_NODE; }
601 * Return if this node has any children.
603 bool HasChildren() const { return !!mFirstChild; }
606 * Get the number of children
607 * @return the number of children
609 uint32_t GetChildCount() const { return mChildCount; }
612 * NOTE: this function is going to be removed soon (hopefully!) Don't use it
613 * in new code.
615 * Get a child by index
616 * @param aIndex the index of the child to get
617 * @return the child, or null if index out of bounds
619 nsIContent* GetChildAt_Deprecated(uint32_t aIndex) const;
622 * Get the index of a child within this content.
624 * @param aPossibleChild the child to get the index of.
625 * @return the index of the child, or Nothing if not a child. Be aware that
626 * anonymous children (e.g. a <div> child of an <input> element) will
627 * result in Nothing.
629 * If the return value is Some, then calling GetChildAt_Deprecated() with
630 * that value will return aPossibleChild.
632 mozilla::Maybe<uint32_t> ComputeIndexOf(const nsINode* aPossibleChild) const;
635 * Get the index of this within parent node (ComputeIndexInParentNode) or
636 * parent content (nsIContent) node (ComputeIndexInParentContent).
638 * @return the index of this node in the parent, or Nothing there is no
639 * parent (content) node or the parent does not have this node anymore
640 * (e.g., being removed from the parent). Be aware that anonymous
641 * children (e.g. a <div> child of an <input> element) will result in
642 * Nothing.
644 * If the return value is Some, then calling GetChildAt_Deprecated() with
645 * that value will return this.
647 mozilla::Maybe<uint32_t> ComputeIndexInParentNode() const;
648 mozilla::Maybe<uint32_t> ComputeIndexInParentContent() const;
651 * Get the index of a child within this content.
653 * @param aPossibleChild the child to get the index of.
654 * @return the index of the child, or -1 if not a child. Be aware that
655 * anonymous children (e.g. a <div> child of an <input> element) will
656 * result in -1.
658 * If the return value is not -1, then calling GetChildAt_Deprecated() with
659 * that value will return aPossibleChild.
661 int32_t ComputeIndexOf_Deprecated(const nsINode* aPossibleChild) const;
664 * Returns the "node document" of this node.
666 * https://dom.spec.whatwg.org/#concept-node-document
668 * Note that in the case that this node is a document node this method
669 * will return |this|. That is different to the Node.ownerDocument DOM
670 * attribute (implemented by nsINode::GetOwnerDocument) which is specified to
671 * be null in that case:
673 * https://dom.spec.whatwg.org/#dom-node-ownerdocument
675 * For all other cases OwnerDoc and GetOwnerDocument behave identically.
677 Document* OwnerDoc() const MOZ_NONNULL_RETURN {
678 return mNodeInfo->GetDocument();
682 * Return the "owner document" of this node as an nsINode*. Implemented
683 * in Document.h.
685 inline nsINode* OwnerDocAsNode() const MOZ_NONNULL_RETURN;
688 * Returns true if the content has an ancestor that is a document.
690 * @return whether this content is in a document tree
692 bool IsInUncomposedDoc() const { return GetBoolFlag(IsInDocument); }
695 * Get the document that this content is currently in, if any. This will be
696 * null if the content has no ancestor that is a document.
698 * @return the current document
701 Document* GetUncomposedDoc() const {
702 return IsInUncomposedDoc() ? OwnerDoc() : nullptr;
706 * Returns true if we're connected, and thus GetComposedDoc() would return a
707 * non-null value.
709 bool IsInComposedDoc() const { return GetBoolFlag(IsConnected); }
712 * This method returns the owner document if the node is connected to it
713 * (as defined in the DOM spec), otherwise it returns null.
714 * In other words, returns non-null even in the case the node is in
715 * Shadow DOM, if there is a possibly shadow boundary crossing path from
716 * the node to its owner document.
718 Document* GetComposedDoc() const {
719 return IsInComposedDoc() ? OwnerDoc() : nullptr;
723 * Returns OwnerDoc() if the node is in uncomposed document and ShadowRoot if
724 * the node is in Shadow DOM and is in composed document.
726 mozilla::dom::DocumentOrShadowRoot* GetUncomposedDocOrConnectedShadowRoot()
727 const;
730 * To be called when reference count of the node drops to zero.
732 void LastRelease();
735 * The values returned by this function are the ones defined for
736 * Node.nodeType
738 uint16_t NodeType() const { return mNodeInfo->NodeType(); }
739 const nsString& NodeName() const { return mNodeInfo->NodeName(); }
740 const nsString& LocalName() const { return mNodeInfo->LocalName(); }
743 * Get the NodeInfo for this element
744 * @return the nodes node info
746 inline mozilla::dom::NodeInfo* NodeInfo() const { return mNodeInfo; }
749 * Called when we have been adopted, and the information of the
750 * node has been changed.
752 * The new document can be reached via OwnerDoc().
754 * If you override this method,
755 * please call up to the parent NodeInfoChanged.
757 * If you change this, change also the similar method in Link.
759 virtual void NodeInfoChanged(Document* aOldDoc) {
760 #ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
761 AssertInvariantsOnNodeInfoChange();
762 #endif
765 inline bool IsInNamespace(int32_t aNamespace) const {
766 return mNodeInfo->NamespaceID() == aNamespace;
770 * Returns the DocGroup of the "node document" of this node.
772 DocGroup* GetDocGroup() const;
775 * Print a debugger friendly descriptor of this element. This will describe
776 * the position of this element in the document.
778 friend std::ostream& operator<<(std::ostream& aStream, const nsINode& aNode);
780 protected:
781 // These 2 methods are useful for the recursive templates IsHTMLElement,
782 // IsSVGElement, etc.
783 inline bool IsNodeInternal() const { return false; }
785 template <typename First, typename... Args>
786 inline bool IsNodeInternal(First aFirst, Args... aArgs) const {
787 return mNodeInfo->Equals(aFirst) || IsNodeInternal(aArgs...);
790 public:
791 inline bool IsHTMLElement() const {
792 return IsElement() && IsInNamespace(kNameSpaceID_XHTML);
795 inline bool IsHTMLElement(const nsAtom* aTag) const {
796 return IsElement() && mNodeInfo->Equals(aTag, kNameSpaceID_XHTML);
799 template <typename First, typename... Args>
800 inline bool IsAnyOfHTMLElements(First aFirst, Args... aArgs) const {
801 return IsHTMLElement() && IsNodeInternal(aFirst, aArgs...);
804 inline bool IsSVGElement() const {
805 return IsElement() && IsInNamespace(kNameSpaceID_SVG);
808 inline bool IsSVGElement(const nsAtom* aTag) const {
809 return IsElement() && mNodeInfo->Equals(aTag, kNameSpaceID_SVG);
812 template <typename First, typename... Args>
813 inline bool IsAnyOfSVGElements(First aFirst, Args... aArgs) const {
814 return IsSVGElement() && IsNodeInternal(aFirst, aArgs...);
817 inline bool IsXULElement() const {
818 return IsElement() && IsInNamespace(kNameSpaceID_XUL);
821 inline bool IsXULElement(const nsAtom* aTag) const {
822 return IsElement() && mNodeInfo->Equals(aTag, kNameSpaceID_XUL);
825 template <typename First, typename... Args>
826 inline bool IsAnyOfXULElements(First aFirst, Args... aArgs) const {
827 return IsXULElement() && IsNodeInternal(aFirst, aArgs...);
830 inline bool IsMathMLElement() const {
831 return IsElement() && IsInNamespace(kNameSpaceID_MathML);
834 inline bool IsMathMLElement(const nsAtom* aTag) const {
835 return IsElement() && mNodeInfo->Equals(aTag, kNameSpaceID_MathML);
838 template <typename First, typename... Args>
839 inline bool IsAnyOfMathMLElements(First aFirst, Args... aArgs) const {
840 return IsMathMLElement() && IsNodeInternal(aFirst, aArgs...);
843 bool IsShadowRoot() const {
844 const bool isShadowRoot = IsInShadowTree() && !GetParentNode();
845 MOZ_ASSERT_IF(isShadowRoot, IsDocumentFragment());
846 return isShadowRoot;
849 bool IsHTMLHeadingElement() const {
850 return IsAnyOfHTMLElements(nsGkAtoms::h1, nsGkAtoms::h2, nsGkAtoms::h3,
851 nsGkAtoms::h4, nsGkAtoms::h5, nsGkAtoms::h6);
855 * Insert a content node before another or at the end.
856 * This method handles calling BindToTree on the child appropriately.
858 * @param aKid the content to insert
859 * @param aBeforeThis an existing node. Use nullptr if you want to
860 * add aKid at the end.
861 * @param aNotify whether to notify the document (current document for
862 * nsIContent, and |this| for Document) that the insert has occurred
863 * @param aRv The error, if any.
864 * Throw NS_ERROR_DOM_HIERARCHY_REQUEST_ERR if one attempts to have
865 * more than one element node as a child of a document. Doing this
866 * will also assert -- you shouldn't be doing it! Check with
867 * Document::GetRootElement() first if you're not sure. Apart from
868 * this one constraint, this doesn't do any checking on whether aKid is
869 * a valid child of |this|.
870 * Throw NS_ERROR_OUT_OF_MEMORY in some cases (from BindToTree).
872 virtual void InsertChildBefore(nsIContent* aKid, nsIContent* aBeforeThis,
873 bool aNotify, mozilla::ErrorResult& aRv);
876 * Append a content node to the end of the child list. This method handles
877 * calling BindToTree on the child appropriately.
879 * @param aKid the content to append
880 * @param aNotify whether to notify the document (current document for
881 * nsIContent, and |this| for Document) that the append has occurred
882 * @param aRv The error, if any.
883 * Throw NS_ERROR_DOM_HIERARCHY_REQUEST_ERR if one attempts to have
884 * more than one element node as a child of a document. Doing this
885 * will also assert -- you shouldn't be doing it! Check with
886 * Document::GetRootElement() first if you're not sure. Apart from
887 * this one constraint, this doesn't do any checking on whether aKid is
888 * a valid child of |this|.
889 * Throw NS_ERROR_OUT_OF_MEMORY in some cases (from BindToTree).
891 void AppendChildTo(nsIContent* aKid, bool aNotify,
892 mozilla::ErrorResult& aRv) {
893 InsertChildBefore(aKid, nullptr, aNotify, aRv);
897 * Remove a child from this node. This method handles calling UnbindFromTree
898 * on the child appropriately.
900 * @param aKid the content to remove
901 * @param aNotify whether to notify the document (current document for
902 * nsIContent, and |this| for Document) that the remove has occurred
904 virtual void RemoveChildNode(nsIContent* aKid, bool aNotify);
907 * Get a property associated with this node.
909 * @param aPropertyName name of property to get.
910 * @param aStatus out parameter for storing resulting status.
911 * Set to NS_PROPTABLE_PROP_NOT_THERE if the property
912 * is not set.
913 * @return the property. Null if the property is not set
914 * (though a null return value does not imply the
915 * property was not set, i.e. it can be set to null).
917 void* GetProperty(const nsAtom* aPropertyName,
918 nsresult* aStatus = nullptr) const;
921 * Set a property to be associated with this node. This will overwrite an
922 * existing value if one exists. The existing value is destroyed using the
923 * destructor function given when that value was set.
925 * @param aPropertyName name of property to set.
926 * @param aValue new value of property.
927 * @param aDtor destructor function to be used when this property
928 * is destroyed.
929 * @param aTransfer if true the property will not be deleted when the
930 * ownerDocument of the node changes, if false it
931 * will be deleted.
933 * @return NS_PROPTABLE_PROP_OVERWRITTEN (success value) if the property
934 * was already set
935 * @throws NS_ERROR_OUT_OF_MEMORY if that occurs
937 nsresult SetProperty(nsAtom* aPropertyName, void* aValue,
938 NSPropertyDtorFunc aDtor = nullptr,
939 bool aTransfer = false);
942 * A generic destructor for property values allocated with new.
944 template <class T>
945 static void DeleteProperty(void*, nsAtom*, void* aPropertyValue, void*) {
946 delete static_cast<T*>(aPropertyValue);
950 * Removes a property associated with this node. The value is destroyed using
951 * the destruction function given when that value was set.
953 * @param aPropertyName name of property to destroy.
955 void RemoveProperty(const nsAtom* aPropertyName);
958 * Take a property associated with this node. The value will not be destroyed
959 * but rather returned. It is the caller's responsibility to destroy the value
960 * after that point.
962 * @param aPropertyName name of property to unset.
963 * @param aStatus out parameter for storing resulting status.
964 * Set to NS_PROPTABLE_PROP_NOT_THERE if the property
965 * is not set.
966 * @return the property. Null if the property is not set
967 * (though a null return value does not imply the
968 * property was not set, i.e. it can be set to null).
970 void* TakeProperty(const nsAtom* aPropertyName, nsresult* aStatus = nullptr);
972 bool HasProperties() const { return HasFlag(NODE_HAS_PROPERTIES); }
975 * Return the principal of this node. This is guaranteed to never be a null
976 * pointer.
978 nsIPrincipal* NodePrincipal() const {
979 return mNodeInfo->NodeInfoManager()->DocumentPrincipal();
983 * Return the CSP of this node's document, if any.
985 nsIContentSecurityPolicy* GetCsp() const;
988 * Get the parent nsIContent for this node.
989 * @return the parent, or null if no parent or the parent is not an nsIContent
991 nsIContent* GetParent() const {
992 return MOZ_LIKELY(GetBoolFlag(ParentIsContent)) ? mParent->AsContent()
993 : nullptr;
997 * Get the parent nsINode for this node. This can be either an nsIContent, a
998 * Document or an Attr.
999 * @return the parent node
1001 nsINode* GetParentNode() const { return mParent; }
1003 nsINode* GetParentOrShadowHostNode() const;
1005 enum FlattenedParentType { eNotForStyle, eForStyle };
1008 * Returns the node that is the parent of this node in the flattened
1009 * tree. This differs from the normal parent if the node is filtered
1010 * into an insertion point, or if the node is a direct child of a
1011 * shadow root.
1013 * @return the flattened tree parent
1015 inline nsINode* GetFlattenedTreeParentNode() const;
1017 nsINode* GetFlattenedTreeParentNodeNonInline() const;
1020 * Like GetFlattenedTreeParentNode, but returns the document for any native
1021 * anonymous content that was generated for ancestor frames of the document
1022 * element's primary frame, such as scrollbar elements created by the root
1023 * scroll frame.
1025 inline nsINode* GetFlattenedTreeParentNodeForStyle() const;
1027 inline mozilla::dom::Element* GetFlattenedTreeParentElement() const;
1028 inline mozilla::dom::Element* GetFlattenedTreeParentElementForStyle() const;
1031 * Get the parent nsINode for this node if it is an Element.
1033 * Defined inline in Element.h
1035 * @return the parent node
1037 inline mozilla::dom::Element* GetParentElement() const;
1040 * Get the parent Element of this node, traversing over a ShadowRoot
1041 * to its host if necessary.
1043 mozilla::dom::Element* GetParentElementCrossingShadowRoot() const;
1046 * Get closest element node for the node. Meaning that if the node is an
1047 * element node, returns itself. Otherwise, returns parent element or null.
1049 inline mozilla::dom::Element* GetAsElementOrParentElement() const;
1052 * Get the root of the subtree this node belongs to. This never returns
1053 * null. It may return 'this' (e.g. for document nodes, and nodes that
1054 * are the roots of disconnected subtrees).
1056 nsINode* SubtreeRoot() const;
1059 * Get context object's shadow-including root if options's composed is true,
1060 * and context object's root otherwise.
1062 nsINode* GetRootNode(const mozilla::dom::GetRootNodeOptions& aOptions);
1064 virtual mozilla::EventListenerManager* GetExistingListenerManager()
1065 const override;
1066 virtual mozilla::EventListenerManager* GetOrCreateListenerManager() override;
1068 mozilla::Maybe<mozilla::dom::EventCallbackDebuggerNotificationType>
1069 GetDebuggerNotificationType() const override;
1071 bool ComputeDefaultWantsUntrusted(mozilla::ErrorResult& aRv) final;
1073 virtual bool IsApzAware() const override;
1075 virtual nsPIDOMWindowOuter* GetOwnerGlobalForBindingsInternal() override;
1076 virtual nsIGlobalObject* GetOwnerGlobal() const override;
1078 using mozilla::dom::EventTarget::DispatchEvent;
1079 // TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230)
1080 MOZ_CAN_RUN_SCRIPT_BOUNDARY bool DispatchEvent(
1081 mozilla::dom::Event& aEvent, mozilla::dom::CallerType aCallerType,
1082 mozilla::ErrorResult& aRv) override;
1084 MOZ_CAN_RUN_SCRIPT
1085 nsresult PostHandleEvent(mozilla::EventChainPostVisitor& aVisitor) override;
1088 * Adds a mutation observer to be notified when this node, or any of its
1089 * descendants, are modified. The node will hold a weak reference to the
1090 * observer, which means that it is the responsibility of the observer to
1091 * remove itself in case it dies before the node. If an observer is added
1092 * while observers are being notified, it may also be notified. In general,
1093 * adding observers while inside a notification is not a good idea. An
1094 * observer that is already observing the node must not be added without
1095 * being removed first.
1097 * For mutation observers that implement nsIAnimationObserver, use
1098 * AddAnimationObserver instead.
1100 void AddMutationObserver(nsIMutationObserver* aMutationObserver) {
1101 nsSlots* s = Slots();
1102 NS_ASSERTION(s->mMutationObservers.IndexOf(aMutationObserver) ==
1103 nsTArray<int>::NoIndex,
1104 "Observer already in the list");
1105 s->mMutationObservers.AppendElement(aMutationObserver);
1109 * Same as above, but only adds the observer if its not observing
1110 * the node already.
1112 * For mutation observers that implement nsIAnimationObserver, use
1113 * AddAnimationObserverUnlessExists instead.
1115 void AddMutationObserverUnlessExists(nsIMutationObserver* aMutationObserver) {
1116 nsSlots* s = Slots();
1117 s->mMutationObservers.AppendElementUnlessExists(aMutationObserver);
1121 * Same as AddMutationObserver, but for nsIAnimationObservers. This
1122 * additionally records on the document that animation observers have
1123 * been registered, which is used to determine whether notifications
1124 * must be fired when animations are added, removed or changed.
1126 void AddAnimationObserver(nsIAnimationObserver* aAnimationObserver);
1129 * Same as above, but only adds the observer if its not observing
1130 * the node already.
1132 void AddAnimationObserverUnlessExists(
1133 nsIAnimationObserver* aAnimationObserver);
1136 * Removes a mutation observer.
1138 void RemoveMutationObserver(nsIMutationObserver* aMutationObserver) {
1139 nsSlots* s = GetExistingSlots();
1140 if (s) {
1141 s->mMutationObservers.RemoveElement(aMutationObserver);
1145 nsAutoTObserverArray<nsIMutationObserver*, 1>* GetMutationObservers() {
1146 return HasSlots() ? &GetExistingSlots()->mMutationObservers : nullptr;
1150 * Helper methods to access ancestor node(s) of type T.
1151 * The implementations of the methods are in mozilla/dom/AncestorIterator.h.
1153 template <typename T>
1154 inline mozilla::dom::AncestorsOfTypeIterator<T> AncestorsOfType() const;
1156 template <typename T>
1157 inline mozilla::dom::InclusiveAncestorsOfTypeIterator<T>
1158 InclusiveAncestorsOfType() const;
1160 template <typename T>
1161 inline mozilla::dom::FlatTreeAncestorsOfTypeIterator<T>
1162 FlatTreeAncestorsOfType() const;
1164 template <typename T>
1165 inline mozilla::dom::InclusiveFlatTreeAncestorsOfTypeIterator<T>
1166 InclusiveFlatTreeAncestorsOfType() const;
1168 template <typename T>
1169 T* FirstAncestorOfType() const;
1171 private:
1173 * Walks aNode, its attributes and, if aDeep is true, its descendant nodes.
1174 * If aClone is true the nodes will be cloned. If aNewNodeInfoManager is
1175 * not null, it is used to create new nodeinfos for the nodes. Also reparents
1176 * the XPConnect wrappers for the nodes into aReparentScope if non-null.
1178 * @param aNode Node to adopt/clone.
1179 * @param aClone If true the node will be cloned and the cloned node will
1180 * be returned.
1181 * @param aDeep If true the function will be called recursively on
1182 * descendants of the node
1183 * @param aNewNodeInfoManager The nodeinfo manager to use to create new
1184 * nodeinfos for aNode and its attributes and
1185 * descendants. May be null if the nodeinfos
1186 * shouldn't be changed.
1187 * @param aReparentScope Scope into which wrappers should be reparented, or
1188 * null if no reparenting should be done.
1189 * @param aParent If aClone is true the cloned node will be appended to
1190 * aParent's children. May be null. If not null then aNode
1191 * must be an nsIContent.
1192 * @param aError The error, if any.
1194 * @return If aClone is true then the cloned node will be returned,
1195 * unless an error occurred. In error conditions, null
1196 * will be returned.
1198 static already_AddRefed<nsINode> CloneAndAdopt(
1199 nsINode* aNode, bool aClone, bool aDeep,
1200 nsNodeInfoManager* aNewNodeInfoManager,
1201 JS::Handle<JSObject*> aReparentScope, nsINode* aParent,
1202 mozilla::ErrorResult& aError);
1204 public:
1206 * Walks the node, its attributes and descendant nodes. If aNewNodeInfoManager
1207 * is not null, it is used to create new nodeinfos for the nodes. Also
1208 * reparents the XPConnect wrappers for the nodes into aReparentScope if
1209 * non-null.
1211 * @param aNewNodeInfoManager The nodeinfo manager to use to create new
1212 * nodeinfos for the node and its attributes and
1213 * descendants. May be null if the nodeinfos
1214 * shouldn't be changed.
1215 * @param aReparentScope New scope for the wrappers, or null if no reparenting
1216 * should be done.
1217 * @param aError The error, if any.
1219 void Adopt(nsNodeInfoManager* aNewNodeInfoManager,
1220 JS::Handle<JSObject*> aReparentScope,
1221 mozilla::ErrorResult& aError);
1224 * Clones the node, its attributes and, if aDeep is true, its descendant nodes
1225 * If aNewNodeInfoManager is not null, it is used to create new nodeinfos for
1226 * the clones.
1228 * @param aDeep If true the function will be called recursively on
1229 * descendants of the node
1230 * @param aNewNodeInfoManager The nodeinfo manager to use to create new
1231 * nodeinfos for the node and its attributes and
1232 * descendants. May be null if the nodeinfos
1233 * shouldn't be changed.
1234 * @param aError The error, if any.
1236 * @return The newly created node. Null in error conditions.
1238 already_AddRefed<nsINode> Clone(bool aDeep,
1239 nsNodeInfoManager* aNewNodeInfoManager,
1240 mozilla::ErrorResult& aError);
1243 * Clones this node. This needs to be overriden by all node classes. aNodeInfo
1244 * should be identical to this node's nodeInfo, except for the document which
1245 * may be different. When cloning an element, all attributes of the element
1246 * will be cloned. The children of the node will not be cloned.
1248 * @param aNodeInfo the nodeinfo to use for the clone
1249 * @param aResult the clone
1251 virtual nsresult Clone(mozilla::dom::NodeInfo*, nsINode** aResult) const = 0;
1253 // This class can be extended by subclasses that wish to store more
1254 // information in the slots.
1255 class nsSlots {
1256 public:
1257 nsSlots();
1259 // If needed we could remove the vtable pointer this dtor causes by
1260 // putting a DestroySlots function on nsINode
1261 virtual ~nsSlots();
1263 virtual void Traverse(nsCycleCollectionTraversalCallback&);
1264 virtual void Unlink();
1267 * A list of mutation observers
1269 nsAutoTObserverArray<nsIMutationObserver*, 1> mMutationObservers;
1272 * An object implementing NodeList for this content (childNodes)
1273 * @see NodeList
1274 * @see nsGenericHTMLElement::GetChildNodes
1276 RefPtr<nsAttrChildContentList> mChildNodes;
1279 * Weak reference to this node. This is cleared by the destructor of
1280 * nsNodeWeakReference.
1282 nsNodeWeakReference* MOZ_NON_OWNING_REF mWeakReference;
1285 * A set of ranges which are in the selection and which have this node as
1286 * their endpoints' closest common inclusive ancestor
1287 * (https://dom.spec.whatwg.org/#concept-tree-inclusive-ancestor). This is
1288 * a UniquePtr instead of just a LinkedList, because that prevents us from
1289 * pushing DOMSlots up to the next allocation bucket size, at the cost of
1290 * some complexity.
1292 mozilla::UniquePtr<mozilla::LinkedList<nsRange>>
1293 mClosestCommonInclusiveAncestorRanges;
1297 * Functions for managing flags and slots
1299 #ifdef DEBUG
1300 nsSlots* DebugGetSlots() { return Slots(); }
1301 #endif
1303 void SetFlags(FlagsType aFlagsToSet) {
1304 NS_ASSERTION(
1305 !(aFlagsToSet &
1306 (NODE_IS_NATIVE_ANONYMOUS_ROOT | NODE_IS_IN_NATIVE_ANONYMOUS_SUBTREE |
1307 NODE_DESCENDANTS_NEED_FRAMES | NODE_NEEDS_FRAME |
1308 NODE_HAS_BEEN_IN_UA_WIDGET)) ||
1309 IsContent(),
1310 "Flag only permitted on nsIContent nodes");
1311 nsWrapperCache::SetFlags(aFlagsToSet);
1314 void UnsetFlags(FlagsType aFlagsToUnset) {
1315 NS_ASSERTION(!(aFlagsToUnset & (NODE_HAS_BEEN_IN_UA_WIDGET |
1316 NODE_IS_NATIVE_ANONYMOUS_ROOT)),
1317 "Trying to unset write-only flags");
1318 nsWrapperCache::UnsetFlags(aFlagsToUnset);
1321 void SetEditableFlag(bool aEditable) {
1322 if (aEditable) {
1323 SetFlags(NODE_IS_EDITABLE);
1324 } else {
1325 UnsetFlags(NODE_IS_EDITABLE);
1329 inline bool IsEditable() const;
1332 * Check if this node is in design mode or not. When this returns true and:
1333 * - if this is a Document node, it's the design mode root.
1334 * - if this is a content node, it's connected, it's not in a shadow tree
1335 * (except shadow tree for UI widget and native anonymous subtree) and its
1336 * uncomposed document is in design mode.
1337 * Note that returning true does NOT mean the node or its children is
1338 * editable. E.g., when this node is in a shadow tree of a UA widget and its
1339 * host is in design mode.
1341 inline bool IsInDesignMode() const;
1344 * Returns true if |this| or any of its ancestors is native anonymous.
1346 bool IsInNativeAnonymousSubtree() const {
1347 return HasFlag(NODE_IS_IN_NATIVE_ANONYMOUS_SUBTREE);
1351 * If |this| or any ancestor is native anonymous, return the root of the
1352 * native anonymous subtree. Note that in case of nested native anonymous
1353 * content, this returns the innermost root, not the outermost.
1355 nsIContent* GetClosestNativeAnonymousSubtreeRoot() const {
1356 if (!IsInNativeAnonymousSubtree()) {
1357 return nullptr;
1359 MOZ_ASSERT(IsContent(), "How did non-content end up in NAC?");
1360 for (const nsINode* node = this; node; node = node->GetParentNode()) {
1361 if (node->IsRootOfNativeAnonymousSubtree()) {
1362 return const_cast<nsINode*>(node)->AsContent();
1365 // FIXME(emilio): This should not happen, usually, but editor removes nodes
1366 // in native anonymous subtrees, and we don't clean nodes from the current
1367 // event content stack from ContentRemoved, so it can actually happen, see
1368 // bug 1510208.
1369 NS_WARNING("GetClosestNativeAnonymousSubtreeRoot on disconnected NAC!");
1370 return nullptr;
1374 * If |this| or any ancestor is native anonymous, return the parent of the
1375 * native anonymous subtree. Note that in case of nested native anonymous
1376 * content, this returns the parent of the innermost root, not the outermost.
1378 nsIContent* GetClosestNativeAnonymousSubtreeRootParent() const {
1379 const nsIContent* root = GetClosestNativeAnonymousSubtreeRoot();
1380 if (!root) {
1381 return nullptr;
1383 // We could put this in nsIContentInlines.h or such to avoid this
1384 // reinterpret_cast, but it doesn't seem worth it.
1385 return reinterpret_cast<const nsINode*>(root)->GetParent();
1389 * Gets the root of the node tree for this content if it is in a shadow tree.
1391 mozilla::dom::ShadowRoot* GetContainingShadow() const;
1393 * Gets the shadow host if this content is in a shadow tree. That is, the host
1394 * of |GetContainingShadow|, if its not null.
1396 * @return The shadow host, if this is in shadow tree, or null.
1398 nsIContent* GetContainingShadowHost() const;
1400 bool IsInSVGUseShadowTree() const {
1401 return !!GetContainingSVGUseShadowHost();
1404 mozilla::dom::SVGUseElement* GetContainingSVGUseShadowHost() const {
1405 if (!IsInShadowTree()) {
1406 return nullptr;
1408 return DoGetContainingSVGUseShadowHost();
1411 // Whether this node has ever been part of a UA widget shadow tree.
1412 bool HasBeenInUAWidget() const { return HasFlag(NODE_HAS_BEEN_IN_UA_WIDGET); }
1414 // True for native anonymous content and for content in UA widgets.
1415 // Only nsIContent can fulfill this condition.
1416 bool ChromeOnlyAccess() const {
1417 return HasFlag(NODE_IS_IN_NATIVE_ANONYMOUS_SUBTREE |
1418 NODE_HAS_BEEN_IN_UA_WIDGET);
1421 const nsIContent* GetChromeOnlyAccessSubtreeRootParent() const {
1422 if (!ChromeOnlyAccess()) {
1423 return nullptr;
1425 // We can have NAC in UA widgets, but not the other way around.
1426 if (IsInNativeAnonymousSubtree()) {
1427 return GetClosestNativeAnonymousSubtreeRootParent();
1429 return GetContainingShadowHost();
1432 bool IsInShadowTree() const { return HasFlag(NODE_IS_IN_SHADOW_TREE); }
1435 * Get whether this node is C++-generated anonymous content
1436 * @see nsIAnonymousContentCreator
1437 * @return whether this content is anonymous
1439 bool IsRootOfNativeAnonymousSubtree() const {
1440 NS_ASSERTION(
1441 !HasFlag(NODE_IS_NATIVE_ANONYMOUS_ROOT) || IsInNativeAnonymousSubtree(),
1442 "Some flags seem to be missing!");
1443 return HasFlag(NODE_IS_NATIVE_ANONYMOUS_ROOT);
1446 // Whether this node is a UA Widget ShadowRoot.
1447 inline bool IsUAWidget() const;
1448 // Whether this node is currently in a UA Widget Shadow tree.
1449 inline bool IsInUAWidget() const;
1450 // Whether this node is the root of a ChromeOnlyAccess DOM subtree.
1451 inline bool IsRootOfChromeAccessOnlySubtree() const;
1454 * Returns true if |this| node is the closest common inclusive ancestor
1455 * (https://dom.spec.whatwg.org/#concept-tree-inclusive-ancestor) of the
1456 * start/end nodes of a Range in a Selection or a descendant of such a common
1457 * ancestor. This node is definitely not selected when |false| is returned,
1458 * but it may or may not be selected when |true| is returned.
1460 bool IsMaybeSelected() const {
1461 return IsDescendantOfClosestCommonInclusiveAncestorForRangeInSelection() ||
1462 IsClosestCommonInclusiveAncestorForRangeInSelection();
1466 * Return true if any part of (this, aStartOffset) .. (this, aEndOffset)
1467 * overlaps any nsRange in
1468 * GetClosestCommonInclusiveAncestorForRangeInSelection ranges (i.e.
1469 * where this is a descendant of a range's common inclusive ancestor node).
1470 * If a nsRange starts in (this, aEndOffset) or if it ends in
1471 * (this, aStartOffset) then it is non-overlapping and the result is false
1472 * for that nsRange. Collapsed ranges always counts as non-overlapping.
1474 * @param aStartOffset has to be less or equal to aEndOffset.
1476 bool IsSelected(uint32_t aStartOffset, uint32_t aEndOffset) const;
1479 * Get the root element of the text editor associated with this node or the
1480 * root element of the text editor of the ancestor 'TextControlElement' if
1481 * this is in its native anonymous subtree. I.e., this returns anonymous
1482 * `<div>` element of a `TextEditor`. Note that this can be used only for
1483 * getting root content of `<input>` or `<textarea>`. I.e., this method
1484 * doesn't support HTML editors. Note that this may create a `TextEditor`
1485 * instance, and it means that the `TextEditor` may modify its native
1486 * anonymous subtree and may run selection listeners.
1488 MOZ_CAN_RUN_SCRIPT mozilla::dom::Element* GetAnonymousRootElementOfTextEditor(
1489 mozilla::TextEditor** aTextEditor = nullptr);
1492 * Get the nearest selection root, ie. the node that will be selected if the
1493 * user does "Select All" while the focus is in this node. Note that if this
1494 * node is not in an editor, the result comes from the nsFrameSelection that
1495 * is related to aPresShell, so the result might not be the ancestor of this
1496 * node. Be aware that if this node and the computed selection limiter are
1497 * not in same subtree, this returns the root content of the closeset subtree.
1499 MOZ_CAN_RUN_SCRIPT nsIContent* GetSelectionRootContent(
1500 mozilla::PresShell* aPresShell);
1502 nsINodeList* ChildNodes();
1504 nsIContent* GetFirstChild() const { return mFirstChild; }
1506 nsIContent* GetLastChild() const;
1509 * Implementation is in Document.h, because it needs to cast from
1510 * Document* to nsINode*.
1512 Document* GetOwnerDocument() const;
1514 // TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230)
1515 MOZ_CAN_RUN_SCRIPT_BOUNDARY void Normalize();
1518 * Get the base URI for any relative URIs within this piece of
1519 * content. Generally, this is the document's base URI, but certain
1520 * content carries a local base for backward compatibility.
1522 * @return the base URI. May return null.
1524 virtual nsIURI* GetBaseURI(bool aTryUseXHRDocBaseURI = false) const = 0;
1525 nsIURI* GetBaseURIObject() const;
1528 * Return true if the node may be apz aware. There are two cases. One is that
1529 * the node is apz aware (such as HTMLInputElement with number type). The
1530 * other is that the node has apz aware listeners. This is a non-virtual
1531 * function which calls IsNodeApzAwareInternal only when the MayBeApzAware is
1532 * set. We check the details in IsNodeApzAwareInternal which may be overriden
1533 * by child classes
1535 bool IsNodeApzAware() const {
1536 return NodeMayBeApzAware() ? IsNodeApzAwareInternal() : false;
1540 * Override this function and set the flag MayBeApzAware in case the node has
1541 * to let APZC be aware of it. It's used when the node may handle the apz
1542 * aware events and may do preventDefault to stop APZC to do default actions.
1544 * For example, instead of scrolling page by APZ, we handle mouse wheel event
1545 * in HTMLInputElement with number type as increasing / decreasing its value.
1547 virtual bool IsNodeApzAwareInternal() const;
1549 void GetTextContent(nsAString& aTextContent, mozilla::OOMReporter& aError) {
1550 GetTextContentInternal(aTextContent, aError);
1552 void SetTextContent(const nsAString& aTextContent,
1553 nsIPrincipal* aSubjectPrincipal,
1554 mozilla::ErrorResult& aError) {
1555 SetTextContentInternal(aTextContent, aSubjectPrincipal, aError);
1557 void SetTextContent(const nsAString& aTextContent,
1558 mozilla::ErrorResult& aError) {
1559 SetTextContentInternal(aTextContent, nullptr, aError);
1562 mozilla::dom::Element* QuerySelector(const nsACString& aSelector,
1563 mozilla::ErrorResult& aResult);
1564 already_AddRefed<nsINodeList> QuerySelectorAll(const nsACString& aSelector,
1565 mozilla::ErrorResult& aResult);
1567 protected:
1568 // Document and ShadowRoot override this with its own (faster) version.
1569 // This should really only be called for elements and document fragments.
1570 mozilla::dom::Element* GetElementById(const nsAString& aId);
1572 void AppendChildToChildList(nsIContent* aKid);
1573 void InsertChildToChildList(nsIContent* aKid, nsIContent* aNextSibling);
1574 void DisconnectChild(nsIContent* aKid);
1576 public:
1577 void LookupPrefix(const nsAString& aNamespace, nsAString& aResult);
1578 bool IsDefaultNamespace(const nsAString& aNamespaceURI) {
1579 nsAutoString defaultNamespace;
1580 LookupNamespaceURI(u""_ns, defaultNamespace);
1581 return aNamespaceURI.Equals(defaultNamespace);
1583 void LookupNamespaceURI(const nsAString& aNamespacePrefix,
1584 nsAString& aNamespaceURI);
1586 nsIContent* GetNextSibling() const { return mNextSibling; }
1587 nsIContent* GetPreviousSibling() const;
1590 * Return true if the node is being removed from the parent, it means that
1591 * the node still knows the container which it's disconnected from, but the
1592 * node has already been removed from the child node chain of the container.
1593 * I.e., Return true between a call of DisconnectChild of the parent and
1594 * a call of UnbindFromTree of the node.
1596 bool IsBeingRemoved() const {
1597 return mParent && !mNextSibling && !mPreviousOrLastSibling;
1601 * Get the next node in the pre-order tree traversal of the DOM. If
1602 * aRoot is non-null, then it must be an ancestor of |this|
1603 * (possibly equal to |this|) and only nodes that are descendants of
1604 * aRoot, not including aRoot itself, will be returned. Returns
1605 * null if there are no more nodes to traverse.
1607 nsIContent* GetNextNode(const nsINode* aRoot = nullptr) const {
1608 return GetNextNodeImpl(aRoot, false);
1612 * Get the next node in the pre-order tree traversal of the DOM but ignoring
1613 * the children of this node. If aRoot is non-null, then it must be an
1614 * ancestor of |this| (possibly equal to |this|) and only nodes that are
1615 * descendants of aRoot, not including aRoot itself, will be returned.
1616 * Returns null if there are no more nodes to traverse.
1618 nsIContent* GetNextNonChildNode(const nsINode* aRoot = nullptr) const {
1619 return GetNextNodeImpl(aRoot, true);
1623 * Returns true if 'this' is either document or element or
1624 * document fragment and aOther is a descendant in the same
1625 * anonymous tree.
1627 bool Contains(const nsINode* aOther) const;
1629 bool UnoptimizableCCNode() const;
1631 private:
1632 mozilla::dom::SVGUseElement* DoGetContainingSVGUseShadowHost() const;
1634 nsIContent* GetNextNodeImpl(const nsINode* aRoot,
1635 const bool aSkipChildren) const {
1636 #ifdef DEBUG
1637 if (aRoot) {
1638 // TODO: perhaps nsINode::IsInclusiveDescendantOf could be used instead.
1639 const nsINode* cur = this;
1640 for (; cur; cur = cur->GetParentNode())
1641 if (cur == aRoot) break;
1642 NS_ASSERTION(cur, "aRoot not an ancestor of |this|?");
1644 #endif
1645 if (!aSkipChildren) {
1646 nsIContent* kid = GetFirstChild();
1647 if (kid) {
1648 return kid;
1651 if (this == aRoot) {
1652 return nullptr;
1654 const nsINode* cur = this;
1655 while (1) {
1656 nsIContent* next = cur->GetNextSibling();
1657 if (next) {
1658 return next;
1660 nsINode* parent = cur->GetParentNode();
1661 if (parent == aRoot) {
1662 return nullptr;
1664 cur = parent;
1666 MOZ_ASSERT_UNREACHABLE("How did we get here?");
1669 public:
1671 * Get the previous nsIContent in the pre-order tree traversal of the DOM. If
1672 * aRoot is non-null, then it must be an ancestor of |this|
1673 * (possibly equal to |this|) and only nsIContents that are descendants of
1674 * aRoot, including aRoot itself, will be returned. Returns
1675 * null if there are no more nsIContents to traverse.
1677 nsIContent* GetPreviousContent(const nsINode* aRoot = nullptr) const {
1678 #ifdef DEBUG
1679 if (aRoot) {
1680 // TODO: perhaps nsINode::IsInclusiveDescendantOf could be used instead.
1681 const nsINode* cur = this;
1682 for (; cur; cur = cur->GetParentNode())
1683 if (cur == aRoot) break;
1684 NS_ASSERTION(cur, "aRoot not an ancestor of |this|?");
1686 #endif
1688 if (this == aRoot) {
1689 return nullptr;
1691 nsIContent* cur = this->GetParent();
1692 nsIContent* iter = this->GetPreviousSibling();
1693 while (iter) {
1694 cur = iter;
1695 iter = reinterpret_cast<nsINode*>(iter)->GetLastChild();
1697 return cur;
1701 * Boolean flags
1703 private:
1704 enum BooleanFlag {
1705 // Set if we're being used from -moz-element
1706 NodeHasRenderingObservers,
1707 // Set if our parent chain (including this node itself) terminates
1708 // in a document
1709 IsInDocument,
1710 // Set if we're part of the composed doc.
1711 // https://dom.spec.whatwg.org/#connected
1712 IsConnected,
1713 // Set if mParent is an nsIContent
1714 ParentIsContent,
1715 // Set if this node is an Element
1716 NodeIsElement,
1717 // Set if the element has a non-empty id attribute. This can in rare
1718 // cases lie for nsXMLElement, such as when the node has been moved between
1719 // documents with different id mappings.
1720 ElementHasID,
1721 // Set if the element might have a class.
1722 ElementMayHaveClass,
1723 // Set if the element might have inline style.
1724 ElementMayHaveStyle,
1725 // Set if the element has a name attribute set.
1726 ElementHasName,
1727 // Set if the element has a part attribute set.
1728 ElementHasPart,
1729 // Set if the element might have a contenteditable attribute set.
1730 ElementMayHaveContentEditableAttr,
1731 // Set if the node is the closest common inclusive ancestor of the start/end
1732 // nodes of a Range that is in a Selection.
1733 NodeIsClosestCommonInclusiveAncestorForRangeInSelection,
1734 // Set if the node is a descendant of a node with the above bit set.
1735 NodeIsDescendantOfClosestCommonInclusiveAncestorForRangeInSelection,
1736 // Set if CanSkipInCC check has been done for this subtree root.
1737 NodeIsCCMarkedRoot,
1738 // Maybe set if this node is in black subtree.
1739 NodeIsCCBlackTree,
1740 // Maybe set if the node is a root of a subtree
1741 // which needs to be kept in the purple buffer.
1742 NodeIsPurpleRoot,
1743 // Set if the element has some style states locked
1744 ElementHasLockedStyleStates,
1745 // Set if element has pointer locked
1746 ElementHasPointerLock,
1747 // Set if the node may have DOMMutationObserver attached to it.
1748 NodeMayHaveDOMMutationObserver,
1749 // Set if node is Content
1750 NodeIsContent,
1751 // Set if the node has animations or transitions
1752 ElementHasAnimations,
1753 // Set if node has a dir attribute with a valid value (ltr, rtl, or auto).
1754 // Note that we cannot compute this from the dir attribute event state
1755 // flags, because we can't use those to distinguish
1756 // <bdi dir="some-invalid-value"> and <bdi dir="auto">.
1757 NodeHasValidDirAttribute,
1758 // Set if the node has dir=auto and has a property pointing to the text
1759 // node that determines its direction
1760 NodeHasDirAutoSet,
1761 // Set if the node is a text node descendant of a node with dir=auto
1762 // and has a TextNodeDirectionalityMap property listing the elements whose
1763 // direction it determines.
1764 NodeHasTextNodeDirectionalityMap,
1765 // Set if a node in the node's parent chain has dir=auto.
1766 NodeAncestorHasDirAuto,
1767 // Set if the node is handling a click.
1768 NodeHandlingClick,
1769 // Set if the element has a parser insertion mode other than "in body",
1770 // per the HTML5 "Parse state" section.
1771 ElementHasWeirdParserInsertionMode,
1772 // Parser sets this flag if it has notified about the node.
1773 ParserHasNotified,
1774 // Sets if the node is apz aware or we have apz aware listeners.
1775 MayBeApzAware,
1776 // Set if the element might have any kind of anonymous content children,
1777 // which would not be found through the element's children list.
1778 ElementMayHaveAnonymousChildren,
1779 // Set if element has CustomElementData.
1780 ElementHasCustomElementData,
1781 // Set if the element was created from prototype cache and
1782 // its l10n attributes haven't been changed.
1783 ElementCreatedFromPrototypeAndHasUnmodifiedL10n,
1784 // Guard value
1785 BooleanFlagCount
1788 void SetBoolFlag(BooleanFlag name, bool value) {
1789 static_assert(BooleanFlagCount <= 8 * sizeof(mBoolFlags),
1790 "Too many boolean flags");
1791 mBoolFlags = (mBoolFlags & ~(1 << name)) | (value << name);
1794 void SetBoolFlag(BooleanFlag name) {
1795 static_assert(BooleanFlagCount <= 8 * sizeof(mBoolFlags),
1796 "Too many boolean flags");
1797 mBoolFlags |= (1 << name);
1800 void ClearBoolFlag(BooleanFlag name) {
1801 static_assert(BooleanFlagCount <= 8 * sizeof(mBoolFlags),
1802 "Too many boolean flags");
1803 mBoolFlags &= ~(1 << name);
1806 bool GetBoolFlag(BooleanFlag name) const {
1807 static_assert(BooleanFlagCount <= 8 * sizeof(mBoolFlags),
1808 "Too many boolean flags");
1809 return mBoolFlags & (1 << name);
1812 public:
1813 bool HasRenderingObservers() const {
1814 return GetBoolFlag(NodeHasRenderingObservers);
1816 void SetHasRenderingObservers(bool aValue) {
1817 SetBoolFlag(NodeHasRenderingObservers, aValue);
1819 bool IsContent() const { return GetBoolFlag(NodeIsContent); }
1820 bool HasID() const { return GetBoolFlag(ElementHasID); }
1821 bool MayHaveClass() const { return GetBoolFlag(ElementMayHaveClass); }
1822 void SetMayHaveClass() { SetBoolFlag(ElementMayHaveClass); }
1823 bool MayHaveStyle() const { return GetBoolFlag(ElementMayHaveStyle); }
1824 bool HasName() const { return GetBoolFlag(ElementHasName); }
1825 bool HasPartAttribute() const { return GetBoolFlag(ElementHasPart); }
1826 bool MayHaveContentEditableAttr() const {
1827 return GetBoolFlag(ElementMayHaveContentEditableAttr);
1830 * https://dom.spec.whatwg.org/#concept-tree-inclusive-ancestor
1832 bool IsClosestCommonInclusiveAncestorForRangeInSelection() const {
1833 return GetBoolFlag(NodeIsClosestCommonInclusiveAncestorForRangeInSelection);
1836 * https://dom.spec.whatwg.org/#concept-tree-inclusive-ancestor
1838 void SetClosestCommonInclusiveAncestorForRangeInSelection() {
1839 SetBoolFlag(NodeIsClosestCommonInclusiveAncestorForRangeInSelection);
1842 * https://dom.spec.whatwg.org/#concept-tree-inclusive-ancestor
1844 void ClearClosestCommonInclusiveAncestorForRangeInSelection() {
1845 ClearBoolFlag(NodeIsClosestCommonInclusiveAncestorForRangeInSelection);
1848 * https://dom.spec.whatwg.org/#concept-tree-inclusive-ancestor
1850 bool IsDescendantOfClosestCommonInclusiveAncestorForRangeInSelection() const {
1851 return GetBoolFlag(
1852 NodeIsDescendantOfClosestCommonInclusiveAncestorForRangeInSelection);
1855 * https://dom.spec.whatwg.org/#concept-tree-inclusive-ancestor
1857 void SetDescendantOfClosestCommonInclusiveAncestorForRangeInSelection() {
1858 SetBoolFlag(
1859 NodeIsDescendantOfClosestCommonInclusiveAncestorForRangeInSelection);
1862 * https://dom.spec.whatwg.org/#concept-tree-inclusive-ancestor
1864 void ClearDescendantOfClosestCommonInclusiveAncestorForRangeInSelection() {
1865 ClearBoolFlag(
1866 NodeIsDescendantOfClosestCommonInclusiveAncestorForRangeInSelection);
1869 void SetCCMarkedRoot(bool aValue) { SetBoolFlag(NodeIsCCMarkedRoot, aValue); }
1870 bool CCMarkedRoot() const { return GetBoolFlag(NodeIsCCMarkedRoot); }
1871 void SetInCCBlackTree(bool aValue) { SetBoolFlag(NodeIsCCBlackTree, aValue); }
1872 bool InCCBlackTree() const { return GetBoolFlag(NodeIsCCBlackTree); }
1873 void SetIsPurpleRoot(bool aValue) { SetBoolFlag(NodeIsPurpleRoot, aValue); }
1874 bool IsPurpleRoot() const { return GetBoolFlag(NodeIsPurpleRoot); }
1875 bool MayHaveDOMMutationObserver() {
1876 return GetBoolFlag(NodeMayHaveDOMMutationObserver);
1878 void SetMayHaveDOMMutationObserver() {
1879 SetBoolFlag(NodeMayHaveDOMMutationObserver, true);
1881 bool HasListenerManager() { return HasFlag(NODE_HAS_LISTENERMANAGER); }
1882 bool HasPointerLock() const { return GetBoolFlag(ElementHasPointerLock); }
1883 void SetPointerLock() { SetBoolFlag(ElementHasPointerLock); }
1884 void ClearPointerLock() { ClearBoolFlag(ElementHasPointerLock); }
1885 bool MayHaveAnimations() const { return GetBoolFlag(ElementHasAnimations); }
1886 void SetMayHaveAnimations() { SetBoolFlag(ElementHasAnimations); }
1887 void SetHasValidDir() { SetBoolFlag(NodeHasValidDirAttribute); }
1888 void ClearHasValidDir() { ClearBoolFlag(NodeHasValidDirAttribute); }
1889 bool HasValidDir() const { return GetBoolFlag(NodeHasValidDirAttribute); }
1890 void SetHasDirAutoSet() {
1891 MOZ_ASSERT(NodeType() != TEXT_NODE, "SetHasDirAutoSet on text node");
1892 SetBoolFlag(NodeHasDirAutoSet);
1894 void ClearHasDirAutoSet() {
1895 MOZ_ASSERT(NodeType() != TEXT_NODE, "ClearHasDirAutoSet on text node");
1896 ClearBoolFlag(NodeHasDirAutoSet);
1898 bool HasDirAutoSet() const { return GetBoolFlag(NodeHasDirAutoSet); }
1899 void SetHasTextNodeDirectionalityMap() {
1900 MOZ_ASSERT(NodeType() == TEXT_NODE,
1901 "SetHasTextNodeDirectionalityMap on non-text node");
1902 SetBoolFlag(NodeHasTextNodeDirectionalityMap);
1904 void ClearHasTextNodeDirectionalityMap() {
1905 MOZ_ASSERT(NodeType() == TEXT_NODE,
1906 "ClearHasTextNodeDirectionalityMap on non-text node");
1907 ClearBoolFlag(NodeHasTextNodeDirectionalityMap);
1909 bool HasTextNodeDirectionalityMap() const {
1910 MOZ_ASSERT(NodeType() == TEXT_NODE,
1911 "HasTextNodeDirectionalityMap on non-text node");
1912 return GetBoolFlag(NodeHasTextNodeDirectionalityMap);
1915 void SetAncestorHasDirAuto() { SetBoolFlag(NodeAncestorHasDirAuto); }
1916 void ClearAncestorHasDirAuto() { ClearBoolFlag(NodeAncestorHasDirAuto); }
1917 bool AncestorHasDirAuto() const {
1918 return GetBoolFlag(NodeAncestorHasDirAuto);
1921 // Implemented in nsIContentInlines.h.
1922 inline bool NodeOrAncestorHasDirAuto() const;
1924 void SetParserHasNotified() { SetBoolFlag(ParserHasNotified); };
1925 bool HasParserNotified() { return GetBoolFlag(ParserHasNotified); }
1927 void SetMayBeApzAware() { SetBoolFlag(MayBeApzAware); }
1928 bool NodeMayBeApzAware() const { return GetBoolFlag(MayBeApzAware); }
1930 void SetMayHaveAnonymousChildren() {
1931 SetBoolFlag(ElementMayHaveAnonymousChildren);
1933 bool MayHaveAnonymousChildren() const {
1934 return GetBoolFlag(ElementMayHaveAnonymousChildren);
1937 void SetHasCustomElementData() { SetBoolFlag(ElementHasCustomElementData); }
1938 bool HasCustomElementData() const {
1939 return GetBoolFlag(ElementHasCustomElementData);
1942 void SetElementCreatedFromPrototypeAndHasUnmodifiedL10n() {
1943 SetBoolFlag(ElementCreatedFromPrototypeAndHasUnmodifiedL10n);
1945 bool HasElementCreatedFromPrototypeAndHasUnmodifiedL10n() {
1946 return GetBoolFlag(ElementCreatedFromPrototypeAndHasUnmodifiedL10n);
1948 void ClearElementCreatedFromPrototypeAndHasUnmodifiedL10n() {
1949 ClearBoolFlag(ElementCreatedFromPrototypeAndHasUnmodifiedL10n);
1952 protected:
1953 void SetParentIsContent(bool aValue) { SetBoolFlag(ParentIsContent, aValue); }
1954 void SetIsInDocument() { SetBoolFlag(IsInDocument); }
1955 void ClearInDocument() { ClearBoolFlag(IsInDocument); }
1956 void SetIsConnected(bool aConnected) { SetBoolFlag(IsConnected, aConnected); }
1957 void SetNodeIsContent() { SetBoolFlag(NodeIsContent); }
1958 void SetIsElement() { SetBoolFlag(NodeIsElement); }
1959 void SetHasID() { SetBoolFlag(ElementHasID); }
1960 void ClearHasID() { ClearBoolFlag(ElementHasID); }
1961 void SetMayHaveStyle() { SetBoolFlag(ElementMayHaveStyle); }
1962 void SetHasName() { SetBoolFlag(ElementHasName); }
1963 void ClearHasName() { ClearBoolFlag(ElementHasName); }
1964 void SetHasPartAttribute(bool aPart) { SetBoolFlag(ElementHasPart, aPart); }
1965 void SetMayHaveContentEditableAttr() {
1966 SetBoolFlag(ElementMayHaveContentEditableAttr);
1968 void SetHasLockedStyleStates() { SetBoolFlag(ElementHasLockedStyleStates); }
1969 void ClearHasLockedStyleStates() {
1970 ClearBoolFlag(ElementHasLockedStyleStates);
1972 bool HasLockedStyleStates() const {
1973 return GetBoolFlag(ElementHasLockedStyleStates);
1975 void SetHasWeirdParserInsertionMode() {
1976 SetBoolFlag(ElementHasWeirdParserInsertionMode);
1978 bool HasWeirdParserInsertionMode() const {
1979 return GetBoolFlag(ElementHasWeirdParserInsertionMode);
1981 bool HandlingClick() const { return GetBoolFlag(NodeHandlingClick); }
1982 void SetHandlingClick() { SetBoolFlag(NodeHandlingClick); }
1983 void ClearHandlingClick() { ClearBoolFlag(NodeHandlingClick); }
1985 void SetSubtreeRootPointer(nsINode* aSubtreeRoot) {
1986 NS_ASSERTION(aSubtreeRoot, "aSubtreeRoot can never be null!");
1987 NS_ASSERTION(!(IsContent() && IsInUncomposedDoc()) && !IsInShadowTree(),
1988 "Shouldn't be here!");
1989 mSubtreeRoot = aSubtreeRoot;
1992 void ClearSubtreeRootPointer() { mSubtreeRoot = nullptr; }
1994 public:
1995 // Makes nsINode object to keep aObject alive.
1996 void BindObject(nsISupports* aObject);
1997 // After calling UnbindObject nsINode object doesn't keep
1998 // aObject alive anymore.
1999 void UnbindObject(nsISupports* aObject);
2001 void GenerateXPath(nsAString& aResult);
2003 already_AddRefed<mozilla::dom::AccessibleNode> GetAccessibleNode();
2006 * Returns the length of this node, as specified at
2007 * <http://dvcs.w3.org/hg/domcore/raw-file/tip/Overview.html#concept-node-length>
2009 uint32_t Length() const;
2011 void GetNodeName(mozilla::dom::DOMString& aNodeName) {
2012 const nsString& nodeName = NodeName();
2013 aNodeName.SetKnownLiveString(nodeName);
2015 [[nodiscard]] nsresult GetBaseURI(nsAString& aBaseURI) const;
2016 // Return the base URI for the document.
2017 // The returned value may differ if the document is loaded via XHR, and
2018 // when accessed from chrome privileged script and
2019 // from content privileged script for compatibility.
2020 void GetBaseURIFromJS(nsAString& aBaseURI, CallerType aCallerType,
2021 ErrorResult& aRv) const;
2022 bool HasChildNodes() const { return HasChildren(); }
2024 // See nsContentUtils::PositionIsBefore for aThisIndex and aOtherIndex usage.
2025 uint16_t CompareDocumentPosition(
2026 nsINode& aOther, mozilla::Maybe<uint32_t>* aThisIndex = nullptr,
2027 mozilla::Maybe<uint32_t>* aOtherIndex = nullptr) const;
2028 void GetNodeValue(nsAString& aNodeValue) { GetNodeValueInternal(aNodeValue); }
2029 void SetNodeValue(const nsAString& aNodeValue, mozilla::ErrorResult& aError) {
2030 SetNodeValueInternal(aNodeValue, aError);
2032 virtual void GetNodeValueInternal(nsAString& aNodeValue);
2033 virtual void SetNodeValueInternal(const nsAString& aNodeValue,
2034 mozilla::ErrorResult& aError) {
2035 // The DOM spec says that when nodeValue is defined to be null "setting it
2036 // has no effect", so we don't throw an exception.
2038 void EnsurePreInsertionValidity(nsINode& aNewChild, nsINode* aRefChild,
2039 mozilla::ErrorResult& aError);
2040 nsINode* InsertBefore(nsINode& aNode, nsINode* aChild,
2041 mozilla::ErrorResult& aError) {
2042 return ReplaceOrInsertBefore(false, &aNode, aChild, aError);
2046 * See <https://dom.spec.whatwg.org/#dom-node-appendchild>.
2048 nsINode* AppendChild(nsINode& aNode, mozilla::ErrorResult& aError) {
2049 return InsertBefore(aNode, nullptr, aError);
2052 nsINode* ReplaceChild(nsINode& aNode, nsINode& aChild,
2053 mozilla::ErrorResult& aError) {
2054 return ReplaceOrInsertBefore(true, &aNode, &aChild, aError);
2056 // TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230)
2057 MOZ_CAN_RUN_SCRIPT_BOUNDARY nsINode* RemoveChild(
2058 nsINode& aChild, mozilla::ErrorResult& aError);
2059 already_AddRefed<nsINode> CloneNode(bool aDeep, mozilla::ErrorResult& aError);
2060 bool IsSameNode(nsINode* aNode);
2061 bool IsEqualNode(nsINode* aNode);
2062 void GetNamespaceURI(nsAString& aNamespaceURI) const {
2063 mNodeInfo->GetNamespaceURI(aNamespaceURI);
2065 #ifdef MOZILLA_INTERNAL_API
2066 void GetPrefix(nsAString& aPrefix) { mNodeInfo->GetPrefix(aPrefix); }
2067 #endif
2068 void GetLocalName(mozilla::dom::DOMString& aLocalName) const {
2069 const nsString& localName = LocalName();
2070 aLocalName.SetKnownLiveString(localName);
2073 nsDOMAttributeMap* GetAttributes();
2075 // Helper method to remove this node from its parent. This is not exposed
2076 // through WebIDL.
2077 // Only call this if the node has a parent node.
2078 nsresult RemoveFromParent() {
2079 nsINode* parent = GetParentNode();
2080 mozilla::ErrorResult rv;
2081 parent->RemoveChild(*this, rv);
2082 return rv.StealNSResult();
2085 // ChildNode methods
2086 inline mozilla::dom::Element* GetPreviousElementSibling() const;
2087 inline mozilla::dom::Element* GetNextElementSibling() const;
2089 MOZ_CAN_RUN_SCRIPT void Before(const Sequence<OwningNodeOrString>& aNodes,
2090 ErrorResult& aRv);
2091 MOZ_CAN_RUN_SCRIPT void After(const Sequence<OwningNodeOrString>& aNodes,
2092 ErrorResult& aRv);
2093 MOZ_CAN_RUN_SCRIPT void ReplaceWith(
2094 const Sequence<OwningNodeOrString>& aNodes, ErrorResult& aRv);
2096 * Remove this node from its parent, if any.
2098 void Remove();
2100 // ParentNode methods
2101 mozilla::dom::Element* GetFirstElementChild() const;
2102 mozilla::dom::Element* GetLastElementChild() const;
2104 already_AddRefed<nsIHTMLCollection> GetElementsByAttribute(
2105 const nsAString& aAttribute, const nsAString& aValue);
2106 already_AddRefed<nsIHTMLCollection> GetElementsByAttributeNS(
2107 const nsAString& aNamespaceURI, const nsAString& aAttribute,
2108 const nsAString& aValue, ErrorResult& aRv);
2110 MOZ_CAN_RUN_SCRIPT void Prepend(const Sequence<OwningNodeOrString>& aNodes,
2111 ErrorResult& aRv);
2112 MOZ_CAN_RUN_SCRIPT void Append(const Sequence<OwningNodeOrString>& aNodes,
2113 ErrorResult& aRv);
2114 MOZ_CAN_RUN_SCRIPT void ReplaceChildren(
2115 const Sequence<OwningNodeOrString>& aNodes, ErrorResult& aRv);
2116 MOZ_CAN_RUN_SCRIPT void ReplaceChildren(nsINode* aNode, ErrorResult& aRv);
2118 void GetBoxQuads(const BoxQuadOptions& aOptions,
2119 nsTArray<RefPtr<DOMQuad>>& aResult, CallerType aCallerType,
2120 ErrorResult& aRv);
2122 void GetBoxQuadsFromWindowOrigin(const BoxQuadOptions& aOptions,
2123 nsTArray<RefPtr<DOMQuad>>& aResult,
2124 ErrorResult& aRv);
2126 already_AddRefed<DOMQuad> ConvertQuadFromNode(
2127 DOMQuad& aQuad, const TextOrElementOrDocument& aFrom,
2128 const ConvertCoordinateOptions& aOptions, CallerType aCallerType,
2129 ErrorResult& aRv);
2130 already_AddRefed<DOMQuad> ConvertRectFromNode(
2131 DOMRectReadOnly& aRect, const TextOrElementOrDocument& aFrom,
2132 const ConvertCoordinateOptions& aOptions, CallerType aCallerType,
2133 ErrorResult& aRv);
2134 already_AddRefed<DOMPoint> ConvertPointFromNode(
2135 const DOMPointInit& aPoint, const TextOrElementOrDocument& aFrom,
2136 const ConvertCoordinateOptions& aOptions, CallerType aCallerType,
2137 ErrorResult& aRv);
2140 * See nsSlots::mClosestCommonInclusiveAncestorRanges.
2142 const mozilla::LinkedList<nsRange>*
2143 GetExistingClosestCommonInclusiveAncestorRanges() const {
2144 if (!HasSlots()) {
2145 return nullptr;
2147 return GetExistingSlots()->mClosestCommonInclusiveAncestorRanges.get();
2151 * See nsSlots::mClosestCommonInclusiveAncestorRanges.
2153 mozilla::LinkedList<nsRange>*
2154 GetExistingClosestCommonInclusiveAncestorRanges() {
2155 if (!HasSlots()) {
2156 return nullptr;
2158 return GetExistingSlots()->mClosestCommonInclusiveAncestorRanges.get();
2162 * See nsSlots::mClosestCommonInclusiveAncestorRanges.
2164 mozilla::UniquePtr<mozilla::LinkedList<nsRange>>&
2165 GetClosestCommonInclusiveAncestorRangesPtr() {
2166 return Slots()->mClosestCommonInclusiveAncestorRanges;
2169 nsIWeakReference* GetExistingWeakReference() {
2170 return HasSlots() ? GetExistingSlots()->mWeakReference : nullptr;
2173 protected:
2174 // Override this function to create a custom slots class.
2175 // Must not return null.
2176 virtual nsINode::nsSlots* CreateSlots();
2178 bool HasSlots() const { return mSlots != nullptr; }
2180 nsSlots* GetExistingSlots() const { return mSlots; }
2182 nsSlots* Slots() {
2183 if (!HasSlots()) {
2184 mSlots = CreateSlots();
2185 MOZ_ASSERT(mSlots);
2187 return GetExistingSlots();
2191 * Invalidate cached child array inside mChildNodes
2192 * of type nsParentNodeChildContentList.
2194 void InvalidateChildNodes();
2196 virtual void GetTextContentInternal(nsAString& aTextContent,
2197 mozilla::OOMReporter& aError);
2198 virtual void SetTextContentInternal(const nsAString& aTextContent,
2199 nsIPrincipal* aSubjectPrincipal,
2200 mozilla::ErrorResult& aError) {}
2202 void EnsurePreInsertionValidity1(mozilla::ErrorResult& aError);
2203 void EnsurePreInsertionValidity2(bool aReplace, nsINode& aNewChild,
2204 nsINode* aRefChild,
2205 mozilla::ErrorResult& aError);
2206 // TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230)
2207 MOZ_CAN_RUN_SCRIPT_BOUNDARY nsINode* ReplaceOrInsertBefore(
2208 bool aReplace, nsINode* aNewChild, nsINode* aRefChild,
2209 mozilla::ErrorResult& aError);
2212 * Returns the Element that should be used for resolving namespaces
2213 * on this node (ie the ownerElement for attributes, the documentElement for
2214 * documents, the node itself for elements and for other nodes the parentNode
2215 * if it is an element).
2217 virtual mozilla::dom::Element* GetNameSpaceElement() = 0;
2220 * Parse the given selector string into a servo SelectorList.
2222 * Never returns null if aRv is not failing.
2224 * Note that the selector list returned here is owned by the owner doc's
2225 * selector cache.
2227 const RawServoSelectorList* ParseSelectorList(
2228 const nsACString& aSelectorString, mozilla::ErrorResult&);
2230 public:
2231 /* Event stuff that documents and elements share.
2233 Note that we include DOCUMENT_ONLY_EVENT events here so that we
2234 can forward all the document stuff to this implementation.
2236 #define EVENT(name_, id_, type_, struct_) \
2237 mozilla::dom::EventHandlerNonNull* GetOn##name_() { \
2238 return GetEventHandler(nsGkAtoms::on##name_); \
2240 void SetOn##name_(mozilla::dom::EventHandlerNonNull* handler) { \
2241 SetEventHandler(nsGkAtoms::on##name_, handler); \
2243 #define TOUCH_EVENT EVENT
2244 #define DOCUMENT_ONLY_EVENT EVENT
2245 #include "mozilla/EventNameList.h"
2246 #undef DOCUMENT_ONLY_EVENT
2247 #undef TOUCH_EVENT
2248 #undef EVENT
2250 protected:
2251 static bool Traverse(nsINode* tmp, nsCycleCollectionTraversalCallback& cb);
2252 static void Unlink(nsINode* tmp);
2254 RefPtr<mozilla::dom::NodeInfo> mNodeInfo;
2256 // mParent is an owning ref most of the time, except for the case of document
2257 // nodes, so it cannot be represented by nsCOMPtr, so mark is as
2258 // MOZ_OWNING_REF.
2259 nsINode* MOZ_OWNING_REF mParent;
2261 private:
2262 #ifndef BOOL_FLAGS_ON_WRAPPER_CACHE
2263 // Boolean flags.
2264 uint32_t mBoolFlags;
2265 #endif
2267 // NOTE, there are 32 bits left here, at least in 64 bit builds.
2269 uint32_t mChildCount;
2271 protected:
2272 // mNextSibling and mFirstChild are strong references while
2273 // mPreviousOrLastSibling is a weak ref. |mFirstChild->mPreviousOrLastSibling|
2274 // points to the last child node.
2275 nsCOMPtr<nsIContent> mFirstChild;
2276 nsCOMPtr<nsIContent> mNextSibling;
2277 nsIContent* MOZ_NON_OWNING_REF mPreviousOrLastSibling;
2279 union {
2280 // Pointer to our primary frame. Might be null.
2281 nsIFrame* mPrimaryFrame;
2283 // Pointer to the root of our subtree. Might be null.
2284 // This reference is non-owning and safe, since it either points to the
2285 // object itself, or is reset by ClearSubtreeRootPointer.
2286 nsINode* MOZ_NON_OWNING_REF mSubtreeRoot;
2289 // Storage for more members that are usually not needed; allocated lazily.
2290 nsSlots* mSlots;
2293 inline nsINode* mozilla::dom::EventTarget::GetAsNode() {
2294 return IsNode() ? AsNode() : nullptr;
2297 inline const nsINode* mozilla::dom::EventTarget::GetAsNode() const {
2298 return const_cast<mozilla::dom::EventTarget*>(this)->GetAsNode();
2301 inline nsINode* mozilla::dom::EventTarget::AsNode() {
2302 MOZ_DIAGNOSTIC_ASSERT(IsNode());
2303 return static_cast<nsINode*>(this);
2306 inline const nsINode* mozilla::dom::EventTarget::AsNode() const {
2307 MOZ_DIAGNOSTIC_ASSERT(IsNode());
2308 return static_cast<const nsINode*>(this);
2311 // Useful inline function for getting a node given an nsIContent and a Document.
2312 // Returns the first argument cast to nsINode if it is non-null, otherwise
2313 // returns the second (which may be null). We use type variables instead of
2314 // nsIContent* and Document* because the actual types must be
2315 // known for the cast to work.
2316 template <class C, class D>
2317 inline nsINode* NODE_FROM(C& aContent, D& aDocument) {
2318 if (aContent) return static_cast<nsINode*>(aContent);
2319 return static_cast<nsINode*>(aDocument);
2322 NS_DEFINE_STATIC_IID_ACCESSOR(nsINode, NS_INODE_IID)
2324 inline nsISupports* ToSupports(nsINode* aPointer) { return aPointer; }
2326 // Some checks are faster to do on nsIContent or Element than on
2327 // nsINode, so spit out FromNode versions taking those types too.
2328 #define NS_IMPL_FROMNODE_GENERIC(_class, _check, _const) \
2329 template <typename T> \
2330 static auto FromNode(_const T& aNode) \
2331 ->decltype(static_cast<_const _class*>(&aNode)) { \
2332 return aNode._check ? static_cast<_const _class*>(&aNode) : nullptr; \
2334 template <typename T> \
2335 static _const _class* FromNode(_const T* aNode) { \
2336 return FromNode(*aNode); \
2338 template <typename T> \
2339 static _const _class* FromNodeOrNull(_const T* aNode) { \
2340 return aNode ? FromNode(*aNode) : nullptr; \
2342 template <typename T> \
2343 static auto FromEventTarget(_const T& aEventTarget) \
2344 ->decltype(static_cast<_const _class*>(&aEventTarget)) { \
2345 return aEventTarget.IsNode() && aEventTarget.AsNode()->_check \
2346 ? static_cast<_const _class*>(&aEventTarget) \
2347 : nullptr; \
2349 template <typename T> \
2350 static _const _class* FromEventTarget(_const T* aEventTarget) { \
2351 return FromEventTarget(*aEventTarget); \
2353 template <typename T> \
2354 static _const _class* FromEventTargetOrNull(_const T* aEventTarget) { \
2355 return aEventTarget ? FromEventTarget(*aEventTarget) : nullptr; \
2358 #define NS_IMPL_FROMNODE_HELPER(_class, _check) \
2359 NS_IMPL_FROMNODE_GENERIC(_class, _check, ) \
2360 NS_IMPL_FROMNODE_GENERIC(_class, _check, const) \
2362 template <typename T> \
2363 static _class* FromNode(T&& aNode) { \
2364 /* We need the double-cast in case aNode is a smartptr. Those */ \
2365 /* can cast to superclasses of the type they're templated on, */ \
2366 /* but not directly to subclasses. */ \
2367 return aNode->_check ? static_cast<_class*>(static_cast<nsINode*>(aNode)) \
2368 : nullptr; \
2370 template <typename T> \
2371 static _class* FromNodeOrNull(T&& aNode) { \
2372 return aNode ? FromNode(aNode) : nullptr; \
2374 template <typename T> \
2375 static _class* FromEventTarget(T&& aEventTarget) { \
2376 /* We need the double-cast in case aEventTarget is a smartptr. Those */ \
2377 /* can cast to superclasses of the type they're templated on, */ \
2378 /* but not directly to subclasses. */ \
2379 return aEventTarget->IsNode() && aEventTarget->AsNode()->_check \
2380 ? static_cast<_class*>(static_cast<EventTarget*>(aEventTarget)) \
2381 : nullptr; \
2383 template <typename T> \
2384 static _class* FromEventTargetOrNull(T&& aEventTarget) { \
2385 return aEventTarget ? FromEventTarget(aEventTarget) : nullptr; \
2388 #define NS_IMPL_FROMNODE(_class, _nsid) \
2389 NS_IMPL_FROMNODE_HELPER(_class, IsInNamespace(_nsid))
2391 #define NS_IMPL_FROMNODE_WITH_TAG(_class, _nsid, _tag) \
2392 NS_IMPL_FROMNODE_HELPER(_class, NodeInfo()->Equals(nsGkAtoms::_tag, _nsid))
2394 #define NS_IMPL_FROMNODE_HTML_WITH_TAG(_class, _tag) \
2395 NS_IMPL_FROMNODE_WITH_TAG(_class, kNameSpaceID_XHTML, _tag)
2397 #endif /* nsINode_h___ */