og/lib/render.js

73 lines
1.7 KiB
JavaScript
Raw Normal View History

2023-12-21 09:21:41 -05:00
import puppeteer from 'puppeteer'
2023-08-02 18:37:47 -04:00
import fs from 'node:fs'
2023-09-10 14:48:50 -04:00
const style = fs.readFileSync('./assets/style.css', 'utf8')
2023-08-02 18:37:47 -04:00
2023-12-21 09:21:41 -05:00
const browser = await puppeteer.launch({
defaultViewport: {
width: 1200,
height: 600
},
headless: 'new',
// slowMo: 250,
args: [
// TODO: fix this
'--disable-gpu',
'--disable-dev-shm-usage',
'--disable-setuid-sandbox',
'--no-sandbox'
]
})
async function wait() {
const selectors = [...document.querySelectorAll('img')]
await Promise.all([
document.fonts.ready,
...selectors.map(img => {
// Image has already finished loading, lets see if it worked
if (img.complete) {
// Image loaded and has presence
if (img.naturalHeight !== 0) return
// Image failed, so it has no height
throw new Error('Image failed to load')
}
// Image hasnt loaded yet, added an event listener to know when it does
return new Promise((resolve, reject) => {
img.addEventListener('load', resolve)
img.addEventListener('error', reject)
})
})
])
}
export async function renderPage(html) {
const page = await browser.newPage()
try {
await page.setContent(html, {
waitUntil: 'domcontentloaded'
})
await page.evaluate(wait)
const buffer = await page.screenshot({
type: 'png',
encoding: 'binary'
})
await page.close()
return buffer
} catch {
await page.close()
throw new Error('Failed to render page')
}
}
2023-08-03 10:49:25 -04:00
export default async function (html, options = {}) {
2023-12-21 09:21:41 -05:00
if (options.format == 'html') {
return await renderHtml(html)
}
return renderPage(`<style>${style}</style>${html}`)
2023-08-02 18:37:47 -04:00
}
2023-08-02 19:54:54 -04:00
export async function renderHtml(html) {
2023-09-10 14:48:50 -04:00
const styleNow = await fs.promises.readFile('./assets/style.css', 'utf8')
2023-12-21 09:21:41 -05:00
return `<style>${styleNow}</style>${html}`
2023-08-02 19:54:54 -04:00
}