og/lib/render.js
2023-12-21 10:03:32 -06:00

68 lines
1.6 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import puppeteer from 'puppeteer'
import { BASE_URL } from '../server.js'
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')
}
}
export default async function (html, options = {}) {
const fullHtml = `<link rel="stylesheet" href="${BASE_URL}/assets/style.css">
<link rel="stylesheet" href="${BASE_URL}/assets/DMSans/style.css">
${html}`
if (options.format == 'html') {
return fullHtml
}
return await renderPage(fullHtml)
}