feat: i18n rss url and different excerpt length for different languages

This commit is contained in:
radishzzz 2025-03-17 02:49:02 +00:00
parent e4c61bf21b
commit f34b0cb46b
6 changed files with 62 additions and 13 deletions

View file

@ -1,14 +1,46 @@
import type { CollectionEntry } from 'astro:content'
import { defaultLocale } from '@/config'
import MarkdownIt from 'markdown-it'
import sanitizeHtml from 'sanitize-html'
const parser = new MarkdownIt()
type ExcerptScene = 'list' | 'meta' | 'og'
// Excerpt length in different scenarios
const EXCERPT_LENGTHS: Record<ExcerptScene, {
cjk: number
other: number
}> = {
list: {
cjk: 120,
other: 240,
},
meta: {
cjk: 120,
other: 240,
},
og: {
cjk: 75,
other: 150,
},
}
const isCJKLang = (lang: string) => ['zh', 'zh-tw', 'ja'].includes(lang)
// Generate an excerpt from Markdown content
export function generateExcerpt(content: string, length: number = 98): string {
export function generateExcerpt(
content: string,
scene: ExcerptScene,
lang: string,
): string {
if (!content)
return ''
const length = isCJKLang(lang)
? EXCERPT_LENGTHS[scene].cjk
: EXCERPT_LENGTHS[scene].other
// Convert Markdown to plain text
const plainText = sanitizeHtml(parser.render(content), {
allowedTags: [],
@ -23,11 +55,14 @@ export function generateExcerpt(content: string, length: number = 98): string {
}
// Automatically generate a description for the article
export function generateDescription(post: CollectionEntry<'posts'>): string {
export function generateDescription(
post: CollectionEntry<'posts'>,
scene: ExcerptScene,
): 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)
const lang = post.data.lang ?? defaultLocale
return generateExcerpt(post.body, scene, lang)
}