Merge branch 'docs/toc-with-anchors' into main

This commit is contained in:
Hans Pagel
2021-03-17 22:36:38 +01:00
2 changed files with 40 additions and 4 deletions

View File

@@ -7,7 +7,9 @@
v-for="(heading, index) in headings" v-for="(heading, index) in headings"
:key="index" :key="index"
> >
{{ heading.text }} <a :href="`#${heading.id}`">
{{ heading.text }}
</a>
</li> </li>
</ul> </ul>
</node-view-wrapper> </node-view-wrapper>
@@ -32,23 +34,38 @@ export default {
methods: { methods: {
handleUpdate() { handleUpdate() {
const headings = [] const headings = []
const transaction = this.editor.state.tr
this.editor.state.doc.descendants(node => { this.editor.state.doc.descendants((node, pos) => {
if (node.type.name === 'heading') { if (node.type.name === 'heading') {
const id = `heading-${headings.length + 1}`
if (node.attrs.id !== id) {
transaction.setNodeMarkup(pos, undefined, {
...node.attrs,
id,
})
}
headings.push({ headings.push({
level: node.attrs.level, level: node.attrs.level,
text: node.textContent, text: node.textContent,
id,
}) })
} }
}) })
transaction.setMeta('preventUpdate', true)
this.editor.view.dispatch(transaction)
this.headings = headings this.headings = headings
}, },
}, },
mounted() { mounted() {
this.editor.on('update', this.handleUpdate) this.editor.on('update', this.handleUpdate)
this.handleUpdate() this.$nextTick(this.handleUpdate)
}, },
} }
</script> </script>
@@ -75,7 +92,7 @@ export default {
&::before { &::before {
display: block; display: block;
content: "In this document"; content: "Table of Contents";
font-weight: 700; font-weight: 700;
letter-spacing: 0.025rem; letter-spacing: 0.025rem;
font-size: 0.75rem; font-size: 0.75rem;
@@ -85,6 +102,10 @@ export default {
} }
&__item { &__item {
a:hover {
opacity: 0.5;
}
&--3 { &--3 {
padding-left: 1rem; padding-left: 1rem;
} }

View File

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