Skip to content

Commit

Permalink
feat: add ids on heading (#423)
Browse files Browse the repository at this point in the history
Co-authored-by: yoko <[email protected]>
  • Loading branch information
Sembauke and sidemt authored Feb 10, 2024
1 parent 795992f commit 977ab27
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import BaseHeading from "@tiptap/extension-heading";
import slugify from "slugify";

export const Heading = BaseHeading.configure({
levels: [1, 2, 3, 4, 5, 6],
}).extend({
addAttributes() {
return {
...this.parent?.(),
id: {
default: null,
parseHTML: (element) => ({
id: slugify(element.textContent, {
lower: true,
}),
}),
renderHTML: (attributes) => ({
id: attributes.id,
}),
},
};
},

onSelectionUpdate({ editor }) {
const { $from } = editor.state.selection;

// This line gets the node at the depth of
// the start of the selection. If the selection
// starts in a heading, this will be the heading node.

const node = $from.node($from.depth);

if (node.type.name === "heading") {
editor.commands.updateAttributes("heading", {
id: slugify(node.textContent, {
lower: true,
}),
});
}
},

renderHTML({ node }) {
return [
"h" + node.attrs.level,
{
id: slugify(node.textContent, {
lower: true,
}),
},
0,
];
},
});
3 changes: 3 additions & 0 deletions apps/frontend/src/lib/editor-config.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import CharacterCount from "@tiptap/extension-character-count";
import Image from "@tiptap/extension-image";
import Placeholder from "@tiptap/extension-placeholder";
import Link from "@tiptap/extension-link";
import { Heading } from "@/components/tip-tap-extensions/heading-extension";

export const extensions = [
StarterKit.configure({
Expand All @@ -18,6 +19,7 @@ export const extensions = [
keepMarks: true,
keepAttributes: false,
},
heading: false,
codeBlock: false,
}),
Placeholder.configure({
Expand Down Expand Up @@ -47,4 +49,5 @@ export const extensions = [
lowlight,
}),
CharacterCount.configure({}),
Heading,
];

0 comments on commit 977ab27

Please sign in to comment.