forked from eri24816/Notion-Hugo
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrender.ts
265 lines (247 loc) · 8.04 KB
/
render.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
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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
import {
Client,
isFullUser,
iteratePaginatedAPI
} from "@notionhq/client"
import {
EquationBlockObjectResponse,
PageObjectResponse
} from "@notionhq/client/build/src/api-endpoints"
import { NotionToMarkdown } from "@pclouddev/notion-to-markdown"
import { MdBlock } from "@pclouddev/notion-to-markdown/build/types"
import fs from "fs-extra"
import katex from "katex"
import path from "path"
import YAML from "yaml"
import { loadConfig } from "./config"
import { getContentFile } from "./file"
import { getCoverLink, getFileName, getPageTitle } from "./helpers"
import { sh } from "./sh"
require("katex/contrib/mhchem"); // modify katex module
function getExpiryTime(blocks: MdBlock[], expiry_time: string | undefined = undefined): string | undefined {
for (const block of blocks) {
if (block.expiry_time !== undefined) {
if (expiry_time === undefined) expiry_time = block.expiry_time
else expiry_time = expiry_time < block.expiry_time ? expiry_time : block.expiry_time
}
if (block.children.length > 0) {
const child_expiry_time = getExpiryTime(block.children, expiry_time)
if (child_expiry_time) {
if (expiry_time === undefined) expiry_time = child_expiry_time
else expiry_time = expiry_time < child_expiry_time? expiry_time : child_expiry_time
}
}
}
return expiry_time
}
let runningWeight = 1
export async function renderPage(page: PageObjectResponse, notion: Client) {
// load formatter config
const formatterConfig = (await loadConfig()).formatter;
formatterConfig.equation.style
const n2m = new NotionToMarkdown({ notionClient: notion });
n2m.setUnsupportedTransformer((type) => {
return `{{< notion-unsupported-block type=${type} >}}`
})
let frontInjectString = ''
switch (formatterConfig.equation.style) {
case 'markdown':
n2m.setCustomTransformer("equation", async (block) => {
const { equation } = block as EquationBlockObjectResponse;
return `\\[${equation}\\]`;
});
break;
case 'shortcode':
n2m.setCustomTransformer("equation", async (block) => {
const { equation } = block as EquationBlockObjectResponse;
return `{{< math >}}\\[${equation}\\]{{< /math >}}`
})
break;
case 'html':
n2m.setCustomTransformer("equation", async (block) => {
const { equation } = block as EquationBlockObjectResponse;
const html = katex.renderToString(equation.expression, {
throwOnError: false,
displayMode: true,
});
return html;
});
frontInjectString += `<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css" integrity="sha384-bYdxxUwYipFNohQlHt0bjN/LCpueqWz13HufFEV1SUatKs1cm4L6fFgCi1jT643X" crossorigin="anonymous">\n`
break
default:
console.warn('[Warn] invalid notion.toml config')
break;
}
let nearest_expiry_time: string | null = null
const mdblocks = await n2m.pageToMarkdown(page.id);
const page_expiry_time = getExpiryTime(mdblocks)
if (page_expiry_time) nearest_expiry_time = page_expiry_time
const mdString = n2m.toMarkdownString(mdblocks);
page.properties.Name;
const title = getPageTitle(page);
const frontMatter: Record<
string,
string | string[] | number | boolean | PageObjectResponse
> = {
title,
date: page.created_time,
lastmod: page.last_edited_time,
draft: false,
};
// set featuredImage
const featuredImageLink = await getCoverLink(page.id, notion);
if (featuredImageLink) {
const { link, expiry_time } = featuredImageLink;
frontMatter.featuredImage = link;
// update nearest_expiry_time
if (expiry_time) {
if (nearest_expiry_time) {
nearest_expiry_time = expiry_time < nearest_expiry_time ? expiry_time : nearest_expiry_time
} else {
nearest_expiry_time = expiry_time
}
}
}
frontMatter.weight = runningWeight++
// map page properties to front matter
for (const property in page.properties) {
const id = page.properties[property].id;
const response = await notion.pages.properties.retrieve({
page_id: page.id,
property_id: id,
});
if (response.object === "property_item") {
switch (response.type) {
case "checkbox":
frontMatter[property] = response.checkbox;
break;
case "select":
if (response.select?.name)
frontMatter[property] = response.select?.name;
break;
case "multi_select":
frontMatter[property] = response.multi_select.map(
(select) => select.name
);
break;
case "email":
if (response.email) frontMatter[property] = response.email;
break;
case "url":
if (response.url) frontMatter[property] = response.url;
break;
case "date":
if (response.date?.start)
frontMatter[property] = response.date?.start;
break;
case "number":
if (response.number) frontMatter[property] = response.number;
break;
case "phone_number":
if (response.phone_number)
frontMatter[property] = response.phone_number;
break;
case "status":
if (response.status?.name)
frontMatter[property] = response.status?.name;
// ignore these properties
case "last_edited_by":
case "last_edited_time":
case "rollup":
case "files":
case "formula":
case "created_by":
case "created_time":
break;
default:
break;
}
} else {
for await (const result of iteratePaginatedAPI(
// @ts-ignore
notion.pages.properties.retrieve,
{
page_id: page.id,
property_id: id,
}
)) {
switch (result.type) {
case "people":
frontMatter[property] = frontMatter[property] || [];
if (isFullUser(result.people)) {
const fm = frontMatter[property];
if (Array.isArray(fm) && result.people.name) {
fm.push(result.people.name);
}
}
break;
case "rich_text":
frontMatter[property] = frontMatter[property] || "";
frontMatter[property] += result.rich_text.plain_text;
// ignore these
case "relation":
case "title":
default:
break;
}
}
}
}
// set default author
if (frontMatter.authors == null) {
const response = await notion.users.retrieve({
user_id: page.last_edited_by.id,
});
if (response.name) {
frontMatter.authors = [response.name];
}
}
// save metadata
frontMatter.NOTION_METADATA = page;
// save update time
frontMatter.UPDATE_TIME = (new Date()).toISOString()
// save nearest expiry time
if (nearest_expiry_time) frontMatter.EXPIRY_TIME = nearest_expiry_time
return {
title,
pageString:
"---\n" +
YAML.stringify(frontMatter, {
defaultStringType: "QUOTE_DOUBLE",
defaultKeyType: "PLAIN",
}) +
"\n---\n" +
frontInjectString + '\n' +
mdString,
};
}
export async function savePage(
page: PageObjectResponse,
notion: Client,
targetFolder: string,
overrideFileName: string | null = null
) {
const postpath = path.join(
"content",
targetFolder,
getFileName(getPageTitle(page), page.id)
);
const post = getContentFile(postpath);
if (post) {
const metadata = post.metadata;
// if the page is not modified, continue
if (post.expiry_time == null && metadata.last_edited_time === page.last_edited_time) {
console.info(`[Info] The post ${postpath} is up-to-date, skipped.`);
return;
}
}
// otherwise update the page
console.info(`[Info] Updating ${postpath}`);
const { title, pageString } = await renderPage(page, notion);
const fileName = overrideFileName || getFileName(title, page.id);
await sh(
`hugo new "${targetFolder}/${fileName}"`,
false
);
fs.writeFileSync(`content/${targetFolder}/${fileName}`, pageString);
}