chore(v2): Define type for markdown right table of contents (#3306)

This commit is contained in:
Sam Zhou 2020-08-20 11:57:19 -04:00 committed by GitHub
parent fb49a7fc89
commit b38f562322
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
7 changed files with 57 additions and 3 deletions

View file

@ -5,11 +5,29 @@
* LICENSE file in the root directory of this source tree.
*/
// @ts-check
const toString = require('mdast-util-to-string');
const visit = require('unist-util-visit');
const escapeHtml = require('escape-html');
/** @typedef {import('@docusaurus/types').MarkdownRightTableOfContents} TOC */
/** @typedef {import('unist').Node} Node */
/**
* @typedef {Object} StringValuedNode
* @property {string} type
* @property {string} value
* @property {number} depth
* @property {Object} data
* @property {StringValuedNode[]} children
*/
// https://github.com/syntax-tree/mdast#heading
/**
* @param {StringValuedNode | undefined} node
* @returns {string}
*/
function toValue(node) {
if (node && node.type) {
switch (node.type) {
@ -34,11 +52,22 @@ function toValue(node) {
// Visit all headings. We `slug` all headings (to account for
// duplicates), but only take h2 and h3 headings.
/**
* @param {StringValuedNode} node
* @returns {TOC[]}
*/
function search(node) {
/** @type {TOC[]} */
const headings = [];
let current = -1;
let currentDepth = 0;
/**
* @param {StringValuedNode} child
* @param {number} index
* @param {Node | undefined} parent
* @returns {void}
*/
const onHeading = (child, index, parent) => {
const value = toString(child);