-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathPostExample.njs
More file actions
86 lines (80 loc) · 2.52 KB
/
PostExample.njs
File metadata and controls
86 lines (80 loc) · 2.52 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
import { readFileSync, existsSync } from "fs";
import Translatable from "./Translatable";
import "./Article.scss";
import prismjs from "prismjs";
import { Remarkable } from "remarkable";
import meta from "remarkable-meta";
class PostExample extends Translatable {
html = "";
static async getPostByKey({ locale, key }) {
await import("prismjs/components/prism-jsx.min");
let path = `i18n/${locale}/examples/${key}.md`;
if (!existsSync(path)) {
path = `i18n/${locale}/examples/404.md`;
}
const text = readFileSync(path, "utf-8");
const md = new Remarkable({
highlight: (code) =>
Prism.highlight(code, prismjs.languages.jsx, "javascript"),
});
md.use(meta);
md.use((md) => {
const originalRender = md.renderer.rules.link_open;
md.renderer.rules.link_open = function () {
let result = originalRender.apply(null, arguments);
const regexp = /href="([^"]*)"/;
const href = regexp.exec(result)[1];
if (!href.startsWith("/")) {
result = result.replace(">", ' target="_blank" rel="noopener">');
}
return result;
};
});
md.use((md) => {
md.renderer.rules.heading_open = function (tokens, i) {
const { content } = tokens[i + 1];
const { hLevel } = tokens[i];
const id = content
.toLowerCase()
.split(/[^a-z]/)
.join("-");
return `<h${hLevel} id="${id}"><a href="#${id}">`;
};
md.renderer.rules.heading_close = function (tokens, i) {
const { hLevel } = tokens[i];
return `</a></h${hLevel}>`;
};
});
return {
html: md.render(text),
...md.meta,
};
}
async initiate({ page, params }) {
super.initiate({ page, locale: page.locale });
const post = await this.getPostByKey({ key: params.slug, locale: page.locale });
Object.assign(this, post);
}
launch({ project, page }) {
page.title = `${this.title} - ${project.name}`;
page.description = this.description;
if (this.status) {
page.status = 404;
}
}
render() {
if (!this.html) return false;
return (
<section class="max-w-screen-md mx-auto px-4 flex flex-wrap sm:flex-nowrap py-12 sm:py-24">
<article class="w-full pb-24">
<h2 class="text-pink-600 text-4xl font-light block mb-8">{this.title}</h2>
<div
html={this.html}
class="prose dark:prose-dark max-w-none text-lg"
/>
</article>
</section>
);
}
}
export default PostExample;