forked from sveltejs/svelte
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_posts.js
69 lines (54 loc) · 1.83 KB
/
_posts.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
import fs from 'fs';
import path from 'path';
import { extract_frontmatter, langs, link_renderer } from '@sveltejs/site-kit/utils/markdown.js';
import marked from 'marked';
import { makeSlugProcessor } from '../../utils/slug';
import { SLUG_PRESERVE_UNICODE } from '../../../config';
import PrismJS from 'prismjs';
import 'prismjs/components/prism-bash';
const makeSlug = makeSlugProcessor(SLUG_PRESERVE_UNICODE);
export default function get_posts() {
return fs
.readdirSync('content/blog')
.map(file => {
if (path.extname(file) !== '.md') return;
const match = /^(\d+-\d+-\d+)-(.+)\.md$/.exec(file);
if (!match) throw new Error(`Invalid filename '${file}'`);
const [, pubdate, slug] = match;
const markdown = fs.readFileSync(`content/blog/${file}`, 'utf-8');
const { content, metadata } = extract_frontmatter(markdown);
const date = new Date(`${pubdate} EDT`); // cheeky hack
metadata.pubdate = pubdate;
metadata.dateString = date.toDateString();
const renderer = new marked.Renderer();
renderer.link = link_renderer;
renderer.code = (source, lang) => {
const plang = langs[lang];
const highlighted = PrismJS.highlight(
source,
PrismJS.languages[plang],
lang,
);
return `<pre class='language-${plang}'><code>${highlighted}</code></pre>`;
};
renderer.heading = (text, level, rawtext) => {
const fragment = makeSlug(rawtext);
return `
<h${level}>
<span id="${fragment}" class="offset-anchor"></span>
<a href="blog/${slug}#${fragment}" class="anchor" aria-hidden="true"></a>
${text}
</h${level}>`;
};
const html = marked(
content.replace(/^\t+/gm, match => match.split('\t').join(' ')),
{ renderer }
);
return {
html,
metadata,
slug
};
})
.sort((a, b) => a.metadata.pubdate < b.metadata.pubdate ? 1 : -1);
}