UNPKG

2.94 kBJavaScriptView Raw
1import { h, createContext, Fragment } from "preact";
2import { useRef } from "preact/hooks";
3import render from "preact-render-to-string";
4export const __DocContext = createContext({
5 head: { current: [] },
6 hydrate: { current: [] },
7});
8export const __hydratedComponents = [];
9const unique = (value, index, self) => self.indexOf(value) === index;
10export const Document = ({ hydrateExportManifest, page, styles = [], hasScripts = false, globalStyle, children, }) => {
11 const head = useRef([]);
12 const hydrate = useRef([]);
13 const subtree = render(h(__DocContext.Provider, { value: { head, hydrate } }, children), {}, { pretty: true });
14 const components = hydrate.current.map(({ name }) => name).filter(unique);
15 if (hydrate.current.length > 0)
16 __hydratedComponents.push({ page, components });
17 const componentStyles = components
18 .map((name) => {
19 const found = hydrateExportManifest.find((entry) => entry.exports.find(([_key, n]) => n === name));
20 if (found)
21 return found.styles;
22 return null;
23 })
24 .filter((v) => v)
25 .filter(unique);
26 return (h("html", { lang: "en", dir: "ltr" },
27 h("head", null,
28 h("meta", Object.assign({}, { charset: "utf-8" })),
29 h("meta", { name: "viewport", content: "width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=5.0" }),
30 h(Fragment, null, head.current),
31 globalStyle && (h("link", { rel: "stylesheet", href: `/_hydrate/styles/${globalStyle}` })),
32 componentStyles &&
33 componentStyles.map((href) => (h("link", { rel: "stylesheet", href: `/_hydrate/styles/${href}` }))),
34 styles.map((style) => (h("style", { dangerouslySetInnerHTML: { __html: style.trim() } }))),
35 hydrate.current.length > 0 && (h("style", { dangerouslySetInnerHTML: {
36 __html: "[data-hydrate]{display:contents;}",
37 } })),
38 hydrate.current.length > 0 && (h(Fragment, null,
39 h("link", { rel: "modulepreload", href: "https://unpkg.com/preact@latest?module" }),
40 h("link", { rel: "modulepreload", href: "https://unpkg.com/preact@latest/hooks/dist/hooks.module.js?module" }),
41 h("link", { rel: "modulepreload", href: `/_hydrate/pages/${page}.js` })))),
42 h("body", null,
43 h("div", { id: "__microsite", dangerouslySetInnerHTML: { __html: subtree } }),
44 hydrate.current.length > 0 && (h("script", { type: "module", defer: true, src: `/_hydrate/pages/${page}.js` })),
45 hasScripts ? (h(Fragment, null,
46 h("script", { type: "module", src: "/index.js" }),
47 h("script", Object.assign({}, { nomodule: "" }, { src: "https://unpkg.com/systemjs@2.0.0/dist/s.min.js" })),
48 h("script", Object.assign({}, { nomodule: "" }, { src: "/index.legacy.js" })))) : null)));
49};