From 1f93499ecef7ab5e1d137448f199402fd9bc9949 Mon Sep 17 00:00:00 2001 From: saicaca Date: Sat, 3 Aug 2024 16:03:03 +0800 Subject: [PATCH] feat: use the first paragraph as the excerpt if `description` is not set --- astro.config.mjs | 3 ++- src/components/PostCard.astro | 4 ++-- src/plugins/remark-excerpt.js | 16 ++++++++++++++++ 3 files changed, 20 insertions(+), 3 deletions(-) create mode 100644 src/plugins/remark-excerpt.js diff --git a/astro.config.mjs b/astro.config.mjs index b732012..877ca42 100644 --- a/astro.config.mjs +++ b/astro.config.mjs @@ -17,6 +17,7 @@ import { AdmonitionComponent } from "./src/plugins/rehype-component-admonition.m import { GithubCardComponent } from "./src/plugins/rehype-component-github-card.mjs" import {parseDirectiveNode} from "./src/plugins/remark-directive-rehype.js"; import { remarkReadingTime } from "./src/plugins/remark-reading-time.mjs" +import {remarkExcerpt} from "./src/plugins/remark-excerpt.js"; const oklchToHex = (str) => { const DEFAULT_HUE = 250 @@ -68,7 +69,7 @@ export default defineConfig({ }), ], markdown: { - remarkPlugins: [remarkMath, remarkReadingTime, remarkGithubAdmonitionsToDirectives, remarkDirective, parseDirectiveNode], + remarkPlugins: [remarkMath, remarkReadingTime, remarkExcerpt, remarkGithubAdmonitionsToDirectives, remarkDirective, parseDirectiveNode], rehypePlugins: [ rehypeKatex, rehypeSlug, diff --git a/src/components/PostCard.astro b/src/components/PostCard.astro index 14002a7..1c7e37b 100644 --- a/src/components/PostCard.astro +++ b/src/components/PostCard.astro @@ -48,8 +48,8 @@ const { remarkPluginFrontmatter } = await entry.render(); -
- { description } +
+ { description || remarkPluginFrontmatter.excerpt }
diff --git a/src/plugins/remark-excerpt.js b/src/plugins/remark-excerpt.js new file mode 100644 index 0000000..3fc8315 --- /dev/null +++ b/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 + }; +} \ No newline at end of file