|
| 1 | +import React, { createElement } from "react"; |
| 2 | +import { writable, type Readable } from "svelte/store"; |
| 3 | +import type ReactDOMServer from "react-dom/server"; |
| 4 | +import { getContext, onDestroy } from "svelte"; |
| 5 | +import type { TreeNode } from "./internal/types"; |
| 6 | + |
| 7 | +export default function hooks<T>( |
| 8 | + callback: () => T, |
| 9 | + ReactDOMClient?: any, |
| 10 | + renderToString?: typeof ReactDOMServer.renderToString |
| 11 | +): Readable<T | undefined> { |
| 12 | + const store = writable<T | undefined>(); |
| 13 | + |
| 14 | + const parent = getContext<TreeNode | undefined>("ReactWrapper"); |
| 15 | + function Hook() { |
| 16 | + store.set(callback()); |
| 17 | + return null; |
| 18 | + } |
| 19 | + |
| 20 | + if (parent) { |
| 21 | + const hook = { Hook, key: getKey(parent) }; |
| 22 | + parent.hooks.update(($hooks) => [...$hooks, hook]); |
| 23 | + onDestroy(() => { |
| 24 | + parent.hooks.update(($hooks) => $hooks.filter((entry) => entry !== hook)); |
| 25 | + }); |
| 26 | + } else if (ReactDOMClient) { |
| 27 | + onDestroy(standalone(Hook, ReactDOMClient, renderToString)); |
| 28 | + } else if (typeof window !== "undefined") { |
| 29 | + throw new Error( |
| 30 | + "The ReactDOMClient parameter is required for hooks(), because no parent component was a sveltified React component" |
| 31 | + ); |
| 32 | + } |
| 33 | + return store; |
| 34 | +} |
| 35 | + |
| 36 | +function standalone( |
| 37 | + Hook: React.FC, |
| 38 | + ReactDOMClient: any, |
| 39 | + renderToString?: typeof ReactDOMServer.renderToString |
| 40 | +) { |
| 41 | + if (typeof document === "undefined") { |
| 42 | + if (!renderToString) { |
| 43 | + throw new Error("renderToString parameter is required for SSR"); |
| 44 | + } |
| 45 | + renderToString(createElement(Hook)); |
| 46 | + return () => {}; |
| 47 | + } |
| 48 | + const el = document.createElement("react-hooks"); |
| 49 | + const root = ReactDOMClient.createRoot?.(el); |
| 50 | + if (root) { |
| 51 | + root.render(createElement(Hook)); |
| 52 | + } else { |
| 53 | + ReactDOMClient.render(createElement(Hook), el); |
| 54 | + } |
| 55 | + return () => { |
| 56 | + if (root) { |
| 57 | + root.unmount(); |
| 58 | + } else { |
| 59 | + ReactDOMClient.unmountComponentAtNode(el); |
| 60 | + } |
| 61 | + }; |
| 62 | +} |
| 63 | + |
| 64 | +const autokeys = new WeakMap(); |
| 65 | +function getKey(node: TreeNode | undefined) { |
| 66 | + if (!node) { |
| 67 | + return undefined; |
| 68 | + } |
| 69 | + let autokey = autokeys.get(node); |
| 70 | + if (autokey === undefined) { |
| 71 | + autokey = 0; |
| 72 | + } else { |
| 73 | + autokey += 1; |
| 74 | + } |
| 75 | + autokeys.set(node, autokey); |
| 76 | + return autokey; |
| 77 | +} |
0 commit comments