Getting Started

Installation

npm i docnode

1. Define your nodes

// nodes.ts
import { defineNode, number, string, boolean } from "docnode";

const TextNode = defineNode({
  type: "text",
  state: {
    text: string(""),
    bold: boolean(false),
    italic: boolean(false),
    underline: boolean(false),
  },
});

const ParagraphNode = defineNode({
  type: "paragraph",
  state: {
    indent: number(0),
  },
});

const HeadingNode = defineNode({
  type: "heading",
  state: {
    indent: number(0),
    level: number(1),
  },
});

2. Define your extensions

// extensions.ts
import type { Extension } from "docnode";
import { ParagraphNode, HeadingNode } from "./nodes";

const RichTextBaseExtension: Extension = {
  nodes: [ParagraphNode, HeadingNode],
  // Let's suppose that you want to ensure that your
  // document always starts with a heading node.
  register: (doc) => {
    doc.onNormalize(() => {
      if (!doc.root.first?.is(HeadingNode)) {
        doc.root.prepend(doc.createNode(HeadingNode));
      }
    });
  },
};

3. Create your document

import { Doc } from "docnode";
import { RichTextBaseExtension } from "./extensions";

const doc = new Doc({ extensions: [RichTextBaseExtension] });

4. Render you document

See the render documentation for more information.

5. Edit your document

// A handler event example:

function setTodoItemDone(todoItemNode: DocNode<typeof TodoItemNode>) {
  node.state.completed.set(true);
}

function duplicateTodoItem(todoItemNode: DocNode<typeof TodoItemNode>) {
  todoItemNode.copy(todoItemNode, "after");
}