UNPKG

jotai

Version:

👻 Next gen state management that will spook you

287 lines (280 loc) • 10.5 kB
import { useRef, useEffect, useContext, useState, useCallback } from 'react'; import { useAtom, SECRET_INTERNAL_getScopeContext } from 'jotai'; function useAtomDevtools(anAtom, options, deprecatedScope) { if (typeof options === "string" || typeof deprecatedScope !== "undefined") { console.warn("DEPRECATED [useAtomDevtools] use DevtoolOptions"); options = { name: options, scope: deprecatedScope }; } const { enabled, name, scope } = options || {}; let extension; try { extension = (enabled != null ? enabled : (import.meta.env && import.meta.env.MODE) !== "production") && window.__REDUX_DEVTOOLS_EXTENSION__; } catch { } if (!extension) { if ((import.meta.env && import.meta.env.MODE) !== "production" && enabled) { console.warn("Please install/enable Redux devtools extension"); } } const [value, setValue] = useAtom(anAtom, scope); const lastValue = useRef(value); const isTimeTraveling = useRef(false); const devtools = useRef(); const atomName = name || anAtom.debugLabel || anAtom.toString(); useEffect(() => { if (!extension) { return; } const setValueIfWritable = (value2) => { if (typeof setValue === "function") { setValue(value2); return; } console.warn("[Warn] you cannot do write operations (Time-travelling, etc) in read-only atoms\n", anAtom); }; devtools.current = extension.connect({ name: atomName }); const unsubscribe = devtools.current.subscribe((message) => { var _a, _b, _c, _d, _e, _f; if (message.type === "ACTION" && message.payload) { try { setValueIfWritable(JSON.parse(message.payload)); } catch (e) { console.error("please dispatch a serializable value that JSON.parse() support\n", e); } } else if (message.type === "DISPATCH" && message.state) { if (((_a = message.payload) == null ? void 0 : _a.type) === "JUMP_TO_ACTION" || ((_b = message.payload) == null ? void 0 : _b.type) === "JUMP_TO_STATE") { isTimeTraveling.current = true; setValueIfWritable(JSON.parse(message.state)); } } else if (message.type === "DISPATCH" && ((_c = message.payload) == null ? void 0 : _c.type) === "COMMIT") { (_d = devtools.current) == null ? void 0 : _d.init(lastValue.current); } else if (message.type === "DISPATCH" && ((_e = message.payload) == null ? void 0 : _e.type) === "IMPORT_STATE") { const computedStates = ((_f = message.payload.nextLiftedState) == null ? void 0 : _f.computedStates) || []; computedStates.forEach(({ state }, index) => { var _a2; if (index === 0) { (_a2 = devtools.current) == null ? void 0 : _a2.init(state); } else { setValueIfWritable(state); } }); } }); devtools.current.shouldInit = true; return unsubscribe; }, [anAtom, extension, atomName, setValue]); useEffect(() => { if (!devtools.current) { return; } lastValue.current = value; if (devtools.current.shouldInit) { devtools.current.init(value); devtools.current.shouldInit = false; } else if (isTimeTraveling.current) { isTimeTraveling.current = false; } else { devtools.current.send(`${atomName} - ${new Date().toLocaleString()}`, value); } }, [anAtom, extension, atomName, value]); } const RESTORE_ATOMS = "h"; const DEV_SUBSCRIBE_STATE = "n"; const DEV_GET_MOUNTED_ATOMS = "l"; const DEV_GET_ATOM_STATE = "a"; const DEV_GET_MOUNTED = "m"; const createAtomsSnapshot = (store, atoms) => { const tuples = atoms.map((atom) => { var _a, _b; const atomState = (_b = (_a = store[DEV_GET_ATOM_STATE]) == null ? void 0 : _a.call(store, atom)) != null ? _b : {}; return [atom, "v" in atomState ? atomState.v : void 0]; }); return new Map(tuples); }; function useAtomsSnapshot(scope) { const ScopeContext = SECRET_INTERNAL_getScopeContext(scope); const scopeContainer = useContext(ScopeContext); const store = scopeContainer.s; if (!store[DEV_SUBSCRIBE_STATE]) { throw new Error("useAtomsSnapshot can only be used in dev mode."); } const [atomsSnapshot, setAtomsSnapshot] = useState(() => /* @__PURE__ */ new Map()); useEffect(() => { var _a; const callback = () => { var _a2; const atoms = Array.from(((_a2 = store[DEV_GET_MOUNTED_ATOMS]) == null ? void 0 : _a2.call(store)) || []); setAtomsSnapshot(createAtomsSnapshot(store, atoms)); }; const unsubscribe = (_a = store[DEV_SUBSCRIBE_STATE]) == null ? void 0 : _a.call(store, callback); callback(); return unsubscribe; }, [store]); return atomsSnapshot; } function useGotoAtomsSnapshot(scope) { const ScopeContext = SECRET_INTERNAL_getScopeContext(scope); const scopeContainer = useContext(ScopeContext); const store = scopeContainer.s; if (!store[DEV_SUBSCRIBE_STATE]) { throw new Error("useGotoAtomsSnapshot can only be used in dev mode."); } return useCallback((values) => { store[RESTORE_ATOMS](values); }, [store]); } const isEqualAtomsValues = (left, right) => left.size === right.size && Array.from(left).every(([left2, v]) => Object.is(right.get(left2), v)); const isEqualAtomsDependents = (left, right) => left.size === right.size && Array.from(left).every(([a, dLeft]) => { const dRight = right.get(a); return dRight && dLeft.size === dRight.size && Array.from(dLeft).every((d) => dRight.has(d)); }); const atomToPrintable = (atom) => atom.debugLabel ? `${atom}:${atom.debugLabel}` : `${atom}`; const getDevtoolsState = (atomsSnapshot) => { const values = {}; atomsSnapshot[0].forEach((v, atom) => { values[atomToPrintable(atom)] = v; }); const dependents = {}; atomsSnapshot[1].forEach((d, atom) => { dependents[atomToPrintable(atom)] = Array.from(d).map(atomToPrintable); }); return { values, dependents }; }; function useAtomsDevtools(name, options) { if (typeof options !== "undefined" && typeof options !== "object") { console.warn("DEPRECATED [useAtomsDevtools] use DevtoolsOptions"); options = { scope: options }; } const { enabled, scope } = options || {}; const ScopeContext = SECRET_INTERNAL_getScopeContext(scope); const { s: store, w: versionedWrite } = useContext(ScopeContext); let extension; try { extension = (enabled != null ? enabled : (import.meta.env && import.meta.env.MODE) !== "production") && window.__REDUX_DEVTOOLS_EXTENSION__; } catch { } if (!extension) { if ((import.meta.env && import.meta.env.MODE) !== "production" && enabled) { console.warn("Please install/enable Redux devtools extension"); } } if (extension && !store[DEV_SUBSCRIBE_STATE]) { throw new Error("useAtomsDevtools can only be used in dev mode."); } const [atomsSnapshot, setAtomsSnapshot] = useState(() => [ /* @__PURE__ */ new Map(), /* @__PURE__ */ new Map() ]); useEffect(() => { var _a; if (!extension) { return; } const callback = () => { var _a2, _b, _c; const values = /* @__PURE__ */ new Map(); const dependents = /* @__PURE__ */ new Map(); for (const atom of ((_a2 = store[DEV_GET_MOUNTED_ATOMS]) == null ? void 0 : _a2.call(store)) || []) { const atomState = (_b = store[DEV_GET_ATOM_STATE]) == null ? void 0 : _b.call(store, atom); if (atomState) { if (atomState.r === atomState.i) { return; } if ("v" in atomState) { values.set(atom, atomState.v); } } const mounted = (_c = store[DEV_GET_MOUNTED]) == null ? void 0 : _c.call(store, atom); if (mounted) { dependents.set(atom, mounted.t); } } setAtomsSnapshot((prev) => { if (isEqualAtomsValues(prev[0], values) && isEqualAtomsDependents(prev[1], dependents)) { return prev; } return [values, dependents]; }); }; const unsubscribe = (_a = store[DEV_SUBSCRIBE_STATE]) == null ? void 0 : _a.call(store, callback); callback(); return unsubscribe; }, [extension, store]); const goToSnapshot = useCallback((values) => { if (versionedWrite) { versionedWrite((version) => { store[RESTORE_ATOMS](values, version); }); } else { store[RESTORE_ATOMS](values); } }, [store, versionedWrite]); const isTimeTraveling = useRef(false); const isRecording = useRef(true); const devtools = useRef(); const snapshots = useRef([]); useEffect(() => { if (!extension) { return; } const getSnapshotAt = (index = snapshots.current.length - 1) => { const snapshot = snapshots.current[index >= 0 ? index : 0]; if (!snapshot) { throw new Error("snaphost index out of bounds"); } return snapshot; }; const connection = extension.connect({ name }); const devtoolsUnsubscribe = connection.subscribe((message) => { var _a; switch (message.type) { case "DISPATCH": switch ((_a = message.payload) == null ? void 0 : _a.type) { case "RESET": break; case "COMMIT": connection.init(getDevtoolsState(getSnapshotAt())); snapshots.current = []; break; case "JUMP_TO_ACTION": case "JUMP_TO_STATE": isTimeTraveling.current = true; goToSnapshot(getSnapshotAt(message.payload.actionId - 1)[0]); break; case "PAUSE_RECORDING": isRecording.current = !isRecording.current; break; } } }); devtools.current = connection; devtools.current.shouldInit = true; return devtoolsUnsubscribe; }, [extension, goToSnapshot, name]); useEffect(() => { if (!devtools.current) { return; } if (devtools.current.shouldInit) { devtools.current.init(void 0); devtools.current.shouldInit = false; return; } if (isTimeTraveling.current) { isTimeTraveling.current = false; } else if (isRecording.current) { snapshots.current.push(atomsSnapshot); devtools.current.send({ type: `${snapshots.current.length}`, updatedAt: new Date().toLocaleString() }, getDevtoolsState(atomsSnapshot)); } }, [atomsSnapshot]); } export { useAtomDevtools, useAtomsDevtools, useAtomsSnapshot, useGotoAtomsSnapshot };