TODO Do we need to go through whole tree? Save references or consider collapsed nodes as not selected
8216
private List<TreeNode> getSelected(TreeNode parent) {
        List<TreeNode> result = new ArrayList<>();
        for (TreeNode n : parent.getChildren()) {
            if (n.isSelected()) {
                result.add(n);
            }
            result.addAll(getSelected(n));
        }
        return result;
    }
1257832
function (node, single, layoutBy) {
    if (!node._private.data.collapsedChildren){
      return;
    }

    //check how the position of the node is changed
    var positionDiff = {
      x: node._private.position.x - node._private.data['position-before-collapse'].x,
      y: node._private.position.y - node._private.data['position-before-collapse'].y
    };

    node.removeData("infoLabel");
    node.removeClass('cy-expand-collapse-collapsed-node');

    node.trigger("expandcollapse.beforeexpand");
    node._private.data.collapsedChildren.restore();
    this.repairEdges(node);
    node._private.data.collapsedChildren = null;

    elementUtilities.moveNodes(positionDiff, node.children());
    node.removeData('position-before-collapse');

    node.trigger("position"); // position not triggered by default when nodes are moved
    node.trigger("expandcollapse.afterexpand");

    // If expand is called just for one node then call end operation to perform layout
    if (single) {
      this.endOperation(layoutBy);
    }
  }
876796
function getTree(table, options) {

      if (table.isPanel) {
        table = table.getView();
      }

      function getDefOpts() {
        return {
          throwIfInvisible: false,
          allFields: false
        };
      }

      var isVisible = table.isVisible(true);
      options = tiaEJ.ctMisc.checkVisibilityAndFillOptions(isVisible, options, getDefOpts);
      var panel = tiaEJ.search.parentPanel(table);
      var root = panel.getRootNode();
      var res = [];

      function traverseSubTree(node, indent) {

        var fieldsToPrint = ['text', 'checked', 'id'];

        if (tia.debugMode) {
          fieldsToPrint = [
            'text',
            'checked',
            'id',
            'visible',
            'expanded',
            'leaf',
            'expandable',
            'index',
            'depth',
            'qtip',
            'qtitle',
            'cls'
          ];
        }

        if (options.allFields) {
          res.push(indent + tiaEJ.ctMisc.stringifyAllRecord(node, fieldsToPrint, true));
        } else {
          res.push(indent + tiaEJ.ctMisc.stringifyRecord(node, fieldsToPrint, true));
        }

        if (node.hasChildNodes()) {
          indent += tia.cC.content.indent;
          node.eachChild(function (curNode) {
            traverseSubTree(curNode, indent);
          });
        }
      }

      traverseSubTree(root, '');

      return tia.cC.content.wrap('Tree content: \n' + res.join('\n') + '\n');

    }
1288493
function updateReport() {
				var nodeIndex = getNodeIndex({}, structureJson);
			
				var treeOptions = {
					"plugins" : [ "themes", "json_data", "ui", "cookies", "contextmenu" ],
          "core" : {
            "html_titles" : true
          },
					"cookies" : {
						"save_opened" : $report.attr("id")+"_opened"
					},
					"contextmenu" : {
						"select_node" : true,
						"items" : contextMenuHandler
					},
					"json_data" : {
						"progressive_render" : true,
						"progressive_unload" : true,
						"data" : dataHandler
          }
				};
				$report.jstree(treeOptions)
				.on("loaded.jstree", function(event, data) {
					$cukeTree.cukeTree().reportRendered($report);
				})
				.on("select_node.jstree", function(event, data) {
					var $node = $(data.args[0]);
					$cukeTree.cukeTree().reportNodeSelected({ $report : $report, selected : $node });
				});	
        
        function dataHandler(item, callback) {
          var data = null;
          if (item === -1) {
            data = [getTreeNode("group", structureJson)];
          } else {
            data = getTreeNodeChildren($(item).attr("id"));
          }
          callback(data);
        }
        
        function getTreeNodeChildren(id) {
          var data = [];
          var parent = nodeIndex[id];
          if (parent.children !== undefined) {
            for(var i=0; i<parent.children.length; i++) { data.push(getTreeNode("group", parent.children[i])); }
          }
          if (parent.features !== undefined) {
            for(var i=0; i<parent.features.length; i++) { data.push(getTreeNode("feature", parent.features[i])); }
          }
          if (parent.elements !== undefined) {
            for(var i=0; i<parent.elements.length; i++) { data.push(getTreeNode("scenario", parent.elements[i])); }
          }
          if (parent.steps !== undefined) {
            for(var i=0; i<parent.steps.length; i++) { data.push(getTreeNode("step", parent.steps[i])); }
          }
          return data;
        }
        
        function getTreeNode(type, reportEntry) {
          var cssClasses = "node-"+ reportEntry.result.status;
          cssClasses += " "+ type +" "+ type +"-"+ reportEntry.result.status;
          
          var title = reportEntry.name;
          switch(type) {
            case "group": 
              title += " ("+ getScenarioCount(type, reportEntry) +" scenario(s))"; 
              break;
            case "feature":
              var scenarioCount = reportEntry.elements !== undefined ? reportEntry.elements.length : 0;
              if (reportEntry.profile !== undefined) {
                title += " <span class='profile'>["+ reportEntry.profile +"]</span>";
              }
              title += " ("+ scenarioCount +" scenario(s))"
              break;
            case "scenario":
              for(var i=0; i < (reportEntry.tags !== undefined ? reportEntry.tags.length : 0); i++) {
                title += " <span class='scenario-tag'>"+ reportEntry.tags[i].name +"</span>";
              }
              break;
            case "step":
              title = '<span class="keyword">'+ reportEntry.keyword +'</span>'+ title;
              break;
          }
          
          var addingChildren = reportEntry.result && reportEntry.result.status == "failed";
                  
          var node = {
            attr : { 
              id : reportEntry.nodeId,
              "data-type" : type, 
              class : cssClasses
            },
            state : addingChildren && type !== "step" ? "open" : "closed",
            data : {
              attr : { 
                href : "javascript:;", 
                "data-path" : reportEntry.uri
              },
              title : title,
              icon : type
            }
          };
          
          if (addingChildren) {
            node.children = getTreeNodeChildren(reportEntry.nodeId);
          }
          
          if (reportEntry.result.error_message !== undefined) {
            node.attr["data-error"] = reportEntry.result.error_message;
          }
          
          if (reportEntry.embeddings !== undefined) {
            node.attr["data-embedding-mime-type"] = reportEntry.embeddings[0].mime_type;
            node.attr["data-embedding-data"] = reportEntry.embeddings[0].data;
          }
          
          return node;
        }
			}
284771
function isCollapsedWhitespaceNode(node) {
	// "If node is not a whitespace node, return false."
	if (!isWhitespaceNode(node)) {
		return false;
	}

	// "If node's data is the empty string, return true."
	if (node.data == "") {
		return true;
	}

	// "Let ancestor be node's parent."
	var ancestor = node.parentNode;

	// "If ancestor is null, return true."
	if (!ancestor) {
		return true;
	}

	// "If the "display" property of some ancestor of node has resolved value
	// "none", return true."
	if (getAncestors(node).some(function(ancestor) {
		return ancestor.nodeType == Node.ELEMENT_NODE
			&& getComputedStyle(ancestor).display == "none";
	})) {
		return true;
	}

	// "While ancestor is not a block node and its parent is not null, set
	// ancestor to its parent."
	while (!isBlockNode(ancestor)
	&& ancestor.parentNode) {
		ancestor = ancestor.parentNode;
	}

	// "Let reference be node."
	var reference = node;

	// "While reference is a descendant of ancestor:"
	while (reference != ancestor) {
		// "Let reference be the node before it in tree order."
		reference = previousNode(reference);

		// "If reference is a block node or a br, return true."
		if (isBlockNode(reference)
		|| isHtmlElement(reference, "br")) {
			return true;
		}

		// "If reference is a Text node that is not a whitespace node, or is an
		// img, break from this loop."
		if ((reference.nodeType == Node.TEXT_NODE && !isWhitespaceNode(reference))
		|| isHtmlElement(reference, "img")) {
			break;
		}
	}

	// "Let reference be node."
	reference = node;

	// "While reference is a descendant of ancestor:"
	var stop = nextNodeDescendants(ancestor);
	while (reference != stop) {
		// "Let reference be the node after it in tree order, or null if there
		// is no such node."
		reference = nextNode(reference);

		// "If reference is a block node or a br, return true."
		if (isBlockNode(reference)
		|| isHtmlElement(reference, "br")) {
			return true;
		}

		// "If reference is a Text node that is not a whitespace node, or is an
		// img, break from this loop."
		if ((reference && reference.nodeType == Node.TEXT_NODE && !isWhitespaceNode(reference))
		|| isHtmlElement(reference, "img")) {
			break;
		}
	}

	// "Return false."
	return false;
}
768138
def update_all_nodes(self):
        
        item_model_controller = self.item_model_controller
        if item_model_controller:
            if self.__node_counts_dirty:
                for item in self.__mapping.values():
                    if "tree_node" in item.data:  # don't update the root node
                        tree_node = item.data["tree_node"]
                        item.data["display"] = self.__display_for_tree_node(tree_node)
                        item_model_controller.data_changed(item.row, item.parent.row, item.parent.id)
                self.__node_counts_dirty = False
850357
def _collapse_subtree(self, name, recursive=True):
        """"""
        oname = name
        children = self._db[name]["children"]
        data = self._db[name]["data"]
        del_list = []
        while (len(children) == 1) and (not data):
            del_list.append(name)
            name = children[0]
            children = self._db[name]["children"]
            data = self._db[name]["data"]
        parent = self._db[oname]["parent"]
        self._db[name]["parent"] = parent
        if parent:
            self._db[parent]["children"].remove(oname)
            self._db[parent]["children"] = sorted(self._db[parent]["children"] + [name])
        else:
            self._root = name
            self._root_hierarchy_length = len(
                self.root_name.split(self._node_separator)
            )
        for node in del_list:
            self._del_node(node)
        if recursive:
            for child in copy.copy(children):
                self._collapse_subtree(child)
1127728
function(callOpts) {
			var opts = this.tree.options;

			//		this.debug("fixSelection3FromEndNodes()");
			_assert(opts.selectMode === 3, "expected selectMode 3");

			// Visit all end nodes and adjust their parent's `selected` and `partsel`
			// attributes. Return selection state true, false, or undefined.
			function _walk(node) {
				var i,
					l,
					child,
					s,
					state,
					allSelected,
					someSelected,
					unselIgnore,
					unselState,
					children = node.children;

				if (children && children.length) {
					// check all children recursively
					allSelected = true;
					someSelected = false;

					for (i = 0, l = children.length; i < l; i++) {
						child = children[i];
						// the selection state of a node is not relevant; we need the end-nodes
						s = _walk(child);
						// if( !child.unselectableIgnore ) {
						unselIgnore = FT.evalOption(
							"unselectableIgnore",
							child,
							child,
							opts,
							false
						);
						if (!unselIgnore) {
							if (s !== false) {
								someSelected = true;
							}
							if (s !== true) {
								allSelected = false;
							}
						}
					}
					state = allSelected
						? true
						: someSelected
							? undefined
							: false;
				} else {
					// This is an end-node: simply report the status
					unselState = FT.evalOption(
						"unselectableStatus",
						node,
						node,
						opts,
						undefined
					);
					state = unselState == null ? !!node.selected : !!unselState;
				}
				node._changeSelectStatusAttrs(state);
				return state;
			}
			_walk(this);

			// Update parent's state
			this.visitParents(function(node) {
				var i,
					l,
					child,
					state,
					unselIgnore,
					unselState,
					children = node.children,
					allSelected = true,
					someSelected = false;

				for (i = 0, l = children.length; i < l; i++) {
					child = children[i];
					unselIgnore = FT.evalOption(
						"unselectableIgnore",
						child,
						child,
						opts,
						false
					);
					if (!unselIgnore) {
						unselState = FT.evalOption(
							"unselectableStatus",
							child,
							child,
							opts,
							undefined
						);
						state =
							unselState == null
								? !!child.selected
								: !!unselState;
						// When fixing the parents, we trust the sibling status (i.e.
						// we don't recurse)
						if (state || child.partsel) {
							someSelected = true;
						}
						if (!state) {
							allSelected = false;
						}
					}
				}
				state = allSelected ? true : someSelected ? undefined : false;
				node._changeSelectStatusAttrs(state);
			});
		}
541272
private void recursiveCollapseAreas(AreaImpl root)
    {
        if (canCollapse(root))
        {
            //System.out.println("Collapsing: " + root);
            recursiveCollapseSubtree(root, root);
            root.removeAllChildren();
        }
        else
        {
            for (int i = 0; i < root.getChildCount(); i++)
                recursiveCollapseAreas((AreaImpl) root.getChildAt(i));
        }
    }
    
    private boolean canCollapse(AreaImpl area)
    {
        return (area.getChildCount() == 1 && area.getChildAt(0).isLeaf());
    }

    private void recursiveCollapseSubtree(AreaImpl src, AreaImpl dest)
    {
        for (int i = 0; i < src.getChildCount(); i++)
        {
            AreaImpl child = (AreaImpl) src.getChildAt(i);
            recursiveCollapseSubtree(child, dest);
            dest.joinChild(child);
        }
    }

    
}
308998
function recollectNodeTree(node, unmountOnly) {
    var component = node._component;
    if (component) {
      // if node is owned by a Component, unmount that component (ends up recursing back here)
      unmountComponent(component);
    } else {
      // If the node's VNode had a ref function, invoke it with null here.
      // (this is part of the React spec, and smart for unsetting references)
      if (node['__preactattr_'] != null && node['__preactattr_'].ref) node['__preactattr_'].ref(null);

      if (unmountOnly === false || node['__preactattr_'] == null) {
        removeNode(node);
      }

      removeChildren(node);
    }
  }
715808
def merge_reference_trees(roots)
      roots.inject(empty_forest) do |forest, root|
        root.keys do |full_key, node|
          if full_key == node.value.to_s
            log_warn(
              "Self-referencing key #{node.full_key(root: false).inspect} in #{node.data[:locale].inspect}"
            )
          end
        end
        forest.merge!(
          root.children,
          on_leaves_merge: lambda do |node, other|
            if node.value != other.value
              log_warn(
                'Conflicting references: '\
            "#{node.full_key(root: false)} ⮕ #{node.value} in #{node.data[:locale]},"\
            " but ⮕ #{other.value} in #{other.data[:locale]}"
              )
            end
          end
        )
      end
    end
1003815
def build_full_toctree(builder, docname, prune, collapse):
    
    env = builder.env
    doctree = env.get_doctree(env.config.master_doc)
    toctrees = []
    for toctreenode in doctree.traverse(addnodes.toctree):
        toctree = env.resolve_toctree(docname, builder, toctreenode,
                                      collapse=collapse,
                                      prune=prune,
                                      )
        toctrees.append(toctree)
    if not toctrees:
        return None
    result = toctrees[0]
    for toctree in toctrees[1:]:
        if toctree:
            result.extend(toctree.children)
    env.resolve_references(result, docname, builder)
    return result
1073818
private void traverseAndRemoveUnusedReferences(Node root) {
    // Create scope from parent of root node, which also has externs as a child, so we'll
    // have extern definitions in scope.
    Scope scope = scopeCreator.createScope(root.getParent(), null);
    if (!scope.hasSlot(NodeUtil.JSC_PROPERTY_NAME_FN)) {
      // TODO(b/70730762): Passes that add references to this should ensure it is declared.
      // NOTE: null input makes this an extern var.
      scope.declare(
          NodeUtil.JSC_PROPERTY_NAME_FN, /* no declaration node */ null, /* no input */ null);
    }
    worklist.add(new Continuation(root, scope));
    while (!worklist.isEmpty()) {
      Continuation continuation = worklist.remove();
      continuation.apply();
    }

    removeUnreferencedVarsAndPolyfills();
    removeIndependentlyRemovableProperties();
    for (Scope fparamScope : allFunctionParamScopes) {
      removeUnreferencedFunctionArgs(fparamScope);
    }
  }
879255
function collectRefs() {
  // check if there's a shadow root in the element
  if (typeof this.shadowRoot === 'undefined') {
    throw new Error('You must create a shadowRoot on the element');
  }

  // create refs base object
  this.refs = {};

  var refsList = this.shadowRoot.querySelectorAll('[ref]');

  // collect refs if any
  if (refsList.length > 0) {
    var refsArray = _toArray(refsList);

    refsArray.map(_assignRef.bind(this));
  }

  // observe added and removed child nodes
  var refsMutationObserver = new MutationObserver(_handleMutations.bind(this));

  refsMutationObserver.observe(this.shadowRoot, {
    childList: true,
    subtree: true
  });
}
306364
function (root, applyFishEyeViewToEachNode) {
    if (root.data("expand") && root._private.data.collapsedChildren != null) {
      // Expand the root and unmark its expand data to specify that it is no more to be expanded
      this.expandNode(root, applyFishEyeViewToEachNode);
      root.removeData("expand");
    }
    // Make a recursive call for children of root
    var children = root.children();
    for (var i = 0; i < children.length; i++) {
      var node = children[i];
      this.expandTopDown(node);
    }
  }
1334753
void flattenSets() {
        Assert.assrt(fType != setRef);

        if (fLeftChild != null) {
            if (fLeftChild.fType == setRef) {
                RBBINode setRefNode = fLeftChild;
                RBBINode usetNode = setRefNode.fLeftChild;
                RBBINode replTree = usetNode.fLeftChild;
                fLeftChild = replTree.cloneTree();
                fLeftChild.fParent = this;
            } else {
                fLeftChild.flattenSets();
            }
        }

        if (fRightChild != null) {
            if (fRightChild.fType == setRef) {
                RBBINode setRefNode = fRightChild;
                RBBINode usetNode = setRefNode.fLeftChild;
                RBBINode replTree = usetNode.fLeftChild;
                fRightChild = replTree.cloneTree();
                fRightChild.fParent = this;
                // delete setRefNode;
            } else {
                fRightChild.flattenSets();
            }
        }
    }
33240
function referenceParentNode () {
            // If nodeName is an empty string, then reference the parent of the root child.
            if (isEmptyString(nodeName)) {
                nodeName = this.$parentName;

                // Even though super might be invoked in different constructors,
                // the same instance will always be referenced. rootName is used
                // to know if the chain has been broken.
                rootName = this.$name;

                // Prevent instance from having parent properties applied more than once.
                if (this.$applied) {
                    throwError(`Cannot invoke super more than once for ${this.$name} instance.`, 'SUPER');
                } else {
                    descriptor.value = true;

                    Object.defineProperty(this, '$applied', descriptor);
                }

            // Otherwise just move to next parent.
            } else {
                // Error out if chain is broken.
                if (this.$name !== rootName) {
                    throwError(`Chain started by ${rootName} instance is being broken by ${this.$name} instance.`, 'SUPER');
                }

                nodeName = CLASS[nodeName].prototype.$parentName;
            }
        }