unist utility to visit nodes
npm install @flex-development/unist-util-visit








[unist][unist] utility to walk the tree
- What is this?
- When should I use this?
- Install
- Use
- API
- [visit(tree[, test], visitor|visitors[, reverse])](#visittree-test-visitorvisitors-reverse)
- CONTINUE
- EXIT
- SKIP
- Action
- ActionTuple
- Index
- Test
- [TestFunction<[T][, P]>](#testfunctiont-p)
- [VisitedAncestor<[Tree][, Check]>](#visitedancestortree-check)
- [VisitedNode<[Tree][, Check]>](#visitednodetree-check)
- [VisitedParent<[Tree][, Check]>](#visitedparenttree-check)
- [Visitor<[Tree][, Check]>](#visitortree-check)
- VisitorResult
- [Visitors<[Tree][, Check]>](#visitorstree-check)
- Related
- Contribute
This package is an essential utility for [unist][unist] that lets you walk the tree.
Use this utility when you want to walk the tree with ancestral information, or need to do a [postorder][postorder]
walk.
You can use [unist-util-visit-parents][unist-util-visit-parents] or [syntax-tree/unist-util-visit][unist-util-visit]
if you only need to do a [preorder][preorder] traversal, or don't care about the entire stack of parents.
This package is [ESM only][esm].
In Node.js (version 18+) with [yarn][yarn]:
``sh`
yarn add @flex-development/unist-util-visit
yarn add -D @types/unist
See Git - Protocols | Yarn
for details regarding installing from Git.
In Deno with [esm.sh][esmsh]:
`ts`
import { CONTINUE, EXIT, SKIP, visit } from 'https://esm.sh/@flex-development/unist-util-visit'
In browsers with [esm.sh][esmsh]:
`html`
`js
import { fromDocs } from '@flex-development/docast-util-from-docs'
import { visit } from '@flex-development/unist-util-visit'
import { directiveFromMarkdown } from 'mdast-util-directive'
import { directive } from 'micromark-extension-directive'
import { read } from 'to-vfile'
const file = await read('examples/docblock.mjs')
const tree = fromDocs(file, {
mdastExtensions: [directiveFromMarkdown()],
micromarkExtensions: [directive()]
})
visit(tree, (node, index, parent, ancestors) => {
console.log(\u001B[1m${node.type}\u001B[22m)index: ${index}
console.log()parent: ${parent?.type}
console.log()ancestors: ${JSON.stringify(ancestors.map(anc => anc.type))}\n
console.log()
})
// enter and leave
visit(tree, {
enter(node, index, parent, ancestors) {/ … /},
leave(node, index, parent, ancestors) {/ … /}
})
`
Yields:
`sh
root
index: undefined
parent: undefined
ancestors: []
comment
index: 0
parent: root
ancestors: []
description
index: 0
parent: comment
ancestors: ["root"]
paragraph
index: 0
parent: description
ancestors: ["root","comment"]
text
index: 0
parent: paragraph
ancestors: ["root","comment","description"]
break
index: 1
parent: description
ancestors: ["root","comment"]
break
index: 2
parent: description
ancestors: ["root","comment"]
containerDirective
index: 3
parent: description
ancestors: ["root","comment"]
paragraph
index: 0
parent: containerDirective
ancestors: ["root","comment","description"]
text
index: 0
parent: paragraph
ancestors: ["root","comment","description","containerDirective"]
inlineCode
index: 1
parent: paragraph
ancestors: ["root","comment","description","containerDirective"]
text
index: 2
parent: paragraph
ancestors: ["root","comment","description","containerDirective"]
code
index: 1
parent: containerDirective
ancestors: ["root","comment","description"]
blockTag
index: 1
parent: comment
ancestors: ["root"]
typeExpression
index: 0
parent: blockTag
ancestors: ["root","comment"]
`
This package exports the identifiers CONTINUE, EXIT, SKIP, and
visit. There is no default export.
Visit nodes, with ancestral information.
This algorithm performs [depth-first tree traversal][dft] in [preorder][preorder] (NLR) and/or
[postorder][postorder] (LRN), or if reverse is given, reverse preorder (NRL) and/or reverse postorder
(RLN). Nodes are handled on [enter][enter] during preorder traversals and on [exit][exit] during postorder
traversals.
You can choose which nodes visitor functions handle by passing a test. For complex tests, you should test
yourself in visitor or visitors instead, as it will be faster and also have improved type information.
Walking the tree is an intensive task. Make use of visitor return values whenever possible. Instead of walking thetree multiple times, walk it once, use [unist-util-is][unist-util-is] to check if a node matches, and then perform
different operations.
You can change tree. See Visitor for more info.
#### Parameters
- tree ([Node][node]) - [tree][tree] to traversetest
- (Test, optional) - [unist-util-is][unist-util-is]-compatible testvisitor
- (Visitor) - handle a node on entervisitors
- (Visitors) - handle each node on enter and/or exitreverse
- (boolean, optional) - traverse in reverse
#### Return
Nothing (void).
Continue traversing as normal (true).
`ts`
const CONTINUE: Continue = true
Stop traversing immediately (false).
`ts`
const EXIT: Exit = false
Do not traverse the [children][child] of this node ('skip').
`ts`
const SKIP: Skip = 'skip'
Union of action types.
`ts`
type Action = Continue | Exit | Skip
List with at most two (2) values, the first an Action and the second an Index.
`ts`
type ActionTuple = [
action?: Action | null | undefined | void,
index?: Index | null | undefined
]
Move to the [sibling][sibling] at index next (after node itself is completely traversed).
Useful if mutating the tree, such as when removing the node the Visitor is currently on, or
any of its previous siblings.
Negative indices (< 0) and indices greater than or equal to parent.children.length stop traversal of the parent.
`ts`
type Index = number
Check for an arbitrary [Node][node].
See [unist-util-is][unist-util-is] for more details.
`ts`
type Test =
| (TestFunction | unist.Node | unist.Node['type'])[]
| TestFunction
| unist.Node
| unist.Node['type']
| null
| undefined
Check if node passes a test.
- T ([Node][node]): node to checkNode
- default: [][node]P
- ([Parent][parent]): [parent][parent] of node TParent
- default: [][parent]
#### Parameters
- node (T): node to checkindex
- (Index | undefined): index of node in parent.childrenparent
- ([Parent][parent] | undefined): [parent][parent] of node
#### Return
Test result (boolean | undefined | void).
> 👉 Note: For the best type-safety, test functions should return [type predicates][type-predicate] (node is Type).
Collect [ancestors][ancestor] of visited nodes in [Tree][tree].
- Tree ([Node][node]) - [tree][tree] to extract ancestors fromNode
- default: [][node]Check
- (Test) - visited node testnull | undefined
- default:
`ts
import type * as docast from '@flex-development/docast'
import type { VisitedAncestor } from '@flex-development/unist-util-visit'
import type * as unist from 'unist'
type Tree = docast.Root
type Check = (value: unist.Node) => value is docast.TypeExpression
type Visited = VisitedAncestor
`
Collect visited nodes in [Tree][tree].
- Tree ([Node][node]) - [tree][tree] to traverseNode
- default: [][node]Check
- (Test) - visited node testnull | undefined
- default:
`ts
import type * as docast from '@flex-development/docast'
import type { VisitedNode } from '@flex-development/unist-util-visit'
type Tree = docast.Root
type Visited = VisitedNode
// | docast.Root
// | docast.Comment
// | docast.BlockTag
// | docast.Description
// | docast.InlineTag
// | docast.TypeExpression
// | mdast.Blockquote
// | mdast.Code
// | mdast.Definition
// | mdast.FootnoteDefinition
// | mdast.Heading
// | mdast.List
// | mdast.ListItem
// | mdast.Paragraph
// | mdast.PhrasingContent
// | mdast.Table
// | mdast.TableCell
// | mdast.TableRow
// | mdast.ThematicBreak
`
Collect [parents][parent] of visited nodes in [Tree][tree].
- Tree ([Node][node]) - [tree][tree] to extract parents fromNode
- default: [][node]Check
- (Test) - visited node testnull | undefined
- default:
`ts
import type * as docast from '@flex-development/docast'
import type { VisitedNode } from '@flex-development/unist-util-visit'
type Tree = docast.Root
type Check = docast.TypeExpression['type']
type Visited = VisitedNode
`
Handle a node.
Visitors are free to transform node. They can also transform parent, or the grandparent of node (the last ofancestors).
> 👉 Note: Replacing node itself, if SKIP is not returned, still causes its [descendants][descendant]
> to be walked (which is a bug).
When adding or removing previous [siblings][sibling] of node, the Visitor should return a new Index tonode
specify the sibling to traverse after is traversed. Adding or removing next siblings of node is handled asIndex
expected without needing to return a new .
Removing the [children][child] of an [ancestor][ancestor] still results in those child nodes being traversed.
- Tree ([Node][node]) - [tree][tree] to traverseNode
- default: [][node]Check
- (Test) - visited node testnull | undefined
- default:
#### Parameters
- node (VisitedNode) - found nodeindex
- (Index | undefined) - index of node in parent.childrenparent
- (VisitedParent | undefined) - [parent][parent] of nodeancestors
- ([VisitedAncestor](#visitedancestortree-check)) - [ancestors][ancestor] of node, ifnode
any, where the last node is the grandparent of
#### Return
What to do next (VisitorResult).
Union of values that can be returned from a Visitor.
An Index is treated as a tuple of [CONTINUE, Index]. An Action is treated as a tuple of[Action].
Returning a tuple only makes sense if the Action is SKIP. When the Action is EXIT, that actionAction
can be returned. When the is CONTINUE, Index can be returned.
`ts`
type VisitorResult = Action | ActionTuple | Index | null | undefined | void
Handle nodes when entering ([preorder][preorder]) and/or leaving ([postorder][postorder]).
- Tree ([Node][node]) - [tree][tree] to traverseNode
- default: [][node]Check
- (Test) - visited node testnull | undefined
- default:
#### Fields
- enter (Visitor, optional) - handle nodes when [entering][enter] (preorder)leave
- (Visitor, optional) - handle nodes when [exiting][exit] (postorder)
- [unist-util-filter][unist-util-filter] — create a new tree with all nodes that pass a testunist-util-flatmap
- [][unist-util-flatmap] — create a new tree by mapping (to an array) with the given functionunist-util-generated
- [][unist-util-generated] — check if a node is generatedunist-util-is
- [][unist-util-is] — check if a node passes a testunist-util-map
- [][unist-util-map] — create a new tree with all nodes mapped by a given functionunist-util-remove
- [][unist-util-remove] — remove nodes from a tree that pass a testunist-util-select
- [][unist-util-filter] — select nodes with CSS-like selectorsunist-util-visit-parents
- [][unist-util-visit-parents] — recursively walk over nodes, with a stack of parents
See CONTRIBUTING.md`.
This project has a code of conduct. By interacting with this repository, organization, or
community you agree to abide by its terms.
[ancestor]: https://github.com/syntax-tree/unist#ancestor
[child]: https://github.com/syntax-tree/unist#child
[dft]: https://github.com/syntax-tree/unist#depth-first-traversal
[descendant]: https://github.com/syntax-tree/unist#descendant
[enter]: https://github.com/syntax-tree/unist#enter
[esm]: https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c
[esmsh]: https://esm.sh/
[exit]: https://github.com/syntax-tree/unist#exit
[node]: https://github.com/syntax-tree/unist#node
[parent]: https://github.com/syntax-tree/unist#parent-1
[postorder]: https://github.com/syntax-tree/unist#postorder
[preorder]: https://github.com/syntax-tree/unist#preorder
[sibling]: https://github.com/syntax-tree/unist#sibling
[tree]: https://github.com/syntax-tree/unist#tree
[type-predicate]: https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates
[unist-util-filter]: https://github.com/syntax-tree/unist-util-filter
[unist-util-flatmap]: https://github.com/syntax-tree/unist-util-flatmap
[unist-util-generated]: https://github.com/syntax-tree/unist-util-generated
[unist-util-is]: https://github.com/syntax-tree/unist-util-is
[unist-util-map]: https://github.com/syntax-tree/unist-util-map
[unist-util-remove]: https://github.com/syntax-tree/unist-util-remove
[unist-util-visit-parents]: https://github.com/syntax-tree/unist-util-visit-parents
[unist-util-visit]: https://github.com/syntax-tree/unist-util-visit
[unist]: https://github.com/syntax-tree/unist
[yarn]: https://yarnpkg.com