-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
export.ts
568 lines (510 loc) · 15.8 KB
/
export.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
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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
import path from 'node:path'
import { Buffer } from 'node:buffer'
import process from 'node:process'
import fs from 'fs-extra'
import { blue, cyan, dim, green, yellow } from 'kolorist'
import { Presets, SingleBar } from 'cli-progress'
import { clearUndefined } from '@antfu/utils'
import { parseRangeString } from '@slidev/parser/core'
import type { ExportArgs, ResolvedSlidevOptions, SlideInfo, TocItem } from '@slidev/types'
import { outlinePdfFactory } from '@lillallol/outline-pdf'
import * as pdfLib from 'pdf-lib'
import { PDFDocument } from 'pdf-lib'
import { resolve } from 'mlly'
import { getRoots } from '../resolver'
export interface ExportOptions {
total: number
range?: string
slides: SlideInfo[]
port?: number
base?: string
format?: 'pdf' | 'png' | 'md'
output?: string
timeout?: number
dark?: boolean
routerMode?: 'hash' | 'history'
width?: number
height?: number
withClicks?: boolean
executablePath?: string
withToc?: boolean
/**
* Render slides slide by slide. Works better with global components, but will break cross slide links and TOC in PDF.
* @default false
*/
perSlide?: boolean
scale?: number
}
function addToTree(tree: TocItem[], info: SlideInfo, slideIndexes: Record<number, number>, level = 1) {
const titleLevel = info.level
if (titleLevel && titleLevel > level && tree.length > 0) {
addToTree(tree[tree.length - 1].children, info, slideIndexes, level + 1)
}
else {
tree.push({
no: info.index,
children: [],
level,
path: String(slideIndexes[info.index + 1]),
hideInToc: Boolean(info.frontmatter?.hideInToc),
title: info.title,
})
}
}
function makeOutline(tree: TocItem[]): string {
return tree.map(({ title, path, level, children }) => {
const rootOutline = title ? `${path}|${'-'.repeat(level - 1)}|${title}` : null
const childrenOutline = makeOutline(children)
return childrenOutline.length > 0 ? `${rootOutline}\n${childrenOutline}` : rootOutline
}).filter(outline => !!outline).join('\n')
}
export interface ExportNotesOptions {
port?: number
base?: string
output?: string
timeout?: number
}
function createSlidevProgress(indeterminate = false) {
function getSpinner(n = 0) {
return [cyan('●'), green('◆'), blue('■'), yellow('▲')][n % 4]
}
let current = 0
let spinner = 0
let timer: any
const progress = new SingleBar({
clearOnComplete: true,
hideCursor: true,
format: ` {spin} ${yellow('rendering')}${indeterminate ? dim(yellow('...')) : ' {bar} {value}/{total}'}`,
linewrap: false,
barsize: 30,
}, Presets.shades_grey)
return {
bar: progress,
start(total: number) {
progress.start(total, 0, { spin: getSpinner(spinner) })
timer = setInterval(() => {
spinner += 1
progress.update(current, { spin: getSpinner(spinner) })
}, 200)
},
update(v: number) {
current = v
progress.update(v, { spin: getSpinner(spinner) })
},
stop() {
clearInterval(timer)
progress.stop()
},
}
}
export async function exportNotes({
port = 18724,
base = '/',
output = 'notes',
timeout = 30000,
}: ExportNotesOptions): Promise<string> {
const { chromium } = await importPlaywright()
const browser = await chromium.launch()
const context = await browser.newContext()
const page = await context.newPage()
const progress = createSlidevProgress(true)
progress.start(1)
if (!output.endsWith('.pdf'))
output = `${output}.pdf`
await page.goto(`http://localhost:${port}${base}presenter/print`, { waitUntil: 'networkidle', timeout })
await page.waitForLoadState('networkidle')
await page.emulateMedia({ media: 'screen' })
await page.pdf({
path: output,
margin: {
left: 0,
top: 0,
right: 0,
bottom: 0,
},
printBackground: true,
preferCSSPageSize: true,
})
progress.stop()
browser.close()
return output
}
export async function exportSlides({
port = 18724,
total = 0,
range,
format = 'pdf',
output = 'slides',
slides,
base = '/',
timeout = 30000,
dark = false,
routerMode = 'history',
width = 1920,
height = 1080,
withClicks = false,
executablePath = undefined,
withToc = false,
perSlide = false,
scale = 1,
}: ExportOptions) {
const pages: number[] = parseRangeString(total, range)
const { chromium } = await importPlaywright()
const browser = await chromium.launch({
executablePath,
})
const context = await browser.newContext({
viewport: {
width,
// Calculate height for every slides to be in the viewport to trigger the rendering of iframes (twitter, youtube...)
height: perSlide ? height : height * pages.length,
},
deviceScaleFactor: scale,
})
const page = await context.newPage()
const progress = createSlidevProgress(!perSlide)
async function go(no: number | string, clicks?: string) {
const query = new URLSearchParams()
if (withClicks)
query.set('print', 'clicks')
else
query.set('print', 'true')
if (range)
query.set('range', range)
if (clicks)
query.set('clicks', clicks)
const path = `${no}?${query.toString()}`
const url = routerMode === 'hash'
? `http://localhost:${port}${base}#${path}`
: `http://localhost:${port}${base}${path}`
await page.goto(url, {
waitUntil: 'networkidle',
timeout,
})
await page.waitForLoadState('networkidle')
await page.emulateMedia({ colorScheme: dark ? 'dark' : 'light', media: 'screen' })
const slide = no === 'print'
? page.locator('body')
: page.locator(`[data-slidev-no="${no}"]`)
await slide.waitFor()
// Wait for slides to be loaded
{
const elements = slide.locator('.slidev-slide-loading')
const count = await elements.count()
for (let index = 0; index < count; index++)
await elements.nth(index).waitFor({ state: 'detached' })
}
// Check for "data-waitfor" attribute and wait for given element to be loaded
{
const elements = slide.locator('[data-waitfor]')
const count = await elements.count()
for (let index = 0; index < count; index++) {
const element = elements.nth(index)
const attribute = await element.getAttribute('data-waitfor')
if (attribute) {
await element.locator(attribute).waitFor({ state: 'visible' })
.catch((e) => {
console.error(e)
process.exitCode = 1
})
}
}
}
// Wait for frames to load
{
const frames = page.frames()
await Promise.all(frames.map(frame => frame.waitForLoadState()))
}
// Wait for Mermaid graphs to be rendered
{
const container = slide.locator('#mermaid-rendering-container')
const count = await container.count()
if (count > 0) {
while (true) {
const element = container.locator('div').first()
if (await element.count() === 0)
break
await element.waitFor({ state: 'detached' })
}
await container.evaluate(node => node.style.display = 'none')
}
}
// Hide Monaco aria container
{
const elements = slide.locator('.monaco-aria-container')
const count = await elements.count()
for (let index = 0; index < count; index++) {
const element = elements.nth(index)
await element.evaluate(node => node.style.display = 'none')
}
}
}
async function getSlidesIndex() {
const clicksBySlide: Record<string, number> = {}
const slides = page.locator('.print-slide-container')
const count = await slides.count()
for (let i = 0; i < count; i++) {
const id = (await slides.nth(i).getAttribute('id')) || ''
const path = Number(id.split('-')[0])
clicksBySlide[path] = (clicksBySlide[path] || 0) + 1
}
const slideIndexes = Object.fromEntries(Object.entries(clicksBySlide)
.reduce<[string, number][]>((acc, [path, clicks], i) => {
acc.push([path, clicks + (acc[i - 1]?.[1] ?? 0)])
return acc
}, []))
return slideIndexes
}
function getClicksFromUrl(url: string) {
return url.match(/clicks=([1-9][0-9]*)/)?.[1]
}
async function genPageWithClicks(
fn: (i: number, clicks?: string) => Promise<any>,
i: number,
clicks?: string,
) {
await fn(i, clicks)
if (withClicks) {
await page.keyboard.press('ArrowRight', { delay: 100 })
const _clicks = getClicksFromUrl(page.url())
if (_clicks && clicks !== _clicks)
await genPageWithClicks(fn, i, _clicks)
}
}
async function genPagePdfPerSlide() {
const buffers: Buffer[] = []
const genPdfBuffer = async (i: number, clicks?: string) => {
await go(i, clicks)
const pdf = await page.pdf({
width,
height,
margin: {
left: 0,
top: 0,
right: 0,
bottom: 0,
},
pageRanges: '1',
printBackground: true,
preferCSSPageSize: true,
})
buffers.push(pdf)
}
let idx = 0
for (const i of pages) {
await genPageWithClicks(genPdfBuffer, i)
progress.update(++idx)
}
let mergedPdf = await PDFDocument.create({})
for (const pdfBytes of buffers) {
const pdf = await PDFDocument.load(pdfBytes)
const copiedPages = await mergedPdf.copyPages(pdf, pdf.getPageIndices())
copiedPages.forEach((page) => {
mergedPdf.addPage(page)
})
}
// Edit generated PDF: add metadata and (optionally) TOC
addPdfMetadata(mergedPdf)
if (withToc)
mergedPdf = await addTocToPdf(mergedPdf)
const buffer = await mergedPdf.save()
await fs.writeFile(output, buffer)
}
async function genPagePdfOnePiece() {
await go('print')
await page.pdf({
path: output,
width,
height,
margin: {
left: 0,
top: 0,
right: 0,
bottom: 0,
},
printBackground: true,
preferCSSPageSize: true,
})
// Edit generated PDF: add metadata and (optionally) TOC
let pdfData = await fs.readFile(output)
let pdf = await PDFDocument.load(pdfData)
addPdfMetadata(pdf)
if (withToc)
pdf = await addTocToPdf(pdf)
pdfData = Buffer.from(await pdf.save())
await fs.writeFile(output, pdfData)
}
async function genPagePngOnePiece() {
await go('print')
await fs.emptyDir(output)
const slides = await page.locator('.print-slide-container')
const count = await slides.count()
for (let i = 0; i < count; i++) {
progress.update(i + 1)
let id = (await slides.nth(i).getAttribute('id')) || ''
id = withClicks ? id : id.split('-')[0]
const buffer = await slides.nth(i).screenshot()
await fs.writeFile(path.join(output, `${id}.png`), buffer)
}
}
async function genPagePngPerSlide() {
const genScreenshot = async (i: number, clicks?: string) => {
await go(i, clicks)
await page.screenshot({
omitBackground: false,
path: path.join(
output,
`${i.toString().padStart(2, '0')}${clicks ? `-${clicks}` : ''}.png`,
),
})
}
for (const i of pages)
await genPageWithClicks(genScreenshot, i)
}
function genPagePdf() {
if (!output.endsWith('.pdf'))
output = `${output}.pdf`
return perSlide
? genPagePdfPerSlide()
: genPagePdfOnePiece()
}
function genPagePng() {
return perSlide
? genPagePngPerSlide()
: genPagePngOnePiece()
}
async function genPageMd(slides: SlideInfo[]) {
const files = await fs.readdir(output)
const mds: string[] = files.map((file, i, files) => {
const slideIndex = getSlideIndex(file)
const mdImg = `![${slides[slideIndex]?.title}](./${path.join(output, file)})\n\n`
if ((i + 1 === files.length || getSlideIndex(files[i + 1]) !== slideIndex) && slides[slideIndex]?.note)
return `${mdImg}${slides[slideIndex]?.note}\n\n`
return mdImg
})
if (!output.endsWith('.md'))
output = `${output}.md`
await fs.writeFile(output, mds.join(''))
}
function getSlideIndex(file: string): number {
const slideId = file.substring(0, file.indexOf('.')).split('-')[0]
return Number(slideId) - 1
}
// Adds metadata (title, author, keywords) to PDF document, mutating it
function addPdfMetadata(pdf: PDFDocument): void {
const titleSlide = slides[0]
if (titleSlide?.title)
pdf.setTitle(titleSlide.title)
if (titleSlide?.frontmatter?.info)
pdf.setSubject(titleSlide.frontmatter.info)
if (titleSlide?.frontmatter?.author)
pdf.setAuthor(titleSlide.frontmatter.author)
if (titleSlide?.frontmatter?.keywords) {
if (Array.isArray(titleSlide?.frontmatter?.keywords))
pdf.setKeywords(titleSlide?.frontmatter?.keywords)
else
pdf.setKeywords(titleSlide?.frontmatter?.keywords.split(','))
}
}
async function addTocToPdf(pdf: PDFDocument): Promise<PDFDocument> {
const outlinePdf = outlinePdfFactory(pdfLib)
const slideIndexes = await getSlidesIndex()
const tocTree = slides.filter(slide => slide.title)
.reduce((acc: TocItem[], slide) => {
addToTree(acc, slide, slideIndexes)
return acc
}, [])
const outline = makeOutline(tocTree)
return await outlinePdf({ outline, pdf })
}
progress.start(pages.length)
if (format === 'pdf') {
await genPagePdf()
}
else if (format === 'png') {
await genPagePng()
}
else if (format === 'md') {
await genPagePng()
await genPageMd(slides)
}
else {
throw new Error(`Unsupported exporting format "${format}"`)
}
progress.stop()
browser.close()
return output
}
export function getExportOptions(args: ExportArgs, options: ResolvedSlidevOptions, outDir?: string, outFilename?: string): Omit<ExportOptions, 'port' | 'base'> {
const config = {
...options.data.config.export,
...args,
...clearUndefined({
withClicks: args['with-clicks'],
executablePath: args['executable-path'],
withToc: args['with-toc'],
perSlide: args['per-slide'],
}),
}
const {
entry,
output,
format,
timeout,
range,
dark,
withClicks,
executablePath,
withToc,
perSlide,
scale,
} = config
outFilename = output || options.data.config.exportFilename || outFilename || `${path.basename(entry, '.md')}-export`
if (outDir)
outFilename = path.join(outDir, outFilename)
return {
output: outFilename,
slides: options.data.slides,
total: options.data.slides.length,
range,
format: (format || 'pdf') as 'pdf' | 'png' | 'md',
timeout: timeout ?? 30000,
dark: dark || options.data.config.colorSchema === 'dark',
routerMode: options.data.config.routerMode,
width: options.data.config.canvasWidth,
height: Math.round(options.data.config.canvasWidth / options.data.config.aspectRatio),
withClicks: withClicks || false,
executablePath,
withToc: withToc || false,
perSlide: perSlide || false,
scale: scale || 1,
}
}
async function importPlaywright(): Promise<typeof import('playwright-chromium')> {
const { userRoot, userWorkspaceRoot } = await getRoots()
// 1. resolve from user root
try {
return await import(await resolve('playwright-chromium', { url: userRoot }))
}
catch { }
// 2. resolve from user workspace root
if (userWorkspaceRoot !== userRoot) {
try {
return await import(await resolve('playwright-chromium', { url: userWorkspaceRoot }))
}
catch { }
}
// 3. resolve from global registry
const { resolveGlobal } = await import('resolve-global')
try {
const imported = await import(resolveGlobal('playwright-chromium'))
return imported.default ?? imported
}
catch { }
// 4. resolve from current @slidev/cli installation
try {
return await import('playwright-chromium')
}
catch { }
throw new Error('The exporting for Slidev is powered by Playwright, please install it via `npm i -D playwright-chromium`')
}