unist utility to walk the tree
This package is an essential utility for 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 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.
This package is ESM only.
In Node.js (version 18+) with yarn:
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
:
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>
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"]
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 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.
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
Nothing (void
).
Continue traversing as normal (true
).
const CONTINUE: Continue = true
Stop traversing immediately (false
).
const EXIT: Exit = false
Do not traverse the children of this node ('skip'
).
const SKIP: Skip = 'skip'
Union of action types.
type Action = Continue | Exit | Skip
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
]
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 = number
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
| undefined
Check if node
passes a test.
node
(T
): node to checkindex
(Index
|undefined
): index ofnode
inparent.children
parent
(Parent
|undefined
): parent ofnode
Test result (boolean | undefined | void
).
π Note: For the best type-safety, test functions should return type predicates (
node is Type
).
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.Root
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.ThematicBreak
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.BlockTag
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
node
itself, ifSKIP
is 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:
node
(VisitedNode<Tree, Check>
) - found nodeindex
(Index
|undefined
) - index ofnode
inparent.children
parent
(VisitedParent<Tree, Check>
|undefined
) - parent ofnode
ancestors
(VisitedAncestor<Tree, Check>[]
) - ancestors ofnode
, if any, where the last node is the grandparent ofnode
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 action
can be returned. When the Action
is CONTINUE
, Index
can be returned.
type VisitorResult = Action | ActionTuple | Index | null | undefined | void
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:
enter
(Visitor<Tree, Check>
, optional) - handle nodes when entering (preorder)leave
(Visitor<Tree, Check>
, optional) - handle nodes when exiting (postorder)
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
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.