UNPKG

1.71 kBJavaScriptView Raw
1import { h, createContext } from "preact";
2import { useContext } from "preact/hooks";
3import { __DocContext } from "./document.js";
4const isServer = typeof window === "undefined";
5const btoa = (str) => Buffer.from(str, "utf-8").toString("base64");
6const HydrateContext = createContext(false);
7export function withHydrate(Component, hydrationProps = {}) {
8 const name = Component.displayName || Component.name;
9 const { method = "idle" } = hydrationProps;
10 const Wrapped = (props, ref) => {
11 const { hydrate } = useContext(__DocContext);
12 const hydrateParent = useContext(HydrateContext);
13 if (hydrateParent)
14 throw new Error(`withHydrate() should only be called at the top-level of a Component tree. <${name} /> should not be nested within <${hydrateParent} />`);
15 if (isServer)
16 hydrate.current.push({ name });
17 if (props.children && !["string", "number"].includes(typeof props.children))
18 throw new Error(`withHydrate() is unable to serialize complex \`children\`. Please inline these children into <${name} />.`);
19 return (h(HydrateContext.Provider, { value: name },
20 h("div", Object.assign({}, (isServer
21 ? {
22 "data-hydrate": name,
23 "data-props": Object.keys(props).length > 0
24 ? btoa(JSON.stringify(props))
25 : null,
26 "data-method": method,
27 }
28 : {})),
29 h(Component, Object.assign({}, Object.assign(Object.assign({}, props), { ref }))))));
30 };
31 Object.defineProperty(Wrapped, "name", { value: name, configurable: true });
32 return Wrapped;
33}