Commit 95b81d0

HPCesia <me@hpcesia.com>
2025-02-06 14:57:27
feat: heading link
Using rehype-autolink-headings to show heading link behind its content.
1 parent 00dc1c9
src/styles/markdown.scss
@@ -7,11 +7,26 @@ article {
   h3,
   h4,
   h5 {
-    display: inline;
+    display: inline-block;
     width: 100%;
     margin: 1rem 0 0.5rem;
     scroll-margin-top: 4rem;
     font-weight: bold;
+    position: relative;
+
+    a {
+      padding: 0 0.5rem;
+      opacity: 0;
+      text-decoration: none;
+      color: theme('colors.primary');
+      transition: opacity 0.2s ease-in-out;
+    }
+
+    &:hover {
+      a {
+        opacity: 1;
+      }
+    }
   }
 
   // 各级标题特殊样式
astro.config.mjs
@@ -1,10 +1,12 @@
 // @ts-check
 import { remarkReadingTime } from './src/plugins/remark-reading-time.mjs';
+import { rehypeHeadingIds } from '@astrojs/markdown-remark';
 import sitemap from '@astrojs/sitemap';
 import tailwind from '@astrojs/tailwind';
 import icon from 'astro-icon';
 import pagefind from 'astro-pagefind';
 import { defineConfig } from 'astro/config';
+import rehypeAutolinkHeadings from 'rehype-autolink-headings';
 
 // https://astro.build/config
 export default defineConfig({
@@ -20,5 +22,21 @@ export default defineConfig({
   ],
   markdown: {
     remarkPlugins: [remarkReadingTime],
+    rehypePlugins: [
+      rehypeHeadingIds,
+      [
+        rehypeAutolinkHeadings,
+        {
+          behavior: 'append',
+          content: {
+            type: 'text',
+            value: '#',
+          },
+          properties: {
+            'aria-label': 'Anchor link',
+          },
+        },
+      ],
+    ],
   },
 });
package.json
@@ -13,6 +13,7 @@
     "pub": "node scripts/pub.mjs"
   },
   "dependencies": {
+    "@astrojs/markdown-remark": "^6.1.0",
     "@astrojs/rss": "^4.0.11",
     "@astrojs/sitemap": "^3.2.1",
     "@astrojs/tailwind": "^5.1.5",
@@ -27,6 +28,7 @@
     "mdast-util-to-string": "^4.0.0",
     "postcss-load-config": "^6.0.1",
     "reading-time": "^1.5.0",
+    "rehype-autolink-headings": "^7.1.0",
     "sass": "^1.84.0",
     "sharp": "^0.33.5",
     "tailwindcss": "^3.4.17",