mirror of
https://github.com/reonokiy/blog.nokiy.net.git
synced 2025-06-16 03:32:51 +02:00
feat: automatically generate meta descriptions for articles
This commit is contained in:
parent
78de8b7911
commit
79f9765688
3 changed files with 51 additions and 10 deletions
34
src/utils/description.ts
Normal file
34
src/utils/description.ts
Normal file
|
@ -0,0 +1,34 @@
|
|||
import type { CollectionEntry } from 'astro:content'
|
||||
import MarkdownIt from 'markdown-it'
|
||||
import sanitizeHtml from 'sanitize-html'
|
||||
|
||||
const parser = new MarkdownIt()
|
||||
|
||||
// Generate an excerpt from Markdown content
|
||||
export function generateExcerpt(content: string, length: number = 100): string {
|
||||
if (!content)
|
||||
return ''
|
||||
|
||||
// Convert Markdown to plain text
|
||||
const plainText = sanitizeHtml(parser.render(content), {
|
||||
allowedTags: [],
|
||||
allowedAttributes: {},
|
||||
})
|
||||
|
||||
// Replace line breaks with spaces
|
||||
const normalizedText = plainText.replace(/\s+/g, ' ')
|
||||
const excerpt = normalizedText.slice(0, length).trim()
|
||||
// Add ellipsis if text was truncated
|
||||
const needsEllipsis = normalizedText.length > length
|
||||
return needsEllipsis ? `${excerpt}...` : excerpt
|
||||
}
|
||||
|
||||
// Automatically generate a description for the article
|
||||
export function generateDescription(post: CollectionEntry<'posts'>): string {
|
||||
// If the article already has a description, return it directly
|
||||
if (post.data.description)
|
||||
return post.data.description
|
||||
|
||||
// Otherwise, generate an excerpt from the article content as the description
|
||||
return generateExcerpt(post.body)
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue