hhk7734 / wiki.loliot.net

14 stars 9 forks source link

목차 변경 방법 #2

Closed HHongSeungWoo closed 3 years ago

HHongSeungWoo commented 4 years ago

@docusaurus/mdx-loader/src/remark/rightToc/search.js

function search(node) {
  const headings = [];
  let current = -1;
  let current_c = -1;
  let currentDepth = 0;

  const onHeading = (child, index, parent) => {
    const value = toString(child);

    if (parent !== node || !value || child.depth > 3 || child.depth < 1) {
      return;
    }

    const entry = {
      value: toValue(child),
      id: child.data.id,
      children: [],
    };

    if (!headings.length || currentDepth >= child.depth) {
      headings.push(entry);
      current += 1;
      currentDepth = child.depth;
    } else {
      if (child.depth === 2) {
        headings[current].children.push(entry);
        current_c += 1;
      } else {
        headings[current].children[current_c].children.push(entry);
      }
    }
  };

  visit(node, 'heading', onHeading);

  return headings;
}
hhk7734 commented 4 years ago
function search(node) {
  const headings = [];
  const minDepth = 1;
  const maxDepth = 4;
  const current = Array(maxDepth - minDepth + 1).fill(-1);
  let previousDepth = 0;

  const onHeading = (child, index, parent) => {
    const value = toString(child);

    if (parent !== node || !value || child.depth > maxDepth || child.depth < minDepth) {
      return;
    }

    const entry = {
      value: toValue(child),
      id: child.data.id,
      children: [],
    };

    if (!headings.length || previousDepth >= child.depth) {
      previousDepth = child.depth;
      current.fill(-1, child.depth - minDepth + 1)
    }

    index = child.depth - minDepth;
    let table = headings;
    for(let i = 0; i < index; i++) {
      table = table[current[i]].children;
    }
    table.push(entry);
    current[index] += 1;
  };

  visit(node, 'heading', onHeading);

  return headings;
}

이렇게 적용함