-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.ts
91 lines (81 loc) · 2.37 KB
/
utils.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import fs from 'fs';
import matter from 'gray-matter';
import React from 'react';
import { Post, PostFrontMatter } from './types';
export const getAllPosts = (): Post[] => {
const files = fs.readdirSync('posts');
//@ts-ignore
return files.reduce((allPosts, postSlug) => {
const source = fs.readFileSync(`posts/${postSlug}`);
const { data, content } = matter(source);
return [
{
frontMatter: data,
body: content,
slug: postSlug.replace('.md', '')
},
...allPosts
];
}, []);
};
export const getPostBySlug = (slug: string): Post => {
const file = fs.readFileSync(`posts/${slug}.md`);
const { data, content } = matter(file);
const postData: PostFrontMatter = {
title: data.title,
description: data.description,
image: data?.image,
tags: data?.tags,
authors: data?.authors,
author_link: data?.author_link,
date: data.date
};
return {
frontMatter: postData,
body: content,
slug: slug
};
};
export const getAIEPBySlug = (week: string, slug: string) => {
const file = fs.readFileSync(`aiep/${week}/${slug}.md`);
const { data, content } = matter(file);
return {
matter: data,
body: content
};
};
// extract text from markdown content
const extractPlainText = (elements: React.ReactNode): string => {
const childrenArray = React.Children.toArray(elements);
return childrenArray.reduce((acc: string, el) => {
if (typeof el === 'string') {
return acc + el;
}
if (React.isValidElement(el) && el.props.children) {
return acc + extractPlainText(el.props.children);
}
return acc;
}, '');
};
// Extract plaintext from markdown content
export const postPreview = (markdownContent: string) => {
const initalText = extractPlainText(markdownContent);
const plainText = initalText
.replace(/!\[[^\]]*\](\([^)]*\)|\[[^\]]*\])/g, '')
.replace(/~~(.*?)~~/g, '')
.replace(/\*\*(.*?)\*\*|__(.*?)__/g, '')
.replace(/\*(.*?)\*|_(.*?)_/g, '')
.replace(/^#+\s+(.*)/gm, '$1')
.replace(
/(?:!?\[[^\]]*\]\([^)]*\)|!?\[[^\]]*\]\[[^\]]*\]|~~.*?~~|\*\*.*?\*\*|__.*?__|\*.*?\*|_.*?_|^#+\s+.*$|[\*>-] .*$|\n\n)/gm,
''
)
.replace(/\n{2,}/g, '\n')
.trim();
const maxLength = 200;
const previewText =
plainText.length > maxLength
? `${plainText.substring(0, maxLength)}...`
: plainText;
return previewText;
};