preview

An app state of the Markdown preview pane in Inkdrop. You can obtain the preview state and integrate it with React components.

It also stores abstract syntax trees of Markdown and HTML for additional processing by plugins.


Data Structure

  • Name
    dom
    Type
    React.ReactElement<unknown> | null
    Description

    A React DOM that was generated by the Markdown renderer.

  • Name
    mdast
    Type
    MdastRoot | null
    Description

    An mdast - Markdown Abstract Syntax Tree format that was generated by the Markdown processor from a currently editing note.

  • Name
    hast
    Type
    HastRoot | null
    Description

    An hast - Hypertext Abstract Syntax Tree format that was generated by the Markdown processor from a currently editing note.

  • Name
    lastError
    Type
    Error | null | undefined
    Description

    The last error that occurred while rendering a note.

To get the preview state manually:

const { preview } = inkdrop.store.getState()

Connect the state with your React component:

import { useSelector } from 'react-redux'
const selector = ({ preview }) => preview
const MyComponent = props => {
  const preview = useSelector(selector)
  // render
}

Extract YAML frontmatter values from mdast

The mdast property can contain YAML frontmatter values if the note has them. For example:

Get `title` from YAML frontmatter

import { useSelector } from 'react-redux'
const selector = ({ preview }) => {
  const { mdast } = preview
  if (mdast?.children[0]?.type === 'yaml') {
    const yamlNode = mdast.children[0]
    const { value: frontmatter } = yamlNode as any
    if (typeof frontmatter === 'object') {
      return (frontmatter.title || frontmatter.subject || '') as string
    }
  }
  return null
}
const MyComponent = props => {
  const title = useSelector(selector)
  // render
}

Extract particular types of nodes from mdast

It's easy to extract a particular type of nodes from the mdast data.

Extract heading nodes

import type { Root as MdastRoot, Heading } from 'mdast'
import { visit } from 'unist-util-visit'

function getHeadingNodes(mdast: MdastRoot): Heading[] {
  const headings: Heading[] = []

  visit(mdast, 'heading', (node: Heading) => {
    headings.push(node)
  })

  return headings
}

Another example:

Count number of tasks

import type { Root as MdastRoot, ListItem } from 'mdast'
import { visit } from 'unist-util-visit'

export type NumberOfTasks = {
  numOfTasks: number
  numOfCheckedTasks: number
}

function countNumberOfTasks(mdast: MdastRoot): NumberOfTasks {
  let numOfTasks = 0,
    numOfCheckedTasks = 0

  visit(mdast, 'listItem', (node: ListItem) => {
    if (typeof node.checked === 'boolean') {
      numOfTasks++
      node.checked && numOfCheckedTasks++
    }
  })

  return {
    numOfTasks,
    numOfCheckedTasks
  }
}
Can you help us improve the docs? 🙏

The source of these docs is here on GitHub. If you see a way these docs can be improved, please fork us!