-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathrenderer.ts
349 lines (306 loc) · 10.6 KB
/
renderer.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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
import type { ExtendedProperties, IOpts, ThemeStyles } from '@/types'
import type { PropertiesHyphen } from 'csstype'
import type { Renderer, RendererObject, Tokens } from 'marked'
import type { ReadTimeResults } from 'reading-time'
import { cloneDeep, toMerged } from 'es-toolkit'
import frontMatter from 'front-matter'
import hljs from 'highlight.js'
import { marked } from 'marked'
import mermaid from 'mermaid'
import readingTime from 'reading-time'
import { getStyleString } from '.'
import markedAlert from './MDAlert'
import { MDKatex } from './MDKatex'
marked.setOptions({
breaks: true,
})
marked.use(MDKatex({ nonStandard: true }))
function buildTheme({ theme: _theme, fonts, size, isUseIndent }: IOpts): ThemeStyles {
const theme = cloneDeep(_theme)
const base = toMerged(theme.base, {
'font-family': fonts,
'font-size': size,
})
if (isUseIndent) {
theme.block.p = {
'text-indent': `2em`,
...theme.block.p,
}
}
const mergeStyles = (styles: Record<string, PropertiesHyphen>): Record<string, ExtendedProperties> =>
Object.fromEntries(
Object.entries(styles).map(([ele, style]) => [ele, toMerged(base, style)]),
)
return {
...mergeStyles(theme.inline),
...mergeStyles(theme.block),
} as ThemeStyles
}
function escapeHtml(text: string): string {
return text
.replace(/&/g, `&`) // 转义 &
.replace(/</g, `<`) // 转义 <
.replace(/>/g, `>`) // 转义 >
.replace(/"/g, `"`) // 转义 "
.replace(/'/g, `'`) // 转义 '
.replace(/`/g, ```) // 转义 `
}
function buildAddition(): string {
return `
<style>
.preview-wrapper pre::before {
position: absolute;
top: 0;
right: 0;
color: #ccc;
text-align: center;
font-size: 0.8em;
padding: 5px 10px 0;
line-height: 15px;
height: 15px;
font-weight: 600;
}
</style>
`
}
function getStyles(styleMapping: ThemeStyles, tokenName: string, addition: string = ``): string {
const dict = styleMapping[tokenName as keyof ThemeStyles]
if (!dict) {
return ``
}
const styles = getStyleString(dict)
return `style="${styles}${addition}"`
}
function buildFootnoteArray(footnotes: [number, string, string][]): string {
return footnotes
.map(([index, title, link]) =>
link === title
? `<code style="font-size: 90%; opacity: 0.6;">[${index}]</code>: <i style="word-break: break-all">${title}</i><br/>`
: `<code style="font-size: 90%; opacity: 0.6;">[${index}]</code> ${title}: <i style="word-break: break-all">${link}</i><br/>`,
)
.join(`\n`)
}
function transform(legend: string, text: string | null, title: string | null): string {
const options = legend.split(`-`)
for (const option of options) {
if (option === `alt` && text) {
return text
}
if (option === `title` && title) {
return title
}
}
return ``
}
const macCodeSvg = `
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" x="0px" y="0px" width="45px" height="13px" viewBox="0 0 450 130">
<ellipse cx="50" cy="65" rx="50" ry="52" stroke="rgb(220,60,54)" stroke-width="2" fill="rgb(237,108,96)" />
<ellipse cx="225" cy="65" rx="50" ry="52" stroke="rgb(218,151,33)" stroke-width="2" fill="rgb(247,193,81)" />
<ellipse cx="400" cy="65" rx="50" ry="52" stroke="rgb(27,161,37)" stroke-width="2" fill="rgb(100,200,86)" />
</svg>
`.trim()
interface ParseResult {
yamlData: Record<string, any>
markdownContent: string
readingTime: ReadTimeResults
}
function parseFrontMatterAndContent(markdownText: string): ParseResult {
try {
const parsed = frontMatter(markdownText)
const yamlData = parsed.attributes
const markdownContent = parsed.body
const readingTimeResult = readingTime(markdownContent)
return {
yamlData: yamlData as Record<string, any>,
markdownContent,
readingTime: readingTimeResult,
}
}
catch (error) {
console.error(`Error parsing front-matter:`, error)
return {
yamlData: {},
markdownContent: markdownText,
readingTime: readingTime(markdownText),
}
}
}
export function initRenderer(opts: IOpts) {
const footnotes: [number, string, string][] = []
let footnoteIndex: number = 0
let styleMapping: ThemeStyles = buildTheme(opts)
let codeIndex: number = 0
let listIndex: number = 0
let isOrdered: boolean = false
function styles(tag: string, addition: string = ``): string {
return getStyles(styleMapping, tag, addition)
}
function styledContent(styleLabel: string, content: string, tagName?: string): string {
const tag = tagName ?? styleLabel
return `<${tag} ${/^h\d$/.test(tag) ? `data-heading="true"` : ``} ${styles(styleLabel)}>${content}</${tag}>`
}
function addFootnote(title: string, link: string): number {
footnotes.push([++footnoteIndex, title, link])
return footnoteIndex
}
function reset(newOpts: Partial<IOpts>): void {
footnotes.length = 0
footnoteIndex = 0
setOptions(newOpts)
}
function setOptions(newOpts: Partial<IOpts>): void {
opts = { ...opts, ...newOpts }
styleMapping = buildTheme(opts)
marked.use(markedAlert({ styles: styleMapping }))
}
function buildReadingTime(readingTime: ReadTimeResults): string {
if (!opts.countStatus) {
return ``
}
if (!readingTime.words) {
return ``
}
return `
<blockquote ${styles(`blockquote`)}>
<p ${styles(`blockquote_p`)}>字数 ${readingTime?.words},阅读大约需 ${Math.ceil(readingTime?.minutes)} 分钟</p>
</blockquote>
`
}
const buildFootnotes = () => {
if (!footnotes.length) {
return ``
}
return (
styledContent(`h4`, `引用链接`)
+ styledContent(`footnotes`, buildFootnoteArray(footnotes), `p`)
)
}
const renderer: RendererObject = {
heading({ tokens, depth }: Tokens.Heading) {
const text = this.parser.parseInline(tokens)
const tag = `h${depth}`
return styledContent(tag, text)
},
paragraph({ tokens }: Tokens.Paragraph): string {
const text = this.parser.parseInline(tokens)
const isFigureImage = text.includes(`<figure`) && text.includes(`<img`)
const isEmpty = text.trim() === ``
if (isFigureImage || isEmpty) {
return text
}
return styledContent(`p`, text)
},
blockquote({ tokens }: Tokens.Blockquote): string {
let text = this.parser.parse(tokens)
text = text.replace(/<p .*?>/g, `<p ${styles(`blockquote_p`)}>`)
return styledContent(`blockquote`, text)
},
code({ text, lang = `` }: Tokens.Code): string {
if (lang.startsWith(`mermaid`)) {
clearTimeout(codeIndex)
codeIndex = setTimeout(() => {
mermaid.run()
}, 0) as any as number
return `<pre class="mermaid">${text}</pre>`
}
const langText = lang.split(` `)[0]
const language = hljs.getLanguage(langText) ? langText : `plaintext`
let highlighted = hljs.highlight(text, { language }).value
// tab to 4 spaces
highlighted = highlighted.replace(/\t/g, ` `)
highlighted = highlighted
.replace(/\r\n/g, `<br/>`)
.replace(/\n/g, `<br/>`)
.replace(/(>[^<]+)|(^[^<]+)/g, str => str.replace(/\s/g, ` `))
const span = `<span class="mac-sign" style="padding: 10px 14px 0;" hidden>${macCodeSvg}</span>`
const code = `<code class="language-${lang}" ${styles(`code`)}>${highlighted}</code>`
return `<pre class="hljs code__pre" ${styles(`code_pre`)}>${span}${code}</pre>`
},
codespan({ text }: Tokens.Codespan): string {
const escapedText = escapeHtml(text)
return styledContent(`codespan`, escapedText, `code`)
},
listitem(item: Tokens.ListItem): string {
const prefix = isOrdered ? `${listIndex + 1}. ` : `• `
const content = item.tokens.map(t => (this[t.type as keyof Renderer] as <T>(token: T) => string)(t)).join(``)
return styledContent(`listitem`, `${prefix}${content}`, `li`)
},
list({ ordered, items, start = 1 }: Tokens.List): string {
const listItems = []
for (let i = 0; i < items.length; i++) {
isOrdered = ordered
listIndex = Number(start) + i - 1
const item = items[i]
listItems.push(this.listitem(item))
}
const label = ordered ? `ol` : `ul`
return styledContent(label, listItems.join(``))
},
image({ href, title, text }: Tokens.Image): string {
const subText = styledContent(`figcaption`, transform(opts.legend!, text, title))
const figureStyles = styles(`figure`)
const imgStyles = styles(`image`)
return `<figure ${figureStyles}><img ${imgStyles} src="${href}" title="${title}" alt="${text}"/>${subText}</figure>`
},
link({ href, title, text, tokens }: Tokens.Link): string {
const parsedText = this.parser.parseInline(tokens)
if (href.startsWith(`https://mp.weixin.qq.com`)) {
return `<a href="${href}" title="${title || text}" ${styles(`wx_link`)}>${parsedText}</a>`
}
if (href === text) {
return parsedText
}
if (opts.citeStatus) {
const ref = addFootnote(title || text, href)
return `<span ${styles(`link`)}>${parsedText}<sup>[${ref}]</sup></span>`
}
return styledContent(`link`, parsedText, `span`)
},
strong({ tokens }: Tokens.Strong): string {
return styledContent(`strong`, this.parser.parseInline(tokens))
},
em({ tokens }: Tokens.Em): string {
return styledContent(`em`, this.parser.parseInline(tokens), `span`)
},
table({ header, rows }: Tokens.Table): string {
const headerRow = header
.map(cell => this.tablecell(cell))
.join(``)
const body = rows
.map((row) => {
const rowContent = row
.map(cell => this.tablecell(cell))
.join(``)
return styledContent(`tr`, rowContent)
})
.join(``)
return `
<section style="padding:0 8px; max-width: 100%; overflow: auto">
<table class="preview-table">
<thead ${styles(`thead`)}>${headerRow}</thead>
<tbody>${body}</tbody>
</table>
</section>
`
},
tablecell(token: Tokens.TableCell): string {
const text = this.parser.parseInline(token.tokens)
return styledContent(`td`, text)
},
hr(_: Tokens.Hr): string {
return styledContent(`hr`, ``)
},
}
marked.use({ renderer })
return {
buildAddition,
buildFootnotes,
setOptions,
reset,
parseFrontMatterAndContent,
buildReadingTime,
createContainer(content: string) {
return styledContent(`container`, content, `section`)
},
}
}