UNPKG

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