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/. */
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"
31 // Including 'windows.h' will #define GetClassInfo to something else.
39 class nsAttrChildContentList
;
42 class nsDOMAttributeMap
;
43 class nsGenericHTMLElement
;
44 class nsIAnimationObserver
;
46 class nsIContentSecurityPolicy
;
48 class nsIHTMLCollection
;
49 class nsMultiMutationObserver
;
54 class nsNodeSupportsWeakRefTearoff
;
55 class nsDOMMutationObserver
;
60 class EventListenerManager
;
61 struct StyleSelectorList
;
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' ||
75 inline bool IsSpaceCharacter(char aChar
) {
76 return aChar
== ' ' || aChar
== '\t' || aChar
== '\n' || aChar
== '\r' ||
82 class AncestorsOfTypeIterator
;
83 struct BoxQuadOptions
;
84 struct ConvertCoordinateOptions
;
87 class DocumentFragment
;
88 class DocumentOrShadowRoot
;
91 class DOMRectReadOnly
;
93 class EventHandlerNonNull
;
95 class FlatTreeAncestorsOfTypeIterator
;
97 class InclusiveAncestorsOfTypeIterator
;
99 class InclusiveFlatTreeAncestorsOfTypeIterator
;
101 class MutationObservers
;
102 template <typename T
>
104 class OwningNodeOrString
;
110 class TextOrElementOrDocument
;
112 struct GetRootNodeOptions
;
113 enum class CallerType
: uint32_t;
115 } // namespace mozilla
117 #define NODE_FLAG_BIT(n_) \
118 (nsWrapperCache::FlagsType(1U) << (WRAPPER_CACHE_FLAGS_BITS_USED + (n_)))
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
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 // Node has an :empty or :-moz-only-whitespace selector
147 NODE_HAS_EMPTY_SELECTOR
= NODE_FLAG_BIT(6),
149 // A child of the node has a selector such that any insertion,
150 // removal, or appending of children requires restyling the parent, if the
151 // parent is an element. If the parent is the shadow root, the child's
152 // siblings are restyled.
153 NODE_HAS_SLOW_SELECTOR
= NODE_FLAG_BIT(7),
155 // A child of the node has a :first-child, :-moz-first-node,
156 // :only-child, :last-child or :-moz-last-node selector.
157 NODE_HAS_EDGE_CHILD_SELECTOR
= NODE_FLAG_BIT(8),
159 // A child of the node has a selector such that any insertion or
160 // removal of children requires restyling later siblings of that
161 // element. Additionally (in this manner it is stronger than
162 // NODE_HAS_SLOW_SELECTOR), if a child's style changes due to any
163 // other content tree changes (e.g., the child changes to or from
164 // matching :empty due to a grandchild insertion or removal), the
165 // child's later siblings must also be restyled.
166 NODE_HAS_SLOW_SELECTOR_LATER_SIBLINGS
= NODE_FLAG_BIT(9),
168 // A child of this node might be matched by :nth-child(.. of <selector>) or
169 // :nth-last-child(.. of <selector>). If a DOM mutation may have caused the
170 // selector to either match or no longer match that child, the child's
171 // siblings are restyled.
172 NODE_HAS_SLOW_SELECTOR_NTH_OF
= NODE_FLAG_BIT(10),
174 // Set of selector flags that may trigger a restyle as a result of DOM
176 NODE_RESTYLE_SELECTOR_FLAGS
=
177 NODE_HAS_EMPTY_SELECTOR
| NODE_HAS_SLOW_SELECTOR
|
178 NODE_HAS_EDGE_CHILD_SELECTOR
| NODE_HAS_SLOW_SELECTOR_LATER_SIBLINGS
|
179 NODE_HAS_SLOW_SELECTOR_NTH_OF
,
181 // This node needs to go through frame construction to get a frame (or
182 // undisplayed entry).
183 NODE_NEEDS_FRAME
= NODE_FLAG_BIT(11),
185 // At least one descendant in the flattened tree has NODE_NEEDS_FRAME set.
186 // This should be set on every node on the flattened tree path between the
187 // node(s) with NODE_NEEDS_FRAME and the root content.
188 NODE_DESCENDANTS_NEED_FRAMES
= NODE_FLAG_BIT(12),
190 // Set if the node has the accesskey attribute set.
191 NODE_HAS_ACCESSKEY
= NODE_FLAG_BIT(13),
193 // Set if the node has right-to-left directionality
194 NODE_HAS_DIRECTION_RTL
= NODE_FLAG_BIT(14),
196 // Set if the node has left-to-right directionality
197 NODE_HAS_DIRECTION_LTR
= NODE_FLAG_BIT(15),
199 NODE_ALL_DIRECTION_FLAGS
= NODE_HAS_DIRECTION_LTR
| NODE_HAS_DIRECTION_RTL
,
201 NODE_HAS_BEEN_IN_UA_WIDGET
= NODE_FLAG_BIT(16),
203 // Set if the node has a nonce value and a header delivered CSP.
204 NODE_HAS_NONCE_AND_HEADER_CSP
= NODE_FLAG_BIT(17),
206 NODE_KEEPS_DOMARENA
= NODE_FLAG_BIT(18),
208 NODE_MAY_HAVE_ELEMENT_CHILDREN
= NODE_FLAG_BIT(19),
210 // Remaining bits are node type specific.
211 NODE_TYPE_SPECIFIC_BITS_OFFSET
= 20
214 // Make sure we have space for our bits
215 #define ASSERT_NODE_FLAGS_SPACE(n) \
216 static_assert(WRAPPER_CACHE_FLAGS_BITS_USED + (n) <= \
217 sizeof(nsWrapperCache::FlagsType) * 8, \
218 "Not enough space for our bits")
219 ASSERT_NODE_FLAGS_SPACE(NODE_TYPE_SPECIFIC_BITS_OFFSET
);
222 * Class used to detect unexpected mutations. To use the class create an
223 * nsMutationGuard on the stack before unexpected mutations could occur.
224 * You can then at any time call Mutated to check if any unexpected mutations
227 class nsMutationGuard
{
229 nsMutationGuard() { mStartingGeneration
= sGeneration
; }
232 * Returns true if any unexpected mutations have occurred. You can pass in
233 * an 8-bit ignore count to ignore a number of expected mutations.
235 * We don't need to care about overflow because subtraction of uint64_t's is
236 * finding the difference between two elements of the group Z < 2^64. Once
237 * we know the difference between two elements we only need to check that is
238 * less than the given number of mutations to know less than that many
239 * mutations occured. Assuming constant 1ns mutations it would take 584
240 * years for sGeneration to fully wrap around so we can ignore a guard living
241 * through a full wrap around.
243 bool Mutated(uint8_t aIgnoreCount
) {
244 return (sGeneration
- mStartingGeneration
) > aIgnoreCount
;
247 // This function should be called whenever a mutation that we want to keep
248 // track of happen. For now this is only done when children are added or
249 // removed, but we might do it for attribute changes too in the future.
250 static void DidMutate() { sGeneration
++; }
253 // This is the value sGeneration had when the guard was constructed.
254 uint64_t mStartingGeneration
;
256 // This value is incremented on every mutation, for the life of the process.
257 static uint64_t sGeneration
;
261 * A class that implements nsIWeakReference
263 class nsNodeWeakReference final
: public nsIWeakReference
{
265 explicit nsNodeWeakReference(nsINode
* aNode
);
271 NS_DECL_NSIWEAKREFERENCE
273 void NoticeNodeDestruction() { mObject
= nullptr; }
276 ~nsNodeWeakReference();
279 // This should be used for any nsINode sub-class that has fields of its own
280 // that it needs to measure; any sub-class that doesn't use it will inherit
281 // AddSizeOfExcludingThis from its super-class. AddSizeOfIncludingThis() need
282 // not be defined, it is inherited from nsINode.
283 #define NS_DECL_ADDSIZEOFEXCLUDINGTHIS \
284 virtual void AddSizeOfExcludingThis(nsWindowSizes& aSizes, \
285 size_t* aNodeSize) const override;
287 // IID for the nsINode interface
288 // Must be kept in sync with xpcom/rust/xpcom/src/interfaces/nonidl.rs
289 #define NS_INODE_IID \
291 0x70ba4547, 0x7699, 0x44fc, { \
292 0xb3, 0x20, 0x52, 0xdb, 0xe3, 0xd1, 0xf9, 0x0a \
297 * An internal interface that abstracts some DOMNode-related parts that both
298 * nsIContent and Document share. An instance of this interface has a list
299 * of nsIContent children and provides access to them.
301 class nsINode
: public mozilla::dom::EventTarget
{
302 #ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
303 void AssertInvariantsOnNodeInfoChange();
306 using BoxQuadOptions
= mozilla::dom::BoxQuadOptions
;
307 using ConvertCoordinateOptions
= mozilla::dom::ConvertCoordinateOptions
;
308 using DocGroup
= mozilla::dom::DocGroup
;
309 using Document
= mozilla::dom::Document
;
310 using DOMPoint
= mozilla::dom::DOMPoint
;
311 using DOMPointInit
= mozilla::dom::DOMPointInit
;
312 using DOMQuad
= mozilla::dom::DOMQuad
;
313 using DOMRectReadOnly
= mozilla::dom::DOMRectReadOnly
;
314 using OwningNodeOrString
= mozilla::dom::OwningNodeOrString
;
315 using TextOrElementOrDocument
= mozilla::dom::TextOrElementOrDocument
;
316 using CallerType
= mozilla::dom::CallerType
;
317 using ErrorResult
= mozilla::ErrorResult
;
319 // XXXbz Maybe we should codegen a class holding these constants and
320 // inherit from it...
321 static const auto ELEMENT_NODE
= mozilla::dom::Node_Binding::ELEMENT_NODE
;
322 static const auto ATTRIBUTE_NODE
= mozilla::dom::Node_Binding::ATTRIBUTE_NODE
;
323 static const auto TEXT_NODE
= mozilla::dom::Node_Binding::TEXT_NODE
;
324 static const auto CDATA_SECTION_NODE
=
325 mozilla::dom::Node_Binding::CDATA_SECTION_NODE
;
326 static const auto ENTITY_REFERENCE_NODE
=
327 mozilla::dom::Node_Binding::ENTITY_REFERENCE_NODE
;
328 static const auto ENTITY_NODE
= mozilla::dom::Node_Binding::ENTITY_NODE
;
329 static const auto PROCESSING_INSTRUCTION_NODE
=
330 mozilla::dom::Node_Binding::PROCESSING_INSTRUCTION_NODE
;
331 static const auto COMMENT_NODE
= mozilla::dom::Node_Binding::COMMENT_NODE
;
332 static const auto DOCUMENT_NODE
= mozilla::dom::Node_Binding::DOCUMENT_NODE
;
333 static const auto DOCUMENT_TYPE_NODE
=
334 mozilla::dom::Node_Binding::DOCUMENT_TYPE_NODE
;
335 static const auto DOCUMENT_FRAGMENT_NODE
=
336 mozilla::dom::Node_Binding::DOCUMENT_FRAGMENT_NODE
;
337 static const auto NOTATION_NODE
= mozilla::dom::Node_Binding::NOTATION_NODE
;
338 static const auto MAX_NODE_TYPE
= NOTATION_NODE
;
340 void* operator new(size_t aSize
, nsNodeInfoManager
* aManager
);
341 void* operator new(size_t aSize
) = delete;
342 void operator delete(void* aPtr
);
345 using Sequence
= mozilla::dom::Sequence
<T
>;
347 NS_DECLARE_STATIC_IID_ACCESSOR(NS_INODE_IID
)
349 // The |aNodeSize| outparam on this function is where the actual node size
350 // value is put. It gets added to the appropriate value within |aSizes| by
351 // AddSizeOfNodeTree().
353 // Among the sub-classes that inherit (directly or indirectly) from nsINode,
354 // measurement of the following members may be added later if DMD finds it is
356 // - nsGenericHTMLElement: mForm, mFieldSet
357 // - nsGenericHTMLFrameElement: mFrameLoader (bug 672539)
358 // - HTMLBodyElement: mContentStyleRule
359 // - HTMLDataListElement: mOptions
360 // - HTMLFieldSetElement: mElements, mDependentElements, mFirstLegend
361 // - HTMLFormElement: many!
362 // - HTMLFrameSetElement: mRowSpecs, mColSpecs
363 // - HTMLInputElement: mInputData, mFiles, mFileList, mStaticDocfileList
364 // - nsHTMLMapElement: mAreas
365 // - HTMLMediaElement: many!
366 // - nsHTMLOutputElement: mDefaultValue, mTokenList
367 // - nsHTMLRowElement: mCells
368 // - nsHTMLSelectElement: mOptions, mRestoreState
369 // - nsHTMLTableElement: mTBodies, mRows, mTableInheritedAttributes
370 // - nsHTMLTableSectionElement: mRows
371 // - nsHTMLTextAreaElement: mControllers, mState
373 // The following members don't need to be measured:
374 // - nsIContent: mPrimaryFrame, because it's non-owning and measured elsewhere
376 virtual void AddSizeOfExcludingThis(nsWindowSizes
& aSizes
,
377 size_t* aNodeSize
) const;
379 // SizeOfIncludingThis doesn't need to be overridden by sub-classes because
380 // sub-classes of nsINode are guaranteed to be laid out in memory in such a
381 // way that |this| points to the start of the allocated object, even in
382 // methods of nsINode's sub-classes, so aSizes.mState.mMallocSizeOf(this) is
383 // always safe to call no matter which object it was invoked on.
384 void AddSizeOfIncludingThis(nsWindowSizes
& aSizes
, size_t* aNodeSize
) const;
386 friend class nsNodeWeakReference
;
387 friend class nsNodeSupportsWeakRefTearoff
;
388 friend class AttrArray
;
390 #ifdef MOZILLA_INTERNAL_API
391 explicit nsINode(already_AddRefed
<mozilla::dom::NodeInfo
>&& aNodeInfo
);
396 bool IsContainerNode() const {
397 return IsElement() || IsDocument() || IsDocumentFragment();
401 * Returns true if the node is a HTMLTemplate element.
403 bool IsTemplateElement() const { return IsHTMLElement(nsGkAtoms::_template
); }
405 bool IsSlotable() const { return IsElement() || IsText(); }
408 * Returns true if this is a document node.
410 bool IsDocument() const {
411 // One less pointer-chase than checking NodeType().
412 return !GetParentNode() && IsInUncomposedDoc();
416 * Return this node as a document. Asserts IsDocument().
418 * This is defined inline in Document.h.
420 inline Document
* AsDocument();
421 inline const Document
* AsDocument() const;
424 * Returns true if this is a document fragment node.
426 bool IsDocumentFragment() const {
427 return NodeType() == DOCUMENT_FRAGMENT_NODE
;
430 virtual bool IsHTMLFormControlElement() const { return false; }
433 * https://dom.spec.whatwg.org/#concept-tree-inclusive-descendant
435 * @param aNode must not be nullptr.
437 bool IsInclusiveDescendantOf(const nsINode
* aNode
) const;
440 * https://dom.spec.whatwg.org/#concept-shadow-including-inclusive-descendant
442 * @param aNode must not be nullptr.
444 bool IsShadowIncludingInclusiveDescendantOf(const nsINode
* aNode
) const;
447 * Returns true if the given node is this node or one of its descendants
448 * in the "flat tree."
450 * @param aNode must not be nullptr.
452 bool IsInclusiveFlatTreeDescendantOf(const nsINode
* aNode
) const;
455 * Return this node as a document fragment. Asserts IsDocumentFragment().
457 * This is defined inline in DocumentFragment.h.
459 inline mozilla::dom::DocumentFragment
* AsDocumentFragment();
460 inline const mozilla::dom::DocumentFragment
* AsDocumentFragment() const;
462 JSObject
* WrapObject(JSContext
*, JS::Handle
<JSObject
*> aGivenProto
) final
;
465 * Hook for constructing JS::ubi::Concrete specializations for memory
466 * reporting. Specializations are defined in NodeUbiReporting.h.
468 virtual void ConstructUbiNode(void* storage
) = 0;
471 * returns true if we are in priviliged code or
472 * layout.css.getBoxQuads.enabled == true.
474 static bool HasBoxQuadsSupport(JSContext
* aCx
, JSObject
* /* unused */);
478 * WrapNode is called from WrapObject to actually wrap this node, WrapObject
479 * does some additional checks and fix-up that's common to all nodes. WrapNode
480 * should just call the DOM binding's Wrap function.
482 * aGivenProto is the prototype to use (or null if the default one should be
483 * used) and should just be passed directly on to the DOM binding's Wrap
486 virtual JSObject
* WrapNode(JSContext
* aCx
,
487 JS::Handle
<JSObject
*> aGivenProto
) = 0;
490 mozilla::dom::ParentObject
GetParentObject()
491 const; // Implemented in Document.h
494 * Returns the first child of a node or the first child of
495 * a template element's content if the provided node is a
498 nsIContent
* GetFirstChildOfTemplateOrNode();
501 * Return the scope chain parent for this node, for use in things
502 * like event handler compilation. Returning null means to use the
503 * global object as the scope chain parent.
505 virtual nsINode
* GetScopeChainParent() const;
507 MOZ_CAN_RUN_SCRIPT
mozilla::dom::Element
* GetParentFlexElement();
510 * Returns the nearest inclusive open popover for a given node, see
511 * https://html.spec.whatwg.org/multipage/popover.html#nearest-inclusive-open-popover
513 mozilla::dom::Element
* GetNearestInclusiveOpenPopover() const;
516 * https://html.spec.whatwg.org/multipage/popover.html#nearest-inclusive-target-popover-for-invoker
518 mozilla::dom::Element
* GetNearestInclusiveTargetPopoverForInvoker() const;
521 * https://html.spec.whatwg.org/multipage/popover.html#popover-target-element
523 nsGenericHTMLElement
* GetEffectivePopoverTargetElement() const;
526 * https://html.spec.whatwg.org/multipage/popover.html#topmost-clicked-popover
528 mozilla::dom::Element
* GetTopmostClickedPopover() const;
530 bool IsNode() const final
{ return true; }
532 NS_IMPL_FROMEVENTTARGET_HELPER(nsINode
, IsNode())
535 * Return whether the node is an Element node. Faster than using `NodeType()`.
537 bool IsElement() const { return GetBoolFlag(NodeIsElement
); }
539 virtual bool IsTextControlElement() const { return false; }
540 virtual bool IsGenericHTMLFormControlElementWithState() const {
544 // Returns non-null if this element subclasses `LinkStyle`.
545 virtual const mozilla::dom::LinkStyle
* AsLinkStyle() const { return nullptr; }
546 mozilla::dom::LinkStyle
* AsLinkStyle() {
547 return const_cast<mozilla::dom::LinkStyle
*>(
548 static_cast<const nsINode
*>(this)->AsLinkStyle());
552 * Return this node as an Element. Should only be used for nodes
553 * for which IsElement() is true. This is defined inline in Element.h.
555 inline mozilla::dom::Element
* AsElement();
556 inline const mozilla::dom::Element
* AsElement() const;
559 * Return whether the node is an nsStyledElement instance or not.
561 virtual bool IsStyledElement() const { return false; }
564 * Return this node as nsIContent. Should only be used for nodes for which
565 * IsContent() is true.
567 * The assertion in nsIContent's constructor makes this safe.
569 nsIContent
* AsContent() {
570 MOZ_ASSERT(IsContent());
571 return reinterpret_cast<nsIContent
*>(this);
573 const nsIContent
* AsContent() const {
574 MOZ_ASSERT(IsContent());
575 return reinterpret_cast<const nsIContent
*>(this);
579 * Return whether the node is a Text node (which might be an actual
580 * textnode, or might be a CDATA section).
582 bool IsText() const {
583 uint32_t nodeType
= NodeType();
584 return nodeType
== TEXT_NODE
|| nodeType
== CDATA_SECTION_NODE
;
588 * Return this node as Text if it is one, otherwise null. This is defined
591 inline mozilla::dom::Text
* GetAsText();
592 inline const mozilla::dom::Text
* GetAsText() const;
595 * Return this node as Text. Asserts IsText(). This is defined inline in
598 inline mozilla::dom::Text
* AsText();
599 inline const mozilla::dom::Text
* AsText() const;
602 * Return whether the node is a ProcessingInstruction node.
604 bool IsProcessingInstruction() const {
605 return NodeType() == PROCESSING_INSTRUCTION_NODE
;
609 * Return whether the node is a CharacterData node (text, cdata,
610 * comment, processing instruction)
612 bool IsCharacterData() const {
613 uint32_t nodeType
= NodeType();
614 return nodeType
== TEXT_NODE
|| nodeType
== CDATA_SECTION_NODE
||
615 nodeType
== PROCESSING_INSTRUCTION_NODE
|| nodeType
== COMMENT_NODE
;
619 * Return whether the node is a Comment node.
621 bool IsComment() const { return NodeType() == COMMENT_NODE
; }
624 * Return whether the node is an Attr node.
626 bool IsAttr() const { return NodeType() == ATTRIBUTE_NODE
; }
629 * Return if this node has any children.
631 bool HasChildren() const { return !!mFirstChild
; }
634 * Get the number of children
635 * @return the number of children
637 uint32_t GetChildCount() const { return mChildCount
; }
640 * NOTE: this function is going to be removed soon (hopefully!) Don't use it
643 * Get a child by index
644 * @param aIndex the index of the child to get
645 * @return the child, or null if index out of bounds
647 nsIContent
* GetChildAt_Deprecated(uint32_t aIndex
) const;
650 * Get the index of a child within this content.
652 * @param aPossibleChild the child to get the index of.
653 * @return the index of the child, or Nothing if not a child. Be aware that
654 * anonymous children (e.g. a <div> child of an <input> element) will
657 * If the return value is Some, then calling GetChildAt_Deprecated() with
658 * that value will return aPossibleChild.
660 mozilla::Maybe
<uint32_t> ComputeIndexOf(const nsINode
* aPossibleChild
) const;
663 * Get the index of this within parent node (ComputeIndexInParentNode) or
664 * parent content (nsIContent) node (ComputeIndexInParentContent).
666 * @return the index of this node in the parent, or Nothing there is no
667 * parent (content) node or the parent does not have this node anymore
668 * (e.g., being removed from the parent). Be aware that anonymous
669 * children (e.g. a <div> child of an <input> element) will result in
672 * If the return value is Some, then calling GetChildAt_Deprecated() with
673 * that value will return this.
675 mozilla::Maybe
<uint32_t> ComputeIndexInParentNode() const;
676 mozilla::Maybe
<uint32_t> ComputeIndexInParentContent() const;
679 * Get the index of a child within this content.
681 * @param aPossibleChild the child to get the index of.
682 * @return the index of the child, or -1 if not a child. Be aware that
683 * anonymous children (e.g. a <div> child of an <input> element) will
686 * If the return value is not -1, then calling GetChildAt_Deprecated() with
687 * that value will return aPossibleChild.
689 int32_t ComputeIndexOf_Deprecated(const nsINode
* aPossibleChild
) const;
692 * Returns the "node document" of this node.
694 * https://dom.spec.whatwg.org/#concept-node-document
696 * Note that in the case that this node is a document node this method
697 * will return |this|. That is different to the Node.ownerDocument DOM
698 * attribute (implemented by nsINode::GetOwnerDocument) which is specified to
699 * be null in that case:
701 * https://dom.spec.whatwg.org/#dom-node-ownerdocument
703 * For all other cases OwnerDoc and GetOwnerDocument behave identically.
705 Document
* OwnerDoc() const MOZ_NONNULL_RETURN
{
706 return mNodeInfo
->GetDocument();
710 * Return the "owner document" of this node as an nsINode*. Implemented
713 inline nsINode
* OwnerDocAsNode() const MOZ_NONNULL_RETURN
;
716 * Returns true if the content has an ancestor that is a document.
718 * @return whether this content is in a document tree
720 bool IsInUncomposedDoc() const { return GetBoolFlag(IsInDocument
); }
723 * Get the document that this content is currently in, if any. This will be
724 * null if the content has no ancestor that is a document.
726 * @return the current document
729 Document
* GetUncomposedDoc() const {
730 return IsInUncomposedDoc() ? OwnerDoc() : nullptr;
734 * Returns true if we're connected, and thus GetComposedDoc() would return a
737 bool IsInComposedDoc() const { return GetBoolFlag(IsConnected
); }
740 * This method returns the owner document if the node is connected to it
741 * (as defined in the DOM spec), otherwise it returns null.
742 * In other words, returns non-null even in the case the node is in
743 * Shadow DOM, if there is a possibly shadow boundary crossing path from
744 * the node to its owner document.
746 Document
* GetComposedDoc() const {
747 return IsInComposedDoc() ? OwnerDoc() : nullptr;
751 * Returns OwnerDoc() if the node is in uncomposed document and ShadowRoot if
752 * the node is in Shadow DOM.
754 mozilla::dom::DocumentOrShadowRoot
* GetContainingDocumentOrShadowRoot() const;
757 * Returns OwnerDoc() if the node is in uncomposed document and ShadowRoot if
758 * the node is in Shadow DOM and is in composed document.
760 mozilla::dom::DocumentOrShadowRoot
* GetUncomposedDocOrConnectedShadowRoot()
764 * To be called when reference count of the node drops to zero.
769 * The values returned by this function are the ones defined for
772 uint16_t NodeType() const { return mNodeInfo
->NodeType(); }
773 const nsString
& NodeName() const { return mNodeInfo
->NodeName(); }
774 const nsString
& LocalName() const { return mNodeInfo
->LocalName(); }
777 * Get the NodeInfo for this element
778 * @return the nodes node info
780 inline mozilla::dom::NodeInfo
* NodeInfo() const { return mNodeInfo
; }
783 * Called when we have been adopted, and the information of the
784 * node has been changed.
786 * The new document can be reached via OwnerDoc().
788 * If you override this method,
789 * please call up to the parent NodeInfoChanged.
791 * If you change this, change also the similar method in Link.
793 virtual void NodeInfoChanged(Document
* aOldDoc
) {
794 #ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
795 AssertInvariantsOnNodeInfoChange();
799 inline bool IsInNamespace(int32_t aNamespace
) const {
800 return mNodeInfo
->NamespaceID() == aNamespace
;
804 * Returns the DocGroup of the "node document" of this node.
806 DocGroup
* GetDocGroup() const;
809 * Print a debugger friendly descriptor of this element. This will describe
810 * the position of this element in the document.
812 friend std::ostream
& operator<<(std::ostream
& aStream
, const nsINode
& aNode
);
815 // These 2 methods are useful for the recursive templates IsHTMLElement,
816 // IsSVGElement, etc.
817 inline bool IsNodeInternal() const { return false; }
819 template <typename First
, typename
... Args
>
820 inline bool IsNodeInternal(First aFirst
, Args
... aArgs
) const {
821 return mNodeInfo
->Equals(aFirst
) || IsNodeInternal(aArgs
...);
825 inline bool IsHTMLElement() const {
826 return IsElement() && IsInNamespace(kNameSpaceID_XHTML
);
829 inline bool IsHTMLElement(const nsAtom
* aTag
) const {
830 return IsElement() && mNodeInfo
->Equals(aTag
, kNameSpaceID_XHTML
);
833 template <typename First
, typename
... Args
>
834 inline bool IsAnyOfHTMLElements(First aFirst
, Args
... aArgs
) const {
835 return IsHTMLElement() && IsNodeInternal(aFirst
, aArgs
...);
838 inline bool IsSVGElement() const {
839 return IsElement() && IsInNamespace(kNameSpaceID_SVG
);
842 inline bool IsSVGElement(const nsAtom
* aTag
) const {
843 return IsElement() && mNodeInfo
->Equals(aTag
, kNameSpaceID_SVG
);
846 template <typename First
, typename
... Args
>
847 inline bool IsAnyOfSVGElements(First aFirst
, Args
... aArgs
) const {
848 return IsSVGElement() && IsNodeInternal(aFirst
, aArgs
...);
851 virtual bool IsSVGAnimationElement() const { return false; }
852 virtual bool IsSVGGeometryElement() const { return false; }
853 virtual bool IsSVGGraphicsElement() const { return false; }
855 inline bool IsXULElement() const {
856 return IsElement() && IsInNamespace(kNameSpaceID_XUL
);
859 inline bool IsXULElement(const nsAtom
* aTag
) const {
860 return IsElement() && mNodeInfo
->Equals(aTag
, kNameSpaceID_XUL
);
863 template <typename First
, typename
... Args
>
864 inline bool IsAnyOfXULElements(First aFirst
, Args
... aArgs
) const {
865 return IsXULElement() && IsNodeInternal(aFirst
, aArgs
...);
868 inline bool IsMathMLElement() const {
869 return IsElement() && IsInNamespace(kNameSpaceID_MathML
);
872 inline bool IsMathMLElement(const nsAtom
* aTag
) const {
873 return IsElement() && mNodeInfo
->Equals(aTag
, kNameSpaceID_MathML
);
876 template <typename First
, typename
... Args
>
877 inline bool IsAnyOfMathMLElements(First aFirst
, Args
... aArgs
) const {
878 return IsMathMLElement() && IsNodeInternal(aFirst
, aArgs
...);
881 bool IsShadowRoot() const {
882 const bool isShadowRoot
= IsInShadowTree() && !GetParentNode();
883 MOZ_ASSERT_IF(isShadowRoot
, IsDocumentFragment());
887 bool IsHTMLHeadingElement() const {
888 return IsAnyOfHTMLElements(nsGkAtoms::h1
, nsGkAtoms::h2
, nsGkAtoms::h3
,
889 nsGkAtoms::h4
, nsGkAtoms::h5
, nsGkAtoms::h6
);
893 * Insert a content node before another or at the end.
894 * This method handles calling BindToTree on the child appropriately.
896 * @param aKid the content to insert
897 * @param aBeforeThis an existing node. Use nullptr if you want to
898 * add aKid at the end.
899 * @param aNotify whether to notify the document (current document for
900 * nsIContent, and |this| for Document) that the insert has occurred
901 * @param aRv The error, if any.
902 * Throw NS_ERROR_DOM_HIERARCHY_REQUEST_ERR if one attempts to have
903 * more than one element node as a child of a document. Doing this
904 * will also assert -- you shouldn't be doing it! Check with
905 * Document::GetRootElement() first if you're not sure. Apart from
906 * this one constraint, this doesn't do any checking on whether aKid is
907 * a valid child of |this|.
908 * Throw NS_ERROR_OUT_OF_MEMORY in some cases (from BindToTree).
910 virtual void InsertChildBefore(nsIContent
* aKid
, nsIContent
* aBeforeThis
,
911 bool aNotify
, mozilla::ErrorResult
& aRv
);
914 * Append a content node to the end of the child list. This method handles
915 * calling BindToTree on the child appropriately.
917 * @param aKid the content to append
918 * @param aNotify whether to notify the document (current document for
919 * nsIContent, and |this| for Document) that the append has occurred
920 * @param aRv The error, if any.
921 * Throw NS_ERROR_DOM_HIERARCHY_REQUEST_ERR if one attempts to have
922 * more than one element node as a child of a document. Doing this
923 * will also assert -- you shouldn't be doing it! Check with
924 * Document::GetRootElement() first if you're not sure. Apart from
925 * this one constraint, this doesn't do any checking on whether aKid is
926 * a valid child of |this|.
927 * Throw NS_ERROR_OUT_OF_MEMORY in some cases (from BindToTree).
929 void AppendChildTo(nsIContent
* aKid
, bool aNotify
,
930 mozilla::ErrorResult
& aRv
) {
931 InsertChildBefore(aKid
, nullptr, aNotify
, aRv
);
935 * Remove a child from this node. This method handles calling UnbindFromTree
936 * on the child appropriately.
938 * @param aKid the content to remove
939 * @param aNotify whether to notify the document (current document for
940 * nsIContent, and |this| for Document) that the remove has occurred
942 virtual void RemoveChildNode(nsIContent
* aKid
, bool aNotify
);
945 * Get a property associated with this node.
947 * @param aPropertyName name of property to get.
948 * @param aStatus out parameter for storing resulting status.
949 * Set to NS_PROPTABLE_PROP_NOT_THERE if the property
951 * @return the property. Null if the property is not set
952 * (though a null return value does not imply the
953 * property was not set, i.e. it can be set to null).
955 void* GetProperty(const nsAtom
* aPropertyName
,
956 nsresult
* aStatus
= nullptr) const;
959 * Set a property to be associated with this node. This will overwrite an
960 * existing value if one exists. The existing value is destroyed using the
961 * destructor function given when that value was set.
963 * @param aPropertyName name of property to set.
964 * @param aValue new value of property.
965 * @param aDtor destructor function to be used when this property
967 * @param aTransfer if true the property will not be deleted when the
968 * ownerDocument of the node changes, if false it
971 * @return NS_PROPTABLE_PROP_OVERWRITTEN (success value) if the property
973 * @throws NS_ERROR_OUT_OF_MEMORY if that occurs
975 nsresult
SetProperty(nsAtom
* aPropertyName
, void* aValue
,
976 NSPropertyDtorFunc aDtor
= nullptr,
977 bool aTransfer
= false);
980 * A generic destructor for property values allocated with new.
983 static void DeleteProperty(void*, nsAtom
*, void* aPropertyValue
, void*) {
984 delete static_cast<T
*>(aPropertyValue
);
988 * Removes a property associated with this node. The value is destroyed using
989 * the destruction function given when that value was set.
991 * @param aPropertyName name of property to destroy.
993 void RemoveProperty(const nsAtom
* aPropertyName
);
996 * Take a property associated with this node. The value will not be destroyed
997 * but rather returned. It is the caller's responsibility to destroy the value
1000 * @param aPropertyName name of property to unset.
1001 * @param aStatus out parameter for storing resulting status.
1002 * Set to NS_PROPTABLE_PROP_NOT_THERE if the property
1004 * @return the property. Null if the property is not set
1005 * (though a null return value does not imply the
1006 * property was not set, i.e. it can be set to null).
1008 void* TakeProperty(const nsAtom
* aPropertyName
, nsresult
* aStatus
= nullptr);
1010 bool HasProperties() const { return HasFlag(NODE_HAS_PROPERTIES
); }
1013 * Return the principal of this node. This is guaranteed to never be a null
1016 nsIPrincipal
* NodePrincipal() const {
1017 return mNodeInfo
->NodeInfoManager()->DocumentPrincipal();
1021 * Return the CSP of this node's document, if any.
1023 nsIContentSecurityPolicy
* GetCsp() const;
1026 * Get the parent nsIContent for this node.
1027 * @return the parent, or null if no parent or the parent is not an nsIContent
1029 nsIContent
* GetParent() const {
1030 return MOZ_LIKELY(GetBoolFlag(ParentIsContent
)) ? mParent
->AsContent()
1035 * Get the parent nsINode for this node. This can be either an nsIContent, a
1036 * Document or an Attr.
1037 * @return the parent node
1039 nsINode
* GetParentNode() const { return mParent
; }
1042 nsIContent
* DoGetShadowHost() const;
1045 nsINode
* GetParentOrShadowHostNode() const {
1046 if (MOZ_LIKELY(mParent
)) {
1049 // We could put this in nsIContentInlines.h or such to avoid this
1050 // reinterpret_cast, but it doesn't seem worth it.
1051 return IsInShadowTree() ? reinterpret_cast<nsINode
*>(DoGetShadowHost())
1055 enum FlattenedParentType
{ eNotForStyle
, eForStyle
};
1058 * Returns the node that is the parent of this node in the flattened
1059 * tree. This differs from the normal parent if the node is filtered
1060 * into an insertion point, or if the node is a direct child of a
1063 * @return the flattened tree parent
1065 inline nsINode
* GetFlattenedTreeParentNode() const;
1067 nsINode
* GetFlattenedTreeParentNodeNonInline() const;
1070 * Like GetFlattenedTreeParentNode, but returns the document for any native
1071 * anonymous content that was generated for ancestor frames of the document
1072 * element's primary frame, such as scrollbar elements created by the root
1075 inline nsINode
* GetFlattenedTreeParentNodeForStyle() const;
1077 inline mozilla::dom::Element
* GetFlattenedTreeParentElement() const;
1078 inline mozilla::dom::Element
* GetFlattenedTreeParentElementForStyle() const;
1081 * Get the parent nsINode for this node if it is an Element.
1083 * Defined inline in Element.h
1085 * @return the parent node
1087 inline mozilla::dom::Element
* GetParentElement() const;
1090 * Get the parent Element of this node, traversing over a ShadowRoot
1091 * to its host if necessary.
1093 mozilla::dom::Element
* GetParentElementCrossingShadowRoot() const;
1096 * Get closest element node for the node. Meaning that if the node is an
1097 * element node, returns itself. Otherwise, returns parent element or null.
1099 inline mozilla::dom::Element
* GetAsElementOrParentElement() const;
1102 * Get the root of the subtree this node belongs to. This never returns
1103 * null. It may return 'this' (e.g. for document nodes, and nodes that
1104 * are the roots of disconnected subtrees).
1106 nsINode
* SubtreeRoot() const;
1109 * Get context object's shadow-including root if options's composed is true,
1110 * and context object's root otherwise.
1112 nsINode
* GetRootNode(const mozilla::dom::GetRootNodeOptions
& aOptions
);
1114 virtual mozilla::EventListenerManager
* GetExistingListenerManager()
1116 virtual mozilla::EventListenerManager
* GetOrCreateListenerManager() override
;
1118 mozilla::Maybe
<mozilla::dom::EventCallbackDebuggerNotificationType
>
1119 GetDebuggerNotificationType() const override
;
1121 bool ComputeDefaultWantsUntrusted(mozilla::ErrorResult
& aRv
) final
;
1123 virtual bool IsApzAware() const override
;
1125 virtual nsPIDOMWindowOuter
* GetOwnerGlobalForBindingsInternal() override
;
1126 virtual nsIGlobalObject
* GetOwnerGlobal() const override
;
1128 using mozilla::dom::EventTarget::DispatchEvent
;
1129 // TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230)
1130 MOZ_CAN_RUN_SCRIPT_BOUNDARY
bool DispatchEvent(
1131 mozilla::dom::Event
& aEvent
, mozilla::dom::CallerType aCallerType
,
1132 mozilla::ErrorResult
& aRv
) override
;
1135 nsresult
PostHandleEvent(mozilla::EventChainPostVisitor
& aVisitor
) override
;
1138 * Adds a mutation observer to be notified when this node, or any of its
1139 * descendants, are modified. The node will hold a weak reference to the
1140 * observer, which means that it is the responsibility of the observer to
1141 * remove itself in case it dies before the node. If an observer is added
1142 * while observers are being notified, it may also be notified. In general,
1143 * adding observers while inside a notification is not a good idea. An
1144 * observer that is already observing the node must not be added without
1145 * being removed first.
1147 * For mutation observers that implement nsIAnimationObserver, use
1148 * AddAnimationObserver instead.
1150 void AddMutationObserver(nsIMutationObserver
* aMutationObserver
) {
1151 nsSlots
* s
= Slots();
1152 if (aMutationObserver
) {
1153 NS_ASSERTION(!s
->mMutationObservers
.contains(aMutationObserver
),
1154 "Observer already in the list");
1156 s
->mMutationObservers
.pushBack(aMutationObserver
);
1160 void AddMutationObserver(nsMultiMutationObserver
* aMultiMutationObserver
);
1163 * Same as above, but only adds the observer if its not observing
1166 * For mutation observers that implement nsIAnimationObserver, use
1167 * AddAnimationObserverUnlessExists instead.
1169 void AddMutationObserverUnlessExists(nsIMutationObserver
* aMutationObserver
) {
1170 nsSlots
* s
= Slots();
1171 if (aMutationObserver
&&
1172 !s
->mMutationObservers
.contains(aMutationObserver
)) {
1173 s
->mMutationObservers
.pushBack(aMutationObserver
);
1177 void AddMutationObserverUnlessExists(
1178 nsMultiMutationObserver
* aMultiMutationObserver
);
1180 * Same as AddMutationObserver, but for nsIAnimationObservers. This
1181 * additionally records on the document that animation observers have
1182 * been registered, which is used to determine whether notifications
1183 * must be fired when animations are added, removed or changed.
1185 void AddAnimationObserver(nsIAnimationObserver
* aAnimationObserver
);
1188 * Same as above, but only adds the observer if its not observing
1191 void AddAnimationObserverUnlessExists(
1192 nsIAnimationObserver
* aAnimationObserver
);
1195 * Removes a mutation observer.
1197 void RemoveMutationObserver(nsIMutationObserver
* aMutationObserver
) {
1198 nsSlots
* s
= GetExistingSlots();
1200 s
->mMutationObservers
.remove(aMutationObserver
);
1204 void RemoveMutationObserver(nsMultiMutationObserver
* aMultiMutationObserver
);
1206 mozilla::SafeDoublyLinkedList
<nsIMutationObserver
>* GetMutationObservers();
1209 * Helper methods to access ancestor node(s) of type T.
1210 * The implementations of the methods are in mozilla/dom/AncestorIterator.h.
1212 template <typename T
>
1213 inline mozilla::dom::AncestorsOfTypeIterator
<T
> AncestorsOfType() const;
1215 template <typename T
>
1216 inline mozilla::dom::InclusiveAncestorsOfTypeIterator
<T
>
1217 InclusiveAncestorsOfType() const;
1219 template <typename T
>
1220 inline mozilla::dom::FlatTreeAncestorsOfTypeIterator
<T
>
1221 FlatTreeAncestorsOfType() const;
1223 template <typename T
>
1224 inline mozilla::dom::InclusiveFlatTreeAncestorsOfTypeIterator
<T
>
1225 InclusiveFlatTreeAncestorsOfType() const;
1227 template <typename T
>
1228 T
* FirstAncestorOfType() const;
1232 * Walks aNode, its attributes and, if aDeep is true, its descendant nodes.
1233 * If aClone is true the nodes will be cloned. If aNewNodeInfoManager is
1234 * not null, it is used to create new nodeinfos for the nodes. Also reparents
1235 * the XPConnect wrappers for the nodes into aReparentScope if non-null.
1237 * @param aNode Node to adopt/clone.
1238 * @param aClone If true the node will be cloned and the cloned node will
1240 * @param aDeep If true the function will be called recursively on
1241 * descendants of the node
1242 * @param aNewNodeInfoManager The nodeinfo manager to use to create new
1243 * nodeinfos for aNode and its attributes and
1244 * descendants. May be null if the nodeinfos
1245 * shouldn't be changed.
1246 * @param aReparentScope Scope into which wrappers should be reparented, or
1247 * null if no reparenting should be done.
1248 * @param aParent If aClone is true the cloned node will be appended to
1249 * aParent's children. May be null. If not null then aNode
1250 * must be an nsIContent.
1251 * @param aError The error, if any.
1253 * @return If aClone is true then the cloned node will be returned,
1254 * unless an error occurred. In error conditions, null
1257 static already_AddRefed
<nsINode
> CloneAndAdopt(
1258 nsINode
* aNode
, bool aClone
, bool aDeep
,
1259 nsNodeInfoManager
* aNewNodeInfoManager
,
1260 JS::Handle
<JSObject
*> aReparentScope
, nsINode
* aParent
,
1261 mozilla::ErrorResult
& aError
);
1265 * Walks the node, its attributes and descendant nodes. If aNewNodeInfoManager
1266 * is not null, it is used to create new nodeinfos for the nodes. Also
1267 * reparents the XPConnect wrappers for the nodes into aReparentScope if
1270 * @param aNewNodeInfoManager The nodeinfo manager to use to create new
1271 * nodeinfos for the node and its attributes and
1272 * descendants. May be null if the nodeinfos
1273 * shouldn't be changed.
1274 * @param aReparentScope New scope for the wrappers, or null if no reparenting
1276 * @param aError The error, if any.
1278 void Adopt(nsNodeInfoManager
* aNewNodeInfoManager
,
1279 JS::Handle
<JSObject
*> aReparentScope
,
1280 mozilla::ErrorResult
& aError
);
1283 * Clones the node, its attributes and, if aDeep is true, its descendant nodes
1284 * If aNewNodeInfoManager is not null, it is used to create new nodeinfos for
1287 * @param aDeep If true the function will be called recursively on
1288 * descendants of the node
1289 * @param aNewNodeInfoManager The nodeinfo manager to use to create new
1290 * nodeinfos for the node and its attributes and
1291 * descendants. May be null if the nodeinfos
1292 * shouldn't be changed.
1293 * @param aError The error, if any.
1295 * @return The newly created node. Null in error conditions.
1297 already_AddRefed
<nsINode
> Clone(bool aDeep
,
1298 nsNodeInfoManager
* aNewNodeInfoManager
,
1299 mozilla::ErrorResult
& aError
);
1302 * Clones this node. This needs to be overriden by all node classes. aNodeInfo
1303 * should be identical to this node's nodeInfo, except for the document which
1304 * may be different. When cloning an element, all attributes of the element
1305 * will be cloned. The children of the node will not be cloned.
1307 * @param aNodeInfo the nodeinfo to use for the clone
1308 * @param aResult the clone
1310 virtual nsresult
Clone(mozilla::dom::NodeInfo
*, nsINode
** aResult
) const = 0;
1312 // This class can be extended by subclasses that wish to store more
1313 // information in the slots.
1318 // If needed we could remove the vtable pointer this dtor causes by
1319 // putting a DestroySlots function on nsINode
1322 virtual void Traverse(nsCycleCollectionTraversalCallback
&);
1323 virtual void Unlink(nsINode
&);
1326 * A list of mutation observers
1328 mozilla::SafeDoublyLinkedList
<nsIMutationObserver
> mMutationObservers
;
1331 * An object implementing NodeList for this content (childNodes)
1333 * @see nsGenericHTMLElement::GetChildNodes
1335 RefPtr
<nsAttrChildContentList
> mChildNodes
;
1338 * Weak reference to this node. This is cleared by the destructor of
1339 * nsNodeWeakReference.
1341 nsNodeWeakReference
* MOZ_NON_OWNING_REF mWeakReference
;
1344 * A set of ranges which are in the selection and which have this node as
1345 * their endpoints' closest common inclusive ancestor
1346 * (https://dom.spec.whatwg.org/#concept-tree-inclusive-ancestor). This is
1347 * a UniquePtr instead of just a LinkedList, because that prevents us from
1348 * pushing DOMSlots up to the next allocation bucket size, at the cost of
1351 mozilla::UniquePtr
<mozilla::LinkedList
<mozilla::dom::AbstractRange
>>
1352 mClosestCommonInclusiveAncestorRanges
;
1356 * Functions for managing flags and slots
1359 nsSlots
* DebugGetSlots() { return Slots(); }
1362 void SetFlags(FlagsType aFlagsToSet
) {
1365 (NODE_IS_NATIVE_ANONYMOUS_ROOT
| NODE_IS_IN_NATIVE_ANONYMOUS_SUBTREE
|
1366 NODE_DESCENDANTS_NEED_FRAMES
| NODE_NEEDS_FRAME
|
1367 NODE_HAS_BEEN_IN_UA_WIDGET
)) ||
1369 "Flag only permitted on nsIContent nodes");
1370 nsWrapperCache::SetFlags(aFlagsToSet
);
1373 void UnsetFlags(FlagsType aFlagsToUnset
) {
1374 NS_ASSERTION(!(aFlagsToUnset
& (NODE_HAS_BEEN_IN_UA_WIDGET
|
1375 NODE_IS_NATIVE_ANONYMOUS_ROOT
)),
1376 "Trying to unset write-only flags");
1377 nsWrapperCache::UnsetFlags(aFlagsToUnset
);
1380 void SetEditableFlag(bool aEditable
) {
1382 SetFlags(NODE_IS_EDITABLE
);
1384 UnsetFlags(NODE_IS_EDITABLE
);
1388 inline bool IsEditable() const;
1391 * Check if this node is in design mode or not. When this returns true and:
1392 * - if this is a Document node, it's the design mode root.
1393 * - if this is a content node, it's connected, it's not in a shadow tree
1394 * (except shadow tree for UI widget and native anonymous subtree) and its
1395 * uncomposed document is in design mode.
1396 * Note that returning true does NOT mean the node or its children is
1397 * editable. E.g., when this node is in a shadow tree of a UA widget and its
1398 * host is in design mode.
1400 inline bool IsInDesignMode() const;
1403 * Returns true if |this| or any of its ancestors is native anonymous.
1405 bool IsInNativeAnonymousSubtree() const {
1406 return HasFlag(NODE_IS_IN_NATIVE_ANONYMOUS_SUBTREE
);
1410 * If |this| or any ancestor is native anonymous, return the root of the
1411 * native anonymous subtree. Note that in case of nested native anonymous
1412 * content, this returns the innermost root, not the outermost.
1414 nsIContent
* GetClosestNativeAnonymousSubtreeRoot() const {
1415 if (!IsInNativeAnonymousSubtree()) {
1416 MOZ_ASSERT(!HasBeenInUAWidget(), "UA widget implies anonymous");
1419 MOZ_ASSERT(IsContent(), "How did non-content end up in NAC?");
1420 if (HasBeenInUAWidget()) {
1421 // reinterpret_cast because in this header we don't know ShadowRoot is an
1422 // nsIContent. ShadowRoot constructor asserts this is correct.
1423 return reinterpret_cast<nsIContent
*>(GetContainingShadow());
1425 for (const nsINode
* node
= this; node
; node
= node
->GetParentNode()) {
1426 if (node
->IsRootOfNativeAnonymousSubtree()) {
1427 return const_cast<nsINode
*>(node
)->AsContent();
1430 // FIXME(emilio): This should not happen, usually, but editor removes nodes
1431 // in native anonymous subtrees, and we don't clean nodes from the current
1432 // event content stack from ContentRemoved, so it can actually happen, see
1434 NS_WARNING("GetClosestNativeAnonymousSubtreeRoot on disconnected NAC!");
1439 * If |this| or any ancestor is native anonymous, return the parent of the
1440 * native anonymous subtree. Note that in case of nested native anonymous
1441 * content, this returns the parent or host of the innermost root, not the
1444 nsIContent
* GetClosestNativeAnonymousSubtreeRootParentOrHost() const {
1445 // We could put this in nsIContentInlines.h or such to avoid this
1446 // reinterpret_cast, but it doesn't seem worth it.
1447 const auto* root
= reinterpret_cast<const nsINode
*>(
1448 GetClosestNativeAnonymousSubtreeRoot());
1452 if (nsIContent
* parent
= root
->GetParent()) {
1455 if (MOZ_UNLIKELY(root
->IsInShadowTree())) {
1456 return root
->DoGetShadowHost();
1462 * Gets the root of the node tree for this content if it is in a shadow tree.
1464 mozilla::dom::ShadowRoot
* GetContainingShadow() const;
1466 * Gets the shadow host if this content is in a shadow tree. That is, the host
1467 * of |GetContainingShadow|, if its not null.
1469 * @return The shadow host, if this is in shadow tree, or null.
1471 nsIContent
* GetContainingShadowHost() const;
1473 bool IsInSVGUseShadowTree() const {
1474 return !!GetContainingSVGUseShadowHost();
1477 mozilla::dom::SVGUseElement
* GetContainingSVGUseShadowHost() const {
1478 if (!IsInShadowTree()) {
1481 return DoGetContainingSVGUseShadowHost();
1484 // Whether this node has ever been part of a UA widget shadow tree.
1485 bool HasBeenInUAWidget() const { return HasFlag(NODE_HAS_BEEN_IN_UA_WIDGET
); }
1487 // True for native anonymous content and for content in UA widgets.
1488 // Only nsIContent can fulfill this condition.
1489 bool ChromeOnlyAccess() const { return IsInNativeAnonymousSubtree(); }
1491 const nsIContent
* GetChromeOnlyAccessSubtreeRootParent() const {
1492 return GetClosestNativeAnonymousSubtreeRootParentOrHost();
1495 bool IsInShadowTree() const { return HasFlag(NODE_IS_IN_SHADOW_TREE
); }
1498 * Get whether this node is C++-generated anonymous content
1499 * @see nsIAnonymousContentCreator
1500 * @return whether this content is anonymous
1502 bool IsRootOfNativeAnonymousSubtree() const {
1504 !HasFlag(NODE_IS_NATIVE_ANONYMOUS_ROOT
) || IsInNativeAnonymousSubtree(),
1505 "Some flags seem to be missing!");
1506 return HasFlag(NODE_IS_NATIVE_ANONYMOUS_ROOT
);
1509 // Whether this node is the root of a ChromeOnlyAccess DOM subtree.
1510 bool IsRootOfChromeAccessOnlySubtree() const {
1511 return IsRootOfNativeAnonymousSubtree();
1515 * Returns true if |this| node is the closest common inclusive ancestor
1516 * (https://dom.spec.whatwg.org/#concept-tree-inclusive-ancestor) of the
1517 * start/end nodes of a Range in a Selection or a descendant of such a common
1518 * ancestor. This node is definitely not selected when |false| is returned,
1519 * but it may or may not be selected when |true| is returned.
1521 bool IsMaybeSelected() const {
1522 return IsDescendantOfClosestCommonInclusiveAncestorForRangeInSelection() ||
1523 IsClosestCommonInclusiveAncestorForRangeInSelection();
1527 * Return true if any part of (this, aStartOffset) .. (this, aEndOffset)
1528 * overlaps any nsRange in
1529 * GetClosestCommonInclusiveAncestorForRangeInSelection ranges (i.e.
1530 * where this is a descendant of a range's common inclusive ancestor node).
1531 * If a nsRange starts in (this, aEndOffset) or if it ends in
1532 * (this, aStartOffset) then it is non-overlapping and the result is false
1533 * for that nsRange. Collapsed ranges always counts as non-overlapping.
1535 * @param aStartOffset has to be less or equal to aEndOffset.
1537 bool IsSelected(uint32_t aStartOffset
, uint32_t aEndOffset
) const;
1540 * Get the root element of the text editor associated with this node or the
1541 * root element of the text editor of the ancestor 'TextControlElement' if
1542 * this is in its native anonymous subtree. I.e., this returns anonymous
1543 * `<div>` element of a `TextEditor`. Note that this can be used only for
1544 * getting root content of `<input>` or `<textarea>`. I.e., this method
1545 * doesn't support HTML editors. Note that this may create a `TextEditor`
1546 * instance, and it means that the `TextEditor` may modify its native
1547 * anonymous subtree and may run selection listeners.
1549 MOZ_CAN_RUN_SCRIPT
mozilla::dom::Element
* GetAnonymousRootElementOfTextEditor(
1550 mozilla::TextEditor
** aTextEditor
= nullptr);
1553 * Get the nearest selection root, ie. the node that will be selected if the
1554 * user does "Select All" while the focus is in this node. Note that if this
1555 * node is not in an editor, the result comes from the nsFrameSelection that
1556 * is related to aPresShell, so the result might not be the ancestor of this
1557 * node. Be aware that if this node and the computed selection limiter are
1558 * not in same subtree, this returns the root content of the closeset subtree.
1560 MOZ_CAN_RUN_SCRIPT nsIContent
* GetSelectionRootContent(
1561 mozilla::PresShell
* aPresShell
);
1563 nsINodeList
* ChildNodes();
1565 nsIContent
* GetFirstChild() const { return mFirstChild
; }
1567 nsIContent
* GetLastChild() const;
1570 * Implementation is in Document.h, because it needs to cast from
1571 * Document* to nsINode*.
1573 Document
* GetOwnerDocument() const;
1575 // TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230)
1576 MOZ_CAN_RUN_SCRIPT_BOUNDARY
void Normalize();
1579 * Get the base URI for any relative URIs within this piece of
1580 * content. Generally, this is the document's base URI, but certain
1581 * content carries a local base for backward compatibility.
1583 * @return the base URI. May return null.
1585 virtual nsIURI
* GetBaseURI(bool aTryUseXHRDocBaseURI
= false) const = 0;
1586 nsIURI
* GetBaseURIObject() const;
1589 * Return true if the node may be apz aware. There are two cases. One is that
1590 * the node is apz aware (such as HTMLInputElement with number type). The
1591 * other is that the node has apz aware listeners. This is a non-virtual
1592 * function which calls IsNodeApzAwareInternal only when the MayBeApzAware is
1593 * set. We check the details in IsNodeApzAwareInternal which may be overriden
1596 bool IsNodeApzAware() const {
1597 return NodeMayBeApzAware() ? IsNodeApzAwareInternal() : false;
1601 * Override this function and set the flag MayBeApzAware in case the node has
1602 * to let APZC be aware of it. It's used when the node may handle the apz
1603 * aware events and may do preventDefault to stop APZC to do default actions.
1605 * For example, instead of scrolling page by APZ, we handle mouse wheel event
1606 * in HTMLInputElement with number type as increasing / decreasing its value.
1608 virtual bool IsNodeApzAwareInternal() const;
1610 void GetTextContent(nsAString
& aTextContent
, mozilla::OOMReporter
& aError
) {
1611 GetTextContentInternal(aTextContent
, aError
);
1613 void SetTextContent(const nsAString
& aTextContent
,
1614 nsIPrincipal
* aSubjectPrincipal
,
1615 mozilla::ErrorResult
& aError
) {
1616 SetTextContentInternal(aTextContent
, aSubjectPrincipal
, aError
);
1618 void SetTextContent(const nsAString
& aTextContent
,
1619 mozilla::ErrorResult
& aError
) {
1620 SetTextContentInternal(aTextContent
, nullptr, aError
);
1623 mozilla::dom::Element
* QuerySelector(const nsACString
& aSelector
,
1624 mozilla::ErrorResult
& aResult
);
1625 already_AddRefed
<nsINodeList
> QuerySelectorAll(const nsACString
& aSelector
,
1626 mozilla::ErrorResult
& aResult
);
1629 // Document and ShadowRoot override this with its own (faster) version.
1630 // This should really only be called for elements and document fragments.
1631 mozilla::dom::Element
* GetElementById(const nsAString
& aId
);
1633 void AppendChildToChildList(nsIContent
* aKid
);
1634 void InsertChildToChildList(nsIContent
* aKid
, nsIContent
* aNextSibling
);
1635 void DisconnectChild(nsIContent
* aKid
);
1638 void LookupPrefix(const nsAString
& aNamespace
, nsAString
& aResult
);
1639 bool IsDefaultNamespace(const nsAString
& aNamespaceURI
) {
1640 nsAutoString defaultNamespace
;
1641 LookupNamespaceURI(u
""_ns
, defaultNamespace
);
1642 return aNamespaceURI
.Equals(defaultNamespace
);
1644 void LookupNamespaceURI(const nsAString
& aNamespacePrefix
,
1645 nsAString
& aNamespaceURI
);
1647 nsIContent
* GetNextSibling() const { return mNextSibling
; }
1648 nsIContent
* GetPreviousSibling() const;
1651 * Return true if the node is being removed from the parent, it means that
1652 * the node still knows the container which it's disconnected from, but the
1653 * node has already been removed from the child node chain of the container.
1654 * I.e., Return true between a call of DisconnectChild of the parent and
1655 * a call of UnbindFromTree of the node.
1657 bool IsBeingRemoved() const {
1658 return mParent
&& !mNextSibling
&& !mPreviousOrLastSibling
;
1662 * Get the next node in the pre-order tree traversal of the DOM. If
1663 * aRoot is non-null, then it must be an ancestor of |this|
1664 * (possibly equal to |this|) and only nodes that are descendants of
1665 * aRoot, not including aRoot itself, will be returned. Returns
1666 * null if there are no more nodes to traverse.
1668 nsIContent
* GetNextNode(const nsINode
* aRoot
= nullptr) const {
1669 return GetNextNodeImpl(aRoot
, false);
1673 * Get the next node in the pre-order tree traversal of the DOM but ignoring
1674 * the children of this node. If aRoot is non-null, then it must be an
1675 * ancestor of |this| (possibly equal to |this|) and only nodes that are
1676 * descendants of aRoot, not including aRoot itself, will be returned.
1677 * Returns null if there are no more nodes to traverse.
1679 nsIContent
* GetNextNonChildNode(const nsINode
* aRoot
= nullptr) const {
1680 return GetNextNodeImpl(aRoot
, true);
1684 * Returns true if 'this' is either document or element or
1685 * document fragment and aOther is a descendant in the same
1688 bool Contains(const nsINode
* aOther
) const;
1690 bool UnoptimizableCCNode() const;
1693 * Fire a DOMNodeRemoved mutation event for all children of this node
1694 * TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230)
1696 MOZ_CAN_RUN_SCRIPT_BOUNDARY
void FireNodeRemovedForChildren();
1698 void QueueDevtoolsAnonymousEvent(bool aIsRemove
);
1701 mozilla::dom::SVGUseElement
* DoGetContainingSVGUseShadowHost() const;
1703 nsIContent
* GetNextNodeImpl(const nsINode
* aRoot
,
1704 const bool aSkipChildren
) const {
1707 // TODO: perhaps nsINode::IsInclusiveDescendantOf could be used instead.
1708 const nsINode
* cur
= this;
1709 for (; cur
; cur
= cur
->GetParentNode())
1710 if (cur
== aRoot
) break;
1711 NS_ASSERTION(cur
, "aRoot not an ancestor of |this|?");
1714 if (!aSkipChildren
) {
1715 nsIContent
* kid
= GetFirstChild();
1720 if (this == aRoot
) {
1723 const nsINode
* cur
= this;
1725 nsIContent
* next
= cur
->GetNextSibling();
1729 nsINode
* parent
= cur
->GetParentNode();
1730 if (parent
== aRoot
) {
1735 MOZ_ASSERT_UNREACHABLE("How did we get here?");
1740 * Get the previous nsIContent in the pre-order tree traversal of the DOM. If
1741 * aRoot is non-null, then it must be an ancestor of |this|
1742 * (possibly equal to |this|) and only nsIContents that are descendants of
1743 * aRoot, including aRoot itself, will be returned. Returns
1744 * null if there are no more nsIContents to traverse.
1746 nsIContent
* GetPreviousContent(const nsINode
* aRoot
= nullptr) const {
1749 // TODO: perhaps nsINode::IsInclusiveDescendantOf could be used instead.
1750 const nsINode
* cur
= this;
1751 for (; cur
; cur
= cur
->GetParentNode())
1752 if (cur
== aRoot
) break;
1753 NS_ASSERTION(cur
, "aRoot not an ancestor of |this|?");
1757 if (this == aRoot
) {
1760 nsIContent
* cur
= this->GetParent();
1761 nsIContent
* iter
= this->GetPreviousSibling();
1764 iter
= reinterpret_cast<nsINode
*>(iter
)->GetLastChild();
1774 // Set if we're being used from -moz-element
1775 NodeHasRenderingObservers
,
1776 // Set if our parent chain (including this node itself) terminates
1779 // Set if we're part of the composed doc.
1780 // https://dom.spec.whatwg.org/#connected
1782 // Set if mParent is an nsIContent
1784 // Set if this node is an Element
1786 // Set if the element has a non-empty id attribute. This can in rare
1787 // cases lie for nsXMLElement, such as when the node has been moved between
1788 // documents with different id mappings.
1790 // Set if the element might have a class.
1791 ElementMayHaveClass
,
1792 // Set if the element might have inline style.
1793 ElementMayHaveStyle
,
1794 // Set if the element has a name attribute set.
1796 // Set if the element has a part attribute set.
1798 // Set if the element might have a contenteditable attribute set.
1799 ElementMayHaveContentEditableAttr
,
1800 // Set if the node is the closest common inclusive ancestor of the start/end
1801 // nodes of a Range that is in a Selection.
1802 NodeIsClosestCommonInclusiveAncestorForRangeInSelection
,
1803 // Set if the node is a descendant of a node with the above bit set.
1804 NodeIsDescendantOfClosestCommonInclusiveAncestorForRangeInSelection
,
1805 // Set if CanSkipInCC check has been done for this subtree root.
1807 // Maybe set if this node is in black subtree.
1809 // Maybe set if the node is a root of a subtree
1810 // which needs to be kept in the purple buffer.
1812 // Set if the element has some style states locked
1813 ElementHasLockedStyleStates
,
1814 // Set if element has pointer locked
1815 ElementHasPointerLock
,
1816 // Set if the node may have DOMMutationObserver attached to it.
1817 NodeMayHaveDOMMutationObserver
,
1818 // Set if node is Content
1820 // Set if the node has animations or transitions
1821 ElementHasAnimations
,
1822 // Set if node has a dir attribute with a valid value (ltr, rtl, or auto).
1823 // Note that we cannot compute this from the dir attribute event state
1824 // flags, because we can't use those to distinguish
1825 // <bdi dir="some-invalid-value"> and <bdi dir="auto">.
1826 NodeHasValidDirAttribute
,
1827 // Set if the node has dir=auto and has a property pointing to the text
1828 // node that determines its direction
1830 // Set if the node is a text node descendant of a node with dir=auto
1831 // and has a TextNodeDirectionalityMap property listing the elements whose
1832 // direction it determines.
1833 NodeHasTextNodeDirectionalityMap
,
1834 // Set if a node in the node's parent chain has dir=auto.
1835 NodeAncestorHasDirAuto
,
1836 // Set if the node is handling a click.
1838 // Set if the element has a parser insertion mode other than "in body",
1839 // per the HTML5 "Parse state" section.
1840 ElementHasWeirdParserInsertionMode
,
1841 // Parser sets this flag if it has notified about the node.
1843 // Sets if the node is apz aware or we have apz aware listeners.
1845 // Set if the element might have any kind of anonymous content children,
1846 // which would not be found through the element's children list.
1847 ElementMayHaveAnonymousChildren
,
1848 // Set if element has CustomElementData.
1849 ElementHasCustomElementData
,
1850 // Set if the element was created from prototype cache and
1851 // its l10n attributes haven't been changed.
1852 ElementCreatedFromPrototypeAndHasUnmodifiedL10n
,
1857 void SetBoolFlag(BooleanFlag name
, bool value
) {
1858 static_assert(BooleanFlagCount
<= 8 * sizeof(mBoolFlags
),
1859 "Too many boolean flags");
1860 mBoolFlags
= (mBoolFlags
& ~(1 << name
)) | (value
<< name
);
1863 void SetBoolFlag(BooleanFlag name
) {
1864 static_assert(BooleanFlagCount
<= 8 * sizeof(mBoolFlags
),
1865 "Too many boolean flags");
1866 mBoolFlags
|= (1 << name
);
1869 void ClearBoolFlag(BooleanFlag name
) {
1870 static_assert(BooleanFlagCount
<= 8 * sizeof(mBoolFlags
),
1871 "Too many boolean flags");
1872 mBoolFlags
&= ~(1 << name
);
1875 bool GetBoolFlag(BooleanFlag name
) const {
1876 static_assert(BooleanFlagCount
<= 8 * sizeof(mBoolFlags
),
1877 "Too many boolean flags");
1878 return mBoolFlags
& (1 << name
);
1882 bool HasRenderingObservers() const {
1883 return GetBoolFlag(NodeHasRenderingObservers
);
1885 void SetHasRenderingObservers(bool aValue
) {
1886 SetBoolFlag(NodeHasRenderingObservers
, aValue
);
1888 bool IsContent() const { return GetBoolFlag(NodeIsContent
); }
1889 bool HasID() const { return GetBoolFlag(ElementHasID
); }
1890 bool MayHaveClass() const { return GetBoolFlag(ElementMayHaveClass
); }
1891 void SetMayHaveClass() { SetBoolFlag(ElementMayHaveClass
); }
1892 bool MayHaveStyle() const { return GetBoolFlag(ElementMayHaveStyle
); }
1893 bool HasName() const { return GetBoolFlag(ElementHasName
); }
1894 bool HasPartAttribute() const { return GetBoolFlag(ElementHasPart
); }
1895 bool MayHaveContentEditableAttr() const {
1896 return GetBoolFlag(ElementMayHaveContentEditableAttr
);
1899 * https://dom.spec.whatwg.org/#concept-tree-inclusive-ancestor
1901 bool IsClosestCommonInclusiveAncestorForRangeInSelection() const {
1902 return GetBoolFlag(NodeIsClosestCommonInclusiveAncestorForRangeInSelection
);
1905 * https://dom.spec.whatwg.org/#concept-tree-inclusive-ancestor
1907 void SetClosestCommonInclusiveAncestorForRangeInSelection() {
1908 SetBoolFlag(NodeIsClosestCommonInclusiveAncestorForRangeInSelection
);
1911 * https://dom.spec.whatwg.org/#concept-tree-inclusive-ancestor
1913 void ClearClosestCommonInclusiveAncestorForRangeInSelection() {
1914 ClearBoolFlag(NodeIsClosestCommonInclusiveAncestorForRangeInSelection
);
1917 * https://dom.spec.whatwg.org/#concept-tree-inclusive-ancestor
1919 bool IsDescendantOfClosestCommonInclusiveAncestorForRangeInSelection() const {
1921 NodeIsDescendantOfClosestCommonInclusiveAncestorForRangeInSelection
);
1924 * https://dom.spec.whatwg.org/#concept-tree-inclusive-ancestor
1926 void SetDescendantOfClosestCommonInclusiveAncestorForRangeInSelection() {
1928 NodeIsDescendantOfClosestCommonInclusiveAncestorForRangeInSelection
);
1931 * https://dom.spec.whatwg.org/#concept-tree-inclusive-ancestor
1933 void ClearDescendantOfClosestCommonInclusiveAncestorForRangeInSelection() {
1935 NodeIsDescendantOfClosestCommonInclusiveAncestorForRangeInSelection
);
1938 void SetCCMarkedRoot(bool aValue
) { SetBoolFlag(NodeIsCCMarkedRoot
, aValue
); }
1939 bool CCMarkedRoot() const { return GetBoolFlag(NodeIsCCMarkedRoot
); }
1940 void SetInCCBlackTree(bool aValue
) { SetBoolFlag(NodeIsCCBlackTree
, aValue
); }
1941 bool InCCBlackTree() const { return GetBoolFlag(NodeIsCCBlackTree
); }
1942 void SetIsPurpleRoot(bool aValue
) { SetBoolFlag(NodeIsPurpleRoot
, aValue
); }
1943 bool IsPurpleRoot() const { return GetBoolFlag(NodeIsPurpleRoot
); }
1944 bool MayHaveDOMMutationObserver() {
1945 return GetBoolFlag(NodeMayHaveDOMMutationObserver
);
1947 void SetMayHaveDOMMutationObserver() {
1948 SetBoolFlag(NodeMayHaveDOMMutationObserver
, true);
1950 bool HasListenerManager() { return HasFlag(NODE_HAS_LISTENERMANAGER
); }
1951 bool HasPointerLock() const { return GetBoolFlag(ElementHasPointerLock
); }
1952 void SetPointerLock() { SetBoolFlag(ElementHasPointerLock
); }
1953 void ClearPointerLock() { ClearBoolFlag(ElementHasPointerLock
); }
1954 bool MayHaveAnimations() const { return GetBoolFlag(ElementHasAnimations
); }
1955 void SetMayHaveAnimations() { SetBoolFlag(ElementHasAnimations
); }
1956 void ClearMayHaveAnimations() { ClearBoolFlag(ElementHasAnimations
); }
1957 void SetHasValidDir() { SetBoolFlag(NodeHasValidDirAttribute
); }
1958 void ClearHasValidDir() { ClearBoolFlag(NodeHasValidDirAttribute
); }
1959 bool HasValidDir() const { return GetBoolFlag(NodeHasValidDirAttribute
); }
1960 void SetHasDirAutoSet() {
1961 MOZ_ASSERT(NodeType() != TEXT_NODE
, "SetHasDirAutoSet on text node");
1962 SetBoolFlag(NodeHasDirAutoSet
);
1964 void ClearHasDirAutoSet() {
1965 MOZ_ASSERT(NodeType() != TEXT_NODE
, "ClearHasDirAutoSet on text node");
1966 ClearBoolFlag(NodeHasDirAutoSet
);
1968 bool HasDirAutoSet() const { return GetBoolFlag(NodeHasDirAutoSet
); }
1969 void SetHasTextNodeDirectionalityMap() {
1970 MOZ_ASSERT(NodeType() == TEXT_NODE
,
1971 "SetHasTextNodeDirectionalityMap on non-text node");
1972 SetBoolFlag(NodeHasTextNodeDirectionalityMap
);
1974 void ClearHasTextNodeDirectionalityMap() {
1975 MOZ_ASSERT(NodeType() == TEXT_NODE
,
1976 "ClearHasTextNodeDirectionalityMap on non-text node");
1977 ClearBoolFlag(NodeHasTextNodeDirectionalityMap
);
1979 bool HasTextNodeDirectionalityMap() const {
1980 MOZ_ASSERT(NodeType() == TEXT_NODE
,
1981 "HasTextNodeDirectionalityMap on non-text node");
1982 return GetBoolFlag(NodeHasTextNodeDirectionalityMap
);
1985 void SetAncestorHasDirAuto() { SetBoolFlag(NodeAncestorHasDirAuto
); }
1986 void ClearAncestorHasDirAuto() { ClearBoolFlag(NodeAncestorHasDirAuto
); }
1987 bool AncestorHasDirAuto() const {
1988 return GetBoolFlag(NodeAncestorHasDirAuto
);
1991 // Implemented in nsIContentInlines.h.
1992 inline bool NodeOrAncestorHasDirAuto() const;
1994 void SetParserHasNotified() { SetBoolFlag(ParserHasNotified
); };
1995 bool HasParserNotified() { return GetBoolFlag(ParserHasNotified
); }
1997 void SetMayBeApzAware() { SetBoolFlag(MayBeApzAware
); }
1998 bool NodeMayBeApzAware() const { return GetBoolFlag(MayBeApzAware
); }
2000 void SetMayHaveAnonymousChildren() {
2001 SetBoolFlag(ElementMayHaveAnonymousChildren
);
2003 bool MayHaveAnonymousChildren() const {
2004 return GetBoolFlag(ElementMayHaveAnonymousChildren
);
2007 void SetHasCustomElementData() { SetBoolFlag(ElementHasCustomElementData
); }
2008 bool HasCustomElementData() const {
2009 return GetBoolFlag(ElementHasCustomElementData
);
2012 void SetElementCreatedFromPrototypeAndHasUnmodifiedL10n() {
2013 SetBoolFlag(ElementCreatedFromPrototypeAndHasUnmodifiedL10n
);
2015 bool HasElementCreatedFromPrototypeAndHasUnmodifiedL10n() {
2016 return GetBoolFlag(ElementCreatedFromPrototypeAndHasUnmodifiedL10n
);
2018 void ClearElementCreatedFromPrototypeAndHasUnmodifiedL10n() {
2019 ClearBoolFlag(ElementCreatedFromPrototypeAndHasUnmodifiedL10n
);
2023 void SetParentIsContent(bool aValue
) { SetBoolFlag(ParentIsContent
, aValue
); }
2024 void SetIsInDocument() { SetBoolFlag(IsInDocument
); }
2025 void ClearInDocument() { ClearBoolFlag(IsInDocument
); }
2026 void SetIsConnected(bool aConnected
) { SetBoolFlag(IsConnected
, aConnected
); }
2027 void SetNodeIsContent() { SetBoolFlag(NodeIsContent
); }
2028 void SetIsElement() { SetBoolFlag(NodeIsElement
); }
2029 void SetHasID() { SetBoolFlag(ElementHasID
); }
2030 void ClearHasID() { ClearBoolFlag(ElementHasID
); }
2031 void SetMayHaveStyle() { SetBoolFlag(ElementMayHaveStyle
); }
2032 void SetHasName() { SetBoolFlag(ElementHasName
); }
2033 void ClearHasName() { ClearBoolFlag(ElementHasName
); }
2034 void SetHasPartAttribute(bool aPart
) { SetBoolFlag(ElementHasPart
, aPart
); }
2035 void SetMayHaveContentEditableAttr() {
2036 SetBoolFlag(ElementMayHaveContentEditableAttr
);
2038 void SetHasLockedStyleStates() { SetBoolFlag(ElementHasLockedStyleStates
); }
2039 void ClearHasLockedStyleStates() {
2040 ClearBoolFlag(ElementHasLockedStyleStates
);
2042 bool HasLockedStyleStates() const {
2043 return GetBoolFlag(ElementHasLockedStyleStates
);
2045 void SetHasWeirdParserInsertionMode() {
2046 SetBoolFlag(ElementHasWeirdParserInsertionMode
);
2048 bool HasWeirdParserInsertionMode() const {
2049 return GetBoolFlag(ElementHasWeirdParserInsertionMode
);
2051 bool HandlingClick() const { return GetBoolFlag(NodeHandlingClick
); }
2052 void SetHandlingClick() { SetBoolFlag(NodeHandlingClick
); }
2053 void ClearHandlingClick() { ClearBoolFlag(NodeHandlingClick
); }
2055 void SetSubtreeRootPointer(nsINode
* aSubtreeRoot
) {
2056 NS_ASSERTION(aSubtreeRoot
, "aSubtreeRoot can never be null!");
2057 NS_ASSERTION(!(IsContent() && IsInUncomposedDoc()) && !IsInShadowTree(),
2058 "Shouldn't be here!");
2059 mSubtreeRoot
= aSubtreeRoot
;
2062 void ClearSubtreeRootPointer() { mSubtreeRoot
= nullptr; }
2065 // Makes nsINode object to keep aObject alive.
2066 void BindObject(nsISupports
* aObject
);
2067 // After calling UnbindObject nsINode object doesn't keep
2068 // aObject alive anymore.
2069 void UnbindObject(nsISupports
* aObject
);
2071 void GenerateXPath(nsAString
& aResult
);
2073 already_AddRefed
<mozilla::dom::AccessibleNode
> GetAccessibleNode();
2076 * Returns the length of this node, as specified at
2077 * <http://dvcs.w3.org/hg/domcore/raw-file/tip/Overview.html#concept-node-length>
2079 uint32_t Length() const;
2081 void GetNodeName(mozilla::dom::DOMString
& aNodeName
) {
2082 const nsString
& nodeName
= NodeName();
2083 aNodeName
.SetKnownLiveString(nodeName
);
2085 [[nodiscard
]] nsresult
GetBaseURI(nsAString
& aBaseURI
) const;
2086 // Return the base URI for the document.
2087 // The returned value may differ if the document is loaded via XHR, and
2088 // when accessed from chrome privileged script and
2089 // from content privileged script for compatibility.
2090 void GetBaseURIFromJS(nsAString
& aBaseURI
, CallerType aCallerType
,
2091 ErrorResult
& aRv
) const;
2092 bool HasChildNodes() const { return HasChildren(); }
2094 // See nsContentUtils::PositionIsBefore for aThisIndex and aOtherIndex usage.
2095 uint16_t CompareDocumentPosition(
2096 nsINode
& aOther
, mozilla::Maybe
<uint32_t>* aThisIndex
= nullptr,
2097 mozilla::Maybe
<uint32_t>* aOtherIndex
= nullptr) const;
2098 void GetNodeValue(nsAString
& aNodeValue
) { GetNodeValueInternal(aNodeValue
); }
2099 void SetNodeValue(const nsAString
& aNodeValue
, mozilla::ErrorResult
& aError
) {
2100 SetNodeValueInternal(aNodeValue
, aError
);
2102 virtual void GetNodeValueInternal(nsAString
& aNodeValue
);
2103 virtual void SetNodeValueInternal(const nsAString
& aNodeValue
,
2104 mozilla::ErrorResult
& aError
) {
2105 // The DOM spec says that when nodeValue is defined to be null "setting it
2106 // has no effect", so we don't throw an exception.
2108 void EnsurePreInsertionValidity(nsINode
& aNewChild
, nsINode
* aRefChild
,
2109 mozilla::ErrorResult
& aError
);
2110 nsINode
* InsertBefore(nsINode
& aNode
, nsINode
* aChild
,
2111 mozilla::ErrorResult
& aError
) {
2112 return ReplaceOrInsertBefore(false, &aNode
, aChild
, aError
);
2116 * See <https://dom.spec.whatwg.org/#dom-node-appendchild>.
2118 nsINode
* AppendChild(nsINode
& aNode
, mozilla::ErrorResult
& aError
) {
2119 return InsertBefore(aNode
, nullptr, aError
);
2122 nsINode
* ReplaceChild(nsINode
& aNode
, nsINode
& aChild
,
2123 mozilla::ErrorResult
& aError
) {
2124 return ReplaceOrInsertBefore(true, &aNode
, &aChild
, aError
);
2126 // TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230)
2127 MOZ_CAN_RUN_SCRIPT_BOUNDARY nsINode
* RemoveChild(
2128 nsINode
& aChild
, mozilla::ErrorResult
& aError
);
2129 already_AddRefed
<nsINode
> CloneNode(bool aDeep
, mozilla::ErrorResult
& aError
);
2130 bool IsSameNode(nsINode
* aNode
);
2131 bool IsEqualNode(nsINode
* aNode
);
2132 void GetNamespaceURI(nsAString
& aNamespaceURI
) const {
2133 mNodeInfo
->GetNamespaceURI(aNamespaceURI
);
2135 #ifdef MOZILLA_INTERNAL_API
2136 void GetPrefix(nsAString
& aPrefix
) { mNodeInfo
->GetPrefix(aPrefix
); }
2138 void GetLocalName(mozilla::dom::DOMString
& aLocalName
) const {
2139 const nsString
& localName
= LocalName();
2140 aLocalName
.SetKnownLiveString(localName
);
2143 nsDOMAttributeMap
* GetAttributes();
2145 // Helper method to remove this node from its parent. This is not exposed
2147 // Only call this if the node has a parent node.
2148 nsresult
RemoveFromParent() {
2149 nsINode
* parent
= GetParentNode();
2150 mozilla::ErrorResult rv
;
2151 parent
->RemoveChild(*this, rv
);
2152 return rv
.StealNSResult();
2155 // ChildNode methods
2156 inline mozilla::dom::Element
* GetPreviousElementSibling() const;
2157 inline mozilla::dom::Element
* GetNextElementSibling() const;
2159 MOZ_CAN_RUN_SCRIPT
void Before(const Sequence
<OwningNodeOrString
>& aNodes
,
2161 MOZ_CAN_RUN_SCRIPT
void After(const Sequence
<OwningNodeOrString
>& aNodes
,
2163 MOZ_CAN_RUN_SCRIPT
void ReplaceWith(
2164 const Sequence
<OwningNodeOrString
>& aNodes
, ErrorResult
& aRv
);
2166 * Remove this node from its parent, if any.
2170 // ParentNode methods
2171 mozilla::dom::Element
* GetFirstElementChild() const;
2172 mozilla::dom::Element
* GetLastElementChild() const;
2174 already_AddRefed
<nsIHTMLCollection
> GetElementsByAttribute(
2175 const nsAString
& aAttribute
, const nsAString
& aValue
);
2176 already_AddRefed
<nsIHTMLCollection
> GetElementsByAttributeNS(
2177 const nsAString
& aNamespaceURI
, const nsAString
& aAttribute
,
2178 const nsAString
& aValue
, ErrorResult
& aRv
);
2180 MOZ_CAN_RUN_SCRIPT
void Prepend(const Sequence
<OwningNodeOrString
>& aNodes
,
2182 MOZ_CAN_RUN_SCRIPT
void Append(const Sequence
<OwningNodeOrString
>& aNodes
,
2184 MOZ_CAN_RUN_SCRIPT
void ReplaceChildren(
2185 const Sequence
<OwningNodeOrString
>& aNodes
, ErrorResult
& aRv
);
2186 MOZ_CAN_RUN_SCRIPT
void ReplaceChildren(nsINode
* aNode
, ErrorResult
& aRv
);
2188 void GetBoxQuads(const BoxQuadOptions
& aOptions
,
2189 nsTArray
<RefPtr
<DOMQuad
>>& aResult
, CallerType aCallerType
,
2192 void GetBoxQuadsFromWindowOrigin(const BoxQuadOptions
& aOptions
,
2193 nsTArray
<RefPtr
<DOMQuad
>>& aResult
,
2196 already_AddRefed
<DOMQuad
> ConvertQuadFromNode(
2197 DOMQuad
& aQuad
, const TextOrElementOrDocument
& aFrom
,
2198 const ConvertCoordinateOptions
& aOptions
, CallerType aCallerType
,
2200 already_AddRefed
<DOMQuad
> ConvertRectFromNode(
2201 DOMRectReadOnly
& aRect
, const TextOrElementOrDocument
& aFrom
,
2202 const ConvertCoordinateOptions
& aOptions
, CallerType aCallerType
,
2204 already_AddRefed
<DOMPoint
> ConvertPointFromNode(
2205 const DOMPointInit
& aPoint
, const TextOrElementOrDocument
& aFrom
,
2206 const ConvertCoordinateOptions
& aOptions
, CallerType aCallerType
,
2210 * See nsSlots::mClosestCommonInclusiveAncestorRanges.
2212 const mozilla::LinkedList
<mozilla::dom::AbstractRange
>*
2213 GetExistingClosestCommonInclusiveAncestorRanges() const {
2217 return GetExistingSlots()->mClosestCommonInclusiveAncestorRanges
.get();
2221 * See nsSlots::mClosestCommonInclusiveAncestorRanges.
2223 mozilla::LinkedList
<mozilla::dom::AbstractRange
>*
2224 GetExistingClosestCommonInclusiveAncestorRanges() {
2228 return GetExistingSlots()->mClosestCommonInclusiveAncestorRanges
.get();
2232 * See nsSlots::mClosestCommonInclusiveAncestorRanges.
2234 mozilla::UniquePtr
<mozilla::LinkedList
<mozilla::dom::AbstractRange
>>&
2235 GetClosestCommonInclusiveAncestorRangesPtr() {
2236 return Slots()->mClosestCommonInclusiveAncestorRanges
;
2239 nsIWeakReference
* GetExistingWeakReference() {
2240 return HasSlots() ? GetExistingSlots()->mWeakReference
: nullptr;
2244 // Override this function to create a custom slots class.
2245 // Must not return null.
2246 virtual nsINode::nsSlots
* CreateSlots();
2248 bool HasSlots() const { return mSlots
!= nullptr; }
2250 nsSlots
* GetExistingSlots() const { return mSlots
; }
2254 mSlots
= CreateSlots();
2257 return GetExistingSlots();
2261 * Invalidate cached child array inside mChildNodes
2262 * of type nsParentNodeChildContentList.
2264 void InvalidateChildNodes();
2266 virtual void GetTextContentInternal(nsAString
& aTextContent
,
2267 mozilla::OOMReporter
& aError
);
2268 virtual void SetTextContentInternal(const nsAString
& aTextContent
,
2269 nsIPrincipal
* aSubjectPrincipal
,
2270 mozilla::ErrorResult
& aError
) {}
2272 void EnsurePreInsertionValidity1(mozilla::ErrorResult
& aError
);
2273 void EnsurePreInsertionValidity2(bool aReplace
, nsINode
& aNewChild
,
2275 mozilla::ErrorResult
& aError
);
2276 // TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230)
2277 MOZ_CAN_RUN_SCRIPT_BOUNDARY nsINode
* ReplaceOrInsertBefore(
2278 bool aReplace
, nsINode
* aNewChild
, nsINode
* aRefChild
,
2279 mozilla::ErrorResult
& aError
);
2282 * Returns the Element that should be used for resolving namespaces
2283 * on this node (ie the ownerElement for attributes, the documentElement for
2284 * documents, the node itself for elements and for other nodes the parentNode
2285 * if it is an element).
2287 virtual mozilla::dom::Element
* GetNameSpaceElement() = 0;
2290 * Parse the given selector string into a servo SelectorList.
2292 * Never returns null if aRv is not failing.
2294 * Note that the selector list returned here is owned by the owner doc's
2297 const mozilla::StyleSelectorList
* ParseSelectorList(
2298 const nsACString
& aSelectorString
, mozilla::ErrorResult
&);
2301 /* Event stuff that documents and elements share.
2303 Note that we include DOCUMENT_ONLY_EVENT events here so that we
2304 can forward all the document stuff to this implementation.
2306 #define EVENT(name_, id_, type_, struct_) \
2307 mozilla::dom::EventHandlerNonNull* GetOn##name_() { \
2308 return GetEventHandler(nsGkAtoms::on##name_); \
2310 void SetOn##name_(mozilla::dom::EventHandlerNonNull* handler) { \
2311 SetEventHandler(nsGkAtoms::on##name_, handler); \
2313 #define TOUCH_EVENT EVENT
2314 #define DOCUMENT_ONLY_EVENT EVENT
2315 #include "mozilla/EventNameList.h"
2316 #undef DOCUMENT_ONLY_EVENT
2321 static bool Traverse(nsINode
* tmp
, nsCycleCollectionTraversalCallback
& cb
);
2322 static void Unlink(nsINode
* tmp
);
2324 RefPtr
<mozilla::dom::NodeInfo
> mNodeInfo
;
2326 // mParent is an owning ref most of the time, except for the case of document
2327 // nodes, so it cannot be represented by nsCOMPtr, so mark is as
2329 nsINode
* MOZ_OWNING_REF mParent
;
2332 #ifndef BOOL_FLAGS_ON_WRAPPER_CACHE
2334 uint32_t mBoolFlags
;
2337 // NOTE, there are 32 bits left here, at least in 64 bit builds.
2339 uint32_t mChildCount
;
2342 // mNextSibling and mFirstChild are strong references while
2343 // mPreviousOrLastSibling is a weak ref. |mFirstChild->mPreviousOrLastSibling|
2344 // points to the last child node.
2345 nsCOMPtr
<nsIContent
> mFirstChild
;
2346 nsCOMPtr
<nsIContent
> mNextSibling
;
2347 nsIContent
* MOZ_NON_OWNING_REF mPreviousOrLastSibling
;
2350 // Pointer to our primary frame. Might be null.
2351 nsIFrame
* mPrimaryFrame
;
2353 // Pointer to the root of our subtree. Might be null.
2354 // This reference is non-owning and safe, since it either points to the
2355 // object itself, or is reset by ClearSubtreeRootPointer.
2356 nsINode
* MOZ_NON_OWNING_REF mSubtreeRoot
;
2359 // Storage for more members that are usually not needed; allocated lazily.
2363 inline nsINode
* mozilla::dom::EventTarget::GetAsNode() {
2364 return IsNode() ? AsNode() : nullptr;
2367 inline const nsINode
* mozilla::dom::EventTarget::GetAsNode() const {
2368 return const_cast<mozilla::dom::EventTarget
*>(this)->GetAsNode();
2371 inline nsINode
* mozilla::dom::EventTarget::AsNode() {
2372 MOZ_DIAGNOSTIC_ASSERT(IsNode());
2373 return static_cast<nsINode
*>(this);
2376 inline const nsINode
* mozilla::dom::EventTarget::AsNode() const {
2377 MOZ_DIAGNOSTIC_ASSERT(IsNode());
2378 return static_cast<const nsINode
*>(this);
2381 // Useful inline function for getting a node given an nsIContent and a Document.
2382 // Returns the first argument cast to nsINode if it is non-null, otherwise
2383 // returns the second (which may be null). We use type variables instead of
2384 // nsIContent* and Document* because the actual types must be
2385 // known for the cast to work.
2386 template <class C
, class D
>
2387 inline nsINode
* NODE_FROM(C
& aContent
, D
& aDocument
) {
2388 if (aContent
) return static_cast<nsINode
*>(aContent
);
2389 return static_cast<nsINode
*>(aDocument
);
2392 NS_DEFINE_STATIC_IID_ACCESSOR(nsINode
, NS_INODE_IID
)
2394 inline nsISupports
* ToSupports(nsINode
* aPointer
) { return aPointer
; }
2396 // Some checks are faster to do on nsIContent or Element than on
2397 // nsINode, so spit out FromNode versions taking those types too.
2398 #define NS_IMPL_FROMNODE_GENERIC(_class, _check, _const) \
2399 template <typename T> \
2400 static auto FromNode(_const T& aNode) \
2401 ->decltype(static_cast<_const _class*>(&aNode)) { \
2402 return aNode._check ? static_cast<_const _class*>(&aNode) : nullptr; \
2404 template <typename T> \
2405 static _const _class* FromNode(_const T* aNode) { \
2406 return FromNode(*aNode); \
2408 template <typename T> \
2409 static _const _class* FromNodeOrNull(_const T* aNode) { \
2410 return aNode ? FromNode(*aNode) : nullptr; \
2412 template <typename T> \
2413 static auto FromEventTarget(_const T& aEventTarget) \
2414 ->decltype(static_cast<_const _class*>(&aEventTarget)) { \
2415 return aEventTarget.IsNode() && aEventTarget.AsNode()->_check \
2416 ? static_cast<_const _class*>(&aEventTarget) \
2419 template <typename T> \
2420 static _const _class* FromEventTarget(_const T* aEventTarget) { \
2421 return FromEventTarget(*aEventTarget); \
2423 template <typename T> \
2424 static _const _class* FromEventTargetOrNull(_const T* aEventTarget) { \
2425 return aEventTarget ? FromEventTarget(*aEventTarget) : nullptr; \
2428 #define NS_IMPL_FROMNODE_HELPER(_class, _check) \
2429 NS_IMPL_FROMNODE_GENERIC(_class, _check, ) \
2430 NS_IMPL_FROMNODE_GENERIC(_class, _check, const) \
2432 template <typename T> \
2433 static _class* FromNode(T&& aNode) { \
2434 /* We need the double-cast in case aNode is a smartptr. Those */ \
2435 /* can cast to superclasses of the type they're templated on, */ \
2436 /* but not directly to subclasses. */ \
2437 return aNode->_check ? static_cast<_class*>(static_cast<nsINode*>(aNode)) \
2440 template <typename T> \
2441 static _class* FromNodeOrNull(T&& aNode) { \
2442 return aNode ? FromNode(aNode) : nullptr; \
2444 template <typename T> \
2445 static _class* FromEventTarget(T&& aEventTarget) { \
2446 /* We need the double-cast in case aEventTarget is a smartptr. Those */ \
2447 /* can cast to superclasses of the type they're templated on, */ \
2448 /* but not directly to subclasses. */ \
2449 return aEventTarget->IsNode() && aEventTarget->AsNode()->_check \
2450 ? static_cast<_class*>(static_cast<EventTarget*>(aEventTarget)) \
2453 template <typename T> \
2454 static _class* FromEventTargetOrNull(T&& aEventTarget) { \
2455 return aEventTarget ? FromEventTarget(aEventTarget) : nullptr; \
2458 #define NS_IMPL_FROMNODE(_class, _nsid) \
2459 NS_IMPL_FROMNODE_HELPER(_class, IsInNamespace(_nsid))
2461 #define NS_IMPL_FROMNODE_WITH_TAG(_class, _nsid, _tag) \
2462 NS_IMPL_FROMNODE_HELPER(_class, NodeInfo()->Equals(nsGkAtoms::_tag, _nsid))
2464 #define NS_IMPL_FROMNODE_HTML_WITH_TAG(_class, _tag) \
2465 NS_IMPL_FROMNODE_WITH_TAG(_class, kNameSpaceID_XHTML, _tag)
2467 #endif /* nsINode_h___ */