/* ----

# Kico Style Docs
# By: Dreamer-Paul
# Last Update: 2022.12.25

---- */

const app = () => {
  ks.image("main img");

  var obj = {
    toggle: ks.select(".sidebar .header"),
    sidebar: ks.select(".sub-sidebar"),
  };

  if (obj.sidebar) {
    obj.toggle.onclick = () => {
      obj.sidebar.classList.toggle("active");
    };
  }

  const renderCodeBlock = () => {
    const demoBlocks = ks.selectAll(".demo-block");
    const codeBlocks = ks.selectAll(".code-block code");

    if (demoBlocks.length !== codeBlocks.length) {
      console.log(demoBlocks, codeBlocks);
      throw new Error("数量不匹配，请检查");
    }

    codeBlocks.forEach((block, index) => {
      const clearedRows = demoBlocks[index].innerHTML.split("\n").filter((row) => row.search(/\S+/) !== -1);

      if (!("fillContent" in block.dataset) || !clearedRows.length) {
        return;
      }

      const firstSpaceBlock = clearedRows[0].match(/\s+/);
      let firstSpaceBlockLength = 0;
      let clearedContents;

      if (firstSpaceBlock) {
        firstSpaceBlockLength = firstSpaceBlock[0].length;

        clearedContents = clearedRows.map((item) => item.substring(firstSpaceBlockLength)).join("\n");
      }
      else {
        clearedContents = demoBlocks[index].innerHTML;
      }

      block.innerHTML = clearedContents.replaceAll("<", "&lt;").replaceAll(">", "&gt;");
    });
  };

  renderCodeBlock();
};

app();
