UNPKG

next-lazy-hydrate

Version:

A template for creating npm packages using TypeScript and VSCode

233 lines (227 loc) 10.9 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __rest = (this && this.__rest) || function (s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const jsx_runtime_1 = require("react/jsx-runtime"); /** MIT License Copyright (c) 2019 Valentin Colmant Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // https://github.com/valcol/react-hydration-on-demand/blob/master/src/index.js /* eslint-disable @typescript-eslint/no-misused-promises */ /* eslint-disable @typescript-eslint/no-unsafe-call */ /* eslint-disable @typescript-eslint/no-unsafe-member-access */ const react_1 = __importStar(require("react")); const react_dom_1 = __importDefault(require("react-dom")); const isClientSide = typeof window !== 'undefined'; const eventListenerOptions = { once: true, capture: true, passive: true, }; const getDisplayName = (WrappedComponent) => { return WrappedComponent.displayName || WrappedComponent.name || 'Component'; }; const withHydrationOnDemandServerSide = ({ wrapperProps }) => (WrappedComponent) => (_a) => { var props = __rest(_a, []); return ((0, jsx_runtime_1.jsx)("section", Object.assign({ "data-hydration-on-demand": true }, wrapperProps, { children: (0, jsx_runtime_1.jsx)(WrappedComponent, Object.assign({}, props)) }))); }; const withHydrationOnDemandClientSide = ({ disableFallback = false, isInputPendingFallbackValue = true, on = [], onBefore, whenInputPending = false, wrapperProps, compatibleMode, }) => (WrappedComponent) => { const WithHydrationOnDemand = (_a) => { var { forceHydration = false } = _a, props = __rest(_a, ["forceHydration"]); const rootRef = (0, react_1.useRef)(null); const cleanupFunctions = (0, react_1.useRef)([]); const isInputPending = () => { var _a, _b; // eslint-disable-next-line const isInputPending = (_b = (_a = navigator === null || navigator === void 0 ? void 0 : navigator.scheduling) === null || _a === void 0 ? void 0 : _a.isInputPending) === null || _b === void 0 ? void 0 : _b.call(_a); // eslint-disable-next-line @typescript-eslint/no-unsafe-return return isInputPending !== null && isInputPending !== void 0 ? isInputPending : isInputPendingFallbackValue; }; const getDefaultHydrationState = () => { const isNotInputPending = whenInputPending && !isInputPending(); return (isNotInputPending || forceHydration) && !onBefore; }; const [isHydrated, setIsHydrated] = (0, react_1.useState)(getDefaultHydrationState()); const cleanUp = () => { cleanupFunctions.current.forEach(fn => fn()); cleanupFunctions.current = []; }; const hydrate = () => __awaiter(void 0, void 0, void 0, function* () { cleanUp(); if (isHydrated) return; let result = null; if (onBefore) { result = (yield onBefore()).default; } setIsHydrated(true); const el = rootRef.current; if (!compatibleMode && result) { if (el) { const action = el.hasChildNodes() ? 'hydrate' : 'render'; react_dom_1.default[action](react_1.default.createElement(result, props), el); } return; } }); const initDOMEvent = (type, getTarget = () => rootRef.current) => { const target = getTarget(); target === null || target === void 0 ? void 0 : target.addEventListener(type, hydrate, eventListenerOptions); cleanupFunctions.current.push(() => { if (!target) return; target.removeEventListener(type, hydrate, eventListenerOptions); }); }; const initTimeout = (delay = 2000) => { if (delay <= 0) return; const timeout = setTimeout(hydrate, delay); cleanupFunctions.current.push(() => clearTimeout(timeout)); }; const initIdleCallback = () => { if (!('requestIdleCallback' in window)) { initTimeout(); return; } const idleCallback = requestIdleCallback(() => requestAnimationFrame(() => hydrate()), { timeout: 500, }); if (!('cancelIdleCallback' in window)) return; cleanupFunctions.current.push(() => { cancelIdleCallback(idleCallback); }); }; const initIntersectionObserver = (getOptions = Function.prototype) => { if (!('IntersectionObserver' in window)) { void hydrate(); return; } if (!rootRef.current) { void hydrate(); return; } const options = getOptions(); const observer = new IntersectionObserver(([entry]) => { if (!entry.isIntersecting || !(entry.intersectionRatio > 0)) return; void hydrate(); }, options); cleanupFunctions.current.push(() => { if (!observer) return; observer.disconnect(); }); observer.observe(rootRef.current); }; const initEvent = (type, options) => { switch (type) { case 'delay': initTimeout(options); break; case 'visible': initIntersectionObserver(options); break; case 'idle': initIdleCallback(); break; default: initDOMEvent(type, options); } }; (0, react_1.useLayoutEffect)(() => { var _a; if (isHydrated) return; if (forceHydration) { void hydrate(); return; } const wasRenderedServerSide = !!((_a = rootRef.current) === null || _a === void 0 ? void 0 : _a.getAttribute('data-hydration-on-demand')); const shouldHydrate = !wasRenderedServerSide && !disableFallback; if (shouldHydrate) void hydrate(); }, [forceHydration]); (0, react_1.useEffect)(() => { if (isHydrated) return; on.forEach(event => Array.isArray(event) ? initEvent(...event) : initEvent(event)); return cleanUp; }, []); if (!isHydrated) return ((0, jsx_runtime_1.jsx)("section", Object.assign({ ref: rootRef, dangerouslySetInnerHTML: { __html: '' }, suppressHydrationWarning: true }, wrapperProps))); if (isHydrated && compatibleMode) { return ((0, jsx_runtime_1.jsx)("section", Object.assign({}, wrapperProps, { children: (0, jsx_runtime_1.jsx)(WrappedComponent, Object.assign({}, props)) }))); } return ((0, jsx_runtime_1.jsx)("section", Object.assign({ ref: rootRef, dangerouslySetInnerHTML: { __html: '' }, suppressHydrationWarning: true }, wrapperProps))); }; WithHydrationOnDemand.displayName = `withHydrationOnDemand(${getDisplayName(WrappedComponent)})`; return WithHydrationOnDemand; }; const withHydrationOnDemand = (options = {}) => { if (isClientSide) return withHydrationOnDemandClientSide(options); return withHydrationOnDemandServerSide(options); }; exports.default = withHydrationOnDemand;