Skip to content

Commit 041a8d7

Browse files
committed
feat: estimate reading time.
1 parent cc5a5f5 commit 041a8d7

File tree

3 files changed

+19
-0
lines changed

3 files changed

+19
-0
lines changed

src/components/metadata-cards/PostMetadata.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ const PostMetadata = ({
99
overrideDate,
1010
updatedDate,
1111
seriesPosts,
12+
estimatedReadingTime,
1213
}) => {
1314
if (!metadata) {
1415
return null;
@@ -87,6 +88,12 @@ const PostMetadata = ({
8788
<p className="text-gray-300 ml-1 mt-1">{updatedDate}</p>
8889
</div>
8990
)}
91+
{estimatedReadingTime > 0 && (
92+
<div>
93+
<Label>Reading Time</Label>
94+
<p className="text-gray-300 ml-1 mt-1">{estimatedReadingTime} min read</p>
95+
</div>
96+
)}
9097
{metadata.tags && (
9198
<div>
9299
<Label>Tags</Label>

src/pages/BlogPostPage.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import Seo from '../components/Seo';
1717
import ShareButtons from '../components/ShareButtons';
1818
import remarkGfm from 'remark-gfm';
1919
import rehypeRaw from 'rehype-raw';
20+
import { calculateReadingTime } from '../utils/readingTime';
2021

2122
const LinkRenderer = ({ href, children }) => {
2223
const isExternal = href.startsWith('http') || href.startsWith('https');
@@ -131,6 +132,7 @@ const BlogPostPage = () => {
131132
const [post, setPost] = useState(null);
132133
const [loading, setLoading] = useState(true);
133134
const [readingProgress, setReadingProgress] = useState(0);
135+
const [estimatedReadingTime, setEstimatedReadingTime] = useState(0);
134136
const [isAtTop, setIsAtTop] = useState(true); // New state for tracking if at top
135137
const contentRef = useRef(null);
136138
const [isModalOpen, setIsModalToOpen] = useState(false);
@@ -241,6 +243,7 @@ const BlogPostPage = () => {
241243
seriesPosts,
242244
currentSeries,
243245
});
246+
setEstimatedReadingTime(calculateReadingTime(postBody));
244247
} catch (error) {
245248
console.error('Error fetching post or metadata:', error);
246249

@@ -421,6 +424,7 @@ const BlogPostPage = () => {
421424
overrideDate={post.attributes.date}
422425
updatedDate={post.attributes.updated}
423426
seriesPosts={post.seriesPosts}
427+
estimatedReadingTime={estimatedReadingTime}
424428
/>
425429
</div>
426430
</div>

src/utils/readingTime.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
// src/utils/readingTime.js
2+
3+
export const calculateReadingTime = (text) => {
4+
const wordsPerMinute = 200; // Average reading speed
5+
const words = text.split(/\s+/).filter(word => word !== '').length;
6+
const minutes = Math.ceil(words / wordsPerMinute);
7+
return minutes;
8+
};

0 commit comments

Comments
 (0)