-
-
Notifications
You must be signed in to change notification settings - Fork 109
/
preview.ts
278 lines (219 loc) · 8.18 KB
/
preview.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
/* eslint-disable @typescript-eslint/no-namespace */
import { EventEmitter } from 'node:events'
import { nanoid } from 'nanoid'
import type { Page, Browser, Target } from 'puppeteer-core'
import TypedEmitter from 'typed-emitter'
import { BrowserManager } from './browser/manager'
import { ConvertType, mimeTypes } from './converter'
import { error } from './error'
import { File, FileType } from './file'
import { debugPreview } from './utils/debug'
const emptyPageURI = `data:text/html;base64,PHRpdGxlPk1hcnAgQ0xJPC90aXRsZT4` // <title>Marp CLI</title>
export namespace Preview {
type PartialByKeys<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>> &
Partial<Pick<T, K>>
// eslint-disable-next-line @typescript-eslint/consistent-type-definitions -- TypedEmitter requires type definition instead of interface
export type Events = {
close: (window: any) => void
exit: () => void
launch: () => void
open: (window: any, location: string) => void
opening: (location: string) => void
}
export interface Options {
browserManager: BrowserManager
height: number
width: number
}
export type ConstructorOptions = PartialByKeys<Options, 'height' | 'width'>
export interface Window extends EventEmitter {
page: Page
close: () => Promise<void>
load: (uri: string) => Promise<void>
}
}
export class Preview extends (EventEmitter as new () => TypedEmitter<Preview.Events>) {
readonly options: Preview.Options
private puppeteerInternal: Browser | undefined
constructor(opts: Preview.ConstructorOptions) {
super()
this.options = {
browserManager: opts.browserManager,
height: opts.height || 360,
width: opts.width || 640,
}
debugPreview('Initialized preview instance: %o', this.options)
}
get puppeteer(): Browser | undefined {
return this.puppeteerInternal
}
async open(location: string) {
this.emit('opening', location)
const win = (await this.createWindow()) || (await this.launch())
win.on('close', () => this.emit('close', win))
await win.load(location)
this.emit('open', win, location)
return win
}
async exit() {
debugPreview('Requested to exit preview')
if (this.puppeteer) {
debugPreview('Closing puppeteer instance for preview...')
await this.puppeteer.close()
this.emit('exit')
this.puppeteerInternal = undefined
debugPreview('Closed puppeteer instance')
}
}
private get browserManager() {
return this.options.browserManager
}
private createWindowObject(page: Page): Preview.Window {
const window = new EventEmitter()
page.on('close', () => window.emit('close'))
return Object.assign(window, {
page,
close: async () => {
try {
debugPreview('Request to close a page: %o', page)
return await page.close()
/* c8 ignore start */
} catch (e: any) {
debugPreview('%O', e)
// Ignore raising error if a target page has already close
if (!e.message.includes('Target closed.')) throw e
}
/* c8 ignore stop */
},
load: async (uri: string) => {
if (uri.startsWith('data:')) {
// A data URI with a huge size may fail opening with a browser due to the limitation of URL length.
// If received a data URI, try to open it with a converted Blob URL.
debugPreview(
'Loading page: Detected to load data URI. Try to convert to Blob URL and open it in the browser.'
)
const [response] = await Promise.all([
page.waitForNavigation({
timeout: 5000,
waitUntil: 'domcontentloaded',
}),
page.evaluate(async (uri) => {
const res = await fetch(uri, { cache: 'no-cache' })
const blob = await res.blob()
location.href = URL.createObjectURL(blob)
}, uri),
])
debugPreview('Loaded: %s', response?.url())
} else {
debugPreview('Loading page: %s', uri)
await page.goto(uri, { timeout: 0, waitUntil: 'domcontentloaded' })
debugPreview('Loaded: %s', uri)
}
await page.createCDPSession().then((session) => {
session.send('Page.resetNavigationHistory').catch(() => {
// No ops
})
})
},
})
}
private async createWindow() {
debugPreview('Trying to create new window')
try {
return this.createWindowObject(
await new Promise<Page>((res, rej) => {
const pptr = this.puppeteer
if (!pptr) {
debugPreview('Ignored: Puppeteer instance is not available')
return rej(false)
}
const id = nanoid()
const idMatcher = (target: Target) => {
debugPreview('Activated the window finder for %s.', id)
const url = new URL(target.url())
if (url.searchParams.get('__marp_cli_id') === id) {
debugPreview('Found a target window with id: %s', id)
pptr.off('targetcreated', idMatcher)
void (async () => {
res((await target.page()) ?? (await target.asPage()))
})()
}
}
pptr.on('targetcreated', idMatcher)
// Open new window with specific identifier
void (async () => {
const [page] = await pptr.pages()
debugPreview('Opening a new window... (id: %s)', id)
await page.evaluate(
`window.open('about:blank?__marp_cli_id=${id}', '', 'width=${this.options.width},height=${this.options.height}')`
)
})()
}).then(async (page) => {
const sizeCorrection = await page.evaluate(
([w, h]) => {
const nw = w - window.innerWidth + w
const nh = h - window.innerHeight + h
window.resizeTo(nw, nh)
return [nw, nh]
},
[this.options.width, this.options.height]
)
debugPreview('Apply window size correction: %o', sizeCorrection)
debugPreview('Created new window: %s', page.url())
return page
})
)
} catch (e: unknown) {
if (!e) return false
throw e
}
}
private async launch(): Promise<Preview.Window> {
const browser = await this.browserManager.browserForPreview()
this.puppeteerInternal = await browser.launch({
args: [
`--app=${emptyPageURI}`,
`--window-size=${this.options.width},${this.options.height}`,
],
defaultViewport: null,
headless: process.env.NODE_ENV === 'test',
ignoreDefaultArgs: ['--enable-automation'],
})
const handlePageOnClose = async () => {
debugPreview('Page closed')
const pagesCount = (await this.puppeteer?.pages())?.length ?? 0
debugPreview('Remaining pages count: %d', pagesCount)
if (pagesCount === 0) await this.exit()
}
this.puppeteerInternal.on('targetcreated', (target) => {
debugPreview('Target created: %o', target.url())
// NOTE: PDF viewer on headfull Chrome may return `null`.
target.page().then((page) => page?.on('close', handlePageOnClose))
})
const [page] = await this.puppeteerInternal.pages()
await page.goto(emptyPageURI, { waitUntil: 'domcontentloaded' })
let windowObject: Preview.Window | undefined
/* c8 ignore start */
if (process.platform === 'darwin') {
// An initial app window is not using in macOS for correct handling activation from Dock
windowObject = (await this.createWindow()) || undefined
await page.close()
}
/* c8 ignore stop */
page.on('close', handlePageOnClose)
this.emit('launch')
return windowObject || this.createWindowObject(page)
}
}
export function fileToURI(file: File, type: ConvertType) {
if (file.type === FileType.File) {
// Convert path to file URI
const uri = file.absolutePath.replace(/\\/g, '/')
return encodeURI(`file://${uri.startsWith('/') ? '' : '/'}${uri}`)
}
if (file.buffer) {
// Convert to data scheme URI
return `data:${mimeTypes[type]};base64,${file.buffer.toString('base64')}`
}
error('Processing file is not convertible to URI for preview.')
}