Commit 2cc5107

HPCesia <me@hpcesia.com>
2025-02-07 10:07:59
feat: auto generate post description
1 parent 438b4f5
Changed files (3)
src/pages/posts/[article].astro
@@ -19,9 +19,11 @@ export async function getStaticPaths() {
 
 const { article } = Astro.props;
 const { Content, headings, remarkPluginFrontmatter } = await render(article);
+
+const description = article.data.description || remarkPluginFrontmatter.excerpt;
 ---
 
-<GridLayout title={article.data.title} description={article.data.description}>
+<GridLayout title={article.data.title} description={description}>
   <Fragment slot="header-content">
     <PostInfo
       title={article.data.title}
src/plugins/remark-excerpt.js
@@ -0,0 +1,16 @@
+import { toString } from 'mdast-util-to-string'
+
+/* Use the post's first paragraph as the excerpt */
+export function remarkExcerpt() {
+  return (tree, { data }) => {
+    let excerpt = ''
+    for (let node of tree.children) {
+      if (node.type !== 'paragraph') {
+        continue
+      }
+      excerpt = toString(node)
+      break
+    }
+    data.astro.frontmatter.excerpt = excerpt
+  }
+}
astro.config.mjs
@@ -1,6 +1,7 @@
 // @ts-check
 import { CDN } from './src/constants/cdn.mjs';
 import { rehypeWrapTables } from './src/plugins/rehype-wrap-tables.mjs';
+import { remarkExcerpt } from './src/plugins/remark-excerpt';
 import { remarkReadingTime } from './src/plugins/remark-reading-time.mjs';
 import { rehypeHeadingIds } from '@astrojs/markdown-remark';
 import sitemap from '@astrojs/sitemap';
@@ -36,6 +37,7 @@ export default defineConfig({
     remarkPlugins: [
       remarkMath,
       remarkReadingTime,
+      remarkExcerpt,
       // @ts-expect-error - types are not up to date
       [
         remarkGithubBlockQuote,