/** * @license * Copyright (c) 2018 The Polymer Project Authors. All rights reserved. * This code may only be used under the BSD style license found at * http://polymer.github.io/LICENSE.txt * The complete set of authors may be found at * http://polymer.github.io/AUTHORS.txt * The complete set of contributors may be found at * http://polymer.github.io/CONTRIBUTORS.txt * Code distributed by Google as part of the polymer project is also * subject to an additional IP rights grant found at * http://polymer.github.io/PATENTS.txt */ import {ASTNode as Node} from 'parse5'; import {isElement, Predicate, predicates as p} from './predicates'; import {childNodesIncludeTemplate, defaultChildNodes, GetChildNodes} from './util'; export {ASTNode as Node} from 'parse5'; /** * Applies `mapfn` to `node` and the tree below `node`, yielding a flattened * list of results. */ export function* treeMap( node: Node, mapfn: (node: Node) => Iterable, getChildNodes?: GetChildNodes): IterableIterator { for (const child of depthFirst(node, getChildNodes)) { yield* mapfn(child); } } /** * Yields `node` and all of its children, recursively. * * Yields `node` first, then yields each descendent in depth first order. */ export function* depthFirst(node: Node, getChildNodes: GetChildNodes = defaultChildNodes): IterableIterator { yield node; const childNodes = getChildNodes(node); if (childNodes === undefined) { return; } for (const child of childNodes) { yield* depthFirst(child, getChildNodes); } } /** * Yields node and all its descendents in reverse document order. * * Equivalent to: * yield* [...depthFirst(node)].reverse() */ export function* depthFirstReversed( node: Node, getChildNodes: GetChildNodes = defaultChildNodes): IterableIterator { const childNodes = getChildNodes(node); if (childNodes !== undefined) { for (const child of reversedView(childNodes)) { yield* depthFirstReversed(child, getChildNodes); } } yield node; } /** * Like `depthFirst`, but descends into the bodies of `