add anchors to table of contents (wip)

This commit is contained in:
Hans Pagel 2021-03-11 00:47:58 +01:00
parent 746d22a05a
commit 87059c9b46
3 changed files with 49 additions and 8 deletions

View File

@ -7,7 +7,9 @@
v-for="(heading, index) in headings"
:key="index"
>
{{ heading.text }}
<a :href="`#${heading.id}`">
{{ heading.text }}
</a>
</li>
</ul>
</node-view-wrapper>
@ -38,17 +40,41 @@ export default {
handleUpdate() {
const headings = []
this.editor.state.doc.descendants(node => {
this.editor.state.doc.descendants((node, pos) => {
if (node.type.name === 'heading') {
const id = `heading-${headings.length + 1}`
if (node.attrs.id !== id) {
this.updateNodeAttributes(node, pos, {
id,
})
}
headings.push({
level: node.attrs.level,
text: node.textContent,
id,
})
}
})
this.headings = headings
},
updateNodeAttributes(node, pos, attributes) {
const { state } = this.editor.view
const transaction = state.tr.setNodeMarkup(pos, undefined, {
...node.attrs,
...attributes,
})
console.log(pos, undefined, {
...node.attrs,
...attributes,
})
// TODO: Why is that not needed? 🤔
this.editor.view.dispatch(transaction)
},
},
mounted() {
@ -58,10 +84,6 @@ export default {
}
</script>
<style>
</style>
<style lang="scss">
/* Basic editor styles */
.ProseMirror {
@ -84,7 +106,7 @@ export default {
&::before {
display: block;
content: "In this document";
content: "Table of Contents";
font-weight: 700;
letter-spacing: 0.025rem;
font-size: 0.75rem;
@ -94,6 +116,10 @@ export default {
}
&__item {
a:hover {
opacity: 0.5;
}
&--3 {
padding-left: 1rem;
}

View File

@ -24,4 +24,19 @@ export default Node.create({
addNodeView() {
return VueNodeViewRenderer(Component)
},
addGlobalAttributes() {
return [
{
types: [
'heading',
],
attributes: {
id: {
default: null,
},
},
},
]
},
})

View File

@ -27,7 +27,6 @@ export default {
TableOfContents,
],
content: `
<toc></toc>
<h2>1 heading</h2>
<p>paragraph</p>
<h3>1.1 heading</h3>
@ -38,6 +37,7 @@ export default {
<p>paragraph</p>
<h3>2.1 heading</h3>
<p>paragraph</p>
<toc></toc>
`,
})
},