From a53bb380ddb8f9e733a3f932dce5ded57da0e3bc Mon Sep 17 00:00:00 2001 From: DIYgod Date: Fri, 14 Jul 2023 18:06:31 +0100 Subject: [PATCH] feat: more accurate reading time --- src/components/home/HomeFeed.tsx | 27 ++++++++++++--------------- src/lib/expand-unit.ts | 5 +++-- src/lib/i18n/locales/zh/common.json | 1 - src/lib/reading-time.ts | 12 ++++++++++++ 4 files changed, 27 insertions(+), 18 deletions(-) create mode 100644 src/lib/reading-time.ts diff --git a/src/components/home/HomeFeed.tsx b/src/components/home/HomeFeed.tsx index 23d1f647..82022c1f 100644 --- a/src/components/home/HomeFeed.tsx +++ b/src/components/home/HomeFeed.tsx @@ -64,7 +64,7 @@ const PostCard = ({ cover={post.metadata?.content.cover} title={post.metadata?.content?.title} /> -
+
{comment && (
@@ -102,10 +102,10 @@ const PostCard = ({
)}
-
+
{!!post.metadata?.content?.tags?.[1] && ( { e.preventDefault() router.push(`/tag/${post.metadata?.content?.tags?.[1]}`) @@ -115,19 +115,16 @@ const PostCard = ({ {post.metadata?.content?.tags?.[1]} )} - {!post.stat?.viewDetailCount && ( - - - - {post.metadata?.content?.readingTime}{" "} - {t(post.metadata?.content?.readingTime === 1 ? "min" : "mins")} - + + + + {post.metadata?.content?.readingTime} {t("min")} - )} + {!!post.stat?.viewDetailCount && ( diff --git a/src/lib/expand-unit.ts b/src/lib/expand-unit.ts index 15948883..683c1e33 100644 --- a/src/lib/expand-unit.ts +++ b/src/lib/expand-unit.ts @@ -4,6 +4,7 @@ import removeMarkdown from "remove-markdown" import { SCORE_API_DOMAIN, SITE_URL } from "~/lib/env" import { toCid, toGateway } from "~/lib/ipfs-parser" +import readingTime from "~/lib/reading-time" import { ExpandedCharacter, ExpandedNote } from "~/lib/types" import { getNoteSlug } from "./helpers" @@ -75,8 +76,8 @@ export const expandCrossbellNote = async ({ expandedNote.metadata.content.readingTime = expandedNote.metadata.content .content ? Math.round( - removeMarkdown(expandedNote.metadata.content.content).length / 400, - ) // TODO + readingTime(removeMarkdown(expandedNote.metadata.content.content)), + ) : 0 if (useStat) { diff --git a/src/lib/i18n/locales/zh/common.json b/src/lib/i18n/locales/zh/common.json index 8bcf1016..e31d2bf6 100644 --- a/src/lib/i18n/locales/zh/common.json +++ b/src/lib/i18n/locales/zh/common.json @@ -94,6 +94,5 @@ "Share Modal": "分享到...", "Share": "分享", "Share Message": "嘿,我发现了一篇宝藏文章「{{title}}」哩,快来看看吧!", - "mins": "分钟", "min": "分钟" } diff --git a/src/lib/reading-time.ts b/src/lib/reading-time.ts new file mode 100644 index 00000000..ad366cc0 --- /dev/null +++ b/src/lib/reading-time.ts @@ -0,0 +1,12 @@ +export default function readingTime(text: string) { + const chineseCharacters = text.replace(/[\x00-\xff]/g, "") + const englishWords = text + .replace(/[^a-zA-Z\s]/g, "") + .split(/\s+/) + .filter(Boolean) + + const chineseReadingTime = chineseCharacters.length / 300 + const englishReadingTime = englishWords.length / 300 + + return chineseReadingTime + englishReadingTime +}