feat: use the first paragraph as the excerpt if `description` is not set

This commit is contained in:
saicaca 2024-08-03 16:03:03 +08:00
parent 9af6cf956a
commit 1f93499ece
3 changed files with 20 additions and 3 deletions

View File

@ -17,6 +17,7 @@ import { AdmonitionComponent } from "./src/plugins/rehype-component-admonition.m
import { GithubCardComponent } from "./src/plugins/rehype-component-github-card.mjs" import { GithubCardComponent } from "./src/plugins/rehype-component-github-card.mjs"
import {parseDirectiveNode} from "./src/plugins/remark-directive-rehype.js"; import {parseDirectiveNode} from "./src/plugins/remark-directive-rehype.js";
import { remarkReadingTime } from "./src/plugins/remark-reading-time.mjs" import { remarkReadingTime } from "./src/plugins/remark-reading-time.mjs"
import {remarkExcerpt} from "./src/plugins/remark-excerpt.js";
const oklchToHex = (str) => { const oklchToHex = (str) => {
const DEFAULT_HUE = 250 const DEFAULT_HUE = 250
@ -68,7 +69,7 @@ export default defineConfig({
}), }),
], ],
markdown: { markdown: {
remarkPlugins: [remarkMath, remarkReadingTime, remarkGithubAdmonitionsToDirectives, remarkDirective, parseDirectiveNode], remarkPlugins: [remarkMath, remarkReadingTime, remarkExcerpt, remarkGithubAdmonitionsToDirectives, remarkDirective, parseDirectiveNode],
rehypePlugins: [ rehypePlugins: [
rehypeKatex, rehypeKatex,
rehypeSlug, rehypeSlug,

View File

@ -48,8 +48,8 @@ const { remarkPluginFrontmatter } = await entry.render();
<PostMetadata published={published} tags={tags} category={category} hideTagsForMobile={true} class="mb-4"></PostMetadata> <PostMetadata published={published} tags={tags} category={category} hideTagsForMobile={true} class="mb-4"></PostMetadata>
<!-- description --> <!-- description -->
<div class="transition text-75 mb-3.5 pr-4"> <div class:list={["transition text-75 mb-3.5 pr-4", {"line-clamp-2 md:line-clamp-1": !description}]}>
{ description } { description || remarkPluginFrontmatter.excerpt }
</div> </div>
<!-- word count and read time --> <!-- word count and read time -->

View File

@ -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
};
}