UNPKG

12.8 kBJavaScriptView Raw
1'use strict';
2
3var react$1 = require('react');
4var react = require('jotai/react');
5
6function _extends() {
7 _extends = Object.assign ? Object.assign.bind() : function (target) {
8 for (var i = 1; i < arguments.length; i++) {
9 var source = arguments[i];
10 for (var key in source) {
11 if (Object.prototype.hasOwnProperty.call(source, key)) {
12 target[key] = source[key];
13 }
14 }
15 }
16 return target;
17 };
18 return _extends.apply(this, arguments);
19}
20function _unsupportedIterableToArray(o, minLen) {
21 if (!o) return;
22 if (typeof o === "string") return _arrayLikeToArray(o, minLen);
23 var n = Object.prototype.toString.call(o).slice(8, -1);
24 if (n === "Object" && o.constructor) n = o.constructor.name;
25 if (n === "Map" || n === "Set") return Array.from(o);
26 if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
27}
28function _arrayLikeToArray(arr, len) {
29 if (len == null || len > arr.length) len = arr.length;
30 for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
31 return arr2;
32}
33function _createForOfIteratorHelperLoose(o, allowArrayLike) {
34 var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
35 if (it) return (it = it.call(o)).next.bind(it);
36 if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
37 if (it) o = it;
38 var i = 0;
39 return function () {
40 if (i >= o.length) return {
41 done: true
42 };
43 return {
44 done: false,
45 value: o[i++]
46 };
47 };
48 }
49 throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
50}
51
52var atomToPrintable$1 = function atomToPrintable(atom) {
53 return atom.debugLabel || atom.toString();
54};
55var stateToPrintable = function stateToPrintable(_ref) {
56 var store = _ref[0],
57 atoms = _ref[1];
58 return Object.fromEntries(atoms.flatMap(function (atom) {
59 var mounted = store.dev_get_mounted == null ? void 0 : store.dev_get_mounted(atom);
60 if (!mounted) {
61 return [];
62 }
63 var dependents = mounted.t;
64 var atomState = (store.dev_get_atom_state == null ? void 0 : store.dev_get_atom_state(atom)) || {};
65 return [[atomToPrintable$1(atom), _extends({}, 'e' in atomState && {
66 error: atomState.e
67 }, 'v' in atomState && {
68 value: atomState.v
69 }, {
70 dependents: Array.from(dependents).map(atomToPrintable$1)
71 })]];
72 }));
73};
74var useAtomsDebugValue = function useAtomsDebugValue(options) {
75 var _options$enabled;
76 var enabled = (_options$enabled = options == null ? void 0 : options.enabled) != null ? _options$enabled : process.env.NODE_ENV !== "production";
77 var store = react.useStore(options);
78 var _useState = react$1.useState([]),
79 atoms = _useState[0],
80 setAtoms = _useState[1];
81 react$1.useEffect(function () {
82 if (!enabled) {
83 return;
84 }
85 var callback = function callback() {
86 setAtoms(Array.from((store.dev_get_mounted_atoms == null ? void 0 : store.dev_get_mounted_atoms()) || []));
87 };
88 var unsubscribe = store.dev_subscribe_state == null ? void 0 : store.dev_subscribe_state(callback);
89 callback();
90 return unsubscribe;
91 }, [enabled, store]);
92 react$1.useDebugValue([store, atoms], stateToPrintable);
93};
94
95function useAtomDevtools(anAtom, options) {
96 var _ref = options || {},
97 enabled = _ref.enabled,
98 name = _ref.name;
99 var extension;
100 try {
101 extension = (enabled != null ? enabled : process.env.NODE_ENV !== "production") && window.__REDUX_DEVTOOLS_EXTENSION__;
102 } catch (_unused) {}
103 if (!extension) {
104 if (process.env.NODE_ENV !== "production" && enabled) {
105 console.warn('Please install/enable Redux devtools extension');
106 }
107 }
108 var _useAtom = react.useAtom(anAtom),
109 value = _useAtom[0],
110 setValue = _useAtom[1];
111 var lastValue = react$1.useRef(value);
112 var isTimeTraveling = react$1.useRef(false);
113 var devtools = react$1.useRef();
114 var atomName = name || anAtom.debugLabel || anAtom.toString();
115 react$1.useEffect(function () {
116 if (!extension) {
117 return;
118 }
119 var setValueIfWritable = function setValueIfWritable(value) {
120 if (typeof setValue === 'function') {
121 setValue(value);
122 return;
123 }
124 console.warn('[Warn] you cannot do write operations (Time-travelling, etc) in read-only atoms\n', anAtom);
125 };
126 devtools.current = extension.connect({
127 name: atomName
128 });
129 var unsubscribe = devtools.current.subscribe(function (message) {
130 var _message$payload3, _message$payload4;
131 if (message.type === 'ACTION' && message.payload) {
132 try {
133 setValueIfWritable(JSON.parse(message.payload));
134 } catch (e) {
135 console.error('please dispatch a serializable value that JSON.parse() support\n', e);
136 }
137 } else if (message.type === 'DISPATCH' && message.state) {
138 var _message$payload, _message$payload2;
139 if (((_message$payload = message.payload) == null ? void 0 : _message$payload.type) === 'JUMP_TO_ACTION' || ((_message$payload2 = message.payload) == null ? void 0 : _message$payload2.type) === 'JUMP_TO_STATE') {
140 isTimeTraveling.current = true;
141 setValueIfWritable(JSON.parse(message.state));
142 }
143 } else if (message.type === 'DISPATCH' && ((_message$payload3 = message.payload) == null ? void 0 : _message$payload3.type) === 'COMMIT') {
144 var _devtools$current;
145 (_devtools$current = devtools.current) == null ? void 0 : _devtools$current.init(lastValue.current);
146 } else if (message.type === 'DISPATCH' && ((_message$payload4 = message.payload) == null ? void 0 : _message$payload4.type) === 'IMPORT_STATE') {
147 var _message$payload$next;
148 var computedStates = ((_message$payload$next = message.payload.nextLiftedState) == null ? void 0 : _message$payload$next.computedStates) || [];
149 computedStates.forEach(function (_ref2, index) {
150 var state = _ref2.state;
151 if (index === 0) {
152 var _devtools$current2;
153 (_devtools$current2 = devtools.current) == null ? void 0 : _devtools$current2.init(state);
154 } else {
155 setValueIfWritable(state);
156 }
157 });
158 }
159 });
160 devtools.current.shouldInit = true;
161 return unsubscribe;
162 }, [anAtom, extension, atomName, setValue]);
163 react$1.useEffect(function () {
164 if (!devtools.current) {
165 return;
166 }
167 lastValue.current = value;
168 if (devtools.current.shouldInit) {
169 devtools.current.init(value);
170 devtools.current.shouldInit = false;
171 } else if (isTimeTraveling.current) {
172 isTimeTraveling.current = false;
173 } else {
174 devtools.current.send(atomName + " - " + new Date().toLocaleString(), value);
175 }
176 }, [anAtom, extension, atomName, value]);
177}
178
179var isEqualAtomsValues = function isEqualAtomsValues(left, right) {
180 return left.size === right.size && Array.from(left).every(function (_ref) {
181 var left = _ref[0],
182 v = _ref[1];
183 return Object.is(right.get(left), v);
184 });
185};
186var isEqualAtomsDependents = function isEqualAtomsDependents(left, right) {
187 return left.size === right.size && Array.from(left).every(function (_ref2) {
188 var a = _ref2[0],
189 dLeft = _ref2[1];
190 var dRight = right.get(a);
191 return dRight && dLeft.size === dRight.size && Array.from(dLeft).every(function (d) {
192 return dRight.has(d);
193 });
194 });
195};
196function useAtomsSnapshot(options) {
197 var store = react.useStore(options);
198 var _useState = react$1.useState(function () {
199 return {
200 values: new Map(),
201 dependents: new Map()
202 };
203 }),
204 atomsSnapshot = _useState[0],
205 setAtomsSnapshot = _useState[1];
206 react$1.useEffect(function () {
207 if (!store.dev_subscribe_state) return;
208 var prevValues = new Map();
209 var prevDependents = new Map();
210 var callback = function callback() {
211 var values = new Map();
212 var dependents = new Map();
213 for (var _iterator = _createForOfIteratorHelperLoose(store.dev_get_mounted_atoms() || []), _step; !(_step = _iterator()).done;) {
214 var atom = _step.value;
215 var atomState = store.dev_get_atom_state(atom);
216 if (atomState) {
217 if ('v' in atomState) {
218 values.set(atom, atomState.v);
219 }
220 }
221 var mounted = store.dev_get_mounted(atom);
222 if (mounted) {
223 dependents.set(atom, mounted.t);
224 }
225 }
226 if (isEqualAtomsValues(prevValues, values) && isEqualAtomsDependents(prevDependents, dependents)) {
227 return;
228 }
229 prevValues = values;
230 prevDependents = dependents;
231 setAtomsSnapshot({
232 values: values,
233 dependents: dependents
234 });
235 };
236 var unsubscribe = store.dev_subscribe_state(callback);
237 callback();
238 return unsubscribe;
239 }, [store]);
240 return atomsSnapshot;
241}
242
243function useGotoAtomsSnapshot(options) {
244 var store = react.useStore(options);
245 return react$1.useCallback(function (snapshot) {
246 if (store.dev_subscribe_state) {
247 store.res(snapshot.values);
248 }
249 }, [store]);
250}
251
252var atomToPrintable = function atomToPrintable(atom) {
253 return atom.debugLabel ? atom + ":" + atom.debugLabel : "" + atom;
254};
255var getDevtoolsState = function getDevtoolsState(atomsSnapshot) {
256 var values = {};
257 atomsSnapshot.values.forEach(function (v, atom) {
258 values[atomToPrintable(atom)] = v;
259 });
260 var dependents = {};
261 atomsSnapshot.dependents.forEach(function (d, atom) {
262 dependents[atomToPrintable(atom)] = Array.from(d).map(atomToPrintable);
263 });
264 return {
265 values: values,
266 dependents: dependents
267 };
268};
269function useAtomsDevtools(name, options) {
270 var _ref = options || {},
271 enabled = _ref.enabled;
272 var extension;
273 try {
274 extension = (enabled != null ? enabled : process.env.NODE_ENV !== "production") && window.__REDUX_DEVTOOLS_EXTENSION__;
275 } catch (_unused) {}
276 if (!extension) {
277 if (process.env.NODE_ENV !== "production" && enabled) {
278 console.warn('Please install/enable Redux devtools extension');
279 }
280 }
281 var atomsSnapshot = useAtomsSnapshot();
282 var goToSnapshot = useGotoAtomsSnapshot();
283 var isTimeTraveling = react$1.useRef(false);
284 var isRecording = react$1.useRef(true);
285 var devtools = react$1.useRef();
286 var snapshots = react$1.useRef([]);
287 react$1.useEffect(function () {
288 if (!extension) {
289 return;
290 }
291 var getSnapshotAt = function getSnapshotAt(index) {
292 if (index === void 0) {
293 index = snapshots.current.length - 1;
294 }
295 var snapshot = snapshots.current[index >= 0 ? index : 0];
296 if (!snapshot) {
297 throw new Error('snaphost index out of bounds');
298 }
299 return snapshot;
300 };
301 var connection = extension.connect({
302 name: name
303 });
304 var devtoolsUnsubscribe = connection.subscribe(function (message) {
305 var _message$payload;
306 switch (message.type) {
307 case 'DISPATCH':
308 switch ((_message$payload = message.payload) == null ? void 0 : _message$payload.type) {
309 case 'RESET':
310 break;
311 case 'COMMIT':
312 connection.init(getDevtoolsState(getSnapshotAt()));
313 snapshots.current = [];
314 break;
315 case 'JUMP_TO_ACTION':
316 case 'JUMP_TO_STATE':
317 isTimeTraveling.current = true;
318 goToSnapshot(getSnapshotAt(message.payload.actionId - 1));
319 break;
320 case 'PAUSE_RECORDING':
321 isRecording.current = !isRecording.current;
322 break;
323 }
324 }
325 });
326 devtools.current = connection;
327 devtools.current.shouldInit = true;
328 return function () {
329 extension.disconnect();
330 devtoolsUnsubscribe == null ? void 0 : devtoolsUnsubscribe();
331 };
332 }, [extension, goToSnapshot, name]);
333 react$1.useEffect(function () {
334 if (!devtools.current) {
335 return;
336 }
337 if (devtools.current.shouldInit) {
338 devtools.current.init(undefined);
339 devtools.current.shouldInit = false;
340 return;
341 }
342 if (isTimeTraveling.current) {
343 isTimeTraveling.current = false;
344 } else if (isRecording.current) {
345 snapshots.current.push(atomsSnapshot);
346 devtools.current.send({
347 type: "" + snapshots.current.length,
348 updatedAt: new Date().toLocaleString()
349 }, getDevtoolsState(atomsSnapshot));
350 }
351 }, [atomsSnapshot]);
352}
353
354exports.useAtomDevtools = useAtomDevtools;
355exports.useAtomsDebugValue = useAtomsDebugValue;
356exports.useAtomsDevtools = useAtomsDevtools;
357exports.useAtomsSnapshot = useAtomsSnapshot;
358exports.useGotoAtomsSnapshot = useGotoAtomsSnapshot;