Assign ID to headers with CustomHTMLRenderer (#84)
authorPietro Bonaldo Gregori <redacted>
Sun, 2 Jul 2023 13:24:03 +0000 (13:24 +0000)
committerGitHub <redacted>
Sun, 2 Jul 2023 13:24:03 +0000 (14:24 +0100)
flatnotes/src/components/NoteViewerEditor.vue

index b1a42e47d06992c07e9b4aad5c0960cdd3c2e777..f3225d714b71638d2be524ce05f2038556670a97 100644 (file)
@@ -178,6 +178,27 @@ import { Viewer } from "@toast-ui/vue-editor";
 import api from "../api";
 import codeSyntaxHighlight from "@toast-ui/editor-plugin-code-syntax-highlight/dist/toastui-editor-plugin-code-syntax-highlight-all.js";
 
+const customHTMLRenderer = {
+  heading( node, { entering, getChildrenText } ) {
+    const tagName = `h${node.level}`;
+
+    if (entering) {
+      return {
+        type: 'openTag',
+        tagName,
+        attributes: {
+          id: getChildrenText(node)
+             .toLowerCase()
+              .replace(/[^a-z0-9-\s]*/g, '')
+              .trim()
+              .replace(/\s/g, '-')
+        }
+      };
+    }
+    return { type: 'closeTag', tagName };
+  }
+};
+
 export default {
   components: {
     Viewer,
@@ -190,6 +211,7 @@ export default {
   },
 
   data: function () {
+
     return {
       editMode: false,
       draftSaveTimeout: null,
@@ -200,10 +222,13 @@ export default {
       noteLoadFailedIcon: null,
       noteLoadFailedMessage: "Failed to load Note",
       viewerOptions: {
+       customHTMLRenderer: customHTMLRenderer,
         plugins: [codeSyntaxHighlight],
         extendedAutolinks: true,
       },
-      editorOptions: { plugins: [codeSyntaxHighlight] },
+      editorOptions: {
+        customHTMLRenderer: customHTMLRenderer,
+        plugins: [codeSyntaxHighlight] },
     };
   },
 
git clone https://git.99rst.org/PROJECT