UNPKG

microsite

Version:
50 lines (49 loc) 2.94 kB
import { h, createContext, Fragment } from "preact"; import { useRef } from "preact/hooks"; import render from "preact-render-to-string"; export const __DocContext = createContext({ head: { current: [] }, hydrate: { current: [] }, }); export const __hydratedComponents = []; const unique = (value, index, self) => self.indexOf(value) === index; export const Document = ({ hydrateExportManifest, page, styles = [], hasScripts = false, globalStyle, children, }) => { const head = useRef([]); const hydrate = useRef([]); const subtree = render(h(__DocContext.Provider, { value: { head, hydrate } }, children), {}, { pretty: true }); const components = hydrate.current.map(({ name }) => name).filter(unique); if (hydrate.current.length > 0) __hydratedComponents.push({ page, components }); const componentStyles = components .map((name) => { const found = hydrateExportManifest.find((entry) => entry.exports.find(([_key, n]) => n === name)); if (found) return found.styles; return null; }) .filter((v) => v) .filter(unique); return (h("html", { lang: "en", dir: "ltr" }, h("head", null, h("meta", Object.assign({}, { charset: "utf-8" })), h("meta", { name: "viewport", content: "width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=5.0" }), h(Fragment, null, head.current), globalStyle && (h("link", { rel: "stylesheet", href: `/_hydrate/styles/${globalStyle}` })), componentStyles && componentStyles.map((href) => (h("link", { rel: "stylesheet", href: `/_hydrate/styles/${href}` }))), styles.map((style) => (h("style", { dangerouslySetInnerHTML: { __html: style.trim() } }))), hydrate.current.length > 0 && (h("style", { dangerouslySetInnerHTML: { __html: "[data-hydrate]{display:contents;}", } })), hydrate.current.length > 0 && (h(Fragment, null, h("link", { rel: "modulepreload", href: "https://unpkg.com/preact@latest?module" }), h("link", { rel: "modulepreload", href: "https://unpkg.com/preact@latest/hooks/dist/hooks.module.js?module" }), h("link", { rel: "modulepreload", href: `/_hydrate/pages/${page}.js` })))), h("body", null, h("div", { id: "__microsite", dangerouslySetInnerHTML: { __html: subtree } }), hydrate.current.length > 0 && (h("script", { type: "module", defer: true, src: `/_hydrate/pages/${page}.js` })), hasScripts ? (h(Fragment, null, h("script", { type: "module", src: "/index.js" }), h("script", Object.assign({}, { nomodule: "" }, { src: "https://unpkg.com/systemjs@2.0.0/dist/s.min.js" })), h("script", Object.assign({}, { nomodule: "" }, { src: "/index.legacy.js" })))) : null))); };