Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

toc sidebar for navigating through long note #2714

Open
andrewchenshx opened this issue May 7, 2024 · 1 comment
Open

toc sidebar for navigating through long note #2714

andrewchenshx opened this issue May 7, 2024 · 1 comment

Comments

@andrewchenshx
Copy link

walks through all heading elements within the note and generates a filterable table of contents containing anchor links in a collapsible, full-height side panel.

@mauritskorse
Copy link

I havent tested it, but I guess something like this could work.
You should add a <div id="toc"></div> next to the div that holds the editorJs instance and style it accordingly

const EditorInstance = new EditorJS({
  //... config
  tools: {
    //...
  },
  onChange: (api, event) => {
      EditorInstance.save()
        .then( async(data) => {
           const headers = getHeaders(data.blocks);
           let toc = buildToc(headers);
           document.getElementById('toc').appendChild(toc);
        })
  }
})

function getHeaders(blocks){
  return blocks
    .filter(block => block.type === 'header')
    .map(({ data: { text, level } }) => ({ text, level }));
}

function buildToc(toc) {
    let root = document.createElement('ul');
    let stack = [root];

    toc.forEach(({ text, level }) => {
        let li = document.createElement('li');
        li.textContent = text;

        while (level < stack.length) {
            stack.pop();
        }

        if (level > stack.length) {
            let ul = document.createElement('ul');
            stack[stack.length - 1].lastChild.appendChild(ul);
            stack.push(ul);
        }

        stack[stack.length - 1].appendChild(li);
    });

    return root;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants