mirror of
https://github.com/reonokiy/blog.nokiy.net.git
synced 2025-06-16 03:32:51 +02:00
fix: prevent HTML tags from being escaped in article descriptions
This commit is contained in:
parent
08438bd71a
commit
cb9a212cc7
2 changed files with 13 additions and 10 deletions
1
.vscode/settings.json
vendored
1
.vscode/settings.json
vendored
|
@ -62,6 +62,7 @@
|
||||||
"abbrlink",
|
"abbrlink",
|
||||||
"antfu",
|
"antfu",
|
||||||
"apiflash",
|
"apiflash",
|
||||||
|
"apos",
|
||||||
"Artículos",
|
"Artículos",
|
||||||
"astrodotbuild",
|
"astrodotbuild",
|
||||||
"astrojs",
|
"astrojs",
|
||||||
|
|
|
@ -1,12 +1,12 @@
|
||||||
import type { CollectionEntry } from 'astro:content'
|
import type { CollectionEntry } from 'astro:content'
|
||||||
import { defaultLocale } from '@/config'
|
import { defaultLocale } from '@/config'
|
||||||
import MarkdownIt from 'markdown-it'
|
import MarkdownIt from 'markdown-it'
|
||||||
import sanitizeHtml from 'sanitize-html'
|
|
||||||
|
|
||||||
const parser = new MarkdownIt()
|
|
||||||
|
|
||||||
type ExcerptScene = 'list' | 'meta' | 'og' | 'rss'
|
type ExcerptScene = 'list' | 'meta' | 'og' | 'rss'
|
||||||
|
|
||||||
|
const parser = new MarkdownIt()
|
||||||
|
const isCJKLang = (lang: string) => ['zh', 'zh-tw', 'ja'].includes(lang)
|
||||||
|
|
||||||
// Excerpt length in different scenarios
|
// Excerpt length in different scenarios
|
||||||
const EXCERPT_LENGTHS: Record<ExcerptScene, {
|
const EXCERPT_LENGTHS: Record<ExcerptScene, {
|
||||||
cjk: number
|
cjk: number
|
||||||
|
@ -30,8 +30,6 @@ const EXCERPT_LENGTHS: Record<ExcerptScene, {
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
const isCJKLang = (lang: string) => ['zh', 'zh-tw', 'ja'].includes(lang)
|
|
||||||
|
|
||||||
// Generate an excerpt from Markdown content
|
// Generate an excerpt from Markdown content
|
||||||
export function generateExcerpt(
|
export function generateExcerpt(
|
||||||
content: string,
|
content: string,
|
||||||
|
@ -45,11 +43,15 @@ export function generateExcerpt(
|
||||||
? EXCERPT_LENGTHS[scene].cjk
|
? EXCERPT_LENGTHS[scene].cjk
|
||||||
: EXCERPT_LENGTHS[scene].other
|
: EXCERPT_LENGTHS[scene].other
|
||||||
|
|
||||||
// Convert Markdown to plain text
|
// Remove all HTML tags and decode HTML entities
|
||||||
const plainText = sanitizeHtml(parser.render(content), {
|
const plainText = parser.render(content)
|
||||||
allowedTags: [],
|
.replace(/<[^>]*>/g, '')
|
||||||
allowedAttributes: {},
|
.replace(/</g, '<')
|
||||||
})
|
.replace(/>/g, '>')
|
||||||
|
.replace(/&/g, '&')
|
||||||
|
.replace(/"/g, '"')
|
||||||
|
.replace(/'/g, '\'')
|
||||||
|
.replace(/ /g, ' ')
|
||||||
|
|
||||||
// Replace line breaks with spaces
|
// Replace line breaks with spaces
|
||||||
const normalizedText = plainText.replace(/\s+/g, ' ')
|
const normalizedText = plainText.replace(/\s+/g, ' ')
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue