@flex-development/unist-util-visit v1.1.0
unist-util-visit
unist utility to walk the tree
Contents
What is this?
This package is an essential utility for unist that lets you walk the tree.
When should I use this?
Use this utility when you want to walk the tree with ancestral information, or need to do a postorder walk.
You can use unist-util-visit-parents or syntax-tree/unist-util-visit
if you only need to do a preorder traversal, or don't care about the entire stack of parents.
Install
This package is ESM only.
In Node.js (version 18+) with yarn:
yarn add @flex-development/unist-util-visit
yarn add -D @types/unistIn Deno with esm.sh:
import { CONTINUE, EXIT, SKIP, visit } from 'https://esm.sh/@flex-development/unist-util-visit'In browsers with esm.sh:
<script type="module">
import { CONTINUE, EXIT, SKIP, visit } from 'https://esm.sh/@flex-development/unist-util-visit'
</script>Use
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`)
console.log(`index: ${index}`)
console.log(`parent: ${parent?.type}`)
console.log(`ancestors: ${JSON.stringify(ancestors.map(anc => anc.type))}\n`)
})
// enter and leave
visit(tree, {
enter(node, index, parent, ancestors) {/* … */},
leave(node, index, parent, ancestors) {/* … */}
})Yields:
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"]API
This package exports the identifiers CONTINUE, EXIT, SKIP, and
visit. There is no default export.
visit(tree[, test], visitor|visitors[, reverse])
Visit nodes, with ancestral information.
This algorithm performs depth-first tree traversal in preorder (NLR) and/or
postorder (LRN), or if reverse is given, reverse preorder (NRL) and/or reverse postorder
(RLN). Nodes are handled on enter during preorder traversals and on 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 the
tree multiple times, walk it once, use 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) - tree to traversetest(Test, optional) -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
Continue traversing as normal (true).
const CONTINUE: Continue = trueEXIT
Stop traversing immediately (false).
const EXIT: Exit = falseSKIP
Do not traverse the children of this node ('skip').
const SKIP: Skip = 'skip'Action
Union of action types.
type Action = Continue | Exit | SkipActionTuple
List with at most two (2) values, the first an Action and the second an Index.
type ActionTuple = [
action?: Action | null | undefined | void,
index?: Index | null | undefined
]Index
Move to the 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.
type Index = numberTest
Check for an arbitrary Node.
See unist-util-is for more details.
type Test =
| (TestFunction | unist.Node | unist.Node['type'])[]
| TestFunction
| unist.Node
| unist.Node['type']
| null
| undefinedTestFunction<[T][, P]>
Check if node passes a test.
Parameters
node(T): node to checkindex(Index|undefined): index ofnodeinparent.childrenparent(Parent|undefined): parent ofnode
Return
Test result (boolean | undefined | void).
👉 Note: For the best type-safety, test functions should return type predicates (
node is Type).
VisitedAncestor<[Tree][, Check]>
Collect ancestors of visited nodes in Tree.
Tree(Node) - tree to extract ancestors from- default:
Node
- default:
Check(Test) - visited node test- default:
null | undefined
- default:
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<Tree, Check> // docast.BlockTag | docast.Comment | docast.RootVisitedNode<[Tree][, Check]>
Collect visited nodes in Tree.
Tree(Node) - tree to traverse- default:
Node
- default:
Check(Test) - visited node test- default:
null | undefined
- default:
import type * as docast from '@flex-development/docast'
import type { VisitedNode } from '@flex-development/unist-util-visit'
type Tree = docast.Root
type Visited = VisitedNode<Tree>
// | 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.ThematicBreakVisitedParent<[Tree][, Check]>
Collect parents of visited nodes in Tree.
Tree(Node) - tree to extract parents from- default:
Node
- default:
Check(Test) - visited node test- default:
null | undefined
- default:
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<Tree, Check> // docast.BlockTagVisitor<[Tree][, Check]>
Handle a node.
Visitors are free to transform node. They can also transform parent, or the grandparent of node (the last of
ancestors).
👉 Note: Replacing
nodeitself, ifSKIPis not returned, still causes its descendants to be walked (which is a bug).
When adding or removing previous siblings of node, the Visitor should return a new Index to
specify the sibling to traverse after node is traversed. Adding or removing next siblings of node is handled as
expected without needing to return a new Index.
Removing the children of an ancestor still results in those child nodes being traversed.
Tree(Node) - tree to traverse- default:
Node
- default:
Check(Test) - visited node test- default:
null | undefined
- default:
Parameters
node(VisitedNode<Tree, Check>) - found nodeindex(Index|undefined) - index ofnodeinparent.childrenparent(VisitedParent<Tree, Check>|undefined) - parent ofnodeancestors(VisitedAncestor<Tree, Check>[]) - ancestors ofnode, if any, where the last node is the grandparent ofnode
Return
What to do next (VisitorResult).
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 action
can be returned. When the Action is CONTINUE, Index can be returned.
type VisitorResult = Action | ActionTuple | Index | null | undefined | voidVisitors<[Tree][, Check]>
Handle nodes when entering (preorder) and/or leaving (postorder).
Tree(Node) - tree to traverse- default:
Node
- default:
Check(Test) - visited node test- default:
null | undefined
- default:
Fields
enter(Visitor<Tree, Check>, optional) - handle nodes when entering (preorder)leave(Visitor<Tree, Check>, optional) - handle nodes when exiting (postorder)
Related
unist-util-filter— create a new tree with all nodes that pass a testunist-util-flatmap— create a new tree by mapping (to an array) with the given functionunist-util-generated— check if a node is generatedunist-util-is— check if a node passes a testunist-util-map— create a new tree with all nodes mapped by a given functionunist-util-remove— remove nodes from a tree that pass a testunist-util-select— select nodes with CSS-like selectorsunist-util-visit-parents— recursively walk over nodes, with a stack of parents
Contribute
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.