forked from jxnblk/repng
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
123 lines (111 loc) · 2.65 KB
/
index.js
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
require('babel-register')({
plugins: [
'babel-plugin-transform-runtime'
].map(require.resolve),
presets: [
'babel-preset-env',
'babel-preset-stage-0',
'babel-preset-react'
].map(require.resolve)
})
const fs = require('fs')
const puppeteer = require('puppeteer')
const { Readable } = require('stream')
const path = require('path')
const { createElement: h } = require('react')
const { renderToStaticMarkup } = require('react-dom/server')
const Datauri = require('datauri')
const resolveCWD = require('resolve-cwd')
const baseCSS = `*{box-sizing:border-box}body{margin:0;font-family:system-ui,sans-serif}`
const getHtmlData = ({
body,
baseCSS,
css,
styles,
webfont
}) => {
const fontCSS = webfont ? getWebfontCSS(webfont) : ''
const html = `<!DOCTYPE html>
<head>
<meta charset="utf-8"><style>${baseCSS}${fontCSS}${css}</style>
${styles}
</head>
${body}`
const htmlBuffer = Buffer.from(html, 'utf8')
const datauri = new Datauri()
datauri.format('.html', htmlBuffer)
const data = datauri.content
return data
}
const getWebfontCSS = (fontpath) => {
const { content } = new Datauri(fontpath)
const [ name, ext ] = fontpath.split('/').slice(-1)[0].split('.')
const css = (`@font-face {
font-family: '${name}';
font-style: normal;
font-weight: 400;
src: url(${content});
}`)
return css
}
module.exports = async (Component, opts = {}) => {
const {
props = {},
css = '',
filename,
outDir,
width,
height,
scale = 1,
webfont,
cssLibrary
} = opts
let body
let styles = ''
const el = h(Component, props)
switch (cssLibrary) {
case 'styled-components':
const { ServerStyleSheet } = require(resolveCWD('styled-components'))
const sheet = new ServerStyleSheet()
body = renderToStaticMarkup(
sheet.collectStyles(el)
)
styles = sheet.getStyleTags()
break
case 'emotion':
const { renderStylesToString } = require(resolveCWD('emotion-server'))
body = renderStylesToString(renderToString(el))
break
default:
body = renderToStaticMarkup(el)
}
const data = getHtmlData({
body,
baseCSS,
css,
styles,
webfont
})
// todo:
// - scale
// - delay
const browser = await puppeteer.launch()
const page = await browser.newPage()
await page.goto(data)
const result = await page.screenshot({
type: 'png',
clip: {
x: 0,
y: 0,
width: parseInt(width),
height: parseInt(height),
},
omitBackground: true
})
await browser.close()
const stream = new Readable()
stream._read = () => {}
stream.push(result)
stream.push(null)
return stream
}