All files / src toc.ts

21.31% Statements 13/61
20% Branches 8/40
25% Functions 1/4
21.67% Lines 13/60

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 1421x                                                                                                                                           1x       1x 1x       1x 1x 1x 1x 1x   1x       1x       1x 1x                                                                                              
import HeadingIdGenerator from "./heading-id-generator";
 
function nPrefix(str, n) {
  let output = "";
  for (let i = 0; i < n; i++) {
    output += str;
  }
  return output;
}
 
/**
 *  eg:
 * Haha [A](www.a.com) xxx [B](www.b.com)
 *  should become
 * Haha A xxx B
 *
 * check issue #41
 */
 
function sanitizeContent(content) {
  let output = "";
  let offset = 0;
 
  // test ![...](...)
  // test [...](...)
  // <a name="myAnchor"></a>Anchor Header
  // test [^footnote]
  const r = /\!?\[([^\]]*)\]\(([^)]*)\)|<([^>]*)>([^<]*)<\/([^>]*)>|\[\^([^\]]*)\]/g;
  let match = null;
  // tslint:disable-next-line:no-conditional-assignment
  while ((match = r.exec(content))) {
    output += content.slice(offset, match.index);
    offset = match.index + match[0].length;
 
    if (match[0][0] === "<") {
      output += match[4];
    } else if (match[0][0] === "[" && match[0][1] === "^") {
      //  # footnote
      output += "";
    } else if (match[0][0] !== "!") {
      output += match[1]; // image
    } else {
      output += match[0];
    }
  }
 
  output += content.slice(offset, content.length);
  return output;
}
 
/**
 *  ordered: boolean
 *  depthFrom: number, default 1
 *  depthTo: number, default 6
 *  tab: string, default `  `
 */
export interface TocOption {
  ordered: boolean;
  depthFrom: number;
  depthTo: number;
  tab: string;
  ignoreLink?: boolean;
}
 
/**
 *
 * @param opt:TocOption =
 * @param tokens = [{content:string, level:number, id:optional|string }]
 * @return {content, array}
 */
export function toc(
  tokens: { content: string; level: number; id?: string }[],
  opt: TocOption,
) {
  const headingIdGenerator = new HeadingIdGenerator();
  Iif (!tokens) {
    return { content: "", array: [] };
  }
 
  const ordered = opt.ordered;
  const depthFrom = opt.depthFrom || 1;
  const depthTo = opt.depthTo || 6;
  let tab = opt.tab || "  ";
  const ignoreLink = opt.ignoreLink || false;
 
  Iif (ordered) {
    tab = "    ";
  }
 
  tokens = tokens.filter((token) => {
    return token.level >= depthFrom && token.level <= depthTo;
  });
 
  Eif (!tokens.length) {
    return { content: "", array: [] };
  }
 
  const outputArr = [];
  let smallestLevel = tokens[0].level;
 
  // get smallestLevel
  for (const token of tokens) {
    if (token.level < smallestLevel) {
      smallestLevel = token.level;
    }
  }
 
  let orderedListNums = [];
  for (const token of tokens) {
    const content = token.content.trim();
    const level = token.level;
    const slug = token.id || headingIdGenerator.generateId(content);
    const n = level - smallestLevel;
    let numStr = "1";
    if (ordered) {
      // number for ordered list
      if (n >= orderedListNums.length) {
        orderedListNums.push(1);
      } else if (n === orderedListNums.length - 1) {
        orderedListNums[orderedListNums.length - 1]++;
      } else {
        orderedListNums = orderedListNums.slice(0, n + 1);
        if (orderedListNums.length) {
          orderedListNums[orderedListNums.length - 1]++;
        }
      }
      numStr = orderedListNums[orderedListNums.length - 1];
    }
    const listItem = `${nPrefix(tab, n)}${ordered ? `${numStr}.` : "-"} ${
      ignoreLink
        ? sanitizeContent(content)
        : `[${sanitizeContent(content)}](#${slug})`
    }`;
    outputArr.push(listItem);
  }
 
  return {
    content: outputArr.join("\n"),
    array: outputArr,
  };
}