1.1.0 • Published 1 year ago

markdoc-traverse v1.1.0

Weekly downloads
-
License
ISC
Repository
github
Last release
1 year ago

A simple, tiny traversal library for Markdoc's AST

Installation

npm install markdoc-traverse

or

yarn add markdoc-traverse

or

pnpm add markdoc-traverse

Usage

Enter / Exit

Visit all nodes by passing an enter function.

Exit from the document node by passing a exit function. Useful for performing operations at the end of traversal

import { traverse } from "markdoc-traverse";
const ast = MarkDoc.parse(`
 Document
 ## Heading
 This is a level 1 heading
`);

traverse(ast, {
  enter(node) {
    // Visits all the nodes in the AST
  },
  exit(node) {
    // Exit after all nodes have been visited in document
  },
});

Nodes

Visit markdoc's nodes by passing any node as visitor

import { traverse } from "markdoc-traverse";

const ast = MarkDoc.parse(`
 Document
 ## Heading
 This is a level 1 heading
`);

traverse(ast, {
  heading: (node) => {
    // Your traversal logic
  },
  document: (node) => {
    // Your traversal logic
  },
});

Visitors are type safe , any makdoc nodes can be passed as a visitor with also option to enter and exit a node

import { traverse } from "markdoc-traverse";

const ast = MarkDoc.parse(`
 Document
 ## Heading
 This is a level 1 heading
`);

traverse(ast, {
  heading: {
    enter(node) {
      // Enter all heading nodes
    },
    exit(node) {
      // Exit at the end of each heading node
    },
  },
});

Tags

Visit custom tags configured by your config

traverse takes a third arugments which is the record of custom tags you would like to visit

import { traverse } from 'markdoc-traverse';

const ast = MarkDoc.parse(`
 {% callout %}
   `content`
 {% /callout %}
`)

const config = {
  tags: {
    callout
  }
};

traverse(ast,{
    callout:(node)=>{
       // Visit tags
    }
},{
  ...config.tags
})

tags are spread from your markdoc config

tags are type safe