import React, { Fragment, hydrate, render, useContext, useEffect, useState, } from "react"; import { isNode } from "sosse/uni"; const emptyFunc = () => {}; type Options = { id: string; component: () => T; container?: Function; suspense?: Function; lazy?: boolean; ssr?: boolean; wrapper?: any[]; }; type ThenArg = T extends PromiseLike ? U : T; let components: Record = {}; const injectCache: Record = {}; export const preload = async function () { const importPromises = []; for (const [id, { component, ssr }] of Object.entries(injectCache)) { if (!ssr) { continue; } const importPromise = (async () => { components[id] = await component(); })(); importPromises.push(importPromise); } await Promise.all(importPromises); }; export const inject = function ({ logInjects = process.env.NODE_ENV !== "production", } = {}) { let jsonElList = document.getElementsByClassName(`sosse-interactive`); if (jsonElList.length === 0) { return; } const componentPromises: Record = {}; const jsonEls = Array.from(jsonElList); jsonEls.forEach(async (el) => { const id = el["dataset"].interactive; const { component, ssr, suspense, lazy, wrapper } = injectCache[id]; const ASuspense = suspense; componentPromises[id] = componentPromises[id] || (async () => { let ComponentPromise = component(); return ASuspense ? React.lazy(async () => ({ default: await ComponentPromise })) : await ComponentPromise; })(); const LoadingComponent = await componentPromises[id]; const containerEl = el.nextElementSibling; const aInject = function () { if (logInjects) { console.info("Injected: " + id); } const props = JSON.parse(el.innerHTML); let vdom = ; if (wrapper.length) { for (const Wrapper of wrapper) { vdom = {vdom}; } } if (ASuspense) { vdom = {vdom}; } const injector = ssr ? hydrate : render; injector(vdom, containerEl); }; if (lazy) { new IntersectionObserver(([entry], obs) => { if (!entry.isIntersecting) return; obs.unobserve(containerEl); aInject(); }).observe(containerEl); } else { aInject(); } }); }; const defaultContainer = function ({ children }) { return
{children}
; }; export const interactive = function >({ id, container = defaultContainer, component, suspense, lazy = false, ssr = false, wrapper = [], }: Options): C { if (suspense && ssr) { console.warn("Using suspense and ssr together isn't supported"); } lazy = lazy && typeof IntersectionObserver === "function"; injectCache[id] = { component, ssr, suspense: !ssr && suspense, lazy, wrapper, }; if (isNode) { const Container = container; return function (props) { const Component = components[id]; return (