insertBefore method

  1. @mustCallSuper
  2. @override
Node insertBefore(
  1. Node newChild,
  2. Node referenceNode
)
override

Implementation

@mustCallSuper
@override
Node insertBefore(Node newChild, Node referenceNode) {
  // https://dom.spec.whatwg.org/#concept-node-pre-insert

  // insertBefore(node, null) is equivalent to appendChild(node)

  // 1. Ensure pre-insertion validity of node into parent before child.
  // 2. Let reference child be child.
  // 3. If reference child is node, set it to node’s next sibling.
  // Already done at C++ side.

  if (enableWebFProfileTracking) {
    WebFProfiler.instance.startTrackUICommandStep('ContainerNode.insertBefore');
  }

  // 4. Adopt node into parent’s node document.
  List<Node> targets = [];
  if (!collectChildrenAndRemoveFromOldParent(newChild, targets)) {
    if (enableWebFProfileTracking) {
      WebFProfiler.instance.finishTrackUICommandStep();
    }

    return newChild;
  }

  // 5. Insert node into parent before reference child.
  _insertNode(targets, referenceNode, _adoptAndInsertBefore);

  // 6. Mark this element to dirty elements.
  if (this is Element) {
    ownerDocument.markElementStyleDirty(this as Element);
  }

  // 7. Trigger connected callback
  if (newChild.isConnected) {
    newChild.connectedCallback();
  }

  // To insert a node into a parent before a child, run step 9 from the spec:
  // 8. Run the children changed steps for parent when inserting a node into a parent.
  // https://dom.spec.whatwg.org/#concept-node-insert
  didInsertNode(targets, referenceNode);

  if (enableWebFProfileTracking) {
    WebFProfiler.instance.finishTrackUICommandStep();
  }

  return newChild;
}