-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
export.ts
363 lines (323 loc) · 10.4 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
import path from 'path'
import fs from 'fs-extra'
import { blue, cyan, dim, green, yellow } from 'kolorist'
import { Presets, SingleBar } from 'cli-progress'
import { parseRangeString } from '@slidev/parser/core'
import type { ExportArgs, SlideInfo, TocItem } from '@slidev/types'
import { outlinePdfFactory } from '@lillallol/outline-pdf'
import * as pdfLib from 'pdf-lib'
import { PDFDocument } from 'pdf-lib'
import type { ResolvedSlidevOptions } from './options'
import { packageExists } from './utils'
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
}
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({
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> {
if (!packageExists('playwright-chromium'))
throw new Error('The exporting for Slidev is powered by Playwright, please installed it via `npm i -D playwright-chromium`')
const { chromium } = await import('playwright-chromium')
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,
}: ExportOptions) {
if (!packageExists('playwright-chromium'))
throw new Error('The exporting for Slidev is powered by Playwright, please installed it via `npm i -D playwright-chromium`')
const pages: number[] = parseRangeString(total, range)
const { chromium } = await import('playwright-chromium')
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: height * pages.length,
},
deviceScaleFactor: 1,
})
const page = await context.newPage()
const progress = createSlidevProgress(true)
async function go(no: number | string, clicks?: string) {
const path = `${no}?print${withClicks ? '=clicks' : ''}${clicks ? `&clicks=${clicks}` : ''}${range ? `&range=${range}` : ''}`
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' })
// Check for "data-waitfor" attribute and wait for given element to be loaded
const elements = await page.locator('[data-waitfor]')
const count = await elements.count()
for (let index = 0; index < count; index++) {
const element = await elements.nth(index)
const attribute = await element.getAttribute('data-waitfor')
if (attribute)
await element.locator(attribute).waitFor()
}
// Wait for frames to load
const frames = await page.frames()
await Promise.all(frames.map(frame => frame.waitForLoadState()))
}
async function getSlidesIndex() {
const clicksBySlide: Record<string, number> = {}
const slides = await page.locator('.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
}
async function genPagePdf() {
if (!output.endsWith('.pdf'))
output = `${output}.pdf`
await go('print')
const slideIndexes = await getSlidesIndex()
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)
const titleSlide = slides[0]
if (titleSlide?.title)
pdf.setTitle(titleSlide.title)
if (titleSlide?.frontmatter?.info)
pdf.setSubject(titleSlide.frontmatter.info)
if (withToc) {
const outlinePdf = outlinePdfFactory(pdfLib)
const tocTree = slides.filter(slide => slide.title)
.reduce((acc: TocItem[], slide) => {
addToTree(acc, slide, slideIndexes)
return acc
}, [])
const outline = makeOutline(tocTree)
pdf = await outlinePdf({ outline, pdf })
}
pdfData = Buffer.from(await pdf.save())
await fs.writeFile(output, pdfData)
}
async function genPagePng() {
await go('print')
await fs.emptyDir(output)
const slides = await page.locator('.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 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
}
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,
withClicks: args['with-clicks'],
executablePath: args['executable-path'],
withToc: args['with-toc'],
}
const {
entry,
output,
format,
timeout,
range,
dark,
withClicks,
executablePath,
withToc,
} = 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,
}
}