All files / src/plugins/default markbind-plugin-tree.ts

96.92% Statements 63/65
70.83% Branches 17/24
100% Functions 15/15
96.77% Lines 60/62

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185                        2x   2x                           7x 7x 7x 7x                 6x     6x             4x                 6x 6x               6x                 7x 1x 1x 1x 1x 1x 1x   6x 6x   6x 5x 5x 1x 1x 2x   1x     6x 6x 6x 6x   1x                 6x     6x 2x   4x             4x 4x 2x 2x     4x   6x 4x                 2x 2x 2x               1x 1x   2x 2x         9x   2x 57x 56x   1x 1x 1x 1x   2x                      
/**
 * Creates tree-like visualisations.
 * Transforms the content in <tree> tags into corresponding textual representations
 * that are easier to visualise the relationships.
 * A common use case is folder structures visualisations.
 */
import _ from 'lodash';
import { MbNode } from '../../utils/node.js';
import { PluginContext } from '../Plugin.js';
 
import { markdownIt as md } from '../../lib/markdown-it/index.js';
 
const CSS_FILE_NAME = 'markbind-plugin-tree.css';
 
const TOKEN = {
  child: '├── ',
  lastChild: '└── ',
  connector: '│   ',
  space: '    ',
};
 
class TreeNode {
  content: string;
  parent: TreeNode | null;
  children: TreeNode[];
  level: number;
 
  constructor(content: string, parent: TreeNode | null, children: TreeNode[], level: number) {
    this.content = content;
    this.parent = parent;
    this.children = children;
    this.level = level;
  }
 
  /**
   * Returns true if this node is the last child of its parent.
   * A root node is considered to be the last child.
   * This is used to determine the correct connector to use.
   */
  isLastChild(): boolean {
    Iif (this.parent === null) {
      return true;
    }
    return this.parent.children[this.parent.children.length - 1] === this;
  }
 
  /**
   * Returns the token to append before the content.
   */
  getPositionalToken(): string {
    return this.isLastChild() ? TOKEN.lastChild : TOKEN.child;
  }
 
  /**
   * Determines the level of a line.
   * Every 2 spaces from the start of the line means 1 level.
   * The root node is level 0.
   */
  static levelize(line: string): number {
    const lineMatch = line.match(/^\s*/) ?? [''];
    return Math.floor(lineMatch[0].length / 2);
  }
 
  /**
   * Returns formatted TreeNode content.
   * Removes dashes (-), asterisks (*), or plus signs (+) at the beginning of the line
   */
  static getContent(raw: string): string {
    return raw.trim().replace(/^[-+*]\s/, '');
  }
 
  /**
   * Creates TreeNode objects from the raw text.
   * @param raw - The raw text to parse.
   * @return The dummy root node of the tree.
   */
  static parse(raw: string): TreeNode {
    const lines = raw.split('\n').filter(line => line.trim() !== '');
    const rootNode = new TreeNode('.', null, [], -1); // dummy root node
    const prevParentStack = [rootNode];
    let prevLevel = rootNode.level;
    let prevParent = rootNode;
    let prevNode = rootNode;
    lines
      .forEach((line) => {
        const level = TreeNode.levelize(line);
        const content = TreeNode.getContent(line);
 
        if (level > prevLevel) {
          prevParentStack.push(prevNode);
          prevParent = prevNode;
        } else if (level < prevLevel) {
          for (let i = 0; i < prevLevel - level; i += 1) {
            prevParentStack.pop();
          }
          prevParent = prevParentStack[prevParentStack.length - 1];
        }
 
        const newNode = new TreeNode(content, prevParent, [], level);
        prevParent.children.push(newNode);
        prevLevel = level;
        prevNode = newNode;
      });
    return rootNode;
  }
 
  /**
   * Traverses the tree and appends the tokens to the given array.
   * @param currNode - The node to traverse.
   * @param result - The array to append the tokens to.
   */
  static traverse(currNode: TreeNode, result: string[]) {
    Iif (!currNode.children) {
      return;
    }
    if (currNode.parent === null) {
      result.push(md.renderInline(`${currNode.content}\n`));
    } else {
      const tokens = [
        '\n',
        md.renderInline(currNode.content),
        currNode.getPositionalToken(),
      ];
 
      // computes the strings appended to the content of the TreeNode
      let curr: TreeNode | null = currNode.parent;
      while (curr && _.has(curr, 'parent.parent')) {
        tokens.push(curr.isLastChild() ? TOKEN.space : TOKEN.connector);
        curr = curr.parent;
      }
 
      result.push(tokens.reverse().join(''));
    }
    currNode.children.forEach((child: TreeNode) => {
      TreeNode.traverse(child, result);
    });
  }
 
  /**
   * Returns the TreeNode as a string.
   * This assumes that the node is a root node.
   */
  toString(): string {
    const treeTokens: string[] = [];
    TreeNode.traverse(this, treeTokens);
    return treeTokens.join('');
  }
 
  /**
   * Returns the rendered tree.
   * @param raw - The raw text to parse.
   */
  static visualize(raw: string): string {
    const dummyRootNode = TreeNode.parse(raw);
    return dummyRootNode.children
      .reduce((prev, curr) => {
        curr.parent = null;
        return prev + curr.toString();
      }, '');
  }
}
 
const getLinks = () => [`<link rel="stylesheet" href="${CSS_FILE_NAME}">`];
 
const processNode = (_pluginContext: PluginContext, node: MbNode) => {
  if (node.name !== 'tree') {
    return;
  }
  node.name = 'div';
  node.attribs.class = node.attribs.class ? `${node.attribs.class} tree` : 'tree';
  node.children = node.children ?? [];
  node.children[0].data = TreeNode.visualize(node.children[0].data);
};
const tagConfig = {
  tree: {
    isSpecial: true,
  },
};
 
export {
  tagConfig,
  getLinks,
  processNode,
};