56 lines
2.3 KiB
JavaScript
56 lines
2.3 KiB
JavaScript
// The HTML document around the app's streamed body. bankai owns the
|
|||
|
|
// <head> (charset, viewport, title, asset links) and the tail
|
||
|
|
// (window.initialState + </html>); the app's view owns <body>.
|
||
|
|
// Page scripts live in <head> (type=module defers itself); the one
|
||
|
|
// exception is the initialState script, which must be inline and is
|
||
|
|
// emitted after the body — inline scripts execute during parse, module
|
||
|
|
// scripts only after it, so the order still holds.
|
||
|
|
|
||
|
|
export function documentHead ({ title, css = [], modulepreload = [], scripts = [] }) {
|
||
|
|
let head = '<!doctype html>\n<html lang="en">\n<head>\n<meta charset="utf-8">\n<meta name="viewport" content="width=device-width, initial-scale=1">\n'
|
||
|
|
if (title) head += `<title>${escapeHtml(title)}</title>\n`
|
||
|
|
for (const href of css) {
|
||
|
|
head += `<link rel="stylesheet" href="${escapeHtml(href)}">\n`
|
||
|
|
}
|
||
|
|
for (const href of modulepreload) {
|
||
|
|
head += `<link rel="modulepreload" href="${escapeHtml(href)}">\n`
|
||
|
|
}
|
||
|
|
for (const src of scripts) {
|
||
|
|
head += `<script type="module" src="${escapeHtml(src)}"></script>\n`
|
||
|
|
}
|
||
|
|
head += '</head>\n'
|
||
|
|
return head
|
||
|
|
}
|
||
|
|
|
||
|
|
export function documentTail (state) {
|
||
|
|
return `\n<script>window.initialState=${serializeState(state)}</script>\n</html>\n`
|
||
|
|
}
|
||
|
|
|
||
|
|
// choo internals that every boot recomputes \u2014 no point shipping them
|
||
|
|
const RECOMPUTED = new Set(['events', 'cache', 'prefetch'])
|
||
|
|
|
||
|
|
// JSON that is safe to embed in an inline <script>: no '</script>' or
|
||
|
|
// '<!--' breakouts, no raw line separators
|
||
|
|
export function serializeState (state) {
|
||
|
|
return JSON.stringify(state, function (key, value) {
|
||
|
|
if (this === state && RECOMPUTED.has(key)) return undefined
|
||
|
|
return value
|
||
|
|
})
|
||
|
|
.replace(/</g, '\\u003c')
|
||
|
|
.replace(/\u2028/g, '\\u2028')
|
||
|
|
.replace(/\u2029/g, '\\u2029')
|
||
|
|
}
|
||
|
|
|
||
|
|
// Early Hints / Link header values for a route's assets
|
||
|
|
export function assetLinks ({ css = [], modulepreload = [], scripts = [] }) {
|
||
|
|
const links = []
|
||
|
|
for (const href of scripts) links.push(`<${href}>; rel=modulepreload`)
|
||
|
|
for (const href of modulepreload) links.push(`<${href}>; rel=modulepreload`)
|
||
|
|
for (const href of css) links.push(`<${href}>; rel=preload; as=style`)
|
||
|
|
return links
|
||
|
|
}
|
||
|
|
|
||
|
|
function escapeHtml (str) {
|
||
|
|
return String(str).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"')
|
||
|
|
}
|