mirror of
https://github.com/reonokiy/blog.nokiy.net.git
synced 2025-06-16 11:41:17 +02:00
feat: i18n rss url and different excerpt length for different languages
This commit is contained in:
parent
e4c61bf21b
commit
f34b0cb46b
6 changed files with 62 additions and 13 deletions
|
@ -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)
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue