-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathcontents.tsx
More file actions
178 lines (139 loc) · 4.91 KB
/
contents.tsx
File metadata and controls
178 lines (139 loc) · 4.91 KB
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
/* eslint-disable @next/next/no-img-element */
import fs from 'fs';
import { globSync } from 'glob';
import matter from 'gray-matter';
import path from 'path';
import siteConfig from '../../config';
import { Content } from '../../types/metadata';
import { parseDate } from './formatDate';
import { kebabToTitleCase } from './kebabToTitleCase';
function getMDXFiles(dir) {
return globSync('**/*.mdx', { cwd: dir })
}
function getExcerpt(content) {
// by <!-- more --> separator
const match = content.match(/<!--\s*more\s*-->/)
if (match) {
return content.slice(0, match.index)
}
// get first paragraph excluding headings
const paragraphs = content.split('\n\n')
for (let i = 0; i < paragraphs.length; i++) {
const paragraph = paragraphs[i].trim()
if (!paragraph.startsWith('#') && !paragraph.startsWith('---')) {
return paragraph.substring(0, 140)
}
}
return ''
}
async function readMDXFile(filePath, category) {
// console.log(`parsing file: ${filePath}`);
let rawContent = fs.readFileSync(filePath, 'utf-8')
let { data: metadata, content } = matter(rawContent)
// console.log(`metadata:`, metadata);
content = content.trim()
// if no title is provided, use the h1 of the content, if no h1 is found, use the filename
if (!metadata.title) {
const h1 = content.match(/^#\s+(.*)$/m)
metadata.title = h1 ? h1[1] : kebabToTitleCase(path.basename(filePath, path.extname(filePath)))
}
metadata.excerpt = metadata.excerpt || metadata.descriotion || getExcerpt(content)
// if no description is provided, use the excerpt, if no excerpt is found, use the first 140 characters of the content
if (!metadata.description) {
metadata.description = metadata.excerpt
}
// if no publishedAt is provided, use the file creation date
if (!metadata.publishedAt) {
metadata.publishedAt = fs.statSync(filePath).birthtime.toISOString()
}
// if no tags is provided, use an empty array
if (!metadata.tags) {
metadata.tags = []
}
// contents/blog/2021-01-01-slug/index.mdx
metadata.relativePath = filePath.match(/contents\/(.*)\.mdx$/)?.[0]
metadata.href = filePath.match(/contents(.*)\.mdx$/)?.[1].replace(/\/index$/, '')
metadata.match = new RegExp(metadata.href.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
metadata.publishedAt = parseDate(metadata.publishedAt)
// if no slug is provided, use the filename
const segments = metadata.href.split('/').slice(2)
// `undefined` is used to represent the index page
metadata.slug = segments.length ? segments : undefined;
// if meta.image is provided, use it as is, if not, use the first image found in the content
if (!metadata.image) {
const match = content.match(/!\[.*?\]\((.*?)\)/)
if (match) {
metadata.image = match[1]
}
}
// if title is H1, remove it from the content
if (content.startsWith(`# ${metadata.title}`)) {
content = content.replace(/^# .*$/m, '').trim()
}
let mdx = null;
let contentsRelativePath = metadata.relativePath.substring('contents'.length + category.length + 2);
if (category === 'blog') {
mdx = await import(`@contents/blog/${contentsRelativePath}`)
} else {
mdx = await import(`@contents/docs/${contentsRelativePath}`)
}
metadata.authors = metadata.authors || [siteConfig.defaultAuthor]
return {
metadata,
content,
mdx
}
}
async function getMDXData(category) {
const dir = `${process.cwd()}/contents/${category}/`
let mdxFiles = getMDXFiles(dir)
return Promise.allSettled(mdxFiles.map(async (file) => {
return await readMDXFile(`${dir}${file}`, category)
})).then((results) => {
return results.map((result) => {
if (result.status === 'fulfilled') {
return result.value
}
console.error(result.reason);
})
})
}
export async function getAllBlogPosts(): Promise<Content[]> {
const posts = await getMDXData('blog') as Content[]
return posts
.sort((a, b) => {
return b.metadata.publishedAt.getTime() - a.metadata.publishedAt.getTime()
})
.filter((post) => {
return post.metadata.slug !== undefined
})
}
export async function getAllDocsPages(): Promise<Content[]> {
return await getMDXData('docs') as Content[]
}
export async function getBlogBySlug(slug): Promise<Content> {
const posts = await getAllBlogPosts() as Content[]
const post = posts.find((post) => {
if (slug === undefined) {
return post.metadata.slug === undefined
}
return post.metadata.slug?.join('/') === slug.join('/')
})
if (!post) {
throw new Error(`Post with slug ${slug} not found`)
}
return post
}
export async function getDocBySlug(slug): Promise<Content> {
const posts = await getAllDocsPages()
const post = posts.find((post) => {
if (slug === undefined) {
return post.metadata.slug === undefined
}
return post.metadata.slug?.join('/') === slug.join('/')
})
if (!post) {
throw new Error(`Post with slug ${slug} not found`)
}
return post
}