forked from slidevjs/slidev
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcore.ts
More file actions
439 lines (389 loc) · 11.6 KB
/
Copy pathcore.ts
File metadata and controls
439 lines (389 loc) · 11.6 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
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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
import type { FrontmatterStyle, SlidevDetectedFeatures, SlidevMarkdown, SlidevPreparserExtension, SourceSlideInfo } from '@slidev/types'
import { ensurePrefix } from '@antfu/utils'
import YAML from 'yaml'
const RE_FRONTMATTER = /^---.*\r?\n([\s\S]*?)---/
const RE_YAML_CODEBLOCK = /^\s*```ya?ml([\s\S]*?)```/
const RE_DOLLAR_INLINE = /\$.*?\$/
const RE_DOLLAR_BLOCK = /\$\$/
const RE_MONACO_BLOCK = /\{monaco.*\}/
const RE_TWEET_TAG = /<Tweet\b/
const RE_BLUESKY_TAG = /<BlueSky\b/
const RE_MERMAID_CODEBLOCK = /^```mermaid/m
const RE_HEADING = /^(#+) (.*)$/m
const RE_LEADING_BACKTICKS = /^\s*`+/
const RE_CRLF = /\r?\n/g
export interface SlidevParserOptions {
noParseYAML?: boolean
preserveCR?: boolean
}
function advanceHtmlCommentState(line: string, inHtmlComment: boolean) {
let cursor = 0
while (cursor < line.length) {
if (inHtmlComment) {
const end = line.indexOf('-->', cursor)
if (end < 0)
return true
inHtmlComment = false
cursor = end + 3
}
else {
const start = line.indexOf('<!--', cursor)
if (start < 0)
return false
const end = line.indexOf('-->', start + 4)
if (end < 0)
return true
cursor = end + 3
}
}
return inHtmlComment
}
export function stringify(data: SlidevMarkdown) {
return `${data.slides.map(stringifySlide).join('\n').trim()}\n`
}
export function stringifySlide(data: SourceSlideInfo, idx = 0) {
return (data.raw.startsWith('---') || idx === 0)
? data.raw
: `---\n${ensurePrefix('\n', data.raw)}`
}
export function prettifySlide(data: SourceSlideInfo) {
const trimed = data.content.trim()
data.content = trimed ? `\n${data.content.trim()}\n` : ''
data.raw = data.frontmatterDoc?.contents
? data.frontmatterStyle === 'yaml'
? `\`\`\`yaml\n${data.frontmatterDoc.toString().trim()}\n\`\`\`\n${data.content}`
: `---\n${data.frontmatterDoc.toString().trim()}\n---\n${data.content}`
: data.content
if (data.note)
data.raw += `\n<!--\n${data.note.trim()}\n-->\n`
return data
}
export function prettify(data: SlidevMarkdown) {
data.slides.forEach(prettifySlide)
return data
}
function matter(code: string, options: SlidevParserOptions) {
let type: FrontmatterStyle | undefined
let raw: string | undefined
let content = code
.replace(RE_FRONTMATTER, (_, f) => {
type = 'frontmatter'
raw = f
return ''
})
if (type !== 'frontmatter') {
content = content
.replace(RE_YAML_CODEBLOCK, (_, f) => {
type = 'yaml'
raw = f
return ''
})
}
const doc = raw && !options.noParseYAML ? YAML.parseDocument(raw) : undefined
return {
type,
raw,
doc,
data: doc?.toJSON(),
content,
}
}
const IMAGE_EXTENSIONS = /\.(?:png|jpe?g|gif|svg|webp|avif|ico|bmp|tiff?)$/i
/**
* Extract image URLs from slide content and frontmatter.
* Strips code blocks first to avoid false positives.
*/
export function extractImagesUsage(content: string, frontmatter: Record<string, any>): string[] {
const images = new Set<string>()
// Collect from frontmatter keys
for (const key of ['image', 'backgroundImage', 'background']) {
const val = frontmatter[key]
if (typeof val === 'string' && val && !val.startsWith('data:')) {
// For `background`, only include if it looks like an image URL
if (key === 'background') {
if (IMAGE_EXTENSIONS.test(val) || val.startsWith('/') || val.startsWith('http'))
images.add(val)
}
else {
images.add(val)
}
}
}
// Strip code blocks to avoid false positives
const stripped = content.replace(/^```[\s\S]+?^```/gm, '')
// Markdown images: 
for (const [, url] of stripped.matchAll(/!\[[^\]]*\]\(([^)]+)\)/g)) {
if (url && !url.startsWith('data:'))
images.add(url.trim())
}
// Vue component props: src="url", image="url"
for (const [, url] of stripped.matchAll(/\b(?:src|image)=["']([^"']+)["']/g)) {
if (url && !url.startsWith('data:') && !url.includes('{{') && IMAGE_EXTENSIONS.test(url))
images.add(url.trim())
}
// Vue bound props: :src="'/path/to/img.png'"
for (const [, url] of stripped.matchAll(/:(?:src|image)=["']'([^']+)'["']/g)) {
if (url && !url.startsWith('data:') && IMAGE_EXTENSIONS.test(url))
images.add(url.trim())
}
// CSS url() with image extension filter
for (const [, url] of stripped.matchAll(/url\(["']?([^"')]+)["']?\)/g)) {
if (url && !url.startsWith('data:') && IMAGE_EXTENSIONS.test(url))
images.add(url.trim())
}
return Array.from(images)
}
export function detectFeatures(code: string): SlidevDetectedFeatures {
return {
katex: !!code.match(RE_DOLLAR_INLINE) || !!code.match(RE_DOLLAR_BLOCK),
monaco: RE_MONACO_BLOCK.test(code) ? scanMonacoReferencedMods(code) : false,
tweet: !!code.match(RE_TWEET_TAG),
bluesky: !!code.match(RE_BLUESKY_TAG),
mermaid: !!code.match(RE_MERMAID_CODEBLOCK),
}
}
export function parseSlide(raw: string, options: SlidevParserOptions = {}): Omit<SourceSlideInfo, 'filepath' | 'index' | 'start' | 'contentStart' | 'end'> {
const matterResult = matter(raw, options)
let note: string | undefined
const frontmatter = matterResult.data || {}
let content = matterResult.content.trim()
const revision = hash(raw.trim())
const comments = Array.from(content.matchAll(/<!--([\s\S]*?)-->/g))
if (comments.length) {
const last = comments[comments.length - 1]
if (last.index !== undefined && last.index + last[0].length >= content.length) {
note = last[1].trim()
content = content.slice(0, last.index).trim()
}
}
let title
let level
if (frontmatter.title || frontmatter.name) {
title = frontmatter.title || frontmatter.name
}
else {
const match = content.match(RE_HEADING)
title = match?.[2]?.trim()
level = match?.[1]?.length
}
if (frontmatter.level)
level = frontmatter.level || 1
const images = extractImagesUsage(content, frontmatter)
return {
raw,
title,
level,
revision,
content,
contentRaw: content,
frontmatter,
frontmatterStyle: matterResult.type,
frontmatterDoc: matterResult.doc,
frontmatterRaw: matterResult.raw,
note,
images,
}
}
export async function parse(
markdown: string,
filepath: string,
extensions?: SlidevPreparserExtension[],
options: SlidevParserOptions = {},
): Promise<SlidevMarkdown> {
const lines = markdown.split(options.preserveCR ? '\n' : RE_CRLF)
const slides: SourceSlideInfo[] = []
let start = 0
let contentStart = 0
let inHtmlComment = false
async function slice(end: number) {
if (start === end)
return
const raw = lines.slice(start, end).join('\n')
const slide: SourceSlideInfo = {
...parseSlide(raw, options),
filepath,
index: slides.length,
start,
contentStart,
end,
}
if (extensions) {
for (const e of extensions) {
if (e.transformSlide) {
const newContent = await e.transformSlide(slide.content, slide.frontmatter)
if (newContent !== undefined)
slide.content = newContent
if (typeof slide.frontmatter.title === 'string') {
slide.title = slide.frontmatter.title
}
if (typeof slide.frontmatter.level === 'number') {
slide.level = slide.frontmatter.level
}
}
if (e.transformNote) {
const newNote = await e.transformNote(slide.note, slide.frontmatter)
if (newNote !== undefined)
slide.note = newNote
}
}
}
slides.push(slide)
start = end + 1
contentStart = end + 1
}
if (extensions) {
for (const e of extensions) {
if (e.transformRawLines)
await e.transformRawLines(lines)
}
}
for (let i = 0; i < lines.length; i++) {
const rawLine = lines[i]
const line = rawLine.trimEnd()
if (inHtmlComment) {
inHtmlComment = advanceHtmlCommentState(rawLine, true)
continue
}
if (line.startsWith('---')) {
await slice(i)
const next = lines[i + 1]
// found frontmatter, skip next dash
if (line[3] !== '-' && next?.trim()) {
start = i
for (i += 1; i < lines.length; i++) {
if (lines[i].trimEnd() === '---')
break
}
contentStart = i + 1
}
}
// skip code block
else if (line.trimStart().startsWith('```')) {
const codeBlockLevel = line.match(RE_LEADING_BACKTICKS)![0]
let j = i + 1
for (; j < lines.length; j++) {
if (lines[j].startsWith(codeBlockLevel))
break
}
// Update i only when code block ends
if (j !== lines.length)
i = j
}
else {
inHtmlComment = advanceHtmlCommentState(rawLine, false)
}
}
if (start <= lines.length - 1)
await slice(lines.length)
return {
filepath,
raw: markdown,
slides,
}
}
export function parseSync(
markdown: string,
filepath: string,
options: SlidevParserOptions = {},
): SlidevMarkdown {
const lines = markdown.split(options.preserveCR ? '\n' : RE_CRLF)
const slides: SourceSlideInfo[] = []
let start = 0
let contentStart = 0
let inHtmlComment = false
function slice(end: number) {
if (start === end)
return
const raw = lines.slice(start, end).join('\n')
const slide: SourceSlideInfo = {
...parseSlide(raw, options),
filepath,
index: slides.length,
start,
contentStart,
end,
}
slides.push(slide)
start = end + 1
contentStart = end + 1
}
for (let i = 0; i < lines.length; i++) {
const rawLine = lines[i]
const line = rawLine.trimEnd()
if (inHtmlComment) {
inHtmlComment = advanceHtmlCommentState(rawLine, true)
continue
}
if (line.startsWith('---')) {
slice(i)
const next = lines[i + 1]
// found frontmatter, skip next dash
if (line[3] !== '-' && next?.trim()) {
start = i
for (i += 1; i < lines.length; i++) {
if (lines[i].trimEnd() === '---')
break
}
contentStart = i + 1
}
}
// skip code block
else if (line.trimStart().startsWith('```')) {
const codeBlockLevel = line.match(RE_LEADING_BACKTICKS)![0]
let j = i + 1
for (; j < lines.length; j++) {
if (lines[j].startsWith(codeBlockLevel))
break
}
// Update i only when code block ends
if (j !== lines.length)
i = j
}
else {
inHtmlComment = advanceHtmlCommentState(rawLine, false)
}
}
if (start <= lines.length - 1)
slice(lines.length)
return {
filepath,
raw: markdown,
slides,
}
}
function scanMonacoReferencedMods(md: string) {
const types = new Set<string>()
const deps = new Set<string>()
md.replace(
/^```(\w+)\s*\{monaco([^}]*)\}\s*(\S[\s\S]*?)^```/gm,
(full, lang = 'ts', kind: string, code: string) => {
lang = lang.trim()
const isDep = kind === '-run'
if (['js', 'javascript', 'ts', 'typescript'].includes(lang)) {
for (const [, , specifier] of code.matchAll(/\s+from\s+(["'])([/.\w@-]+)\1/g)) {
if (specifier) {
if (!'./'.includes(specifier))
types.add(specifier) // All local TS files are loaded by globbing
if (isDep)
deps.add(specifier)
}
}
}
return ''
},
)
return {
types: Array.from(types),
deps: Array.from(deps),
}
}
function hash(str: string) {
let hash = 0
for (let i = 0; i < str.length; i++) {
hash = ((hash << 5) - hash) + str.charCodeAt(i)
hash |= 0
}
return hash.toString(36).slice(0, 12)
}
export * from './config'
export * from './utils'