53 lines
2.7 KiB
JavaScript
53 lines
2.7 KiB
JavaScript
import { randomBytes } from 'node:crypto'
|
|
|
|
// A separate document keeps the main application's strict image/script policy intact.
|
|
// The sandbox has no same-origin access; only this nonce-protected sizing bridge runs.
|
|
export function htmlPreviewDocument({ dark = false, remoteImages = false } = {}) {
|
|
const nonce = randomBytes(24).toString('base64')
|
|
const background = dark ? '#222225' : '#ffffff',
|
|
foreground = dark ? '#eeeef0' : '#252329',
|
|
accent = dark ? '#b49aef' : '#6d3bd1'
|
|
const csp = `default-src 'none'; img-src data:${remoteImages ? ' https:' : ''}; style-src 'unsafe-inline'; script-src 'nonce-${nonce}'; base-uri 'none'; form-action 'none'; frame-ancestors 'self'; sandbox allow-scripts`
|
|
const html = `<!doctype html><html><head><meta charset="utf-8"><meta name="color-scheme" content="${dark ? 'dark' : 'light'}"><style>
|
|
html,body{margin:0;background:${background};color:${foreground};color-scheme:${dark ? 'dark' : 'light'}}
|
|
body{font:14px/1.6 Arial,sans-serif;overflow-wrap:anywhere}
|
|
#mail-content{display:flow-root;padding:16px;box-sizing:border-box;min-width:0}
|
|
#mail-content>:first-child{margin-top:0}#mail-content>:last-child{margin-bottom:0}
|
|
img{max-width:100%;height:auto}table{max-width:100%;border-collapse:collapse}pre{white-space:pre-wrap}
|
|
blockquote{border-left:3px solid ${accent};margin-left:0;padding-left:16px}a{color:${accent}}
|
|
${dark ? `#mail-content,#mail-content *:not(img){color:${foreground}!important;background-color:transparent!important;border-color:#494950!important}#mail-content a,#mail-content a *{color:${accent}!important}` : ''}
|
|
</style></head><body><div id="mail-content"></div><script nonce="${nonce}">
|
|
(() => {
|
|
const channel = location.hash.slice(1), root = document.getElementById('mail-content');
|
|
let scheduled = false, lastHeight = 0;
|
|
function report() {
|
|
if (scheduled) return;
|
|
scheduled = true;
|
|
requestAnimationFrame(() => {
|
|
scheduled = false;
|
|
const height = Math.max(1, Math.ceil(root.getBoundingClientRect().height));
|
|
if (height !== lastHeight) {
|
|
lastHeight = height;
|
|
parent.postMessage({ type: 'syncova-preview-size', channel, height }, '*');
|
|
}
|
|
});
|
|
}
|
|
addEventListener('message', (event) => {
|
|
const data = event.data;
|
|
if (event.source !== parent || data?.type !== 'syncova-preview-content' ||
|
|
data.channel !== channel || typeof data.html !== 'string') return;
|
|
root.innerHTML = data.html;
|
|
root.querySelectorAll('img').forEach(image => {
|
|
image.referrerPolicy = 'no-referrer';
|
|
image.addEventListener('load', report);
|
|
image.addEventListener('error', report);
|
|
});
|
|
report();
|
|
});
|
|
new ResizeObserver(report).observe(root);
|
|
addEventListener('resize', report);
|
|
})();
|
|
</script></body></html>`
|
|
return { html, csp }
|
|
}
|