UNPKG

15.2 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 isEqualAtomsValues = function isEqualAtomsValues(left, right) {
242 return left.size === right.size && Array.from(left).every(function (_ref) {
243 var left = _ref[0],
244 v = _ref[1];
245 return Object.is(right.get(left), v);
246 });
247};
248
249var isEqualAtomsDependents = function isEqualAtomsDependents(left, right) {
250 return left.size === right.size && Array.from(left).every(function (_ref2) {
251 var a = _ref2[0],
252 dLeft = _ref2[1];
253 var dRight = right.get(a);
254 return dRight && dLeft.size === dRight.size && Array.from(dLeft).every(function (d) {
255 return dRight.has(d);
256 });
257 });
258};
259
260function useAtomsSnapshot(scope) {
261 var ScopeContext = jotai.SECRET_INTERNAL_getScopeContext(scope);
262 var scopeContainer = react.useContext(ScopeContext);
263 var store = scopeContainer.s;
264
265 var _useState = react.useState(function () {
266 return {
267 values: new Map(),
268 dependents: new Map()
269 };
270 }),
271 atomsSnapshot = _useState[0],
272 setAtomsSnapshot = _useState[1];
273
274 react.useEffect(function () {
275 if (!store[DEV_SUBSCRIBE_STATE]) return;
276 var prevValues = new Map();
277 var prevDependents = new Map();
278 var invalidatedAtoms = new Set();
279
280 var callback = function callback() {
281 var values = new Map();
282 var dependents = new Map();
283 var hasNewInvalidatedAtoms = false;
284
285 for (var _iterator = _createForOfIteratorHelperLoose(store[DEV_GET_MOUNTED_ATOMS]() || []), _step; !(_step = _iterator()).done;) {
286 var atom = _step.value;
287 var atomState = store[DEV_GET_ATOM_STATE](atom);
288
289 if (atomState) {
290 if (!atomState.y) {
291 if ('p' in atomState) {
292 return;
293 }
294
295 if (!invalidatedAtoms.has(atom)) {
296 invalidatedAtoms.add(atom);
297 hasNewInvalidatedAtoms = true;
298 }
299 }
300
301 if ('v' in atomState) {
302 values.set(atom, atomState.v);
303 }
304 }
305
306 var mounted = store[DEV_GET_MOUNTED](atom);
307
308 if (mounted) {
309 dependents.set(atom, mounted.t);
310 }
311 }
312
313 if (hasNewInvalidatedAtoms) {
314 return;
315 }
316
317 if (isEqualAtomsValues(prevValues, values) && isEqualAtomsDependents(prevDependents, dependents)) {
318 return;
319 }
320
321 prevValues = values;
322 prevDependents = dependents;
323 invalidatedAtoms.clear();
324 setAtomsSnapshot({
325 values: values,
326 dependents: dependents
327 });
328 };
329
330 var unsubscribe = store[DEV_SUBSCRIBE_STATE](callback);
331 callback();
332 return unsubscribe;
333 }, [store]);
334 return atomsSnapshot;
335}
336
337function useGotoAtomsSnapshot(scope) {
338 var ScopeContext = jotai.SECRET_INTERNAL_getScopeContext(scope);
339
340 var _useContext = react.useContext(ScopeContext),
341 store = _useContext.s,
342 versionedWrite = _useContext.w;
343
344 return react.useCallback(function (snapshot) {
345 if (!store[DEV_SUBSCRIBE_STATE]) return;
346
347 var restoreAtoms = function restoreAtoms(values) {
348 if (versionedWrite) {
349 versionedWrite(function (version) {
350 store[RESTORE_ATOMS](values, version);
351 });
352 } else {
353 store[RESTORE_ATOMS](values);
354 }
355 };
356
357 if (isIterable(snapshot)) {
358 if (process.env.NODE_ENV !== "production") {
359 console.warn('snapshot as iterable is deprecated. use an object instead.');
360 }
361
362 restoreAtoms(snapshot);
363 return;
364 }
365
366 restoreAtoms(snapshot.values);
367 }, [store, versionedWrite]);
368}
369
370var isIterable = function isIterable(item) {
371 return typeof item[Symbol.iterator] === 'function';
372};
373
374var atomToPrintable = function atomToPrintable(atom) {
375 return atom.debugLabel ? atom + ":" + atom.debugLabel : "" + atom;
376};
377
378var getDevtoolsState = function getDevtoolsState(atomsSnapshot) {
379 var values = {};
380 atomsSnapshot.values.forEach(function (v, atom) {
381 values[atomToPrintable(atom)] = v;
382 });
383 var dependents = {};
384 atomsSnapshot.dependents.forEach(function (d, atom) {
385 dependents[atomToPrintable(atom)] = Array.from(d).map(atomToPrintable);
386 });
387 return {
388 values: values,
389 dependents: dependents
390 };
391};
392
393function useAtomsDevtools(name, options) {
394 if (typeof options !== 'undefined' && typeof options !== 'object') {
395 console.warn('DEPRECATED [useAtomsDevtools] use DevtoolsOptions');
396 options = {
397 scope: options
398 };
399 }
400
401 var _ref = options || {},
402 enabled = _ref.enabled,
403 scope = _ref.scope;
404
405 var extension;
406
407 try {
408 extension = (enabled != null ? enabled : process.env.NODE_ENV !== "production") && window.__REDUX_DEVTOOLS_EXTENSION__;
409 } catch (_unused) {}
410
411 if (!extension) {
412 if (process.env.NODE_ENV !== "production" && enabled) {
413 console.warn('Please install/enable Redux devtools extension');
414 }
415 }
416
417 var atomsSnapshot = useAtomsSnapshot(scope);
418 var goToSnapshot = useGotoAtomsSnapshot(scope);
419 var isTimeTraveling = react.useRef(false);
420 var isRecording = react.useRef(true);
421 var devtools = react.useRef();
422 var snapshots = react.useRef([]);
423 react.useEffect(function () {
424 if (!extension) {
425 return;
426 }
427
428 var getSnapshotAt = function getSnapshotAt(index) {
429 if (index === void 0) {
430 index = snapshots.current.length - 1;
431 }
432
433 var snapshot = snapshots.current[index >= 0 ? index : 0];
434
435 if (!snapshot) {
436 throw new Error('snaphost index out of bounds');
437 }
438
439 return snapshot;
440 };
441
442 var connection = extension.connect({
443 name: name
444 });
445 var devtoolsUnsubscribe = connection.subscribe(function (message) {
446 var _message$payload;
447
448 switch (message.type) {
449 case 'DISPATCH':
450 switch ((_message$payload = message.payload) == null ? void 0 : _message$payload.type) {
451 case 'RESET':
452 break;
453
454 case 'COMMIT':
455 connection.init(getDevtoolsState(getSnapshotAt()));
456 snapshots.current = [];
457 break;
458
459 case 'JUMP_TO_ACTION':
460 case 'JUMP_TO_STATE':
461 isTimeTraveling.current = true;
462 goToSnapshot(getSnapshotAt(message.payload.actionId - 1));
463 break;
464
465 case 'PAUSE_RECORDING':
466 isRecording.current = !isRecording.current;
467 break;
468 }
469
470 }
471 });
472 devtools.current = connection;
473 devtools.current.shouldInit = true;
474 return devtoolsUnsubscribe;
475 }, [extension, goToSnapshot, name]);
476 react.useEffect(function () {
477 if (!devtools.current) {
478 return;
479 }
480
481 if (devtools.current.shouldInit) {
482 devtools.current.init(undefined);
483 devtools.current.shouldInit = false;
484 return;
485 }
486
487 if (isTimeTraveling.current) {
488 isTimeTraveling.current = false;
489 } else if (isRecording.current) {
490 snapshots.current.push(atomsSnapshot);
491 devtools.current.send({
492 type: "" + snapshots.current.length,
493 updatedAt: new Date().toLocaleString()
494 }, getDevtoolsState(atomsSnapshot));
495 }
496 }, [atomsSnapshot]);
497}
498
499exports.useAtomDevtools = useAtomDevtools;
500exports.useAtomsDebugValue = useAtomsDebugValue;
501exports.useAtomsDevtools = useAtomsDevtools;
502exports.useAtomsSnapshot = useAtomsSnapshot;
503exports.useGotoAtomsSnapshot = useGotoAtomsSnapshot;