unist-util-visit

repository·main·Indexed 43 days ago

https://github.com/syntax-tree/unist-util-visit

A utility for walking unist trees version 5.1.0. It provides the visit() function to traverse nodes with optional filtering by type or test, and allows controlling traversal flow using CONTINUE, EXIT, and SKIP actions.

Tokens
1.4K
Snippets
5
Records
7
Agent score
6%

What's inside unist-util-visit

  1. Visitor implementation details and constraints

    main

    When implementing a Visitor for visit():

    • Node Replacement: You can replace the node itself, but if you do not return SKIP, the descendants of the original node will still be walked (this is a known behavior/limitation).
    • Sibling Manipulation:
      • If you add or remove previous siblings of node (or next siblings in reverse mode), you must return a new Index to specify which sibling to traverse after node is processed.
      • If you add or remove next siblings of node (or previous siblings in reverse mode), the traversal handles this automatically without needing a returned Index.
    • Parent Manipulation: Removing the children property of a parent does not prevent the children from being traversed.
  2. Install unist-util-visit

    main

    This package is ESM only.

    In Node.js (version 16+), install via npm:

    npm install unist-util-visit

    In Deno, use esm.sh:

    import {CONTINUE, EXIT, SKIP, visit} from 'https://esm.sh/unist-util-visit@5'

    In browsers, use esm.sh with the bundle flag:

    <script type="module">
      import {CONTINUE, EXIT, SKIP, visit} from 'https://esm.sh/unist-util-visit@5?bundle'
    </script>
    npm install unist-util-visit
  3. Walk a unist tree with visit()

    main

    Use the visit function to traverse a unist tree. You can provide a test (like a node type string) to filter which nodes the visitor function is called for.

    If you need access to the entire stack of parents during traversal, use unist-util-visit-parents instead.

    import {fromMarkdown} from 'mdast-util-from-markdown'
    import {visit} from 'unist-util-visit'
    
    const tree = fromMarkdown('Some *emphasis*, **strong**, and `code`.')
    
    visit(tree, 'text', function (node, index, parent) {
      console.log([node.value, parent ? parent.type : index])
    })
  4. Use visit(tree[, test], visitor[, reverse]) to traverse trees

    main

    The visit function traverses a unist tree.

    Parameters:

    • tree: The unist tree to traverse.
    • test (optional): A unist-util-is compatible test to filter nodes.
    • visitor: A function called for each matching node.
    • reverse (optional): Boolean to traverse the tree in reverse order.

    Visitor Signature: function (node, index, parent)

    • node: The found node.
    • index: The index of the node in its parent (or undefined).
    • parent: The parent of the node (or undefined).

    Visitor Return Values (Actions): The visitor can return an Action or an Index to control traversal:

    • CONTINUE: Continue traversing as normal (default behavior, returns true).
    • EXIT: Stop traversing the tree immediately (returns false).
    • SKIP: Do not traverse this node's children (returns 'skip').
    • Index: Returning an Index (a number) allows you to specify which sibling to traverse next. This is primarily used when adding or removing siblings. An Index is treated as a tuple of [CONTINUE, Index].
    // Example of the visit signature concept
    visit(tree, 'type', (node, index, parent) => {
      // logic
      return SKIP; // or CONTINUE, EXIT, or a new index
    })
  5. Control traversal with CONTINUE, EXIT, and SKIP

    main

    When writing a Visitor function for visit(), you can return specific constants to control the traversal flow:

    • CONTINUE: The default behavior. Continue traversing the tree normally.
    • EXIT: Immediately stop all traversal.
    • SKIP: Stop traversing the children of the current node, but continue with the rest of the tree.
    import {CONTINUE, EXIT, SKIP} from 'unist-util-visit'
  6. The Visitor callback signature

    main

    A Visitor is a function called for each node that matches the provided test.

    (node, index, parent) => VisitorResult

    Parameters

    • node: The current node being visited.
    • index: The index of the node within its parent. This is undefined if the node has no parent (e.g., the root node).
    • parent: The parent of the current node. This is undefined if the node has no parent.

    Return Value

    The visitor returns a VisitorResult, which determines the next step in the traversal (e.g., CONTINUE, EXIT, SKIP, or a new index).

  7. Use visit() to traverse a tree

    main

    The visit() function performs a depth-first tree traversal in preorder (NLR) by default, or reverse preorder (NRL) if the reverse option is provided. You can use it to find and process specific nodes in a unist tree.

    Usage Patterns

    1. With a test and a visitor: Pass a test (compatible with unist-util-is) to filter which nodes the visitor is called for. This is the most efficient way to target specific node types.
    2. Without a test: If you omit the test argument, the second argument is treated as the visitor function, and it will be called for every node in the tree.

    Performance Tip

    Walking a tree is intensive. Instead of walking the tree multiple times with different tests, walk it once and use unist-util-is inside your visitor to perform different operations based on the node type.

    import { visit } from 'unist-util-visit'
    
    // Example: Visit all 'paragraph' nodes
    visit(tree, 'paragraph', (node, index, parent) => {
      // Do something with the paragraph node
    })