BaseNode

Reference

BaseClass to use when creating nodes

Nodes are a representation of a group of tokens and/or other nodes.

Tip: When defining Nodes is highly recommended have well defined start and an end patterns, this is to avoid problems and be more easy to implement your processor

Extending

The recommendation way to use this class is create your own Base class and then extend the others using this class.

Check the markdown language example:

// language-kit/packages/markdown/src/MarkdownNode.ts
...
export class MarkdownNode extends BaseNode {
    public type: string = MarkdownNodeType.Unknown

    public toHtml() {
        return ''
    }
}

The interesting thing is that it have an toHtml().

This method return nothing by default

But the child classes can overwrite this method to output the correct html tags.

With this we have an standard of how to parse the nodes to html.

Check NodeArray extends see more.

Methods

setPositions()

Update node & tokens start & end positions

const node = new MyNode()

node.setPositions()

If the language have children nodes you can overwrite this methods to also set the children nodes like the exemplo bellow.

export class MarkdownNodeTextBold extends MarkdownNode {
    ...
    public setPositions(offset?: number): this {
        super.setPositions(offset)

        // +2 for open ** or __
        this.children.setPositions(this.start + 2)

        return this
    }
    ...
}

toText

Convert the array of nodes into text using BaseNode.toText()

const nodes = parser.toNodes('Hello')

nodes.toText() // Hello word

Examples

Markdown
## Heading
Node class
  // language-kit/packages/markdown/src/MarkdownNodeHeading.ts
 import { MarkdownNode, MarkdownNodeType } from './MarkdownNode'

  export class MarkdownNodeHeading extends MarkdownNode {
      public readonly type = MarkdownNodeType.Heading
      public level = 1
      public body = ''

      public toHtml() {
          const tag = this.level > 6 ? 'h6' : `h${this.level}`

          return `<${tag}>${this.body}</${tag}>`
      }
  }
JSON
 {
      start: 0,
      end: 9,
      type: 'heading',
      tokens: [
          { type: 'Symbol', value: '#', start: 0, end: 0 },
          { type: 'Symbol', value: '#', start: 1, end: 1 },
          { type: 'WhiteSpace', value: ' ', start: 2, end: 2 },
          { type: 'Word', value: 'Heading', start: 3, end: 9 },
      ]
},
HTML
 <h2>Heading</h2>