UNPKG

microsite

Version:
30 lines (29 loc) 1.55 kB
import { h, createContext } from "preact"; import { useContext } from "preact/hooks"; const isServer = typeof window === "undefined"; const btoa = (str) => Buffer.from(str, "utf-8").toString("base64"); export const HydrateContext = createContext(false); export function withHydrate(Component, hydrationProps = {}) { const name = Component.displayName || Component.name; const { method = "idle" } = hydrationProps; const Wrapped = (props, ref) => { const hydrateParent = useContext(HydrateContext); if (hydrateParent) throw new Error(`withHydrate() should only be called at the top-level of a Component tree. <${name} /> should not be nested within <${hydrateParent} />`); if (props.children && !["string", "number"].includes(typeof props.children)) throw new Error(`withHydrate() is unable to serialize complex \`children\`. Please inline these children into <${name} />.`); return (h(HydrateContext.Provider, { value: name }, h("div", Object.assign({}, (isServer ? { "data-hydrate": name, "data-props": Object.keys(props).length > 0 ? btoa(JSON.stringify(props)) : null, "data-method": method, } : {})), h(Component, Object.assign({}, Object.assign(Object.assign({}, props), { ref })))))); }; Object.defineProperty(Wrapped, "name", { value: name, configurable: true }); return Wrapped; }