UNPKG

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