mirror of https://github.com/sgoudham/carbon.git
You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
61 lines
1.5 KiB
JavaScript
61 lines
1.5 KiB
JavaScript
7 years ago
|
/* global domtoimage */
|
||
7 years ago
|
const ARBITRARY_WAIT_TIME = 500
|
||
7 years ago
|
|
||
7 years ago
|
module.exports = browser => async (req, res) => {
|
||
7 years ago
|
const page = await browser.newPage()
|
||
|
const { state } = req.body
|
||
7 years ago
|
|
||
7 years ago
|
if (!state) res.status(400).send()
|
||
7 years ago
|
|
||
|
try {
|
||
6 years ago
|
await page.goto(`http://carbon.now.sh?state=${state}`)
|
||
|
await page.addScriptTag({ path: './customDomToImage.js' })
|
||
7 years ago
|
|
||
7 years ago
|
// wait for page to detect language
|
||
|
await delay(ARBITRARY_WAIT_TIME)
|
||
|
|
||
7 years ago
|
const targetElement = await page.$('#export-container')
|
||
|
|
||
6 years ago
|
const dataUrl = await page.evaluate((target = document) => {
|
||
7 years ago
|
const config = {
|
||
|
style: {
|
||
|
transform: 'scale(2)',
|
||
|
'transform-origin': 'center'
|
||
|
},
|
||
7 years ago
|
filter: n => {
|
||
|
// %[00 -> 19] cause failures
|
||
|
if (
|
||
6 years ago
|
n.innerText &&
|
||
|
n.innerText.match(/%\S\S/) &&
|
||
7 years ago
|
n.className &&
|
||
|
n.className.startsWith('cm-') // is CodeMirror primitive string
|
||
|
) {
|
||
6 years ago
|
n.innerText = encodeURIComponent(n.innerText)
|
||
7 years ago
|
}
|
||
|
if (n.className) {
|
||
|
return String(n.className).indexOf('eliminateOnRender') < 0
|
||
|
}
|
||
|
return true
|
||
|
},
|
||
7 years ago
|
width: target.offsetWidth * 2,
|
||
|
height: target.offsetHeight * 2
|
||
|
}
|
||
|
|
||
|
return domtoimage.toPng(target, config)
|
||
|
}, targetElement)
|
||
|
|
||
|
res.status(200).json({ dataUrl })
|
||
|
} catch (e) {
|
||
7 years ago
|
// eslint-disable-next-line
|
||
7 years ago
|
console.error(e)
|
||
|
res.status(500).send()
|
||
|
} finally {
|
||
|
await page.close()
|
||
|
}
|
||
|
}
|
||
7 years ago
|
|
||
|
// private
|
||
|
function delay(ms) {
|
||
|
return new Promise(r => setTimeout(r, ms))
|
||
|
}
|