Skip to main content
Version: 1.x.x

@yozora/ast-util

Npm VersionNpm DownloadNpm LicenseModule formats: cjs, esmNode.js VersionCode Style: prettier

This package contains a collect of utility functions to handle Yozora markdown ast.

Install

npm install --save @yozora/ast-util

Usage

NameDescription
calcHeadingTocGenerate heading toc, and update the referenced Heading.identifier simultaneously
calcDefinitionMapTraverse yozora ast and generate a link reference definition map.
calcFootnoteDefinitionMapTraverse yozora ast and generate a footnote reference definition map.
collectDefinitionsCollect link reference definitions in a pre-order traversal.
collectFootnoteDefinitionsCollect footnote reference definitions in a pre-order traversal.
defaultUrlResolverDefault url resolver
replaceASTTraverse Yozora AST and perform a replacing operation for each matched node (irreversible)
replaceFootnotesInReferencesReplace inline footnotes into footnote references and footnote reference definitions (irreversible)
resolveUrlsForAstTraverse Yozora AST and resolve urls for aim nodes (irreversible)
searchNodeSearch a node from Yozora AST in pre-order traversing
shallowCloneAstShallow clone the Yozora AST until the match reaches the termination condition.
traverseASTTraverse Yozora AST and perform a mutating operation for each matched node

Example

import { ImageType, BlockquoteType } from '@yozora/ast'
import {
collectDefinitions,
collectFootnoteDefinitions,
calcHeadingToc,
replaceAST,
traverseAST,
} from '@yozora/ast-util'

// Collect definitions.
collectDefinitions(
root, // Yozora ast root
[DefinitionType], // aim Yast types, optional
[], // preset definitions, optional
)

// Collect footnote definitions.
collectFootnoteDefinitions(
root, // Yozora ast root
[FootnoteDefinitionType], // aim Yast types, optional
[], // preset footnote definitions, optional
true, // prefer reference type footnotes, optional.
)

// traverse the Yozora AST and set the image title to the image alt
traverseAST(
root, // Yozora ast root
[ImageType], // aim Yast types, required
(node) => node.title = node.alt // mutating operation, required
)

// traverse the Yozora AST and replace the image to two images.
replaceAST(
root,
[ImageType],
(node) => [node, node]
)

// Generate heading toc, each toc node's identifier will with the prefix 'custom-identifier-prefix-'.
// The default prefix is 'heading-'
calcHeadingToc(root, 'custom-identifier-prefix-')

// shallow clone the Yozora AST until a blockquote type node with a blockquote
// type parent and in addition it is not the first child of its parent encountered.
const root2 = shallowCloneAst(
root,
(node, parent, childIndex) => (
parent.type === BlockquoteType &&
childIndex > 0 &&
node.type === BlockquoteType
)
)