-
-
Notifications
You must be signed in to change notification settings - Fork 8.7k
/
Copy pathblog.js
86 lines (80 loc) · 2.22 KB
/
blog.js
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
/**
* Copyright (c) 2017-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
const React = require('react');
const path = require('path');
const fs = require('fs-extra');
const {renderToStaticMarkupWithDoctype} = require('./renderUtils');
const metadataUtils = require('./metadataUtils');
function urlToSource(url) {
if (!url || typeof url !== 'string') {
return null;
}
return url
.replace(/\/index.html$/, '.md')
.replace(/\.html$/, '.md')
.replace(new RegExp('/', 'g'), '-');
}
function fileToUrl(file) {
if (!file || !fs.existsSync(file) || typeof file !== 'string') {
return null;
}
return path
.basename(file)
.replace('-', '/')
.replace('-', '/')
.replace('-', '/')
.replace(/\.md$/, '.html');
}
function getPagesMarkup(numOfBlog, config) {
const BlogPageLayout = require('../core/BlogPageLayout.js');
const blogPages = {};
const perPage = 10;
for (let page = 0; page < Math.ceil(numOfBlog / perPage); page++) {
const metadata = {page, perPage};
const blogPageComp = (
<BlogPageLayout metadata={metadata} language="en" config={config} />
);
const str = renderToStaticMarkupWithDoctype(blogPageComp);
const pagePath = `${page > 0 ? `page${page + 1}` : ''}/index.html`;
blogPages[pagePath] = str;
}
return blogPages;
}
function getMetadata(file) {
if (!file || !fs.existsSync(file)) {
return null;
}
const result = metadataUtils.extractMetadata(
fs.readFileSync(file, {encoding: 'utf8'}),
);
const metadata = Object.assign(
{path: fileToUrl(file), content: result.rawContent},
result.metadata,
);
metadata.id = metadata.title;
return metadata;
}
function getPostMarkup(file, config) {
const metadata = getMetadata(file);
if (!metadata) {
return null;
}
const BlogPostLayout = require('../core/BlogPostLayout.js');
const blogPostComp = (
<BlogPostLayout metadata={metadata} language="en" config={config}>
{metadata.content}
</BlogPostLayout>
);
return renderToStaticMarkupWithDoctype(blogPostComp);
}
module.exports = {
fileToUrl,
getMetadata,
getPagesMarkup,
getPostMarkup,
urlToSource,
};