feat(原生支持字数统计和阅读时长): 统一使用WordCount组件

(cherry picked from commit d8180e1a783ad50c501b741adc72f2747896bdc1)
This commit is contained in:
anime
2024-12-23 20:10:53 +08:00
parent 09c092aefe
commit ff89e16ee2
8 changed files with 91 additions and 230 deletions

27
lib/plugins/wordCount.js Normal file
View File

@@ -0,0 +1,27 @@
/**
* 更新字数统计和阅读时间
*/
export function countWords(pageContentText) {
const wordCount = fnGetCpmisWords(pageContentText)
// 阅读速度 300-500每分钟
const readTime = Math.floor(wordCount / 400) + 1
return { wordCount, readTime }
}
// 用word方式计算正文字数
function fnGetCpmisWords(str) {
if (!str) {
return 0
}
let sLen = 0
try {
// eslint-disable-next-line no-irregular-whitespace
str = str.replace(/(\r\n+|\s+| +)/g, '龘')
// eslint-disable-next-line no-control-regex
str = str.replace(/[\x00-\xff]/g, 'm')
str = str.replace(/m+/g, '*')
str = str.replace(/龘+/g, '')
sLen = str.length
} catch (e) {}
return sLen
}

View File

@@ -10,6 +10,7 @@ import { getPageContentText } from '@/pages/search/[keyword]'
import { getAiSummary } from '@/lib/plugins/aiSummary'
import BLOG from '@/blog.config'
import { uploadDataToAlgolia } from '@/lib/plugins/algolia'
import { countWords } from '@/lib/plugins/wordCount'
/**
* 获取文章的关联推荐文章列表,目前根据标签关联性筛选
@@ -115,7 +116,10 @@ export async function processPostData(props, from) {
key => props.post.blockMap.block[key]?.value?.parent_id === props.post.id
)
props.post.toc = getPageTableOfContents(props.post, props.post.blockMap)
const pageContentText = getPageContentText(props.post, props.post.blockMap)
const { wordCount, readTime } = countWords(pageContentText)
props.post.wordCount = wordCount
props.post.readTime = readTime
const aiSummaryAPI = siteConfig('AI_SUMMARY_API')
if (aiSummaryAPI) {
const post = props.post
@@ -131,7 +135,7 @@ export async function processPostData(props, from) {
for (let heading of post.toc) {
content += heading.text + ' '
}
content += getPageContentText(post, post.blockMap)
content += pageContentText
const combinedText = post.title + ' ' + content
const truncatedText = combinedText.slice(0, wordLimit)
aiSummary = await getAiSummary(