UNPKG

17.5 kBJavaScriptView Raw
1(function (global, factory) {
2 typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react'), require('jotai')) :
3 typeof define === 'function' && define.amd ? define(['exports', 'react', 'jotai'], factory) :
4 (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.jotaiDevtools = {}, global.React, global.jotai));
5})(this, (function (exports, react, jotai) { 'use strict';
6
7 function _extends() {
8 _extends = Object.assign ? Object.assign.bind() : function (target) {
9 for (var i = 1; i < arguments.length; i++) {
10 var source = arguments[i];
11
12 for (var key in source) {
13 if (Object.prototype.hasOwnProperty.call(source, key)) {
14 target[key] = source[key];
15 }
16 }
17 }
18
19 return target;
20 };
21 return _extends.apply(this, arguments);
22 }
23
24 function _unsupportedIterableToArray(o, minLen) {
25 if (!o) return;
26 if (typeof o === "string") return _arrayLikeToArray(o, minLen);
27 var n = Object.prototype.toString.call(o).slice(8, -1);
28 if (n === "Object" && o.constructor) n = o.constructor.name;
29 if (n === "Map" || n === "Set") return Array.from(o);
30 if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
31 }
32
33 function _arrayLikeToArray(arr, len) {
34 if (len == null || len > arr.length) len = arr.length;
35
36 for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
37
38 return arr2;
39 }
40
41 function _createForOfIteratorHelperLoose(o, allowArrayLike) {
42 var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
43 if (it) return (it = it.call(o)).next.bind(it);
44
45 if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
46 if (it) o = it;
47 var i = 0;
48 return function () {
49 if (i >= o.length) return {
50 done: true
51 };
52 return {
53 done: false,
54 value: o[i++]
55 };
56 };
57 }
58
59 throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
60 }
61
62 var RESTORE_ATOMS = 'h';
63 var DEV_SUBSCRIBE_STATE = 'n';
64 var DEV_GET_MOUNTED_ATOMS = 'l';
65 var DEV_GET_ATOM_STATE = 'a';
66 var DEV_GET_MOUNTED = 'm';
67
68 var atomToPrintable$1 = function atomToPrintable(atom) {
69 return atom.debugLabel || atom.toString();
70 };
71
72 var stateToPrintable = function stateToPrintable(_ref) {
73 var store = _ref[0],
74 atoms = _ref[1];
75 return Object.fromEntries(atoms.flatMap(function (atom) {
76 var _store$DEV_GET_MOUNTE, _store$DEV_GET_ATOM_S;
77
78 var mounted = (_store$DEV_GET_MOUNTE = store[DEV_GET_MOUNTED]) == null ? void 0 : _store$DEV_GET_MOUNTE.call(store, atom);
79
80 if (!mounted) {
81 return [];
82 }
83
84 var dependents = mounted.t;
85 var atomState = ((_store$DEV_GET_ATOM_S = store[DEV_GET_ATOM_STATE]) == null ? void 0 : _store$DEV_GET_ATOM_S.call(store, atom)) || {};
86 return [[atomToPrintable$1(atom), _extends({}, 'e' in atomState && {
87 error: atomState.e
88 }, 'p' in atomState && {
89 promise: atomState.p
90 }, 'v' in atomState && {
91 value: atomState.v
92 }, {
93 dependents: Array.from(dependents).map(atomToPrintable$1)
94 })]];
95 }));
96 };
97
98 var useAtomsDebugValue = function useAtomsDebugValue(options) {
99 var _options$enabled;
100
101 var enabled = (_options$enabled = options == null ? void 0 : options.enabled) != null ? _options$enabled : true;
102 var ScopeContext = jotai.SECRET_INTERNAL_getScopeContext(options == null ? void 0 : options.scope);
103
104 var _useContext = react.useContext(ScopeContext),
105 store = _useContext.s;
106
107 var _useState = react.useState([]),
108 atoms = _useState[0],
109 setAtoms = _useState[1];
110
111 react.useEffect(function () {
112 var _store$DEV_SUBSCRIBE_;
113
114 if (!enabled) {
115 return;
116 }
117
118 var callback = function callback() {
119 var _store$DEV_GET_MOUNTE2;
120
121 setAtoms(Array.from(((_store$DEV_GET_MOUNTE2 = store[DEV_GET_MOUNTED_ATOMS]) == null ? void 0 : _store$DEV_GET_MOUNTE2.call(store)) || []));
122 };
123
124 var unsubscribe = (_store$DEV_SUBSCRIBE_ = store[DEV_SUBSCRIBE_STATE]) == null ? void 0 : _store$DEV_SUBSCRIBE_.call(store, callback);
125 callback();
126 return unsubscribe;
127 }, [enabled, store]);
128 react.useDebugValue([store, atoms], stateToPrintable);
129 };
130
131 function useAtomDevtools(anAtom, options, deprecatedScope) {
132 if (typeof options === 'string' || typeof deprecatedScope !== 'undefined') {
133 console.warn('DEPRECATED [useAtomDevtools] use DevtoolOptions');
134 options = {
135 name: options,
136 scope: deprecatedScope
137 };
138 }
139
140 var _ref = options || {},
141 enabled = _ref.enabled,
142 name = _ref.name,
143 scope = _ref.scope;
144
145 var extension;
146
147 try {
148 extension = (enabled != null ? enabled : true) && window.__REDUX_DEVTOOLS_EXTENSION__;
149 } catch (_unused) {}
150
151 if (!extension) {
152 if (enabled) {
153 console.warn('Please install/enable Redux devtools extension');
154 }
155 }
156
157 var _useAtom = jotai.useAtom(anAtom, scope),
158 value = _useAtom[0],
159 setValue = _useAtom[1];
160
161 var lastValue = react.useRef(value);
162 var isTimeTraveling = react.useRef(false);
163 var devtools = react.useRef();
164 var atomName = name || anAtom.debugLabel || anAtom.toString();
165 react.useEffect(function () {
166 if (!extension) {
167 return;
168 }
169
170 var setValueIfWritable = function setValueIfWritable(value) {
171 if (typeof setValue === 'function') {
172 setValue(value);
173 return;
174 }
175
176 console.warn('[Warn] you cannot do write operations (Time-travelling, etc) in read-only atoms\n', anAtom);
177 };
178
179 devtools.current = extension.connect({
180 name: atomName
181 });
182 var unsubscribe = devtools.current.subscribe(function (message) {
183 var _message$payload3, _message$payload4;
184
185 if (message.type === 'ACTION' && message.payload) {
186 try {
187 setValueIfWritable(JSON.parse(message.payload));
188 } catch (e) {
189 console.error('please dispatch a serializable value that JSON.parse() support\n', e);
190 }
191 } else if (message.type === 'DISPATCH' && message.state) {
192 var _message$payload, _message$payload2;
193
194 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') {
195 isTimeTraveling.current = true;
196 setValueIfWritable(JSON.parse(message.state));
197 }
198 } else if (message.type === 'DISPATCH' && ((_message$payload3 = message.payload) == null ? void 0 : _message$payload3.type) === 'COMMIT') {
199 var _devtools$current;
200
201 (_devtools$current = devtools.current) == null ? void 0 : _devtools$current.init(lastValue.current);
202 } else if (message.type === 'DISPATCH' && ((_message$payload4 = message.payload) == null ? void 0 : _message$payload4.type) === 'IMPORT_STATE') {
203 var _message$payload$next;
204
205 var computedStates = ((_message$payload$next = message.payload.nextLiftedState) == null ? void 0 : _message$payload$next.computedStates) || [];
206 computedStates.forEach(function (_ref2, index) {
207 var state = _ref2.state;
208
209 if (index === 0) {
210 var _devtools$current2;
211
212 (_devtools$current2 = devtools.current) == null ? void 0 : _devtools$current2.init(state);
213 } else {
214 setValueIfWritable(state);
215 }
216 });
217 }
218 });
219 devtools.current.shouldInit = true;
220 return unsubscribe;
221 }, [anAtom, extension, atomName, setValue]);
222 react.useEffect(function () {
223 if (!devtools.current) {
224 return;
225 }
226
227 lastValue.current = value;
228
229 if (devtools.current.shouldInit) {
230 devtools.current.init(value);
231 devtools.current.shouldInit = false;
232 } else if (isTimeTraveling.current) {
233 isTimeTraveling.current = false;
234 } else {
235 devtools.current.send(atomName + " - " + new Date().toLocaleString(), value);
236 }
237 }, [anAtom, extension, atomName, value]);
238 }
239
240 var createAtomsSnapshot = function createAtomsSnapshot(store, atoms) {
241 var tuples = atoms.map(function (atom) {
242 var _store$DEV_GET_ATOM_S, _store$DEV_GET_ATOM_S2;
243
244 var atomState = (_store$DEV_GET_ATOM_S = (_store$DEV_GET_ATOM_S2 = store[DEV_GET_ATOM_STATE]) == null ? void 0 : _store$DEV_GET_ATOM_S2.call(store, atom)) != null ? _store$DEV_GET_ATOM_S : {};
245 return [atom, 'v' in atomState ? atomState.v : undefined];
246 });
247 return new Map(tuples);
248 };
249
250 function useAtomsSnapshot(scope) {
251 var ScopeContext = jotai.SECRET_INTERNAL_getScopeContext(scope);
252 var scopeContainer = react.useContext(ScopeContext);
253 var store = scopeContainer.s;
254
255 if (!store[DEV_SUBSCRIBE_STATE]) {
256 throw new Error('useAtomsSnapshot can only be used in dev mode.');
257 }
258
259 var _useState = react.useState(function () {
260 return new Map();
261 }),
262 atomsSnapshot = _useState[0],
263 setAtomsSnapshot = _useState[1];
264
265 react.useEffect(function () {
266 var _store$DEV_SUBSCRIBE_;
267
268 var callback = function callback() {
269 var _store$DEV_GET_MOUNTE;
270
271 var atoms = Array.from(((_store$DEV_GET_MOUNTE = store[DEV_GET_MOUNTED_ATOMS]) == null ? void 0 : _store$DEV_GET_MOUNTE.call(store)) || []);
272 setAtomsSnapshot(createAtomsSnapshot(store, atoms));
273 };
274
275 var unsubscribe = (_store$DEV_SUBSCRIBE_ = store[DEV_SUBSCRIBE_STATE]) == null ? void 0 : _store$DEV_SUBSCRIBE_.call(store, callback);
276 callback();
277 return unsubscribe;
278 }, [store]);
279 return atomsSnapshot;
280 }
281
282 function useGotoAtomsSnapshot(scope) {
283 var ScopeContext = jotai.SECRET_INTERNAL_getScopeContext(scope);
284 var scopeContainer = react.useContext(ScopeContext);
285 var store = scopeContainer.s;
286
287 if (!store[DEV_SUBSCRIBE_STATE]) {
288 throw new Error('useGotoAtomsSnapshot can only be used in dev mode.');
289 }
290
291 return react.useCallback(function (values) {
292 store[RESTORE_ATOMS](values);
293 }, [store]);
294 }
295
296 var isEqualAtomsValues = function isEqualAtomsValues(left, right) {
297 return left.size === right.size && Array.from(left).every(function (_ref) {
298 var left = _ref[0],
299 v = _ref[1];
300 return Object.is(right.get(left), v);
301 });
302 };
303
304 var isEqualAtomsDependents = function isEqualAtomsDependents(left, right) {
305 return left.size === right.size && Array.from(left).every(function (_ref2) {
306 var a = _ref2[0],
307 dLeft = _ref2[1];
308 var dRight = right.get(a);
309 return dRight && dLeft.size === dRight.size && Array.from(dLeft).every(function (d) {
310 return dRight.has(d);
311 });
312 });
313 };
314
315 var atomToPrintable = function atomToPrintable(atom) {
316 return atom.debugLabel ? atom + ":" + atom.debugLabel : "" + atom;
317 };
318
319 var getDevtoolsState = function getDevtoolsState(atomsSnapshot) {
320 var values = {};
321 atomsSnapshot.values.forEach(function (v, atom) {
322 values[atomToPrintable(atom)] = v;
323 });
324 var dependents = {};
325 atomsSnapshot.dependents.forEach(function (d, atom) {
326 dependents[atomToPrintable(atom)] = Array.from(d).map(atomToPrintable);
327 });
328 return {
329 values: values,
330 dependents: dependents
331 };
332 };
333
334 function useAtomsDevtools(name, options) {
335 if (typeof options !== 'undefined' && typeof options !== 'object') {
336 console.warn('DEPRECATED [useAtomsDevtools] use DevtoolsOptions');
337 options = {
338 scope: options
339 };
340 }
341
342 var _ref3 = options || {},
343 enabled = _ref3.enabled,
344 scope = _ref3.scope;
345
346 var ScopeContext = jotai.SECRET_INTERNAL_getScopeContext(scope);
347
348 var _useContext = react.useContext(ScopeContext),
349 store = _useContext.s,
350 versionedWrite = _useContext.w;
351
352 var extension;
353
354 try {
355 extension = (enabled != null ? enabled : true) && window.__REDUX_DEVTOOLS_EXTENSION__;
356 } catch (_unused) {}
357
358 if (!extension) {
359 if (enabled) {
360 console.warn('Please install/enable Redux devtools extension');
361 }
362 }
363
364 if (extension && !store[DEV_SUBSCRIBE_STATE]) {
365 throw new Error('useAtomsDevtools can only be used in dev mode.');
366 }
367
368 var _useState = react.useState(function () {
369 return {
370 values: new Map(),
371 dependents: new Map()
372 };
373 }),
374 atomsSnapshot = _useState[0],
375 setAtomsSnapshot = _useState[1];
376
377 react.useEffect(function () {
378 var _store$DEV_SUBSCRIBE_;
379
380 if (!extension) {
381 return;
382 }
383
384 var callback = function callback() {
385 var values = new Map();
386 var dependents = new Map();
387
388 for (var _iterator = _createForOfIteratorHelperLoose(((_store$DEV_GET_MOUNTE = store[DEV_GET_MOUNTED_ATOMS]) == null ? void 0 : _store$DEV_GET_MOUNTE.call(store)) || []), _step; !(_step = _iterator()).done;) {
389 var _store$DEV_GET_MOUNTE, _store$DEV_GET_ATOM_S, _store$DEV_GET_MOUNTE2;
390
391 var atom = _step.value;
392 var atomState = (_store$DEV_GET_ATOM_S = store[DEV_GET_ATOM_STATE]) == null ? void 0 : _store$DEV_GET_ATOM_S.call(store, atom);
393
394 if (atomState) {
395 if (atomState.r === atomState.i) {
396 return;
397 }
398
399 if ('v' in atomState) {
400 values.set(atom, atomState.v);
401 }
402 }
403
404 var mounted = (_store$DEV_GET_MOUNTE2 = store[DEV_GET_MOUNTED]) == null ? void 0 : _store$DEV_GET_MOUNTE2.call(store, atom);
405
406 if (mounted) {
407 dependents.set(atom, mounted.t);
408 }
409 }
410
411 setAtomsSnapshot(function (prev) {
412 if (isEqualAtomsValues(prev.values, values) && isEqualAtomsDependents(prev.dependents, dependents)) {
413 return prev;
414 }
415
416 return {
417 values: values,
418 dependents: dependents
419 };
420 });
421 };
422
423 var unsubscribe = (_store$DEV_SUBSCRIBE_ = store[DEV_SUBSCRIBE_STATE]) == null ? void 0 : _store$DEV_SUBSCRIBE_.call(store, callback);
424 callback();
425 return unsubscribe;
426 }, [extension, store]);
427 var goToSnapshot = react.useCallback(function (snapshot) {
428 var values = snapshot.values;
429
430 if (versionedWrite) {
431 versionedWrite(function (version) {
432 store[RESTORE_ATOMS](values, version);
433 });
434 } else {
435 store[RESTORE_ATOMS](values);
436 }
437 }, [store, versionedWrite]);
438 var isTimeTraveling = react.useRef(false);
439 var isRecording = react.useRef(true);
440 var devtools = react.useRef();
441 var snapshots = react.useRef([]);
442 react.useEffect(function () {
443 if (!extension) {
444 return;
445 }
446
447 var getSnapshotAt = function getSnapshotAt(index) {
448 if (index === void 0) {
449 index = snapshots.current.length - 1;
450 }
451
452 var snapshot = snapshots.current[index >= 0 ? index : 0];
453
454 if (!snapshot) {
455 throw new Error('snaphost index out of bounds');
456 }
457
458 return snapshot;
459 };
460
461 var connection = extension.connect({
462 name: name
463 });
464 var devtoolsUnsubscribe = connection.subscribe(function (message) {
465 var _message$payload;
466
467 switch (message.type) {
468 case 'DISPATCH':
469 switch ((_message$payload = message.payload) == null ? void 0 : _message$payload.type) {
470 case 'RESET':
471 break;
472
473 case 'COMMIT':
474 connection.init(getDevtoolsState(getSnapshotAt()));
475 snapshots.current = [];
476 break;
477
478 case 'JUMP_TO_ACTION':
479 case 'JUMP_TO_STATE':
480 isTimeTraveling.current = true;
481 goToSnapshot(getSnapshotAt(message.payload.actionId - 1));
482 break;
483
484 case 'PAUSE_RECORDING':
485 isRecording.current = !isRecording.current;
486 break;
487 }
488
489 }
490 });
491 devtools.current = connection;
492 devtools.current.shouldInit = true;
493 return devtoolsUnsubscribe;
494 }, [extension, goToSnapshot, name]);
495 react.useEffect(function () {
496 if (!devtools.current) {
497 return;
498 }
499
500 if (devtools.current.shouldInit) {
501 devtools.current.init(undefined);
502 devtools.current.shouldInit = false;
503 return;
504 }
505
506 if (isTimeTraveling.current) {
507 isTimeTraveling.current = false;
508 } else if (isRecording.current) {
509 snapshots.current.push(atomsSnapshot);
510 devtools.current.send({
511 type: "" + snapshots.current.length,
512 updatedAt: new Date().toLocaleString()
513 }, getDevtoolsState(atomsSnapshot));
514 }
515 }, [atomsSnapshot]);
516 }
517
518 exports.useAtomDevtools = useAtomDevtools;
519 exports.useAtomsDebugValue = useAtomsDebugValue;
520 exports.useAtomsDevtools = useAtomsDevtools;
521 exports.useAtomsSnapshot = useAtomsSnapshot;
522 exports.useGotoAtomsSnapshot = useGotoAtomsSnapshot;
523
524 Object.defineProperty(exports, '__esModule', { value: true });
525
526}));