landvex: Fixar och tester klara för alla komponenter
- Datafabrik: Dockerfile fix, agentorkestrering fungerar - Vision: Identify-modell, FAISS, OCR alla testade - API: Alla 7 integrationstester passerade - Upplösare: Entitetsupplösning verifierad
This commit is contained in:
+21
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2019 Tanner Linsley
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
<img src="https://static.scarf.sh/a.png?x-pxid=be2d8a11-9712-4c1d-9963-580b2d4fb133" />
|
||||
|
||||

|
||||
|
||||
## Note
|
||||
|
||||
You're looking at the v3 version of react-query. Starting with v4, react-query is now available as [@tanstack/react-query](https://www.npmjs.com/package/@tanstack/react-query)
|
||||
|
||||
Find the docs at https://tanstack.com/query/latest
|
||||
|
||||
<!-- Use the force, Luke -->
|
||||
Generated
Vendored
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"internal": true,
|
||||
"main": "../lib/broadcastQueryClient-experimental/index.js",
|
||||
"module": "../es/broadcastQueryClient-experimental/index.js",
|
||||
"types": "../types/broadcastQueryClient-experimental/index.d.ts"
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"internal": true,
|
||||
"main": "../lib/core/index.js",
|
||||
"module": "../es/core/index.js",
|
||||
"types": "../types/core/index.d.ts"
|
||||
}
|
||||
Generated
Vendored
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"internal": true,
|
||||
"main": "../lib/createAsyncStoragePersistor-experimental/index.js",
|
||||
"module": "../es/createAsyncStoragePersistor-experimental/index.js",
|
||||
"types": "../types/createAsyncStoragePersistor-experimental/index.d.ts"
|
||||
}
|
||||
Generated
Vendored
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"internal": true,
|
||||
"main": "../lib/createWebStoragePersistor-experimental/index.js",
|
||||
"module": "../es/createWebStoragePersistor-experimental/index.js",
|
||||
"types": "../types/createWebStoragePersistor-experimental/index.d.ts"
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"internal": true,
|
||||
"main": "../../lib/devtools/index.js",
|
||||
"module": "../../es/devtools/index.js",
|
||||
"types": "../../types/devtools/index.d.ts"
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
if (process.env.NODE_ENV !== 'development') {
|
||||
module.exports = {
|
||||
ReactQueryDevtools: function () {
|
||||
return null
|
||||
},
|
||||
ReactQueryDevtoolsPanel: function () {
|
||||
return null
|
||||
},
|
||||
}
|
||||
} else {
|
||||
module.exports = require('./development')
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"internal": true,
|
||||
"main": "./index.js",
|
||||
"module": "./index.js",
|
||||
"types": "../types/devtools/index.d.ts"
|
||||
}
|
||||
Generated
Vendored
+1041
@@ -0,0 +1,1041 @@
|
||||
(function (global, factory) {
|
||||
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
|
||||
typeof define === 'function' && define.amd ? define(['exports'], factory) :
|
||||
(global = global || self, factory(global.ReactQueryBroadcastQueryClientExperimental = {}));
|
||||
}(this, (function (exports) { 'use strict';
|
||||
|
||||
/**
|
||||
* returns true if the given object is a promise
|
||||
*/
|
||||
function isPromise(obj) {
|
||||
if (obj && typeof obj.then === 'function') {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
function sleep(time) {
|
||||
if (!time) time = 0;
|
||||
return new Promise(function (res) {
|
||||
return setTimeout(res, time);
|
||||
});
|
||||
}
|
||||
function randomInt(min, max) {
|
||||
return Math.floor(Math.random() * (max - min + 1) + min);
|
||||
}
|
||||
/**
|
||||
* https://stackoverflow.com/a/8084248
|
||||
*/
|
||||
|
||||
function randomToken() {
|
||||
return Math.random().toString(36).substring(2);
|
||||
}
|
||||
var lastMs = 0;
|
||||
var additional = 0;
|
||||
/**
|
||||
* returns the current time in micro-seconds,
|
||||
* WARNING: This is a pseudo-function
|
||||
* Performance.now is not reliable in webworkers, so we just make sure to never return the same time.
|
||||
* This is enough in browsers, and this function will not be used in nodejs.
|
||||
* The main reason for this hack is to ensure that BroadcastChannel behaves equal to production when it is used in fast-running unit tests.
|
||||
*/
|
||||
|
||||
function microSeconds() {
|
||||
var ms = new Date().getTime();
|
||||
|
||||
if (ms === lastMs) {
|
||||
additional++;
|
||||
return ms * 1000 + additional;
|
||||
} else {
|
||||
lastMs = ms;
|
||||
additional = 0;
|
||||
return ms * 1000;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* copied from the 'detect-node' npm module
|
||||
* We cannot use the module directly because it causes problems with rollup
|
||||
* @link https://github.com/iliakan/detect-node/blob/master/index.js
|
||||
*/
|
||||
|
||||
var isNode = Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]';
|
||||
|
||||
var microSeconds$1 = microSeconds;
|
||||
var type = 'native';
|
||||
function create(channelName) {
|
||||
var state = {
|
||||
messagesCallback: null,
|
||||
bc: new BroadcastChannel(channelName),
|
||||
subFns: [] // subscriberFunctions
|
||||
|
||||
};
|
||||
|
||||
state.bc.onmessage = function (msg) {
|
||||
if (state.messagesCallback) {
|
||||
state.messagesCallback(msg.data);
|
||||
}
|
||||
};
|
||||
|
||||
return state;
|
||||
}
|
||||
function close(channelState) {
|
||||
channelState.bc.close();
|
||||
channelState.subFns = [];
|
||||
}
|
||||
function postMessage(channelState, messageJson) {
|
||||
channelState.bc.postMessage(messageJson, false);
|
||||
}
|
||||
function onMessage(channelState, fn) {
|
||||
channelState.messagesCallback = fn;
|
||||
}
|
||||
function canBeUsed() {
|
||||
/**
|
||||
* in the electron-renderer, isNode will be true even if we are in browser-context
|
||||
* so we also check if window is undefined
|
||||
*/
|
||||
if (isNode && typeof window === 'undefined') return false;
|
||||
|
||||
if (typeof BroadcastChannel === 'function') {
|
||||
if (BroadcastChannel._pubkey) {
|
||||
throw new Error('BroadcastChannel: Do not overwrite window.BroadcastChannel with this module, this is not a polyfill');
|
||||
}
|
||||
|
||||
return true;
|
||||
} else return false;
|
||||
}
|
||||
function averageResponseTime() {
|
||||
return 150;
|
||||
}
|
||||
var NativeMethod = {
|
||||
create: create,
|
||||
close: close,
|
||||
onMessage: onMessage,
|
||||
postMessage: postMessage,
|
||||
canBeUsed: canBeUsed,
|
||||
type: type,
|
||||
averageResponseTime: averageResponseTime,
|
||||
microSeconds: microSeconds$1
|
||||
};
|
||||
|
||||
/**
|
||||
* this is a set which automatically forgets
|
||||
* a given entry when a new entry is set and the ttl
|
||||
* of the old one is over
|
||||
* @constructor
|
||||
*/
|
||||
var ObliviousSet = function ObliviousSet(ttl) {
|
||||
var set = new Set();
|
||||
var timeMap = new Map();
|
||||
this.has = set.has.bind(set);
|
||||
|
||||
this.add = function (value) {
|
||||
timeMap.set(value, now());
|
||||
set.add(value);
|
||||
|
||||
_removeTooOldValues();
|
||||
};
|
||||
|
||||
this.clear = function () {
|
||||
set.clear();
|
||||
timeMap.clear();
|
||||
};
|
||||
|
||||
function _removeTooOldValues() {
|
||||
var olderThen = now() - ttl;
|
||||
var iterator = set[Symbol.iterator]();
|
||||
|
||||
while (true) {
|
||||
var value = iterator.next().value;
|
||||
if (!value) return; // no more elements
|
||||
|
||||
var time = timeMap.get(value);
|
||||
|
||||
if (time < olderThen) {
|
||||
timeMap["delete"](value);
|
||||
set["delete"](value);
|
||||
} else {
|
||||
// we reached a value that is not old enough
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
function now() {
|
||||
return new Date().getTime();
|
||||
}
|
||||
|
||||
function fillOptionsWithDefaults() {
|
||||
var originalOptions = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
|
||||
var options = JSON.parse(JSON.stringify(originalOptions)); // main
|
||||
|
||||
if (typeof options.webWorkerSupport === 'undefined') options.webWorkerSupport = true; // indexed-db
|
||||
|
||||
if (!options.idb) options.idb = {}; // after this time the messages get deleted
|
||||
|
||||
if (!options.idb.ttl) options.idb.ttl = 1000 * 45;
|
||||
if (!options.idb.fallbackInterval) options.idb.fallbackInterval = 150; // handles abrupt db onclose events.
|
||||
|
||||
if (originalOptions.idb && typeof originalOptions.idb.onclose === 'function') options.idb.onclose = originalOptions.idb.onclose; // localstorage
|
||||
|
||||
if (!options.localstorage) options.localstorage = {};
|
||||
if (!options.localstorage.removeTimeout) options.localstorage.removeTimeout = 1000 * 60; // custom methods
|
||||
|
||||
if (originalOptions.methods) options.methods = originalOptions.methods; // node
|
||||
|
||||
if (!options.node) options.node = {};
|
||||
if (!options.node.ttl) options.node.ttl = 1000 * 60 * 2; // 2 minutes;
|
||||
|
||||
if (typeof options.node.useFastPath === 'undefined') options.node.useFastPath = true;
|
||||
return options;
|
||||
}
|
||||
|
||||
/**
|
||||
* this method uses indexeddb to store the messages
|
||||
* There is currently no observerAPI for idb
|
||||
* @link https://github.com/w3c/IndexedDB/issues/51
|
||||
*/
|
||||
var microSeconds$2 = microSeconds;
|
||||
var DB_PREFIX = 'pubkey.broadcast-channel-0-';
|
||||
var OBJECT_STORE_ID = 'messages';
|
||||
var type$1 = 'idb';
|
||||
function getIdb() {
|
||||
if (typeof indexedDB !== 'undefined') return indexedDB;
|
||||
|
||||
if (typeof window !== 'undefined') {
|
||||
if (typeof window.mozIndexedDB !== 'undefined') return window.mozIndexedDB;
|
||||
if (typeof window.webkitIndexedDB !== 'undefined') return window.webkitIndexedDB;
|
||||
if (typeof window.msIndexedDB !== 'undefined') return window.msIndexedDB;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
function createDatabase(channelName) {
|
||||
var IndexedDB = getIdb(); // create table
|
||||
|
||||
var dbName = DB_PREFIX + channelName;
|
||||
var openRequest = IndexedDB.open(dbName, 1);
|
||||
|
||||
openRequest.onupgradeneeded = function (ev) {
|
||||
var db = ev.target.result;
|
||||
db.createObjectStore(OBJECT_STORE_ID, {
|
||||
keyPath: 'id',
|
||||
autoIncrement: true
|
||||
});
|
||||
};
|
||||
|
||||
var dbPromise = new Promise(function (res, rej) {
|
||||
openRequest.onerror = function (ev) {
|
||||
return rej(ev);
|
||||
};
|
||||
|
||||
openRequest.onsuccess = function () {
|
||||
res(openRequest.result);
|
||||
};
|
||||
});
|
||||
return dbPromise;
|
||||
}
|
||||
/**
|
||||
* writes the new message to the database
|
||||
* so other readers can find it
|
||||
*/
|
||||
|
||||
function writeMessage(db, readerUuid, messageJson) {
|
||||
var time = new Date().getTime();
|
||||
var writeObject = {
|
||||
uuid: readerUuid,
|
||||
time: time,
|
||||
data: messageJson
|
||||
};
|
||||
var transaction = db.transaction([OBJECT_STORE_ID], 'readwrite');
|
||||
return new Promise(function (res, rej) {
|
||||
transaction.oncomplete = function () {
|
||||
return res();
|
||||
};
|
||||
|
||||
transaction.onerror = function (ev) {
|
||||
return rej(ev);
|
||||
};
|
||||
|
||||
var objectStore = transaction.objectStore(OBJECT_STORE_ID);
|
||||
objectStore.add(writeObject);
|
||||
});
|
||||
}
|
||||
function getMessagesHigherThan(db, lastCursorId) {
|
||||
var objectStore = db.transaction(OBJECT_STORE_ID).objectStore(OBJECT_STORE_ID);
|
||||
var ret = [];
|
||||
|
||||
function openCursor() {
|
||||
// Occasionally Safari will fail on IDBKeyRange.bound, this
|
||||
// catches that error, having it open the cursor to the first
|
||||
// item. When it gets data it will advance to the desired key.
|
||||
try {
|
||||
var keyRangeValue = IDBKeyRange.bound(lastCursorId + 1, Infinity);
|
||||
return objectStore.openCursor(keyRangeValue);
|
||||
} catch (e) {
|
||||
return objectStore.openCursor();
|
||||
}
|
||||
}
|
||||
|
||||
return new Promise(function (res) {
|
||||
openCursor().onsuccess = function (ev) {
|
||||
var cursor = ev.target.result;
|
||||
|
||||
if (cursor) {
|
||||
if (cursor.value.id < lastCursorId + 1) {
|
||||
cursor["continue"](lastCursorId + 1);
|
||||
} else {
|
||||
ret.push(cursor.value);
|
||||
cursor["continue"]();
|
||||
}
|
||||
} else {
|
||||
res(ret);
|
||||
}
|
||||
};
|
||||
});
|
||||
}
|
||||
function removeMessageById(db, id) {
|
||||
var request = db.transaction([OBJECT_STORE_ID], 'readwrite').objectStore(OBJECT_STORE_ID)["delete"](id);
|
||||
return new Promise(function (res) {
|
||||
request.onsuccess = function () {
|
||||
return res();
|
||||
};
|
||||
});
|
||||
}
|
||||
function getOldMessages(db, ttl) {
|
||||
var olderThen = new Date().getTime() - ttl;
|
||||
var objectStore = db.transaction(OBJECT_STORE_ID).objectStore(OBJECT_STORE_ID);
|
||||
var ret = [];
|
||||
return new Promise(function (res) {
|
||||
objectStore.openCursor().onsuccess = function (ev) {
|
||||
var cursor = ev.target.result;
|
||||
|
||||
if (cursor) {
|
||||
var msgObk = cursor.value;
|
||||
|
||||
if (msgObk.time < olderThen) {
|
||||
ret.push(msgObk); //alert("Name for SSN " + cursor.key + " is " + cursor.value.name);
|
||||
|
||||
cursor["continue"]();
|
||||
} else {
|
||||
// no more old messages,
|
||||
res(ret);
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
res(ret);
|
||||
}
|
||||
};
|
||||
});
|
||||
}
|
||||
function cleanOldMessages(db, ttl) {
|
||||
return getOldMessages(db, ttl).then(function (tooOld) {
|
||||
return Promise.all(tooOld.map(function (msgObj) {
|
||||
return removeMessageById(db, msgObj.id);
|
||||
}));
|
||||
});
|
||||
}
|
||||
function create$1(channelName, options) {
|
||||
options = fillOptionsWithDefaults(options);
|
||||
return createDatabase(channelName).then(function (db) {
|
||||
var state = {
|
||||
closed: false,
|
||||
lastCursorId: 0,
|
||||
channelName: channelName,
|
||||
options: options,
|
||||
uuid: randomToken(),
|
||||
|
||||
/**
|
||||
* emittedMessagesIds
|
||||
* contains all messages that have been emitted before
|
||||
* @type {ObliviousSet}
|
||||
*/
|
||||
eMIs: new ObliviousSet(options.idb.ttl * 2),
|
||||
// ensures we do not read messages in parrallel
|
||||
writeBlockPromise: Promise.resolve(),
|
||||
messagesCallback: null,
|
||||
readQueuePromises: [],
|
||||
db: db
|
||||
};
|
||||
/**
|
||||
* Handle abrupt closes that do not originate from db.close().
|
||||
* This could happen, for example, if the underlying storage is
|
||||
* removed or if the user clears the database in the browser's
|
||||
* history preferences.
|
||||
*/
|
||||
|
||||
db.onclose = function () {
|
||||
state.closed = true;
|
||||
if (options.idb.onclose) options.idb.onclose();
|
||||
};
|
||||
/**
|
||||
* if service-workers are used,
|
||||
* we have no 'storage'-event if they post a message,
|
||||
* therefore we also have to set an interval
|
||||
*/
|
||||
|
||||
|
||||
_readLoop(state);
|
||||
|
||||
return state;
|
||||
});
|
||||
}
|
||||
|
||||
function _readLoop(state) {
|
||||
if (state.closed) return;
|
||||
readNewMessages(state).then(function () {
|
||||
return sleep(state.options.idb.fallbackInterval);
|
||||
}).then(function () {
|
||||
return _readLoop(state);
|
||||
});
|
||||
}
|
||||
|
||||
function _filterMessage(msgObj, state) {
|
||||
if (msgObj.uuid === state.uuid) return false; // send by own
|
||||
|
||||
if (state.eMIs.has(msgObj.id)) return false; // already emitted
|
||||
|
||||
if (msgObj.data.time < state.messagesCallbackTime) return false; // older then onMessageCallback
|
||||
|
||||
return true;
|
||||
}
|
||||
/**
|
||||
* reads all new messages from the database and emits them
|
||||
*/
|
||||
|
||||
|
||||
function readNewMessages(state) {
|
||||
// channel already closed
|
||||
if (state.closed) return Promise.resolve(); // if no one is listening, we do not need to scan for new messages
|
||||
|
||||
if (!state.messagesCallback) return Promise.resolve();
|
||||
return getMessagesHigherThan(state.db, state.lastCursorId).then(function (newerMessages) {
|
||||
var useMessages = newerMessages
|
||||
/**
|
||||
* there is a bug in iOS where the msgObj can be undefined some times
|
||||
* so we filter them out
|
||||
* @link https://github.com/pubkey/broadcast-channel/issues/19
|
||||
*/
|
||||
.filter(function (msgObj) {
|
||||
return !!msgObj;
|
||||
}).map(function (msgObj) {
|
||||
if (msgObj.id > state.lastCursorId) {
|
||||
state.lastCursorId = msgObj.id;
|
||||
}
|
||||
|
||||
return msgObj;
|
||||
}).filter(function (msgObj) {
|
||||
return _filterMessage(msgObj, state);
|
||||
}).sort(function (msgObjA, msgObjB) {
|
||||
return msgObjA.time - msgObjB.time;
|
||||
}); // sort by time
|
||||
|
||||
useMessages.forEach(function (msgObj) {
|
||||
if (state.messagesCallback) {
|
||||
state.eMIs.add(msgObj.id);
|
||||
state.messagesCallback(msgObj.data);
|
||||
}
|
||||
});
|
||||
return Promise.resolve();
|
||||
});
|
||||
}
|
||||
|
||||
function close$1(channelState) {
|
||||
channelState.closed = true;
|
||||
channelState.db.close();
|
||||
}
|
||||
function postMessage$1(channelState, messageJson) {
|
||||
channelState.writeBlockPromise = channelState.writeBlockPromise.then(function () {
|
||||
return writeMessage(channelState.db, channelState.uuid, messageJson);
|
||||
}).then(function () {
|
||||
if (randomInt(0, 10) === 0) {
|
||||
/* await (do not await) */
|
||||
cleanOldMessages(channelState.db, channelState.options.idb.ttl);
|
||||
}
|
||||
});
|
||||
return channelState.writeBlockPromise;
|
||||
}
|
||||
function onMessage$1(channelState, fn, time) {
|
||||
channelState.messagesCallbackTime = time;
|
||||
channelState.messagesCallback = fn;
|
||||
readNewMessages(channelState);
|
||||
}
|
||||
function canBeUsed$1() {
|
||||
if (isNode) return false;
|
||||
var idb = getIdb();
|
||||
if (!idb) return false;
|
||||
return true;
|
||||
}
|
||||
function averageResponseTime$1(options) {
|
||||
return options.idb.fallbackInterval * 2;
|
||||
}
|
||||
var IndexeDbMethod = {
|
||||
create: create$1,
|
||||
close: close$1,
|
||||
onMessage: onMessage$1,
|
||||
postMessage: postMessage$1,
|
||||
canBeUsed: canBeUsed$1,
|
||||
type: type$1,
|
||||
averageResponseTime: averageResponseTime$1,
|
||||
microSeconds: microSeconds$2
|
||||
};
|
||||
|
||||
/**
|
||||
* A localStorage-only method which uses localstorage and its 'storage'-event
|
||||
* This does not work inside of webworkers because they have no access to locastorage
|
||||
* This is basically implemented to support IE9 or your grandmothers toaster.
|
||||
* @link https://caniuse.com/#feat=namevalue-storage
|
||||
* @link https://caniuse.com/#feat=indexeddb
|
||||
*/
|
||||
var microSeconds$3 = microSeconds;
|
||||
var KEY_PREFIX = 'pubkey.broadcastChannel-';
|
||||
var type$2 = 'localstorage';
|
||||
/**
|
||||
* copied from crosstab
|
||||
* @link https://github.com/tejacques/crosstab/blob/master/src/crosstab.js#L32
|
||||
*/
|
||||
|
||||
function getLocalStorage() {
|
||||
var localStorage;
|
||||
if (typeof window === 'undefined') return null;
|
||||
|
||||
try {
|
||||
localStorage = window.localStorage;
|
||||
localStorage = window['ie8-eventlistener/storage'] || window.localStorage;
|
||||
} catch (e) {// New versions of Firefox throw a Security exception
|
||||
// if cookies are disabled. See
|
||||
// https://bugzilla.mozilla.org/show_bug.cgi?id=1028153
|
||||
}
|
||||
|
||||
return localStorage;
|
||||
}
|
||||
function storageKey(channelName) {
|
||||
return KEY_PREFIX + channelName;
|
||||
}
|
||||
/**
|
||||
* writes the new message to the storage
|
||||
* and fires the storage-event so other readers can find it
|
||||
*/
|
||||
|
||||
function postMessage$2(channelState, messageJson) {
|
||||
return new Promise(function (res) {
|
||||
sleep().then(function () {
|
||||
var key = storageKey(channelState.channelName);
|
||||
var writeObj = {
|
||||
token: randomToken(),
|
||||
time: new Date().getTime(),
|
||||
data: messageJson,
|
||||
uuid: channelState.uuid
|
||||
};
|
||||
var value = JSON.stringify(writeObj);
|
||||
getLocalStorage().setItem(key, value);
|
||||
/**
|
||||
* StorageEvent does not fire the 'storage' event
|
||||
* in the window that changes the state of the local storage.
|
||||
* So we fire it manually
|
||||
*/
|
||||
|
||||
var ev = document.createEvent('Event');
|
||||
ev.initEvent('storage', true, true);
|
||||
ev.key = key;
|
||||
ev.newValue = value;
|
||||
window.dispatchEvent(ev);
|
||||
res();
|
||||
});
|
||||
});
|
||||
}
|
||||
function addStorageEventListener(channelName, fn) {
|
||||
var key = storageKey(channelName);
|
||||
|
||||
var listener = function listener(ev) {
|
||||
if (ev.key === key) {
|
||||
fn(JSON.parse(ev.newValue));
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('storage', listener);
|
||||
return listener;
|
||||
}
|
||||
function removeStorageEventListener(listener) {
|
||||
window.removeEventListener('storage', listener);
|
||||
}
|
||||
function create$2(channelName, options) {
|
||||
options = fillOptionsWithDefaults(options);
|
||||
|
||||
if (!canBeUsed$2()) {
|
||||
throw new Error('BroadcastChannel: localstorage cannot be used');
|
||||
}
|
||||
|
||||
var uuid = randomToken();
|
||||
/**
|
||||
* eMIs
|
||||
* contains all messages that have been emitted before
|
||||
* @type {ObliviousSet}
|
||||
*/
|
||||
|
||||
var eMIs = new ObliviousSet(options.localstorage.removeTimeout);
|
||||
var state = {
|
||||
channelName: channelName,
|
||||
uuid: uuid,
|
||||
eMIs: eMIs // emittedMessagesIds
|
||||
|
||||
};
|
||||
state.listener = addStorageEventListener(channelName, function (msgObj) {
|
||||
if (!state.messagesCallback) return; // no listener
|
||||
|
||||
if (msgObj.uuid === uuid) return; // own message
|
||||
|
||||
if (!msgObj.token || eMIs.has(msgObj.token)) return; // already emitted
|
||||
|
||||
if (msgObj.data.time && msgObj.data.time < state.messagesCallbackTime) return; // too old
|
||||
|
||||
eMIs.add(msgObj.token);
|
||||
state.messagesCallback(msgObj.data);
|
||||
});
|
||||
return state;
|
||||
}
|
||||
function close$2(channelState) {
|
||||
removeStorageEventListener(channelState.listener);
|
||||
}
|
||||
function onMessage$2(channelState, fn, time) {
|
||||
channelState.messagesCallbackTime = time;
|
||||
channelState.messagesCallback = fn;
|
||||
}
|
||||
function canBeUsed$2() {
|
||||
if (isNode) return false;
|
||||
var ls = getLocalStorage();
|
||||
if (!ls) return false;
|
||||
|
||||
try {
|
||||
var key = '__broadcastchannel_check';
|
||||
ls.setItem(key, 'works');
|
||||
ls.removeItem(key);
|
||||
} catch (e) {
|
||||
// Safari 10 in private mode will not allow write access to local
|
||||
// storage and fail with a QuotaExceededError. See
|
||||
// https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API#Private_Browsing_Incognito_modes
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
function averageResponseTime$2() {
|
||||
var defaultTime = 120;
|
||||
var userAgent = navigator.userAgent.toLowerCase();
|
||||
|
||||
if (userAgent.includes('safari') && !userAgent.includes('chrome')) {
|
||||
// safari is much slower so this time is higher
|
||||
return defaultTime * 2;
|
||||
}
|
||||
|
||||
return defaultTime;
|
||||
}
|
||||
var LocalstorageMethod = {
|
||||
create: create$2,
|
||||
close: close$2,
|
||||
onMessage: onMessage$2,
|
||||
postMessage: postMessage$2,
|
||||
canBeUsed: canBeUsed$2,
|
||||
type: type$2,
|
||||
averageResponseTime: averageResponseTime$2,
|
||||
microSeconds: microSeconds$3
|
||||
};
|
||||
|
||||
var microSeconds$4 = microSeconds;
|
||||
var type$3 = 'simulate';
|
||||
var SIMULATE_CHANNELS = new Set();
|
||||
function create$3(channelName) {
|
||||
var state = {
|
||||
name: channelName,
|
||||
messagesCallback: null
|
||||
};
|
||||
SIMULATE_CHANNELS.add(state);
|
||||
return state;
|
||||
}
|
||||
function close$3(channelState) {
|
||||
SIMULATE_CHANNELS["delete"](channelState);
|
||||
}
|
||||
function postMessage$3(channelState, messageJson) {
|
||||
return new Promise(function (res) {
|
||||
return setTimeout(function () {
|
||||
var channelArray = Array.from(SIMULATE_CHANNELS);
|
||||
channelArray.filter(function (channel) {
|
||||
return channel.name === channelState.name;
|
||||
}).filter(function (channel) {
|
||||
return channel !== channelState;
|
||||
}).filter(function (channel) {
|
||||
return !!channel.messagesCallback;
|
||||
}).forEach(function (channel) {
|
||||
return channel.messagesCallback(messageJson);
|
||||
});
|
||||
res();
|
||||
}, 5);
|
||||
});
|
||||
}
|
||||
function onMessage$3(channelState, fn) {
|
||||
channelState.messagesCallback = fn;
|
||||
}
|
||||
function canBeUsed$3() {
|
||||
return true;
|
||||
}
|
||||
function averageResponseTime$3() {
|
||||
return 5;
|
||||
}
|
||||
var SimulateMethod = {
|
||||
create: create$3,
|
||||
close: close$3,
|
||||
onMessage: onMessage$3,
|
||||
postMessage: postMessage$3,
|
||||
canBeUsed: canBeUsed$3,
|
||||
type: type$3,
|
||||
averageResponseTime: averageResponseTime$3,
|
||||
microSeconds: microSeconds$4
|
||||
};
|
||||
|
||||
var METHODS = [NativeMethod, // fastest
|
||||
IndexeDbMethod, LocalstorageMethod];
|
||||
/**
|
||||
* The NodeMethod is loaded lazy
|
||||
* so it will not get bundled in browser-builds
|
||||
*/
|
||||
|
||||
if (isNode) {
|
||||
/**
|
||||
* we use the non-transpiled code for nodejs
|
||||
* because it runs faster
|
||||
*/
|
||||
var NodeMethod = require('../../src/methods/' + // use this hack so that browserify and others
|
||||
// do not import the node-method by default
|
||||
// when bundling.
|
||||
'node.js');
|
||||
/**
|
||||
* this will be false for webpackbuilds
|
||||
* which will shim the node-method with an empty object {}
|
||||
*/
|
||||
|
||||
|
||||
if (typeof NodeMethod.canBeUsed === 'function') {
|
||||
METHODS.push(NodeMethod);
|
||||
}
|
||||
}
|
||||
|
||||
function chooseMethod(options) {
|
||||
var chooseMethods = [].concat(options.methods, METHODS).filter(Boolean); // directly chosen
|
||||
|
||||
if (options.type) {
|
||||
if (options.type === 'simulate') {
|
||||
// only use simulate-method if directly chosen
|
||||
return SimulateMethod;
|
||||
}
|
||||
|
||||
var ret = chooseMethods.find(function (m) {
|
||||
return m.type === options.type;
|
||||
});
|
||||
if (!ret) throw new Error('method-type ' + options.type + ' not found');else return ret;
|
||||
}
|
||||
/**
|
||||
* if no webworker support is needed,
|
||||
* remove idb from the list so that localstorage is been chosen
|
||||
*/
|
||||
|
||||
|
||||
if (!options.webWorkerSupport && !isNode) {
|
||||
chooseMethods = chooseMethods.filter(function (m) {
|
||||
return m.type !== 'idb';
|
||||
});
|
||||
}
|
||||
|
||||
var useMethod = chooseMethods.find(function (method) {
|
||||
return method.canBeUsed();
|
||||
});
|
||||
if (!useMethod) throw new Error('No useable methode found:' + JSON.stringify(METHODS.map(function (m) {
|
||||
return m.type;
|
||||
})));else return useMethod;
|
||||
}
|
||||
|
||||
var BroadcastChannel$1 = function BroadcastChannel(name, options) {
|
||||
this.name = name;
|
||||
|
||||
this.options = fillOptionsWithDefaults(options);
|
||||
this.method = chooseMethod(this.options); // isListening
|
||||
|
||||
this._iL = false;
|
||||
/**
|
||||
* _onMessageListener
|
||||
* setting onmessage twice,
|
||||
* will overwrite the first listener
|
||||
*/
|
||||
|
||||
this._onML = null;
|
||||
/**
|
||||
* _addEventListeners
|
||||
*/
|
||||
|
||||
this._addEL = {
|
||||
message: [],
|
||||
internal: []
|
||||
};
|
||||
/**
|
||||
* _beforeClose
|
||||
* array of promises that will be awaited
|
||||
* before the channel is closed
|
||||
*/
|
||||
|
||||
this._befC = [];
|
||||
/**
|
||||
* _preparePromise
|
||||
*/
|
||||
|
||||
this._prepP = null;
|
||||
|
||||
_prepareChannel(this);
|
||||
}; // STATICS
|
||||
|
||||
/**
|
||||
* used to identify if someone overwrites
|
||||
* window.BroadcastChannel with this
|
||||
* See methods/native.js
|
||||
*/
|
||||
|
||||
BroadcastChannel$1._pubkey = true;
|
||||
|
||||
BroadcastChannel$1.prototype = {
|
||||
postMessage: function postMessage(msg) {
|
||||
if (this.closed) {
|
||||
throw new Error('BroadcastChannel.postMessage(): ' + 'Cannot post message after channel has closed');
|
||||
}
|
||||
|
||||
return _post(this, 'message', msg);
|
||||
},
|
||||
postInternal: function postInternal(msg) {
|
||||
return _post(this, 'internal', msg);
|
||||
},
|
||||
|
||||
set onmessage(fn) {
|
||||
var time = this.method.microSeconds();
|
||||
var listenObj = {
|
||||
time: time,
|
||||
fn: fn
|
||||
};
|
||||
|
||||
_removeListenerObject(this, 'message', this._onML);
|
||||
|
||||
if (fn && typeof fn === 'function') {
|
||||
this._onML = listenObj;
|
||||
|
||||
_addListenerObject(this, 'message', listenObj);
|
||||
} else {
|
||||
this._onML = null;
|
||||
}
|
||||
},
|
||||
|
||||
addEventListener: function addEventListener(type, fn) {
|
||||
var time = this.method.microSeconds();
|
||||
var listenObj = {
|
||||
time: time,
|
||||
fn: fn
|
||||
};
|
||||
|
||||
_addListenerObject(this, type, listenObj);
|
||||
},
|
||||
removeEventListener: function removeEventListener(type, fn) {
|
||||
var obj = this._addEL[type].find(function (obj) {
|
||||
return obj.fn === fn;
|
||||
});
|
||||
|
||||
_removeListenerObject(this, type, obj);
|
||||
},
|
||||
close: function close() {
|
||||
var _this = this;
|
||||
|
||||
if (this.closed) return;
|
||||
this.closed = true;
|
||||
var awaitPrepare = this._prepP ? this._prepP : Promise.resolve();
|
||||
this._onML = null;
|
||||
this._addEL.message = [];
|
||||
return awaitPrepare.then(function () {
|
||||
return Promise.all(_this._befC.map(function (fn) {
|
||||
return fn();
|
||||
}));
|
||||
}).then(function () {
|
||||
return _this.method.close(_this._state);
|
||||
});
|
||||
},
|
||||
|
||||
get type() {
|
||||
return this.method.type;
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
function _post(broadcastChannel, type, msg) {
|
||||
var time = broadcastChannel.method.microSeconds();
|
||||
var msgObj = {
|
||||
time: time,
|
||||
type: type,
|
||||
data: msg
|
||||
};
|
||||
var awaitPrepare = broadcastChannel._prepP ? broadcastChannel._prepP : Promise.resolve();
|
||||
return awaitPrepare.then(function () {
|
||||
return broadcastChannel.method.postMessage(broadcastChannel._state, msgObj);
|
||||
});
|
||||
}
|
||||
|
||||
function _prepareChannel(channel) {
|
||||
var maybePromise = channel.method.create(channel.name, channel.options);
|
||||
|
||||
if (isPromise(maybePromise)) {
|
||||
channel._prepP = maybePromise;
|
||||
maybePromise.then(function (s) {
|
||||
// used in tests to simulate slow runtime
|
||||
|
||||
/*if (channel.options.prepareDelay) {
|
||||
await new Promise(res => setTimeout(res, this.options.prepareDelay));
|
||||
}*/
|
||||
channel._state = s;
|
||||
});
|
||||
} else {
|
||||
channel._state = maybePromise;
|
||||
}
|
||||
}
|
||||
|
||||
function _hasMessageListeners(channel) {
|
||||
if (channel._addEL.message.length > 0) return true;
|
||||
if (channel._addEL.internal.length > 0) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
function _addListenerObject(channel, type, obj) {
|
||||
channel._addEL[type].push(obj);
|
||||
|
||||
_startListening(channel);
|
||||
}
|
||||
|
||||
function _removeListenerObject(channel, type, obj) {
|
||||
channel._addEL[type] = channel._addEL[type].filter(function (o) {
|
||||
return o !== obj;
|
||||
});
|
||||
|
||||
_stopListening(channel);
|
||||
}
|
||||
|
||||
function _startListening(channel) {
|
||||
if (!channel._iL && _hasMessageListeners(channel)) {
|
||||
// someone is listening, start subscribing
|
||||
var listenerFn = function listenerFn(msgObj) {
|
||||
channel._addEL[msgObj.type].forEach(function (obj) {
|
||||
if (msgObj.time >= obj.time) {
|
||||
obj.fn(msgObj.data);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
var time = channel.method.microSeconds();
|
||||
|
||||
if (channel._prepP) {
|
||||
channel._prepP.then(function () {
|
||||
channel._iL = true;
|
||||
channel.method.onMessage(channel._state, listenerFn, time);
|
||||
});
|
||||
} else {
|
||||
channel._iL = true;
|
||||
channel.method.onMessage(channel._state, listenerFn, time);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function _stopListening(channel) {
|
||||
if (channel._iL && !_hasMessageListeners(channel)) {
|
||||
// noone is listening, stop subscribing
|
||||
channel._iL = false;
|
||||
var time = channel.method.microSeconds();
|
||||
channel.method.onMessage(channel._state, null, time);
|
||||
}
|
||||
}
|
||||
|
||||
function broadcastQueryClient(_ref) {
|
||||
var queryClient = _ref.queryClient,
|
||||
_ref$broadcastChannel = _ref.broadcastChannel,
|
||||
broadcastChannel = _ref$broadcastChannel === void 0 ? 'react-query' : _ref$broadcastChannel;
|
||||
var transaction = false;
|
||||
|
||||
var tx = function tx(cb) {
|
||||
transaction = true;
|
||||
cb();
|
||||
transaction = false;
|
||||
};
|
||||
|
||||
var channel = new BroadcastChannel$1(broadcastChannel, {
|
||||
webWorkerSupport: false
|
||||
});
|
||||
var queryCache = queryClient.getQueryCache();
|
||||
queryClient.getQueryCache().subscribe(function (queryEvent) {
|
||||
var _queryEvent$action;
|
||||
|
||||
if (transaction || !(queryEvent == null ? void 0 : queryEvent.query)) {
|
||||
return;
|
||||
}
|
||||
|
||||
var _queryEvent$query = queryEvent.query,
|
||||
queryHash = _queryEvent$query.queryHash,
|
||||
queryKey = _queryEvent$query.queryKey,
|
||||
state = _queryEvent$query.state;
|
||||
|
||||
if (queryEvent.type === 'queryUpdated' && ((_queryEvent$action = queryEvent.action) == null ? void 0 : _queryEvent$action.type) === 'success') {
|
||||
channel.postMessage({
|
||||
type: 'queryUpdated',
|
||||
queryHash: queryHash,
|
||||
queryKey: queryKey,
|
||||
state: state
|
||||
});
|
||||
}
|
||||
|
||||
if (queryEvent.type === 'queryRemoved') {
|
||||
channel.postMessage({
|
||||
type: 'queryRemoved',
|
||||
queryHash: queryHash,
|
||||
queryKey: queryKey
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
channel.onmessage = function (action) {
|
||||
if (!(action == null ? void 0 : action.type)) {
|
||||
return;
|
||||
}
|
||||
|
||||
tx(function () {
|
||||
var type = action.type,
|
||||
queryHash = action.queryHash,
|
||||
queryKey = action.queryKey,
|
||||
state = action.state;
|
||||
|
||||
if (type === 'queryUpdated') {
|
||||
var query = queryCache.get(queryHash);
|
||||
|
||||
if (query) {
|
||||
query.setState(state);
|
||||
return;
|
||||
}
|
||||
|
||||
queryCache.build(queryClient, {
|
||||
queryKey: queryKey,
|
||||
queryHash: queryHash
|
||||
}, state);
|
||||
} else if (type === 'queryRemoved') {
|
||||
var _query = queryCache.get(queryHash);
|
||||
|
||||
if (_query) {
|
||||
queryCache.remove(_query);
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
exports.broadcastQueryClient = broadcastQueryClient;
|
||||
|
||||
Object.defineProperty(exports, '__esModule', { value: true });
|
||||
|
||||
})));
|
||||
//# sourceMappingURL=broadcastQueryClient-experimental.development.js.map
|
||||
Generated
Vendored
+1
File diff suppressed because one or more lines are too long
Generated
Vendored
+2
File diff suppressed because one or more lines are too long
Generated
Vendored
+1
File diff suppressed because one or more lines are too long
Generated
Vendored
+137
@@ -0,0 +1,137 @@
|
||||
(function (global, factory) {
|
||||
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
|
||||
typeof define === 'function' && define.amd ? define(['exports'], factory) :
|
||||
(global = global || self, factory(global.ReactQueryCreateAsyncStoragePersistorExperimental = {}));
|
||||
}(this, (function (exports) { 'use strict';
|
||||
|
||||
function _await(value, then, direct) {
|
||||
if (direct) {
|
||||
return then ? then(value) : value;
|
||||
}
|
||||
|
||||
if (!value || !value.then) {
|
||||
value = Promise.resolve(value);
|
||||
}
|
||||
|
||||
return then ? value.then(then) : value;
|
||||
}
|
||||
|
||||
function _async(f) {
|
||||
return function () {
|
||||
for (var args = [], i = 0; i < arguments.length; i++) {
|
||||
args[i] = arguments[i];
|
||||
}
|
||||
|
||||
try {
|
||||
return Promise.resolve(f.apply(this, args));
|
||||
} catch (e) {
|
||||
return Promise.reject(e);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function _empty() {}
|
||||
|
||||
function _invokeIgnored(body) {
|
||||
var result = body();
|
||||
|
||||
if (result && result.then) {
|
||||
return result.then(_empty);
|
||||
}
|
||||
}
|
||||
|
||||
var createAsyncStoragePersistor = function createAsyncStoragePersistor(_ref) {
|
||||
var storage = _ref.storage,
|
||||
_ref$key = _ref.key,
|
||||
key = _ref$key === void 0 ? "REACT_QUERY_OFFLINE_CACHE" : _ref$key,
|
||||
_ref$throttleTime = _ref.throttleTime,
|
||||
throttleTime = _ref$throttleTime === void 0 ? 1000 : _ref$throttleTime,
|
||||
_ref$serialize = _ref.serialize,
|
||||
serialize = _ref$serialize === void 0 ? JSON.stringify : _ref$serialize,
|
||||
_ref$deserialize = _ref.deserialize,
|
||||
deserialize = _ref$deserialize === void 0 ? JSON.parse : _ref$deserialize;
|
||||
return {
|
||||
persistClient: asyncThrottle(function (persistedClient) {
|
||||
return storage.setItem(key, serialize(persistedClient));
|
||||
}, {
|
||||
interval: throttleTime
|
||||
}),
|
||||
restoreClient: _async(function () {
|
||||
return _await(storage.getItem(key), function (cacheString) {
|
||||
if (!cacheString) {
|
||||
return;
|
||||
}
|
||||
|
||||
return deserialize(cacheString);
|
||||
});
|
||||
}),
|
||||
removeClient: function removeClient() {
|
||||
return storage.removeItem(key);
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
function asyncThrottle(func, _temp) {
|
||||
var _ref2 = _temp === void 0 ? {} : _temp,
|
||||
_ref2$interval = _ref2.interval,
|
||||
interval = _ref2$interval === void 0 ? 1000 : _ref2$interval,
|
||||
_ref2$limit = _ref2.limit,
|
||||
limit = _ref2$limit === void 0 ? 1 : _ref2$limit;
|
||||
|
||||
if (typeof func !== 'function') throw new Error('argument is not function.');
|
||||
var running = {
|
||||
current: false
|
||||
};
|
||||
var lastTime = 0;
|
||||
var timeout;
|
||||
var queue = [];
|
||||
return function () {
|
||||
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
|
||||
args[_key] = arguments[_key];
|
||||
}
|
||||
|
||||
return _async(function () {
|
||||
if (running.current) {
|
||||
lastTime = Date.now();
|
||||
|
||||
if (queue.length > limit) {
|
||||
queue.shift();
|
||||
}
|
||||
|
||||
queue.push(args);
|
||||
clearTimeout(timeout);
|
||||
}
|
||||
|
||||
return _invokeIgnored(function () {
|
||||
if (Date.now() - lastTime > interval) {
|
||||
running.current = true;
|
||||
return _await(func.apply(void 0, args), function () {
|
||||
lastTime = Date.now();
|
||||
running.current = false;
|
||||
});
|
||||
} else {
|
||||
if (queue.length > 0) {
|
||||
var lastArgs = queue[queue.length - 1];
|
||||
timeout = setTimeout(_async(function () {
|
||||
return _invokeIgnored(function () {
|
||||
if (!running.current) {
|
||||
running.current = true;
|
||||
return _await(func.apply(void 0, lastArgs), function () {
|
||||
running.current = false;
|
||||
});
|
||||
}
|
||||
});
|
||||
}), interval);
|
||||
}
|
||||
}
|
||||
});
|
||||
})();
|
||||
};
|
||||
}
|
||||
|
||||
exports.createAsyncStoragePersistor = createAsyncStoragePersistor;
|
||||
|
||||
Object.defineProperty(exports, '__esModule', { value: true });
|
||||
|
||||
})));
|
||||
//# sourceMappingURL=createAsyncStoragePersistor-experimental.development.js.map
|
||||
Generated
Vendored
+1
File diff suppressed because one or more lines are too long
cc-frontend/node_modules/react-query/dist/createAsyncStoragePersistor-experimental.production.min.js
Generated
Vendored
+2
@@ -0,0 +1,2 @@
|
||||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e=e||self).ReactQueryCreateAsyncStoragePersistorExperimental={})}(this,(function(e){"use strict";function t(e,t,n){return n?t?t(e):e:(e&&e.then||(e=Promise.resolve(e)),t?e.then(t):e)}function n(e){return function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];try{return Promise.resolve(e.apply(this,t))}catch(e){return Promise.reject(e)}}}function r(){}function i(e){var t=e();if(t&&t.then)return t.then(r)}function o(e,r){var o=void 0===r?{}:r,u=o.interval,f=void 0===u?1e3:u,c=o.limit,s=void 0===c?1:c;if("function"!=typeof e)throw new Error("argument is not function.");var a,l={current:!1},v=0,d=[];return function(){for(var r=arguments.length,o=new Array(r),u=0;u<r;u++)o[u]=arguments[u];return n((function(){return l.current&&(v=Date.now(),d.length>s&&d.shift(),d.push(o),clearTimeout(a)),i((function(){if(Date.now()-v>f)return l.current=!0,t(e.apply(void 0,o),(function(){v=Date.now(),l.current=!1}));if(d.length>0){var r=d[d.length-1];a=setTimeout(n((function(){return i((function(){if(!l.current)return l.current=!0,t(e.apply(void 0,r),(function(){l.current=!1}))}))})),f)}}))}))()}}e.createAsyncStoragePersistor=function(e){var r=e.storage,i=e.key,u=void 0===i?"REACT_QUERY_OFFLINE_CACHE":i,f=e.throttleTime,c=void 0===f?1e3:f,s=e.serialize,a=void 0===s?JSON.stringify:s,l=e.deserialize,v=void 0===l?JSON.parse:l;return{persistClient:o((function(e){return r.setItem(u,a(e))}),{interval:c}),restoreClient:n((function(){return t(r.getItem(u),(function(e){if(e)return v(e)}))})),removeClient:function(){return r.removeItem(u)}}},Object.defineProperty(e,"__esModule",{value:!0})}));
|
||||
//# sourceMappingURL=createAsyncStoragePersistor-experimental.production.min.js.map
|
||||
Generated
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"createAsyncStoragePersistor-experimental.production.min.js","sources":["../src/createAsyncStoragePersistor-experimental/index.ts"],"sourcesContent":["import { PersistedClient, Persistor } from '../persistQueryClient-experimental'\n\ninterface AsyncStorage {\n getItem: (key: string) => Promise<string | null>\n setItem: (key: string, value: string) => Promise<void>\n removeItem: (key: string) => Promise<void>\n}\n\ninterface CreateAsyncStoragePersistorOptions {\n /** The storage client used for setting an retrieving items from cache */\n storage: AsyncStorage\n /** The key to use when storing the cache */\n key?: string\n /** To avoid spamming,\n * pass a time in ms to throttle saving the cache to disk */\n throttleTime?: number\n /**\n * How to serialize the data to storage.\n * @default `JSON.stringify`\n */\n serialize?: (client: PersistedClient) => string\n /**\n * How to deserialize the data from storage.\n * @default `JSON.parse`\n */\n deserialize?: (cachedString: string) => PersistedClient\n}\n\nexport const createAsyncStoragePersistor = ({\n storage,\n key = `REACT_QUERY_OFFLINE_CACHE`,\n throttleTime = 1000,\n serialize = JSON.stringify,\n deserialize = JSON.parse,\n}: CreateAsyncStoragePersistorOptions): Persistor => {\n return {\n persistClient: asyncThrottle(\n persistedClient => storage.setItem(key, serialize(persistedClient)),\n { interval: throttleTime }\n ),\n restoreClient: async () => {\n const cacheString = await storage.getItem(key)\n\n if (!cacheString) {\n return\n }\n\n return deserialize(cacheString) as PersistedClient\n },\n removeClient: () => storage.removeItem(key),\n }\n}\n\nfunction asyncThrottle<Args extends readonly unknown[], Result>(\n func: (...args: Args) => Promise<Result>,\n { interval = 1000, limit = 1 }: { interval?: number; limit?: number } = {}\n) {\n if (typeof func !== 'function') throw new Error('argument is not function.')\n const running = { current: false }\n let lastTime = 0\n let timeout: number\n const queue: Array<Args> = []\n return (...args: Args) =>\n (async () => {\n if (running.current) {\n lastTime = Date.now()\n if (queue.length > limit) {\n queue.shift()\n }\n\n queue.push(args)\n clearTimeout(timeout)\n }\n if (Date.now() - lastTime > interval) {\n running.current = true\n await func(...args)\n lastTime = Date.now()\n running.current = false\n } else {\n if (queue.length > 0) {\n const lastArgs = queue[queue.length - 1]!\n timeout = setTimeout(async () => {\n if (!running.current) {\n running.current = true\n await func(...lastArgs)\n running.current = false\n }\n }, interval)\n }\n }\n })()\n}\n"],"names":["value","then","direct","Promise","resolve","f","args","i","arguments","length","apply","this","e","reject","body","result","asyncThrottle","func","interval","limit","Error","timeout","running","current","lastTime","queue","_async","Date","now","shift","push","clearTimeout","lastArgs","setTimeout","storage","key","throttleTime","serialize","JSON","stringify","deserialize","parse","persistClient","persistedClient","setItem","restoreClient","getItem","cacheString","removeClient","removeItem"],"mappings":"+OAoFO,WAAgBA,EAAOC,EAAMC,UAC/BA,EACID,EAAOA,EAAKD,GAASA,GAExBA,GAAUA,EAAMC,OACpBD,EAAQG,QAAQC,QAAQJ,IAElBC,EAAOD,EAAMC,KAAKA,GAAQD,GArB3B,WAAgBK,UACf,eACD,IAAIC,EAAO,GAAIC,EAAI,EAAGA,EAAIC,UAAUC,OAAQF,IAChDD,EAAKC,GAAKC,UAAUD,cAGbJ,QAAQC,QAAQC,EAAEK,MAAMC,KAAML,IACpC,MAAMM,UACAT,QAAQU,OAAOD,KAkhBlB,cAtDA,WAAwBE,OAC1BC,EAASD,OACTC,GAAUA,EAAOd,YACbc,EAAOd,QAxfhB,SAASe,EACPC,sBACwE,SAAtEC,SAAAA,aAAW,UAAMC,MAAAA,aAAQ,OAEP,mBAATF,EAAqB,MAAM,IAAIG,MAAM,iCAG5CC,EAFEC,EAAU,CAAEC,SAAS,GACvBC,EAAW,EAETC,EAAqB,UACpB,sCAAInB,2BAAAA,yBACToB,qBACMJ,EAAQC,UACVC,EAAWG,KAAKC,MACZH,EAAMhB,OAASU,GACjBM,EAAMI,QAGRJ,EAAMK,KAAKxB,GACXyB,aAAaV,qBAEXM,KAAKC,MAAQJ,EAAWN,SAC1BI,EAAQC,SAAU,IACZN,eAAQX,eACdkB,EAAWG,KAAKC,MAChBN,EAAQC,SAAU,QAEdE,EAAMhB,OAAS,OACXuB,EAAWP,EAAMA,EAAMhB,OAAS,GACtCY,EAAUY,kDACHX,EAAQC,eACXD,EAAQC,SAAU,IACZN,eAAQe,eACdV,EAAQC,SAAU,WAEnBL,SAxBTQ,kCAnCuC,gBACzCQ,IAAAA,YACAC,IAAAA,+CACAC,aAAAA,aAAe,UACfC,UAAAA,aAAYC,KAAKC,gBACjBC,YAAAA,aAAcF,KAAKG,cAEZ,CACLC,cAAe1B,GACb,SAAA2B,UAAmBT,EAAQU,QAAQT,EAAKE,EAAUM,MAClD,CAAEzB,SAAUkB,IAEdS,qCAC4BX,EAAQY,QAAQX,aAApCY,MAEDA,SAIEP,EAAYO,SAErBC,aAAc,kBAAMd,EAAQe,WAAWd"}
|
||||
Generated
Vendored
+147
@@ -0,0 +1,147 @@
|
||||
(function (global, factory) {
|
||||
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
|
||||
typeof define === 'function' && define.amd ? define(['exports'], factory) :
|
||||
(global = global || self, factory(global.ReactQueryCreateWebStoragePersistorExperimental = {}));
|
||||
}(this, (function (exports) { 'use strict';
|
||||
|
||||
function _extends() {
|
||||
_extends = Object.assign || function (target) {
|
||||
for (var i = 1; i < arguments.length; i++) {
|
||||
var source = arguments[i];
|
||||
|
||||
for (var key in source) {
|
||||
if (Object.prototype.hasOwnProperty.call(source, key)) {
|
||||
target[key] = source[key];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return target;
|
||||
};
|
||||
|
||||
return _extends.apply(this, arguments);
|
||||
}
|
||||
|
||||
function noop() {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function createWebStoragePersistor(_ref) {
|
||||
var storage = _ref.storage,
|
||||
_ref$key = _ref.key,
|
||||
key = _ref$key === void 0 ? "REACT_QUERY_OFFLINE_CACHE" : _ref$key,
|
||||
_ref$throttleTime = _ref.throttleTime,
|
||||
throttleTime = _ref$throttleTime === void 0 ? 1000 : _ref$throttleTime,
|
||||
_ref$serialize = _ref.serialize,
|
||||
serialize = _ref$serialize === void 0 ? JSON.stringify : _ref$serialize,
|
||||
_ref$deserialize = _ref.deserialize,
|
||||
deserialize = _ref$deserialize === void 0 ? JSON.parse : _ref$deserialize;
|
||||
|
||||
//try to save data to storage
|
||||
function trySave(persistedClient) {
|
||||
try {
|
||||
storage.setItem(key, serialize(persistedClient));
|
||||
} catch (_unused) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
if (typeof storage !== 'undefined') {
|
||||
return {
|
||||
persistClient: throttle(function (persistedClient) {
|
||||
if (trySave(persistedClient) !== true) {
|
||||
var mutations = [].concat(persistedClient.clientState.mutations);
|
||||
var queries = [].concat(persistedClient.clientState.queries);
|
||||
|
||||
var _client = _extends({}, persistedClient, {
|
||||
clientState: {
|
||||
mutations: mutations,
|
||||
queries: queries
|
||||
}
|
||||
}); // sort queries by dataUpdatedAt (oldest first)
|
||||
|
||||
|
||||
var sortedQueries = [].concat(queries).sort(function (a, b) {
|
||||
return a.state.dataUpdatedAt - b.state.dataUpdatedAt;
|
||||
}); // clean old queries and try to save
|
||||
|
||||
var _loop = function _loop() {
|
||||
var oldestData = sortedQueries.shift();
|
||||
_client.clientState.queries = queries.filter(function (q) {
|
||||
return q !== oldestData;
|
||||
});
|
||||
|
||||
if (trySave(_client)) {
|
||||
return {
|
||||
v: void 0
|
||||
}; // save success
|
||||
}
|
||||
};
|
||||
|
||||
while (sortedQueries.length > 0) {
|
||||
var _ret = _loop();
|
||||
|
||||
if (typeof _ret === "object") return _ret.v;
|
||||
} // clean mutations and try to save
|
||||
|
||||
|
||||
while (mutations.shift()) {
|
||||
if (trySave(_client)) {
|
||||
return; // save success
|
||||
}
|
||||
}
|
||||
}
|
||||
}, throttleTime),
|
||||
restoreClient: function restoreClient() {
|
||||
var cacheString = storage.getItem(key);
|
||||
|
||||
if (!cacheString) {
|
||||
return;
|
||||
}
|
||||
|
||||
return deserialize(cacheString);
|
||||
},
|
||||
removeClient: function removeClient() {
|
||||
storage.removeItem(key);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
persistClient: noop,
|
||||
restoreClient: noop,
|
||||
removeClient: noop
|
||||
};
|
||||
}
|
||||
|
||||
function throttle(func, wait) {
|
||||
if (wait === void 0) {
|
||||
wait = 100;
|
||||
}
|
||||
|
||||
var timer = null;
|
||||
var params;
|
||||
return function () {
|
||||
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
|
||||
args[_key] = arguments[_key];
|
||||
}
|
||||
|
||||
params = args;
|
||||
|
||||
if (timer === null) {
|
||||
timer = setTimeout(function () {
|
||||
func.apply(void 0, params);
|
||||
timer = null;
|
||||
}, wait);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
exports.createWebStoragePersistor = createWebStoragePersistor;
|
||||
|
||||
Object.defineProperty(exports, '__esModule', { value: true });
|
||||
|
||||
})));
|
||||
//# sourceMappingURL=createWebStoragePersistor-experimental.development.js.map
|
||||
Generated
Vendored
+1
File diff suppressed because one or more lines are too long
Generated
Vendored
+2
@@ -0,0 +1,2 @@
|
||||
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t=t||self).ReactQueryCreateWebStoragePersistorExperimental={})}(this,(function(t){"use strict";function e(){return(e=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t}).apply(this,arguments)}function r(){}function n(t,e){void 0===e&&(e=100);var r,n=null;return function(){for(var i=arguments.length,o=new Array(i),a=0;a<i;a++)o[a]=arguments[a];r=o,null===n&&(n=setTimeout((function(){t.apply(void 0,r),n=null}),e))}}t.createWebStoragePersistor=function(t){var i=t.storage,o=t.key,a=void 0===o?"REACT_QUERY_OFFLINE_CACHE":o,u=t.throttleTime,f=void 0===u?1e3:u,s=t.serialize,c=void 0===s?JSON.stringify:s,l=t.deserialize,d=void 0===l?JSON.parse:l;function v(t){try{i.setItem(a,c(t))}catch(t){return!1}return!0}return void 0!==i?{persistClient:n((function(t){if(!0!==v(t)){for(var r=[].concat(t.clientState.mutations),n=[].concat(t.clientState.queries),i=e({},t,{clientState:{mutations:r,queries:n}}),o=[].concat(n).sort((function(t,e){return t.state.dataUpdatedAt-e.state.dataUpdatedAt})),a=function(){var t=o.shift();if(i.clientState.queries=n.filter((function(e){return e!==t})),v(i))return{v:void 0}};o.length>0;){var u=a();if("object"==typeof u)return u.v}for(;r.shift();)if(v(i))return}}),f),restoreClient:function(){var t=i.getItem(a);if(t)return d(t)},removeClient:function(){i.removeItem(a)}}:{persistClient:r,restoreClient:r,removeClient:r}},Object.defineProperty(t,"__esModule",{value:!0})}));
|
||||
//# sourceMappingURL=createWebStoragePersistor-experimental.production.min.js.map
|
||||
Generated
Vendored
+1
File diff suppressed because one or more lines are too long
Generated
Vendored
+124
@@ -0,0 +1,124 @@
|
||||
(function (global, factory) {
|
||||
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react-query')) :
|
||||
typeof define === 'function' && define.amd ? define(['exports', 'react-query'], factory) :
|
||||
(global = global || self, factory(global.ReactQueryPersistQueryClientExperimental = {}, global.ReactQuery));
|
||||
}(this, (function (exports, reactQuery) { 'use strict';
|
||||
|
||||
// TYPES
|
||||
// FUNCTIONS
|
||||
var logger = console;
|
||||
function getLogger() {
|
||||
return logger;
|
||||
}
|
||||
|
||||
function _await(value, then, direct) {
|
||||
if (direct) {
|
||||
return then ? then(value) : value;
|
||||
}
|
||||
|
||||
if (!value || !value.then) {
|
||||
value = Promise.resolve(value);
|
||||
}
|
||||
|
||||
return then ? value.then(then) : value;
|
||||
}
|
||||
|
||||
function _catch(body, recover) {
|
||||
try {
|
||||
var result = body();
|
||||
} catch (e) {
|
||||
return recover(e);
|
||||
}
|
||||
|
||||
if (result && result.then) {
|
||||
return result.then(void 0, recover);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function _continue(value, then) {
|
||||
return value && value.then ? value.then(then) : then(value);
|
||||
}
|
||||
|
||||
function _empty() {}
|
||||
|
||||
function _invokeIgnored(body) {
|
||||
var result = body();
|
||||
|
||||
if (result && result.then) {
|
||||
return result.then(_empty);
|
||||
}
|
||||
}
|
||||
|
||||
function _async(f) {
|
||||
return function () {
|
||||
for (var args = [], i = 0; i < arguments.length; i++) {
|
||||
args[i] = arguments[i];
|
||||
}
|
||||
|
||||
try {
|
||||
return Promise.resolve(f.apply(this, args));
|
||||
} catch (e) {
|
||||
return Promise.reject(e);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
var persistQueryClient = _async(function (_ref) {
|
||||
var queryClient = _ref.queryClient,
|
||||
persistor = _ref.persistor,
|
||||
_ref$maxAge = _ref.maxAge,
|
||||
maxAge = _ref$maxAge === void 0 ? 1000 * 60 * 60 * 24 : _ref$maxAge,
|
||||
_ref$buster = _ref.buster,
|
||||
buster = _ref$buster === void 0 ? '' : _ref$buster,
|
||||
hydrateOptions = _ref.hydrateOptions,
|
||||
dehydrateOptions = _ref.dehydrateOptions;
|
||||
return _invokeIgnored(function () {
|
||||
if (typeof window !== 'undefined') {
|
||||
// Subscribe to changes
|
||||
var saveClient = function saveClient() {
|
||||
var persistClient = {
|
||||
buster: buster,
|
||||
timestamp: Date.now(),
|
||||
clientState: reactQuery.dehydrate(queryClient, dehydrateOptions)
|
||||
};
|
||||
persistor.persistClient(persistClient);
|
||||
}; // Attempt restore
|
||||
|
||||
|
||||
return _continue(_catch(function () {
|
||||
return _await(persistor.restoreClient(), function (persistedClient) {
|
||||
if (persistedClient) {
|
||||
if (persistedClient.timestamp) {
|
||||
var expired = Date.now() - persistedClient.timestamp > maxAge;
|
||||
var busted = persistedClient.buster !== buster;
|
||||
|
||||
if (expired || busted) {
|
||||
persistor.removeClient();
|
||||
} else {
|
||||
reactQuery.hydrate(queryClient, persistedClient.clientState, hydrateOptions);
|
||||
}
|
||||
} else {
|
||||
persistor.removeClient();
|
||||
}
|
||||
}
|
||||
});
|
||||
}, function (err) {
|
||||
getLogger().error(err);
|
||||
getLogger().warn('Encountered an error attempting to restore client cache from persisted location. As a precaution, the persisted cache will be discarded.');
|
||||
persistor.removeClient();
|
||||
}), function () {
|
||||
// Subscribe to changes in the query cache to trigger the save
|
||||
queryClient.getQueryCache().subscribe(saveClient);
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
exports.persistQueryClient = persistQueryClient;
|
||||
|
||||
Object.defineProperty(exports, '__esModule', { value: true });
|
||||
|
||||
})));
|
||||
//# sourceMappingURL=persistQueryClient-experimental.development.js.map
|
||||
Generated
Vendored
+1
File diff suppressed because one or more lines are too long
Generated
Vendored
+2
@@ -0,0 +1,2 @@
|
||||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react-query")):"function"==typeof define&&define.amd?define(["exports","react-query"],t):t((e=e||self).ReactQueryPersistQueryClientExperimental={},e.ReactQuery)}(this,(function(e,t){"use strict";var r=console;function n(){return r}function i(){}var o,u=(o=function(e){var r=e.queryClient,o=e.persistor,u=e.maxAge,a=void 0===u?864e5:u,c=e.buster,s=void 0===c?"":c,f=e.hydrateOptions,d=e.dehydrateOptions;return function(e){var t=e();if(t&&t.then)return t.then(i)}((function(){if("undefined"!=typeof window){var e=function(){var e={buster:s,timestamp:Date.now(),clientState:t.dehydrate(r,d)};o.persistClient(e)};return function(e,t){return e&&e.then?e.then(t):t(e)}(function(e,t){try{var r=e()}catch(e){return t(e)}return r&&r.then?r.then(void 0,t):r}((function(){return e=o.restoreClient(),n=function(e){if(e)if(e.timestamp){var n=Date.now()-e.timestamp>a,i=e.buster!==s;n||i?o.removeClient():t.hydrate(r,e.clientState,f)}else o.removeClient()},i?n?n(e):e:(e&&e.then||(e=Promise.resolve(e)),n?e.then(n):e);var e,n,i}),(function(e){n().error(e),n().warn("Encountered an error attempting to restore client cache from persisted location. As a precaution, the persisted cache will be discarded."),o.removeClient()})),(function(){r.getQueryCache().subscribe(e)}))}}))},function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];try{return Promise.resolve(o.apply(this,e))}catch(e){return Promise.reject(e)}});e.persistQueryClient=u,Object.defineProperty(e,"__esModule",{value:!0})}));
|
||||
//# sourceMappingURL=persistQueryClient-experimental.production.min.js.map
|
||||
Generated
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"persistQueryClient-experimental.production.min.js","sources":["../src/core/logger.ts","../src/persistQueryClient-experimental/index.ts"],"sourcesContent":["// TYPES\n\nexport interface Logger {\n log: LogFunction\n warn: LogFunction\n error: LogFunction\n}\n\ntype LogFunction = (...args: any[]) => void\n\n// FUNCTIONS\n\nlet logger: Logger = console\n\nexport function getLogger(): Logger {\n return logger\n}\n\nexport function setLogger(newLogger: Logger) {\n logger = newLogger\n}\n","import { QueryClient } from '../core'\nimport { getLogger } from '../core/logger'\nimport {\n dehydrate,\n DehydratedState,\n DehydrateOptions,\n HydrateOptions,\n hydrate,\n} from 'react-query'\nimport { Promisable } from 'type-fest'\n\nexport interface Persistor {\n persistClient(persistClient: PersistedClient): Promisable<void>\n restoreClient(): Promisable<PersistedClient | undefined>\n removeClient(): Promisable<void>\n}\n\nexport interface PersistedClient {\n timestamp: number\n buster: string\n clientState: DehydratedState\n}\n\nexport interface PersistQueryClientOptions {\n /** The QueryClient to persist */\n queryClient: QueryClient\n /** The Persistor interface for storing and restoring the cache\n * to/from a persisted location */\n persistor: Persistor\n /** The max-allowed age of the cache.\n * If a persisted cache is found that is older than this\n * time, it will be discarded */\n maxAge?: number\n /** A unique string that can be used to forcefully\n * invalidate existing caches if they do not share the same buster string */\n buster?: string\n /** The options passed to the hydrate function */\n hydrateOptions?: HydrateOptions\n /** The options passed to the dehydrate function */\n dehydrateOptions?: DehydrateOptions\n}\n\nexport async function persistQueryClient({\n queryClient,\n persistor,\n maxAge = 1000 * 60 * 60 * 24,\n buster = '',\n hydrateOptions,\n dehydrateOptions,\n}: PersistQueryClientOptions) {\n if (typeof window !== 'undefined') {\n // Subscribe to changes\n const saveClient = () => {\n const persistClient: PersistedClient = {\n buster,\n timestamp: Date.now(),\n clientState: dehydrate(queryClient, dehydrateOptions),\n }\n\n persistor.persistClient(persistClient)\n }\n\n // Attempt restore\n try {\n const persistedClient = await persistor.restoreClient()\n\n if (persistedClient) {\n if (persistedClient.timestamp) {\n const expired = Date.now() - persistedClient.timestamp > maxAge\n const busted = persistedClient.buster !== buster\n if (expired || busted) {\n persistor.removeClient()\n } else {\n hydrate(queryClient, persistedClient.clientState, hydrateOptions)\n }\n } else {\n persistor.removeClient()\n }\n }\n } catch (err) {\n getLogger().error(err)\n getLogger().warn(\n 'Encountered an error attempting to restore client cache from persisted location. As a precaution, the persisted cache will be discarded.'\n )\n persistor.removeClient()\n }\n\n // Subscribe to changes in the query cache to trigger the save\n queryClient.getQueryCache().subscribe(saveClient)\n }\n}\n"],"names":["logger","console","getLogger","f","persistQueryClient","queryClient","persistor","maxAge","buster","hydrateOptions","dehydrateOptions","body","result","then","window","saveClient","persistClient","timestamp","Date","now","clientState","dehydrate","value","recover","e","restoreClient","persistedClient","expired","busted","removeClient","hydrate","direct","Promise","resolve","err","error","warn","getQueryCache","subscribe","args","i","arguments","length","apply","this","reject"],"mappings":"0RAYA,IAAIA,EAAiBC,QAEd,SAASC,WACPF,ECilBF,kBA1hBgBG,EA5BDC,GA4BCD,kBA3BrBE,IAAAA,YACAC,IAAAA,cACAC,OAAAA,aAAS,YACTC,OAAAA,aAAS,KACTC,IAAAA,eACAC,IAAAA,wBA0fK,SAAwBC,OAC1BC,EAASD,OACTC,GAAUA,EAAOC,YACbD,EAAOC,wBA3fQ,oBAAXC,YAEHC,EAAa,eACXC,EAAiC,CACrCR,OAAAA,EACAS,UAAWC,KAAKC,MAChBC,YAAaC,YAAUhB,EAAaK,IAGtCJ,EAAUU,cAAcA,WA2CvB,SAAmBM,EAAOT,UACzBS,GAASA,EAAMT,KAAOS,EAAMT,KAAKA,GAAQA,EAAKS,IA2c/C,SAAgBX,EAAMY,WAEvBX,EAASD,IACZ,MAAMa,UACAD,EAAQC,UAEZZ,GAAUA,EAAOC,KACbD,EAAOC,UAAK,EAAQU,GAErBX,sBAveeU,EApBahB,EAAUmB,gBAoBhBZ,WApBlBa,MAEFA,KACEA,EAAgBT,eACZU,EAAUT,KAAKC,MAAQO,EAAgBT,UAAYV,EACnDqB,EAASF,EAAgBlB,SAAWA,EACtCmB,GAAWC,EACbtB,EAAUuB,eAEVC,UAAQzB,EAAaqB,EAAgBN,YAAaX,QAGpDH,EAAUuB,gBASfE,EACIlB,EAAOA,EAAKS,GAASA,GAExBA,GAAUA,EAAMT,OACpBS,EAAQU,QAAQC,QAAQX,IAElBT,EAAOS,EAAMT,KAAKA,GAAQS,GAP3B,IAAgBA,EAAOT,EAAMkB,cALvBG,GACPhC,IAAYiC,MAAMD,GAClBhC,IAAYkC,KACV,4IAEF9B,EAAUuB,8BAIZxB,EAAYgC,gBAAgBC,UAAUvB,WAjBlC,eACD,IAAIwB,EAAO,GAAIC,EAAI,EAAGA,EAAIC,UAAUC,OAAQF,IAChDD,EAAKC,GAAKC,UAAUD,cAGbR,QAAQC,QAAQ9B,EAAEwC,MAAMC,KAAML,IACpC,MAAMf,UACAQ,QAAQa,OAAOrB"}
|
||||
+3355
@@ -0,0 +1,3355 @@
|
||||
(function (global, factory) {
|
||||
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
|
||||
typeof define === 'function' && define.amd ? define(['exports'], factory) :
|
||||
(global = global || self, factory(global.ReactQueryCore = {}));
|
||||
}(this, (function (exports) { 'use strict';
|
||||
|
||||
function _inheritsLoose(subClass, superClass) {
|
||||
subClass.prototype = Object.create(superClass.prototype);
|
||||
subClass.prototype.constructor = subClass;
|
||||
subClass.__proto__ = superClass;
|
||||
}
|
||||
|
||||
var Subscribable = /*#__PURE__*/function () {
|
||||
function Subscribable() {
|
||||
this.listeners = [];
|
||||
}
|
||||
|
||||
var _proto = Subscribable.prototype;
|
||||
|
||||
_proto.subscribe = function subscribe(listener) {
|
||||
var _this = this;
|
||||
|
||||
var callback = listener || function () {
|
||||
return undefined;
|
||||
};
|
||||
|
||||
this.listeners.push(callback);
|
||||
this.onSubscribe();
|
||||
return function () {
|
||||
_this.listeners = _this.listeners.filter(function (x) {
|
||||
return x !== callback;
|
||||
});
|
||||
|
||||
_this.onUnsubscribe();
|
||||
};
|
||||
};
|
||||
|
||||
_proto.hasListeners = function hasListeners() {
|
||||
return this.listeners.length > 0;
|
||||
};
|
||||
|
||||
_proto.onSubscribe = function onSubscribe() {// Do nothing
|
||||
};
|
||||
|
||||
_proto.onUnsubscribe = function onUnsubscribe() {// Do nothing
|
||||
};
|
||||
|
||||
return Subscribable;
|
||||
}();
|
||||
|
||||
function _extends() {
|
||||
_extends = Object.assign || function (target) {
|
||||
for (var i = 1; i < arguments.length; i++) {
|
||||
var source = arguments[i];
|
||||
|
||||
for (var key in source) {
|
||||
if (Object.prototype.hasOwnProperty.call(source, key)) {
|
||||
target[key] = source[key];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return target;
|
||||
};
|
||||
|
||||
return _extends.apply(this, arguments);
|
||||
}
|
||||
|
||||
// TYPES
|
||||
// UTILS
|
||||
var isServer = typeof window === 'undefined';
|
||||
function noop() {
|
||||
return undefined;
|
||||
}
|
||||
function functionalUpdate(updater, input) {
|
||||
return typeof updater === 'function' ? updater(input) : updater;
|
||||
}
|
||||
function isValidTimeout(value) {
|
||||
return typeof value === 'number' && value >= 0 && value !== Infinity;
|
||||
}
|
||||
function ensureQueryKeyArray(value) {
|
||||
return Array.isArray(value) ? value : [value];
|
||||
}
|
||||
function difference(array1, array2) {
|
||||
return array1.filter(function (x) {
|
||||
return array2.indexOf(x) === -1;
|
||||
});
|
||||
}
|
||||
function replaceAt(array, index, value) {
|
||||
var copy = array.slice(0);
|
||||
copy[index] = value;
|
||||
return copy;
|
||||
}
|
||||
function timeUntilStale(updatedAt, staleTime) {
|
||||
return Math.max(updatedAt + (staleTime || 0) - Date.now(), 0);
|
||||
}
|
||||
function parseQueryArgs(arg1, arg2, arg3) {
|
||||
if (!isQueryKey(arg1)) {
|
||||
return arg1;
|
||||
}
|
||||
|
||||
if (typeof arg2 === 'function') {
|
||||
return _extends({}, arg3, {
|
||||
queryKey: arg1,
|
||||
queryFn: arg2
|
||||
});
|
||||
}
|
||||
|
||||
return _extends({}, arg2, {
|
||||
queryKey: arg1
|
||||
});
|
||||
}
|
||||
function parseFilterArgs(arg1, arg2, arg3) {
|
||||
return isQueryKey(arg1) ? [_extends({}, arg2, {
|
||||
queryKey: arg1
|
||||
}), arg3] : [arg1 || {}, arg2];
|
||||
}
|
||||
function mapQueryStatusFilter(active, inactive) {
|
||||
if (active === true && inactive === true || active == null && inactive == null) {
|
||||
return 'all';
|
||||
} else if (active === false && inactive === false) {
|
||||
return 'none';
|
||||
} else {
|
||||
// At this point, active|inactive can only be true|false or false|true
|
||||
// so, when only one value is provided, the missing one has to be the negated value
|
||||
var isActive = active != null ? active : !inactive;
|
||||
return isActive ? 'active' : 'inactive';
|
||||
}
|
||||
}
|
||||
function matchQuery(filters, query) {
|
||||
var active = filters.active,
|
||||
exact = filters.exact,
|
||||
fetching = filters.fetching,
|
||||
inactive = filters.inactive,
|
||||
predicate = filters.predicate,
|
||||
queryKey = filters.queryKey,
|
||||
stale = filters.stale;
|
||||
|
||||
if (isQueryKey(queryKey)) {
|
||||
if (exact) {
|
||||
if (query.queryHash !== hashQueryKeyByOptions(queryKey, query.options)) {
|
||||
return false;
|
||||
}
|
||||
} else if (!partialMatchKey(query.queryKey, queryKey)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
var queryStatusFilter = mapQueryStatusFilter(active, inactive);
|
||||
|
||||
if (queryStatusFilter === 'none') {
|
||||
return false;
|
||||
} else if (queryStatusFilter !== 'all') {
|
||||
var isActive = query.isActive();
|
||||
|
||||
if (queryStatusFilter === 'active' && !isActive) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (queryStatusFilter === 'inactive' && isActive) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof stale === 'boolean' && query.isStale() !== stale) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (typeof fetching === 'boolean' && query.isFetching() !== fetching) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (predicate && !predicate(query)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
function matchMutation(filters, mutation) {
|
||||
var exact = filters.exact,
|
||||
fetching = filters.fetching,
|
||||
predicate = filters.predicate,
|
||||
mutationKey = filters.mutationKey;
|
||||
|
||||
if (isQueryKey(mutationKey)) {
|
||||
if (!mutation.options.mutationKey) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (exact) {
|
||||
if (hashQueryKey(mutation.options.mutationKey) !== hashQueryKey(mutationKey)) {
|
||||
return false;
|
||||
}
|
||||
} else if (!partialMatchKey(mutation.options.mutationKey, mutationKey)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof fetching === 'boolean' && mutation.state.status === 'loading' !== fetching) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (predicate && !predicate(mutation)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
function hashQueryKeyByOptions(queryKey, options) {
|
||||
var hashFn = (options == null ? void 0 : options.queryKeyHashFn) || hashQueryKey;
|
||||
return hashFn(queryKey);
|
||||
}
|
||||
/**
|
||||
* Default query keys hash function.
|
||||
*/
|
||||
|
||||
function hashQueryKey(queryKey) {
|
||||
var asArray = ensureQueryKeyArray(queryKey);
|
||||
return stableValueHash(asArray);
|
||||
}
|
||||
/**
|
||||
* Hashes the value into a stable hash.
|
||||
*/
|
||||
|
||||
function stableValueHash(value) {
|
||||
return JSON.stringify(value, function (_, val) {
|
||||
return isPlainObject(val) ? Object.keys(val).sort().reduce(function (result, key) {
|
||||
result[key] = val[key];
|
||||
return result;
|
||||
}, {}) : val;
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Checks if key `b` partially matches with key `a`.
|
||||
*/
|
||||
|
||||
function partialMatchKey(a, b) {
|
||||
return partialDeepEqual(ensureQueryKeyArray(a), ensureQueryKeyArray(b));
|
||||
}
|
||||
/**
|
||||
* Checks if `b` partially matches with `a`.
|
||||
*/
|
||||
|
||||
function partialDeepEqual(a, b) {
|
||||
if (a === b) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (typeof a !== typeof b) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (a && b && typeof a === 'object' && typeof b === 'object') {
|
||||
return !Object.keys(b).some(function (key) {
|
||||
return !partialDeepEqual(a[key], b[key]);
|
||||
});
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
/**
|
||||
* This function returns `a` if `b` is deeply equal.
|
||||
* If not, it will replace any deeply equal children of `b` with those of `a`.
|
||||
* This can be used for structural sharing between JSON values for example.
|
||||
*/
|
||||
|
||||
function replaceEqualDeep(a, b) {
|
||||
if (a === b) {
|
||||
return a;
|
||||
}
|
||||
|
||||
var array = Array.isArray(a) && Array.isArray(b);
|
||||
|
||||
if (array || isPlainObject(a) && isPlainObject(b)) {
|
||||
var aSize = array ? a.length : Object.keys(a).length;
|
||||
var bItems = array ? b : Object.keys(b);
|
||||
var bSize = bItems.length;
|
||||
var copy = array ? [] : {};
|
||||
var equalItems = 0;
|
||||
|
||||
for (var i = 0; i < bSize; i++) {
|
||||
var key = array ? i : bItems[i];
|
||||
copy[key] = replaceEqualDeep(a[key], b[key]);
|
||||
|
||||
if (copy[key] === a[key]) {
|
||||
equalItems++;
|
||||
}
|
||||
}
|
||||
|
||||
return aSize === bSize && equalItems === aSize ? a : copy;
|
||||
}
|
||||
|
||||
return b;
|
||||
}
|
||||
/**
|
||||
* Shallow compare objects. Only works with objects that always have the same properties.
|
||||
*/
|
||||
|
||||
function shallowEqualObjects(a, b) {
|
||||
if (a && !b || b && !a) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (var key in a) {
|
||||
if (a[key] !== b[key]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
} // Copied from: https://github.com/jonschlinkert/is-plain-object
|
||||
|
||||
function isPlainObject(o) {
|
||||
if (!hasObjectPrototype(o)) {
|
||||
return false;
|
||||
} // If has modified constructor
|
||||
|
||||
|
||||
var ctor = o.constructor;
|
||||
|
||||
if (typeof ctor === 'undefined') {
|
||||
return true;
|
||||
} // If has modified prototype
|
||||
|
||||
|
||||
var prot = ctor.prototype;
|
||||
|
||||
if (!hasObjectPrototype(prot)) {
|
||||
return false;
|
||||
} // If constructor does not have an Object-specific method
|
||||
|
||||
|
||||
if (!prot.hasOwnProperty('isPrototypeOf')) {
|
||||
return false;
|
||||
} // Most likely a plain Object
|
||||
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
function hasObjectPrototype(o) {
|
||||
return Object.prototype.toString.call(o) === '[object Object]';
|
||||
}
|
||||
|
||||
function isQueryKey(value) {
|
||||
return typeof value === 'string' || Array.isArray(value);
|
||||
}
|
||||
function isError(value) {
|
||||
return value instanceof Error;
|
||||
}
|
||||
function sleep(timeout) {
|
||||
return new Promise(function (resolve) {
|
||||
setTimeout(resolve, timeout);
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Schedules a microtask.
|
||||
* This can be useful to schedule state updates after rendering.
|
||||
*/
|
||||
|
||||
function scheduleMicrotask(callback) {
|
||||
Promise.resolve().then(callback).catch(function (error) {
|
||||
return setTimeout(function () {
|
||||
throw error;
|
||||
});
|
||||
});
|
||||
}
|
||||
function getAbortController() {
|
||||
if (typeof AbortController === 'function') {
|
||||
return new AbortController();
|
||||
}
|
||||
}
|
||||
|
||||
var FocusManager = /*#__PURE__*/function (_Subscribable) {
|
||||
_inheritsLoose(FocusManager, _Subscribable);
|
||||
|
||||
function FocusManager() {
|
||||
var _this;
|
||||
|
||||
_this = _Subscribable.call(this) || this;
|
||||
|
||||
_this.setup = function (onFocus) {
|
||||
var _window;
|
||||
|
||||
if (!isServer && ((_window = window) == null ? void 0 : _window.addEventListener)) {
|
||||
var listener = function listener() {
|
||||
return onFocus();
|
||||
}; // Listen to visibillitychange and focus
|
||||
|
||||
|
||||
window.addEventListener('visibilitychange', listener, false);
|
||||
window.addEventListener('focus', listener, false);
|
||||
return function () {
|
||||
// Be sure to unsubscribe if a new handler is set
|
||||
window.removeEventListener('visibilitychange', listener);
|
||||
window.removeEventListener('focus', listener);
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
return _this;
|
||||
}
|
||||
|
||||
var _proto = FocusManager.prototype;
|
||||
|
||||
_proto.onSubscribe = function onSubscribe() {
|
||||
if (!this.cleanup) {
|
||||
this.setEventListener(this.setup);
|
||||
}
|
||||
};
|
||||
|
||||
_proto.onUnsubscribe = function onUnsubscribe() {
|
||||
if (!this.hasListeners()) {
|
||||
var _this$cleanup;
|
||||
|
||||
(_this$cleanup = this.cleanup) == null ? void 0 : _this$cleanup.call(this);
|
||||
this.cleanup = undefined;
|
||||
}
|
||||
};
|
||||
|
||||
_proto.setEventListener = function setEventListener(setup) {
|
||||
var _this$cleanup2,
|
||||
_this2 = this;
|
||||
|
||||
this.setup = setup;
|
||||
(_this$cleanup2 = this.cleanup) == null ? void 0 : _this$cleanup2.call(this);
|
||||
this.cleanup = setup(function (focused) {
|
||||
if (typeof focused === 'boolean') {
|
||||
_this2.setFocused(focused);
|
||||
} else {
|
||||
_this2.onFocus();
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
_proto.setFocused = function setFocused(focused) {
|
||||
this.focused = focused;
|
||||
|
||||
if (focused) {
|
||||
this.onFocus();
|
||||
}
|
||||
};
|
||||
|
||||
_proto.onFocus = function onFocus() {
|
||||
this.listeners.forEach(function (listener) {
|
||||
listener();
|
||||
});
|
||||
};
|
||||
|
||||
_proto.isFocused = function isFocused() {
|
||||
if (typeof this.focused === 'boolean') {
|
||||
return this.focused;
|
||||
} // document global can be unavailable in react native
|
||||
|
||||
|
||||
if (typeof document === 'undefined') {
|
||||
return true;
|
||||
}
|
||||
|
||||
return [undefined, 'visible', 'prerender'].includes(document.visibilityState);
|
||||
};
|
||||
|
||||
return FocusManager;
|
||||
}(Subscribable);
|
||||
var focusManager = new FocusManager();
|
||||
|
||||
var OnlineManager = /*#__PURE__*/function (_Subscribable) {
|
||||
_inheritsLoose(OnlineManager, _Subscribable);
|
||||
|
||||
function OnlineManager() {
|
||||
var _this;
|
||||
|
||||
_this = _Subscribable.call(this) || this;
|
||||
|
||||
_this.setup = function (onOnline) {
|
||||
var _window;
|
||||
|
||||
if (!isServer && ((_window = window) == null ? void 0 : _window.addEventListener)) {
|
||||
var listener = function listener() {
|
||||
return onOnline();
|
||||
}; // Listen to online
|
||||
|
||||
|
||||
window.addEventListener('online', listener, false);
|
||||
window.addEventListener('offline', listener, false);
|
||||
return function () {
|
||||
// Be sure to unsubscribe if a new handler is set
|
||||
window.removeEventListener('online', listener);
|
||||
window.removeEventListener('offline', listener);
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
return _this;
|
||||
}
|
||||
|
||||
var _proto = OnlineManager.prototype;
|
||||
|
||||
_proto.onSubscribe = function onSubscribe() {
|
||||
if (!this.cleanup) {
|
||||
this.setEventListener(this.setup);
|
||||
}
|
||||
};
|
||||
|
||||
_proto.onUnsubscribe = function onUnsubscribe() {
|
||||
if (!this.hasListeners()) {
|
||||
var _this$cleanup;
|
||||
|
||||
(_this$cleanup = this.cleanup) == null ? void 0 : _this$cleanup.call(this);
|
||||
this.cleanup = undefined;
|
||||
}
|
||||
};
|
||||
|
||||
_proto.setEventListener = function setEventListener(setup) {
|
||||
var _this$cleanup2,
|
||||
_this2 = this;
|
||||
|
||||
this.setup = setup;
|
||||
(_this$cleanup2 = this.cleanup) == null ? void 0 : _this$cleanup2.call(this);
|
||||
this.cleanup = setup(function (online) {
|
||||
if (typeof online === 'boolean') {
|
||||
_this2.setOnline(online);
|
||||
} else {
|
||||
_this2.onOnline();
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
_proto.setOnline = function setOnline(online) {
|
||||
this.online = online;
|
||||
|
||||
if (online) {
|
||||
this.onOnline();
|
||||
}
|
||||
};
|
||||
|
||||
_proto.onOnline = function onOnline() {
|
||||
this.listeners.forEach(function (listener) {
|
||||
listener();
|
||||
});
|
||||
};
|
||||
|
||||
_proto.isOnline = function isOnline() {
|
||||
if (typeof this.online === 'boolean') {
|
||||
return this.online;
|
||||
}
|
||||
|
||||
if (typeof navigator === 'undefined' || typeof navigator.onLine === 'undefined') {
|
||||
return true;
|
||||
}
|
||||
|
||||
return navigator.onLine;
|
||||
};
|
||||
|
||||
return OnlineManager;
|
||||
}(Subscribable);
|
||||
var onlineManager = new OnlineManager();
|
||||
|
||||
function defaultRetryDelay(failureCount) {
|
||||
return Math.min(1000 * Math.pow(2, failureCount), 30000);
|
||||
}
|
||||
|
||||
function isCancelable(value) {
|
||||
return typeof (value == null ? void 0 : value.cancel) === 'function';
|
||||
}
|
||||
var CancelledError = function CancelledError(options) {
|
||||
this.revert = options == null ? void 0 : options.revert;
|
||||
this.silent = options == null ? void 0 : options.silent;
|
||||
};
|
||||
function isCancelledError(value) {
|
||||
return value instanceof CancelledError;
|
||||
} // CLASS
|
||||
|
||||
var Retryer = function Retryer(config) {
|
||||
var _this = this;
|
||||
|
||||
var cancelRetry = false;
|
||||
var cancelFn;
|
||||
var continueFn;
|
||||
var promiseResolve;
|
||||
var promiseReject;
|
||||
this.abort = config.abort;
|
||||
|
||||
this.cancel = function (cancelOptions) {
|
||||
return cancelFn == null ? void 0 : cancelFn(cancelOptions);
|
||||
};
|
||||
|
||||
this.cancelRetry = function () {
|
||||
cancelRetry = true;
|
||||
};
|
||||
|
||||
this.continueRetry = function () {
|
||||
cancelRetry = false;
|
||||
};
|
||||
|
||||
this.continue = function () {
|
||||
return continueFn == null ? void 0 : continueFn();
|
||||
};
|
||||
|
||||
this.failureCount = 0;
|
||||
this.isPaused = false;
|
||||
this.isResolved = false;
|
||||
this.isTransportCancelable = false;
|
||||
this.promise = new Promise(function (outerResolve, outerReject) {
|
||||
promiseResolve = outerResolve;
|
||||
promiseReject = outerReject;
|
||||
});
|
||||
|
||||
var resolve = function resolve(value) {
|
||||
if (!_this.isResolved) {
|
||||
_this.isResolved = true;
|
||||
config.onSuccess == null ? void 0 : config.onSuccess(value);
|
||||
continueFn == null ? void 0 : continueFn();
|
||||
promiseResolve(value);
|
||||
}
|
||||
};
|
||||
|
||||
var reject = function reject(value) {
|
||||
if (!_this.isResolved) {
|
||||
_this.isResolved = true;
|
||||
config.onError == null ? void 0 : config.onError(value);
|
||||
continueFn == null ? void 0 : continueFn();
|
||||
promiseReject(value);
|
||||
}
|
||||
};
|
||||
|
||||
var pause = function pause() {
|
||||
return new Promise(function (continueResolve) {
|
||||
continueFn = continueResolve;
|
||||
_this.isPaused = true;
|
||||
config.onPause == null ? void 0 : config.onPause();
|
||||
}).then(function () {
|
||||
continueFn = undefined;
|
||||
_this.isPaused = false;
|
||||
config.onContinue == null ? void 0 : config.onContinue();
|
||||
});
|
||||
}; // Create loop function
|
||||
|
||||
|
||||
var run = function run() {
|
||||
// Do nothing if already resolved
|
||||
if (_this.isResolved) {
|
||||
return;
|
||||
}
|
||||
|
||||
var promiseOrValue; // Execute query
|
||||
|
||||
try {
|
||||
promiseOrValue = config.fn();
|
||||
} catch (error) {
|
||||
promiseOrValue = Promise.reject(error);
|
||||
} // Create callback to cancel this fetch
|
||||
|
||||
|
||||
cancelFn = function cancelFn(cancelOptions) {
|
||||
if (!_this.isResolved) {
|
||||
reject(new CancelledError(cancelOptions));
|
||||
_this.abort == null ? void 0 : _this.abort(); // Cancel transport if supported
|
||||
|
||||
if (isCancelable(promiseOrValue)) {
|
||||
try {
|
||||
promiseOrValue.cancel();
|
||||
} catch (_unused) {}
|
||||
}
|
||||
}
|
||||
}; // Check if the transport layer support cancellation
|
||||
|
||||
|
||||
_this.isTransportCancelable = isCancelable(promiseOrValue);
|
||||
Promise.resolve(promiseOrValue).then(resolve).catch(function (error) {
|
||||
var _config$retry, _config$retryDelay;
|
||||
|
||||
// Stop if the fetch is already resolved
|
||||
if (_this.isResolved) {
|
||||
return;
|
||||
} // Do we need to retry the request?
|
||||
|
||||
|
||||
var retry = (_config$retry = config.retry) != null ? _config$retry : 3;
|
||||
var retryDelay = (_config$retryDelay = config.retryDelay) != null ? _config$retryDelay : defaultRetryDelay;
|
||||
var delay = typeof retryDelay === 'function' ? retryDelay(_this.failureCount, error) : retryDelay;
|
||||
var shouldRetry = retry === true || typeof retry === 'number' && _this.failureCount < retry || typeof retry === 'function' && retry(_this.failureCount, error);
|
||||
|
||||
if (cancelRetry || !shouldRetry) {
|
||||
// We are done if the query does not need to be retried
|
||||
reject(error);
|
||||
return;
|
||||
}
|
||||
|
||||
_this.failureCount++; // Notify on fail
|
||||
|
||||
config.onFail == null ? void 0 : config.onFail(_this.failureCount, error); // Delay
|
||||
|
||||
sleep(delay) // Pause if the document is not visible or when the device is offline
|
||||
.then(function () {
|
||||
if (!focusManager.isFocused() || !onlineManager.isOnline()) {
|
||||
return pause();
|
||||
}
|
||||
}).then(function () {
|
||||
if (cancelRetry) {
|
||||
reject(error);
|
||||
} else {
|
||||
run();
|
||||
}
|
||||
});
|
||||
});
|
||||
}; // Start loop
|
||||
|
||||
|
||||
run();
|
||||
};
|
||||
|
||||
// CLASS
|
||||
var NotifyManager = /*#__PURE__*/function () {
|
||||
function NotifyManager() {
|
||||
this.queue = [];
|
||||
this.transactions = 0;
|
||||
|
||||
this.notifyFn = function (callback) {
|
||||
callback();
|
||||
};
|
||||
|
||||
this.batchNotifyFn = function (callback) {
|
||||
callback();
|
||||
};
|
||||
}
|
||||
|
||||
var _proto = NotifyManager.prototype;
|
||||
|
||||
_proto.batch = function batch(callback) {
|
||||
var result;
|
||||
this.transactions++;
|
||||
|
||||
try {
|
||||
result = callback();
|
||||
} finally {
|
||||
this.transactions--;
|
||||
|
||||
if (!this.transactions) {
|
||||
this.flush();
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
_proto.schedule = function schedule(callback) {
|
||||
var _this = this;
|
||||
|
||||
if (this.transactions) {
|
||||
this.queue.push(callback);
|
||||
} else {
|
||||
scheduleMicrotask(function () {
|
||||
_this.notifyFn(callback);
|
||||
});
|
||||
}
|
||||
}
|
||||
/**
|
||||
* All calls to the wrapped function will be batched.
|
||||
*/
|
||||
;
|
||||
|
||||
_proto.batchCalls = function batchCalls(callback) {
|
||||
var _this2 = this;
|
||||
|
||||
return function () {
|
||||
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
|
||||
args[_key] = arguments[_key];
|
||||
}
|
||||
|
||||
_this2.schedule(function () {
|
||||
callback.apply(void 0, args);
|
||||
});
|
||||
};
|
||||
};
|
||||
|
||||
_proto.flush = function flush() {
|
||||
var _this3 = this;
|
||||
|
||||
var queue = this.queue;
|
||||
this.queue = [];
|
||||
|
||||
if (queue.length) {
|
||||
scheduleMicrotask(function () {
|
||||
_this3.batchNotifyFn(function () {
|
||||
queue.forEach(function (callback) {
|
||||
_this3.notifyFn(callback);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Use this method to set a custom notify function.
|
||||
* This can be used to for example wrap notifications with `React.act` while running tests.
|
||||
*/
|
||||
;
|
||||
|
||||
_proto.setNotifyFunction = function setNotifyFunction(fn) {
|
||||
this.notifyFn = fn;
|
||||
}
|
||||
/**
|
||||
* Use this method to set a custom function to batch notifications together into a single tick.
|
||||
* By default React Query will use the batch function provided by ReactDOM or React Native.
|
||||
*/
|
||||
;
|
||||
|
||||
_proto.setBatchNotifyFunction = function setBatchNotifyFunction(fn) {
|
||||
this.batchNotifyFn = fn;
|
||||
};
|
||||
|
||||
return NotifyManager;
|
||||
}(); // SINGLETON
|
||||
|
||||
var notifyManager = new NotifyManager();
|
||||
|
||||
// TYPES
|
||||
// FUNCTIONS
|
||||
var logger = console;
|
||||
function getLogger() {
|
||||
return logger;
|
||||
}
|
||||
function setLogger(newLogger) {
|
||||
logger = newLogger;
|
||||
}
|
||||
|
||||
// CLASS
|
||||
var Query = /*#__PURE__*/function () {
|
||||
function Query(config) {
|
||||
this.abortSignalConsumed = false;
|
||||
this.hadObservers = false;
|
||||
this.defaultOptions = config.defaultOptions;
|
||||
this.setOptions(config.options);
|
||||
this.observers = [];
|
||||
this.cache = config.cache;
|
||||
this.queryKey = config.queryKey;
|
||||
this.queryHash = config.queryHash;
|
||||
this.initialState = config.state || this.getDefaultState(this.options);
|
||||
this.state = this.initialState;
|
||||
this.meta = config.meta;
|
||||
this.scheduleGc();
|
||||
}
|
||||
|
||||
var _proto = Query.prototype;
|
||||
|
||||
_proto.setOptions = function setOptions(options) {
|
||||
var _this$options$cacheTi;
|
||||
|
||||
this.options = _extends({}, this.defaultOptions, options);
|
||||
this.meta = options == null ? void 0 : options.meta; // Default to 5 minutes if not cache time is set
|
||||
|
||||
this.cacheTime = Math.max(this.cacheTime || 0, (_this$options$cacheTi = this.options.cacheTime) != null ? _this$options$cacheTi : 5 * 60 * 1000);
|
||||
};
|
||||
|
||||
_proto.setDefaultOptions = function setDefaultOptions(options) {
|
||||
this.defaultOptions = options;
|
||||
};
|
||||
|
||||
_proto.scheduleGc = function scheduleGc() {
|
||||
var _this = this;
|
||||
|
||||
this.clearGcTimeout();
|
||||
|
||||
if (isValidTimeout(this.cacheTime)) {
|
||||
this.gcTimeout = setTimeout(function () {
|
||||
_this.optionalRemove();
|
||||
}, this.cacheTime);
|
||||
}
|
||||
};
|
||||
|
||||
_proto.clearGcTimeout = function clearGcTimeout() {
|
||||
if (this.gcTimeout) {
|
||||
clearTimeout(this.gcTimeout);
|
||||
this.gcTimeout = undefined;
|
||||
}
|
||||
};
|
||||
|
||||
_proto.optionalRemove = function optionalRemove() {
|
||||
if (!this.observers.length) {
|
||||
if (this.state.isFetching) {
|
||||
if (this.hadObservers) {
|
||||
this.scheduleGc();
|
||||
}
|
||||
} else {
|
||||
this.cache.remove(this);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
_proto.setData = function setData(updater, options) {
|
||||
var _this$options$isDataE, _this$options;
|
||||
|
||||
var prevData = this.state.data; // Get the new data
|
||||
|
||||
var data = functionalUpdate(updater, prevData); // Use prev data if an isDataEqual function is defined and returns `true`
|
||||
|
||||
if ((_this$options$isDataE = (_this$options = this.options).isDataEqual) == null ? void 0 : _this$options$isDataE.call(_this$options, prevData, data)) {
|
||||
data = prevData;
|
||||
} else if (this.options.structuralSharing !== false) {
|
||||
// Structurally share data between prev and new data if needed
|
||||
data = replaceEqualDeep(prevData, data);
|
||||
} // Set data and mark it as cached
|
||||
|
||||
|
||||
this.dispatch({
|
||||
data: data,
|
||||
type: 'success',
|
||||
dataUpdatedAt: options == null ? void 0 : options.updatedAt
|
||||
});
|
||||
return data;
|
||||
};
|
||||
|
||||
_proto.setState = function setState(state, setStateOptions) {
|
||||
this.dispatch({
|
||||
type: 'setState',
|
||||
state: state,
|
||||
setStateOptions: setStateOptions
|
||||
});
|
||||
};
|
||||
|
||||
_proto.cancel = function cancel(options) {
|
||||
var _this$retryer;
|
||||
|
||||
var promise = this.promise;
|
||||
(_this$retryer = this.retryer) == null ? void 0 : _this$retryer.cancel(options);
|
||||
return promise ? promise.then(noop).catch(noop) : Promise.resolve();
|
||||
};
|
||||
|
||||
_proto.destroy = function destroy() {
|
||||
this.clearGcTimeout();
|
||||
this.cancel({
|
||||
silent: true
|
||||
});
|
||||
};
|
||||
|
||||
_proto.reset = function reset() {
|
||||
this.destroy();
|
||||
this.setState(this.initialState);
|
||||
};
|
||||
|
||||
_proto.isActive = function isActive() {
|
||||
return this.observers.some(function (observer) {
|
||||
return observer.options.enabled !== false;
|
||||
});
|
||||
};
|
||||
|
||||
_proto.isFetching = function isFetching() {
|
||||
return this.state.isFetching;
|
||||
};
|
||||
|
||||
_proto.isStale = function isStale() {
|
||||
return this.state.isInvalidated || !this.state.dataUpdatedAt || this.observers.some(function (observer) {
|
||||
return observer.getCurrentResult().isStale;
|
||||
});
|
||||
};
|
||||
|
||||
_proto.isStaleByTime = function isStaleByTime(staleTime) {
|
||||
if (staleTime === void 0) {
|
||||
staleTime = 0;
|
||||
}
|
||||
|
||||
return this.state.isInvalidated || !this.state.dataUpdatedAt || !timeUntilStale(this.state.dataUpdatedAt, staleTime);
|
||||
};
|
||||
|
||||
_proto.onFocus = function onFocus() {
|
||||
var _this$retryer2;
|
||||
|
||||
var observer = this.observers.find(function (x) {
|
||||
return x.shouldFetchOnWindowFocus();
|
||||
});
|
||||
|
||||
if (observer) {
|
||||
observer.refetch();
|
||||
} // Continue fetch if currently paused
|
||||
|
||||
|
||||
(_this$retryer2 = this.retryer) == null ? void 0 : _this$retryer2.continue();
|
||||
};
|
||||
|
||||
_proto.onOnline = function onOnline() {
|
||||
var _this$retryer3;
|
||||
|
||||
var observer = this.observers.find(function (x) {
|
||||
return x.shouldFetchOnReconnect();
|
||||
});
|
||||
|
||||
if (observer) {
|
||||
observer.refetch();
|
||||
} // Continue fetch if currently paused
|
||||
|
||||
|
||||
(_this$retryer3 = this.retryer) == null ? void 0 : _this$retryer3.continue();
|
||||
};
|
||||
|
||||
_proto.addObserver = function addObserver(observer) {
|
||||
if (this.observers.indexOf(observer) === -1) {
|
||||
this.observers.push(observer);
|
||||
this.hadObservers = true; // Stop the query from being garbage collected
|
||||
|
||||
this.clearGcTimeout();
|
||||
this.cache.notify({
|
||||
type: 'observerAdded',
|
||||
query: this,
|
||||
observer: observer
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
_proto.removeObserver = function removeObserver(observer) {
|
||||
if (this.observers.indexOf(observer) !== -1) {
|
||||
this.observers = this.observers.filter(function (x) {
|
||||
return x !== observer;
|
||||
});
|
||||
|
||||
if (!this.observers.length) {
|
||||
// If the transport layer does not support cancellation
|
||||
// we'll let the query continue so the result can be cached
|
||||
if (this.retryer) {
|
||||
if (this.retryer.isTransportCancelable || this.abortSignalConsumed) {
|
||||
this.retryer.cancel({
|
||||
revert: true
|
||||
});
|
||||
} else {
|
||||
this.retryer.cancelRetry();
|
||||
}
|
||||
}
|
||||
|
||||
if (this.cacheTime) {
|
||||
this.scheduleGc();
|
||||
} else {
|
||||
this.cache.remove(this);
|
||||
}
|
||||
}
|
||||
|
||||
this.cache.notify({
|
||||
type: 'observerRemoved',
|
||||
query: this,
|
||||
observer: observer
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
_proto.getObserversCount = function getObserversCount() {
|
||||
return this.observers.length;
|
||||
};
|
||||
|
||||
_proto.invalidate = function invalidate() {
|
||||
if (!this.state.isInvalidated) {
|
||||
this.dispatch({
|
||||
type: 'invalidate'
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
_proto.fetch = function fetch(options, fetchOptions) {
|
||||
var _this2 = this,
|
||||
_this$options$behavio,
|
||||
_context$fetchOptions,
|
||||
_abortController$abor;
|
||||
|
||||
if (this.state.isFetching) {
|
||||
if (this.state.dataUpdatedAt && (fetchOptions == null ? void 0 : fetchOptions.cancelRefetch)) {
|
||||
// Silently cancel current fetch if the user wants to cancel refetches
|
||||
this.cancel({
|
||||
silent: true
|
||||
});
|
||||
} else if (this.promise) {
|
||||
var _this$retryer4;
|
||||
|
||||
// make sure that retries that were potentially cancelled due to unmounts can continue
|
||||
(_this$retryer4 = this.retryer) == null ? void 0 : _this$retryer4.continueRetry(); // Return current promise if we are already fetching
|
||||
|
||||
return this.promise;
|
||||
}
|
||||
} // Update config if passed, otherwise the config from the last execution is used
|
||||
|
||||
|
||||
if (options) {
|
||||
this.setOptions(options);
|
||||
} // Use the options from the first observer with a query function if no function is found.
|
||||
// This can happen when the query is hydrated or created with setQueryData.
|
||||
|
||||
|
||||
if (!this.options.queryFn) {
|
||||
var observer = this.observers.find(function (x) {
|
||||
return x.options.queryFn;
|
||||
});
|
||||
|
||||
if (observer) {
|
||||
this.setOptions(observer.options);
|
||||
}
|
||||
}
|
||||
|
||||
var queryKey = ensureQueryKeyArray(this.queryKey);
|
||||
var abortController = getAbortController(); // Create query function context
|
||||
|
||||
var queryFnContext = {
|
||||
queryKey: queryKey,
|
||||
pageParam: undefined,
|
||||
meta: this.meta
|
||||
};
|
||||
Object.defineProperty(queryFnContext, 'signal', {
|
||||
enumerable: true,
|
||||
get: function get() {
|
||||
if (abortController) {
|
||||
_this2.abortSignalConsumed = true;
|
||||
return abortController.signal;
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
}); // Create fetch function
|
||||
|
||||
var fetchFn = function fetchFn() {
|
||||
if (!_this2.options.queryFn) {
|
||||
return Promise.reject('Missing queryFn');
|
||||
}
|
||||
|
||||
_this2.abortSignalConsumed = false;
|
||||
return _this2.options.queryFn(queryFnContext);
|
||||
}; // Trigger behavior hook
|
||||
|
||||
|
||||
var context = {
|
||||
fetchOptions: fetchOptions,
|
||||
options: this.options,
|
||||
queryKey: queryKey,
|
||||
state: this.state,
|
||||
fetchFn: fetchFn,
|
||||
meta: this.meta
|
||||
};
|
||||
|
||||
if ((_this$options$behavio = this.options.behavior) == null ? void 0 : _this$options$behavio.onFetch) {
|
||||
var _this$options$behavio2;
|
||||
|
||||
(_this$options$behavio2 = this.options.behavior) == null ? void 0 : _this$options$behavio2.onFetch(context);
|
||||
} // Store state in case the current fetch needs to be reverted
|
||||
|
||||
|
||||
this.revertState = this.state; // Set to fetching state if not already in it
|
||||
|
||||
if (!this.state.isFetching || this.state.fetchMeta !== ((_context$fetchOptions = context.fetchOptions) == null ? void 0 : _context$fetchOptions.meta)) {
|
||||
var _context$fetchOptions2;
|
||||
|
||||
this.dispatch({
|
||||
type: 'fetch',
|
||||
meta: (_context$fetchOptions2 = context.fetchOptions) == null ? void 0 : _context$fetchOptions2.meta
|
||||
});
|
||||
} // Try to fetch the data
|
||||
|
||||
|
||||
this.retryer = new Retryer({
|
||||
fn: context.fetchFn,
|
||||
abort: abortController == null ? void 0 : (_abortController$abor = abortController.abort) == null ? void 0 : _abortController$abor.bind(abortController),
|
||||
onSuccess: function onSuccess(data) {
|
||||
_this2.setData(data); // Notify cache callback
|
||||
|
||||
|
||||
_this2.cache.config.onSuccess == null ? void 0 : _this2.cache.config.onSuccess(data, _this2); // Remove query after fetching if cache time is 0
|
||||
|
||||
if (_this2.cacheTime === 0) {
|
||||
_this2.optionalRemove();
|
||||
}
|
||||
},
|
||||
onError: function onError(error) {
|
||||
// Optimistically update state if needed
|
||||
if (!(isCancelledError(error) && error.silent)) {
|
||||
_this2.dispatch({
|
||||
type: 'error',
|
||||
error: error
|
||||
});
|
||||
}
|
||||
|
||||
if (!isCancelledError(error)) {
|
||||
// Notify cache callback
|
||||
_this2.cache.config.onError == null ? void 0 : _this2.cache.config.onError(error, _this2); // Log error
|
||||
|
||||
getLogger().error(error);
|
||||
} // Remove query after fetching if cache time is 0
|
||||
|
||||
|
||||
if (_this2.cacheTime === 0) {
|
||||
_this2.optionalRemove();
|
||||
}
|
||||
},
|
||||
onFail: function onFail() {
|
||||
_this2.dispatch({
|
||||
type: 'failed'
|
||||
});
|
||||
},
|
||||
onPause: function onPause() {
|
||||
_this2.dispatch({
|
||||
type: 'pause'
|
||||
});
|
||||
},
|
||||
onContinue: function onContinue() {
|
||||
_this2.dispatch({
|
||||
type: 'continue'
|
||||
});
|
||||
},
|
||||
retry: context.options.retry,
|
||||
retryDelay: context.options.retryDelay
|
||||
});
|
||||
this.promise = this.retryer.promise;
|
||||
return this.promise;
|
||||
};
|
||||
|
||||
_proto.dispatch = function dispatch(action) {
|
||||
var _this3 = this;
|
||||
|
||||
this.state = this.reducer(this.state, action);
|
||||
notifyManager.batch(function () {
|
||||
_this3.observers.forEach(function (observer) {
|
||||
observer.onQueryUpdate(action);
|
||||
});
|
||||
|
||||
_this3.cache.notify({
|
||||
query: _this3,
|
||||
type: 'queryUpdated',
|
||||
action: action
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
_proto.getDefaultState = function getDefaultState(options) {
|
||||
var data = typeof options.initialData === 'function' ? options.initialData() : options.initialData;
|
||||
var hasInitialData = typeof options.initialData !== 'undefined';
|
||||
var initialDataUpdatedAt = hasInitialData ? typeof options.initialDataUpdatedAt === 'function' ? options.initialDataUpdatedAt() : options.initialDataUpdatedAt : 0;
|
||||
var hasData = typeof data !== 'undefined';
|
||||
return {
|
||||
data: data,
|
||||
dataUpdateCount: 0,
|
||||
dataUpdatedAt: hasData ? initialDataUpdatedAt != null ? initialDataUpdatedAt : Date.now() : 0,
|
||||
error: null,
|
||||
errorUpdateCount: 0,
|
||||
errorUpdatedAt: 0,
|
||||
fetchFailureCount: 0,
|
||||
fetchMeta: null,
|
||||
isFetching: false,
|
||||
isInvalidated: false,
|
||||
isPaused: false,
|
||||
status: hasData ? 'success' : 'idle'
|
||||
};
|
||||
};
|
||||
|
||||
_proto.reducer = function reducer(state, action) {
|
||||
var _action$meta, _action$dataUpdatedAt;
|
||||
|
||||
switch (action.type) {
|
||||
case 'failed':
|
||||
return _extends({}, state, {
|
||||
fetchFailureCount: state.fetchFailureCount + 1
|
||||
});
|
||||
|
||||
case 'pause':
|
||||
return _extends({}, state, {
|
||||
isPaused: true
|
||||
});
|
||||
|
||||
case 'continue':
|
||||
return _extends({}, state, {
|
||||
isPaused: false
|
||||
});
|
||||
|
||||
case 'fetch':
|
||||
return _extends({}, state, {
|
||||
fetchFailureCount: 0,
|
||||
fetchMeta: (_action$meta = action.meta) != null ? _action$meta : null,
|
||||
isFetching: true,
|
||||
isPaused: false
|
||||
}, !state.dataUpdatedAt && {
|
||||
error: null,
|
||||
status: 'loading'
|
||||
});
|
||||
|
||||
case 'success':
|
||||
return _extends({}, state, {
|
||||
data: action.data,
|
||||
dataUpdateCount: state.dataUpdateCount + 1,
|
||||
dataUpdatedAt: (_action$dataUpdatedAt = action.dataUpdatedAt) != null ? _action$dataUpdatedAt : Date.now(),
|
||||
error: null,
|
||||
fetchFailureCount: 0,
|
||||
isFetching: false,
|
||||
isInvalidated: false,
|
||||
isPaused: false,
|
||||
status: 'success'
|
||||
});
|
||||
|
||||
case 'error':
|
||||
var error = action.error;
|
||||
|
||||
if (isCancelledError(error) && error.revert && this.revertState) {
|
||||
return _extends({}, this.revertState);
|
||||
}
|
||||
|
||||
return _extends({}, state, {
|
||||
error: error,
|
||||
errorUpdateCount: state.errorUpdateCount + 1,
|
||||
errorUpdatedAt: Date.now(),
|
||||
fetchFailureCount: state.fetchFailureCount + 1,
|
||||
isFetching: false,
|
||||
isPaused: false,
|
||||
status: 'error'
|
||||
});
|
||||
|
||||
case 'invalidate':
|
||||
return _extends({}, state, {
|
||||
isInvalidated: true
|
||||
});
|
||||
|
||||
case 'setState':
|
||||
return _extends({}, state, action.state);
|
||||
|
||||
default:
|
||||
return state;
|
||||
}
|
||||
};
|
||||
|
||||
return Query;
|
||||
}();
|
||||
|
||||
// CLASS
|
||||
var QueryCache = /*#__PURE__*/function (_Subscribable) {
|
||||
_inheritsLoose(QueryCache, _Subscribable);
|
||||
|
||||
function QueryCache(config) {
|
||||
var _this;
|
||||
|
||||
_this = _Subscribable.call(this) || this;
|
||||
_this.config = config || {};
|
||||
_this.queries = [];
|
||||
_this.queriesMap = {};
|
||||
return _this;
|
||||
}
|
||||
|
||||
var _proto = QueryCache.prototype;
|
||||
|
||||
_proto.build = function build(client, options, state) {
|
||||
var _options$queryHash;
|
||||
|
||||
var queryKey = options.queryKey;
|
||||
var queryHash = (_options$queryHash = options.queryHash) != null ? _options$queryHash : hashQueryKeyByOptions(queryKey, options);
|
||||
var query = this.get(queryHash);
|
||||
|
||||
if (!query) {
|
||||
query = new Query({
|
||||
cache: this,
|
||||
queryKey: queryKey,
|
||||
queryHash: queryHash,
|
||||
options: client.defaultQueryOptions(options),
|
||||
state: state,
|
||||
defaultOptions: client.getQueryDefaults(queryKey),
|
||||
meta: options.meta
|
||||
});
|
||||
this.add(query);
|
||||
}
|
||||
|
||||
return query;
|
||||
};
|
||||
|
||||
_proto.add = function add(query) {
|
||||
if (!this.queriesMap[query.queryHash]) {
|
||||
this.queriesMap[query.queryHash] = query;
|
||||
this.queries.push(query);
|
||||
this.notify({
|
||||
type: 'queryAdded',
|
||||
query: query
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
_proto.remove = function remove(query) {
|
||||
var queryInMap = this.queriesMap[query.queryHash];
|
||||
|
||||
if (queryInMap) {
|
||||
query.destroy();
|
||||
this.queries = this.queries.filter(function (x) {
|
||||
return x !== query;
|
||||
});
|
||||
|
||||
if (queryInMap === query) {
|
||||
delete this.queriesMap[query.queryHash];
|
||||
}
|
||||
|
||||
this.notify({
|
||||
type: 'queryRemoved',
|
||||
query: query
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
_proto.clear = function clear() {
|
||||
var _this2 = this;
|
||||
|
||||
notifyManager.batch(function () {
|
||||
_this2.queries.forEach(function (query) {
|
||||
_this2.remove(query);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
_proto.get = function get(queryHash) {
|
||||
return this.queriesMap[queryHash];
|
||||
};
|
||||
|
||||
_proto.getAll = function getAll() {
|
||||
return this.queries;
|
||||
};
|
||||
|
||||
_proto.find = function find(arg1, arg2) {
|
||||
var _parseFilterArgs = parseFilterArgs(arg1, arg2),
|
||||
filters = _parseFilterArgs[0];
|
||||
|
||||
if (typeof filters.exact === 'undefined') {
|
||||
filters.exact = true;
|
||||
}
|
||||
|
||||
return this.queries.find(function (query) {
|
||||
return matchQuery(filters, query);
|
||||
});
|
||||
};
|
||||
|
||||
_proto.findAll = function findAll(arg1, arg2) {
|
||||
var _parseFilterArgs2 = parseFilterArgs(arg1, arg2),
|
||||
filters = _parseFilterArgs2[0];
|
||||
|
||||
return Object.keys(filters).length > 0 ? this.queries.filter(function (query) {
|
||||
return matchQuery(filters, query);
|
||||
}) : this.queries;
|
||||
};
|
||||
|
||||
_proto.notify = function notify(event) {
|
||||
var _this3 = this;
|
||||
|
||||
notifyManager.batch(function () {
|
||||
_this3.listeners.forEach(function (listener) {
|
||||
listener(event);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
_proto.onFocus = function onFocus() {
|
||||
var _this4 = this;
|
||||
|
||||
notifyManager.batch(function () {
|
||||
_this4.queries.forEach(function (query) {
|
||||
query.onFocus();
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
_proto.onOnline = function onOnline() {
|
||||
var _this5 = this;
|
||||
|
||||
notifyManager.batch(function () {
|
||||
_this5.queries.forEach(function (query) {
|
||||
query.onOnline();
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
return QueryCache;
|
||||
}(Subscribable);
|
||||
|
||||
// CLASS
|
||||
var Mutation = /*#__PURE__*/function () {
|
||||
function Mutation(config) {
|
||||
this.options = _extends({}, config.defaultOptions, config.options);
|
||||
this.mutationId = config.mutationId;
|
||||
this.mutationCache = config.mutationCache;
|
||||
this.observers = [];
|
||||
this.state = config.state || getDefaultState();
|
||||
this.meta = config.meta;
|
||||
}
|
||||
|
||||
var _proto = Mutation.prototype;
|
||||
|
||||
_proto.setState = function setState(state) {
|
||||
this.dispatch({
|
||||
type: 'setState',
|
||||
state: state
|
||||
});
|
||||
};
|
||||
|
||||
_proto.addObserver = function addObserver(observer) {
|
||||
if (this.observers.indexOf(observer) === -1) {
|
||||
this.observers.push(observer);
|
||||
}
|
||||
};
|
||||
|
||||
_proto.removeObserver = function removeObserver(observer) {
|
||||
this.observers = this.observers.filter(function (x) {
|
||||
return x !== observer;
|
||||
});
|
||||
};
|
||||
|
||||
_proto.cancel = function cancel() {
|
||||
if (this.retryer) {
|
||||
this.retryer.cancel();
|
||||
return this.retryer.promise.then(noop).catch(noop);
|
||||
}
|
||||
|
||||
return Promise.resolve();
|
||||
};
|
||||
|
||||
_proto.continue = function _continue() {
|
||||
if (this.retryer) {
|
||||
this.retryer.continue();
|
||||
return this.retryer.promise;
|
||||
}
|
||||
|
||||
return this.execute();
|
||||
};
|
||||
|
||||
_proto.execute = function execute() {
|
||||
var _this = this;
|
||||
|
||||
var data;
|
||||
var restored = this.state.status === 'loading';
|
||||
var promise = Promise.resolve();
|
||||
|
||||
if (!restored) {
|
||||
this.dispatch({
|
||||
type: 'loading',
|
||||
variables: this.options.variables
|
||||
});
|
||||
promise = promise.then(function () {
|
||||
// Notify cache callback
|
||||
_this.mutationCache.config.onMutate == null ? void 0 : _this.mutationCache.config.onMutate(_this.state.variables, _this);
|
||||
}).then(function () {
|
||||
return _this.options.onMutate == null ? void 0 : _this.options.onMutate(_this.state.variables);
|
||||
}).then(function (context) {
|
||||
if (context !== _this.state.context) {
|
||||
_this.dispatch({
|
||||
type: 'loading',
|
||||
context: context,
|
||||
variables: _this.state.variables
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return promise.then(function () {
|
||||
return _this.executeMutation();
|
||||
}).then(function (result) {
|
||||
data = result; // Notify cache callback
|
||||
|
||||
_this.mutationCache.config.onSuccess == null ? void 0 : _this.mutationCache.config.onSuccess(data, _this.state.variables, _this.state.context, _this);
|
||||
}).then(function () {
|
||||
return _this.options.onSuccess == null ? void 0 : _this.options.onSuccess(data, _this.state.variables, _this.state.context);
|
||||
}).then(function () {
|
||||
return _this.options.onSettled == null ? void 0 : _this.options.onSettled(data, null, _this.state.variables, _this.state.context);
|
||||
}).then(function () {
|
||||
_this.dispatch({
|
||||
type: 'success',
|
||||
data: data
|
||||
});
|
||||
|
||||
return data;
|
||||
}).catch(function (error) {
|
||||
// Notify cache callback
|
||||
_this.mutationCache.config.onError == null ? void 0 : _this.mutationCache.config.onError(error, _this.state.variables, _this.state.context, _this); // Log error
|
||||
|
||||
getLogger().error(error);
|
||||
return Promise.resolve().then(function () {
|
||||
return _this.options.onError == null ? void 0 : _this.options.onError(error, _this.state.variables, _this.state.context);
|
||||
}).then(function () {
|
||||
return _this.options.onSettled == null ? void 0 : _this.options.onSettled(undefined, error, _this.state.variables, _this.state.context);
|
||||
}).then(function () {
|
||||
_this.dispatch({
|
||||
type: 'error',
|
||||
error: error
|
||||
});
|
||||
|
||||
throw error;
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
_proto.executeMutation = function executeMutation() {
|
||||
var _this2 = this,
|
||||
_this$options$retry;
|
||||
|
||||
this.retryer = new Retryer({
|
||||
fn: function fn() {
|
||||
if (!_this2.options.mutationFn) {
|
||||
return Promise.reject('No mutationFn found');
|
||||
}
|
||||
|
||||
return _this2.options.mutationFn(_this2.state.variables);
|
||||
},
|
||||
onFail: function onFail() {
|
||||
_this2.dispatch({
|
||||
type: 'failed'
|
||||
});
|
||||
},
|
||||
onPause: function onPause() {
|
||||
_this2.dispatch({
|
||||
type: 'pause'
|
||||
});
|
||||
},
|
||||
onContinue: function onContinue() {
|
||||
_this2.dispatch({
|
||||
type: 'continue'
|
||||
});
|
||||
},
|
||||
retry: (_this$options$retry = this.options.retry) != null ? _this$options$retry : 0,
|
||||
retryDelay: this.options.retryDelay
|
||||
});
|
||||
return this.retryer.promise;
|
||||
};
|
||||
|
||||
_proto.dispatch = function dispatch(action) {
|
||||
var _this3 = this;
|
||||
|
||||
this.state = reducer(this.state, action);
|
||||
notifyManager.batch(function () {
|
||||
_this3.observers.forEach(function (observer) {
|
||||
observer.onMutationUpdate(action);
|
||||
});
|
||||
|
||||
_this3.mutationCache.notify(_this3);
|
||||
});
|
||||
};
|
||||
|
||||
return Mutation;
|
||||
}();
|
||||
function getDefaultState() {
|
||||
return {
|
||||
context: undefined,
|
||||
data: undefined,
|
||||
error: null,
|
||||
failureCount: 0,
|
||||
isPaused: false,
|
||||
status: 'idle',
|
||||
variables: undefined
|
||||
};
|
||||
}
|
||||
|
||||
function reducer(state, action) {
|
||||
switch (action.type) {
|
||||
case 'failed':
|
||||
return _extends({}, state, {
|
||||
failureCount: state.failureCount + 1
|
||||
});
|
||||
|
||||
case 'pause':
|
||||
return _extends({}, state, {
|
||||
isPaused: true
|
||||
});
|
||||
|
||||
case 'continue':
|
||||
return _extends({}, state, {
|
||||
isPaused: false
|
||||
});
|
||||
|
||||
case 'loading':
|
||||
return _extends({}, state, {
|
||||
context: action.context,
|
||||
data: undefined,
|
||||
error: null,
|
||||
isPaused: false,
|
||||
status: 'loading',
|
||||
variables: action.variables
|
||||
});
|
||||
|
||||
case 'success':
|
||||
return _extends({}, state, {
|
||||
data: action.data,
|
||||
error: null,
|
||||
status: 'success',
|
||||
isPaused: false
|
||||
});
|
||||
|
||||
case 'error':
|
||||
return _extends({}, state, {
|
||||
data: undefined,
|
||||
error: action.error,
|
||||
failureCount: state.failureCount + 1,
|
||||
isPaused: false,
|
||||
status: 'error'
|
||||
});
|
||||
|
||||
case 'setState':
|
||||
return _extends({}, state, action.state);
|
||||
|
||||
default:
|
||||
return state;
|
||||
}
|
||||
}
|
||||
|
||||
// CLASS
|
||||
var MutationCache = /*#__PURE__*/function (_Subscribable) {
|
||||
_inheritsLoose(MutationCache, _Subscribable);
|
||||
|
||||
function MutationCache(config) {
|
||||
var _this;
|
||||
|
||||
_this = _Subscribable.call(this) || this;
|
||||
_this.config = config || {};
|
||||
_this.mutations = [];
|
||||
_this.mutationId = 0;
|
||||
return _this;
|
||||
}
|
||||
|
||||
var _proto = MutationCache.prototype;
|
||||
|
||||
_proto.build = function build(client, options, state) {
|
||||
var mutation = new Mutation({
|
||||
mutationCache: this,
|
||||
mutationId: ++this.mutationId,
|
||||
options: client.defaultMutationOptions(options),
|
||||
state: state,
|
||||
defaultOptions: options.mutationKey ? client.getMutationDefaults(options.mutationKey) : undefined,
|
||||
meta: options.meta
|
||||
});
|
||||
this.add(mutation);
|
||||
return mutation;
|
||||
};
|
||||
|
||||
_proto.add = function add(mutation) {
|
||||
this.mutations.push(mutation);
|
||||
this.notify(mutation);
|
||||
};
|
||||
|
||||
_proto.remove = function remove(mutation) {
|
||||
this.mutations = this.mutations.filter(function (x) {
|
||||
return x !== mutation;
|
||||
});
|
||||
mutation.cancel();
|
||||
this.notify(mutation);
|
||||
};
|
||||
|
||||
_proto.clear = function clear() {
|
||||
var _this2 = this;
|
||||
|
||||
notifyManager.batch(function () {
|
||||
_this2.mutations.forEach(function (mutation) {
|
||||
_this2.remove(mutation);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
_proto.getAll = function getAll() {
|
||||
return this.mutations;
|
||||
};
|
||||
|
||||
_proto.find = function find(filters) {
|
||||
if (typeof filters.exact === 'undefined') {
|
||||
filters.exact = true;
|
||||
}
|
||||
|
||||
return this.mutations.find(function (mutation) {
|
||||
return matchMutation(filters, mutation);
|
||||
});
|
||||
};
|
||||
|
||||
_proto.findAll = function findAll(filters) {
|
||||
return this.mutations.filter(function (mutation) {
|
||||
return matchMutation(filters, mutation);
|
||||
});
|
||||
};
|
||||
|
||||
_proto.notify = function notify(mutation) {
|
||||
var _this3 = this;
|
||||
|
||||
notifyManager.batch(function () {
|
||||
_this3.listeners.forEach(function (listener) {
|
||||
listener(mutation);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
_proto.onFocus = function onFocus() {
|
||||
this.resumePausedMutations();
|
||||
};
|
||||
|
||||
_proto.onOnline = function onOnline() {
|
||||
this.resumePausedMutations();
|
||||
};
|
||||
|
||||
_proto.resumePausedMutations = function resumePausedMutations() {
|
||||
var pausedMutations = this.mutations.filter(function (x) {
|
||||
return x.state.isPaused;
|
||||
});
|
||||
return notifyManager.batch(function () {
|
||||
return pausedMutations.reduce(function (promise, mutation) {
|
||||
return promise.then(function () {
|
||||
return mutation.continue().catch(noop);
|
||||
});
|
||||
}, Promise.resolve());
|
||||
});
|
||||
};
|
||||
|
||||
return MutationCache;
|
||||
}(Subscribable);
|
||||
|
||||
function infiniteQueryBehavior() {
|
||||
return {
|
||||
onFetch: function onFetch(context) {
|
||||
context.fetchFn = function () {
|
||||
var _context$fetchOptions, _context$fetchOptions2, _context$fetchOptions3, _context$fetchOptions4, _context$state$data, _context$state$data2;
|
||||
|
||||
var refetchPage = (_context$fetchOptions = context.fetchOptions) == null ? void 0 : (_context$fetchOptions2 = _context$fetchOptions.meta) == null ? void 0 : _context$fetchOptions2.refetchPage;
|
||||
var fetchMore = (_context$fetchOptions3 = context.fetchOptions) == null ? void 0 : (_context$fetchOptions4 = _context$fetchOptions3.meta) == null ? void 0 : _context$fetchOptions4.fetchMore;
|
||||
var pageParam = fetchMore == null ? void 0 : fetchMore.pageParam;
|
||||
var isFetchingNextPage = (fetchMore == null ? void 0 : fetchMore.direction) === 'forward';
|
||||
var isFetchingPreviousPage = (fetchMore == null ? void 0 : fetchMore.direction) === 'backward';
|
||||
var oldPages = ((_context$state$data = context.state.data) == null ? void 0 : _context$state$data.pages) || [];
|
||||
var oldPageParams = ((_context$state$data2 = context.state.data) == null ? void 0 : _context$state$data2.pageParams) || [];
|
||||
var abortController = getAbortController();
|
||||
var abortSignal = abortController == null ? void 0 : abortController.signal;
|
||||
var newPageParams = oldPageParams;
|
||||
var cancelled = false; // Get query function
|
||||
|
||||
var queryFn = context.options.queryFn || function () {
|
||||
return Promise.reject('Missing queryFn');
|
||||
};
|
||||
|
||||
var buildNewPages = function buildNewPages(pages, param, page, previous) {
|
||||
newPageParams = previous ? [param].concat(newPageParams) : [].concat(newPageParams, [param]);
|
||||
return previous ? [page].concat(pages) : [].concat(pages, [page]);
|
||||
}; // Create function to fetch a page
|
||||
|
||||
|
||||
var fetchPage = function fetchPage(pages, manual, param, previous) {
|
||||
if (cancelled) {
|
||||
return Promise.reject('Cancelled');
|
||||
}
|
||||
|
||||
if (typeof param === 'undefined' && !manual && pages.length) {
|
||||
return Promise.resolve(pages);
|
||||
}
|
||||
|
||||
var queryFnContext = {
|
||||
queryKey: context.queryKey,
|
||||
signal: abortSignal,
|
||||
pageParam: param,
|
||||
meta: context.meta
|
||||
};
|
||||
var queryFnResult = queryFn(queryFnContext);
|
||||
var promise = Promise.resolve(queryFnResult).then(function (page) {
|
||||
return buildNewPages(pages, param, page, previous);
|
||||
});
|
||||
|
||||
if (isCancelable(queryFnResult)) {
|
||||
var promiseAsAny = promise;
|
||||
promiseAsAny.cancel = queryFnResult.cancel;
|
||||
}
|
||||
|
||||
return promise;
|
||||
};
|
||||
|
||||
var promise; // Fetch first page?
|
||||
|
||||
if (!oldPages.length) {
|
||||
promise = fetchPage([]);
|
||||
} // Fetch next page?
|
||||
else if (isFetchingNextPage) {
|
||||
var manual = typeof pageParam !== 'undefined';
|
||||
var param = manual ? pageParam : getNextPageParam(context.options, oldPages);
|
||||
promise = fetchPage(oldPages, manual, param);
|
||||
} // Fetch previous page?
|
||||
else if (isFetchingPreviousPage) {
|
||||
var _manual = typeof pageParam !== 'undefined';
|
||||
|
||||
var _param = _manual ? pageParam : getPreviousPageParam(context.options, oldPages);
|
||||
|
||||
promise = fetchPage(oldPages, _manual, _param, true);
|
||||
} // Refetch pages
|
||||
else {
|
||||
(function () {
|
||||
newPageParams = [];
|
||||
var manual = typeof context.options.getNextPageParam === 'undefined';
|
||||
var shouldFetchFirstPage = refetchPage && oldPages[0] ? refetchPage(oldPages[0], 0, oldPages) : true; // Fetch first page
|
||||
|
||||
promise = shouldFetchFirstPage ? fetchPage([], manual, oldPageParams[0]) : Promise.resolve(buildNewPages([], oldPageParams[0], oldPages[0])); // Fetch remaining pages
|
||||
|
||||
var _loop = function _loop(i) {
|
||||
promise = promise.then(function (pages) {
|
||||
var shouldFetchNextPage = refetchPage && oldPages[i] ? refetchPage(oldPages[i], i, oldPages) : true;
|
||||
|
||||
if (shouldFetchNextPage) {
|
||||
var _param2 = manual ? oldPageParams[i] : getNextPageParam(context.options, pages);
|
||||
|
||||
return fetchPage(pages, manual, _param2);
|
||||
}
|
||||
|
||||
return Promise.resolve(buildNewPages(pages, oldPageParams[i], oldPages[i]));
|
||||
});
|
||||
};
|
||||
|
||||
for (var i = 1; i < oldPages.length; i++) {
|
||||
_loop(i);
|
||||
}
|
||||
})();
|
||||
}
|
||||
|
||||
var finalPromise = promise.then(function (pages) {
|
||||
return {
|
||||
pages: pages,
|
||||
pageParams: newPageParams
|
||||
};
|
||||
});
|
||||
var finalPromiseAsAny = finalPromise;
|
||||
|
||||
finalPromiseAsAny.cancel = function () {
|
||||
cancelled = true;
|
||||
abortController == null ? void 0 : abortController.abort();
|
||||
|
||||
if (isCancelable(promise)) {
|
||||
promise.cancel();
|
||||
}
|
||||
};
|
||||
|
||||
return finalPromise;
|
||||
};
|
||||
}
|
||||
};
|
||||
}
|
||||
function getNextPageParam(options, pages) {
|
||||
return options.getNextPageParam == null ? void 0 : options.getNextPageParam(pages[pages.length - 1], pages);
|
||||
}
|
||||
function getPreviousPageParam(options, pages) {
|
||||
return options.getPreviousPageParam == null ? void 0 : options.getPreviousPageParam(pages[0], pages);
|
||||
}
|
||||
/**
|
||||
* Checks if there is a next page.
|
||||
* Returns `undefined` if it cannot be determined.
|
||||
*/
|
||||
|
||||
function hasNextPage(options, pages) {
|
||||
if (options.getNextPageParam && Array.isArray(pages)) {
|
||||
var nextPageParam = getNextPageParam(options, pages);
|
||||
return typeof nextPageParam !== 'undefined' && nextPageParam !== null && nextPageParam !== false;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Checks if there is a previous page.
|
||||
* Returns `undefined` if it cannot be determined.
|
||||
*/
|
||||
|
||||
function hasPreviousPage(options, pages) {
|
||||
if (options.getPreviousPageParam && Array.isArray(pages)) {
|
||||
var previousPageParam = getPreviousPageParam(options, pages);
|
||||
return typeof previousPageParam !== 'undefined' && previousPageParam !== null && previousPageParam !== false;
|
||||
}
|
||||
}
|
||||
|
||||
// CLASS
|
||||
var QueryClient = /*#__PURE__*/function () {
|
||||
function QueryClient(config) {
|
||||
if (config === void 0) {
|
||||
config = {};
|
||||
}
|
||||
|
||||
this.queryCache = config.queryCache || new QueryCache();
|
||||
this.mutationCache = config.mutationCache || new MutationCache();
|
||||
this.defaultOptions = config.defaultOptions || {};
|
||||
this.queryDefaults = [];
|
||||
this.mutationDefaults = [];
|
||||
}
|
||||
|
||||
var _proto = QueryClient.prototype;
|
||||
|
||||
_proto.mount = function mount() {
|
||||
var _this = this;
|
||||
|
||||
this.unsubscribeFocus = focusManager.subscribe(function () {
|
||||
if (focusManager.isFocused() && onlineManager.isOnline()) {
|
||||
_this.mutationCache.onFocus();
|
||||
|
||||
_this.queryCache.onFocus();
|
||||
}
|
||||
});
|
||||
this.unsubscribeOnline = onlineManager.subscribe(function () {
|
||||
if (focusManager.isFocused() && onlineManager.isOnline()) {
|
||||
_this.mutationCache.onOnline();
|
||||
|
||||
_this.queryCache.onOnline();
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
_proto.unmount = function unmount() {
|
||||
var _this$unsubscribeFocu, _this$unsubscribeOnli;
|
||||
|
||||
(_this$unsubscribeFocu = this.unsubscribeFocus) == null ? void 0 : _this$unsubscribeFocu.call(this);
|
||||
(_this$unsubscribeOnli = this.unsubscribeOnline) == null ? void 0 : _this$unsubscribeOnli.call(this);
|
||||
};
|
||||
|
||||
_proto.isFetching = function isFetching(arg1, arg2) {
|
||||
var _parseFilterArgs = parseFilterArgs(arg1, arg2),
|
||||
filters = _parseFilterArgs[0];
|
||||
|
||||
filters.fetching = true;
|
||||
return this.queryCache.findAll(filters).length;
|
||||
};
|
||||
|
||||
_proto.isMutating = function isMutating(filters) {
|
||||
return this.mutationCache.findAll(_extends({}, filters, {
|
||||
fetching: true
|
||||
})).length;
|
||||
};
|
||||
|
||||
_proto.getQueryData = function getQueryData(queryKey, filters) {
|
||||
var _this$queryCache$find;
|
||||
|
||||
return (_this$queryCache$find = this.queryCache.find(queryKey, filters)) == null ? void 0 : _this$queryCache$find.state.data;
|
||||
};
|
||||
|
||||
_proto.getQueriesData = function getQueriesData(queryKeyOrFilters) {
|
||||
return this.getQueryCache().findAll(queryKeyOrFilters).map(function (_ref) {
|
||||
var queryKey = _ref.queryKey,
|
||||
state = _ref.state;
|
||||
var data = state.data;
|
||||
return [queryKey, data];
|
||||
});
|
||||
};
|
||||
|
||||
_proto.setQueryData = function setQueryData(queryKey, updater, options) {
|
||||
var parsedOptions = parseQueryArgs(queryKey);
|
||||
var defaultedOptions = this.defaultQueryOptions(parsedOptions);
|
||||
return this.queryCache.build(this, defaultedOptions).setData(updater, options);
|
||||
};
|
||||
|
||||
_proto.setQueriesData = function setQueriesData(queryKeyOrFilters, updater, options) {
|
||||
var _this2 = this;
|
||||
|
||||
return notifyManager.batch(function () {
|
||||
return _this2.getQueryCache().findAll(queryKeyOrFilters).map(function (_ref2) {
|
||||
var queryKey = _ref2.queryKey;
|
||||
return [queryKey, _this2.setQueryData(queryKey, updater, options)];
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
_proto.getQueryState = function getQueryState(queryKey, filters) {
|
||||
var _this$queryCache$find2;
|
||||
|
||||
return (_this$queryCache$find2 = this.queryCache.find(queryKey, filters)) == null ? void 0 : _this$queryCache$find2.state;
|
||||
};
|
||||
|
||||
_proto.removeQueries = function removeQueries(arg1, arg2) {
|
||||
var _parseFilterArgs2 = parseFilterArgs(arg1, arg2),
|
||||
filters = _parseFilterArgs2[0];
|
||||
|
||||
var queryCache = this.queryCache;
|
||||
notifyManager.batch(function () {
|
||||
queryCache.findAll(filters).forEach(function (query) {
|
||||
queryCache.remove(query);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
_proto.resetQueries = function resetQueries(arg1, arg2, arg3) {
|
||||
var _this3 = this;
|
||||
|
||||
var _parseFilterArgs3 = parseFilterArgs(arg1, arg2, arg3),
|
||||
filters = _parseFilterArgs3[0],
|
||||
options = _parseFilterArgs3[1];
|
||||
|
||||
var queryCache = this.queryCache;
|
||||
|
||||
var refetchFilters = _extends({}, filters, {
|
||||
active: true
|
||||
});
|
||||
|
||||
return notifyManager.batch(function () {
|
||||
queryCache.findAll(filters).forEach(function (query) {
|
||||
query.reset();
|
||||
});
|
||||
return _this3.refetchQueries(refetchFilters, options);
|
||||
});
|
||||
};
|
||||
|
||||
_proto.cancelQueries = function cancelQueries(arg1, arg2, arg3) {
|
||||
var _this4 = this;
|
||||
|
||||
var _parseFilterArgs4 = parseFilterArgs(arg1, arg2, arg3),
|
||||
filters = _parseFilterArgs4[0],
|
||||
_parseFilterArgs4$ = _parseFilterArgs4[1],
|
||||
cancelOptions = _parseFilterArgs4$ === void 0 ? {} : _parseFilterArgs4$;
|
||||
|
||||
if (typeof cancelOptions.revert === 'undefined') {
|
||||
cancelOptions.revert = true;
|
||||
}
|
||||
|
||||
var promises = notifyManager.batch(function () {
|
||||
return _this4.queryCache.findAll(filters).map(function (query) {
|
||||
return query.cancel(cancelOptions);
|
||||
});
|
||||
});
|
||||
return Promise.all(promises).then(noop).catch(noop);
|
||||
};
|
||||
|
||||
_proto.invalidateQueries = function invalidateQueries(arg1, arg2, arg3) {
|
||||
var _ref3,
|
||||
_filters$refetchActiv,
|
||||
_filters$refetchInact,
|
||||
_this5 = this;
|
||||
|
||||
var _parseFilterArgs5 = parseFilterArgs(arg1, arg2, arg3),
|
||||
filters = _parseFilterArgs5[0],
|
||||
options = _parseFilterArgs5[1];
|
||||
|
||||
var refetchFilters = _extends({}, filters, {
|
||||
// if filters.refetchActive is not provided and filters.active is explicitly false,
|
||||
// e.g. invalidateQueries({ active: false }), we don't want to refetch active queries
|
||||
active: (_ref3 = (_filters$refetchActiv = filters.refetchActive) != null ? _filters$refetchActiv : filters.active) != null ? _ref3 : true,
|
||||
inactive: (_filters$refetchInact = filters.refetchInactive) != null ? _filters$refetchInact : false
|
||||
});
|
||||
|
||||
return notifyManager.batch(function () {
|
||||
_this5.queryCache.findAll(filters).forEach(function (query) {
|
||||
query.invalidate();
|
||||
});
|
||||
|
||||
return _this5.refetchQueries(refetchFilters, options);
|
||||
});
|
||||
};
|
||||
|
||||
_proto.refetchQueries = function refetchQueries(arg1, arg2, arg3) {
|
||||
var _this6 = this;
|
||||
|
||||
var _parseFilterArgs6 = parseFilterArgs(arg1, arg2, arg3),
|
||||
filters = _parseFilterArgs6[0],
|
||||
options = _parseFilterArgs6[1];
|
||||
|
||||
var promises = notifyManager.batch(function () {
|
||||
return _this6.queryCache.findAll(filters).map(function (query) {
|
||||
return query.fetch(undefined, _extends({}, options, {
|
||||
meta: {
|
||||
refetchPage: filters == null ? void 0 : filters.refetchPage
|
||||
}
|
||||
}));
|
||||
});
|
||||
});
|
||||
var promise = Promise.all(promises).then(noop);
|
||||
|
||||
if (!(options == null ? void 0 : options.throwOnError)) {
|
||||
promise = promise.catch(noop);
|
||||
}
|
||||
|
||||
return promise;
|
||||
};
|
||||
|
||||
_proto.fetchQuery = function fetchQuery(arg1, arg2, arg3) {
|
||||
var parsedOptions = parseQueryArgs(arg1, arg2, arg3);
|
||||
var defaultedOptions = this.defaultQueryOptions(parsedOptions); // https://github.com/tannerlinsley/react-query/issues/652
|
||||
|
||||
if (typeof defaultedOptions.retry === 'undefined') {
|
||||
defaultedOptions.retry = false;
|
||||
}
|
||||
|
||||
var query = this.queryCache.build(this, defaultedOptions);
|
||||
return query.isStaleByTime(defaultedOptions.staleTime) ? query.fetch(defaultedOptions) : Promise.resolve(query.state.data);
|
||||
};
|
||||
|
||||
_proto.prefetchQuery = function prefetchQuery(arg1, arg2, arg3) {
|
||||
return this.fetchQuery(arg1, arg2, arg3).then(noop).catch(noop);
|
||||
};
|
||||
|
||||
_proto.fetchInfiniteQuery = function fetchInfiniteQuery(arg1, arg2, arg3) {
|
||||
var parsedOptions = parseQueryArgs(arg1, arg2, arg3);
|
||||
parsedOptions.behavior = infiniteQueryBehavior();
|
||||
return this.fetchQuery(parsedOptions);
|
||||
};
|
||||
|
||||
_proto.prefetchInfiniteQuery = function prefetchInfiniteQuery(arg1, arg2, arg3) {
|
||||
return this.fetchInfiniteQuery(arg1, arg2, arg3).then(noop).catch(noop);
|
||||
};
|
||||
|
||||
_proto.cancelMutations = function cancelMutations() {
|
||||
var _this7 = this;
|
||||
|
||||
var promises = notifyManager.batch(function () {
|
||||
return _this7.mutationCache.getAll().map(function (mutation) {
|
||||
return mutation.cancel();
|
||||
});
|
||||
});
|
||||
return Promise.all(promises).then(noop).catch(noop);
|
||||
};
|
||||
|
||||
_proto.resumePausedMutations = function resumePausedMutations() {
|
||||
return this.getMutationCache().resumePausedMutations();
|
||||
};
|
||||
|
||||
_proto.executeMutation = function executeMutation(options) {
|
||||
return this.mutationCache.build(this, options).execute();
|
||||
};
|
||||
|
||||
_proto.getQueryCache = function getQueryCache() {
|
||||
return this.queryCache;
|
||||
};
|
||||
|
||||
_proto.getMutationCache = function getMutationCache() {
|
||||
return this.mutationCache;
|
||||
};
|
||||
|
||||
_proto.getDefaultOptions = function getDefaultOptions() {
|
||||
return this.defaultOptions;
|
||||
};
|
||||
|
||||
_proto.setDefaultOptions = function setDefaultOptions(options) {
|
||||
this.defaultOptions = options;
|
||||
};
|
||||
|
||||
_proto.setQueryDefaults = function setQueryDefaults(queryKey, options) {
|
||||
var result = this.queryDefaults.find(function (x) {
|
||||
return hashQueryKey(queryKey) === hashQueryKey(x.queryKey);
|
||||
});
|
||||
|
||||
if (result) {
|
||||
result.defaultOptions = options;
|
||||
} else {
|
||||
this.queryDefaults.push({
|
||||
queryKey: queryKey,
|
||||
defaultOptions: options
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
_proto.getQueryDefaults = function getQueryDefaults(queryKey) {
|
||||
var _this$queryDefaults$f;
|
||||
|
||||
return queryKey ? (_this$queryDefaults$f = this.queryDefaults.find(function (x) {
|
||||
return partialMatchKey(queryKey, x.queryKey);
|
||||
})) == null ? void 0 : _this$queryDefaults$f.defaultOptions : undefined;
|
||||
};
|
||||
|
||||
_proto.setMutationDefaults = function setMutationDefaults(mutationKey, options) {
|
||||
var result = this.mutationDefaults.find(function (x) {
|
||||
return hashQueryKey(mutationKey) === hashQueryKey(x.mutationKey);
|
||||
});
|
||||
|
||||
if (result) {
|
||||
result.defaultOptions = options;
|
||||
} else {
|
||||
this.mutationDefaults.push({
|
||||
mutationKey: mutationKey,
|
||||
defaultOptions: options
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
_proto.getMutationDefaults = function getMutationDefaults(mutationKey) {
|
||||
var _this$mutationDefault;
|
||||
|
||||
return mutationKey ? (_this$mutationDefault = this.mutationDefaults.find(function (x) {
|
||||
return partialMatchKey(mutationKey, x.mutationKey);
|
||||
})) == null ? void 0 : _this$mutationDefault.defaultOptions : undefined;
|
||||
};
|
||||
|
||||
_proto.defaultQueryOptions = function defaultQueryOptions(options) {
|
||||
if (options == null ? void 0 : options._defaulted) {
|
||||
return options;
|
||||
}
|
||||
|
||||
var defaultedOptions = _extends({}, this.defaultOptions.queries, this.getQueryDefaults(options == null ? void 0 : options.queryKey), options, {
|
||||
_defaulted: true
|
||||
});
|
||||
|
||||
if (!defaultedOptions.queryHash && defaultedOptions.queryKey) {
|
||||
defaultedOptions.queryHash = hashQueryKeyByOptions(defaultedOptions.queryKey, defaultedOptions);
|
||||
}
|
||||
|
||||
return defaultedOptions;
|
||||
};
|
||||
|
||||
_proto.defaultQueryObserverOptions = function defaultQueryObserverOptions(options) {
|
||||
return this.defaultQueryOptions(options);
|
||||
};
|
||||
|
||||
_proto.defaultMutationOptions = function defaultMutationOptions(options) {
|
||||
if (options == null ? void 0 : options._defaulted) {
|
||||
return options;
|
||||
}
|
||||
|
||||
return _extends({}, this.defaultOptions.mutations, this.getMutationDefaults(options == null ? void 0 : options.mutationKey), options, {
|
||||
_defaulted: true
|
||||
});
|
||||
};
|
||||
|
||||
_proto.clear = function clear() {
|
||||
this.queryCache.clear();
|
||||
this.mutationCache.clear();
|
||||
};
|
||||
|
||||
return QueryClient;
|
||||
}();
|
||||
|
||||
var QueryObserver = /*#__PURE__*/function (_Subscribable) {
|
||||
_inheritsLoose(QueryObserver, _Subscribable);
|
||||
|
||||
function QueryObserver(client, options) {
|
||||
var _this;
|
||||
|
||||
_this = _Subscribable.call(this) || this;
|
||||
_this.client = client;
|
||||
_this.options = options;
|
||||
_this.trackedProps = [];
|
||||
_this.selectError = null;
|
||||
|
||||
_this.bindMethods();
|
||||
|
||||
_this.setOptions(options);
|
||||
|
||||
return _this;
|
||||
}
|
||||
|
||||
var _proto = QueryObserver.prototype;
|
||||
|
||||
_proto.bindMethods = function bindMethods() {
|
||||
this.remove = this.remove.bind(this);
|
||||
this.refetch = this.refetch.bind(this);
|
||||
};
|
||||
|
||||
_proto.onSubscribe = function onSubscribe() {
|
||||
if (this.listeners.length === 1) {
|
||||
this.currentQuery.addObserver(this);
|
||||
|
||||
if (shouldFetchOnMount(this.currentQuery, this.options)) {
|
||||
this.executeFetch();
|
||||
}
|
||||
|
||||
this.updateTimers();
|
||||
}
|
||||
};
|
||||
|
||||
_proto.onUnsubscribe = function onUnsubscribe() {
|
||||
if (!this.listeners.length) {
|
||||
this.destroy();
|
||||
}
|
||||
};
|
||||
|
||||
_proto.shouldFetchOnReconnect = function shouldFetchOnReconnect() {
|
||||
return shouldFetchOn(this.currentQuery, this.options, this.options.refetchOnReconnect);
|
||||
};
|
||||
|
||||
_proto.shouldFetchOnWindowFocus = function shouldFetchOnWindowFocus() {
|
||||
return shouldFetchOn(this.currentQuery, this.options, this.options.refetchOnWindowFocus);
|
||||
};
|
||||
|
||||
_proto.destroy = function destroy() {
|
||||
this.listeners = [];
|
||||
this.clearTimers();
|
||||
this.currentQuery.removeObserver(this);
|
||||
};
|
||||
|
||||
_proto.setOptions = function setOptions(options, notifyOptions) {
|
||||
var prevOptions = this.options;
|
||||
var prevQuery = this.currentQuery;
|
||||
this.options = this.client.defaultQueryObserverOptions(options);
|
||||
|
||||
if (typeof this.options.enabled !== 'undefined' && typeof this.options.enabled !== 'boolean') {
|
||||
throw new Error('Expected enabled to be a boolean');
|
||||
} // Keep previous query key if the user does not supply one
|
||||
|
||||
|
||||
if (!this.options.queryKey) {
|
||||
this.options.queryKey = prevOptions.queryKey;
|
||||
}
|
||||
|
||||
this.updateQuery();
|
||||
var mounted = this.hasListeners(); // Fetch if there are subscribers
|
||||
|
||||
if (mounted && shouldFetchOptionally(this.currentQuery, prevQuery, this.options, prevOptions)) {
|
||||
this.executeFetch();
|
||||
} // Update result
|
||||
|
||||
|
||||
this.updateResult(notifyOptions); // Update stale interval if needed
|
||||
|
||||
if (mounted && (this.currentQuery !== prevQuery || this.options.enabled !== prevOptions.enabled || this.options.staleTime !== prevOptions.staleTime)) {
|
||||
this.updateStaleTimeout();
|
||||
}
|
||||
|
||||
var nextRefetchInterval = this.computeRefetchInterval(); // Update refetch interval if needed
|
||||
|
||||
if (mounted && (this.currentQuery !== prevQuery || this.options.enabled !== prevOptions.enabled || nextRefetchInterval !== this.currentRefetchInterval)) {
|
||||
this.updateRefetchInterval(nextRefetchInterval);
|
||||
}
|
||||
};
|
||||
|
||||
_proto.getOptimisticResult = function getOptimisticResult(options) {
|
||||
var defaultedOptions = this.client.defaultQueryObserverOptions(options);
|
||||
var query = this.client.getQueryCache().build(this.client, defaultedOptions);
|
||||
return this.createResult(query, defaultedOptions);
|
||||
};
|
||||
|
||||
_proto.getCurrentResult = function getCurrentResult() {
|
||||
return this.currentResult;
|
||||
};
|
||||
|
||||
_proto.trackResult = function trackResult(result, defaultedOptions) {
|
||||
var _this2 = this;
|
||||
|
||||
var trackedResult = {};
|
||||
|
||||
var trackProp = function trackProp(key) {
|
||||
if (!_this2.trackedProps.includes(key)) {
|
||||
_this2.trackedProps.push(key);
|
||||
}
|
||||
};
|
||||
|
||||
Object.keys(result).forEach(function (key) {
|
||||
Object.defineProperty(trackedResult, key, {
|
||||
configurable: false,
|
||||
enumerable: true,
|
||||
get: function get() {
|
||||
trackProp(key);
|
||||
return result[key];
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
if (defaultedOptions.useErrorBoundary || defaultedOptions.suspense) {
|
||||
trackProp('error');
|
||||
}
|
||||
|
||||
return trackedResult;
|
||||
};
|
||||
|
||||
_proto.getNextResult = function getNextResult(options) {
|
||||
var _this3 = this;
|
||||
|
||||
return new Promise(function (resolve, reject) {
|
||||
var unsubscribe = _this3.subscribe(function (result) {
|
||||
if (!result.isFetching) {
|
||||
unsubscribe();
|
||||
|
||||
if (result.isError && (options == null ? void 0 : options.throwOnError)) {
|
||||
reject(result.error);
|
||||
} else {
|
||||
resolve(result);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
_proto.getCurrentQuery = function getCurrentQuery() {
|
||||
return this.currentQuery;
|
||||
};
|
||||
|
||||
_proto.remove = function remove() {
|
||||
this.client.getQueryCache().remove(this.currentQuery);
|
||||
};
|
||||
|
||||
_proto.refetch = function refetch(options) {
|
||||
return this.fetch(_extends({}, options, {
|
||||
meta: {
|
||||
refetchPage: options == null ? void 0 : options.refetchPage
|
||||
}
|
||||
}));
|
||||
};
|
||||
|
||||
_proto.fetchOptimistic = function fetchOptimistic(options) {
|
||||
var _this4 = this;
|
||||
|
||||
var defaultedOptions = this.client.defaultQueryObserverOptions(options);
|
||||
var query = this.client.getQueryCache().build(this.client, defaultedOptions);
|
||||
return query.fetch().then(function () {
|
||||
return _this4.createResult(query, defaultedOptions);
|
||||
});
|
||||
};
|
||||
|
||||
_proto.fetch = function fetch(fetchOptions) {
|
||||
var _this5 = this;
|
||||
|
||||
return this.executeFetch(fetchOptions).then(function () {
|
||||
_this5.updateResult();
|
||||
|
||||
return _this5.currentResult;
|
||||
});
|
||||
};
|
||||
|
||||
_proto.executeFetch = function executeFetch(fetchOptions) {
|
||||
// Make sure we reference the latest query as the current one might have been removed
|
||||
this.updateQuery(); // Fetch
|
||||
|
||||
var promise = this.currentQuery.fetch(this.options, fetchOptions);
|
||||
|
||||
if (!(fetchOptions == null ? void 0 : fetchOptions.throwOnError)) {
|
||||
promise = promise.catch(noop);
|
||||
}
|
||||
|
||||
return promise;
|
||||
};
|
||||
|
||||
_proto.updateStaleTimeout = function updateStaleTimeout() {
|
||||
var _this6 = this;
|
||||
|
||||
this.clearStaleTimeout();
|
||||
|
||||
if (isServer || this.currentResult.isStale || !isValidTimeout(this.options.staleTime)) {
|
||||
return;
|
||||
}
|
||||
|
||||
var time = timeUntilStale(this.currentResult.dataUpdatedAt, this.options.staleTime); // The timeout is sometimes triggered 1 ms before the stale time expiration.
|
||||
// To mitigate this issue we always add 1 ms to the timeout.
|
||||
|
||||
var timeout = time + 1;
|
||||
this.staleTimeoutId = setTimeout(function () {
|
||||
if (!_this6.currentResult.isStale) {
|
||||
_this6.updateResult();
|
||||
}
|
||||
}, timeout);
|
||||
};
|
||||
|
||||
_proto.computeRefetchInterval = function computeRefetchInterval() {
|
||||
var _this$options$refetch;
|
||||
|
||||
return typeof this.options.refetchInterval === 'function' ? this.options.refetchInterval(this.currentResult.data, this.currentQuery) : (_this$options$refetch = this.options.refetchInterval) != null ? _this$options$refetch : false;
|
||||
};
|
||||
|
||||
_proto.updateRefetchInterval = function updateRefetchInterval(nextInterval) {
|
||||
var _this7 = this;
|
||||
|
||||
this.clearRefetchInterval();
|
||||
this.currentRefetchInterval = nextInterval;
|
||||
|
||||
if (isServer || this.options.enabled === false || !isValidTimeout(this.currentRefetchInterval) || this.currentRefetchInterval === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.refetchIntervalId = setInterval(function () {
|
||||
if (_this7.options.refetchIntervalInBackground || focusManager.isFocused()) {
|
||||
_this7.executeFetch();
|
||||
}
|
||||
}, this.currentRefetchInterval);
|
||||
};
|
||||
|
||||
_proto.updateTimers = function updateTimers() {
|
||||
this.updateStaleTimeout();
|
||||
this.updateRefetchInterval(this.computeRefetchInterval());
|
||||
};
|
||||
|
||||
_proto.clearTimers = function clearTimers() {
|
||||
this.clearStaleTimeout();
|
||||
this.clearRefetchInterval();
|
||||
};
|
||||
|
||||
_proto.clearStaleTimeout = function clearStaleTimeout() {
|
||||
if (this.staleTimeoutId) {
|
||||
clearTimeout(this.staleTimeoutId);
|
||||
this.staleTimeoutId = undefined;
|
||||
}
|
||||
};
|
||||
|
||||
_proto.clearRefetchInterval = function clearRefetchInterval() {
|
||||
if (this.refetchIntervalId) {
|
||||
clearInterval(this.refetchIntervalId);
|
||||
this.refetchIntervalId = undefined;
|
||||
}
|
||||
};
|
||||
|
||||
_proto.createResult = function createResult(query, options) {
|
||||
var prevQuery = this.currentQuery;
|
||||
var prevOptions = this.options;
|
||||
var prevResult = this.currentResult;
|
||||
var prevResultState = this.currentResultState;
|
||||
var prevResultOptions = this.currentResultOptions;
|
||||
var queryChange = query !== prevQuery;
|
||||
var queryInitialState = queryChange ? query.state : this.currentQueryInitialState;
|
||||
var prevQueryResult = queryChange ? this.currentResult : this.previousQueryResult;
|
||||
var state = query.state;
|
||||
var dataUpdatedAt = state.dataUpdatedAt,
|
||||
error = state.error,
|
||||
errorUpdatedAt = state.errorUpdatedAt,
|
||||
isFetching = state.isFetching,
|
||||
status = state.status;
|
||||
var isPreviousData = false;
|
||||
var isPlaceholderData = false;
|
||||
var data; // Optimistically set result in fetching state if needed
|
||||
|
||||
if (options.optimisticResults) {
|
||||
var mounted = this.hasListeners();
|
||||
var fetchOnMount = !mounted && shouldFetchOnMount(query, options);
|
||||
var fetchOptionally = mounted && shouldFetchOptionally(query, prevQuery, options, prevOptions);
|
||||
|
||||
if (fetchOnMount || fetchOptionally) {
|
||||
isFetching = true;
|
||||
|
||||
if (!dataUpdatedAt) {
|
||||
status = 'loading';
|
||||
}
|
||||
}
|
||||
} // Keep previous data if needed
|
||||
|
||||
|
||||
if (options.keepPreviousData && !state.dataUpdateCount && (prevQueryResult == null ? void 0 : prevQueryResult.isSuccess) && status !== 'error') {
|
||||
data = prevQueryResult.data;
|
||||
dataUpdatedAt = prevQueryResult.dataUpdatedAt;
|
||||
status = prevQueryResult.status;
|
||||
isPreviousData = true;
|
||||
} // Select data if needed
|
||||
else if (options.select && typeof state.data !== 'undefined') {
|
||||
// Memoize select result
|
||||
if (prevResult && state.data === (prevResultState == null ? void 0 : prevResultState.data) && options.select === this.selectFn) {
|
||||
data = this.selectResult;
|
||||
} else {
|
||||
try {
|
||||
this.selectFn = options.select;
|
||||
data = options.select(state.data);
|
||||
|
||||
if (options.structuralSharing !== false) {
|
||||
data = replaceEqualDeep(prevResult == null ? void 0 : prevResult.data, data);
|
||||
}
|
||||
|
||||
this.selectResult = data;
|
||||
this.selectError = null;
|
||||
} catch (selectError) {
|
||||
getLogger().error(selectError);
|
||||
this.selectError = selectError;
|
||||
}
|
||||
}
|
||||
} // Use query data
|
||||
else {
|
||||
data = state.data;
|
||||
} // Show placeholder data if needed
|
||||
|
||||
|
||||
if (typeof options.placeholderData !== 'undefined' && typeof data === 'undefined' && (status === 'loading' || status === 'idle')) {
|
||||
var placeholderData; // Memoize placeholder data
|
||||
|
||||
if ((prevResult == null ? void 0 : prevResult.isPlaceholderData) && options.placeholderData === (prevResultOptions == null ? void 0 : prevResultOptions.placeholderData)) {
|
||||
placeholderData = prevResult.data;
|
||||
} else {
|
||||
placeholderData = typeof options.placeholderData === 'function' ? options.placeholderData() : options.placeholderData;
|
||||
|
||||
if (options.select && typeof placeholderData !== 'undefined') {
|
||||
try {
|
||||
placeholderData = options.select(placeholderData);
|
||||
|
||||
if (options.structuralSharing !== false) {
|
||||
placeholderData = replaceEqualDeep(prevResult == null ? void 0 : prevResult.data, placeholderData);
|
||||
}
|
||||
|
||||
this.selectError = null;
|
||||
} catch (selectError) {
|
||||
getLogger().error(selectError);
|
||||
this.selectError = selectError;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof placeholderData !== 'undefined') {
|
||||
status = 'success';
|
||||
data = placeholderData;
|
||||
isPlaceholderData = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (this.selectError) {
|
||||
error = this.selectError;
|
||||
data = this.selectResult;
|
||||
errorUpdatedAt = Date.now();
|
||||
status = 'error';
|
||||
}
|
||||
|
||||
var result = {
|
||||
status: status,
|
||||
isLoading: status === 'loading',
|
||||
isSuccess: status === 'success',
|
||||
isError: status === 'error',
|
||||
isIdle: status === 'idle',
|
||||
data: data,
|
||||
dataUpdatedAt: dataUpdatedAt,
|
||||
error: error,
|
||||
errorUpdatedAt: errorUpdatedAt,
|
||||
failureCount: state.fetchFailureCount,
|
||||
errorUpdateCount: state.errorUpdateCount,
|
||||
isFetched: state.dataUpdateCount > 0 || state.errorUpdateCount > 0,
|
||||
isFetchedAfterMount: state.dataUpdateCount > queryInitialState.dataUpdateCount || state.errorUpdateCount > queryInitialState.errorUpdateCount,
|
||||
isFetching: isFetching,
|
||||
isRefetching: isFetching && status !== 'loading',
|
||||
isLoadingError: status === 'error' && state.dataUpdatedAt === 0,
|
||||
isPlaceholderData: isPlaceholderData,
|
||||
isPreviousData: isPreviousData,
|
||||
isRefetchError: status === 'error' && state.dataUpdatedAt !== 0,
|
||||
isStale: isStale(query, options),
|
||||
refetch: this.refetch,
|
||||
remove: this.remove
|
||||
};
|
||||
return result;
|
||||
};
|
||||
|
||||
_proto.shouldNotifyListeners = function shouldNotifyListeners(result, prevResult) {
|
||||
if (!prevResult) {
|
||||
return true;
|
||||
}
|
||||
|
||||
var _this$options = this.options,
|
||||
notifyOnChangeProps = _this$options.notifyOnChangeProps,
|
||||
notifyOnChangePropsExclusions = _this$options.notifyOnChangePropsExclusions;
|
||||
|
||||
if (!notifyOnChangeProps && !notifyOnChangePropsExclusions) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (notifyOnChangeProps === 'tracked' && !this.trackedProps.length) {
|
||||
return true;
|
||||
}
|
||||
|
||||
var includedProps = notifyOnChangeProps === 'tracked' ? this.trackedProps : notifyOnChangeProps;
|
||||
return Object.keys(result).some(function (key) {
|
||||
var typedKey = key;
|
||||
var changed = result[typedKey] !== prevResult[typedKey];
|
||||
var isIncluded = includedProps == null ? void 0 : includedProps.some(function (x) {
|
||||
return x === key;
|
||||
});
|
||||
var isExcluded = notifyOnChangePropsExclusions == null ? void 0 : notifyOnChangePropsExclusions.some(function (x) {
|
||||
return x === key;
|
||||
});
|
||||
return changed && !isExcluded && (!includedProps || isIncluded);
|
||||
});
|
||||
};
|
||||
|
||||
_proto.updateResult = function updateResult(notifyOptions) {
|
||||
var prevResult = this.currentResult;
|
||||
this.currentResult = this.createResult(this.currentQuery, this.options);
|
||||
this.currentResultState = this.currentQuery.state;
|
||||
this.currentResultOptions = this.options; // Only notify if something has changed
|
||||
|
||||
if (shallowEqualObjects(this.currentResult, prevResult)) {
|
||||
return;
|
||||
} // Determine which callbacks to trigger
|
||||
|
||||
|
||||
var defaultNotifyOptions = {
|
||||
cache: true
|
||||
};
|
||||
|
||||
if ((notifyOptions == null ? void 0 : notifyOptions.listeners) !== false && this.shouldNotifyListeners(this.currentResult, prevResult)) {
|
||||
defaultNotifyOptions.listeners = true;
|
||||
}
|
||||
|
||||
this.notify(_extends({}, defaultNotifyOptions, notifyOptions));
|
||||
};
|
||||
|
||||
_proto.updateQuery = function updateQuery() {
|
||||
var query = this.client.getQueryCache().build(this.client, this.options);
|
||||
|
||||
if (query === this.currentQuery) {
|
||||
return;
|
||||
}
|
||||
|
||||
var prevQuery = this.currentQuery;
|
||||
this.currentQuery = query;
|
||||
this.currentQueryInitialState = query.state;
|
||||
this.previousQueryResult = this.currentResult;
|
||||
|
||||
if (this.hasListeners()) {
|
||||
prevQuery == null ? void 0 : prevQuery.removeObserver(this);
|
||||
query.addObserver(this);
|
||||
}
|
||||
};
|
||||
|
||||
_proto.onQueryUpdate = function onQueryUpdate(action) {
|
||||
var notifyOptions = {};
|
||||
|
||||
if (action.type === 'success') {
|
||||
notifyOptions.onSuccess = true;
|
||||
} else if (action.type === 'error' && !isCancelledError(action.error)) {
|
||||
notifyOptions.onError = true;
|
||||
}
|
||||
|
||||
this.updateResult(notifyOptions);
|
||||
|
||||
if (this.hasListeners()) {
|
||||
this.updateTimers();
|
||||
}
|
||||
};
|
||||
|
||||
_proto.notify = function notify(notifyOptions) {
|
||||
var _this8 = this;
|
||||
|
||||
notifyManager.batch(function () {
|
||||
// First trigger the configuration callbacks
|
||||
if (notifyOptions.onSuccess) {
|
||||
_this8.options.onSuccess == null ? void 0 : _this8.options.onSuccess(_this8.currentResult.data);
|
||||
_this8.options.onSettled == null ? void 0 : _this8.options.onSettled(_this8.currentResult.data, null);
|
||||
} else if (notifyOptions.onError) {
|
||||
_this8.options.onError == null ? void 0 : _this8.options.onError(_this8.currentResult.error);
|
||||
_this8.options.onSettled == null ? void 0 : _this8.options.onSettled(undefined, _this8.currentResult.error);
|
||||
} // Then trigger the listeners
|
||||
|
||||
|
||||
if (notifyOptions.listeners) {
|
||||
_this8.listeners.forEach(function (listener) {
|
||||
listener(_this8.currentResult);
|
||||
});
|
||||
} // Then the cache listeners
|
||||
|
||||
|
||||
if (notifyOptions.cache) {
|
||||
_this8.client.getQueryCache().notify({
|
||||
query: _this8.currentQuery,
|
||||
type: 'observerResultsUpdated'
|
||||
});
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
return QueryObserver;
|
||||
}(Subscribable);
|
||||
|
||||
function shouldLoadOnMount(query, options) {
|
||||
return options.enabled !== false && !query.state.dataUpdatedAt && !(query.state.status === 'error' && options.retryOnMount === false);
|
||||
}
|
||||
|
||||
function shouldFetchOnMount(query, options) {
|
||||
return shouldLoadOnMount(query, options) || query.state.dataUpdatedAt > 0 && shouldFetchOn(query, options, options.refetchOnMount);
|
||||
}
|
||||
|
||||
function shouldFetchOn(query, options, field) {
|
||||
if (options.enabled !== false) {
|
||||
var value = typeof field === 'function' ? field(query) : field;
|
||||
return value === 'always' || value !== false && isStale(query, options);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
function shouldFetchOptionally(query, prevQuery, options, prevOptions) {
|
||||
return options.enabled !== false && (query !== prevQuery || prevOptions.enabled === false) && (!options.suspense || query.state.status !== 'error') && isStale(query, options);
|
||||
}
|
||||
|
||||
function isStale(query, options) {
|
||||
return query.isStaleByTime(options.staleTime);
|
||||
}
|
||||
|
||||
var QueriesObserver = /*#__PURE__*/function (_Subscribable) {
|
||||
_inheritsLoose(QueriesObserver, _Subscribable);
|
||||
|
||||
function QueriesObserver(client, queries) {
|
||||
var _this;
|
||||
|
||||
_this = _Subscribable.call(this) || this;
|
||||
_this.client = client;
|
||||
_this.queries = [];
|
||||
_this.result = [];
|
||||
_this.observers = [];
|
||||
_this.observersMap = {};
|
||||
|
||||
if (queries) {
|
||||
_this.setQueries(queries);
|
||||
}
|
||||
|
||||
return _this;
|
||||
}
|
||||
|
||||
var _proto = QueriesObserver.prototype;
|
||||
|
||||
_proto.onSubscribe = function onSubscribe() {
|
||||
var _this2 = this;
|
||||
|
||||
if (this.listeners.length === 1) {
|
||||
this.observers.forEach(function (observer) {
|
||||
observer.subscribe(function (result) {
|
||||
_this2.onUpdate(observer, result);
|
||||
});
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
_proto.onUnsubscribe = function onUnsubscribe() {
|
||||
if (!this.listeners.length) {
|
||||
this.destroy();
|
||||
}
|
||||
};
|
||||
|
||||
_proto.destroy = function destroy() {
|
||||
this.listeners = [];
|
||||
this.observers.forEach(function (observer) {
|
||||
observer.destroy();
|
||||
});
|
||||
};
|
||||
|
||||
_proto.setQueries = function setQueries(queries, notifyOptions) {
|
||||
this.queries = queries;
|
||||
this.updateObservers(notifyOptions);
|
||||
};
|
||||
|
||||
_proto.getCurrentResult = function getCurrentResult() {
|
||||
return this.result;
|
||||
};
|
||||
|
||||
_proto.getOptimisticResult = function getOptimisticResult(queries) {
|
||||
return this.findMatchingObservers(queries).map(function (match) {
|
||||
return match.observer.getOptimisticResult(match.defaultedQueryOptions);
|
||||
});
|
||||
};
|
||||
|
||||
_proto.findMatchingObservers = function findMatchingObservers(queries) {
|
||||
var _this3 = this;
|
||||
|
||||
var prevObservers = this.observers;
|
||||
var defaultedQueryOptions = queries.map(function (options) {
|
||||
return _this3.client.defaultQueryObserverOptions(options);
|
||||
});
|
||||
var matchingObservers = defaultedQueryOptions.flatMap(function (defaultedOptions) {
|
||||
var match = prevObservers.find(function (observer) {
|
||||
return observer.options.queryHash === defaultedOptions.queryHash;
|
||||
});
|
||||
|
||||
if (match != null) {
|
||||
return [{
|
||||
defaultedQueryOptions: defaultedOptions,
|
||||
observer: match
|
||||
}];
|
||||
}
|
||||
|
||||
return [];
|
||||
});
|
||||
var matchedQueryHashes = matchingObservers.map(function (match) {
|
||||
return match.defaultedQueryOptions.queryHash;
|
||||
});
|
||||
var unmatchedQueries = defaultedQueryOptions.filter(function (defaultedOptions) {
|
||||
return !matchedQueryHashes.includes(defaultedOptions.queryHash);
|
||||
});
|
||||
var unmatchedObservers = prevObservers.filter(function (prevObserver) {
|
||||
return !matchingObservers.some(function (match) {
|
||||
return match.observer === prevObserver;
|
||||
});
|
||||
});
|
||||
var newOrReusedObservers = unmatchedQueries.map(function (options, index) {
|
||||
if (options.keepPreviousData) {
|
||||
// return previous data from one of the observers that no longer match
|
||||
var previouslyUsedObserver = unmatchedObservers[index];
|
||||
|
||||
if (previouslyUsedObserver !== undefined) {
|
||||
return {
|
||||
defaultedQueryOptions: options,
|
||||
observer: previouslyUsedObserver
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
defaultedQueryOptions: options,
|
||||
observer: _this3.getObserver(options)
|
||||
};
|
||||
});
|
||||
|
||||
var sortMatchesByOrderOfQueries = function sortMatchesByOrderOfQueries(a, b) {
|
||||
return defaultedQueryOptions.indexOf(a.defaultedQueryOptions) - defaultedQueryOptions.indexOf(b.defaultedQueryOptions);
|
||||
};
|
||||
|
||||
return matchingObservers.concat(newOrReusedObservers).sort(sortMatchesByOrderOfQueries);
|
||||
};
|
||||
|
||||
_proto.getObserver = function getObserver(options) {
|
||||
var defaultedOptions = this.client.defaultQueryObserverOptions(options);
|
||||
var currentObserver = this.observersMap[defaultedOptions.queryHash];
|
||||
return currentObserver != null ? currentObserver : new QueryObserver(this.client, defaultedOptions);
|
||||
};
|
||||
|
||||
_proto.updateObservers = function updateObservers(notifyOptions) {
|
||||
var _this4 = this;
|
||||
|
||||
notifyManager.batch(function () {
|
||||
var prevObservers = _this4.observers;
|
||||
|
||||
var newObserverMatches = _this4.findMatchingObservers(_this4.queries); // set options for the new observers to notify of changes
|
||||
|
||||
|
||||
newObserverMatches.forEach(function (match) {
|
||||
return match.observer.setOptions(match.defaultedQueryOptions, notifyOptions);
|
||||
});
|
||||
var newObservers = newObserverMatches.map(function (match) {
|
||||
return match.observer;
|
||||
});
|
||||
var newObserversMap = Object.fromEntries(newObservers.map(function (observer) {
|
||||
return [observer.options.queryHash, observer];
|
||||
}));
|
||||
var newResult = newObservers.map(function (observer) {
|
||||
return observer.getCurrentResult();
|
||||
});
|
||||
var hasIndexChange = newObservers.some(function (observer, index) {
|
||||
return observer !== prevObservers[index];
|
||||
});
|
||||
|
||||
if (prevObservers.length === newObservers.length && !hasIndexChange) {
|
||||
return;
|
||||
}
|
||||
|
||||
_this4.observers = newObservers;
|
||||
_this4.observersMap = newObserversMap;
|
||||
_this4.result = newResult;
|
||||
|
||||
if (!_this4.hasListeners()) {
|
||||
return;
|
||||
}
|
||||
|
||||
difference(prevObservers, newObservers).forEach(function (observer) {
|
||||
observer.destroy();
|
||||
});
|
||||
difference(newObservers, prevObservers).forEach(function (observer) {
|
||||
observer.subscribe(function (result) {
|
||||
_this4.onUpdate(observer, result);
|
||||
});
|
||||
});
|
||||
|
||||
_this4.notify();
|
||||
});
|
||||
};
|
||||
|
||||
_proto.onUpdate = function onUpdate(observer, result) {
|
||||
var index = this.observers.indexOf(observer);
|
||||
|
||||
if (index !== -1) {
|
||||
this.result = replaceAt(this.result, index, result);
|
||||
this.notify();
|
||||
}
|
||||
};
|
||||
|
||||
_proto.notify = function notify() {
|
||||
var _this5 = this;
|
||||
|
||||
notifyManager.batch(function () {
|
||||
_this5.listeners.forEach(function (listener) {
|
||||
listener(_this5.result);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
return QueriesObserver;
|
||||
}(Subscribable);
|
||||
|
||||
var InfiniteQueryObserver = /*#__PURE__*/function (_QueryObserver) {
|
||||
_inheritsLoose(InfiniteQueryObserver, _QueryObserver);
|
||||
|
||||
// Type override
|
||||
// Type override
|
||||
// Type override
|
||||
// eslint-disable-next-line @typescript-eslint/no-useless-constructor
|
||||
function InfiniteQueryObserver(client, options) {
|
||||
return _QueryObserver.call(this, client, options) || this;
|
||||
}
|
||||
|
||||
var _proto = InfiniteQueryObserver.prototype;
|
||||
|
||||
_proto.bindMethods = function bindMethods() {
|
||||
_QueryObserver.prototype.bindMethods.call(this);
|
||||
|
||||
this.fetchNextPage = this.fetchNextPage.bind(this);
|
||||
this.fetchPreviousPage = this.fetchPreviousPage.bind(this);
|
||||
};
|
||||
|
||||
_proto.setOptions = function setOptions(options, notifyOptions) {
|
||||
_QueryObserver.prototype.setOptions.call(this, _extends({}, options, {
|
||||
behavior: infiniteQueryBehavior()
|
||||
}), notifyOptions);
|
||||
};
|
||||
|
||||
_proto.getOptimisticResult = function getOptimisticResult(options) {
|
||||
options.behavior = infiniteQueryBehavior();
|
||||
return _QueryObserver.prototype.getOptimisticResult.call(this, options);
|
||||
};
|
||||
|
||||
_proto.fetchNextPage = function fetchNextPage(options) {
|
||||
var _options$cancelRefetc;
|
||||
|
||||
return this.fetch({
|
||||
// TODO consider removing `?? true` in future breaking change, to be consistent with `refetch` API (see https://github.com/tannerlinsley/react-query/issues/2617)
|
||||
cancelRefetch: (_options$cancelRefetc = options == null ? void 0 : options.cancelRefetch) != null ? _options$cancelRefetc : true,
|
||||
throwOnError: options == null ? void 0 : options.throwOnError,
|
||||
meta: {
|
||||
fetchMore: {
|
||||
direction: 'forward',
|
||||
pageParam: options == null ? void 0 : options.pageParam
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
_proto.fetchPreviousPage = function fetchPreviousPage(options) {
|
||||
var _options$cancelRefetc2;
|
||||
|
||||
return this.fetch({
|
||||
// TODO consider removing `?? true` in future breaking change, to be consistent with `refetch` API (see https://github.com/tannerlinsley/react-query/issues/2617)
|
||||
cancelRefetch: (_options$cancelRefetc2 = options == null ? void 0 : options.cancelRefetch) != null ? _options$cancelRefetc2 : true,
|
||||
throwOnError: options == null ? void 0 : options.throwOnError,
|
||||
meta: {
|
||||
fetchMore: {
|
||||
direction: 'backward',
|
||||
pageParam: options == null ? void 0 : options.pageParam
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
_proto.createResult = function createResult(query, options) {
|
||||
var _state$data, _state$data2, _state$fetchMeta, _state$fetchMeta$fetc, _state$fetchMeta2, _state$fetchMeta2$fet;
|
||||
|
||||
var state = query.state;
|
||||
|
||||
var result = _QueryObserver.prototype.createResult.call(this, query, options);
|
||||
|
||||
return _extends({}, result, {
|
||||
fetchNextPage: this.fetchNextPage,
|
||||
fetchPreviousPage: this.fetchPreviousPage,
|
||||
hasNextPage: hasNextPage(options, (_state$data = state.data) == null ? void 0 : _state$data.pages),
|
||||
hasPreviousPage: hasPreviousPage(options, (_state$data2 = state.data) == null ? void 0 : _state$data2.pages),
|
||||
isFetchingNextPage: state.isFetching && ((_state$fetchMeta = state.fetchMeta) == null ? void 0 : (_state$fetchMeta$fetc = _state$fetchMeta.fetchMore) == null ? void 0 : _state$fetchMeta$fetc.direction) === 'forward',
|
||||
isFetchingPreviousPage: state.isFetching && ((_state$fetchMeta2 = state.fetchMeta) == null ? void 0 : (_state$fetchMeta2$fet = _state$fetchMeta2.fetchMore) == null ? void 0 : _state$fetchMeta2$fet.direction) === 'backward'
|
||||
});
|
||||
};
|
||||
|
||||
return InfiniteQueryObserver;
|
||||
}(QueryObserver);
|
||||
|
||||
// CLASS
|
||||
var MutationObserver = /*#__PURE__*/function (_Subscribable) {
|
||||
_inheritsLoose(MutationObserver, _Subscribable);
|
||||
|
||||
function MutationObserver(client, options) {
|
||||
var _this;
|
||||
|
||||
_this = _Subscribable.call(this) || this;
|
||||
_this.client = client;
|
||||
|
||||
_this.setOptions(options);
|
||||
|
||||
_this.bindMethods();
|
||||
|
||||
_this.updateResult();
|
||||
|
||||
return _this;
|
||||
}
|
||||
|
||||
var _proto = MutationObserver.prototype;
|
||||
|
||||
_proto.bindMethods = function bindMethods() {
|
||||
this.mutate = this.mutate.bind(this);
|
||||
this.reset = this.reset.bind(this);
|
||||
};
|
||||
|
||||
_proto.setOptions = function setOptions(options) {
|
||||
this.options = this.client.defaultMutationOptions(options);
|
||||
};
|
||||
|
||||
_proto.onUnsubscribe = function onUnsubscribe() {
|
||||
if (!this.listeners.length) {
|
||||
var _this$currentMutation;
|
||||
|
||||
(_this$currentMutation = this.currentMutation) == null ? void 0 : _this$currentMutation.removeObserver(this);
|
||||
}
|
||||
};
|
||||
|
||||
_proto.onMutationUpdate = function onMutationUpdate(action) {
|
||||
this.updateResult(); // Determine which callbacks to trigger
|
||||
|
||||
var notifyOptions = {
|
||||
listeners: true
|
||||
};
|
||||
|
||||
if (action.type === 'success') {
|
||||
notifyOptions.onSuccess = true;
|
||||
} else if (action.type === 'error') {
|
||||
notifyOptions.onError = true;
|
||||
}
|
||||
|
||||
this.notify(notifyOptions);
|
||||
};
|
||||
|
||||
_proto.getCurrentResult = function getCurrentResult() {
|
||||
return this.currentResult;
|
||||
};
|
||||
|
||||
_proto.reset = function reset() {
|
||||
this.currentMutation = undefined;
|
||||
this.updateResult();
|
||||
this.notify({
|
||||
listeners: true
|
||||
});
|
||||
};
|
||||
|
||||
_proto.mutate = function mutate(variables, options) {
|
||||
this.mutateOptions = options;
|
||||
|
||||
if (this.currentMutation) {
|
||||
this.currentMutation.removeObserver(this);
|
||||
}
|
||||
|
||||
this.currentMutation = this.client.getMutationCache().build(this.client, _extends({}, this.options, {
|
||||
variables: typeof variables !== 'undefined' ? variables : this.options.variables
|
||||
}));
|
||||
this.currentMutation.addObserver(this);
|
||||
return this.currentMutation.execute();
|
||||
};
|
||||
|
||||
_proto.updateResult = function updateResult() {
|
||||
var state = this.currentMutation ? this.currentMutation.state : getDefaultState();
|
||||
|
||||
var result = _extends({}, state, {
|
||||
isLoading: state.status === 'loading',
|
||||
isSuccess: state.status === 'success',
|
||||
isError: state.status === 'error',
|
||||
isIdle: state.status === 'idle',
|
||||
mutate: this.mutate,
|
||||
reset: this.reset
|
||||
});
|
||||
|
||||
this.currentResult = result;
|
||||
};
|
||||
|
||||
_proto.notify = function notify(options) {
|
||||
var _this2 = this;
|
||||
|
||||
notifyManager.batch(function () {
|
||||
// First trigger the mutate callbacks
|
||||
if (_this2.mutateOptions) {
|
||||
if (options.onSuccess) {
|
||||
_this2.mutateOptions.onSuccess == null ? void 0 : _this2.mutateOptions.onSuccess(_this2.currentResult.data, _this2.currentResult.variables, _this2.currentResult.context);
|
||||
_this2.mutateOptions.onSettled == null ? void 0 : _this2.mutateOptions.onSettled(_this2.currentResult.data, null, _this2.currentResult.variables, _this2.currentResult.context);
|
||||
} else if (options.onError) {
|
||||
_this2.mutateOptions.onError == null ? void 0 : _this2.mutateOptions.onError(_this2.currentResult.error, _this2.currentResult.variables, _this2.currentResult.context);
|
||||
_this2.mutateOptions.onSettled == null ? void 0 : _this2.mutateOptions.onSettled(undefined, _this2.currentResult.error, _this2.currentResult.variables, _this2.currentResult.context);
|
||||
}
|
||||
} // Then trigger the listeners
|
||||
|
||||
|
||||
if (options.listeners) {
|
||||
_this2.listeners.forEach(function (listener) {
|
||||
listener(_this2.currentResult);
|
||||
});
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
return MutationObserver;
|
||||
}(Subscribable);
|
||||
|
||||
// TYPES
|
||||
// FUNCTIONS
|
||||
function dehydrateMutation(mutation) {
|
||||
return {
|
||||
mutationKey: mutation.options.mutationKey,
|
||||
state: mutation.state
|
||||
};
|
||||
} // Most config is not dehydrated but instead meant to configure again when
|
||||
// consuming the de/rehydrated data, typically with useQuery on the client.
|
||||
// Sometimes it might make sense to prefetch data on the server and include
|
||||
// in the html-payload, but not consume it on the initial render.
|
||||
|
||||
|
||||
function dehydrateQuery(query) {
|
||||
return {
|
||||
state: query.state,
|
||||
queryKey: query.queryKey,
|
||||
queryHash: query.queryHash
|
||||
};
|
||||
}
|
||||
|
||||
function defaultShouldDehydrateMutation(mutation) {
|
||||
return mutation.state.isPaused;
|
||||
}
|
||||
|
||||
function defaultShouldDehydrateQuery(query) {
|
||||
return query.state.status === 'success';
|
||||
}
|
||||
|
||||
function dehydrate(client, options) {
|
||||
var _options, _options2;
|
||||
|
||||
options = options || {};
|
||||
var mutations = [];
|
||||
var queries = [];
|
||||
|
||||
if (((_options = options) == null ? void 0 : _options.dehydrateMutations) !== false) {
|
||||
var shouldDehydrateMutation = options.shouldDehydrateMutation || defaultShouldDehydrateMutation;
|
||||
client.getMutationCache().getAll().forEach(function (mutation) {
|
||||
if (shouldDehydrateMutation(mutation)) {
|
||||
mutations.push(dehydrateMutation(mutation));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (((_options2 = options) == null ? void 0 : _options2.dehydrateQueries) !== false) {
|
||||
var shouldDehydrateQuery = options.shouldDehydrateQuery || defaultShouldDehydrateQuery;
|
||||
client.getQueryCache().getAll().forEach(function (query) {
|
||||
if (shouldDehydrateQuery(query)) {
|
||||
queries.push(dehydrateQuery(query));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
mutations: mutations,
|
||||
queries: queries
|
||||
};
|
||||
}
|
||||
function hydrate(client, dehydratedState, options) {
|
||||
if (typeof dehydratedState !== 'object' || dehydratedState === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
var mutationCache = client.getMutationCache();
|
||||
var queryCache = client.getQueryCache();
|
||||
var mutations = dehydratedState.mutations || [];
|
||||
var queries = dehydratedState.queries || [];
|
||||
mutations.forEach(function (dehydratedMutation) {
|
||||
var _options$defaultOptio;
|
||||
|
||||
mutationCache.build(client, _extends({}, options == null ? void 0 : (_options$defaultOptio = options.defaultOptions) == null ? void 0 : _options$defaultOptio.mutations, {
|
||||
mutationKey: dehydratedMutation.mutationKey
|
||||
}), dehydratedMutation.state);
|
||||
});
|
||||
queries.forEach(function (dehydratedQuery) {
|
||||
var _options$defaultOptio2;
|
||||
|
||||
var query = queryCache.get(dehydratedQuery.queryHash); // Do not hydrate if an existing query exists with newer data
|
||||
|
||||
if (query) {
|
||||
if (query.state.dataUpdatedAt < dehydratedQuery.state.dataUpdatedAt) {
|
||||
query.setState(dehydratedQuery.state);
|
||||
}
|
||||
|
||||
return;
|
||||
} // Restore query
|
||||
|
||||
|
||||
queryCache.build(client, _extends({}, options == null ? void 0 : (_options$defaultOptio2 = options.defaultOptions) == null ? void 0 : _options$defaultOptio2.queries, {
|
||||
queryKey: dehydratedQuery.queryKey,
|
||||
queryHash: dehydratedQuery.queryHash
|
||||
}), dehydratedQuery.state);
|
||||
});
|
||||
}
|
||||
|
||||
exports.CancelledError = CancelledError;
|
||||
exports.InfiniteQueryObserver = InfiniteQueryObserver;
|
||||
exports.MutationCache = MutationCache;
|
||||
exports.MutationObserver = MutationObserver;
|
||||
exports.QueriesObserver = QueriesObserver;
|
||||
exports.QueryCache = QueryCache;
|
||||
exports.QueryClient = QueryClient;
|
||||
exports.QueryObserver = QueryObserver;
|
||||
exports.dehydrate = dehydrate;
|
||||
exports.focusManager = focusManager;
|
||||
exports.hashQueryKey = hashQueryKey;
|
||||
exports.hydrate = hydrate;
|
||||
exports.isCancelledError = isCancelledError;
|
||||
exports.isError = isError;
|
||||
exports.notifyManager = notifyManager;
|
||||
exports.onlineManager = onlineManager;
|
||||
exports.setLogger = setLogger;
|
||||
|
||||
Object.defineProperty(exports, '__esModule', { value: true });
|
||||
|
||||
})));
|
||||
//# sourceMappingURL=react-query-core.development.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
+2
File diff suppressed because one or more lines are too long
+1
File diff suppressed because one or more lines are too long
+2086
@@ -0,0 +1,2086 @@
|
||||
(function (global, factory) {
|
||||
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react'), require('react-query')) :
|
||||
typeof define === 'function' && define.amd ? define(['exports', 'react', 'react-query'], factory) :
|
||||
(global = global || self, factory(global.ReactQueryDevtools = {}, global.React, global.ReactQuery));
|
||||
}(this, (function (exports, React, reactQuery) { 'use strict';
|
||||
|
||||
var React__default = 'default' in React ? React['default'] : React;
|
||||
|
||||
function _extends() {
|
||||
_extends = Object.assign || function (target) {
|
||||
for (var i = 1; i < arguments.length; i++) {
|
||||
var source = arguments[i];
|
||||
|
||||
for (var key in source) {
|
||||
if (Object.prototype.hasOwnProperty.call(source, key)) {
|
||||
target[key] = source[key];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return target;
|
||||
};
|
||||
|
||||
return _extends.apply(this, arguments);
|
||||
}
|
||||
|
||||
function _objectWithoutPropertiesLoose(source, excluded) {
|
||||
if (source == null) return {};
|
||||
var target = {};
|
||||
var sourceKeys = Object.keys(source);
|
||||
var key, i;
|
||||
|
||||
for (i = 0; i < sourceKeys.length; i++) {
|
||||
key = sourceKeys[i];
|
||||
if (excluded.indexOf(key) >= 0) continue;
|
||||
target[key] = source[key];
|
||||
}
|
||||
|
||||
return target;
|
||||
}
|
||||
|
||||
function _extends$1() {
|
||||
_extends$1 = Object.assign || function (target) {
|
||||
for (var i = 1; i < arguments.length; i++) {
|
||||
var source = arguments[i];
|
||||
|
||||
for (var key in source) {
|
||||
if (Object.prototype.hasOwnProperty.call(source, key)) {
|
||||
target[key] = source[key];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return target;
|
||||
};
|
||||
|
||||
return _extends$1.apply(this, arguments);
|
||||
}
|
||||
|
||||
var characterMap = {
|
||||
"À": "A",
|
||||
"Á": "A",
|
||||
"Â": "A",
|
||||
"Ã": "A",
|
||||
"Ä": "A",
|
||||
"Å": "A",
|
||||
"Ấ": "A",
|
||||
"Ắ": "A",
|
||||
"Ẳ": "A",
|
||||
"Ẵ": "A",
|
||||
"Ặ": "A",
|
||||
"Æ": "AE",
|
||||
"Ầ": "A",
|
||||
"Ằ": "A",
|
||||
"Ȃ": "A",
|
||||
"Ç": "C",
|
||||
"Ḉ": "C",
|
||||
"È": "E",
|
||||
"É": "E",
|
||||
"Ê": "E",
|
||||
"Ë": "E",
|
||||
"Ế": "E",
|
||||
"Ḗ": "E",
|
||||
"Ề": "E",
|
||||
"Ḕ": "E",
|
||||
"Ḝ": "E",
|
||||
"Ȇ": "E",
|
||||
"Ì": "I",
|
||||
"Í": "I",
|
||||
"Î": "I",
|
||||
"Ï": "I",
|
||||
"Ḯ": "I",
|
||||
"Ȋ": "I",
|
||||
"Ð": "D",
|
||||
"Ñ": "N",
|
||||
"Ò": "O",
|
||||
"Ó": "O",
|
||||
"Ô": "O",
|
||||
"Õ": "O",
|
||||
"Ö": "O",
|
||||
"Ø": "O",
|
||||
"Ố": "O",
|
||||
"Ṍ": "O",
|
||||
"Ṓ": "O",
|
||||
"Ȏ": "O",
|
||||
"Ù": "U",
|
||||
"Ú": "U",
|
||||
"Û": "U",
|
||||
"Ü": "U",
|
||||
"Ý": "Y",
|
||||
"à": "a",
|
||||
"á": "a",
|
||||
"â": "a",
|
||||
"ã": "a",
|
||||
"ä": "a",
|
||||
"å": "a",
|
||||
"ấ": "a",
|
||||
"ắ": "a",
|
||||
"ẳ": "a",
|
||||
"ẵ": "a",
|
||||
"ặ": "a",
|
||||
"æ": "ae",
|
||||
"ầ": "a",
|
||||
"ằ": "a",
|
||||
"ȃ": "a",
|
||||
"ç": "c",
|
||||
"ḉ": "c",
|
||||
"è": "e",
|
||||
"é": "e",
|
||||
"ê": "e",
|
||||
"ë": "e",
|
||||
"ế": "e",
|
||||
"ḗ": "e",
|
||||
"ề": "e",
|
||||
"ḕ": "e",
|
||||
"ḝ": "e",
|
||||
"ȇ": "e",
|
||||
"ì": "i",
|
||||
"í": "i",
|
||||
"î": "i",
|
||||
"ï": "i",
|
||||
"ḯ": "i",
|
||||
"ȋ": "i",
|
||||
"ð": "d",
|
||||
"ñ": "n",
|
||||
"ò": "o",
|
||||
"ó": "o",
|
||||
"ô": "o",
|
||||
"õ": "o",
|
||||
"ö": "o",
|
||||
"ø": "o",
|
||||
"ố": "o",
|
||||
"ṍ": "o",
|
||||
"ṓ": "o",
|
||||
"ȏ": "o",
|
||||
"ù": "u",
|
||||
"ú": "u",
|
||||
"û": "u",
|
||||
"ü": "u",
|
||||
"ý": "y",
|
||||
"ÿ": "y",
|
||||
"Ā": "A",
|
||||
"ā": "a",
|
||||
"Ă": "A",
|
||||
"ă": "a",
|
||||
"Ą": "A",
|
||||
"ą": "a",
|
||||
"Ć": "C",
|
||||
"ć": "c",
|
||||
"Ĉ": "C",
|
||||
"ĉ": "c",
|
||||
"Ċ": "C",
|
||||
"ċ": "c",
|
||||
"Č": "C",
|
||||
"č": "c",
|
||||
"C̆": "C",
|
||||
"c̆": "c",
|
||||
"Ď": "D",
|
||||
"ď": "d",
|
||||
"Đ": "D",
|
||||
"đ": "d",
|
||||
"Ē": "E",
|
||||
"ē": "e",
|
||||
"Ĕ": "E",
|
||||
"ĕ": "e",
|
||||
"Ė": "E",
|
||||
"ė": "e",
|
||||
"Ę": "E",
|
||||
"ę": "e",
|
||||
"Ě": "E",
|
||||
"ě": "e",
|
||||
"Ĝ": "G",
|
||||
"Ǵ": "G",
|
||||
"ĝ": "g",
|
||||
"ǵ": "g",
|
||||
"Ğ": "G",
|
||||
"ğ": "g",
|
||||
"Ġ": "G",
|
||||
"ġ": "g",
|
||||
"Ģ": "G",
|
||||
"ģ": "g",
|
||||
"Ĥ": "H",
|
||||
"ĥ": "h",
|
||||
"Ħ": "H",
|
||||
"ħ": "h",
|
||||
"Ḫ": "H",
|
||||
"ḫ": "h",
|
||||
"Ĩ": "I",
|
||||
"ĩ": "i",
|
||||
"Ī": "I",
|
||||
"ī": "i",
|
||||
"Ĭ": "I",
|
||||
"ĭ": "i",
|
||||
"Į": "I",
|
||||
"į": "i",
|
||||
"İ": "I",
|
||||
"ı": "i",
|
||||
"IJ": "IJ",
|
||||
"ij": "ij",
|
||||
"Ĵ": "J",
|
||||
"ĵ": "j",
|
||||
"Ķ": "K",
|
||||
"ķ": "k",
|
||||
"Ḱ": "K",
|
||||
"ḱ": "k",
|
||||
"K̆": "K",
|
||||
"k̆": "k",
|
||||
"Ĺ": "L",
|
||||
"ĺ": "l",
|
||||
"Ļ": "L",
|
||||
"ļ": "l",
|
||||
"Ľ": "L",
|
||||
"ľ": "l",
|
||||
"Ŀ": "L",
|
||||
"ŀ": "l",
|
||||
"Ł": "l",
|
||||
"ł": "l",
|
||||
"Ḿ": "M",
|
||||
"ḿ": "m",
|
||||
"M̆": "M",
|
||||
"m̆": "m",
|
||||
"Ń": "N",
|
||||
"ń": "n",
|
||||
"Ņ": "N",
|
||||
"ņ": "n",
|
||||
"Ň": "N",
|
||||
"ň": "n",
|
||||
"ʼn": "n",
|
||||
"N̆": "N",
|
||||
"n̆": "n",
|
||||
"Ō": "O",
|
||||
"ō": "o",
|
||||
"Ŏ": "O",
|
||||
"ŏ": "o",
|
||||
"Ő": "O",
|
||||
"ő": "o",
|
||||
"Œ": "OE",
|
||||
"œ": "oe",
|
||||
"P̆": "P",
|
||||
"p̆": "p",
|
||||
"Ŕ": "R",
|
||||
"ŕ": "r",
|
||||
"Ŗ": "R",
|
||||
"ŗ": "r",
|
||||
"Ř": "R",
|
||||
"ř": "r",
|
||||
"R̆": "R",
|
||||
"r̆": "r",
|
||||
"Ȓ": "R",
|
||||
"ȓ": "r",
|
||||
"Ś": "S",
|
||||
"ś": "s",
|
||||
"Ŝ": "S",
|
||||
"ŝ": "s",
|
||||
"Ş": "S",
|
||||
"Ș": "S",
|
||||
"ș": "s",
|
||||
"ş": "s",
|
||||
"Š": "S",
|
||||
"š": "s",
|
||||
"Ţ": "T",
|
||||
"ţ": "t",
|
||||
"ț": "t",
|
||||
"Ț": "T",
|
||||
"Ť": "T",
|
||||
"ť": "t",
|
||||
"Ŧ": "T",
|
||||
"ŧ": "t",
|
||||
"T̆": "T",
|
||||
"t̆": "t",
|
||||
"Ũ": "U",
|
||||
"ũ": "u",
|
||||
"Ū": "U",
|
||||
"ū": "u",
|
||||
"Ŭ": "U",
|
||||
"ŭ": "u",
|
||||
"Ů": "U",
|
||||
"ů": "u",
|
||||
"Ű": "U",
|
||||
"ű": "u",
|
||||
"Ų": "U",
|
||||
"ų": "u",
|
||||
"Ȗ": "U",
|
||||
"ȗ": "u",
|
||||
"V̆": "V",
|
||||
"v̆": "v",
|
||||
"Ŵ": "W",
|
||||
"ŵ": "w",
|
||||
"Ẃ": "W",
|
||||
"ẃ": "w",
|
||||
"X̆": "X",
|
||||
"x̆": "x",
|
||||
"Ŷ": "Y",
|
||||
"ŷ": "y",
|
||||
"Ÿ": "Y",
|
||||
"Y̆": "Y",
|
||||
"y̆": "y",
|
||||
"Ź": "Z",
|
||||
"ź": "z",
|
||||
"Ż": "Z",
|
||||
"ż": "z",
|
||||
"Ž": "Z",
|
||||
"ž": "z",
|
||||
"ſ": "s",
|
||||
"ƒ": "f",
|
||||
"Ơ": "O",
|
||||
"ơ": "o",
|
||||
"Ư": "U",
|
||||
"ư": "u",
|
||||
"Ǎ": "A",
|
||||
"ǎ": "a",
|
||||
"Ǐ": "I",
|
||||
"ǐ": "i",
|
||||
"Ǒ": "O",
|
||||
"ǒ": "o",
|
||||
"Ǔ": "U",
|
||||
"ǔ": "u",
|
||||
"Ǖ": "U",
|
||||
"ǖ": "u",
|
||||
"Ǘ": "U",
|
||||
"ǘ": "u",
|
||||
"Ǚ": "U",
|
||||
"ǚ": "u",
|
||||
"Ǜ": "U",
|
||||
"ǜ": "u",
|
||||
"Ứ": "U",
|
||||
"ứ": "u",
|
||||
"Ṹ": "U",
|
||||
"ṹ": "u",
|
||||
"Ǻ": "A",
|
||||
"ǻ": "a",
|
||||
"Ǽ": "AE",
|
||||
"ǽ": "ae",
|
||||
"Ǿ": "O",
|
||||
"ǿ": "o",
|
||||
"Þ": "TH",
|
||||
"þ": "th",
|
||||
"Ṕ": "P",
|
||||
"ṕ": "p",
|
||||
"Ṥ": "S",
|
||||
"ṥ": "s",
|
||||
"X́": "X",
|
||||
"x́": "x",
|
||||
"Ѓ": "Г",
|
||||
"ѓ": "г",
|
||||
"Ќ": "К",
|
||||
"ќ": "к",
|
||||
"A̋": "A",
|
||||
"a̋": "a",
|
||||
"E̋": "E",
|
||||
"e̋": "e",
|
||||
"I̋": "I",
|
||||
"i̋": "i",
|
||||
"Ǹ": "N",
|
||||
"ǹ": "n",
|
||||
"Ồ": "O",
|
||||
"ồ": "o",
|
||||
"Ṑ": "O",
|
||||
"ṑ": "o",
|
||||
"Ừ": "U",
|
||||
"ừ": "u",
|
||||
"Ẁ": "W",
|
||||
"ẁ": "w",
|
||||
"Ỳ": "Y",
|
||||
"ỳ": "y",
|
||||
"Ȁ": "A",
|
||||
"ȁ": "a",
|
||||
"Ȅ": "E",
|
||||
"ȅ": "e",
|
||||
"Ȉ": "I",
|
||||
"ȉ": "i",
|
||||
"Ȍ": "O",
|
||||
"ȍ": "o",
|
||||
"Ȑ": "R",
|
||||
"ȑ": "r",
|
||||
"Ȕ": "U",
|
||||
"ȕ": "u",
|
||||
"B̌": "B",
|
||||
"b̌": "b",
|
||||
"Č̣": "C",
|
||||
"č̣": "c",
|
||||
"Ê̌": "E",
|
||||
"ê̌": "e",
|
||||
"F̌": "F",
|
||||
"f̌": "f",
|
||||
"Ǧ": "G",
|
||||
"ǧ": "g",
|
||||
"Ȟ": "H",
|
||||
"ȟ": "h",
|
||||
"J̌": "J",
|
||||
"ǰ": "j",
|
||||
"Ǩ": "K",
|
||||
"ǩ": "k",
|
||||
"M̌": "M",
|
||||
"m̌": "m",
|
||||
"P̌": "P",
|
||||
"p̌": "p",
|
||||
"Q̌": "Q",
|
||||
"q̌": "q",
|
||||
"Ř̩": "R",
|
||||
"ř̩": "r",
|
||||
"Ṧ": "S",
|
||||
"ṧ": "s",
|
||||
"V̌": "V",
|
||||
"v̌": "v",
|
||||
"W̌": "W",
|
||||
"w̌": "w",
|
||||
"X̌": "X",
|
||||
"x̌": "x",
|
||||
"Y̌": "Y",
|
||||
"y̌": "y",
|
||||
"A̧": "A",
|
||||
"a̧": "a",
|
||||
"B̧": "B",
|
||||
"b̧": "b",
|
||||
"Ḑ": "D",
|
||||
"ḑ": "d",
|
||||
"Ȩ": "E",
|
||||
"ȩ": "e",
|
||||
"Ɛ̧": "E",
|
||||
"ɛ̧": "e",
|
||||
"Ḩ": "H",
|
||||
"ḩ": "h",
|
||||
"I̧": "I",
|
||||
"i̧": "i",
|
||||
"Ɨ̧": "I",
|
||||
"ɨ̧": "i",
|
||||
"M̧": "M",
|
||||
"m̧": "m",
|
||||
"O̧": "O",
|
||||
"o̧": "o",
|
||||
"Q̧": "Q",
|
||||
"q̧": "q",
|
||||
"U̧": "U",
|
||||
"u̧": "u",
|
||||
"X̧": "X",
|
||||
"x̧": "x",
|
||||
"Z̧": "Z",
|
||||
"z̧": "z"
|
||||
};
|
||||
var chars = Object.keys(characterMap).join('|');
|
||||
var allAccents = new RegExp(chars, 'g');
|
||||
var firstAccent = new RegExp(chars, '');
|
||||
|
||||
var removeAccents = function (string) {
|
||||
return string.replace(allAccents, function (match) {
|
||||
return characterMap[match];
|
||||
});
|
||||
};
|
||||
|
||||
var hasAccents = function (string) {
|
||||
return !!string.match(firstAccent);
|
||||
};
|
||||
|
||||
var removeAccents_1 = removeAccents;
|
||||
var has = hasAccents;
|
||||
var remove = removeAccents;
|
||||
removeAccents_1.has = has;
|
||||
removeAccents_1.remove = remove;
|
||||
|
||||
var rankings = {
|
||||
CASE_SENSITIVE_EQUAL: 7,
|
||||
EQUAL: 6,
|
||||
STARTS_WITH: 5,
|
||||
WORD_STARTS_WITH: 4,
|
||||
CONTAINS: 3,
|
||||
ACRONYM: 2,
|
||||
MATCHES: 1,
|
||||
NO_MATCH: 0
|
||||
};
|
||||
matchSorter.rankings = rankings;
|
||||
|
||||
var defaultBaseSortFn = function (a, b) {
|
||||
return String(a.rankedValue).localeCompare(String(b.rankedValue));
|
||||
};
|
||||
/**
|
||||
* Takes an array of items and a value and returns a new array with the items that match the given value
|
||||
* @param {Array} items - the items to sort
|
||||
* @param {String} value - the value to use for ranking
|
||||
* @param {Object} options - Some options to configure the sorter
|
||||
* @return {Array} - the new sorted array
|
||||
*/
|
||||
|
||||
|
||||
function matchSorter(items, value, options) {
|
||||
if (options === void 0) {
|
||||
options = {};
|
||||
}
|
||||
|
||||
var _options = options,
|
||||
keys = _options.keys,
|
||||
_options$threshold = _options.threshold,
|
||||
threshold = _options$threshold === void 0 ? rankings.MATCHES : _options$threshold,
|
||||
_options$baseSort = _options.baseSort,
|
||||
baseSort = _options$baseSort === void 0 ? defaultBaseSortFn : _options$baseSort;
|
||||
var matchedItems = items.reduce(reduceItemsToRanked, []);
|
||||
return matchedItems.sort(function (a, b) {
|
||||
return sortRankedValues(a, b, baseSort);
|
||||
}).map(function (_ref) {
|
||||
var item = _ref.item;
|
||||
return item;
|
||||
});
|
||||
|
||||
function reduceItemsToRanked(matches, item, index) {
|
||||
var rankingInfo = getHighestRanking(item, keys, value, options);
|
||||
var rank = rankingInfo.rank,
|
||||
_rankingInfo$keyThres = rankingInfo.keyThreshold,
|
||||
keyThreshold = _rankingInfo$keyThres === void 0 ? threshold : _rankingInfo$keyThres;
|
||||
|
||||
if (rank >= keyThreshold) {
|
||||
matches.push(_extends$1({}, rankingInfo, {
|
||||
item: item,
|
||||
index: index
|
||||
}));
|
||||
}
|
||||
|
||||
return matches;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Gets the highest ranking for value for the given item based on its values for the given keys
|
||||
* @param {*} item - the item to rank
|
||||
* @param {Array} keys - the keys to get values from the item for the ranking
|
||||
* @param {String} value - the value to rank against
|
||||
* @param {Object} options - options to control the ranking
|
||||
* @return {{rank: Number, keyIndex: Number, keyThreshold: Number}} - the highest ranking
|
||||
*/
|
||||
|
||||
|
||||
function getHighestRanking(item, keys, value, options) {
|
||||
if (!keys) {
|
||||
// if keys is not specified, then we assume the item given is ready to be matched
|
||||
var stringItem = item;
|
||||
return {
|
||||
// ends up being duplicate of 'item' in matches but consistent
|
||||
rankedValue: stringItem,
|
||||
rank: getMatchRanking(stringItem, value, options),
|
||||
keyIndex: -1,
|
||||
keyThreshold: options.threshold
|
||||
};
|
||||
}
|
||||
|
||||
var valuesToRank = getAllValuesToRank(item, keys);
|
||||
return valuesToRank.reduce(function (_ref2, _ref3, i) {
|
||||
var rank = _ref2.rank,
|
||||
rankedValue = _ref2.rankedValue,
|
||||
keyIndex = _ref2.keyIndex,
|
||||
keyThreshold = _ref2.keyThreshold;
|
||||
var itemValue = _ref3.itemValue,
|
||||
attributes = _ref3.attributes;
|
||||
var newRank = getMatchRanking(itemValue, value, options);
|
||||
var newRankedValue = rankedValue;
|
||||
var minRanking = attributes.minRanking,
|
||||
maxRanking = attributes.maxRanking,
|
||||
threshold = attributes.threshold;
|
||||
|
||||
if (newRank < minRanking && newRank >= rankings.MATCHES) {
|
||||
newRank = minRanking;
|
||||
} else if (newRank > maxRanking) {
|
||||
newRank = maxRanking;
|
||||
}
|
||||
|
||||
if (newRank > rank) {
|
||||
rank = newRank;
|
||||
keyIndex = i;
|
||||
keyThreshold = threshold;
|
||||
newRankedValue = itemValue;
|
||||
}
|
||||
|
||||
return {
|
||||
rankedValue: newRankedValue,
|
||||
rank: rank,
|
||||
keyIndex: keyIndex,
|
||||
keyThreshold: keyThreshold
|
||||
};
|
||||
}, {
|
||||
rankedValue: item,
|
||||
rank: rankings.NO_MATCH,
|
||||
keyIndex: -1,
|
||||
keyThreshold: options.threshold
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Gives a rankings score based on how well the two strings match.
|
||||
* @param {String} testString - the string to test against
|
||||
* @param {String} stringToRank - the string to rank
|
||||
* @param {Object} options - options for the match (like keepDiacritics for comparison)
|
||||
* @returns {Number} the ranking for how well stringToRank matches testString
|
||||
*/
|
||||
|
||||
|
||||
function getMatchRanking(testString, stringToRank, options) {
|
||||
testString = prepareValueForComparison(testString, options);
|
||||
stringToRank = prepareValueForComparison(stringToRank, options); // too long
|
||||
|
||||
if (stringToRank.length > testString.length) {
|
||||
return rankings.NO_MATCH;
|
||||
} // case sensitive equals
|
||||
|
||||
|
||||
if (testString === stringToRank) {
|
||||
return rankings.CASE_SENSITIVE_EQUAL;
|
||||
} // Lower casing before further comparison
|
||||
|
||||
|
||||
testString = testString.toLowerCase();
|
||||
stringToRank = stringToRank.toLowerCase(); // case insensitive equals
|
||||
|
||||
if (testString === stringToRank) {
|
||||
return rankings.EQUAL;
|
||||
} // starts with
|
||||
|
||||
|
||||
if (testString.startsWith(stringToRank)) {
|
||||
return rankings.STARTS_WITH;
|
||||
} // word starts with
|
||||
|
||||
|
||||
if (testString.includes(" " + stringToRank)) {
|
||||
return rankings.WORD_STARTS_WITH;
|
||||
} // contains
|
||||
|
||||
|
||||
if (testString.includes(stringToRank)) {
|
||||
return rankings.CONTAINS;
|
||||
} else if (stringToRank.length === 1) {
|
||||
// If the only character in the given stringToRank
|
||||
// isn't even contained in the testString, then
|
||||
// it's definitely not a match.
|
||||
return rankings.NO_MATCH;
|
||||
} // acronym
|
||||
|
||||
|
||||
if (getAcronym(testString).includes(stringToRank)) {
|
||||
return rankings.ACRONYM;
|
||||
} // will return a number between rankings.MATCHES and
|
||||
// rankings.MATCHES + 1 depending on how close of a match it is.
|
||||
|
||||
|
||||
return getClosenessRanking(testString, stringToRank);
|
||||
}
|
||||
/**
|
||||
* Generates an acronym for a string.
|
||||
*
|
||||
* @param {String} string the string for which to produce the acronym
|
||||
* @returns {String} the acronym
|
||||
*/
|
||||
|
||||
|
||||
function getAcronym(string) {
|
||||
var acronym = '';
|
||||
var wordsInString = string.split(' ');
|
||||
wordsInString.forEach(function (wordInString) {
|
||||
var splitByHyphenWords = wordInString.split('-');
|
||||
splitByHyphenWords.forEach(function (splitByHyphenWord) {
|
||||
acronym += splitByHyphenWord.substr(0, 1);
|
||||
});
|
||||
});
|
||||
return acronym;
|
||||
}
|
||||
/**
|
||||
* Returns a score based on how spread apart the
|
||||
* characters from the stringToRank are within the testString.
|
||||
* A number close to rankings.MATCHES represents a loose match. A number close
|
||||
* to rankings.MATCHES + 1 represents a tighter match.
|
||||
* @param {String} testString - the string to test against
|
||||
* @param {String} stringToRank - the string to rank
|
||||
* @returns {Number} the number between rankings.MATCHES and
|
||||
* rankings.MATCHES + 1 for how well stringToRank matches testString
|
||||
*/
|
||||
|
||||
|
||||
function getClosenessRanking(testString, stringToRank) {
|
||||
var matchingInOrderCharCount = 0;
|
||||
var charNumber = 0;
|
||||
|
||||
function findMatchingCharacter(matchChar, string, index) {
|
||||
for (var j = index; j < string.length; j++) {
|
||||
var stringChar = string[j];
|
||||
|
||||
if (stringChar === matchChar) {
|
||||
matchingInOrderCharCount += 1;
|
||||
return j + 1;
|
||||
}
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
function getRanking(spread) {
|
||||
var inOrderPercentage = matchingInOrderCharCount / stringToRank.length;
|
||||
var ranking = rankings.MATCHES + inOrderPercentage * (1 / spread);
|
||||
return ranking;
|
||||
}
|
||||
|
||||
var firstIndex = findMatchingCharacter(stringToRank[0], testString, 0);
|
||||
|
||||
if (firstIndex < 0) {
|
||||
return rankings.NO_MATCH;
|
||||
}
|
||||
|
||||
charNumber = firstIndex;
|
||||
|
||||
for (var i = 1; i < stringToRank.length; i++) {
|
||||
var matchChar = stringToRank[i];
|
||||
charNumber = findMatchingCharacter(matchChar, testString, charNumber);
|
||||
var found = charNumber > -1;
|
||||
|
||||
if (!found) {
|
||||
return rankings.NO_MATCH;
|
||||
}
|
||||
}
|
||||
|
||||
var spread = charNumber - firstIndex;
|
||||
return getRanking(spread);
|
||||
}
|
||||
/**
|
||||
* Sorts items that have a rank, index, and keyIndex
|
||||
* @param {Object} a - the first item to sort
|
||||
* @param {Object} b - the second item to sort
|
||||
* @return {Number} -1 if a should come first, 1 if b should come first, 0 if equal
|
||||
*/
|
||||
|
||||
|
||||
function sortRankedValues(a, b, baseSort) {
|
||||
var aFirst = -1;
|
||||
var bFirst = 1;
|
||||
var aRank = a.rank,
|
||||
aKeyIndex = a.keyIndex;
|
||||
var bRank = b.rank,
|
||||
bKeyIndex = b.keyIndex;
|
||||
|
||||
if (aRank === bRank) {
|
||||
if (aKeyIndex === bKeyIndex) {
|
||||
// use the base sort function as a tie-breaker
|
||||
return baseSort(a, b);
|
||||
} else {
|
||||
return aKeyIndex < bKeyIndex ? aFirst : bFirst;
|
||||
}
|
||||
} else {
|
||||
return aRank > bRank ? aFirst : bFirst;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Prepares value for comparison by stringifying it, removing diacritics (if specified)
|
||||
* @param {String} value - the value to clean
|
||||
* @param {Object} options - {keepDiacritics: whether to remove diacritics}
|
||||
* @return {String} the prepared value
|
||||
*/
|
||||
|
||||
|
||||
function prepareValueForComparison(value, _ref4) {
|
||||
var keepDiacritics = _ref4.keepDiacritics; // value might not actually be a string at this point (we don't get to choose)
|
||||
// so part of preparing the value for comparison is ensure that it is a string
|
||||
|
||||
value = "" + value; // toString
|
||||
|
||||
if (!keepDiacritics) {
|
||||
value = removeAccents_1(value);
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
/**
|
||||
* Gets value for key in item at arbitrarily nested keypath
|
||||
* @param {Object} item - the item
|
||||
* @param {Object|Function} key - the potentially nested keypath or property callback
|
||||
* @return {Array} - an array containing the value(s) at the nested keypath
|
||||
*/
|
||||
|
||||
|
||||
function getItemValues(item, key) {
|
||||
if (typeof key === 'object') {
|
||||
key = key.key;
|
||||
}
|
||||
|
||||
var value;
|
||||
|
||||
if (typeof key === 'function') {
|
||||
value = key(item); // eslint-disable-next-line no-negated-condition
|
||||
} else {
|
||||
value = getNestedValue(key, item);
|
||||
} // concat because `value` can be a string or an array
|
||||
// eslint-disable-next-line
|
||||
|
||||
|
||||
return value != null ? [].concat(value) : null;
|
||||
}
|
||||
/**
|
||||
* Given key: "foo.bar.baz"
|
||||
* And obj: {foo: {bar: {baz: 'buzz'}}}
|
||||
* -> 'buzz'
|
||||
* @param key a dot-separated set of keys
|
||||
* @param obj the object to get the value from
|
||||
*/
|
||||
|
||||
|
||||
function getNestedValue(key, obj) {
|
||||
// @ts-expect-error really have no idea how to type this properly...
|
||||
return key.split('.').reduce(function (itemObj, nestedKey) {
|
||||
// @ts-expect-error lost on this one as well...
|
||||
return itemObj ? itemObj[nestedKey] : null;
|
||||
}, obj);
|
||||
}
|
||||
/**
|
||||
* Gets all the values for the given keys in the given item and returns an array of those values
|
||||
* @param item - the item from which the values will be retrieved
|
||||
* @param keys - the keys to use to retrieve the values
|
||||
* @return objects with {itemValue, attributes}
|
||||
*/
|
||||
|
||||
|
||||
function getAllValuesToRank(item, keys) {
|
||||
return keys.reduce(function (allVals, key) {
|
||||
var values = getItemValues(item, key);
|
||||
|
||||
if (values) {
|
||||
values.forEach(function (itemValue) {
|
||||
allVals.push({
|
||||
itemValue: itemValue,
|
||||
attributes: getKeyAttributes(key)
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
return allVals;
|
||||
}, []);
|
||||
}
|
||||
|
||||
var defaultKeyAttributes = {
|
||||
maxRanking: Infinity,
|
||||
minRanking: -Infinity
|
||||
};
|
||||
/**
|
||||
* Gets all the attributes for the given key
|
||||
* @param key - the key from which the attributes will be retrieved
|
||||
* @return object containing the key's attributes
|
||||
*/
|
||||
|
||||
function getKeyAttributes(key) {
|
||||
if (typeof key === 'string') {
|
||||
return defaultKeyAttributes;
|
||||
}
|
||||
|
||||
return _extends$1({}, defaultKeyAttributes, key);
|
||||
}
|
||||
|
||||
var getItem = function getItem(key) {
|
||||
try {
|
||||
var itemValue = localStorage.getItem(key);
|
||||
|
||||
if (typeof itemValue === 'string') {
|
||||
return JSON.parse(itemValue);
|
||||
}
|
||||
|
||||
return undefined;
|
||||
} catch (_unused) {
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
|
||||
function useLocalStorage(key, defaultValue) {
|
||||
var _React$useState = React__default.useState(),
|
||||
value = _React$useState[0],
|
||||
setValue = _React$useState[1];
|
||||
|
||||
React__default.useEffect(function () {
|
||||
var initialValue = getItem(key);
|
||||
|
||||
if (typeof initialValue === 'undefined' || initialValue === null) {
|
||||
setValue(typeof defaultValue === 'function' ? defaultValue() : defaultValue);
|
||||
} else {
|
||||
setValue(initialValue);
|
||||
}
|
||||
}, [defaultValue, key]);
|
||||
var setter = React__default.useCallback(function (updater) {
|
||||
setValue(function (old) {
|
||||
var newVal = updater;
|
||||
|
||||
if (typeof updater == 'function') {
|
||||
newVal = updater(old);
|
||||
}
|
||||
|
||||
try {
|
||||
localStorage.setItem(key, JSON.stringify(newVal));
|
||||
} catch (_unused2) {}
|
||||
|
||||
return newVal;
|
||||
});
|
||||
}, [key]);
|
||||
return [value, setter];
|
||||
}
|
||||
|
||||
var defaultTheme = {
|
||||
background: '#0b1521',
|
||||
backgroundAlt: '#132337',
|
||||
foreground: 'white',
|
||||
gray: '#3f4e60',
|
||||
grayAlt: '#222e3e',
|
||||
inputBackgroundColor: '#fff',
|
||||
inputTextColor: '#000',
|
||||
success: '#00ab52',
|
||||
danger: '#ff0085',
|
||||
active: '#006bff',
|
||||
warning: '#ffb200'
|
||||
};
|
||||
var ThemeContext = /*#__PURE__*/React__default.createContext(defaultTheme);
|
||||
function ThemeProvider(_ref) {
|
||||
var theme = _ref.theme,
|
||||
rest = _objectWithoutPropertiesLoose(_ref, ["theme"]);
|
||||
|
||||
return /*#__PURE__*/React__default.createElement(ThemeContext.Provider, _extends({
|
||||
value: theme
|
||||
}, rest));
|
||||
}
|
||||
function useTheme() {
|
||||
return React__default.useContext(ThemeContext);
|
||||
}
|
||||
|
||||
function useMediaQuery(query) {
|
||||
// Keep track of the preference in state, start with the current match
|
||||
var _React$useState = React__default.useState(function () {
|
||||
if (typeof window !== 'undefined') {
|
||||
return window.matchMedia && window.matchMedia(query).matches;
|
||||
}
|
||||
}),
|
||||
isMatch = _React$useState[0],
|
||||
setIsMatch = _React$useState[1]; // Watch for changes
|
||||
|
||||
|
||||
React__default.useEffect(function () {
|
||||
if (typeof window !== 'undefined') {
|
||||
if (!window.matchMedia) {
|
||||
return;
|
||||
} // Create a matcher
|
||||
|
||||
|
||||
var matcher = window.matchMedia(query); // Create our handler
|
||||
|
||||
var onChange = function onChange(_ref) {
|
||||
var matches = _ref.matches;
|
||||
return setIsMatch(matches);
|
||||
}; // Listen for changes
|
||||
|
||||
|
||||
matcher.addListener(onChange);
|
||||
return function () {
|
||||
// Stop listening for changes
|
||||
matcher.removeListener(onChange);
|
||||
};
|
||||
}
|
||||
}, [isMatch, query, setIsMatch]);
|
||||
return isMatch;
|
||||
}
|
||||
|
||||
var isServer = typeof window === 'undefined';
|
||||
function getQueryStatusColor(query, theme) {
|
||||
return query.state.isFetching ? theme.active : !query.getObserversCount() ? theme.gray : query.isStale() ? theme.warning : theme.success;
|
||||
}
|
||||
function getQueryStatusLabel(query) {
|
||||
return query.state.isFetching ? 'fetching' : !query.getObserversCount() ? 'inactive' : query.isStale() ? 'stale' : 'fresh';
|
||||
}
|
||||
function styled(type, newStyles, queries) {
|
||||
if (queries === void 0) {
|
||||
queries = {};
|
||||
}
|
||||
|
||||
return /*#__PURE__*/React__default.forwardRef(function (_ref, ref) {
|
||||
var style = _ref.style,
|
||||
rest = _objectWithoutPropertiesLoose(_ref, ["style"]);
|
||||
|
||||
var theme = useTheme();
|
||||
var mediaStyles = Object.entries(queries).reduce(function (current, _ref2) {
|
||||
var key = _ref2[0],
|
||||
value = _ref2[1];
|
||||
// eslint-disable-next-line react-hooks/rules-of-hooks
|
||||
return useMediaQuery(key) ? _extends({}, current, typeof value === 'function' ? value(rest, theme) : value) : current;
|
||||
}, {});
|
||||
return /*#__PURE__*/React__default.createElement(type, _extends({}, rest, {
|
||||
style: _extends({}, typeof newStyles === 'function' ? newStyles(rest, theme) : newStyles, style, mediaStyles),
|
||||
ref: ref
|
||||
}));
|
||||
});
|
||||
}
|
||||
function useIsMounted() {
|
||||
var mountedRef = React__default.useRef(false);
|
||||
var isMounted = React__default.useCallback(function () {
|
||||
return mountedRef.current;
|
||||
}, []);
|
||||
React__default[isServer ? 'useEffect' : 'useLayoutEffect'](function () {
|
||||
mountedRef.current = true;
|
||||
return function () {
|
||||
mountedRef.current = false;
|
||||
};
|
||||
}, []);
|
||||
return isMounted;
|
||||
}
|
||||
/**
|
||||
* This hook is a safe useState version which schedules state updates in microtasks
|
||||
* to prevent updating a component state while React is rendering different components
|
||||
* or when the component is not mounted anymore.
|
||||
*/
|
||||
|
||||
function useSafeState(initialState) {
|
||||
var isMounted = useIsMounted();
|
||||
|
||||
var _React$useState = React__default.useState(initialState),
|
||||
state = _React$useState[0],
|
||||
setState = _React$useState[1];
|
||||
|
||||
var safeSetState = React__default.useCallback(function (value) {
|
||||
scheduleMicrotask(function () {
|
||||
if (isMounted()) {
|
||||
setState(value);
|
||||
}
|
||||
});
|
||||
}, [isMounted]);
|
||||
return [state, safeSetState];
|
||||
}
|
||||
/**
|
||||
* Displays a string regardless the type of the data
|
||||
* @param {unknown} value Value to be stringified
|
||||
*/
|
||||
|
||||
var displayValue = function displayValue(value) {
|
||||
var name = Object.getOwnPropertyNames(Object(value));
|
||||
var newValue = typeof value === 'bigint' ? value.toString() + "n" : value;
|
||||
return JSON.stringify(newValue, name);
|
||||
};
|
||||
/**
|
||||
* Schedules a microtask.
|
||||
* This can be useful to schedule state updates after rendering.
|
||||
*/
|
||||
|
||||
function scheduleMicrotask(callback) {
|
||||
Promise.resolve().then(callback).catch(function (error) {
|
||||
return setTimeout(function () {
|
||||
throw error;
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
var Panel = styled('div', function (_props, theme) {
|
||||
return {
|
||||
fontSize: 'clamp(12px, 1.5vw, 14px)',
|
||||
fontFamily: "sans-serif",
|
||||
display: 'flex',
|
||||
backgroundColor: theme.background,
|
||||
color: theme.foreground
|
||||
};
|
||||
}, {
|
||||
'(max-width: 700px)': {
|
||||
flexDirection: 'column'
|
||||
},
|
||||
'(max-width: 600px)': {
|
||||
fontSize: '.9em' // flexDirection: 'column',
|
||||
|
||||
}
|
||||
});
|
||||
var ActiveQueryPanel = styled('div', function () {
|
||||
return {
|
||||
flex: '1 1 500px',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
overflow: 'auto',
|
||||
height: '100%'
|
||||
};
|
||||
}, {
|
||||
'(max-width: 700px)': function maxWidth700px(_props, theme) {
|
||||
return {
|
||||
borderTop: "2px solid " + theme.gray
|
||||
};
|
||||
}
|
||||
});
|
||||
var Button = styled('button', function (props, theme) {
|
||||
return {
|
||||
appearance: 'none',
|
||||
fontSize: '.9em',
|
||||
fontWeight: 'bold',
|
||||
background: theme.gray,
|
||||
border: '0',
|
||||
borderRadius: '.3em',
|
||||
color: 'white',
|
||||
padding: '.5em',
|
||||
opacity: props.disabled ? '.5' : undefined,
|
||||
cursor: 'pointer'
|
||||
};
|
||||
});
|
||||
var QueryKeys = styled('span', {
|
||||
display: 'inline-block',
|
||||
fontSize: '0.9em'
|
||||
});
|
||||
var QueryKey = styled('span', {
|
||||
display: 'inline-flex',
|
||||
alignItems: 'center',
|
||||
padding: '.2em .4em',
|
||||
fontWeight: 'bold',
|
||||
textShadow: '0 0 10px black',
|
||||
borderRadius: '.2em'
|
||||
});
|
||||
var Code = styled('code', {
|
||||
fontSize: '.9em',
|
||||
color: 'inherit',
|
||||
background: 'inherit'
|
||||
});
|
||||
var Input = styled('input', function (_props, theme) {
|
||||
return {
|
||||
backgroundColor: theme.inputBackgroundColor,
|
||||
border: 0,
|
||||
borderRadius: '.2em',
|
||||
color: theme.inputTextColor,
|
||||
fontSize: '.9em',
|
||||
lineHeight: "1.3",
|
||||
padding: '.3em .4em'
|
||||
};
|
||||
});
|
||||
var Select = styled('select', function (_props, theme) {
|
||||
return {
|
||||
display: "inline-block",
|
||||
fontSize: ".9em",
|
||||
fontFamily: "sans-serif",
|
||||
fontWeight: 'normal',
|
||||
lineHeight: "1.3",
|
||||
padding: ".3em 1.5em .3em .5em",
|
||||
height: 'auto',
|
||||
border: 0,
|
||||
borderRadius: ".2em",
|
||||
appearance: "none",
|
||||
WebkitAppearance: 'none',
|
||||
backgroundColor: theme.inputBackgroundColor,
|
||||
backgroundImage: "url(\"data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='100' height='100' fill='%23444444'><polygon points='0,25 100,25 50,75'/></svg>\")",
|
||||
backgroundRepeat: "no-repeat",
|
||||
backgroundPosition: "right .55em center",
|
||||
backgroundSize: ".65em auto, 100%",
|
||||
color: theme.inputTextColor
|
||||
};
|
||||
}, {
|
||||
'(max-width: 500px)': {
|
||||
display: 'none'
|
||||
}
|
||||
});
|
||||
|
||||
var Entry = styled('div', {
|
||||
fontFamily: 'Menlo, monospace',
|
||||
fontSize: '1em',
|
||||
lineHeight: '1.7',
|
||||
outline: 'none',
|
||||
wordBreak: 'break-word'
|
||||
});
|
||||
var Label = styled('span', {
|
||||
color: 'white'
|
||||
});
|
||||
var LabelButton = styled('button', {
|
||||
cursor: 'pointer',
|
||||
color: 'white'
|
||||
});
|
||||
var ExpandButton = styled('button', {
|
||||
cursor: 'pointer',
|
||||
color: 'inherit',
|
||||
font: 'inherit',
|
||||
outline: 'inherit',
|
||||
background: 'transparent',
|
||||
border: 'none',
|
||||
padding: 0
|
||||
});
|
||||
var Value = styled('span', function (_props, theme) {
|
||||
return {
|
||||
color: theme.danger
|
||||
};
|
||||
});
|
||||
var SubEntries = styled('div', {
|
||||
marginLeft: '.1em',
|
||||
paddingLeft: '1em',
|
||||
borderLeft: '2px solid rgba(0,0,0,.15)'
|
||||
});
|
||||
var Info = styled('span', {
|
||||
color: 'grey',
|
||||
fontSize: '.7em'
|
||||
});
|
||||
var Expander = function Expander(_ref) {
|
||||
var expanded = _ref.expanded,
|
||||
_ref$style = _ref.style,
|
||||
style = _ref$style === void 0 ? {} : _ref$style;
|
||||
return /*#__PURE__*/React__default.createElement("span", {
|
||||
style: _extends({
|
||||
display: 'inline-block',
|
||||
transition: 'all .1s ease',
|
||||
transform: "rotate(" + (expanded ? 90 : 0) + "deg) " + (style.transform || '')
|
||||
}, style)
|
||||
}, "\u25B6");
|
||||
};
|
||||
|
||||
/**
|
||||
* Chunk elements in the array by size
|
||||
*
|
||||
* when the array cannot be chunked evenly by size, the last chunk will be
|
||||
* filled with the remaining elements
|
||||
*
|
||||
* @example
|
||||
* chunkArray(['a','b', 'c', 'd', 'e'], 2) // returns [['a','b'], ['c', 'd'], ['e']]
|
||||
*/
|
||||
function chunkArray(array, size) {
|
||||
if (size < 1) return [];
|
||||
var i = 0;
|
||||
var result = [];
|
||||
|
||||
while (i < array.length) {
|
||||
result.push(array.slice(i, i + size));
|
||||
i = i + size;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
var DefaultRenderer = function DefaultRenderer(_ref2) {
|
||||
var HandleEntry = _ref2.HandleEntry,
|
||||
label = _ref2.label,
|
||||
value = _ref2.value,
|
||||
_ref2$subEntries = _ref2.subEntries,
|
||||
subEntries = _ref2$subEntries === void 0 ? [] : _ref2$subEntries,
|
||||
_ref2$subEntryPages = _ref2.subEntryPages,
|
||||
subEntryPages = _ref2$subEntryPages === void 0 ? [] : _ref2$subEntryPages,
|
||||
type = _ref2.type,
|
||||
_ref2$expanded = _ref2.expanded,
|
||||
expanded = _ref2$expanded === void 0 ? false : _ref2$expanded,
|
||||
toggleExpanded = _ref2.toggleExpanded,
|
||||
pageSize = _ref2.pageSize;
|
||||
|
||||
var _React$useState = React__default.useState([]),
|
||||
expandedPages = _React$useState[0],
|
||||
setExpandedPages = _React$useState[1];
|
||||
|
||||
return /*#__PURE__*/React__default.createElement(Entry, {
|
||||
key: label
|
||||
}, (subEntryPages == null ? void 0 : subEntryPages.length) ? /*#__PURE__*/React__default.createElement(React__default.Fragment, null, /*#__PURE__*/React__default.createElement(ExpandButton, {
|
||||
onClick: function onClick() {
|
||||
return toggleExpanded();
|
||||
}
|
||||
}, /*#__PURE__*/React__default.createElement(Expander, {
|
||||
expanded: expanded
|
||||
}), " ", label, ' ', /*#__PURE__*/React__default.createElement(Info, null, String(type).toLowerCase() === 'iterable' ? '(Iterable) ' : '', subEntries.length, " ", subEntries.length > 1 ? "items" : "item")), expanded ? subEntryPages.length === 1 ? /*#__PURE__*/React__default.createElement(SubEntries, null, subEntries.map(function (entry) {
|
||||
return /*#__PURE__*/React__default.createElement(HandleEntry, {
|
||||
key: entry.label,
|
||||
entry: entry
|
||||
});
|
||||
})) : /*#__PURE__*/React__default.createElement(SubEntries, null, subEntryPages.map(function (entries, index) {
|
||||
return /*#__PURE__*/React__default.createElement("div", {
|
||||
key: index
|
||||
}, /*#__PURE__*/React__default.createElement(Entry, null, /*#__PURE__*/React__default.createElement(LabelButton, {
|
||||
onClick: function onClick() {
|
||||
return setExpandedPages(function (old) {
|
||||
return old.includes(index) ? old.filter(function (d) {
|
||||
return d !== index;
|
||||
}) : [].concat(old, [index]);
|
||||
});
|
||||
}
|
||||
}, /*#__PURE__*/React__default.createElement(Expander, {
|
||||
expanded: expanded
|
||||
}), " [", index * pageSize, " ...", ' ', index * pageSize + pageSize - 1, "]"), expandedPages.includes(index) ? /*#__PURE__*/React__default.createElement(SubEntries, null, entries.map(function (entry) {
|
||||
return /*#__PURE__*/React__default.createElement(HandleEntry, {
|
||||
key: entry.label,
|
||||
entry: entry
|
||||
});
|
||||
})) : null));
|
||||
})) : null) : /*#__PURE__*/React__default.createElement(React__default.Fragment, null, /*#__PURE__*/React__default.createElement(Label, null, label, ":"), " ", /*#__PURE__*/React__default.createElement(Value, null, displayValue(value))));
|
||||
};
|
||||
|
||||
function isIterable(x) {
|
||||
return Symbol.iterator in x;
|
||||
}
|
||||
|
||||
function Explorer(_ref3) {
|
||||
var value = _ref3.value,
|
||||
defaultExpanded = _ref3.defaultExpanded,
|
||||
_ref3$renderer = _ref3.renderer,
|
||||
renderer = _ref3$renderer === void 0 ? DefaultRenderer : _ref3$renderer,
|
||||
_ref3$pageSize = _ref3.pageSize,
|
||||
pageSize = _ref3$pageSize === void 0 ? 100 : _ref3$pageSize,
|
||||
rest = _objectWithoutPropertiesLoose(_ref3, ["value", "defaultExpanded", "renderer", "pageSize"]);
|
||||
|
||||
var _React$useState2 = React__default.useState(Boolean(defaultExpanded)),
|
||||
expanded = _React$useState2[0],
|
||||
setExpanded = _React$useState2[1];
|
||||
|
||||
var toggleExpanded = React__default.useCallback(function () {
|
||||
return setExpanded(function (old) {
|
||||
return !old;
|
||||
});
|
||||
}, []);
|
||||
var type = typeof value;
|
||||
var subEntries = [];
|
||||
|
||||
var makeProperty = function makeProperty(sub) {
|
||||
var _ref4;
|
||||
|
||||
var subDefaultExpanded = defaultExpanded === true ? (_ref4 = {}, _ref4[sub.label] = true, _ref4) : defaultExpanded == null ? void 0 : defaultExpanded[sub.label];
|
||||
return _extends({}, sub, {
|
||||
defaultExpanded: subDefaultExpanded
|
||||
});
|
||||
};
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
type = 'array';
|
||||
subEntries = value.map(function (d, i) {
|
||||
return makeProperty({
|
||||
label: i.toString(),
|
||||
value: d
|
||||
});
|
||||
});
|
||||
} else if (value !== null && typeof value === 'object' && isIterable(value) && typeof value[Symbol.iterator] === 'function') {
|
||||
type = 'Iterable';
|
||||
subEntries = Array.from(value, function (val, i) {
|
||||
return makeProperty({
|
||||
label: i.toString(),
|
||||
value: val
|
||||
});
|
||||
});
|
||||
} else if (typeof value === 'object' && value !== null) {
|
||||
type = 'object';
|
||||
subEntries = Object.entries(value).map(function (_ref5) {
|
||||
var key = _ref5[0],
|
||||
val = _ref5[1];
|
||||
return makeProperty({
|
||||
label: key,
|
||||
value: val
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
var subEntryPages = chunkArray(subEntries, pageSize);
|
||||
return renderer(_extends({
|
||||
HandleEntry: function HandleEntry(_ref6) {
|
||||
var entry = _ref6.entry;
|
||||
return /*#__PURE__*/React__default.createElement(Explorer, _extends({
|
||||
value: value,
|
||||
renderer: renderer
|
||||
}, rest, entry));
|
||||
},
|
||||
type: type,
|
||||
subEntries: subEntries,
|
||||
subEntryPages: subEntryPages,
|
||||
value: value,
|
||||
expanded: expanded,
|
||||
toggleExpanded: toggleExpanded,
|
||||
pageSize: pageSize
|
||||
}, rest));
|
||||
}
|
||||
|
||||
function Logo(props) {
|
||||
return /*#__PURE__*/React.createElement("svg", _extends({
|
||||
width: "40px",
|
||||
height: "40px",
|
||||
viewBox: "0 0 190 190",
|
||||
version: "1.1"
|
||||
}, props), /*#__PURE__*/React.createElement("g", {
|
||||
stroke: "none",
|
||||
strokeWidth: "1",
|
||||
fill: "none",
|
||||
fillRule: "evenodd"
|
||||
}, /*#__PURE__*/React.createElement("g", {
|
||||
transform: "translate(-33.000000, 0.000000)"
|
||||
}, /*#__PURE__*/React.createElement("path", {
|
||||
d: "M72.7239712,61.3436237 C69.631224,46.362877 68.9675112,34.8727722 70.9666331,26.5293551 C72.1555965,21.5671678 74.3293088,17.5190846 77.6346064,14.5984631 C81.1241394,11.5150478 85.5360327,10.0020122 90.493257,10.0020122 C98.6712013,10.0020122 107.26826,13.7273214 116.455725,20.8044264 C120.20312,23.6910458 124.092437,27.170411 128.131651,31.2444746 C128.45314,30.8310265 128.816542,30.4410453 129.22143,30.0806152 C140.64098,19.9149716 150.255245,13.5989272 158.478408,11.1636507 C163.367899,9.715636 167.958526,9.57768202 172.138936,10.983031 C176.551631,12.4664684 180.06766,15.5329489 182.548314,19.8281091 C186.642288,26.9166735 187.721918,36.2310983 186.195595,47.7320243 C185.573451,52.4199112 184.50985,57.5263831 183.007094,63.0593153 C183.574045,63.1277086 184.142416,63.2532808 184.705041,63.4395297 C199.193932,68.2358678 209.453582,73.3937462 215.665021,79.2882839 C219.360669,82.7953831 221.773972,86.6998434 222.646365,91.0218204 C223.567176,95.5836746 222.669313,100.159332 220.191548,104.451297 C216.105211,111.529614 208.591643,117.11221 197.887587,121.534031 C193.589552,123.309539 188.726579,124.917559 183.293259,126.363748 C183.541176,126.92292 183.733521,127.516759 183.862138,128.139758 C186.954886,143.120505 187.618598,154.61061 185.619477,162.954027 C184.430513,167.916214 182.256801,171.964297 178.951503,174.884919 C175.46197,177.968334 171.050077,179.48137 166.092853,179.48137 C157.914908,179.48137 149.31785,175.756061 140.130385,168.678956 C136.343104,165.761613 132.410866,162.238839 128.325434,158.108619 C127.905075,158.765474 127.388968,159.376011 126.77857,159.919385 C115.35902,170.085028 105.744755,176.401073 97.5215915,178.836349 C92.6321009,180.284364 88.0414736,180.422318 83.8610636,179.016969 C79.4483686,177.533532 75.9323404,174.467051 73.4516862,170.171891 C69.3577116,163.083327 68.2780823,153.768902 69.8044053,142.267976 C70.449038,137.410634 71.56762,132.103898 73.1575891,126.339009 C72.5361041,126.276104 71.9120754,126.144816 71.2949591,125.940529 C56.8060684,121.144191 46.5464184,115.986312 40.3349789,110.091775 C36.6393312,106.584675 34.2260275,102.680215 33.3536352,98.3582381 C32.4328237,93.7963839 33.3306866,89.2207269 35.8084524,84.9287618 C39.8947886,77.8504443 47.4083565,72.2678481 58.1124133,67.8460273 C62.5385143,66.0176154 67.5637208,64.366822 73.1939394,62.8874674 C72.9933393,62.3969171 72.8349374,61.8811235 72.7239712,61.3436237 Z",
|
||||
fill: "#002C4B",
|
||||
fillRule: "nonzero",
|
||||
transform: "translate(128.000000, 95.000000) scale(-1, 1) translate(-128.000000, -95.000000) "
|
||||
}), /*#__PURE__*/React.createElement("path", {
|
||||
d: "M113.396882,64 L142.608177,64 C144.399254,64 146.053521,64.958025 146.944933,66.5115174 L161.577138,92.0115174 C162.461464,93.5526583 162.461464,95.4473417 161.577138,96.9884826 L146.944933,122.488483 C146.053521,124.041975 144.399254,125 142.608177,125 L113.396882,125 C111.605806,125 109.951539,124.041975 109.060126,122.488483 L94.4279211,96.9884826 C93.543596,95.4473417 93.543596,93.5526583 94.4279211,92.0115174 L109.060126,66.5115174 C109.951539,64.958025 111.605806,64 113.396882,64 Z M138.987827,70.2765273 C140.779849,70.2765273 142.434839,71.2355558 143.325899,72.7903404 L154.343038,92.0138131 C155.225607,93.5537825 155.225607,95.4462175 154.343038,96.9861869 L143.325899,116.20966 C142.434839,117.764444 140.779849,118.723473 138.987827,118.723473 L117.017233,118.723473 C115.225211,118.723473 113.570221,117.764444 112.67916,116.20966 L101.662022,96.9861869 C100.779452,95.4462175 100.779452,93.5537825 101.662022,92.0138131 L112.67916,72.7903404 C113.570221,71.2355558 115.225211,70.2765273 117.017233,70.2765273 L138.987827,70.2765273 Z M135.080648,77.1414791 L120.924411,77.1414791 C119.134228,77.1414791 117.480644,78.0985567 116.5889,79.6508285 L116.5889,79.6508285 L109.489217,92.0093494 C108.603232,93.5515958 108.603232,95.4484042 109.489217,96.9906506 L109.489217,96.9906506 L116.5889,109.349172 C117.480644,110.901443 119.134228,111.858521 120.924411,111.858521 L120.924411,111.858521 L135.080648,111.858521 C136.870831,111.858521 138.524416,110.901443 139.41616,109.349172 L139.41616,109.349172 L146.515843,96.9906506 C147.401828,95.4484042 147.401828,93.5515958 146.515843,92.0093494 L146.515843,92.0093494 L139.41616,79.6508285 C138.524416,78.0985567 136.870831,77.1414791 135.080648,77.1414791 L135.080648,77.1414791 Z M131.319186,83.7122186 C133.108028,83.7122186 134.760587,84.6678753 135.652827,86.2183156 L138.983552,92.0060969 C139.87203,93.5500005 139.87203,95.4499995 138.983552,96.9939031 L135.652827,102.781684 C134.760587,104.332125 133.108028,105.287781 131.319186,105.287781 L124.685874,105.287781 C122.897032,105.287781 121.244473,104.332125 120.352233,102.781684 L117.021508,96.9939031 C116.13303,95.4499995 116.13303,93.5500005 117.021508,92.0060969 L120.352233,86.2183156 C121.244473,84.6678753 122.897032,83.7122186 124.685874,83.7122186 L131.319186,83.7122186 Z M128.003794,90.1848875 C126.459294,90.1848875 125.034382,91.0072828 124.263005,92.3424437 C123.491732,93.6774232 123.491732,95.3225768 124.263005,96.6575563 C125.034382,97.9927172 126.459294,98.8151125 128.001266,98.8151125 L128.001266,98.8151125 C129.545766,98.8151125 130.970678,97.9927172 131.742055,96.6575563 C132.513327,95.3225768 132.513327,93.6774232 131.742055,92.3424437 C130.970678,91.0072828 129.545766,90.1848875 128.003794,90.1848875 L128.003794,90.1848875 Z M93,94.5009646 L100.767764,94.5009646",
|
||||
fill: "#FFD94C"
|
||||
}), /*#__PURE__*/React.createElement("path", {
|
||||
d: "M87.8601729,108.357758 C89.1715224,107.608286 90.8360246,108.074601 91.5779424,109.399303 L91.5779424,109.399303 L92.0525843,110.24352 C95.8563392,116.982993 99.8190116,123.380176 103.940602,129.435068 C108.807881,136.585427 114.28184,143.82411 120.362479,151.151115 C121.316878,152.30114 121.184944,154.011176 120.065686,154.997937 L120.065686,154.997937 L119.454208,155.534625 C99.3465389,173.103314 86.2778188,176.612552 80.2480482,166.062341 C74.3500652,155.742717 76.4844915,136.982888 86.6513274,109.782853 C86.876818,109.179582 87.3045861,108.675291 87.8601729,108.357758 Z M173.534177,129.041504 C174.986131,128.785177 176.375496,129.742138 176.65963,131.194242 L176.65963,131.194242 L176.812815,131.986376 C181.782365,157.995459 178.283348,171 166.315764,171 C154.609745,171 139.708724,159.909007 121.612702,137.727022 C121.211349,137.235047 120.994572,136.617371 121,135.981509 C121.013158,134.480686 122.235785,133.274651 123.730918,133.287756 L123.730918,133.287756 L124.684654,133.294531 C132.305698,133.335994 139.714387,133.071591 146.910723,132.501323 C155.409039,131.82788 164.283523,130.674607 173.534177,129.041504 Z M180.408726,73.8119663 C180.932139,72.4026903 182.508386,71.6634537 183.954581,72.149012 L183.954581,72.149012 L184.742552,72.4154854 C210.583763,81.217922 220.402356,90.8916805 214.198332,101.436761 C208.129904,111.751366 190.484347,119.260339 161.26166,123.963678 C160.613529,124.067994 159.948643,123.945969 159.382735,123.618843 C158.047025,122.846729 157.602046,121.158214 158.388848,119.847438 L158.388848,119.847438 L158.889328,119.0105 C162.877183,112.31633 166.481358,105.654262 169.701854,99.0242957 C173.50501,91.1948179 177.073967,82.7907081 180.408726,73.8119663 Z M94.7383398,66.0363218 C95.3864708,65.9320063 96.0513565,66.0540315 96.6172646,66.3811573 C97.9529754,67.153271 98.3979538,68.8417862 97.6111517,70.1525615 L97.6111517,70.1525615 L97.1106718,70.9895001 C93.1228168,77.6836699 89.5186416,84.3457379 86.2981462,90.9757043 C82.49499,98.8051821 78.9260328,107.209292 75.5912744,116.188034 C75.0678608,117.59731 73.4916142,118.336546 72.045419,117.850988 L72.045419,117.850988 L71.2574475,117.584515 C45.4162372,108.782078 35.597644,99.1083195 41.8016679,88.5632391 C47.8700957,78.2486335 65.515653,70.7396611 94.7383398,66.0363218 Z M136.545792,34.4653746 C156.653461,16.8966864 169.722181,13.3874478 175.751952,23.9376587 C181.649935,34.2572826 179.515508,53.0171122 169.348673,80.2171474 C169.123182,80.8204179 168.695414,81.324709 168.139827,81.6422422 C166.828478,82.3917144 165.163975,81.9253986 164.422058,80.6006966 L164.422058,80.6006966 L163.947416,79.7564798 C160.143661,73.0170065 156.180988,66.6198239 152.059398,60.564932 C147.192119,53.4145727 141.71816,46.1758903 135.637521,38.8488847 C134.683122,37.6988602 134.815056,35.9888243 135.934314,35.0020629 L135.934314,35.0020629 Z M90.6842361,18 C102.390255,18 117.291276,29.0909926 135.387298,51.2729777 C135.788651,51.7649527 136.005428,52.3826288 136,53.0184911 C135.986842,54.5193144 134.764215,55.7253489 133.269082,55.7122445 L133.269082,55.7122445 L132.315346,55.7054689 C124.694302,55.6640063 117.285613,55.9284091 110.089277,56.4986773 C101.590961,57.17212 92.7164767,58.325393 83.4658235,59.9584962 C82.0138691,60.2148231 80.6245044,59.2578618 80.3403697,57.805758 L80.3403697,57.805758 L80.1871846,57.0136235 C75.2176347,31.0045412 78.7166519,18 90.6842361,18 Z",
|
||||
fill: "#FF4154"
|
||||
}))));
|
||||
}
|
||||
|
||||
function noop() {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
var isServer$1 = typeof window === 'undefined';
|
||||
function ReactQueryDevtools(_ref) {
|
||||
var initialIsOpen = _ref.initialIsOpen,
|
||||
_ref$panelProps = _ref.panelProps,
|
||||
panelProps = _ref$panelProps === void 0 ? {} : _ref$panelProps,
|
||||
_ref$closeButtonProps = _ref.closeButtonProps,
|
||||
closeButtonProps = _ref$closeButtonProps === void 0 ? {} : _ref$closeButtonProps,
|
||||
_ref$toggleButtonProp = _ref.toggleButtonProps,
|
||||
toggleButtonProps = _ref$toggleButtonProp === void 0 ? {} : _ref$toggleButtonProp,
|
||||
_ref$position = _ref.position,
|
||||
position = _ref$position === void 0 ? 'bottom-left' : _ref$position,
|
||||
_ref$containerElement = _ref.containerElement,
|
||||
Container = _ref$containerElement === void 0 ? 'aside' : _ref$containerElement,
|
||||
styleNonce = _ref.styleNonce;
|
||||
var rootRef = React__default.useRef(null);
|
||||
var panelRef = React__default.useRef(null);
|
||||
|
||||
var _useLocalStorage = useLocalStorage('reactQueryDevtoolsOpen', initialIsOpen),
|
||||
isOpen = _useLocalStorage[0],
|
||||
setIsOpen = _useLocalStorage[1];
|
||||
|
||||
var _useLocalStorage2 = useLocalStorage('reactQueryDevtoolsHeight', null),
|
||||
devtoolsHeight = _useLocalStorage2[0],
|
||||
setDevtoolsHeight = _useLocalStorage2[1];
|
||||
|
||||
var _useSafeState = useSafeState(false),
|
||||
isResolvedOpen = _useSafeState[0],
|
||||
setIsResolvedOpen = _useSafeState[1];
|
||||
|
||||
var _useSafeState2 = useSafeState(false),
|
||||
isResizing = _useSafeState2[0],
|
||||
setIsResizing = _useSafeState2[1];
|
||||
|
||||
var isMounted = useIsMounted();
|
||||
|
||||
var _handleDragStart = function handleDragStart(panelElement, startEvent) {
|
||||
var _panelElement$getBoun;
|
||||
|
||||
if (startEvent.button !== 0) return; // Only allow left click for drag
|
||||
|
||||
setIsResizing(true);
|
||||
var dragInfo = {
|
||||
originalHeight: (_panelElement$getBoun = panelElement == null ? void 0 : panelElement.getBoundingClientRect().height) != null ? _panelElement$getBoun : 0,
|
||||
pageY: startEvent.pageY
|
||||
};
|
||||
|
||||
var run = function run(moveEvent) {
|
||||
var delta = dragInfo.pageY - moveEvent.pageY;
|
||||
var newHeight = (dragInfo == null ? void 0 : dragInfo.originalHeight) + delta;
|
||||
setDevtoolsHeight(newHeight);
|
||||
|
||||
if (newHeight < 70) {
|
||||
setIsOpen(false);
|
||||
} else {
|
||||
setIsOpen(true);
|
||||
}
|
||||
};
|
||||
|
||||
var unsub = function unsub() {
|
||||
setIsResizing(false);
|
||||
document.removeEventListener('mousemove', run);
|
||||
document.removeEventListener('mouseUp', unsub);
|
||||
};
|
||||
|
||||
document.addEventListener('mousemove', run);
|
||||
document.addEventListener('mouseup', unsub);
|
||||
};
|
||||
|
||||
React__default.useEffect(function () {
|
||||
setIsResolvedOpen(isOpen != null ? isOpen : false);
|
||||
}, [isOpen, isResolvedOpen, setIsResolvedOpen]); // Toggle panel visibility before/after transition (depending on direction).
|
||||
// Prevents focusing in a closed panel.
|
||||
|
||||
React__default.useEffect(function () {
|
||||
var ref = panelRef.current;
|
||||
|
||||
if (ref) {
|
||||
var handlePanelTransitionStart = function handlePanelTransitionStart() {
|
||||
if (ref && isResolvedOpen) {
|
||||
ref.style.visibility = 'visible';
|
||||
}
|
||||
};
|
||||
|
||||
var handlePanelTransitionEnd = function handlePanelTransitionEnd() {
|
||||
if (ref && !isResolvedOpen) {
|
||||
ref.style.visibility = 'hidden';
|
||||
}
|
||||
};
|
||||
|
||||
ref.addEventListener('transitionstart', handlePanelTransitionStart);
|
||||
ref.addEventListener('transitionend', handlePanelTransitionEnd);
|
||||
return function () {
|
||||
ref.removeEventListener('transitionstart', handlePanelTransitionStart);
|
||||
ref.removeEventListener('transitionend', handlePanelTransitionEnd);
|
||||
};
|
||||
}
|
||||
}, [isResolvedOpen]);
|
||||
React__default[isServer$1 ? 'useEffect' : 'useLayoutEffect'](function () {
|
||||
if (isResolvedOpen) {
|
||||
var _rootRef$current, _rootRef$current$pare;
|
||||
|
||||
var previousValue = (_rootRef$current = rootRef.current) == null ? void 0 : (_rootRef$current$pare = _rootRef$current.parentElement) == null ? void 0 : _rootRef$current$pare.style.paddingBottom;
|
||||
|
||||
var run = function run() {
|
||||
var _panelRef$current, _rootRef$current2;
|
||||
|
||||
var containerHeight = (_panelRef$current = panelRef.current) == null ? void 0 : _panelRef$current.getBoundingClientRect().height;
|
||||
|
||||
if ((_rootRef$current2 = rootRef.current) == null ? void 0 : _rootRef$current2.parentElement) {
|
||||
rootRef.current.parentElement.style.paddingBottom = containerHeight + "px";
|
||||
}
|
||||
};
|
||||
|
||||
run();
|
||||
|
||||
if (typeof window !== 'undefined') {
|
||||
window.addEventListener('resize', run);
|
||||
return function () {
|
||||
var _rootRef$current3;
|
||||
|
||||
window.removeEventListener('resize', run);
|
||||
|
||||
if (((_rootRef$current3 = rootRef.current) == null ? void 0 : _rootRef$current3.parentElement) && typeof previousValue === 'string') {
|
||||
rootRef.current.parentElement.style.paddingBottom = previousValue;
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
}, [isResolvedOpen]);
|
||||
|
||||
var _panelProps$style = panelProps.style,
|
||||
panelStyle = _panelProps$style === void 0 ? {} : _panelProps$style,
|
||||
otherPanelProps = _objectWithoutPropertiesLoose(panelProps, ["style"]);
|
||||
|
||||
var _closeButtonProps$sty = closeButtonProps.style,
|
||||
closeButtonStyle = _closeButtonProps$sty === void 0 ? {} : _closeButtonProps$sty,
|
||||
onCloseClick = closeButtonProps.onClick,
|
||||
otherCloseButtonProps = _objectWithoutPropertiesLoose(closeButtonProps, ["style", "onClick"]);
|
||||
|
||||
var _toggleButtonProps$st = toggleButtonProps.style,
|
||||
toggleButtonStyle = _toggleButtonProps$st === void 0 ? {} : _toggleButtonProps$st,
|
||||
onToggleClick = toggleButtonProps.onClick,
|
||||
otherToggleButtonProps = _objectWithoutPropertiesLoose(toggleButtonProps, ["style", "onClick"]); // Do not render on the server
|
||||
|
||||
|
||||
if (!isMounted()) return null;
|
||||
return /*#__PURE__*/React__default.createElement(Container, {
|
||||
ref: rootRef,
|
||||
className: "ReactQueryDevtools",
|
||||
"aria-label": "React Query Devtools"
|
||||
}, /*#__PURE__*/React__default.createElement(ThemeProvider, {
|
||||
theme: defaultTheme
|
||||
}, /*#__PURE__*/React__default.createElement(ReactQueryDevtoolsPanel, _extends({
|
||||
ref: panelRef,
|
||||
styleNonce: styleNonce
|
||||
}, otherPanelProps, {
|
||||
style: _extends({
|
||||
position: 'fixed',
|
||||
bottom: '0',
|
||||
right: '0',
|
||||
zIndex: 99999,
|
||||
width: '100%',
|
||||
height: devtoolsHeight != null ? devtoolsHeight : 500,
|
||||
maxHeight: '90%',
|
||||
boxShadow: '0 0 20px rgba(0,0,0,.3)',
|
||||
borderTop: "1px solid " + defaultTheme.gray,
|
||||
transformOrigin: 'top',
|
||||
// visibility will be toggled after transitions, but set initial state here
|
||||
visibility: isOpen ? 'visible' : 'hidden'
|
||||
}, panelStyle, isResizing ? {
|
||||
transition: "none"
|
||||
} : {
|
||||
transition: "all .2s ease"
|
||||
}, isResolvedOpen ? {
|
||||
opacity: 1,
|
||||
pointerEvents: 'all',
|
||||
transform: "translateY(0) scale(1)"
|
||||
} : {
|
||||
opacity: 0,
|
||||
pointerEvents: 'none',
|
||||
transform: "translateY(15px) scale(1.02)"
|
||||
}),
|
||||
isOpen: isResolvedOpen,
|
||||
setIsOpen: setIsOpen,
|
||||
handleDragStart: function handleDragStart(e) {
|
||||
return _handleDragStart(panelRef.current, e);
|
||||
}
|
||||
})), isResolvedOpen ? /*#__PURE__*/React__default.createElement(Button, _extends({
|
||||
type: "button",
|
||||
"aria-controls": "ReactQueryDevtoolsPanel",
|
||||
"aria-haspopup": "true",
|
||||
"aria-expanded": "true"
|
||||
}, otherCloseButtonProps, {
|
||||
onClick: function onClick(e) {
|
||||
setIsOpen(false);
|
||||
onCloseClick && onCloseClick(e);
|
||||
},
|
||||
style: _extends({
|
||||
position: 'fixed',
|
||||
zIndex: 99999,
|
||||
margin: '.5em',
|
||||
bottom: 0
|
||||
}, position === 'top-right' ? {
|
||||
right: '0'
|
||||
} : position === 'top-left' ? {
|
||||
left: '0'
|
||||
} : position === 'bottom-right' ? {
|
||||
right: '0'
|
||||
} : {
|
||||
left: '0'
|
||||
}, closeButtonStyle)
|
||||
}), "Close") : null), !isResolvedOpen ? /*#__PURE__*/React__default.createElement("button", _extends({
|
||||
type: "button"
|
||||
}, otherToggleButtonProps, {
|
||||
"aria-label": "Open React Query Devtools",
|
||||
"aria-controls": "ReactQueryDevtoolsPanel",
|
||||
"aria-haspopup": "true",
|
||||
"aria-expanded": "false",
|
||||
onClick: function onClick(e) {
|
||||
setIsOpen(true);
|
||||
onToggleClick && onToggleClick(e);
|
||||
},
|
||||
style: _extends({
|
||||
background: 'none',
|
||||
border: 0,
|
||||
padding: 0,
|
||||
position: 'fixed',
|
||||
zIndex: 99999,
|
||||
display: 'inline-flex',
|
||||
fontSize: '1.5em',
|
||||
margin: '.5em',
|
||||
cursor: 'pointer',
|
||||
width: 'fit-content'
|
||||
}, position === 'top-right' ? {
|
||||
top: '0',
|
||||
right: '0'
|
||||
} : position === 'top-left' ? {
|
||||
top: '0',
|
||||
left: '0'
|
||||
} : position === 'bottom-right' ? {
|
||||
bottom: '0',
|
||||
right: '0'
|
||||
} : {
|
||||
bottom: '0',
|
||||
left: '0'
|
||||
}, toggleButtonStyle)
|
||||
}), /*#__PURE__*/React__default.createElement(Logo, {
|
||||
"aria-hidden": true
|
||||
})) : null);
|
||||
}
|
||||
|
||||
var getStatusRank = function getStatusRank(q) {
|
||||
return q.state.isFetching ? 0 : !q.getObserversCount() ? 3 : q.isStale() ? 2 : 1;
|
||||
};
|
||||
|
||||
var sortFns = {
|
||||
'Status > Last Updated': function StatusLastUpdated(a, b) {
|
||||
var _sortFns$LastUpdated;
|
||||
|
||||
return getStatusRank(a) === getStatusRank(b) ? (_sortFns$LastUpdated = sortFns['Last Updated']) == null ? void 0 : _sortFns$LastUpdated.call(sortFns, a, b) : getStatusRank(a) > getStatusRank(b) ? 1 : -1;
|
||||
},
|
||||
'Query Hash': function QueryHash(a, b) {
|
||||
return a.queryHash > b.queryHash ? 1 : -1;
|
||||
},
|
||||
'Last Updated': function LastUpdated(a, b) {
|
||||
return a.state.dataUpdatedAt < b.state.dataUpdatedAt ? 1 : -1;
|
||||
}
|
||||
};
|
||||
var ReactQueryDevtoolsPanel = /*#__PURE__*/React__default.forwardRef(function ReactQueryDevtoolsPanel(props, ref) {
|
||||
var _activeQuery$state;
|
||||
|
||||
var _props$isOpen = props.isOpen,
|
||||
isOpen = _props$isOpen === void 0 ? true : _props$isOpen,
|
||||
styleNonce = props.styleNonce,
|
||||
setIsOpen = props.setIsOpen,
|
||||
handleDragStart = props.handleDragStart,
|
||||
panelProps = _objectWithoutPropertiesLoose(props, ["isOpen", "styleNonce", "setIsOpen", "handleDragStart"]);
|
||||
|
||||
var queryClient = reactQuery.useQueryClient();
|
||||
var queryCache = queryClient.getQueryCache();
|
||||
|
||||
var _useLocalStorage3 = useLocalStorage('reactQueryDevtoolsSortFn', Object.keys(sortFns)[0]),
|
||||
sort = _useLocalStorage3[0],
|
||||
setSort = _useLocalStorage3[1];
|
||||
|
||||
var _useLocalStorage4 = useLocalStorage('reactQueryDevtoolsFilter', ''),
|
||||
filter = _useLocalStorage4[0],
|
||||
setFilter = _useLocalStorage4[1];
|
||||
|
||||
var _useLocalStorage5 = useLocalStorage('reactQueryDevtoolsSortDesc', false),
|
||||
sortDesc = _useLocalStorage5[0],
|
||||
setSortDesc = _useLocalStorage5[1];
|
||||
|
||||
var sortFn = React__default.useMemo(function () {
|
||||
return sortFns[sort];
|
||||
}, [sort]);
|
||||
React__default[isServer$1 ? 'useEffect' : 'useLayoutEffect'](function () {
|
||||
if (!sortFn) {
|
||||
setSort(Object.keys(sortFns)[0]);
|
||||
}
|
||||
}, [setSort, sortFn]);
|
||||
|
||||
var _useSafeState3 = useSafeState(Object.values(queryCache.findAll())),
|
||||
unsortedQueries = _useSafeState3[0],
|
||||
setUnsortedQueries = _useSafeState3[1];
|
||||
|
||||
var _useLocalStorage6 = useLocalStorage('reactQueryDevtoolsActiveQueryHash', ''),
|
||||
activeQueryHash = _useLocalStorage6[0],
|
||||
setActiveQueryHash = _useLocalStorage6[1];
|
||||
|
||||
var queries = React__default.useMemo(function () {
|
||||
var sorted = [].concat(unsortedQueries).sort(sortFn);
|
||||
|
||||
if (sortDesc) {
|
||||
sorted.reverse();
|
||||
}
|
||||
|
||||
if (!filter) {
|
||||
return sorted;
|
||||
}
|
||||
|
||||
return matchSorter(sorted, filter, {
|
||||
keys: ['queryHash']
|
||||
}).filter(function (d) {
|
||||
return d.queryHash;
|
||||
});
|
||||
}, [sortDesc, sortFn, unsortedQueries, filter]);
|
||||
var activeQuery = React__default.useMemo(function () {
|
||||
return queries.find(function (query) {
|
||||
return query.queryHash === activeQueryHash;
|
||||
});
|
||||
}, [activeQueryHash, queries]);
|
||||
var hasFresh = queries.filter(function (q) {
|
||||
return getQueryStatusLabel(q) === 'fresh';
|
||||
}).length;
|
||||
var hasFetching = queries.filter(function (q) {
|
||||
return getQueryStatusLabel(q) === 'fetching';
|
||||
}).length;
|
||||
var hasStale = queries.filter(function (q) {
|
||||
return getQueryStatusLabel(q) === 'stale';
|
||||
}).length;
|
||||
var hasInactive = queries.filter(function (q) {
|
||||
return getQueryStatusLabel(q) === 'inactive';
|
||||
}).length;
|
||||
React__default.useEffect(function () {
|
||||
if (isOpen) {
|
||||
var unsubscribe = queryCache.subscribe(function () {
|
||||
setUnsortedQueries(Object.values(queryCache.getAll()));
|
||||
}); // re-subscribing after the panel is closed and re-opened won't trigger the callback,
|
||||
// So we'll manually populate our state
|
||||
|
||||
setUnsortedQueries(Object.values(queryCache.getAll()));
|
||||
return unsubscribe;
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}, [isOpen, sort, sortFn, sortDesc, setUnsortedQueries, queryCache]);
|
||||
|
||||
var handleRefetch = function handleRefetch() {
|
||||
var promise = activeQuery == null ? void 0 : activeQuery.fetch();
|
||||
promise == null ? void 0 : promise.catch(noop);
|
||||
};
|
||||
|
||||
return /*#__PURE__*/React__default.createElement(ThemeProvider, {
|
||||
theme: defaultTheme
|
||||
}, /*#__PURE__*/React__default.createElement(Panel, _extends({
|
||||
ref: ref,
|
||||
className: "ReactQueryDevtoolsPanel",
|
||||
"aria-label": "React Query Devtools Panel",
|
||||
id: "ReactQueryDevtoolsPanel"
|
||||
}, panelProps), /*#__PURE__*/React__default.createElement("style", {
|
||||
nonce: styleNonce,
|
||||
dangerouslySetInnerHTML: {
|
||||
__html: "\n .ReactQueryDevtoolsPanel * {\n scrollbar-color: " + defaultTheme.backgroundAlt + " " + defaultTheme.gray + ";\n }\n\n .ReactQueryDevtoolsPanel *::-webkit-scrollbar, .ReactQueryDevtoolsPanel scrollbar {\n width: 1em;\n height: 1em;\n }\n\n .ReactQueryDevtoolsPanel *::-webkit-scrollbar-track, .ReactQueryDevtoolsPanel scrollbar-track {\n background: " + defaultTheme.backgroundAlt + ";\n }\n\n .ReactQueryDevtoolsPanel *::-webkit-scrollbar-thumb, .ReactQueryDevtoolsPanel scrollbar-thumb {\n background: " + defaultTheme.gray + ";\n border-radius: .5em;\n border: 3px solid " + defaultTheme.backgroundAlt + ";\n }\n "
|
||||
}
|
||||
}), /*#__PURE__*/React__default.createElement("div", {
|
||||
style: {
|
||||
position: 'absolute',
|
||||
left: 0,
|
||||
top: 0,
|
||||
width: '100%',
|
||||
height: '4px',
|
||||
marginBottom: '-4px',
|
||||
cursor: 'row-resize',
|
||||
zIndex: 100000
|
||||
},
|
||||
onMouseDown: handleDragStart
|
||||
}), /*#__PURE__*/React__default.createElement("div", {
|
||||
style: {
|
||||
flex: '1 1 500px',
|
||||
minHeight: '40%',
|
||||
maxHeight: '100%',
|
||||
overflow: 'auto',
|
||||
borderRight: "1px solid " + defaultTheme.grayAlt,
|
||||
display: isOpen ? 'flex' : 'none',
|
||||
flexDirection: 'column'
|
||||
}
|
||||
}, /*#__PURE__*/React__default.createElement("div", {
|
||||
style: {
|
||||
padding: '.5em',
|
||||
background: defaultTheme.backgroundAlt,
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center'
|
||||
}
|
||||
}, /*#__PURE__*/React__default.createElement("button", {
|
||||
type: "button",
|
||||
"aria-label": "Close React Query Devtools",
|
||||
"aria-controls": "ReactQueryDevtoolsPanel",
|
||||
"aria-haspopup": "true",
|
||||
"aria-expanded": "true",
|
||||
onClick: function onClick() {
|
||||
return setIsOpen(false);
|
||||
},
|
||||
style: {
|
||||
display: 'inline-flex',
|
||||
background: 'none',
|
||||
border: 0,
|
||||
padding: 0,
|
||||
marginRight: '.5em',
|
||||
cursor: 'pointer'
|
||||
}
|
||||
}, /*#__PURE__*/React__default.createElement(Logo, {
|
||||
"aria-hidden": true
|
||||
})), /*#__PURE__*/React__default.createElement("div", {
|
||||
style: {
|
||||
display: 'flex',
|
||||
flexDirection: 'column'
|
||||
}
|
||||
}, /*#__PURE__*/React__default.createElement(QueryKeys, {
|
||||
style: {
|
||||
marginBottom: '.5em'
|
||||
}
|
||||
}, /*#__PURE__*/React__default.createElement(QueryKey, {
|
||||
style: {
|
||||
background: defaultTheme.success,
|
||||
opacity: hasFresh ? 1 : 0.3
|
||||
}
|
||||
}, "fresh ", /*#__PURE__*/React__default.createElement(Code, null, "(", hasFresh, ")")), ' ', /*#__PURE__*/React__default.createElement(QueryKey, {
|
||||
style: {
|
||||
background: defaultTheme.active,
|
||||
opacity: hasFetching ? 1 : 0.3
|
||||
}
|
||||
}, "fetching ", /*#__PURE__*/React__default.createElement(Code, null, "(", hasFetching, ")")), ' ', /*#__PURE__*/React__default.createElement(QueryKey, {
|
||||
style: {
|
||||
background: defaultTheme.warning,
|
||||
color: 'black',
|
||||
textShadow: '0',
|
||||
opacity: hasStale ? 1 : 0.3
|
||||
}
|
||||
}, "stale ", /*#__PURE__*/React__default.createElement(Code, null, "(", hasStale, ")")), ' ', /*#__PURE__*/React__default.createElement(QueryKey, {
|
||||
style: {
|
||||
background: defaultTheme.gray,
|
||||
opacity: hasInactive ? 1 : 0.3
|
||||
}
|
||||
}, "inactive ", /*#__PURE__*/React__default.createElement(Code, null, "(", hasInactive, ")"))), /*#__PURE__*/React__default.createElement("div", {
|
||||
style: {
|
||||
display: 'flex',
|
||||
alignItems: 'center'
|
||||
}
|
||||
}, /*#__PURE__*/React__default.createElement(Input, {
|
||||
placeholder: "Filter",
|
||||
"aria-label": "Filter by queryhash",
|
||||
value: filter != null ? filter : '',
|
||||
onChange: function onChange(e) {
|
||||
return setFilter(e.target.value);
|
||||
},
|
||||
onKeyDown: function onKeyDown(e) {
|
||||
if (e.key === 'Escape') setFilter('');
|
||||
},
|
||||
style: {
|
||||
flex: '1',
|
||||
marginRight: '.5em',
|
||||
width: '100%'
|
||||
}
|
||||
}), !filter ? /*#__PURE__*/React__default.createElement(React__default.Fragment, null, /*#__PURE__*/React__default.createElement(Select, {
|
||||
"aria-label": "Sort queries",
|
||||
value: sort,
|
||||
onChange: function onChange(e) {
|
||||
return setSort(e.target.value);
|
||||
},
|
||||
style: {
|
||||
flex: '1',
|
||||
minWidth: 75,
|
||||
marginRight: '.5em'
|
||||
}
|
||||
}, Object.keys(sortFns).map(function (key) {
|
||||
return /*#__PURE__*/React__default.createElement("option", {
|
||||
key: key,
|
||||
value: key
|
||||
}, "Sort by ", key);
|
||||
})), /*#__PURE__*/React__default.createElement(Button, {
|
||||
type: "button",
|
||||
onClick: function onClick() {
|
||||
return setSortDesc(function (old) {
|
||||
return !old;
|
||||
});
|
||||
},
|
||||
style: {
|
||||
padding: '.3em .4em'
|
||||
}
|
||||
}, sortDesc ? '⬇ Desc' : '⬆ Asc')) : null))), /*#__PURE__*/React__default.createElement("div", {
|
||||
style: {
|
||||
overflowY: 'auto',
|
||||
flex: '1'
|
||||
}
|
||||
}, queries.map(function (query, i) {
|
||||
var isDisabled = query.getObserversCount() > 0 && !query.isActive();
|
||||
return /*#__PURE__*/React__default.createElement("div", {
|
||||
key: query.queryHash || i,
|
||||
role: "button",
|
||||
"aria-label": "Open query details for " + query.queryHash,
|
||||
onClick: function onClick() {
|
||||
return setActiveQueryHash(activeQueryHash === query.queryHash ? '' : query.queryHash);
|
||||
},
|
||||
style: {
|
||||
display: 'flex',
|
||||
borderBottom: "solid 1px " + defaultTheme.grayAlt,
|
||||
cursor: 'pointer',
|
||||
background: query === activeQuery ? 'rgba(255,255,255,.1)' : undefined
|
||||
}
|
||||
}, /*#__PURE__*/React__default.createElement("div", {
|
||||
style: {
|
||||
flex: '0 0 auto',
|
||||
width: '2em',
|
||||
height: '2em',
|
||||
background: getQueryStatusColor(query, defaultTheme),
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
fontWeight: 'bold',
|
||||
textShadow: getQueryStatusLabel(query) === 'stale' ? '0' : '0 0 10px black',
|
||||
color: getQueryStatusLabel(query) === 'stale' ? 'black' : 'white'
|
||||
}
|
||||
}, query.getObserversCount()), isDisabled ? /*#__PURE__*/React__default.createElement("div", {
|
||||
style: {
|
||||
flex: '0 0 auto',
|
||||
height: '2em',
|
||||
background: defaultTheme.gray,
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
fontWeight: 'bold',
|
||||
padding: '0 0.5em'
|
||||
}
|
||||
}, "disabled") : null, /*#__PURE__*/React__default.createElement(Code, {
|
||||
style: {
|
||||
padding: '.5em'
|
||||
}
|
||||
}, "" + query.queryHash));
|
||||
}))), activeQuery ? /*#__PURE__*/React__default.createElement(ActiveQueryPanel, null, /*#__PURE__*/React__default.createElement("div", {
|
||||
style: {
|
||||
padding: '.5em',
|
||||
background: defaultTheme.backgroundAlt,
|
||||
position: 'sticky',
|
||||
top: 0,
|
||||
zIndex: 1
|
||||
}
|
||||
}, "Query Details"), /*#__PURE__*/React__default.createElement("div", {
|
||||
style: {
|
||||
padding: '.5em'
|
||||
}
|
||||
}, /*#__PURE__*/React__default.createElement("div", {
|
||||
style: {
|
||||
marginBottom: '.5em',
|
||||
display: 'flex',
|
||||
alignItems: 'start',
|
||||
justifyContent: 'space-between'
|
||||
}
|
||||
}, /*#__PURE__*/React__default.createElement(Code, {
|
||||
style: {
|
||||
lineHeight: '1.8em'
|
||||
}
|
||||
}, /*#__PURE__*/React__default.createElement("pre", {
|
||||
style: {
|
||||
margin: 0,
|
||||
padding: 0,
|
||||
overflow: 'auto'
|
||||
}
|
||||
}, JSON.stringify(activeQuery.queryKey, null, 2))), /*#__PURE__*/React__default.createElement("span", {
|
||||
style: {
|
||||
padding: '0.3em .6em',
|
||||
borderRadius: '0.4em',
|
||||
fontWeight: 'bold',
|
||||
textShadow: '0 2px 10px black',
|
||||
background: getQueryStatusColor(activeQuery, defaultTheme),
|
||||
flexShrink: 0
|
||||
}
|
||||
}, getQueryStatusLabel(activeQuery))), /*#__PURE__*/React__default.createElement("div", {
|
||||
style: {
|
||||
marginBottom: '.5em',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'space-between'
|
||||
}
|
||||
}, "Observers: ", /*#__PURE__*/React__default.createElement(Code, null, activeQuery.getObserversCount())), /*#__PURE__*/React__default.createElement("div", {
|
||||
style: {
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'space-between'
|
||||
}
|
||||
}, "Last Updated:", ' ', /*#__PURE__*/React__default.createElement(Code, null, new Date(activeQuery.state.dataUpdatedAt).toLocaleTimeString()))), /*#__PURE__*/React__default.createElement("div", {
|
||||
style: {
|
||||
background: defaultTheme.backgroundAlt,
|
||||
padding: '.5em',
|
||||
position: 'sticky',
|
||||
top: 0,
|
||||
zIndex: 1
|
||||
}
|
||||
}, "Actions"), /*#__PURE__*/React__default.createElement("div", {
|
||||
style: {
|
||||
padding: '0.5em'
|
||||
}
|
||||
}, /*#__PURE__*/React__default.createElement(Button, {
|
||||
type: "button",
|
||||
onClick: handleRefetch,
|
||||
disabled: activeQuery.state.isFetching,
|
||||
style: {
|
||||
background: defaultTheme.active
|
||||
}
|
||||
}, "Refetch"), ' ', /*#__PURE__*/React__default.createElement(Button, {
|
||||
type: "button",
|
||||
onClick: function onClick() {
|
||||
return queryClient.invalidateQueries(activeQuery);
|
||||
},
|
||||
style: {
|
||||
background: defaultTheme.warning,
|
||||
color: defaultTheme.inputTextColor
|
||||
}
|
||||
}, "Invalidate"), ' ', /*#__PURE__*/React__default.createElement(Button, {
|
||||
type: "button",
|
||||
onClick: function onClick() {
|
||||
return queryClient.resetQueries(activeQuery);
|
||||
},
|
||||
style: {
|
||||
background: defaultTheme.gray
|
||||
}
|
||||
}, "Reset"), ' ', /*#__PURE__*/React__default.createElement(Button, {
|
||||
type: "button",
|
||||
onClick: function onClick() {
|
||||
return queryClient.removeQueries(activeQuery);
|
||||
},
|
||||
style: {
|
||||
background: defaultTheme.danger
|
||||
}
|
||||
}, "Remove")), /*#__PURE__*/React__default.createElement("div", {
|
||||
style: {
|
||||
background: defaultTheme.backgroundAlt,
|
||||
padding: '.5em',
|
||||
position: 'sticky',
|
||||
top: 0,
|
||||
zIndex: 1
|
||||
}
|
||||
}, "Data Explorer"), /*#__PURE__*/React__default.createElement("div", {
|
||||
style: {
|
||||
padding: '.5em'
|
||||
}
|
||||
}, /*#__PURE__*/React__default.createElement(Explorer, {
|
||||
label: "Data",
|
||||
value: activeQuery == null ? void 0 : (_activeQuery$state = activeQuery.state) == null ? void 0 : _activeQuery$state.data,
|
||||
defaultExpanded: {}
|
||||
})), /*#__PURE__*/React__default.createElement("div", {
|
||||
style: {
|
||||
background: defaultTheme.backgroundAlt,
|
||||
padding: '.5em',
|
||||
position: 'sticky',
|
||||
top: 0,
|
||||
zIndex: 1
|
||||
}
|
||||
}, "Query Explorer"), /*#__PURE__*/React__default.createElement("div", {
|
||||
style: {
|
||||
padding: '.5em'
|
||||
}
|
||||
}, /*#__PURE__*/React__default.createElement(Explorer, {
|
||||
label: "Query",
|
||||
value: activeQuery,
|
||||
defaultExpanded: {
|
||||
queryKey: true
|
||||
}
|
||||
}))) : null));
|
||||
});
|
||||
|
||||
exports.ReactQueryDevtools = ReactQueryDevtools;
|
||||
exports.ReactQueryDevtoolsPanel = ReactQueryDevtoolsPanel;
|
||||
|
||||
Object.defineProperty(exports, '__esModule', { value: true });
|
||||
|
||||
})));
|
||||
//# sourceMappingURL=react-query-devtools.development.js.map
|
||||
Generated
Vendored
+1
File diff suppressed because one or more lines are too long
+2
File diff suppressed because one or more lines are too long
Generated
Vendored
+1
File diff suppressed because one or more lines are too long
+35
@@ -0,0 +1,35 @@
|
||||
(function (global, factory) {
|
||||
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react-query')) :
|
||||
typeof define === 'function' && define.amd ? define(['exports', 'react-query'], factory) :
|
||||
(global = global || self, factory(global.ReactQueryHydration = {}, global.ReactQuery));
|
||||
}(this, (function (exports, reactQuery) { 'use strict';
|
||||
|
||||
Object.defineProperty(exports, 'Hydrate', {
|
||||
enumerable: true,
|
||||
get: function () {
|
||||
return reactQuery.Hydrate;
|
||||
}
|
||||
});
|
||||
Object.defineProperty(exports, 'dehydrate', {
|
||||
enumerable: true,
|
||||
get: function () {
|
||||
return reactQuery.dehydrate;
|
||||
}
|
||||
});
|
||||
Object.defineProperty(exports, 'hydrate', {
|
||||
enumerable: true,
|
||||
get: function () {
|
||||
return reactQuery.hydrate;
|
||||
}
|
||||
});
|
||||
Object.defineProperty(exports, 'useHydrate', {
|
||||
enumerable: true,
|
||||
get: function () {
|
||||
return reactQuery.useHydrate;
|
||||
}
|
||||
});
|
||||
|
||||
Object.defineProperty(exports, '__esModule', { value: true });
|
||||
|
||||
})));
|
||||
//# sourceMappingURL=react-query-hydration.development.js.map
|
||||
Generated
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"react-query-hydration.development.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
||||
Generated
Vendored
+2
@@ -0,0 +1,2 @@
|
||||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react-query")):"function"==typeof define&&define.amd?define(["exports","react-query"],t):t((e=e||self).ReactQueryHydration={},e.ReactQuery)}(this,(function(e,t){"use strict";Object.defineProperty(e,"Hydrate",{enumerable:!0,get:function(){return t.Hydrate}}),Object.defineProperty(e,"dehydrate",{enumerable:!0,get:function(){return t.dehydrate}}),Object.defineProperty(e,"hydrate",{enumerable:!0,get:function(){return t.hydrate}}),Object.defineProperty(e,"useHydrate",{enumerable:!0,get:function(){return t.useHydrate}}),Object.defineProperty(e,"__esModule",{value:!0})}));
|
||||
//# sourceMappingURL=react-query-hydration.production.min.js.map
|
||||
Generated
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"react-query-hydration.production.min.js","sources":[],"sourcesContent":[],"names":[],"mappings":""}
|
||||
+3783
@@ -0,0 +1,3783 @@
|
||||
(function (global, factory) {
|
||||
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react')) :
|
||||
typeof define === 'function' && define.amd ? define(['exports', 'react'], factory) :
|
||||
(global = global || self, factory(global.ReactQuery = {}, global.React));
|
||||
}(this, (function (exports, React) { 'use strict';
|
||||
|
||||
var React__default = 'default' in React ? React['default'] : React;
|
||||
|
||||
function _inheritsLoose(subClass, superClass) {
|
||||
subClass.prototype = Object.create(superClass.prototype);
|
||||
subClass.prototype.constructor = subClass;
|
||||
subClass.__proto__ = superClass;
|
||||
}
|
||||
|
||||
var Subscribable = /*#__PURE__*/function () {
|
||||
function Subscribable() {
|
||||
this.listeners = [];
|
||||
}
|
||||
|
||||
var _proto = Subscribable.prototype;
|
||||
|
||||
_proto.subscribe = function subscribe(listener) {
|
||||
var _this = this;
|
||||
|
||||
var callback = listener || function () {
|
||||
return undefined;
|
||||
};
|
||||
|
||||
this.listeners.push(callback);
|
||||
this.onSubscribe();
|
||||
return function () {
|
||||
_this.listeners = _this.listeners.filter(function (x) {
|
||||
return x !== callback;
|
||||
});
|
||||
|
||||
_this.onUnsubscribe();
|
||||
};
|
||||
};
|
||||
|
||||
_proto.hasListeners = function hasListeners() {
|
||||
return this.listeners.length > 0;
|
||||
};
|
||||
|
||||
_proto.onSubscribe = function onSubscribe() {// Do nothing
|
||||
};
|
||||
|
||||
_proto.onUnsubscribe = function onUnsubscribe() {// Do nothing
|
||||
};
|
||||
|
||||
return Subscribable;
|
||||
}();
|
||||
|
||||
function _extends() {
|
||||
_extends = Object.assign || function (target) {
|
||||
for (var i = 1; i < arguments.length; i++) {
|
||||
var source = arguments[i];
|
||||
|
||||
for (var key in source) {
|
||||
if (Object.prototype.hasOwnProperty.call(source, key)) {
|
||||
target[key] = source[key];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return target;
|
||||
};
|
||||
|
||||
return _extends.apply(this, arguments);
|
||||
}
|
||||
|
||||
// TYPES
|
||||
// UTILS
|
||||
var isServer = typeof window === 'undefined';
|
||||
function noop() {
|
||||
return undefined;
|
||||
}
|
||||
function functionalUpdate(updater, input) {
|
||||
return typeof updater === 'function' ? updater(input) : updater;
|
||||
}
|
||||
function isValidTimeout(value) {
|
||||
return typeof value === 'number' && value >= 0 && value !== Infinity;
|
||||
}
|
||||
function ensureQueryKeyArray(value) {
|
||||
return Array.isArray(value) ? value : [value];
|
||||
}
|
||||
function difference(array1, array2) {
|
||||
return array1.filter(function (x) {
|
||||
return array2.indexOf(x) === -1;
|
||||
});
|
||||
}
|
||||
function replaceAt(array, index, value) {
|
||||
var copy = array.slice(0);
|
||||
copy[index] = value;
|
||||
return copy;
|
||||
}
|
||||
function timeUntilStale(updatedAt, staleTime) {
|
||||
return Math.max(updatedAt + (staleTime || 0) - Date.now(), 0);
|
||||
}
|
||||
function parseQueryArgs(arg1, arg2, arg3) {
|
||||
if (!isQueryKey(arg1)) {
|
||||
return arg1;
|
||||
}
|
||||
|
||||
if (typeof arg2 === 'function') {
|
||||
return _extends({}, arg3, {
|
||||
queryKey: arg1,
|
||||
queryFn: arg2
|
||||
});
|
||||
}
|
||||
|
||||
return _extends({}, arg2, {
|
||||
queryKey: arg1
|
||||
});
|
||||
}
|
||||
function parseMutationArgs(arg1, arg2, arg3) {
|
||||
if (isQueryKey(arg1)) {
|
||||
if (typeof arg2 === 'function') {
|
||||
return _extends({}, arg3, {
|
||||
mutationKey: arg1,
|
||||
mutationFn: arg2
|
||||
});
|
||||
}
|
||||
|
||||
return _extends({}, arg2, {
|
||||
mutationKey: arg1
|
||||
});
|
||||
}
|
||||
|
||||
if (typeof arg1 === 'function') {
|
||||
return _extends({}, arg2, {
|
||||
mutationFn: arg1
|
||||
});
|
||||
}
|
||||
|
||||
return _extends({}, arg1);
|
||||
}
|
||||
function parseFilterArgs(arg1, arg2, arg3) {
|
||||
return isQueryKey(arg1) ? [_extends({}, arg2, {
|
||||
queryKey: arg1
|
||||
}), arg3] : [arg1 || {}, arg2];
|
||||
}
|
||||
function parseMutationFilterArgs(arg1, arg2) {
|
||||
return isQueryKey(arg1) ? _extends({}, arg2, {
|
||||
mutationKey: arg1
|
||||
}) : arg1;
|
||||
}
|
||||
function mapQueryStatusFilter(active, inactive) {
|
||||
if (active === true && inactive === true || active == null && inactive == null) {
|
||||
return 'all';
|
||||
} else if (active === false && inactive === false) {
|
||||
return 'none';
|
||||
} else {
|
||||
// At this point, active|inactive can only be true|false or false|true
|
||||
// so, when only one value is provided, the missing one has to be the negated value
|
||||
var isActive = active != null ? active : !inactive;
|
||||
return isActive ? 'active' : 'inactive';
|
||||
}
|
||||
}
|
||||
function matchQuery(filters, query) {
|
||||
var active = filters.active,
|
||||
exact = filters.exact,
|
||||
fetching = filters.fetching,
|
||||
inactive = filters.inactive,
|
||||
predicate = filters.predicate,
|
||||
queryKey = filters.queryKey,
|
||||
stale = filters.stale;
|
||||
|
||||
if (isQueryKey(queryKey)) {
|
||||
if (exact) {
|
||||
if (query.queryHash !== hashQueryKeyByOptions(queryKey, query.options)) {
|
||||
return false;
|
||||
}
|
||||
} else if (!partialMatchKey(query.queryKey, queryKey)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
var queryStatusFilter = mapQueryStatusFilter(active, inactive);
|
||||
|
||||
if (queryStatusFilter === 'none') {
|
||||
return false;
|
||||
} else if (queryStatusFilter !== 'all') {
|
||||
var isActive = query.isActive();
|
||||
|
||||
if (queryStatusFilter === 'active' && !isActive) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (queryStatusFilter === 'inactive' && isActive) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof stale === 'boolean' && query.isStale() !== stale) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (typeof fetching === 'boolean' && query.isFetching() !== fetching) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (predicate && !predicate(query)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
function matchMutation(filters, mutation) {
|
||||
var exact = filters.exact,
|
||||
fetching = filters.fetching,
|
||||
predicate = filters.predicate,
|
||||
mutationKey = filters.mutationKey;
|
||||
|
||||
if (isQueryKey(mutationKey)) {
|
||||
if (!mutation.options.mutationKey) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (exact) {
|
||||
if (hashQueryKey(mutation.options.mutationKey) !== hashQueryKey(mutationKey)) {
|
||||
return false;
|
||||
}
|
||||
} else if (!partialMatchKey(mutation.options.mutationKey, mutationKey)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof fetching === 'boolean' && mutation.state.status === 'loading' !== fetching) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (predicate && !predicate(mutation)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
function hashQueryKeyByOptions(queryKey, options) {
|
||||
var hashFn = (options == null ? void 0 : options.queryKeyHashFn) || hashQueryKey;
|
||||
return hashFn(queryKey);
|
||||
}
|
||||
/**
|
||||
* Default query keys hash function.
|
||||
*/
|
||||
|
||||
function hashQueryKey(queryKey) {
|
||||
var asArray = ensureQueryKeyArray(queryKey);
|
||||
return stableValueHash(asArray);
|
||||
}
|
||||
/**
|
||||
* Hashes the value into a stable hash.
|
||||
*/
|
||||
|
||||
function stableValueHash(value) {
|
||||
return JSON.stringify(value, function (_, val) {
|
||||
return isPlainObject(val) ? Object.keys(val).sort().reduce(function (result, key) {
|
||||
result[key] = val[key];
|
||||
return result;
|
||||
}, {}) : val;
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Checks if key `b` partially matches with key `a`.
|
||||
*/
|
||||
|
||||
function partialMatchKey(a, b) {
|
||||
return partialDeepEqual(ensureQueryKeyArray(a), ensureQueryKeyArray(b));
|
||||
}
|
||||
/**
|
||||
* Checks if `b` partially matches with `a`.
|
||||
*/
|
||||
|
||||
function partialDeepEqual(a, b) {
|
||||
if (a === b) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (typeof a !== typeof b) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (a && b && typeof a === 'object' && typeof b === 'object') {
|
||||
return !Object.keys(b).some(function (key) {
|
||||
return !partialDeepEqual(a[key], b[key]);
|
||||
});
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
/**
|
||||
* This function returns `a` if `b` is deeply equal.
|
||||
* If not, it will replace any deeply equal children of `b` with those of `a`.
|
||||
* This can be used for structural sharing between JSON values for example.
|
||||
*/
|
||||
|
||||
function replaceEqualDeep(a, b) {
|
||||
if (a === b) {
|
||||
return a;
|
||||
}
|
||||
|
||||
var array = Array.isArray(a) && Array.isArray(b);
|
||||
|
||||
if (array || isPlainObject(a) && isPlainObject(b)) {
|
||||
var aSize = array ? a.length : Object.keys(a).length;
|
||||
var bItems = array ? b : Object.keys(b);
|
||||
var bSize = bItems.length;
|
||||
var copy = array ? [] : {};
|
||||
var equalItems = 0;
|
||||
|
||||
for (var i = 0; i < bSize; i++) {
|
||||
var key = array ? i : bItems[i];
|
||||
copy[key] = replaceEqualDeep(a[key], b[key]);
|
||||
|
||||
if (copy[key] === a[key]) {
|
||||
equalItems++;
|
||||
}
|
||||
}
|
||||
|
||||
return aSize === bSize && equalItems === aSize ? a : copy;
|
||||
}
|
||||
|
||||
return b;
|
||||
}
|
||||
/**
|
||||
* Shallow compare objects. Only works with objects that always have the same properties.
|
||||
*/
|
||||
|
||||
function shallowEqualObjects(a, b) {
|
||||
if (a && !b || b && !a) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (var key in a) {
|
||||
if (a[key] !== b[key]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
} // Copied from: https://github.com/jonschlinkert/is-plain-object
|
||||
|
||||
function isPlainObject(o) {
|
||||
if (!hasObjectPrototype(o)) {
|
||||
return false;
|
||||
} // If has modified constructor
|
||||
|
||||
|
||||
var ctor = o.constructor;
|
||||
|
||||
if (typeof ctor === 'undefined') {
|
||||
return true;
|
||||
} // If has modified prototype
|
||||
|
||||
|
||||
var prot = ctor.prototype;
|
||||
|
||||
if (!hasObjectPrototype(prot)) {
|
||||
return false;
|
||||
} // If constructor does not have an Object-specific method
|
||||
|
||||
|
||||
if (!prot.hasOwnProperty('isPrototypeOf')) {
|
||||
return false;
|
||||
} // Most likely a plain Object
|
||||
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
function hasObjectPrototype(o) {
|
||||
return Object.prototype.toString.call(o) === '[object Object]';
|
||||
}
|
||||
|
||||
function isQueryKey(value) {
|
||||
return typeof value === 'string' || Array.isArray(value);
|
||||
}
|
||||
function isError(value) {
|
||||
return value instanceof Error;
|
||||
}
|
||||
function sleep(timeout) {
|
||||
return new Promise(function (resolve) {
|
||||
setTimeout(resolve, timeout);
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Schedules a microtask.
|
||||
* This can be useful to schedule state updates after rendering.
|
||||
*/
|
||||
|
||||
function scheduleMicrotask(callback) {
|
||||
Promise.resolve().then(callback).catch(function (error) {
|
||||
return setTimeout(function () {
|
||||
throw error;
|
||||
});
|
||||
});
|
||||
}
|
||||
function getAbortController() {
|
||||
if (typeof AbortController === 'function') {
|
||||
return new AbortController();
|
||||
}
|
||||
}
|
||||
|
||||
var FocusManager = /*#__PURE__*/function (_Subscribable) {
|
||||
_inheritsLoose(FocusManager, _Subscribable);
|
||||
|
||||
function FocusManager() {
|
||||
var _this;
|
||||
|
||||
_this = _Subscribable.call(this) || this;
|
||||
|
||||
_this.setup = function (onFocus) {
|
||||
var _window;
|
||||
|
||||
if (!isServer && ((_window = window) == null ? void 0 : _window.addEventListener)) {
|
||||
var listener = function listener() {
|
||||
return onFocus();
|
||||
}; // Listen to visibillitychange and focus
|
||||
|
||||
|
||||
window.addEventListener('visibilitychange', listener, false);
|
||||
window.addEventListener('focus', listener, false);
|
||||
return function () {
|
||||
// Be sure to unsubscribe if a new handler is set
|
||||
window.removeEventListener('visibilitychange', listener);
|
||||
window.removeEventListener('focus', listener);
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
return _this;
|
||||
}
|
||||
|
||||
var _proto = FocusManager.prototype;
|
||||
|
||||
_proto.onSubscribe = function onSubscribe() {
|
||||
if (!this.cleanup) {
|
||||
this.setEventListener(this.setup);
|
||||
}
|
||||
};
|
||||
|
||||
_proto.onUnsubscribe = function onUnsubscribe() {
|
||||
if (!this.hasListeners()) {
|
||||
var _this$cleanup;
|
||||
|
||||
(_this$cleanup = this.cleanup) == null ? void 0 : _this$cleanup.call(this);
|
||||
this.cleanup = undefined;
|
||||
}
|
||||
};
|
||||
|
||||
_proto.setEventListener = function setEventListener(setup) {
|
||||
var _this$cleanup2,
|
||||
_this2 = this;
|
||||
|
||||
this.setup = setup;
|
||||
(_this$cleanup2 = this.cleanup) == null ? void 0 : _this$cleanup2.call(this);
|
||||
this.cleanup = setup(function (focused) {
|
||||
if (typeof focused === 'boolean') {
|
||||
_this2.setFocused(focused);
|
||||
} else {
|
||||
_this2.onFocus();
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
_proto.setFocused = function setFocused(focused) {
|
||||
this.focused = focused;
|
||||
|
||||
if (focused) {
|
||||
this.onFocus();
|
||||
}
|
||||
};
|
||||
|
||||
_proto.onFocus = function onFocus() {
|
||||
this.listeners.forEach(function (listener) {
|
||||
listener();
|
||||
});
|
||||
};
|
||||
|
||||
_proto.isFocused = function isFocused() {
|
||||
if (typeof this.focused === 'boolean') {
|
||||
return this.focused;
|
||||
} // document global can be unavailable in react native
|
||||
|
||||
|
||||
if (typeof document === 'undefined') {
|
||||
return true;
|
||||
}
|
||||
|
||||
return [undefined, 'visible', 'prerender'].includes(document.visibilityState);
|
||||
};
|
||||
|
||||
return FocusManager;
|
||||
}(Subscribable);
|
||||
var focusManager = new FocusManager();
|
||||
|
||||
var OnlineManager = /*#__PURE__*/function (_Subscribable) {
|
||||
_inheritsLoose(OnlineManager, _Subscribable);
|
||||
|
||||
function OnlineManager() {
|
||||
var _this;
|
||||
|
||||
_this = _Subscribable.call(this) || this;
|
||||
|
||||
_this.setup = function (onOnline) {
|
||||
var _window;
|
||||
|
||||
if (!isServer && ((_window = window) == null ? void 0 : _window.addEventListener)) {
|
||||
var listener = function listener() {
|
||||
return onOnline();
|
||||
}; // Listen to online
|
||||
|
||||
|
||||
window.addEventListener('online', listener, false);
|
||||
window.addEventListener('offline', listener, false);
|
||||
return function () {
|
||||
// Be sure to unsubscribe if a new handler is set
|
||||
window.removeEventListener('online', listener);
|
||||
window.removeEventListener('offline', listener);
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
return _this;
|
||||
}
|
||||
|
||||
var _proto = OnlineManager.prototype;
|
||||
|
||||
_proto.onSubscribe = function onSubscribe() {
|
||||
if (!this.cleanup) {
|
||||
this.setEventListener(this.setup);
|
||||
}
|
||||
};
|
||||
|
||||
_proto.onUnsubscribe = function onUnsubscribe() {
|
||||
if (!this.hasListeners()) {
|
||||
var _this$cleanup;
|
||||
|
||||
(_this$cleanup = this.cleanup) == null ? void 0 : _this$cleanup.call(this);
|
||||
this.cleanup = undefined;
|
||||
}
|
||||
};
|
||||
|
||||
_proto.setEventListener = function setEventListener(setup) {
|
||||
var _this$cleanup2,
|
||||
_this2 = this;
|
||||
|
||||
this.setup = setup;
|
||||
(_this$cleanup2 = this.cleanup) == null ? void 0 : _this$cleanup2.call(this);
|
||||
this.cleanup = setup(function (online) {
|
||||
if (typeof online === 'boolean') {
|
||||
_this2.setOnline(online);
|
||||
} else {
|
||||
_this2.onOnline();
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
_proto.setOnline = function setOnline(online) {
|
||||
this.online = online;
|
||||
|
||||
if (online) {
|
||||
this.onOnline();
|
||||
}
|
||||
};
|
||||
|
||||
_proto.onOnline = function onOnline() {
|
||||
this.listeners.forEach(function (listener) {
|
||||
listener();
|
||||
});
|
||||
};
|
||||
|
||||
_proto.isOnline = function isOnline() {
|
||||
if (typeof this.online === 'boolean') {
|
||||
return this.online;
|
||||
}
|
||||
|
||||
if (typeof navigator === 'undefined' || typeof navigator.onLine === 'undefined') {
|
||||
return true;
|
||||
}
|
||||
|
||||
return navigator.onLine;
|
||||
};
|
||||
|
||||
return OnlineManager;
|
||||
}(Subscribable);
|
||||
var onlineManager = new OnlineManager();
|
||||
|
||||
function defaultRetryDelay(failureCount) {
|
||||
return Math.min(1000 * Math.pow(2, failureCount), 30000);
|
||||
}
|
||||
|
||||
function isCancelable(value) {
|
||||
return typeof (value == null ? void 0 : value.cancel) === 'function';
|
||||
}
|
||||
var CancelledError = function CancelledError(options) {
|
||||
this.revert = options == null ? void 0 : options.revert;
|
||||
this.silent = options == null ? void 0 : options.silent;
|
||||
};
|
||||
function isCancelledError(value) {
|
||||
return value instanceof CancelledError;
|
||||
} // CLASS
|
||||
|
||||
var Retryer = function Retryer(config) {
|
||||
var _this = this;
|
||||
|
||||
var cancelRetry = false;
|
||||
var cancelFn;
|
||||
var continueFn;
|
||||
var promiseResolve;
|
||||
var promiseReject;
|
||||
this.abort = config.abort;
|
||||
|
||||
this.cancel = function (cancelOptions) {
|
||||
return cancelFn == null ? void 0 : cancelFn(cancelOptions);
|
||||
};
|
||||
|
||||
this.cancelRetry = function () {
|
||||
cancelRetry = true;
|
||||
};
|
||||
|
||||
this.continueRetry = function () {
|
||||
cancelRetry = false;
|
||||
};
|
||||
|
||||
this.continue = function () {
|
||||
return continueFn == null ? void 0 : continueFn();
|
||||
};
|
||||
|
||||
this.failureCount = 0;
|
||||
this.isPaused = false;
|
||||
this.isResolved = false;
|
||||
this.isTransportCancelable = false;
|
||||
this.promise = new Promise(function (outerResolve, outerReject) {
|
||||
promiseResolve = outerResolve;
|
||||
promiseReject = outerReject;
|
||||
});
|
||||
|
||||
var resolve = function resolve(value) {
|
||||
if (!_this.isResolved) {
|
||||
_this.isResolved = true;
|
||||
config.onSuccess == null ? void 0 : config.onSuccess(value);
|
||||
continueFn == null ? void 0 : continueFn();
|
||||
promiseResolve(value);
|
||||
}
|
||||
};
|
||||
|
||||
var reject = function reject(value) {
|
||||
if (!_this.isResolved) {
|
||||
_this.isResolved = true;
|
||||
config.onError == null ? void 0 : config.onError(value);
|
||||
continueFn == null ? void 0 : continueFn();
|
||||
promiseReject(value);
|
||||
}
|
||||
};
|
||||
|
||||
var pause = function pause() {
|
||||
return new Promise(function (continueResolve) {
|
||||
continueFn = continueResolve;
|
||||
_this.isPaused = true;
|
||||
config.onPause == null ? void 0 : config.onPause();
|
||||
}).then(function () {
|
||||
continueFn = undefined;
|
||||
_this.isPaused = false;
|
||||
config.onContinue == null ? void 0 : config.onContinue();
|
||||
});
|
||||
}; // Create loop function
|
||||
|
||||
|
||||
var run = function run() {
|
||||
// Do nothing if already resolved
|
||||
if (_this.isResolved) {
|
||||
return;
|
||||
}
|
||||
|
||||
var promiseOrValue; // Execute query
|
||||
|
||||
try {
|
||||
promiseOrValue = config.fn();
|
||||
} catch (error) {
|
||||
promiseOrValue = Promise.reject(error);
|
||||
} // Create callback to cancel this fetch
|
||||
|
||||
|
||||
cancelFn = function cancelFn(cancelOptions) {
|
||||
if (!_this.isResolved) {
|
||||
reject(new CancelledError(cancelOptions));
|
||||
_this.abort == null ? void 0 : _this.abort(); // Cancel transport if supported
|
||||
|
||||
if (isCancelable(promiseOrValue)) {
|
||||
try {
|
||||
promiseOrValue.cancel();
|
||||
} catch (_unused) {}
|
||||
}
|
||||
}
|
||||
}; // Check if the transport layer support cancellation
|
||||
|
||||
|
||||
_this.isTransportCancelable = isCancelable(promiseOrValue);
|
||||
Promise.resolve(promiseOrValue).then(resolve).catch(function (error) {
|
||||
var _config$retry, _config$retryDelay;
|
||||
|
||||
// Stop if the fetch is already resolved
|
||||
if (_this.isResolved) {
|
||||
return;
|
||||
} // Do we need to retry the request?
|
||||
|
||||
|
||||
var retry = (_config$retry = config.retry) != null ? _config$retry : 3;
|
||||
var retryDelay = (_config$retryDelay = config.retryDelay) != null ? _config$retryDelay : defaultRetryDelay;
|
||||
var delay = typeof retryDelay === 'function' ? retryDelay(_this.failureCount, error) : retryDelay;
|
||||
var shouldRetry = retry === true || typeof retry === 'number' && _this.failureCount < retry || typeof retry === 'function' && retry(_this.failureCount, error);
|
||||
|
||||
if (cancelRetry || !shouldRetry) {
|
||||
// We are done if the query does not need to be retried
|
||||
reject(error);
|
||||
return;
|
||||
}
|
||||
|
||||
_this.failureCount++; // Notify on fail
|
||||
|
||||
config.onFail == null ? void 0 : config.onFail(_this.failureCount, error); // Delay
|
||||
|
||||
sleep(delay) // Pause if the document is not visible or when the device is offline
|
||||
.then(function () {
|
||||
if (!focusManager.isFocused() || !onlineManager.isOnline()) {
|
||||
return pause();
|
||||
}
|
||||
}).then(function () {
|
||||
if (cancelRetry) {
|
||||
reject(error);
|
||||
} else {
|
||||
run();
|
||||
}
|
||||
});
|
||||
});
|
||||
}; // Start loop
|
||||
|
||||
|
||||
run();
|
||||
};
|
||||
|
||||
// CLASS
|
||||
var NotifyManager = /*#__PURE__*/function () {
|
||||
function NotifyManager() {
|
||||
this.queue = [];
|
||||
this.transactions = 0;
|
||||
|
||||
this.notifyFn = function (callback) {
|
||||
callback();
|
||||
};
|
||||
|
||||
this.batchNotifyFn = function (callback) {
|
||||
callback();
|
||||
};
|
||||
}
|
||||
|
||||
var _proto = NotifyManager.prototype;
|
||||
|
||||
_proto.batch = function batch(callback) {
|
||||
var result;
|
||||
this.transactions++;
|
||||
|
||||
try {
|
||||
result = callback();
|
||||
} finally {
|
||||
this.transactions--;
|
||||
|
||||
if (!this.transactions) {
|
||||
this.flush();
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
_proto.schedule = function schedule(callback) {
|
||||
var _this = this;
|
||||
|
||||
if (this.transactions) {
|
||||
this.queue.push(callback);
|
||||
} else {
|
||||
scheduleMicrotask(function () {
|
||||
_this.notifyFn(callback);
|
||||
});
|
||||
}
|
||||
}
|
||||
/**
|
||||
* All calls to the wrapped function will be batched.
|
||||
*/
|
||||
;
|
||||
|
||||
_proto.batchCalls = function batchCalls(callback) {
|
||||
var _this2 = this;
|
||||
|
||||
return function () {
|
||||
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
|
||||
args[_key] = arguments[_key];
|
||||
}
|
||||
|
||||
_this2.schedule(function () {
|
||||
callback.apply(void 0, args);
|
||||
});
|
||||
};
|
||||
};
|
||||
|
||||
_proto.flush = function flush() {
|
||||
var _this3 = this;
|
||||
|
||||
var queue = this.queue;
|
||||
this.queue = [];
|
||||
|
||||
if (queue.length) {
|
||||
scheduleMicrotask(function () {
|
||||
_this3.batchNotifyFn(function () {
|
||||
queue.forEach(function (callback) {
|
||||
_this3.notifyFn(callback);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Use this method to set a custom notify function.
|
||||
* This can be used to for example wrap notifications with `React.act` while running tests.
|
||||
*/
|
||||
;
|
||||
|
||||
_proto.setNotifyFunction = function setNotifyFunction(fn) {
|
||||
this.notifyFn = fn;
|
||||
}
|
||||
/**
|
||||
* Use this method to set a custom function to batch notifications together into a single tick.
|
||||
* By default React Query will use the batch function provided by ReactDOM or React Native.
|
||||
*/
|
||||
;
|
||||
|
||||
_proto.setBatchNotifyFunction = function setBatchNotifyFunction(fn) {
|
||||
this.batchNotifyFn = fn;
|
||||
};
|
||||
|
||||
return NotifyManager;
|
||||
}(); // SINGLETON
|
||||
|
||||
var notifyManager = new NotifyManager();
|
||||
|
||||
// TYPES
|
||||
// FUNCTIONS
|
||||
var logger = console;
|
||||
function getLogger() {
|
||||
return logger;
|
||||
}
|
||||
function setLogger(newLogger) {
|
||||
logger = newLogger;
|
||||
}
|
||||
|
||||
// CLASS
|
||||
var Query = /*#__PURE__*/function () {
|
||||
function Query(config) {
|
||||
this.abortSignalConsumed = false;
|
||||
this.hadObservers = false;
|
||||
this.defaultOptions = config.defaultOptions;
|
||||
this.setOptions(config.options);
|
||||
this.observers = [];
|
||||
this.cache = config.cache;
|
||||
this.queryKey = config.queryKey;
|
||||
this.queryHash = config.queryHash;
|
||||
this.initialState = config.state || this.getDefaultState(this.options);
|
||||
this.state = this.initialState;
|
||||
this.meta = config.meta;
|
||||
this.scheduleGc();
|
||||
}
|
||||
|
||||
var _proto = Query.prototype;
|
||||
|
||||
_proto.setOptions = function setOptions(options) {
|
||||
var _this$options$cacheTi;
|
||||
|
||||
this.options = _extends({}, this.defaultOptions, options);
|
||||
this.meta = options == null ? void 0 : options.meta; // Default to 5 minutes if not cache time is set
|
||||
|
||||
this.cacheTime = Math.max(this.cacheTime || 0, (_this$options$cacheTi = this.options.cacheTime) != null ? _this$options$cacheTi : 5 * 60 * 1000);
|
||||
};
|
||||
|
||||
_proto.setDefaultOptions = function setDefaultOptions(options) {
|
||||
this.defaultOptions = options;
|
||||
};
|
||||
|
||||
_proto.scheduleGc = function scheduleGc() {
|
||||
var _this = this;
|
||||
|
||||
this.clearGcTimeout();
|
||||
|
||||
if (isValidTimeout(this.cacheTime)) {
|
||||
this.gcTimeout = setTimeout(function () {
|
||||
_this.optionalRemove();
|
||||
}, this.cacheTime);
|
||||
}
|
||||
};
|
||||
|
||||
_proto.clearGcTimeout = function clearGcTimeout() {
|
||||
if (this.gcTimeout) {
|
||||
clearTimeout(this.gcTimeout);
|
||||
this.gcTimeout = undefined;
|
||||
}
|
||||
};
|
||||
|
||||
_proto.optionalRemove = function optionalRemove() {
|
||||
if (!this.observers.length) {
|
||||
if (this.state.isFetching) {
|
||||
if (this.hadObservers) {
|
||||
this.scheduleGc();
|
||||
}
|
||||
} else {
|
||||
this.cache.remove(this);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
_proto.setData = function setData(updater, options) {
|
||||
var _this$options$isDataE, _this$options;
|
||||
|
||||
var prevData = this.state.data; // Get the new data
|
||||
|
||||
var data = functionalUpdate(updater, prevData); // Use prev data if an isDataEqual function is defined and returns `true`
|
||||
|
||||
if ((_this$options$isDataE = (_this$options = this.options).isDataEqual) == null ? void 0 : _this$options$isDataE.call(_this$options, prevData, data)) {
|
||||
data = prevData;
|
||||
} else if (this.options.structuralSharing !== false) {
|
||||
// Structurally share data between prev and new data if needed
|
||||
data = replaceEqualDeep(prevData, data);
|
||||
} // Set data and mark it as cached
|
||||
|
||||
|
||||
this.dispatch({
|
||||
data: data,
|
||||
type: 'success',
|
||||
dataUpdatedAt: options == null ? void 0 : options.updatedAt
|
||||
});
|
||||
return data;
|
||||
};
|
||||
|
||||
_proto.setState = function setState(state, setStateOptions) {
|
||||
this.dispatch({
|
||||
type: 'setState',
|
||||
state: state,
|
||||
setStateOptions: setStateOptions
|
||||
});
|
||||
};
|
||||
|
||||
_proto.cancel = function cancel(options) {
|
||||
var _this$retryer;
|
||||
|
||||
var promise = this.promise;
|
||||
(_this$retryer = this.retryer) == null ? void 0 : _this$retryer.cancel(options);
|
||||
return promise ? promise.then(noop).catch(noop) : Promise.resolve();
|
||||
};
|
||||
|
||||
_proto.destroy = function destroy() {
|
||||
this.clearGcTimeout();
|
||||
this.cancel({
|
||||
silent: true
|
||||
});
|
||||
};
|
||||
|
||||
_proto.reset = function reset() {
|
||||
this.destroy();
|
||||
this.setState(this.initialState);
|
||||
};
|
||||
|
||||
_proto.isActive = function isActive() {
|
||||
return this.observers.some(function (observer) {
|
||||
return observer.options.enabled !== false;
|
||||
});
|
||||
};
|
||||
|
||||
_proto.isFetching = function isFetching() {
|
||||
return this.state.isFetching;
|
||||
};
|
||||
|
||||
_proto.isStale = function isStale() {
|
||||
return this.state.isInvalidated || !this.state.dataUpdatedAt || this.observers.some(function (observer) {
|
||||
return observer.getCurrentResult().isStale;
|
||||
});
|
||||
};
|
||||
|
||||
_proto.isStaleByTime = function isStaleByTime(staleTime) {
|
||||
if (staleTime === void 0) {
|
||||
staleTime = 0;
|
||||
}
|
||||
|
||||
return this.state.isInvalidated || !this.state.dataUpdatedAt || !timeUntilStale(this.state.dataUpdatedAt, staleTime);
|
||||
};
|
||||
|
||||
_proto.onFocus = function onFocus() {
|
||||
var _this$retryer2;
|
||||
|
||||
var observer = this.observers.find(function (x) {
|
||||
return x.shouldFetchOnWindowFocus();
|
||||
});
|
||||
|
||||
if (observer) {
|
||||
observer.refetch();
|
||||
} // Continue fetch if currently paused
|
||||
|
||||
|
||||
(_this$retryer2 = this.retryer) == null ? void 0 : _this$retryer2.continue();
|
||||
};
|
||||
|
||||
_proto.onOnline = function onOnline() {
|
||||
var _this$retryer3;
|
||||
|
||||
var observer = this.observers.find(function (x) {
|
||||
return x.shouldFetchOnReconnect();
|
||||
});
|
||||
|
||||
if (observer) {
|
||||
observer.refetch();
|
||||
} // Continue fetch if currently paused
|
||||
|
||||
|
||||
(_this$retryer3 = this.retryer) == null ? void 0 : _this$retryer3.continue();
|
||||
};
|
||||
|
||||
_proto.addObserver = function addObserver(observer) {
|
||||
if (this.observers.indexOf(observer) === -1) {
|
||||
this.observers.push(observer);
|
||||
this.hadObservers = true; // Stop the query from being garbage collected
|
||||
|
||||
this.clearGcTimeout();
|
||||
this.cache.notify({
|
||||
type: 'observerAdded',
|
||||
query: this,
|
||||
observer: observer
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
_proto.removeObserver = function removeObserver(observer) {
|
||||
if (this.observers.indexOf(observer) !== -1) {
|
||||
this.observers = this.observers.filter(function (x) {
|
||||
return x !== observer;
|
||||
});
|
||||
|
||||
if (!this.observers.length) {
|
||||
// If the transport layer does not support cancellation
|
||||
// we'll let the query continue so the result can be cached
|
||||
if (this.retryer) {
|
||||
if (this.retryer.isTransportCancelable || this.abortSignalConsumed) {
|
||||
this.retryer.cancel({
|
||||
revert: true
|
||||
});
|
||||
} else {
|
||||
this.retryer.cancelRetry();
|
||||
}
|
||||
}
|
||||
|
||||
if (this.cacheTime) {
|
||||
this.scheduleGc();
|
||||
} else {
|
||||
this.cache.remove(this);
|
||||
}
|
||||
}
|
||||
|
||||
this.cache.notify({
|
||||
type: 'observerRemoved',
|
||||
query: this,
|
||||
observer: observer
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
_proto.getObserversCount = function getObserversCount() {
|
||||
return this.observers.length;
|
||||
};
|
||||
|
||||
_proto.invalidate = function invalidate() {
|
||||
if (!this.state.isInvalidated) {
|
||||
this.dispatch({
|
||||
type: 'invalidate'
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
_proto.fetch = function fetch(options, fetchOptions) {
|
||||
var _this2 = this,
|
||||
_this$options$behavio,
|
||||
_context$fetchOptions,
|
||||
_abortController$abor;
|
||||
|
||||
if (this.state.isFetching) {
|
||||
if (this.state.dataUpdatedAt && (fetchOptions == null ? void 0 : fetchOptions.cancelRefetch)) {
|
||||
// Silently cancel current fetch if the user wants to cancel refetches
|
||||
this.cancel({
|
||||
silent: true
|
||||
});
|
||||
} else if (this.promise) {
|
||||
var _this$retryer4;
|
||||
|
||||
// make sure that retries that were potentially cancelled due to unmounts can continue
|
||||
(_this$retryer4 = this.retryer) == null ? void 0 : _this$retryer4.continueRetry(); // Return current promise if we are already fetching
|
||||
|
||||
return this.promise;
|
||||
}
|
||||
} // Update config if passed, otherwise the config from the last execution is used
|
||||
|
||||
|
||||
if (options) {
|
||||
this.setOptions(options);
|
||||
} // Use the options from the first observer with a query function if no function is found.
|
||||
// This can happen when the query is hydrated or created with setQueryData.
|
||||
|
||||
|
||||
if (!this.options.queryFn) {
|
||||
var observer = this.observers.find(function (x) {
|
||||
return x.options.queryFn;
|
||||
});
|
||||
|
||||
if (observer) {
|
||||
this.setOptions(observer.options);
|
||||
}
|
||||
}
|
||||
|
||||
var queryKey = ensureQueryKeyArray(this.queryKey);
|
||||
var abortController = getAbortController(); // Create query function context
|
||||
|
||||
var queryFnContext = {
|
||||
queryKey: queryKey,
|
||||
pageParam: undefined,
|
||||
meta: this.meta
|
||||
};
|
||||
Object.defineProperty(queryFnContext, 'signal', {
|
||||
enumerable: true,
|
||||
get: function get() {
|
||||
if (abortController) {
|
||||
_this2.abortSignalConsumed = true;
|
||||
return abortController.signal;
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
}); // Create fetch function
|
||||
|
||||
var fetchFn = function fetchFn() {
|
||||
if (!_this2.options.queryFn) {
|
||||
return Promise.reject('Missing queryFn');
|
||||
}
|
||||
|
||||
_this2.abortSignalConsumed = false;
|
||||
return _this2.options.queryFn(queryFnContext);
|
||||
}; // Trigger behavior hook
|
||||
|
||||
|
||||
var context = {
|
||||
fetchOptions: fetchOptions,
|
||||
options: this.options,
|
||||
queryKey: queryKey,
|
||||
state: this.state,
|
||||
fetchFn: fetchFn,
|
||||
meta: this.meta
|
||||
};
|
||||
|
||||
if ((_this$options$behavio = this.options.behavior) == null ? void 0 : _this$options$behavio.onFetch) {
|
||||
var _this$options$behavio2;
|
||||
|
||||
(_this$options$behavio2 = this.options.behavior) == null ? void 0 : _this$options$behavio2.onFetch(context);
|
||||
} // Store state in case the current fetch needs to be reverted
|
||||
|
||||
|
||||
this.revertState = this.state; // Set to fetching state if not already in it
|
||||
|
||||
if (!this.state.isFetching || this.state.fetchMeta !== ((_context$fetchOptions = context.fetchOptions) == null ? void 0 : _context$fetchOptions.meta)) {
|
||||
var _context$fetchOptions2;
|
||||
|
||||
this.dispatch({
|
||||
type: 'fetch',
|
||||
meta: (_context$fetchOptions2 = context.fetchOptions) == null ? void 0 : _context$fetchOptions2.meta
|
||||
});
|
||||
} // Try to fetch the data
|
||||
|
||||
|
||||
this.retryer = new Retryer({
|
||||
fn: context.fetchFn,
|
||||
abort: abortController == null ? void 0 : (_abortController$abor = abortController.abort) == null ? void 0 : _abortController$abor.bind(abortController),
|
||||
onSuccess: function onSuccess(data) {
|
||||
_this2.setData(data); // Notify cache callback
|
||||
|
||||
|
||||
_this2.cache.config.onSuccess == null ? void 0 : _this2.cache.config.onSuccess(data, _this2); // Remove query after fetching if cache time is 0
|
||||
|
||||
if (_this2.cacheTime === 0) {
|
||||
_this2.optionalRemove();
|
||||
}
|
||||
},
|
||||
onError: function onError(error) {
|
||||
// Optimistically update state if needed
|
||||
if (!(isCancelledError(error) && error.silent)) {
|
||||
_this2.dispatch({
|
||||
type: 'error',
|
||||
error: error
|
||||
});
|
||||
}
|
||||
|
||||
if (!isCancelledError(error)) {
|
||||
// Notify cache callback
|
||||
_this2.cache.config.onError == null ? void 0 : _this2.cache.config.onError(error, _this2); // Log error
|
||||
|
||||
getLogger().error(error);
|
||||
} // Remove query after fetching if cache time is 0
|
||||
|
||||
|
||||
if (_this2.cacheTime === 0) {
|
||||
_this2.optionalRemove();
|
||||
}
|
||||
},
|
||||
onFail: function onFail() {
|
||||
_this2.dispatch({
|
||||
type: 'failed'
|
||||
});
|
||||
},
|
||||
onPause: function onPause() {
|
||||
_this2.dispatch({
|
||||
type: 'pause'
|
||||
});
|
||||
},
|
||||
onContinue: function onContinue() {
|
||||
_this2.dispatch({
|
||||
type: 'continue'
|
||||
});
|
||||
},
|
||||
retry: context.options.retry,
|
||||
retryDelay: context.options.retryDelay
|
||||
});
|
||||
this.promise = this.retryer.promise;
|
||||
return this.promise;
|
||||
};
|
||||
|
||||
_proto.dispatch = function dispatch(action) {
|
||||
var _this3 = this;
|
||||
|
||||
this.state = this.reducer(this.state, action);
|
||||
notifyManager.batch(function () {
|
||||
_this3.observers.forEach(function (observer) {
|
||||
observer.onQueryUpdate(action);
|
||||
});
|
||||
|
||||
_this3.cache.notify({
|
||||
query: _this3,
|
||||
type: 'queryUpdated',
|
||||
action: action
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
_proto.getDefaultState = function getDefaultState(options) {
|
||||
var data = typeof options.initialData === 'function' ? options.initialData() : options.initialData;
|
||||
var hasInitialData = typeof options.initialData !== 'undefined';
|
||||
var initialDataUpdatedAt = hasInitialData ? typeof options.initialDataUpdatedAt === 'function' ? options.initialDataUpdatedAt() : options.initialDataUpdatedAt : 0;
|
||||
var hasData = typeof data !== 'undefined';
|
||||
return {
|
||||
data: data,
|
||||
dataUpdateCount: 0,
|
||||
dataUpdatedAt: hasData ? initialDataUpdatedAt != null ? initialDataUpdatedAt : Date.now() : 0,
|
||||
error: null,
|
||||
errorUpdateCount: 0,
|
||||
errorUpdatedAt: 0,
|
||||
fetchFailureCount: 0,
|
||||
fetchMeta: null,
|
||||
isFetching: false,
|
||||
isInvalidated: false,
|
||||
isPaused: false,
|
||||
status: hasData ? 'success' : 'idle'
|
||||
};
|
||||
};
|
||||
|
||||
_proto.reducer = function reducer(state, action) {
|
||||
var _action$meta, _action$dataUpdatedAt;
|
||||
|
||||
switch (action.type) {
|
||||
case 'failed':
|
||||
return _extends({}, state, {
|
||||
fetchFailureCount: state.fetchFailureCount + 1
|
||||
});
|
||||
|
||||
case 'pause':
|
||||
return _extends({}, state, {
|
||||
isPaused: true
|
||||
});
|
||||
|
||||
case 'continue':
|
||||
return _extends({}, state, {
|
||||
isPaused: false
|
||||
});
|
||||
|
||||
case 'fetch':
|
||||
return _extends({}, state, {
|
||||
fetchFailureCount: 0,
|
||||
fetchMeta: (_action$meta = action.meta) != null ? _action$meta : null,
|
||||
isFetching: true,
|
||||
isPaused: false
|
||||
}, !state.dataUpdatedAt && {
|
||||
error: null,
|
||||
status: 'loading'
|
||||
});
|
||||
|
||||
case 'success':
|
||||
return _extends({}, state, {
|
||||
data: action.data,
|
||||
dataUpdateCount: state.dataUpdateCount + 1,
|
||||
dataUpdatedAt: (_action$dataUpdatedAt = action.dataUpdatedAt) != null ? _action$dataUpdatedAt : Date.now(),
|
||||
error: null,
|
||||
fetchFailureCount: 0,
|
||||
isFetching: false,
|
||||
isInvalidated: false,
|
||||
isPaused: false,
|
||||
status: 'success'
|
||||
});
|
||||
|
||||
case 'error':
|
||||
var error = action.error;
|
||||
|
||||
if (isCancelledError(error) && error.revert && this.revertState) {
|
||||
return _extends({}, this.revertState);
|
||||
}
|
||||
|
||||
return _extends({}, state, {
|
||||
error: error,
|
||||
errorUpdateCount: state.errorUpdateCount + 1,
|
||||
errorUpdatedAt: Date.now(),
|
||||
fetchFailureCount: state.fetchFailureCount + 1,
|
||||
isFetching: false,
|
||||
isPaused: false,
|
||||
status: 'error'
|
||||
});
|
||||
|
||||
case 'invalidate':
|
||||
return _extends({}, state, {
|
||||
isInvalidated: true
|
||||
});
|
||||
|
||||
case 'setState':
|
||||
return _extends({}, state, action.state);
|
||||
|
||||
default:
|
||||
return state;
|
||||
}
|
||||
};
|
||||
|
||||
return Query;
|
||||
}();
|
||||
|
||||
// CLASS
|
||||
var QueryCache = /*#__PURE__*/function (_Subscribable) {
|
||||
_inheritsLoose(QueryCache, _Subscribable);
|
||||
|
||||
function QueryCache(config) {
|
||||
var _this;
|
||||
|
||||
_this = _Subscribable.call(this) || this;
|
||||
_this.config = config || {};
|
||||
_this.queries = [];
|
||||
_this.queriesMap = {};
|
||||
return _this;
|
||||
}
|
||||
|
||||
var _proto = QueryCache.prototype;
|
||||
|
||||
_proto.build = function build(client, options, state) {
|
||||
var _options$queryHash;
|
||||
|
||||
var queryKey = options.queryKey;
|
||||
var queryHash = (_options$queryHash = options.queryHash) != null ? _options$queryHash : hashQueryKeyByOptions(queryKey, options);
|
||||
var query = this.get(queryHash);
|
||||
|
||||
if (!query) {
|
||||
query = new Query({
|
||||
cache: this,
|
||||
queryKey: queryKey,
|
||||
queryHash: queryHash,
|
||||
options: client.defaultQueryOptions(options),
|
||||
state: state,
|
||||
defaultOptions: client.getQueryDefaults(queryKey),
|
||||
meta: options.meta
|
||||
});
|
||||
this.add(query);
|
||||
}
|
||||
|
||||
return query;
|
||||
};
|
||||
|
||||
_proto.add = function add(query) {
|
||||
if (!this.queriesMap[query.queryHash]) {
|
||||
this.queriesMap[query.queryHash] = query;
|
||||
this.queries.push(query);
|
||||
this.notify({
|
||||
type: 'queryAdded',
|
||||
query: query
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
_proto.remove = function remove(query) {
|
||||
var queryInMap = this.queriesMap[query.queryHash];
|
||||
|
||||
if (queryInMap) {
|
||||
query.destroy();
|
||||
this.queries = this.queries.filter(function (x) {
|
||||
return x !== query;
|
||||
});
|
||||
|
||||
if (queryInMap === query) {
|
||||
delete this.queriesMap[query.queryHash];
|
||||
}
|
||||
|
||||
this.notify({
|
||||
type: 'queryRemoved',
|
||||
query: query
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
_proto.clear = function clear() {
|
||||
var _this2 = this;
|
||||
|
||||
notifyManager.batch(function () {
|
||||
_this2.queries.forEach(function (query) {
|
||||
_this2.remove(query);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
_proto.get = function get(queryHash) {
|
||||
return this.queriesMap[queryHash];
|
||||
};
|
||||
|
||||
_proto.getAll = function getAll() {
|
||||
return this.queries;
|
||||
};
|
||||
|
||||
_proto.find = function find(arg1, arg2) {
|
||||
var _parseFilterArgs = parseFilterArgs(arg1, arg2),
|
||||
filters = _parseFilterArgs[0];
|
||||
|
||||
if (typeof filters.exact === 'undefined') {
|
||||
filters.exact = true;
|
||||
}
|
||||
|
||||
return this.queries.find(function (query) {
|
||||
return matchQuery(filters, query);
|
||||
});
|
||||
};
|
||||
|
||||
_proto.findAll = function findAll(arg1, arg2) {
|
||||
var _parseFilterArgs2 = parseFilterArgs(arg1, arg2),
|
||||
filters = _parseFilterArgs2[0];
|
||||
|
||||
return Object.keys(filters).length > 0 ? this.queries.filter(function (query) {
|
||||
return matchQuery(filters, query);
|
||||
}) : this.queries;
|
||||
};
|
||||
|
||||
_proto.notify = function notify(event) {
|
||||
var _this3 = this;
|
||||
|
||||
notifyManager.batch(function () {
|
||||
_this3.listeners.forEach(function (listener) {
|
||||
listener(event);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
_proto.onFocus = function onFocus() {
|
||||
var _this4 = this;
|
||||
|
||||
notifyManager.batch(function () {
|
||||
_this4.queries.forEach(function (query) {
|
||||
query.onFocus();
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
_proto.onOnline = function onOnline() {
|
||||
var _this5 = this;
|
||||
|
||||
notifyManager.batch(function () {
|
||||
_this5.queries.forEach(function (query) {
|
||||
query.onOnline();
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
return QueryCache;
|
||||
}(Subscribable);
|
||||
|
||||
// CLASS
|
||||
var Mutation = /*#__PURE__*/function () {
|
||||
function Mutation(config) {
|
||||
this.options = _extends({}, config.defaultOptions, config.options);
|
||||
this.mutationId = config.mutationId;
|
||||
this.mutationCache = config.mutationCache;
|
||||
this.observers = [];
|
||||
this.state = config.state || getDefaultState();
|
||||
this.meta = config.meta;
|
||||
}
|
||||
|
||||
var _proto = Mutation.prototype;
|
||||
|
||||
_proto.setState = function setState(state) {
|
||||
this.dispatch({
|
||||
type: 'setState',
|
||||
state: state
|
||||
});
|
||||
};
|
||||
|
||||
_proto.addObserver = function addObserver(observer) {
|
||||
if (this.observers.indexOf(observer) === -1) {
|
||||
this.observers.push(observer);
|
||||
}
|
||||
};
|
||||
|
||||
_proto.removeObserver = function removeObserver(observer) {
|
||||
this.observers = this.observers.filter(function (x) {
|
||||
return x !== observer;
|
||||
});
|
||||
};
|
||||
|
||||
_proto.cancel = function cancel() {
|
||||
if (this.retryer) {
|
||||
this.retryer.cancel();
|
||||
return this.retryer.promise.then(noop).catch(noop);
|
||||
}
|
||||
|
||||
return Promise.resolve();
|
||||
};
|
||||
|
||||
_proto.continue = function _continue() {
|
||||
if (this.retryer) {
|
||||
this.retryer.continue();
|
||||
return this.retryer.promise;
|
||||
}
|
||||
|
||||
return this.execute();
|
||||
};
|
||||
|
||||
_proto.execute = function execute() {
|
||||
var _this = this;
|
||||
|
||||
var data;
|
||||
var restored = this.state.status === 'loading';
|
||||
var promise = Promise.resolve();
|
||||
|
||||
if (!restored) {
|
||||
this.dispatch({
|
||||
type: 'loading',
|
||||
variables: this.options.variables
|
||||
});
|
||||
promise = promise.then(function () {
|
||||
// Notify cache callback
|
||||
_this.mutationCache.config.onMutate == null ? void 0 : _this.mutationCache.config.onMutate(_this.state.variables, _this);
|
||||
}).then(function () {
|
||||
return _this.options.onMutate == null ? void 0 : _this.options.onMutate(_this.state.variables);
|
||||
}).then(function (context) {
|
||||
if (context !== _this.state.context) {
|
||||
_this.dispatch({
|
||||
type: 'loading',
|
||||
context: context,
|
||||
variables: _this.state.variables
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return promise.then(function () {
|
||||
return _this.executeMutation();
|
||||
}).then(function (result) {
|
||||
data = result; // Notify cache callback
|
||||
|
||||
_this.mutationCache.config.onSuccess == null ? void 0 : _this.mutationCache.config.onSuccess(data, _this.state.variables, _this.state.context, _this);
|
||||
}).then(function () {
|
||||
return _this.options.onSuccess == null ? void 0 : _this.options.onSuccess(data, _this.state.variables, _this.state.context);
|
||||
}).then(function () {
|
||||
return _this.options.onSettled == null ? void 0 : _this.options.onSettled(data, null, _this.state.variables, _this.state.context);
|
||||
}).then(function () {
|
||||
_this.dispatch({
|
||||
type: 'success',
|
||||
data: data
|
||||
});
|
||||
|
||||
return data;
|
||||
}).catch(function (error) {
|
||||
// Notify cache callback
|
||||
_this.mutationCache.config.onError == null ? void 0 : _this.mutationCache.config.onError(error, _this.state.variables, _this.state.context, _this); // Log error
|
||||
|
||||
getLogger().error(error);
|
||||
return Promise.resolve().then(function () {
|
||||
return _this.options.onError == null ? void 0 : _this.options.onError(error, _this.state.variables, _this.state.context);
|
||||
}).then(function () {
|
||||
return _this.options.onSettled == null ? void 0 : _this.options.onSettled(undefined, error, _this.state.variables, _this.state.context);
|
||||
}).then(function () {
|
||||
_this.dispatch({
|
||||
type: 'error',
|
||||
error: error
|
||||
});
|
||||
|
||||
throw error;
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
_proto.executeMutation = function executeMutation() {
|
||||
var _this2 = this,
|
||||
_this$options$retry;
|
||||
|
||||
this.retryer = new Retryer({
|
||||
fn: function fn() {
|
||||
if (!_this2.options.mutationFn) {
|
||||
return Promise.reject('No mutationFn found');
|
||||
}
|
||||
|
||||
return _this2.options.mutationFn(_this2.state.variables);
|
||||
},
|
||||
onFail: function onFail() {
|
||||
_this2.dispatch({
|
||||
type: 'failed'
|
||||
});
|
||||
},
|
||||
onPause: function onPause() {
|
||||
_this2.dispatch({
|
||||
type: 'pause'
|
||||
});
|
||||
},
|
||||
onContinue: function onContinue() {
|
||||
_this2.dispatch({
|
||||
type: 'continue'
|
||||
});
|
||||
},
|
||||
retry: (_this$options$retry = this.options.retry) != null ? _this$options$retry : 0,
|
||||
retryDelay: this.options.retryDelay
|
||||
});
|
||||
return this.retryer.promise;
|
||||
};
|
||||
|
||||
_proto.dispatch = function dispatch(action) {
|
||||
var _this3 = this;
|
||||
|
||||
this.state = reducer(this.state, action);
|
||||
notifyManager.batch(function () {
|
||||
_this3.observers.forEach(function (observer) {
|
||||
observer.onMutationUpdate(action);
|
||||
});
|
||||
|
||||
_this3.mutationCache.notify(_this3);
|
||||
});
|
||||
};
|
||||
|
||||
return Mutation;
|
||||
}();
|
||||
function getDefaultState() {
|
||||
return {
|
||||
context: undefined,
|
||||
data: undefined,
|
||||
error: null,
|
||||
failureCount: 0,
|
||||
isPaused: false,
|
||||
status: 'idle',
|
||||
variables: undefined
|
||||
};
|
||||
}
|
||||
|
||||
function reducer(state, action) {
|
||||
switch (action.type) {
|
||||
case 'failed':
|
||||
return _extends({}, state, {
|
||||
failureCount: state.failureCount + 1
|
||||
});
|
||||
|
||||
case 'pause':
|
||||
return _extends({}, state, {
|
||||
isPaused: true
|
||||
});
|
||||
|
||||
case 'continue':
|
||||
return _extends({}, state, {
|
||||
isPaused: false
|
||||
});
|
||||
|
||||
case 'loading':
|
||||
return _extends({}, state, {
|
||||
context: action.context,
|
||||
data: undefined,
|
||||
error: null,
|
||||
isPaused: false,
|
||||
status: 'loading',
|
||||
variables: action.variables
|
||||
});
|
||||
|
||||
case 'success':
|
||||
return _extends({}, state, {
|
||||
data: action.data,
|
||||
error: null,
|
||||
status: 'success',
|
||||
isPaused: false
|
||||
});
|
||||
|
||||
case 'error':
|
||||
return _extends({}, state, {
|
||||
data: undefined,
|
||||
error: action.error,
|
||||
failureCount: state.failureCount + 1,
|
||||
isPaused: false,
|
||||
status: 'error'
|
||||
});
|
||||
|
||||
case 'setState':
|
||||
return _extends({}, state, action.state);
|
||||
|
||||
default:
|
||||
return state;
|
||||
}
|
||||
}
|
||||
|
||||
// CLASS
|
||||
var MutationCache = /*#__PURE__*/function (_Subscribable) {
|
||||
_inheritsLoose(MutationCache, _Subscribable);
|
||||
|
||||
function MutationCache(config) {
|
||||
var _this;
|
||||
|
||||
_this = _Subscribable.call(this) || this;
|
||||
_this.config = config || {};
|
||||
_this.mutations = [];
|
||||
_this.mutationId = 0;
|
||||
return _this;
|
||||
}
|
||||
|
||||
var _proto = MutationCache.prototype;
|
||||
|
||||
_proto.build = function build(client, options, state) {
|
||||
var mutation = new Mutation({
|
||||
mutationCache: this,
|
||||
mutationId: ++this.mutationId,
|
||||
options: client.defaultMutationOptions(options),
|
||||
state: state,
|
||||
defaultOptions: options.mutationKey ? client.getMutationDefaults(options.mutationKey) : undefined,
|
||||
meta: options.meta
|
||||
});
|
||||
this.add(mutation);
|
||||
return mutation;
|
||||
};
|
||||
|
||||
_proto.add = function add(mutation) {
|
||||
this.mutations.push(mutation);
|
||||
this.notify(mutation);
|
||||
};
|
||||
|
||||
_proto.remove = function remove(mutation) {
|
||||
this.mutations = this.mutations.filter(function (x) {
|
||||
return x !== mutation;
|
||||
});
|
||||
mutation.cancel();
|
||||
this.notify(mutation);
|
||||
};
|
||||
|
||||
_proto.clear = function clear() {
|
||||
var _this2 = this;
|
||||
|
||||
notifyManager.batch(function () {
|
||||
_this2.mutations.forEach(function (mutation) {
|
||||
_this2.remove(mutation);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
_proto.getAll = function getAll() {
|
||||
return this.mutations;
|
||||
};
|
||||
|
||||
_proto.find = function find(filters) {
|
||||
if (typeof filters.exact === 'undefined') {
|
||||
filters.exact = true;
|
||||
}
|
||||
|
||||
return this.mutations.find(function (mutation) {
|
||||
return matchMutation(filters, mutation);
|
||||
});
|
||||
};
|
||||
|
||||
_proto.findAll = function findAll(filters) {
|
||||
return this.mutations.filter(function (mutation) {
|
||||
return matchMutation(filters, mutation);
|
||||
});
|
||||
};
|
||||
|
||||
_proto.notify = function notify(mutation) {
|
||||
var _this3 = this;
|
||||
|
||||
notifyManager.batch(function () {
|
||||
_this3.listeners.forEach(function (listener) {
|
||||
listener(mutation);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
_proto.onFocus = function onFocus() {
|
||||
this.resumePausedMutations();
|
||||
};
|
||||
|
||||
_proto.onOnline = function onOnline() {
|
||||
this.resumePausedMutations();
|
||||
};
|
||||
|
||||
_proto.resumePausedMutations = function resumePausedMutations() {
|
||||
var pausedMutations = this.mutations.filter(function (x) {
|
||||
return x.state.isPaused;
|
||||
});
|
||||
return notifyManager.batch(function () {
|
||||
return pausedMutations.reduce(function (promise, mutation) {
|
||||
return promise.then(function () {
|
||||
return mutation.continue().catch(noop);
|
||||
});
|
||||
}, Promise.resolve());
|
||||
});
|
||||
};
|
||||
|
||||
return MutationCache;
|
||||
}(Subscribable);
|
||||
|
||||
function infiniteQueryBehavior() {
|
||||
return {
|
||||
onFetch: function onFetch(context) {
|
||||
context.fetchFn = function () {
|
||||
var _context$fetchOptions, _context$fetchOptions2, _context$fetchOptions3, _context$fetchOptions4, _context$state$data, _context$state$data2;
|
||||
|
||||
var refetchPage = (_context$fetchOptions = context.fetchOptions) == null ? void 0 : (_context$fetchOptions2 = _context$fetchOptions.meta) == null ? void 0 : _context$fetchOptions2.refetchPage;
|
||||
var fetchMore = (_context$fetchOptions3 = context.fetchOptions) == null ? void 0 : (_context$fetchOptions4 = _context$fetchOptions3.meta) == null ? void 0 : _context$fetchOptions4.fetchMore;
|
||||
var pageParam = fetchMore == null ? void 0 : fetchMore.pageParam;
|
||||
var isFetchingNextPage = (fetchMore == null ? void 0 : fetchMore.direction) === 'forward';
|
||||
var isFetchingPreviousPage = (fetchMore == null ? void 0 : fetchMore.direction) === 'backward';
|
||||
var oldPages = ((_context$state$data = context.state.data) == null ? void 0 : _context$state$data.pages) || [];
|
||||
var oldPageParams = ((_context$state$data2 = context.state.data) == null ? void 0 : _context$state$data2.pageParams) || [];
|
||||
var abortController = getAbortController();
|
||||
var abortSignal = abortController == null ? void 0 : abortController.signal;
|
||||
var newPageParams = oldPageParams;
|
||||
var cancelled = false; // Get query function
|
||||
|
||||
var queryFn = context.options.queryFn || function () {
|
||||
return Promise.reject('Missing queryFn');
|
||||
};
|
||||
|
||||
var buildNewPages = function buildNewPages(pages, param, page, previous) {
|
||||
newPageParams = previous ? [param].concat(newPageParams) : [].concat(newPageParams, [param]);
|
||||
return previous ? [page].concat(pages) : [].concat(pages, [page]);
|
||||
}; // Create function to fetch a page
|
||||
|
||||
|
||||
var fetchPage = function fetchPage(pages, manual, param, previous) {
|
||||
if (cancelled) {
|
||||
return Promise.reject('Cancelled');
|
||||
}
|
||||
|
||||
if (typeof param === 'undefined' && !manual && pages.length) {
|
||||
return Promise.resolve(pages);
|
||||
}
|
||||
|
||||
var queryFnContext = {
|
||||
queryKey: context.queryKey,
|
||||
signal: abortSignal,
|
||||
pageParam: param,
|
||||
meta: context.meta
|
||||
};
|
||||
var queryFnResult = queryFn(queryFnContext);
|
||||
var promise = Promise.resolve(queryFnResult).then(function (page) {
|
||||
return buildNewPages(pages, param, page, previous);
|
||||
});
|
||||
|
||||
if (isCancelable(queryFnResult)) {
|
||||
var promiseAsAny = promise;
|
||||
promiseAsAny.cancel = queryFnResult.cancel;
|
||||
}
|
||||
|
||||
return promise;
|
||||
};
|
||||
|
||||
var promise; // Fetch first page?
|
||||
|
||||
if (!oldPages.length) {
|
||||
promise = fetchPage([]);
|
||||
} // Fetch next page?
|
||||
else if (isFetchingNextPage) {
|
||||
var manual = typeof pageParam !== 'undefined';
|
||||
var param = manual ? pageParam : getNextPageParam(context.options, oldPages);
|
||||
promise = fetchPage(oldPages, manual, param);
|
||||
} // Fetch previous page?
|
||||
else if (isFetchingPreviousPage) {
|
||||
var _manual = typeof pageParam !== 'undefined';
|
||||
|
||||
var _param = _manual ? pageParam : getPreviousPageParam(context.options, oldPages);
|
||||
|
||||
promise = fetchPage(oldPages, _manual, _param, true);
|
||||
} // Refetch pages
|
||||
else {
|
||||
(function () {
|
||||
newPageParams = [];
|
||||
var manual = typeof context.options.getNextPageParam === 'undefined';
|
||||
var shouldFetchFirstPage = refetchPage && oldPages[0] ? refetchPage(oldPages[0], 0, oldPages) : true; // Fetch first page
|
||||
|
||||
promise = shouldFetchFirstPage ? fetchPage([], manual, oldPageParams[0]) : Promise.resolve(buildNewPages([], oldPageParams[0], oldPages[0])); // Fetch remaining pages
|
||||
|
||||
var _loop = function _loop(i) {
|
||||
promise = promise.then(function (pages) {
|
||||
var shouldFetchNextPage = refetchPage && oldPages[i] ? refetchPage(oldPages[i], i, oldPages) : true;
|
||||
|
||||
if (shouldFetchNextPage) {
|
||||
var _param2 = manual ? oldPageParams[i] : getNextPageParam(context.options, pages);
|
||||
|
||||
return fetchPage(pages, manual, _param2);
|
||||
}
|
||||
|
||||
return Promise.resolve(buildNewPages(pages, oldPageParams[i], oldPages[i]));
|
||||
});
|
||||
};
|
||||
|
||||
for (var i = 1; i < oldPages.length; i++) {
|
||||
_loop(i);
|
||||
}
|
||||
})();
|
||||
}
|
||||
|
||||
var finalPromise = promise.then(function (pages) {
|
||||
return {
|
||||
pages: pages,
|
||||
pageParams: newPageParams
|
||||
};
|
||||
});
|
||||
var finalPromiseAsAny = finalPromise;
|
||||
|
||||
finalPromiseAsAny.cancel = function () {
|
||||
cancelled = true;
|
||||
abortController == null ? void 0 : abortController.abort();
|
||||
|
||||
if (isCancelable(promise)) {
|
||||
promise.cancel();
|
||||
}
|
||||
};
|
||||
|
||||
return finalPromise;
|
||||
};
|
||||
}
|
||||
};
|
||||
}
|
||||
function getNextPageParam(options, pages) {
|
||||
return options.getNextPageParam == null ? void 0 : options.getNextPageParam(pages[pages.length - 1], pages);
|
||||
}
|
||||
function getPreviousPageParam(options, pages) {
|
||||
return options.getPreviousPageParam == null ? void 0 : options.getPreviousPageParam(pages[0], pages);
|
||||
}
|
||||
/**
|
||||
* Checks if there is a next page.
|
||||
* Returns `undefined` if it cannot be determined.
|
||||
*/
|
||||
|
||||
function hasNextPage(options, pages) {
|
||||
if (options.getNextPageParam && Array.isArray(pages)) {
|
||||
var nextPageParam = getNextPageParam(options, pages);
|
||||
return typeof nextPageParam !== 'undefined' && nextPageParam !== null && nextPageParam !== false;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Checks if there is a previous page.
|
||||
* Returns `undefined` if it cannot be determined.
|
||||
*/
|
||||
|
||||
function hasPreviousPage(options, pages) {
|
||||
if (options.getPreviousPageParam && Array.isArray(pages)) {
|
||||
var previousPageParam = getPreviousPageParam(options, pages);
|
||||
return typeof previousPageParam !== 'undefined' && previousPageParam !== null && previousPageParam !== false;
|
||||
}
|
||||
}
|
||||
|
||||
// CLASS
|
||||
var QueryClient = /*#__PURE__*/function () {
|
||||
function QueryClient(config) {
|
||||
if (config === void 0) {
|
||||
config = {};
|
||||
}
|
||||
|
||||
this.queryCache = config.queryCache || new QueryCache();
|
||||
this.mutationCache = config.mutationCache || new MutationCache();
|
||||
this.defaultOptions = config.defaultOptions || {};
|
||||
this.queryDefaults = [];
|
||||
this.mutationDefaults = [];
|
||||
}
|
||||
|
||||
var _proto = QueryClient.prototype;
|
||||
|
||||
_proto.mount = function mount() {
|
||||
var _this = this;
|
||||
|
||||
this.unsubscribeFocus = focusManager.subscribe(function () {
|
||||
if (focusManager.isFocused() && onlineManager.isOnline()) {
|
||||
_this.mutationCache.onFocus();
|
||||
|
||||
_this.queryCache.onFocus();
|
||||
}
|
||||
});
|
||||
this.unsubscribeOnline = onlineManager.subscribe(function () {
|
||||
if (focusManager.isFocused() && onlineManager.isOnline()) {
|
||||
_this.mutationCache.onOnline();
|
||||
|
||||
_this.queryCache.onOnline();
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
_proto.unmount = function unmount() {
|
||||
var _this$unsubscribeFocu, _this$unsubscribeOnli;
|
||||
|
||||
(_this$unsubscribeFocu = this.unsubscribeFocus) == null ? void 0 : _this$unsubscribeFocu.call(this);
|
||||
(_this$unsubscribeOnli = this.unsubscribeOnline) == null ? void 0 : _this$unsubscribeOnli.call(this);
|
||||
};
|
||||
|
||||
_proto.isFetching = function isFetching(arg1, arg2) {
|
||||
var _parseFilterArgs = parseFilterArgs(arg1, arg2),
|
||||
filters = _parseFilterArgs[0];
|
||||
|
||||
filters.fetching = true;
|
||||
return this.queryCache.findAll(filters).length;
|
||||
};
|
||||
|
||||
_proto.isMutating = function isMutating(filters) {
|
||||
return this.mutationCache.findAll(_extends({}, filters, {
|
||||
fetching: true
|
||||
})).length;
|
||||
};
|
||||
|
||||
_proto.getQueryData = function getQueryData(queryKey, filters) {
|
||||
var _this$queryCache$find;
|
||||
|
||||
return (_this$queryCache$find = this.queryCache.find(queryKey, filters)) == null ? void 0 : _this$queryCache$find.state.data;
|
||||
};
|
||||
|
||||
_proto.getQueriesData = function getQueriesData(queryKeyOrFilters) {
|
||||
return this.getQueryCache().findAll(queryKeyOrFilters).map(function (_ref) {
|
||||
var queryKey = _ref.queryKey,
|
||||
state = _ref.state;
|
||||
var data = state.data;
|
||||
return [queryKey, data];
|
||||
});
|
||||
};
|
||||
|
||||
_proto.setQueryData = function setQueryData(queryKey, updater, options) {
|
||||
var parsedOptions = parseQueryArgs(queryKey);
|
||||
var defaultedOptions = this.defaultQueryOptions(parsedOptions);
|
||||
return this.queryCache.build(this, defaultedOptions).setData(updater, options);
|
||||
};
|
||||
|
||||
_proto.setQueriesData = function setQueriesData(queryKeyOrFilters, updater, options) {
|
||||
var _this2 = this;
|
||||
|
||||
return notifyManager.batch(function () {
|
||||
return _this2.getQueryCache().findAll(queryKeyOrFilters).map(function (_ref2) {
|
||||
var queryKey = _ref2.queryKey;
|
||||
return [queryKey, _this2.setQueryData(queryKey, updater, options)];
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
_proto.getQueryState = function getQueryState(queryKey, filters) {
|
||||
var _this$queryCache$find2;
|
||||
|
||||
return (_this$queryCache$find2 = this.queryCache.find(queryKey, filters)) == null ? void 0 : _this$queryCache$find2.state;
|
||||
};
|
||||
|
||||
_proto.removeQueries = function removeQueries(arg1, arg2) {
|
||||
var _parseFilterArgs2 = parseFilterArgs(arg1, arg2),
|
||||
filters = _parseFilterArgs2[0];
|
||||
|
||||
var queryCache = this.queryCache;
|
||||
notifyManager.batch(function () {
|
||||
queryCache.findAll(filters).forEach(function (query) {
|
||||
queryCache.remove(query);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
_proto.resetQueries = function resetQueries(arg1, arg2, arg3) {
|
||||
var _this3 = this;
|
||||
|
||||
var _parseFilterArgs3 = parseFilterArgs(arg1, arg2, arg3),
|
||||
filters = _parseFilterArgs3[0],
|
||||
options = _parseFilterArgs3[1];
|
||||
|
||||
var queryCache = this.queryCache;
|
||||
|
||||
var refetchFilters = _extends({}, filters, {
|
||||
active: true
|
||||
});
|
||||
|
||||
return notifyManager.batch(function () {
|
||||
queryCache.findAll(filters).forEach(function (query) {
|
||||
query.reset();
|
||||
});
|
||||
return _this3.refetchQueries(refetchFilters, options);
|
||||
});
|
||||
};
|
||||
|
||||
_proto.cancelQueries = function cancelQueries(arg1, arg2, arg3) {
|
||||
var _this4 = this;
|
||||
|
||||
var _parseFilterArgs4 = parseFilterArgs(arg1, arg2, arg3),
|
||||
filters = _parseFilterArgs4[0],
|
||||
_parseFilterArgs4$ = _parseFilterArgs4[1],
|
||||
cancelOptions = _parseFilterArgs4$ === void 0 ? {} : _parseFilterArgs4$;
|
||||
|
||||
if (typeof cancelOptions.revert === 'undefined') {
|
||||
cancelOptions.revert = true;
|
||||
}
|
||||
|
||||
var promises = notifyManager.batch(function () {
|
||||
return _this4.queryCache.findAll(filters).map(function (query) {
|
||||
return query.cancel(cancelOptions);
|
||||
});
|
||||
});
|
||||
return Promise.all(promises).then(noop).catch(noop);
|
||||
};
|
||||
|
||||
_proto.invalidateQueries = function invalidateQueries(arg1, arg2, arg3) {
|
||||
var _ref3,
|
||||
_filters$refetchActiv,
|
||||
_filters$refetchInact,
|
||||
_this5 = this;
|
||||
|
||||
var _parseFilterArgs5 = parseFilterArgs(arg1, arg2, arg3),
|
||||
filters = _parseFilterArgs5[0],
|
||||
options = _parseFilterArgs5[1];
|
||||
|
||||
var refetchFilters = _extends({}, filters, {
|
||||
// if filters.refetchActive is not provided and filters.active is explicitly false,
|
||||
// e.g. invalidateQueries({ active: false }), we don't want to refetch active queries
|
||||
active: (_ref3 = (_filters$refetchActiv = filters.refetchActive) != null ? _filters$refetchActiv : filters.active) != null ? _ref3 : true,
|
||||
inactive: (_filters$refetchInact = filters.refetchInactive) != null ? _filters$refetchInact : false
|
||||
});
|
||||
|
||||
return notifyManager.batch(function () {
|
||||
_this5.queryCache.findAll(filters).forEach(function (query) {
|
||||
query.invalidate();
|
||||
});
|
||||
|
||||
return _this5.refetchQueries(refetchFilters, options);
|
||||
});
|
||||
};
|
||||
|
||||
_proto.refetchQueries = function refetchQueries(arg1, arg2, arg3) {
|
||||
var _this6 = this;
|
||||
|
||||
var _parseFilterArgs6 = parseFilterArgs(arg1, arg2, arg3),
|
||||
filters = _parseFilterArgs6[0],
|
||||
options = _parseFilterArgs6[1];
|
||||
|
||||
var promises = notifyManager.batch(function () {
|
||||
return _this6.queryCache.findAll(filters).map(function (query) {
|
||||
return query.fetch(undefined, _extends({}, options, {
|
||||
meta: {
|
||||
refetchPage: filters == null ? void 0 : filters.refetchPage
|
||||
}
|
||||
}));
|
||||
});
|
||||
});
|
||||
var promise = Promise.all(promises).then(noop);
|
||||
|
||||
if (!(options == null ? void 0 : options.throwOnError)) {
|
||||
promise = promise.catch(noop);
|
||||
}
|
||||
|
||||
return promise;
|
||||
};
|
||||
|
||||
_proto.fetchQuery = function fetchQuery(arg1, arg2, arg3) {
|
||||
var parsedOptions = parseQueryArgs(arg1, arg2, arg3);
|
||||
var defaultedOptions = this.defaultQueryOptions(parsedOptions); // https://github.com/tannerlinsley/react-query/issues/652
|
||||
|
||||
if (typeof defaultedOptions.retry === 'undefined') {
|
||||
defaultedOptions.retry = false;
|
||||
}
|
||||
|
||||
var query = this.queryCache.build(this, defaultedOptions);
|
||||
return query.isStaleByTime(defaultedOptions.staleTime) ? query.fetch(defaultedOptions) : Promise.resolve(query.state.data);
|
||||
};
|
||||
|
||||
_proto.prefetchQuery = function prefetchQuery(arg1, arg2, arg3) {
|
||||
return this.fetchQuery(arg1, arg2, arg3).then(noop).catch(noop);
|
||||
};
|
||||
|
||||
_proto.fetchInfiniteQuery = function fetchInfiniteQuery(arg1, arg2, arg3) {
|
||||
var parsedOptions = parseQueryArgs(arg1, arg2, arg3);
|
||||
parsedOptions.behavior = infiniteQueryBehavior();
|
||||
return this.fetchQuery(parsedOptions);
|
||||
};
|
||||
|
||||
_proto.prefetchInfiniteQuery = function prefetchInfiniteQuery(arg1, arg2, arg3) {
|
||||
return this.fetchInfiniteQuery(arg1, arg2, arg3).then(noop).catch(noop);
|
||||
};
|
||||
|
||||
_proto.cancelMutations = function cancelMutations() {
|
||||
var _this7 = this;
|
||||
|
||||
var promises = notifyManager.batch(function () {
|
||||
return _this7.mutationCache.getAll().map(function (mutation) {
|
||||
return mutation.cancel();
|
||||
});
|
||||
});
|
||||
return Promise.all(promises).then(noop).catch(noop);
|
||||
};
|
||||
|
||||
_proto.resumePausedMutations = function resumePausedMutations() {
|
||||
return this.getMutationCache().resumePausedMutations();
|
||||
};
|
||||
|
||||
_proto.executeMutation = function executeMutation(options) {
|
||||
return this.mutationCache.build(this, options).execute();
|
||||
};
|
||||
|
||||
_proto.getQueryCache = function getQueryCache() {
|
||||
return this.queryCache;
|
||||
};
|
||||
|
||||
_proto.getMutationCache = function getMutationCache() {
|
||||
return this.mutationCache;
|
||||
};
|
||||
|
||||
_proto.getDefaultOptions = function getDefaultOptions() {
|
||||
return this.defaultOptions;
|
||||
};
|
||||
|
||||
_proto.setDefaultOptions = function setDefaultOptions(options) {
|
||||
this.defaultOptions = options;
|
||||
};
|
||||
|
||||
_proto.setQueryDefaults = function setQueryDefaults(queryKey, options) {
|
||||
var result = this.queryDefaults.find(function (x) {
|
||||
return hashQueryKey(queryKey) === hashQueryKey(x.queryKey);
|
||||
});
|
||||
|
||||
if (result) {
|
||||
result.defaultOptions = options;
|
||||
} else {
|
||||
this.queryDefaults.push({
|
||||
queryKey: queryKey,
|
||||
defaultOptions: options
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
_proto.getQueryDefaults = function getQueryDefaults(queryKey) {
|
||||
var _this$queryDefaults$f;
|
||||
|
||||
return queryKey ? (_this$queryDefaults$f = this.queryDefaults.find(function (x) {
|
||||
return partialMatchKey(queryKey, x.queryKey);
|
||||
})) == null ? void 0 : _this$queryDefaults$f.defaultOptions : undefined;
|
||||
};
|
||||
|
||||
_proto.setMutationDefaults = function setMutationDefaults(mutationKey, options) {
|
||||
var result = this.mutationDefaults.find(function (x) {
|
||||
return hashQueryKey(mutationKey) === hashQueryKey(x.mutationKey);
|
||||
});
|
||||
|
||||
if (result) {
|
||||
result.defaultOptions = options;
|
||||
} else {
|
||||
this.mutationDefaults.push({
|
||||
mutationKey: mutationKey,
|
||||
defaultOptions: options
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
_proto.getMutationDefaults = function getMutationDefaults(mutationKey) {
|
||||
var _this$mutationDefault;
|
||||
|
||||
return mutationKey ? (_this$mutationDefault = this.mutationDefaults.find(function (x) {
|
||||
return partialMatchKey(mutationKey, x.mutationKey);
|
||||
})) == null ? void 0 : _this$mutationDefault.defaultOptions : undefined;
|
||||
};
|
||||
|
||||
_proto.defaultQueryOptions = function defaultQueryOptions(options) {
|
||||
if (options == null ? void 0 : options._defaulted) {
|
||||
return options;
|
||||
}
|
||||
|
||||
var defaultedOptions = _extends({}, this.defaultOptions.queries, this.getQueryDefaults(options == null ? void 0 : options.queryKey), options, {
|
||||
_defaulted: true
|
||||
});
|
||||
|
||||
if (!defaultedOptions.queryHash && defaultedOptions.queryKey) {
|
||||
defaultedOptions.queryHash = hashQueryKeyByOptions(defaultedOptions.queryKey, defaultedOptions);
|
||||
}
|
||||
|
||||
return defaultedOptions;
|
||||
};
|
||||
|
||||
_proto.defaultQueryObserverOptions = function defaultQueryObserverOptions(options) {
|
||||
return this.defaultQueryOptions(options);
|
||||
};
|
||||
|
||||
_proto.defaultMutationOptions = function defaultMutationOptions(options) {
|
||||
if (options == null ? void 0 : options._defaulted) {
|
||||
return options;
|
||||
}
|
||||
|
||||
return _extends({}, this.defaultOptions.mutations, this.getMutationDefaults(options == null ? void 0 : options.mutationKey), options, {
|
||||
_defaulted: true
|
||||
});
|
||||
};
|
||||
|
||||
_proto.clear = function clear() {
|
||||
this.queryCache.clear();
|
||||
this.mutationCache.clear();
|
||||
};
|
||||
|
||||
return QueryClient;
|
||||
}();
|
||||
|
||||
var QueryObserver = /*#__PURE__*/function (_Subscribable) {
|
||||
_inheritsLoose(QueryObserver, _Subscribable);
|
||||
|
||||
function QueryObserver(client, options) {
|
||||
var _this;
|
||||
|
||||
_this = _Subscribable.call(this) || this;
|
||||
_this.client = client;
|
||||
_this.options = options;
|
||||
_this.trackedProps = [];
|
||||
_this.selectError = null;
|
||||
|
||||
_this.bindMethods();
|
||||
|
||||
_this.setOptions(options);
|
||||
|
||||
return _this;
|
||||
}
|
||||
|
||||
var _proto = QueryObserver.prototype;
|
||||
|
||||
_proto.bindMethods = function bindMethods() {
|
||||
this.remove = this.remove.bind(this);
|
||||
this.refetch = this.refetch.bind(this);
|
||||
};
|
||||
|
||||
_proto.onSubscribe = function onSubscribe() {
|
||||
if (this.listeners.length === 1) {
|
||||
this.currentQuery.addObserver(this);
|
||||
|
||||
if (shouldFetchOnMount(this.currentQuery, this.options)) {
|
||||
this.executeFetch();
|
||||
}
|
||||
|
||||
this.updateTimers();
|
||||
}
|
||||
};
|
||||
|
||||
_proto.onUnsubscribe = function onUnsubscribe() {
|
||||
if (!this.listeners.length) {
|
||||
this.destroy();
|
||||
}
|
||||
};
|
||||
|
||||
_proto.shouldFetchOnReconnect = function shouldFetchOnReconnect() {
|
||||
return shouldFetchOn(this.currentQuery, this.options, this.options.refetchOnReconnect);
|
||||
};
|
||||
|
||||
_proto.shouldFetchOnWindowFocus = function shouldFetchOnWindowFocus() {
|
||||
return shouldFetchOn(this.currentQuery, this.options, this.options.refetchOnWindowFocus);
|
||||
};
|
||||
|
||||
_proto.destroy = function destroy() {
|
||||
this.listeners = [];
|
||||
this.clearTimers();
|
||||
this.currentQuery.removeObserver(this);
|
||||
};
|
||||
|
||||
_proto.setOptions = function setOptions(options, notifyOptions) {
|
||||
var prevOptions = this.options;
|
||||
var prevQuery = this.currentQuery;
|
||||
this.options = this.client.defaultQueryObserverOptions(options);
|
||||
|
||||
if (typeof this.options.enabled !== 'undefined' && typeof this.options.enabled !== 'boolean') {
|
||||
throw new Error('Expected enabled to be a boolean');
|
||||
} // Keep previous query key if the user does not supply one
|
||||
|
||||
|
||||
if (!this.options.queryKey) {
|
||||
this.options.queryKey = prevOptions.queryKey;
|
||||
}
|
||||
|
||||
this.updateQuery();
|
||||
var mounted = this.hasListeners(); // Fetch if there are subscribers
|
||||
|
||||
if (mounted && shouldFetchOptionally(this.currentQuery, prevQuery, this.options, prevOptions)) {
|
||||
this.executeFetch();
|
||||
} // Update result
|
||||
|
||||
|
||||
this.updateResult(notifyOptions); // Update stale interval if needed
|
||||
|
||||
if (mounted && (this.currentQuery !== prevQuery || this.options.enabled !== prevOptions.enabled || this.options.staleTime !== prevOptions.staleTime)) {
|
||||
this.updateStaleTimeout();
|
||||
}
|
||||
|
||||
var nextRefetchInterval = this.computeRefetchInterval(); // Update refetch interval if needed
|
||||
|
||||
if (mounted && (this.currentQuery !== prevQuery || this.options.enabled !== prevOptions.enabled || nextRefetchInterval !== this.currentRefetchInterval)) {
|
||||
this.updateRefetchInterval(nextRefetchInterval);
|
||||
}
|
||||
};
|
||||
|
||||
_proto.getOptimisticResult = function getOptimisticResult(options) {
|
||||
var defaultedOptions = this.client.defaultQueryObserverOptions(options);
|
||||
var query = this.client.getQueryCache().build(this.client, defaultedOptions);
|
||||
return this.createResult(query, defaultedOptions);
|
||||
};
|
||||
|
||||
_proto.getCurrentResult = function getCurrentResult() {
|
||||
return this.currentResult;
|
||||
};
|
||||
|
||||
_proto.trackResult = function trackResult(result, defaultedOptions) {
|
||||
var _this2 = this;
|
||||
|
||||
var trackedResult = {};
|
||||
|
||||
var trackProp = function trackProp(key) {
|
||||
if (!_this2.trackedProps.includes(key)) {
|
||||
_this2.trackedProps.push(key);
|
||||
}
|
||||
};
|
||||
|
||||
Object.keys(result).forEach(function (key) {
|
||||
Object.defineProperty(trackedResult, key, {
|
||||
configurable: false,
|
||||
enumerable: true,
|
||||
get: function get() {
|
||||
trackProp(key);
|
||||
return result[key];
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
if (defaultedOptions.useErrorBoundary || defaultedOptions.suspense) {
|
||||
trackProp('error');
|
||||
}
|
||||
|
||||
return trackedResult;
|
||||
};
|
||||
|
||||
_proto.getNextResult = function getNextResult(options) {
|
||||
var _this3 = this;
|
||||
|
||||
return new Promise(function (resolve, reject) {
|
||||
var unsubscribe = _this3.subscribe(function (result) {
|
||||
if (!result.isFetching) {
|
||||
unsubscribe();
|
||||
|
||||
if (result.isError && (options == null ? void 0 : options.throwOnError)) {
|
||||
reject(result.error);
|
||||
} else {
|
||||
resolve(result);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
_proto.getCurrentQuery = function getCurrentQuery() {
|
||||
return this.currentQuery;
|
||||
};
|
||||
|
||||
_proto.remove = function remove() {
|
||||
this.client.getQueryCache().remove(this.currentQuery);
|
||||
};
|
||||
|
||||
_proto.refetch = function refetch(options) {
|
||||
return this.fetch(_extends({}, options, {
|
||||
meta: {
|
||||
refetchPage: options == null ? void 0 : options.refetchPage
|
||||
}
|
||||
}));
|
||||
};
|
||||
|
||||
_proto.fetchOptimistic = function fetchOptimistic(options) {
|
||||
var _this4 = this;
|
||||
|
||||
var defaultedOptions = this.client.defaultQueryObserverOptions(options);
|
||||
var query = this.client.getQueryCache().build(this.client, defaultedOptions);
|
||||
return query.fetch().then(function () {
|
||||
return _this4.createResult(query, defaultedOptions);
|
||||
});
|
||||
};
|
||||
|
||||
_proto.fetch = function fetch(fetchOptions) {
|
||||
var _this5 = this;
|
||||
|
||||
return this.executeFetch(fetchOptions).then(function () {
|
||||
_this5.updateResult();
|
||||
|
||||
return _this5.currentResult;
|
||||
});
|
||||
};
|
||||
|
||||
_proto.executeFetch = function executeFetch(fetchOptions) {
|
||||
// Make sure we reference the latest query as the current one might have been removed
|
||||
this.updateQuery(); // Fetch
|
||||
|
||||
var promise = this.currentQuery.fetch(this.options, fetchOptions);
|
||||
|
||||
if (!(fetchOptions == null ? void 0 : fetchOptions.throwOnError)) {
|
||||
promise = promise.catch(noop);
|
||||
}
|
||||
|
||||
return promise;
|
||||
};
|
||||
|
||||
_proto.updateStaleTimeout = function updateStaleTimeout() {
|
||||
var _this6 = this;
|
||||
|
||||
this.clearStaleTimeout();
|
||||
|
||||
if (isServer || this.currentResult.isStale || !isValidTimeout(this.options.staleTime)) {
|
||||
return;
|
||||
}
|
||||
|
||||
var time = timeUntilStale(this.currentResult.dataUpdatedAt, this.options.staleTime); // The timeout is sometimes triggered 1 ms before the stale time expiration.
|
||||
// To mitigate this issue we always add 1 ms to the timeout.
|
||||
|
||||
var timeout = time + 1;
|
||||
this.staleTimeoutId = setTimeout(function () {
|
||||
if (!_this6.currentResult.isStale) {
|
||||
_this6.updateResult();
|
||||
}
|
||||
}, timeout);
|
||||
};
|
||||
|
||||
_proto.computeRefetchInterval = function computeRefetchInterval() {
|
||||
var _this$options$refetch;
|
||||
|
||||
return typeof this.options.refetchInterval === 'function' ? this.options.refetchInterval(this.currentResult.data, this.currentQuery) : (_this$options$refetch = this.options.refetchInterval) != null ? _this$options$refetch : false;
|
||||
};
|
||||
|
||||
_proto.updateRefetchInterval = function updateRefetchInterval(nextInterval) {
|
||||
var _this7 = this;
|
||||
|
||||
this.clearRefetchInterval();
|
||||
this.currentRefetchInterval = nextInterval;
|
||||
|
||||
if (isServer || this.options.enabled === false || !isValidTimeout(this.currentRefetchInterval) || this.currentRefetchInterval === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.refetchIntervalId = setInterval(function () {
|
||||
if (_this7.options.refetchIntervalInBackground || focusManager.isFocused()) {
|
||||
_this7.executeFetch();
|
||||
}
|
||||
}, this.currentRefetchInterval);
|
||||
};
|
||||
|
||||
_proto.updateTimers = function updateTimers() {
|
||||
this.updateStaleTimeout();
|
||||
this.updateRefetchInterval(this.computeRefetchInterval());
|
||||
};
|
||||
|
||||
_proto.clearTimers = function clearTimers() {
|
||||
this.clearStaleTimeout();
|
||||
this.clearRefetchInterval();
|
||||
};
|
||||
|
||||
_proto.clearStaleTimeout = function clearStaleTimeout() {
|
||||
if (this.staleTimeoutId) {
|
||||
clearTimeout(this.staleTimeoutId);
|
||||
this.staleTimeoutId = undefined;
|
||||
}
|
||||
};
|
||||
|
||||
_proto.clearRefetchInterval = function clearRefetchInterval() {
|
||||
if (this.refetchIntervalId) {
|
||||
clearInterval(this.refetchIntervalId);
|
||||
this.refetchIntervalId = undefined;
|
||||
}
|
||||
};
|
||||
|
||||
_proto.createResult = function createResult(query, options) {
|
||||
var prevQuery = this.currentQuery;
|
||||
var prevOptions = this.options;
|
||||
var prevResult = this.currentResult;
|
||||
var prevResultState = this.currentResultState;
|
||||
var prevResultOptions = this.currentResultOptions;
|
||||
var queryChange = query !== prevQuery;
|
||||
var queryInitialState = queryChange ? query.state : this.currentQueryInitialState;
|
||||
var prevQueryResult = queryChange ? this.currentResult : this.previousQueryResult;
|
||||
var state = query.state;
|
||||
var dataUpdatedAt = state.dataUpdatedAt,
|
||||
error = state.error,
|
||||
errorUpdatedAt = state.errorUpdatedAt,
|
||||
isFetching = state.isFetching,
|
||||
status = state.status;
|
||||
var isPreviousData = false;
|
||||
var isPlaceholderData = false;
|
||||
var data; // Optimistically set result in fetching state if needed
|
||||
|
||||
if (options.optimisticResults) {
|
||||
var mounted = this.hasListeners();
|
||||
var fetchOnMount = !mounted && shouldFetchOnMount(query, options);
|
||||
var fetchOptionally = mounted && shouldFetchOptionally(query, prevQuery, options, prevOptions);
|
||||
|
||||
if (fetchOnMount || fetchOptionally) {
|
||||
isFetching = true;
|
||||
|
||||
if (!dataUpdatedAt) {
|
||||
status = 'loading';
|
||||
}
|
||||
}
|
||||
} // Keep previous data if needed
|
||||
|
||||
|
||||
if (options.keepPreviousData && !state.dataUpdateCount && (prevQueryResult == null ? void 0 : prevQueryResult.isSuccess) && status !== 'error') {
|
||||
data = prevQueryResult.data;
|
||||
dataUpdatedAt = prevQueryResult.dataUpdatedAt;
|
||||
status = prevQueryResult.status;
|
||||
isPreviousData = true;
|
||||
} // Select data if needed
|
||||
else if (options.select && typeof state.data !== 'undefined') {
|
||||
// Memoize select result
|
||||
if (prevResult && state.data === (prevResultState == null ? void 0 : prevResultState.data) && options.select === this.selectFn) {
|
||||
data = this.selectResult;
|
||||
} else {
|
||||
try {
|
||||
this.selectFn = options.select;
|
||||
data = options.select(state.data);
|
||||
|
||||
if (options.structuralSharing !== false) {
|
||||
data = replaceEqualDeep(prevResult == null ? void 0 : prevResult.data, data);
|
||||
}
|
||||
|
||||
this.selectResult = data;
|
||||
this.selectError = null;
|
||||
} catch (selectError) {
|
||||
getLogger().error(selectError);
|
||||
this.selectError = selectError;
|
||||
}
|
||||
}
|
||||
} // Use query data
|
||||
else {
|
||||
data = state.data;
|
||||
} // Show placeholder data if needed
|
||||
|
||||
|
||||
if (typeof options.placeholderData !== 'undefined' && typeof data === 'undefined' && (status === 'loading' || status === 'idle')) {
|
||||
var placeholderData; // Memoize placeholder data
|
||||
|
||||
if ((prevResult == null ? void 0 : prevResult.isPlaceholderData) && options.placeholderData === (prevResultOptions == null ? void 0 : prevResultOptions.placeholderData)) {
|
||||
placeholderData = prevResult.data;
|
||||
} else {
|
||||
placeholderData = typeof options.placeholderData === 'function' ? options.placeholderData() : options.placeholderData;
|
||||
|
||||
if (options.select && typeof placeholderData !== 'undefined') {
|
||||
try {
|
||||
placeholderData = options.select(placeholderData);
|
||||
|
||||
if (options.structuralSharing !== false) {
|
||||
placeholderData = replaceEqualDeep(prevResult == null ? void 0 : prevResult.data, placeholderData);
|
||||
}
|
||||
|
||||
this.selectError = null;
|
||||
} catch (selectError) {
|
||||
getLogger().error(selectError);
|
||||
this.selectError = selectError;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof placeholderData !== 'undefined') {
|
||||
status = 'success';
|
||||
data = placeholderData;
|
||||
isPlaceholderData = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (this.selectError) {
|
||||
error = this.selectError;
|
||||
data = this.selectResult;
|
||||
errorUpdatedAt = Date.now();
|
||||
status = 'error';
|
||||
}
|
||||
|
||||
var result = {
|
||||
status: status,
|
||||
isLoading: status === 'loading',
|
||||
isSuccess: status === 'success',
|
||||
isError: status === 'error',
|
||||
isIdle: status === 'idle',
|
||||
data: data,
|
||||
dataUpdatedAt: dataUpdatedAt,
|
||||
error: error,
|
||||
errorUpdatedAt: errorUpdatedAt,
|
||||
failureCount: state.fetchFailureCount,
|
||||
errorUpdateCount: state.errorUpdateCount,
|
||||
isFetched: state.dataUpdateCount > 0 || state.errorUpdateCount > 0,
|
||||
isFetchedAfterMount: state.dataUpdateCount > queryInitialState.dataUpdateCount || state.errorUpdateCount > queryInitialState.errorUpdateCount,
|
||||
isFetching: isFetching,
|
||||
isRefetching: isFetching && status !== 'loading',
|
||||
isLoadingError: status === 'error' && state.dataUpdatedAt === 0,
|
||||
isPlaceholderData: isPlaceholderData,
|
||||
isPreviousData: isPreviousData,
|
||||
isRefetchError: status === 'error' && state.dataUpdatedAt !== 0,
|
||||
isStale: isStale(query, options),
|
||||
refetch: this.refetch,
|
||||
remove: this.remove
|
||||
};
|
||||
return result;
|
||||
};
|
||||
|
||||
_proto.shouldNotifyListeners = function shouldNotifyListeners(result, prevResult) {
|
||||
if (!prevResult) {
|
||||
return true;
|
||||
}
|
||||
|
||||
var _this$options = this.options,
|
||||
notifyOnChangeProps = _this$options.notifyOnChangeProps,
|
||||
notifyOnChangePropsExclusions = _this$options.notifyOnChangePropsExclusions;
|
||||
|
||||
if (!notifyOnChangeProps && !notifyOnChangePropsExclusions) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (notifyOnChangeProps === 'tracked' && !this.trackedProps.length) {
|
||||
return true;
|
||||
}
|
||||
|
||||
var includedProps = notifyOnChangeProps === 'tracked' ? this.trackedProps : notifyOnChangeProps;
|
||||
return Object.keys(result).some(function (key) {
|
||||
var typedKey = key;
|
||||
var changed = result[typedKey] !== prevResult[typedKey];
|
||||
var isIncluded = includedProps == null ? void 0 : includedProps.some(function (x) {
|
||||
return x === key;
|
||||
});
|
||||
var isExcluded = notifyOnChangePropsExclusions == null ? void 0 : notifyOnChangePropsExclusions.some(function (x) {
|
||||
return x === key;
|
||||
});
|
||||
return changed && !isExcluded && (!includedProps || isIncluded);
|
||||
});
|
||||
};
|
||||
|
||||
_proto.updateResult = function updateResult(notifyOptions) {
|
||||
var prevResult = this.currentResult;
|
||||
this.currentResult = this.createResult(this.currentQuery, this.options);
|
||||
this.currentResultState = this.currentQuery.state;
|
||||
this.currentResultOptions = this.options; // Only notify if something has changed
|
||||
|
||||
if (shallowEqualObjects(this.currentResult, prevResult)) {
|
||||
return;
|
||||
} // Determine which callbacks to trigger
|
||||
|
||||
|
||||
var defaultNotifyOptions = {
|
||||
cache: true
|
||||
};
|
||||
|
||||
if ((notifyOptions == null ? void 0 : notifyOptions.listeners) !== false && this.shouldNotifyListeners(this.currentResult, prevResult)) {
|
||||
defaultNotifyOptions.listeners = true;
|
||||
}
|
||||
|
||||
this.notify(_extends({}, defaultNotifyOptions, notifyOptions));
|
||||
};
|
||||
|
||||
_proto.updateQuery = function updateQuery() {
|
||||
var query = this.client.getQueryCache().build(this.client, this.options);
|
||||
|
||||
if (query === this.currentQuery) {
|
||||
return;
|
||||
}
|
||||
|
||||
var prevQuery = this.currentQuery;
|
||||
this.currentQuery = query;
|
||||
this.currentQueryInitialState = query.state;
|
||||
this.previousQueryResult = this.currentResult;
|
||||
|
||||
if (this.hasListeners()) {
|
||||
prevQuery == null ? void 0 : prevQuery.removeObserver(this);
|
||||
query.addObserver(this);
|
||||
}
|
||||
};
|
||||
|
||||
_proto.onQueryUpdate = function onQueryUpdate(action) {
|
||||
var notifyOptions = {};
|
||||
|
||||
if (action.type === 'success') {
|
||||
notifyOptions.onSuccess = true;
|
||||
} else if (action.type === 'error' && !isCancelledError(action.error)) {
|
||||
notifyOptions.onError = true;
|
||||
}
|
||||
|
||||
this.updateResult(notifyOptions);
|
||||
|
||||
if (this.hasListeners()) {
|
||||
this.updateTimers();
|
||||
}
|
||||
};
|
||||
|
||||
_proto.notify = function notify(notifyOptions) {
|
||||
var _this8 = this;
|
||||
|
||||
notifyManager.batch(function () {
|
||||
// First trigger the configuration callbacks
|
||||
if (notifyOptions.onSuccess) {
|
||||
_this8.options.onSuccess == null ? void 0 : _this8.options.onSuccess(_this8.currentResult.data);
|
||||
_this8.options.onSettled == null ? void 0 : _this8.options.onSettled(_this8.currentResult.data, null);
|
||||
} else if (notifyOptions.onError) {
|
||||
_this8.options.onError == null ? void 0 : _this8.options.onError(_this8.currentResult.error);
|
||||
_this8.options.onSettled == null ? void 0 : _this8.options.onSettled(undefined, _this8.currentResult.error);
|
||||
} // Then trigger the listeners
|
||||
|
||||
|
||||
if (notifyOptions.listeners) {
|
||||
_this8.listeners.forEach(function (listener) {
|
||||
listener(_this8.currentResult);
|
||||
});
|
||||
} // Then the cache listeners
|
||||
|
||||
|
||||
if (notifyOptions.cache) {
|
||||
_this8.client.getQueryCache().notify({
|
||||
query: _this8.currentQuery,
|
||||
type: 'observerResultsUpdated'
|
||||
});
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
return QueryObserver;
|
||||
}(Subscribable);
|
||||
|
||||
function shouldLoadOnMount(query, options) {
|
||||
return options.enabled !== false && !query.state.dataUpdatedAt && !(query.state.status === 'error' && options.retryOnMount === false);
|
||||
}
|
||||
|
||||
function shouldFetchOnMount(query, options) {
|
||||
return shouldLoadOnMount(query, options) || query.state.dataUpdatedAt > 0 && shouldFetchOn(query, options, options.refetchOnMount);
|
||||
}
|
||||
|
||||
function shouldFetchOn(query, options, field) {
|
||||
if (options.enabled !== false) {
|
||||
var value = typeof field === 'function' ? field(query) : field;
|
||||
return value === 'always' || value !== false && isStale(query, options);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
function shouldFetchOptionally(query, prevQuery, options, prevOptions) {
|
||||
return options.enabled !== false && (query !== prevQuery || prevOptions.enabled === false) && (!options.suspense || query.state.status !== 'error') && isStale(query, options);
|
||||
}
|
||||
|
||||
function isStale(query, options) {
|
||||
return query.isStaleByTime(options.staleTime);
|
||||
}
|
||||
|
||||
var QueriesObserver = /*#__PURE__*/function (_Subscribable) {
|
||||
_inheritsLoose(QueriesObserver, _Subscribable);
|
||||
|
||||
function QueriesObserver(client, queries) {
|
||||
var _this;
|
||||
|
||||
_this = _Subscribable.call(this) || this;
|
||||
_this.client = client;
|
||||
_this.queries = [];
|
||||
_this.result = [];
|
||||
_this.observers = [];
|
||||
_this.observersMap = {};
|
||||
|
||||
if (queries) {
|
||||
_this.setQueries(queries);
|
||||
}
|
||||
|
||||
return _this;
|
||||
}
|
||||
|
||||
var _proto = QueriesObserver.prototype;
|
||||
|
||||
_proto.onSubscribe = function onSubscribe() {
|
||||
var _this2 = this;
|
||||
|
||||
if (this.listeners.length === 1) {
|
||||
this.observers.forEach(function (observer) {
|
||||
observer.subscribe(function (result) {
|
||||
_this2.onUpdate(observer, result);
|
||||
});
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
_proto.onUnsubscribe = function onUnsubscribe() {
|
||||
if (!this.listeners.length) {
|
||||
this.destroy();
|
||||
}
|
||||
};
|
||||
|
||||
_proto.destroy = function destroy() {
|
||||
this.listeners = [];
|
||||
this.observers.forEach(function (observer) {
|
||||
observer.destroy();
|
||||
});
|
||||
};
|
||||
|
||||
_proto.setQueries = function setQueries(queries, notifyOptions) {
|
||||
this.queries = queries;
|
||||
this.updateObservers(notifyOptions);
|
||||
};
|
||||
|
||||
_proto.getCurrentResult = function getCurrentResult() {
|
||||
return this.result;
|
||||
};
|
||||
|
||||
_proto.getOptimisticResult = function getOptimisticResult(queries) {
|
||||
return this.findMatchingObservers(queries).map(function (match) {
|
||||
return match.observer.getOptimisticResult(match.defaultedQueryOptions);
|
||||
});
|
||||
};
|
||||
|
||||
_proto.findMatchingObservers = function findMatchingObservers(queries) {
|
||||
var _this3 = this;
|
||||
|
||||
var prevObservers = this.observers;
|
||||
var defaultedQueryOptions = queries.map(function (options) {
|
||||
return _this3.client.defaultQueryObserverOptions(options);
|
||||
});
|
||||
var matchingObservers = defaultedQueryOptions.flatMap(function (defaultedOptions) {
|
||||
var match = prevObservers.find(function (observer) {
|
||||
return observer.options.queryHash === defaultedOptions.queryHash;
|
||||
});
|
||||
|
||||
if (match != null) {
|
||||
return [{
|
||||
defaultedQueryOptions: defaultedOptions,
|
||||
observer: match
|
||||
}];
|
||||
}
|
||||
|
||||
return [];
|
||||
});
|
||||
var matchedQueryHashes = matchingObservers.map(function (match) {
|
||||
return match.defaultedQueryOptions.queryHash;
|
||||
});
|
||||
var unmatchedQueries = defaultedQueryOptions.filter(function (defaultedOptions) {
|
||||
return !matchedQueryHashes.includes(defaultedOptions.queryHash);
|
||||
});
|
||||
var unmatchedObservers = prevObservers.filter(function (prevObserver) {
|
||||
return !matchingObservers.some(function (match) {
|
||||
return match.observer === prevObserver;
|
||||
});
|
||||
});
|
||||
var newOrReusedObservers = unmatchedQueries.map(function (options, index) {
|
||||
if (options.keepPreviousData) {
|
||||
// return previous data from one of the observers that no longer match
|
||||
var previouslyUsedObserver = unmatchedObservers[index];
|
||||
|
||||
if (previouslyUsedObserver !== undefined) {
|
||||
return {
|
||||
defaultedQueryOptions: options,
|
||||
observer: previouslyUsedObserver
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
defaultedQueryOptions: options,
|
||||
observer: _this3.getObserver(options)
|
||||
};
|
||||
});
|
||||
|
||||
var sortMatchesByOrderOfQueries = function sortMatchesByOrderOfQueries(a, b) {
|
||||
return defaultedQueryOptions.indexOf(a.defaultedQueryOptions) - defaultedQueryOptions.indexOf(b.defaultedQueryOptions);
|
||||
};
|
||||
|
||||
return matchingObservers.concat(newOrReusedObservers).sort(sortMatchesByOrderOfQueries);
|
||||
};
|
||||
|
||||
_proto.getObserver = function getObserver(options) {
|
||||
var defaultedOptions = this.client.defaultQueryObserverOptions(options);
|
||||
var currentObserver = this.observersMap[defaultedOptions.queryHash];
|
||||
return currentObserver != null ? currentObserver : new QueryObserver(this.client, defaultedOptions);
|
||||
};
|
||||
|
||||
_proto.updateObservers = function updateObservers(notifyOptions) {
|
||||
var _this4 = this;
|
||||
|
||||
notifyManager.batch(function () {
|
||||
var prevObservers = _this4.observers;
|
||||
|
||||
var newObserverMatches = _this4.findMatchingObservers(_this4.queries); // set options for the new observers to notify of changes
|
||||
|
||||
|
||||
newObserverMatches.forEach(function (match) {
|
||||
return match.observer.setOptions(match.defaultedQueryOptions, notifyOptions);
|
||||
});
|
||||
var newObservers = newObserverMatches.map(function (match) {
|
||||
return match.observer;
|
||||
});
|
||||
var newObserversMap = Object.fromEntries(newObservers.map(function (observer) {
|
||||
return [observer.options.queryHash, observer];
|
||||
}));
|
||||
var newResult = newObservers.map(function (observer) {
|
||||
return observer.getCurrentResult();
|
||||
});
|
||||
var hasIndexChange = newObservers.some(function (observer, index) {
|
||||
return observer !== prevObservers[index];
|
||||
});
|
||||
|
||||
if (prevObservers.length === newObservers.length && !hasIndexChange) {
|
||||
return;
|
||||
}
|
||||
|
||||
_this4.observers = newObservers;
|
||||
_this4.observersMap = newObserversMap;
|
||||
_this4.result = newResult;
|
||||
|
||||
if (!_this4.hasListeners()) {
|
||||
return;
|
||||
}
|
||||
|
||||
difference(prevObservers, newObservers).forEach(function (observer) {
|
||||
observer.destroy();
|
||||
});
|
||||
difference(newObservers, prevObservers).forEach(function (observer) {
|
||||
observer.subscribe(function (result) {
|
||||
_this4.onUpdate(observer, result);
|
||||
});
|
||||
});
|
||||
|
||||
_this4.notify();
|
||||
});
|
||||
};
|
||||
|
||||
_proto.onUpdate = function onUpdate(observer, result) {
|
||||
var index = this.observers.indexOf(observer);
|
||||
|
||||
if (index !== -1) {
|
||||
this.result = replaceAt(this.result, index, result);
|
||||
this.notify();
|
||||
}
|
||||
};
|
||||
|
||||
_proto.notify = function notify() {
|
||||
var _this5 = this;
|
||||
|
||||
notifyManager.batch(function () {
|
||||
_this5.listeners.forEach(function (listener) {
|
||||
listener(_this5.result);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
return QueriesObserver;
|
||||
}(Subscribable);
|
||||
|
||||
var InfiniteQueryObserver = /*#__PURE__*/function (_QueryObserver) {
|
||||
_inheritsLoose(InfiniteQueryObserver, _QueryObserver);
|
||||
|
||||
// Type override
|
||||
// Type override
|
||||
// Type override
|
||||
// eslint-disable-next-line @typescript-eslint/no-useless-constructor
|
||||
function InfiniteQueryObserver(client, options) {
|
||||
return _QueryObserver.call(this, client, options) || this;
|
||||
}
|
||||
|
||||
var _proto = InfiniteQueryObserver.prototype;
|
||||
|
||||
_proto.bindMethods = function bindMethods() {
|
||||
_QueryObserver.prototype.bindMethods.call(this);
|
||||
|
||||
this.fetchNextPage = this.fetchNextPage.bind(this);
|
||||
this.fetchPreviousPage = this.fetchPreviousPage.bind(this);
|
||||
};
|
||||
|
||||
_proto.setOptions = function setOptions(options, notifyOptions) {
|
||||
_QueryObserver.prototype.setOptions.call(this, _extends({}, options, {
|
||||
behavior: infiniteQueryBehavior()
|
||||
}), notifyOptions);
|
||||
};
|
||||
|
||||
_proto.getOptimisticResult = function getOptimisticResult(options) {
|
||||
options.behavior = infiniteQueryBehavior();
|
||||
return _QueryObserver.prototype.getOptimisticResult.call(this, options);
|
||||
};
|
||||
|
||||
_proto.fetchNextPage = function fetchNextPage(options) {
|
||||
var _options$cancelRefetc;
|
||||
|
||||
return this.fetch({
|
||||
// TODO consider removing `?? true` in future breaking change, to be consistent with `refetch` API (see https://github.com/tannerlinsley/react-query/issues/2617)
|
||||
cancelRefetch: (_options$cancelRefetc = options == null ? void 0 : options.cancelRefetch) != null ? _options$cancelRefetc : true,
|
||||
throwOnError: options == null ? void 0 : options.throwOnError,
|
||||
meta: {
|
||||
fetchMore: {
|
||||
direction: 'forward',
|
||||
pageParam: options == null ? void 0 : options.pageParam
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
_proto.fetchPreviousPage = function fetchPreviousPage(options) {
|
||||
var _options$cancelRefetc2;
|
||||
|
||||
return this.fetch({
|
||||
// TODO consider removing `?? true` in future breaking change, to be consistent with `refetch` API (see https://github.com/tannerlinsley/react-query/issues/2617)
|
||||
cancelRefetch: (_options$cancelRefetc2 = options == null ? void 0 : options.cancelRefetch) != null ? _options$cancelRefetc2 : true,
|
||||
throwOnError: options == null ? void 0 : options.throwOnError,
|
||||
meta: {
|
||||
fetchMore: {
|
||||
direction: 'backward',
|
||||
pageParam: options == null ? void 0 : options.pageParam
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
_proto.createResult = function createResult(query, options) {
|
||||
var _state$data, _state$data2, _state$fetchMeta, _state$fetchMeta$fetc, _state$fetchMeta2, _state$fetchMeta2$fet;
|
||||
|
||||
var state = query.state;
|
||||
|
||||
var result = _QueryObserver.prototype.createResult.call(this, query, options);
|
||||
|
||||
return _extends({}, result, {
|
||||
fetchNextPage: this.fetchNextPage,
|
||||
fetchPreviousPage: this.fetchPreviousPage,
|
||||
hasNextPage: hasNextPage(options, (_state$data = state.data) == null ? void 0 : _state$data.pages),
|
||||
hasPreviousPage: hasPreviousPage(options, (_state$data2 = state.data) == null ? void 0 : _state$data2.pages),
|
||||
isFetchingNextPage: state.isFetching && ((_state$fetchMeta = state.fetchMeta) == null ? void 0 : (_state$fetchMeta$fetc = _state$fetchMeta.fetchMore) == null ? void 0 : _state$fetchMeta$fetc.direction) === 'forward',
|
||||
isFetchingPreviousPage: state.isFetching && ((_state$fetchMeta2 = state.fetchMeta) == null ? void 0 : (_state$fetchMeta2$fet = _state$fetchMeta2.fetchMore) == null ? void 0 : _state$fetchMeta2$fet.direction) === 'backward'
|
||||
});
|
||||
};
|
||||
|
||||
return InfiniteQueryObserver;
|
||||
}(QueryObserver);
|
||||
|
||||
// CLASS
|
||||
var MutationObserver = /*#__PURE__*/function (_Subscribable) {
|
||||
_inheritsLoose(MutationObserver, _Subscribable);
|
||||
|
||||
function MutationObserver(client, options) {
|
||||
var _this;
|
||||
|
||||
_this = _Subscribable.call(this) || this;
|
||||
_this.client = client;
|
||||
|
||||
_this.setOptions(options);
|
||||
|
||||
_this.bindMethods();
|
||||
|
||||
_this.updateResult();
|
||||
|
||||
return _this;
|
||||
}
|
||||
|
||||
var _proto = MutationObserver.prototype;
|
||||
|
||||
_proto.bindMethods = function bindMethods() {
|
||||
this.mutate = this.mutate.bind(this);
|
||||
this.reset = this.reset.bind(this);
|
||||
};
|
||||
|
||||
_proto.setOptions = function setOptions(options) {
|
||||
this.options = this.client.defaultMutationOptions(options);
|
||||
};
|
||||
|
||||
_proto.onUnsubscribe = function onUnsubscribe() {
|
||||
if (!this.listeners.length) {
|
||||
var _this$currentMutation;
|
||||
|
||||
(_this$currentMutation = this.currentMutation) == null ? void 0 : _this$currentMutation.removeObserver(this);
|
||||
}
|
||||
};
|
||||
|
||||
_proto.onMutationUpdate = function onMutationUpdate(action) {
|
||||
this.updateResult(); // Determine which callbacks to trigger
|
||||
|
||||
var notifyOptions = {
|
||||
listeners: true
|
||||
};
|
||||
|
||||
if (action.type === 'success') {
|
||||
notifyOptions.onSuccess = true;
|
||||
} else if (action.type === 'error') {
|
||||
notifyOptions.onError = true;
|
||||
}
|
||||
|
||||
this.notify(notifyOptions);
|
||||
};
|
||||
|
||||
_proto.getCurrentResult = function getCurrentResult() {
|
||||
return this.currentResult;
|
||||
};
|
||||
|
||||
_proto.reset = function reset() {
|
||||
this.currentMutation = undefined;
|
||||
this.updateResult();
|
||||
this.notify({
|
||||
listeners: true
|
||||
});
|
||||
};
|
||||
|
||||
_proto.mutate = function mutate(variables, options) {
|
||||
this.mutateOptions = options;
|
||||
|
||||
if (this.currentMutation) {
|
||||
this.currentMutation.removeObserver(this);
|
||||
}
|
||||
|
||||
this.currentMutation = this.client.getMutationCache().build(this.client, _extends({}, this.options, {
|
||||
variables: typeof variables !== 'undefined' ? variables : this.options.variables
|
||||
}));
|
||||
this.currentMutation.addObserver(this);
|
||||
return this.currentMutation.execute();
|
||||
};
|
||||
|
||||
_proto.updateResult = function updateResult() {
|
||||
var state = this.currentMutation ? this.currentMutation.state : getDefaultState();
|
||||
|
||||
var result = _extends({}, state, {
|
||||
isLoading: state.status === 'loading',
|
||||
isSuccess: state.status === 'success',
|
||||
isError: state.status === 'error',
|
||||
isIdle: state.status === 'idle',
|
||||
mutate: this.mutate,
|
||||
reset: this.reset
|
||||
});
|
||||
|
||||
this.currentResult = result;
|
||||
};
|
||||
|
||||
_proto.notify = function notify(options) {
|
||||
var _this2 = this;
|
||||
|
||||
notifyManager.batch(function () {
|
||||
// First trigger the mutate callbacks
|
||||
if (_this2.mutateOptions) {
|
||||
if (options.onSuccess) {
|
||||
_this2.mutateOptions.onSuccess == null ? void 0 : _this2.mutateOptions.onSuccess(_this2.currentResult.data, _this2.currentResult.variables, _this2.currentResult.context);
|
||||
_this2.mutateOptions.onSettled == null ? void 0 : _this2.mutateOptions.onSettled(_this2.currentResult.data, null, _this2.currentResult.variables, _this2.currentResult.context);
|
||||
} else if (options.onError) {
|
||||
_this2.mutateOptions.onError == null ? void 0 : _this2.mutateOptions.onError(_this2.currentResult.error, _this2.currentResult.variables, _this2.currentResult.context);
|
||||
_this2.mutateOptions.onSettled == null ? void 0 : _this2.mutateOptions.onSettled(undefined, _this2.currentResult.error, _this2.currentResult.variables, _this2.currentResult.context);
|
||||
}
|
||||
} // Then trigger the listeners
|
||||
|
||||
|
||||
if (options.listeners) {
|
||||
_this2.listeners.forEach(function (listener) {
|
||||
listener(_this2.currentResult);
|
||||
});
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
return MutationObserver;
|
||||
}(Subscribable);
|
||||
|
||||
// TYPES
|
||||
// FUNCTIONS
|
||||
function dehydrateMutation(mutation) {
|
||||
return {
|
||||
mutationKey: mutation.options.mutationKey,
|
||||
state: mutation.state
|
||||
};
|
||||
} // Most config is not dehydrated but instead meant to configure again when
|
||||
// consuming the de/rehydrated data, typically with useQuery on the client.
|
||||
// Sometimes it might make sense to prefetch data on the server and include
|
||||
// in the html-payload, but not consume it on the initial render.
|
||||
|
||||
|
||||
function dehydrateQuery(query) {
|
||||
return {
|
||||
state: query.state,
|
||||
queryKey: query.queryKey,
|
||||
queryHash: query.queryHash
|
||||
};
|
||||
}
|
||||
|
||||
function defaultShouldDehydrateMutation(mutation) {
|
||||
return mutation.state.isPaused;
|
||||
}
|
||||
|
||||
function defaultShouldDehydrateQuery(query) {
|
||||
return query.state.status === 'success';
|
||||
}
|
||||
|
||||
function dehydrate(client, options) {
|
||||
var _options, _options2;
|
||||
|
||||
options = options || {};
|
||||
var mutations = [];
|
||||
var queries = [];
|
||||
|
||||
if (((_options = options) == null ? void 0 : _options.dehydrateMutations) !== false) {
|
||||
var shouldDehydrateMutation = options.shouldDehydrateMutation || defaultShouldDehydrateMutation;
|
||||
client.getMutationCache().getAll().forEach(function (mutation) {
|
||||
if (shouldDehydrateMutation(mutation)) {
|
||||
mutations.push(dehydrateMutation(mutation));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (((_options2 = options) == null ? void 0 : _options2.dehydrateQueries) !== false) {
|
||||
var shouldDehydrateQuery = options.shouldDehydrateQuery || defaultShouldDehydrateQuery;
|
||||
client.getQueryCache().getAll().forEach(function (query) {
|
||||
if (shouldDehydrateQuery(query)) {
|
||||
queries.push(dehydrateQuery(query));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
mutations: mutations,
|
||||
queries: queries
|
||||
};
|
||||
}
|
||||
function hydrate(client, dehydratedState, options) {
|
||||
if (typeof dehydratedState !== 'object' || dehydratedState === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
var mutationCache = client.getMutationCache();
|
||||
var queryCache = client.getQueryCache();
|
||||
var mutations = dehydratedState.mutations || [];
|
||||
var queries = dehydratedState.queries || [];
|
||||
mutations.forEach(function (dehydratedMutation) {
|
||||
var _options$defaultOptio;
|
||||
|
||||
mutationCache.build(client, _extends({}, options == null ? void 0 : (_options$defaultOptio = options.defaultOptions) == null ? void 0 : _options$defaultOptio.mutations, {
|
||||
mutationKey: dehydratedMutation.mutationKey
|
||||
}), dehydratedMutation.state);
|
||||
});
|
||||
queries.forEach(function (dehydratedQuery) {
|
||||
var _options$defaultOptio2;
|
||||
|
||||
var query = queryCache.get(dehydratedQuery.queryHash); // Do not hydrate if an existing query exists with newer data
|
||||
|
||||
if (query) {
|
||||
if (query.state.dataUpdatedAt < dehydratedQuery.state.dataUpdatedAt) {
|
||||
query.setState(dehydratedQuery.state);
|
||||
}
|
||||
|
||||
return;
|
||||
} // Restore query
|
||||
|
||||
|
||||
queryCache.build(client, _extends({}, options == null ? void 0 : (_options$defaultOptio2 = options.defaultOptions) == null ? void 0 : _options$defaultOptio2.queries, {
|
||||
queryKey: dehydratedQuery.queryKey,
|
||||
queryHash: dehydratedQuery.queryHash
|
||||
}), dehydratedQuery.state);
|
||||
});
|
||||
}
|
||||
|
||||
var defaultContext = /*#__PURE__*/React__default.createContext(undefined);
|
||||
var QueryClientSharingContext = /*#__PURE__*/React__default.createContext(false); // if contextSharing is on, we share the first and at least one
|
||||
// instance of the context across the window
|
||||
// to ensure that if React Query is used across
|
||||
// different bundles or microfrontends they will
|
||||
// all use the same **instance** of context, regardless
|
||||
// of module scoping.
|
||||
|
||||
function getQueryClientContext(contextSharing) {
|
||||
if (contextSharing && typeof window !== 'undefined') {
|
||||
if (!window.ReactQueryClientContext) {
|
||||
window.ReactQueryClientContext = defaultContext;
|
||||
}
|
||||
|
||||
return window.ReactQueryClientContext;
|
||||
}
|
||||
|
||||
return defaultContext;
|
||||
}
|
||||
|
||||
var useQueryClient = function useQueryClient() {
|
||||
var queryClient = React__default.useContext(getQueryClientContext(React__default.useContext(QueryClientSharingContext)));
|
||||
|
||||
if (!queryClient) {
|
||||
throw new Error('No QueryClient set, use QueryClientProvider to set one');
|
||||
}
|
||||
|
||||
return queryClient;
|
||||
};
|
||||
var QueryClientProvider = function QueryClientProvider(_ref) {
|
||||
var client = _ref.client,
|
||||
_ref$contextSharing = _ref.contextSharing,
|
||||
contextSharing = _ref$contextSharing === void 0 ? false : _ref$contextSharing,
|
||||
children = _ref.children;
|
||||
React__default.useEffect(function () {
|
||||
client.mount();
|
||||
return function () {
|
||||
client.unmount();
|
||||
};
|
||||
}, [client]);
|
||||
var Context = getQueryClientContext(contextSharing);
|
||||
return /*#__PURE__*/React__default.createElement(QueryClientSharingContext.Provider, {
|
||||
value: contextSharing
|
||||
}, /*#__PURE__*/React__default.createElement(Context.Provider, {
|
||||
value: client
|
||||
}, children));
|
||||
};
|
||||
|
||||
function createValue() {
|
||||
var _isReset = false;
|
||||
return {
|
||||
clearReset: function clearReset() {
|
||||
_isReset = false;
|
||||
},
|
||||
reset: function reset() {
|
||||
_isReset = true;
|
||||
},
|
||||
isReset: function isReset() {
|
||||
return _isReset;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
var QueryErrorResetBoundaryContext = /*#__PURE__*/React__default.createContext(createValue()); // HOOK
|
||||
|
||||
var useQueryErrorResetBoundary = function useQueryErrorResetBoundary() {
|
||||
return React__default.useContext(QueryErrorResetBoundaryContext);
|
||||
}; // COMPONENT
|
||||
|
||||
var QueryErrorResetBoundary = function QueryErrorResetBoundary(_ref) {
|
||||
var children = _ref.children;
|
||||
var value = React__default.useMemo(function () {
|
||||
return createValue();
|
||||
}, []);
|
||||
return /*#__PURE__*/React__default.createElement(QueryErrorResetBoundaryContext.Provider, {
|
||||
value: value
|
||||
}, typeof children === 'function' ? children(value) : children);
|
||||
};
|
||||
|
||||
var checkIsFetching = function checkIsFetching(queryClient, filters, isFetching, setIsFetching) {
|
||||
var newIsFetching = queryClient.isFetching(filters);
|
||||
|
||||
if (isFetching !== newIsFetching) {
|
||||
setIsFetching(newIsFetching);
|
||||
}
|
||||
};
|
||||
|
||||
function useIsFetching(arg1, arg2) {
|
||||
var mountedRef = React__default.useRef(false);
|
||||
var queryClient = useQueryClient();
|
||||
|
||||
var _parseFilterArgs = parseFilterArgs(arg1, arg2),
|
||||
filters = _parseFilterArgs[0];
|
||||
|
||||
var _React$useState = React__default.useState(queryClient.isFetching(filters)),
|
||||
isFetching = _React$useState[0],
|
||||
setIsFetching = _React$useState[1];
|
||||
|
||||
var filtersRef = React__default.useRef(filters);
|
||||
filtersRef.current = filters;
|
||||
var isFetchingRef = React__default.useRef(isFetching);
|
||||
isFetchingRef.current = isFetching;
|
||||
React__default.useEffect(function () {
|
||||
mountedRef.current = true;
|
||||
checkIsFetching(queryClient, filtersRef.current, isFetchingRef.current, setIsFetching);
|
||||
var unsubscribe = queryClient.getQueryCache().subscribe(notifyManager.batchCalls(function () {
|
||||
if (mountedRef.current) {
|
||||
checkIsFetching(queryClient, filtersRef.current, isFetchingRef.current, setIsFetching);
|
||||
}
|
||||
}));
|
||||
return function () {
|
||||
mountedRef.current = false;
|
||||
unsubscribe();
|
||||
};
|
||||
}, [queryClient]);
|
||||
return isFetching;
|
||||
}
|
||||
|
||||
function useIsMutating(arg1, arg2) {
|
||||
var mountedRef = React__default.useRef(false);
|
||||
var filters = parseMutationFilterArgs(arg1, arg2);
|
||||
var queryClient = useQueryClient();
|
||||
|
||||
var _React$useState = React__default.useState(queryClient.isMutating(filters)),
|
||||
isMutating = _React$useState[0],
|
||||
setIsMutating = _React$useState[1];
|
||||
|
||||
var filtersRef = React__default.useRef(filters);
|
||||
filtersRef.current = filters;
|
||||
var isMutatingRef = React__default.useRef(isMutating);
|
||||
isMutatingRef.current = isMutating;
|
||||
React__default.useEffect(function () {
|
||||
mountedRef.current = true;
|
||||
var unsubscribe = queryClient.getMutationCache().subscribe(notifyManager.batchCalls(function () {
|
||||
if (mountedRef.current) {
|
||||
var newIsMutating = queryClient.isMutating(filtersRef.current);
|
||||
|
||||
if (isMutatingRef.current !== newIsMutating) {
|
||||
setIsMutating(newIsMutating);
|
||||
}
|
||||
}
|
||||
}));
|
||||
return function () {
|
||||
mountedRef.current = false;
|
||||
unsubscribe();
|
||||
};
|
||||
}, [queryClient]);
|
||||
return isMutating;
|
||||
}
|
||||
|
||||
function shouldThrowError(suspense, _useErrorBoundary, params) {
|
||||
// Allow useErrorBoundary function to override throwing behavior on a per-error basis
|
||||
if (typeof _useErrorBoundary === 'function') {
|
||||
return _useErrorBoundary.apply(void 0, params);
|
||||
} // Allow useErrorBoundary to override suspense's throwing behavior
|
||||
|
||||
|
||||
if (typeof _useErrorBoundary === 'boolean') return _useErrorBoundary; // If suspense is enabled default to throwing errors
|
||||
|
||||
return !!suspense;
|
||||
}
|
||||
|
||||
function useMutation(arg1, arg2, arg3) {
|
||||
var mountedRef = React__default.useRef(false);
|
||||
|
||||
var _React$useState = React__default.useState(0),
|
||||
forceUpdate = _React$useState[1];
|
||||
|
||||
var options = parseMutationArgs(arg1, arg2, arg3);
|
||||
var queryClient = useQueryClient();
|
||||
var obsRef = React__default.useRef();
|
||||
|
||||
if (!obsRef.current) {
|
||||
obsRef.current = new MutationObserver(queryClient, options);
|
||||
} else {
|
||||
obsRef.current.setOptions(options);
|
||||
}
|
||||
|
||||
var currentResult = obsRef.current.getCurrentResult();
|
||||
React__default.useEffect(function () {
|
||||
mountedRef.current = true;
|
||||
var unsubscribe = obsRef.current.subscribe(notifyManager.batchCalls(function () {
|
||||
if (mountedRef.current) {
|
||||
forceUpdate(function (x) {
|
||||
return x + 1;
|
||||
});
|
||||
}
|
||||
}));
|
||||
return function () {
|
||||
mountedRef.current = false;
|
||||
unsubscribe();
|
||||
};
|
||||
}, []);
|
||||
var mutate = React__default.useCallback(function (variables, mutateOptions) {
|
||||
obsRef.current.mutate(variables, mutateOptions).catch(noop);
|
||||
}, []);
|
||||
|
||||
if (currentResult.error && shouldThrowError(undefined, obsRef.current.options.useErrorBoundary, [currentResult.error])) {
|
||||
throw currentResult.error;
|
||||
}
|
||||
|
||||
return _extends({}, currentResult, {
|
||||
mutate: mutate,
|
||||
mutateAsync: currentResult.mutate
|
||||
});
|
||||
}
|
||||
|
||||
function useBaseQuery(options, Observer) {
|
||||
var mountedRef = React__default.useRef(false);
|
||||
|
||||
var _React$useState = React__default.useState(0),
|
||||
forceUpdate = _React$useState[1];
|
||||
|
||||
var queryClient = useQueryClient();
|
||||
var errorResetBoundary = useQueryErrorResetBoundary();
|
||||
var defaultedOptions = queryClient.defaultQueryObserverOptions(options); // Make sure results are optimistically set in fetching state before subscribing or updating options
|
||||
|
||||
defaultedOptions.optimisticResults = true; // Include callbacks in batch renders
|
||||
|
||||
if (defaultedOptions.onError) {
|
||||
defaultedOptions.onError = notifyManager.batchCalls(defaultedOptions.onError);
|
||||
}
|
||||
|
||||
if (defaultedOptions.onSuccess) {
|
||||
defaultedOptions.onSuccess = notifyManager.batchCalls(defaultedOptions.onSuccess);
|
||||
}
|
||||
|
||||
if (defaultedOptions.onSettled) {
|
||||
defaultedOptions.onSettled = notifyManager.batchCalls(defaultedOptions.onSettled);
|
||||
}
|
||||
|
||||
if (defaultedOptions.suspense) {
|
||||
// Always set stale time when using suspense to prevent
|
||||
// fetching again when directly mounting after suspending
|
||||
if (typeof defaultedOptions.staleTime !== 'number') {
|
||||
defaultedOptions.staleTime = 1000;
|
||||
} // Set cache time to 1 if the option has been set to 0
|
||||
// when using suspense to prevent infinite loop of fetches
|
||||
|
||||
|
||||
if (defaultedOptions.cacheTime === 0) {
|
||||
defaultedOptions.cacheTime = 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (defaultedOptions.suspense || defaultedOptions.useErrorBoundary) {
|
||||
// Prevent retrying failed query if the error boundary has not been reset yet
|
||||
if (!errorResetBoundary.isReset()) {
|
||||
defaultedOptions.retryOnMount = false;
|
||||
}
|
||||
}
|
||||
|
||||
var _React$useState2 = React__default.useState(function () {
|
||||
return new Observer(queryClient, defaultedOptions);
|
||||
}),
|
||||
observer = _React$useState2[0];
|
||||
|
||||
var result = observer.getOptimisticResult(defaultedOptions);
|
||||
React__default.useEffect(function () {
|
||||
mountedRef.current = true;
|
||||
errorResetBoundary.clearReset();
|
||||
var unsubscribe = observer.subscribe(notifyManager.batchCalls(function () {
|
||||
if (mountedRef.current) {
|
||||
forceUpdate(function (x) {
|
||||
return x + 1;
|
||||
});
|
||||
}
|
||||
})); // Update result to make sure we did not miss any query updates
|
||||
// between creating the observer and subscribing to it.
|
||||
|
||||
observer.updateResult();
|
||||
return function () {
|
||||
mountedRef.current = false;
|
||||
unsubscribe();
|
||||
};
|
||||
}, [errorResetBoundary, observer]);
|
||||
React__default.useEffect(function () {
|
||||
// Do not notify on updates because of changes in the options because
|
||||
// these changes should already be reflected in the optimistic result.
|
||||
observer.setOptions(defaultedOptions, {
|
||||
listeners: false
|
||||
});
|
||||
}, [defaultedOptions, observer]); // Handle suspense
|
||||
|
||||
if (defaultedOptions.suspense && result.isLoading) {
|
||||
throw observer.fetchOptimistic(defaultedOptions).then(function (_ref) {
|
||||
var data = _ref.data;
|
||||
defaultedOptions.onSuccess == null ? void 0 : defaultedOptions.onSuccess(data);
|
||||
defaultedOptions.onSettled == null ? void 0 : defaultedOptions.onSettled(data, null);
|
||||
}).catch(function (error) {
|
||||
errorResetBoundary.clearReset();
|
||||
defaultedOptions.onError == null ? void 0 : defaultedOptions.onError(error);
|
||||
defaultedOptions.onSettled == null ? void 0 : defaultedOptions.onSettled(undefined, error);
|
||||
});
|
||||
} // Handle error boundary
|
||||
|
||||
|
||||
if (result.isError && !errorResetBoundary.isReset() && !result.isFetching && shouldThrowError(defaultedOptions.suspense, defaultedOptions.useErrorBoundary, [result.error, observer.getCurrentQuery()])) {
|
||||
throw result.error;
|
||||
} // Handle result property usage tracking
|
||||
|
||||
|
||||
if (defaultedOptions.notifyOnChangeProps === 'tracked') {
|
||||
result = observer.trackResult(result, defaultedOptions);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function useQuery(arg1, arg2, arg3) {
|
||||
var parsedOptions = parseQueryArgs(arg1, arg2, arg3);
|
||||
return useBaseQuery(parsedOptions, QueryObserver);
|
||||
}
|
||||
|
||||
function useQueries(queries) {
|
||||
var mountedRef = React__default.useRef(false);
|
||||
|
||||
var _React$useState = React__default.useState(0),
|
||||
forceUpdate = _React$useState[1];
|
||||
|
||||
var queryClient = useQueryClient();
|
||||
var defaultedQueries = React.useMemo(function () {
|
||||
return queries.map(function (options) {
|
||||
var defaultedOptions = queryClient.defaultQueryObserverOptions(options); // Make sure the results are already in fetching state before subscribing or updating options
|
||||
|
||||
defaultedOptions.optimisticResults = true;
|
||||
return defaultedOptions;
|
||||
});
|
||||
}, [queries, queryClient]);
|
||||
|
||||
var _React$useState2 = React__default.useState(function () {
|
||||
return new QueriesObserver(queryClient, defaultedQueries);
|
||||
}),
|
||||
observer = _React$useState2[0];
|
||||
|
||||
var result = observer.getOptimisticResult(defaultedQueries);
|
||||
React__default.useEffect(function () {
|
||||
mountedRef.current = true;
|
||||
var unsubscribe = observer.subscribe(notifyManager.batchCalls(function () {
|
||||
if (mountedRef.current) {
|
||||
forceUpdate(function (x) {
|
||||
return x + 1;
|
||||
});
|
||||
}
|
||||
}));
|
||||
return function () {
|
||||
mountedRef.current = false;
|
||||
unsubscribe();
|
||||
};
|
||||
}, [observer]);
|
||||
React__default.useEffect(function () {
|
||||
// Do not notify on updates because of changes in the options because
|
||||
// these changes should already be reflected in the optimistic result.
|
||||
observer.setQueries(defaultedQueries, {
|
||||
listeners: false
|
||||
});
|
||||
}, [defaultedQueries, observer]);
|
||||
return result;
|
||||
}
|
||||
|
||||
function useInfiniteQuery(arg1, arg2, arg3) {
|
||||
var options = parseQueryArgs(arg1, arg2, arg3);
|
||||
return useBaseQuery(options, InfiniteQueryObserver);
|
||||
}
|
||||
|
||||
function useHydrate(state, options) {
|
||||
var queryClient = useQueryClient();
|
||||
var optionsRef = React__default.useRef(options);
|
||||
optionsRef.current = options; // Running hydrate again with the same queries is safe,
|
||||
// it wont overwrite or initialize existing queries,
|
||||
// relying on useMemo here is only a performance optimization.
|
||||
// hydrate can and should be run *during* render here for SSR to work properly
|
||||
|
||||
React__default.useMemo(function () {
|
||||
if (state) {
|
||||
hydrate(queryClient, state, optionsRef.current);
|
||||
}
|
||||
}, [queryClient, state]);
|
||||
}
|
||||
var Hydrate = function Hydrate(_ref) {
|
||||
var children = _ref.children,
|
||||
options = _ref.options,
|
||||
state = _ref.state;
|
||||
useHydrate(state, options);
|
||||
return children;
|
||||
};
|
||||
|
||||
exports.CancelledError = CancelledError;
|
||||
exports.Hydrate = Hydrate;
|
||||
exports.InfiniteQueryObserver = InfiniteQueryObserver;
|
||||
exports.MutationCache = MutationCache;
|
||||
exports.MutationObserver = MutationObserver;
|
||||
exports.QueriesObserver = QueriesObserver;
|
||||
exports.QueryCache = QueryCache;
|
||||
exports.QueryClient = QueryClient;
|
||||
exports.QueryClientProvider = QueryClientProvider;
|
||||
exports.QueryErrorResetBoundary = QueryErrorResetBoundary;
|
||||
exports.QueryObserver = QueryObserver;
|
||||
exports.dehydrate = dehydrate;
|
||||
exports.focusManager = focusManager;
|
||||
exports.hashQueryKey = hashQueryKey;
|
||||
exports.hydrate = hydrate;
|
||||
exports.isCancelledError = isCancelledError;
|
||||
exports.isError = isError;
|
||||
exports.notifyManager = notifyManager;
|
||||
exports.onlineManager = onlineManager;
|
||||
exports.setLogger = setLogger;
|
||||
exports.useHydrate = useHydrate;
|
||||
exports.useInfiniteQuery = useInfiniteQuery;
|
||||
exports.useIsFetching = useIsFetching;
|
||||
exports.useIsMutating = useIsMutating;
|
||||
exports.useMutation = useMutation;
|
||||
exports.useQueries = useQueries;
|
||||
exports.useQuery = useQuery;
|
||||
exports.useQueryClient = useQueryClient;
|
||||
exports.useQueryErrorResetBoundary = useQueryErrorResetBoundary;
|
||||
|
||||
Object.defineProperty(exports, '__esModule', { value: true });
|
||||
|
||||
})));
|
||||
//# sourceMappingURL=react-query.development.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
+2
File diff suppressed because one or more lines are too long
+1
File diff suppressed because one or more lines are too long
Generated
Vendored
+80
@@ -0,0 +1,80 @@
|
||||
import { BroadcastChannel } from 'broadcast-channel';
|
||||
export function broadcastQueryClient(_ref) {
|
||||
var queryClient = _ref.queryClient,
|
||||
_ref$broadcastChannel = _ref.broadcastChannel,
|
||||
broadcastChannel = _ref$broadcastChannel === void 0 ? 'react-query' : _ref$broadcastChannel;
|
||||
var transaction = false;
|
||||
|
||||
var tx = function tx(cb) {
|
||||
transaction = true;
|
||||
cb();
|
||||
transaction = false;
|
||||
};
|
||||
|
||||
var channel = new BroadcastChannel(broadcastChannel, {
|
||||
webWorkerSupport: false
|
||||
});
|
||||
var queryCache = queryClient.getQueryCache();
|
||||
queryClient.getQueryCache().subscribe(function (queryEvent) {
|
||||
var _queryEvent$action;
|
||||
|
||||
if (transaction || !(queryEvent == null ? void 0 : queryEvent.query)) {
|
||||
return;
|
||||
}
|
||||
|
||||
var _queryEvent$query = queryEvent.query,
|
||||
queryHash = _queryEvent$query.queryHash,
|
||||
queryKey = _queryEvent$query.queryKey,
|
||||
state = _queryEvent$query.state;
|
||||
|
||||
if (queryEvent.type === 'queryUpdated' && ((_queryEvent$action = queryEvent.action) == null ? void 0 : _queryEvent$action.type) === 'success') {
|
||||
channel.postMessage({
|
||||
type: 'queryUpdated',
|
||||
queryHash: queryHash,
|
||||
queryKey: queryKey,
|
||||
state: state
|
||||
});
|
||||
}
|
||||
|
||||
if (queryEvent.type === 'queryRemoved') {
|
||||
channel.postMessage({
|
||||
type: 'queryRemoved',
|
||||
queryHash: queryHash,
|
||||
queryKey: queryKey
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
channel.onmessage = function (action) {
|
||||
if (!(action == null ? void 0 : action.type)) {
|
||||
return;
|
||||
}
|
||||
|
||||
tx(function () {
|
||||
var type = action.type,
|
||||
queryHash = action.queryHash,
|
||||
queryKey = action.queryKey,
|
||||
state = action.state;
|
||||
|
||||
if (type === 'queryUpdated') {
|
||||
var query = queryCache.get(queryHash);
|
||||
|
||||
if (query) {
|
||||
query.setState(state);
|
||||
return;
|
||||
}
|
||||
|
||||
queryCache.build(queryClient, {
|
||||
queryKey: queryKey,
|
||||
queryHash: queryHash
|
||||
}, state);
|
||||
} else if (type === 'queryRemoved') {
|
||||
var _query = queryCache.get(queryHash);
|
||||
|
||||
if (_query) {
|
||||
queryCache.remove(_query);
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
}
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
import _inheritsLoose from "@babel/runtime/helpers/esm/inheritsLoose";
|
||||
import { Subscribable } from './subscribable';
|
||||
import { isServer } from './utils';
|
||||
export var FocusManager = /*#__PURE__*/function (_Subscribable) {
|
||||
_inheritsLoose(FocusManager, _Subscribable);
|
||||
|
||||
function FocusManager() {
|
||||
var _this;
|
||||
|
||||
_this = _Subscribable.call(this) || this;
|
||||
|
||||
_this.setup = function (onFocus) {
|
||||
var _window;
|
||||
|
||||
if (!isServer && ((_window = window) == null ? void 0 : _window.addEventListener)) {
|
||||
var listener = function listener() {
|
||||
return onFocus();
|
||||
}; // Listen to visibillitychange and focus
|
||||
|
||||
|
||||
window.addEventListener('visibilitychange', listener, false);
|
||||
window.addEventListener('focus', listener, false);
|
||||
return function () {
|
||||
// Be sure to unsubscribe if a new handler is set
|
||||
window.removeEventListener('visibilitychange', listener);
|
||||
window.removeEventListener('focus', listener);
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
return _this;
|
||||
}
|
||||
|
||||
var _proto = FocusManager.prototype;
|
||||
|
||||
_proto.onSubscribe = function onSubscribe() {
|
||||
if (!this.cleanup) {
|
||||
this.setEventListener(this.setup);
|
||||
}
|
||||
};
|
||||
|
||||
_proto.onUnsubscribe = function onUnsubscribe() {
|
||||
if (!this.hasListeners()) {
|
||||
var _this$cleanup;
|
||||
|
||||
(_this$cleanup = this.cleanup) == null ? void 0 : _this$cleanup.call(this);
|
||||
this.cleanup = undefined;
|
||||
}
|
||||
};
|
||||
|
||||
_proto.setEventListener = function setEventListener(setup) {
|
||||
var _this$cleanup2,
|
||||
_this2 = this;
|
||||
|
||||
this.setup = setup;
|
||||
(_this$cleanup2 = this.cleanup) == null ? void 0 : _this$cleanup2.call(this);
|
||||
this.cleanup = setup(function (focused) {
|
||||
if (typeof focused === 'boolean') {
|
||||
_this2.setFocused(focused);
|
||||
} else {
|
||||
_this2.onFocus();
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
_proto.setFocused = function setFocused(focused) {
|
||||
this.focused = focused;
|
||||
|
||||
if (focused) {
|
||||
this.onFocus();
|
||||
}
|
||||
};
|
||||
|
||||
_proto.onFocus = function onFocus() {
|
||||
this.listeners.forEach(function (listener) {
|
||||
listener();
|
||||
});
|
||||
};
|
||||
|
||||
_proto.isFocused = function isFocused() {
|
||||
if (typeof this.focused === 'boolean') {
|
||||
return this.focused;
|
||||
} // document global can be unavailable in react native
|
||||
|
||||
|
||||
if (typeof document === 'undefined') {
|
||||
return true;
|
||||
}
|
||||
|
||||
return [undefined, 'visible', 'prerender'].includes(document.visibilityState);
|
||||
};
|
||||
|
||||
return FocusManager;
|
||||
}(Subscribable);
|
||||
export var focusManager = new FocusManager();
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
import _extends from "@babel/runtime/helpers/esm/extends";
|
||||
|
||||
// TYPES
|
||||
// FUNCTIONS
|
||||
function dehydrateMutation(mutation) {
|
||||
return {
|
||||
mutationKey: mutation.options.mutationKey,
|
||||
state: mutation.state
|
||||
};
|
||||
} // Most config is not dehydrated but instead meant to configure again when
|
||||
// consuming the de/rehydrated data, typically with useQuery on the client.
|
||||
// Sometimes it might make sense to prefetch data on the server and include
|
||||
// in the html-payload, but not consume it on the initial render.
|
||||
|
||||
|
||||
function dehydrateQuery(query) {
|
||||
return {
|
||||
state: query.state,
|
||||
queryKey: query.queryKey,
|
||||
queryHash: query.queryHash
|
||||
};
|
||||
}
|
||||
|
||||
function defaultShouldDehydrateMutation(mutation) {
|
||||
return mutation.state.isPaused;
|
||||
}
|
||||
|
||||
function defaultShouldDehydrateQuery(query) {
|
||||
return query.state.status === 'success';
|
||||
}
|
||||
|
||||
export function dehydrate(client, options) {
|
||||
var _options, _options2;
|
||||
|
||||
options = options || {};
|
||||
var mutations = [];
|
||||
var queries = [];
|
||||
|
||||
if (((_options = options) == null ? void 0 : _options.dehydrateMutations) !== false) {
|
||||
var shouldDehydrateMutation = options.shouldDehydrateMutation || defaultShouldDehydrateMutation;
|
||||
client.getMutationCache().getAll().forEach(function (mutation) {
|
||||
if (shouldDehydrateMutation(mutation)) {
|
||||
mutations.push(dehydrateMutation(mutation));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (((_options2 = options) == null ? void 0 : _options2.dehydrateQueries) !== false) {
|
||||
var shouldDehydrateQuery = options.shouldDehydrateQuery || defaultShouldDehydrateQuery;
|
||||
client.getQueryCache().getAll().forEach(function (query) {
|
||||
if (shouldDehydrateQuery(query)) {
|
||||
queries.push(dehydrateQuery(query));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
mutations: mutations,
|
||||
queries: queries
|
||||
};
|
||||
}
|
||||
export function hydrate(client, dehydratedState, options) {
|
||||
if (typeof dehydratedState !== 'object' || dehydratedState === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
var mutationCache = client.getMutationCache();
|
||||
var queryCache = client.getQueryCache();
|
||||
var mutations = dehydratedState.mutations || [];
|
||||
var queries = dehydratedState.queries || [];
|
||||
mutations.forEach(function (dehydratedMutation) {
|
||||
var _options$defaultOptio;
|
||||
|
||||
mutationCache.build(client, _extends({}, options == null ? void 0 : (_options$defaultOptio = options.defaultOptions) == null ? void 0 : _options$defaultOptio.mutations, {
|
||||
mutationKey: dehydratedMutation.mutationKey
|
||||
}), dehydratedMutation.state);
|
||||
});
|
||||
queries.forEach(function (dehydratedQuery) {
|
||||
var _options$defaultOptio2;
|
||||
|
||||
var query = queryCache.get(dehydratedQuery.queryHash); // Do not hydrate if an existing query exists with newer data
|
||||
|
||||
if (query) {
|
||||
if (query.state.dataUpdatedAt < dehydratedQuery.state.dataUpdatedAt) {
|
||||
query.setState(dehydratedQuery.state);
|
||||
}
|
||||
|
||||
return;
|
||||
} // Restore query
|
||||
|
||||
|
||||
queryCache.build(client, _extends({}, options == null ? void 0 : (_options$defaultOptio2 = options.defaultOptions) == null ? void 0 : _options$defaultOptio2.queries, {
|
||||
queryKey: dehydratedQuery.queryKey,
|
||||
queryHash: dehydratedQuery.queryHash
|
||||
}), dehydratedQuery.state);
|
||||
});
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
export { CancelledError } from './retryer';
|
||||
export { QueryCache } from './queryCache';
|
||||
export { QueryClient } from './queryClient';
|
||||
export { QueryObserver } from './queryObserver';
|
||||
export { QueriesObserver } from './queriesObserver';
|
||||
export { InfiniteQueryObserver } from './infiniteQueryObserver';
|
||||
export { MutationCache } from './mutationCache';
|
||||
export { MutationObserver } from './mutationObserver';
|
||||
export { setLogger } from './logger';
|
||||
export { notifyManager } from './notifyManager';
|
||||
export { focusManager } from './focusManager';
|
||||
export { onlineManager } from './onlineManager';
|
||||
export { hashQueryKey, isError } from './utils';
|
||||
export { isCancelledError } from './retryer';
|
||||
export { dehydrate, hydrate } from './hydration'; // Types
|
||||
|
||||
export * from './types';
|
||||
+153
@@ -0,0 +1,153 @@
|
||||
import { isCancelable } from './retryer';
|
||||
import { getAbortController } from './utils';
|
||||
export function infiniteQueryBehavior() {
|
||||
return {
|
||||
onFetch: function onFetch(context) {
|
||||
context.fetchFn = function () {
|
||||
var _context$fetchOptions, _context$fetchOptions2, _context$fetchOptions3, _context$fetchOptions4, _context$state$data, _context$state$data2;
|
||||
|
||||
var refetchPage = (_context$fetchOptions = context.fetchOptions) == null ? void 0 : (_context$fetchOptions2 = _context$fetchOptions.meta) == null ? void 0 : _context$fetchOptions2.refetchPage;
|
||||
var fetchMore = (_context$fetchOptions3 = context.fetchOptions) == null ? void 0 : (_context$fetchOptions4 = _context$fetchOptions3.meta) == null ? void 0 : _context$fetchOptions4.fetchMore;
|
||||
var pageParam = fetchMore == null ? void 0 : fetchMore.pageParam;
|
||||
var isFetchingNextPage = (fetchMore == null ? void 0 : fetchMore.direction) === 'forward';
|
||||
var isFetchingPreviousPage = (fetchMore == null ? void 0 : fetchMore.direction) === 'backward';
|
||||
var oldPages = ((_context$state$data = context.state.data) == null ? void 0 : _context$state$data.pages) || [];
|
||||
var oldPageParams = ((_context$state$data2 = context.state.data) == null ? void 0 : _context$state$data2.pageParams) || [];
|
||||
var abortController = getAbortController();
|
||||
var abortSignal = abortController == null ? void 0 : abortController.signal;
|
||||
var newPageParams = oldPageParams;
|
||||
var cancelled = false; // Get query function
|
||||
|
||||
var queryFn = context.options.queryFn || function () {
|
||||
return Promise.reject('Missing queryFn');
|
||||
};
|
||||
|
||||
var buildNewPages = function buildNewPages(pages, param, page, previous) {
|
||||
newPageParams = previous ? [param].concat(newPageParams) : [].concat(newPageParams, [param]);
|
||||
return previous ? [page].concat(pages) : [].concat(pages, [page]);
|
||||
}; // Create function to fetch a page
|
||||
|
||||
|
||||
var fetchPage = function fetchPage(pages, manual, param, previous) {
|
||||
if (cancelled) {
|
||||
return Promise.reject('Cancelled');
|
||||
}
|
||||
|
||||
if (typeof param === 'undefined' && !manual && pages.length) {
|
||||
return Promise.resolve(pages);
|
||||
}
|
||||
|
||||
var queryFnContext = {
|
||||
queryKey: context.queryKey,
|
||||
signal: abortSignal,
|
||||
pageParam: param,
|
||||
meta: context.meta
|
||||
};
|
||||
var queryFnResult = queryFn(queryFnContext);
|
||||
var promise = Promise.resolve(queryFnResult).then(function (page) {
|
||||
return buildNewPages(pages, param, page, previous);
|
||||
});
|
||||
|
||||
if (isCancelable(queryFnResult)) {
|
||||
var promiseAsAny = promise;
|
||||
promiseAsAny.cancel = queryFnResult.cancel;
|
||||
}
|
||||
|
||||
return promise;
|
||||
};
|
||||
|
||||
var promise; // Fetch first page?
|
||||
|
||||
if (!oldPages.length) {
|
||||
promise = fetchPage([]);
|
||||
} // Fetch next page?
|
||||
else if (isFetchingNextPage) {
|
||||
var manual = typeof pageParam !== 'undefined';
|
||||
var param = manual ? pageParam : getNextPageParam(context.options, oldPages);
|
||||
promise = fetchPage(oldPages, manual, param);
|
||||
} // Fetch previous page?
|
||||
else if (isFetchingPreviousPage) {
|
||||
var _manual = typeof pageParam !== 'undefined';
|
||||
|
||||
var _param = _manual ? pageParam : getPreviousPageParam(context.options, oldPages);
|
||||
|
||||
promise = fetchPage(oldPages, _manual, _param, true);
|
||||
} // Refetch pages
|
||||
else {
|
||||
(function () {
|
||||
newPageParams = [];
|
||||
var manual = typeof context.options.getNextPageParam === 'undefined';
|
||||
var shouldFetchFirstPage = refetchPage && oldPages[0] ? refetchPage(oldPages[0], 0, oldPages) : true; // Fetch first page
|
||||
|
||||
promise = shouldFetchFirstPage ? fetchPage([], manual, oldPageParams[0]) : Promise.resolve(buildNewPages([], oldPageParams[0], oldPages[0])); // Fetch remaining pages
|
||||
|
||||
var _loop = function _loop(i) {
|
||||
promise = promise.then(function (pages) {
|
||||
var shouldFetchNextPage = refetchPage && oldPages[i] ? refetchPage(oldPages[i], i, oldPages) : true;
|
||||
|
||||
if (shouldFetchNextPage) {
|
||||
var _param2 = manual ? oldPageParams[i] : getNextPageParam(context.options, pages);
|
||||
|
||||
return fetchPage(pages, manual, _param2);
|
||||
}
|
||||
|
||||
return Promise.resolve(buildNewPages(pages, oldPageParams[i], oldPages[i]));
|
||||
});
|
||||
};
|
||||
|
||||
for (var i = 1; i < oldPages.length; i++) {
|
||||
_loop(i);
|
||||
}
|
||||
})();
|
||||
}
|
||||
|
||||
var finalPromise = promise.then(function (pages) {
|
||||
return {
|
||||
pages: pages,
|
||||
pageParams: newPageParams
|
||||
};
|
||||
});
|
||||
var finalPromiseAsAny = finalPromise;
|
||||
|
||||
finalPromiseAsAny.cancel = function () {
|
||||
cancelled = true;
|
||||
abortController == null ? void 0 : abortController.abort();
|
||||
|
||||
if (isCancelable(promise)) {
|
||||
promise.cancel();
|
||||
}
|
||||
};
|
||||
|
||||
return finalPromise;
|
||||
};
|
||||
}
|
||||
};
|
||||
}
|
||||
export function getNextPageParam(options, pages) {
|
||||
return options.getNextPageParam == null ? void 0 : options.getNextPageParam(pages[pages.length - 1], pages);
|
||||
}
|
||||
export function getPreviousPageParam(options, pages) {
|
||||
return options.getPreviousPageParam == null ? void 0 : options.getPreviousPageParam(pages[0], pages);
|
||||
}
|
||||
/**
|
||||
* Checks if there is a next page.
|
||||
* Returns `undefined` if it cannot be determined.
|
||||
*/
|
||||
|
||||
export function hasNextPage(options, pages) {
|
||||
if (options.getNextPageParam && Array.isArray(pages)) {
|
||||
var nextPageParam = getNextPageParam(options, pages);
|
||||
return typeof nextPageParam !== 'undefined' && nextPageParam !== null && nextPageParam !== false;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Checks if there is a previous page.
|
||||
* Returns `undefined` if it cannot be determined.
|
||||
*/
|
||||
|
||||
export function hasPreviousPage(options, pages) {
|
||||
if (options.getPreviousPageParam && Array.isArray(pages)) {
|
||||
var previousPageParam = getPreviousPageParam(options, pages);
|
||||
return typeof previousPageParam !== 'undefined' && previousPageParam !== null && previousPageParam !== false;
|
||||
}
|
||||
}
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
import _extends from "@babel/runtime/helpers/esm/extends";
|
||||
import _inheritsLoose from "@babel/runtime/helpers/esm/inheritsLoose";
|
||||
import { QueryObserver } from './queryObserver';
|
||||
import { hasNextPage, hasPreviousPage, infiniteQueryBehavior } from './infiniteQueryBehavior';
|
||||
export var InfiniteQueryObserver = /*#__PURE__*/function (_QueryObserver) {
|
||||
_inheritsLoose(InfiniteQueryObserver, _QueryObserver);
|
||||
|
||||
// Type override
|
||||
// Type override
|
||||
// Type override
|
||||
// eslint-disable-next-line @typescript-eslint/no-useless-constructor
|
||||
function InfiniteQueryObserver(client, options) {
|
||||
return _QueryObserver.call(this, client, options) || this;
|
||||
}
|
||||
|
||||
var _proto = InfiniteQueryObserver.prototype;
|
||||
|
||||
_proto.bindMethods = function bindMethods() {
|
||||
_QueryObserver.prototype.bindMethods.call(this);
|
||||
|
||||
this.fetchNextPage = this.fetchNextPage.bind(this);
|
||||
this.fetchPreviousPage = this.fetchPreviousPage.bind(this);
|
||||
};
|
||||
|
||||
_proto.setOptions = function setOptions(options, notifyOptions) {
|
||||
_QueryObserver.prototype.setOptions.call(this, _extends({}, options, {
|
||||
behavior: infiniteQueryBehavior()
|
||||
}), notifyOptions);
|
||||
};
|
||||
|
||||
_proto.getOptimisticResult = function getOptimisticResult(options) {
|
||||
options.behavior = infiniteQueryBehavior();
|
||||
return _QueryObserver.prototype.getOptimisticResult.call(this, options);
|
||||
};
|
||||
|
||||
_proto.fetchNextPage = function fetchNextPage(options) {
|
||||
var _options$cancelRefetc;
|
||||
|
||||
return this.fetch({
|
||||
// TODO consider removing `?? true` in future breaking change, to be consistent with `refetch` API (see https://github.com/tannerlinsley/react-query/issues/2617)
|
||||
cancelRefetch: (_options$cancelRefetc = options == null ? void 0 : options.cancelRefetch) != null ? _options$cancelRefetc : true,
|
||||
throwOnError: options == null ? void 0 : options.throwOnError,
|
||||
meta: {
|
||||
fetchMore: {
|
||||
direction: 'forward',
|
||||
pageParam: options == null ? void 0 : options.pageParam
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
_proto.fetchPreviousPage = function fetchPreviousPage(options) {
|
||||
var _options$cancelRefetc2;
|
||||
|
||||
return this.fetch({
|
||||
// TODO consider removing `?? true` in future breaking change, to be consistent with `refetch` API (see https://github.com/tannerlinsley/react-query/issues/2617)
|
||||
cancelRefetch: (_options$cancelRefetc2 = options == null ? void 0 : options.cancelRefetch) != null ? _options$cancelRefetc2 : true,
|
||||
throwOnError: options == null ? void 0 : options.throwOnError,
|
||||
meta: {
|
||||
fetchMore: {
|
||||
direction: 'backward',
|
||||
pageParam: options == null ? void 0 : options.pageParam
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
_proto.createResult = function createResult(query, options) {
|
||||
var _state$data, _state$data2, _state$fetchMeta, _state$fetchMeta$fetc, _state$fetchMeta2, _state$fetchMeta2$fet;
|
||||
|
||||
var state = query.state;
|
||||
|
||||
var result = _QueryObserver.prototype.createResult.call(this, query, options);
|
||||
|
||||
return _extends({}, result, {
|
||||
fetchNextPage: this.fetchNextPage,
|
||||
fetchPreviousPage: this.fetchPreviousPage,
|
||||
hasNextPage: hasNextPage(options, (_state$data = state.data) == null ? void 0 : _state$data.pages),
|
||||
hasPreviousPage: hasPreviousPage(options, (_state$data2 = state.data) == null ? void 0 : _state$data2.pages),
|
||||
isFetchingNextPage: state.isFetching && ((_state$fetchMeta = state.fetchMeta) == null ? void 0 : (_state$fetchMeta$fetc = _state$fetchMeta.fetchMore) == null ? void 0 : _state$fetchMeta$fetc.direction) === 'forward',
|
||||
isFetchingPreviousPage: state.isFetching && ((_state$fetchMeta2 = state.fetchMeta) == null ? void 0 : (_state$fetchMeta2$fet = _state$fetchMeta2.fetchMore) == null ? void 0 : _state$fetchMeta2$fet.direction) === 'backward'
|
||||
});
|
||||
};
|
||||
|
||||
return InfiniteQueryObserver;
|
||||
}(QueryObserver);
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
// TYPES
|
||||
// FUNCTIONS
|
||||
var logger = console;
|
||||
export function getLogger() {
|
||||
return logger;
|
||||
}
|
||||
export function setLogger(newLogger) {
|
||||
logger = newLogger;
|
||||
}
|
||||
+232
@@ -0,0 +1,232 @@
|
||||
import _extends from "@babel/runtime/helpers/esm/extends";
|
||||
import { getLogger } from './logger';
|
||||
import { notifyManager } from './notifyManager';
|
||||
import { Retryer } from './retryer';
|
||||
import { noop } from './utils'; // TYPES
|
||||
|
||||
// CLASS
|
||||
export var Mutation = /*#__PURE__*/function () {
|
||||
function Mutation(config) {
|
||||
this.options = _extends({}, config.defaultOptions, config.options);
|
||||
this.mutationId = config.mutationId;
|
||||
this.mutationCache = config.mutationCache;
|
||||
this.observers = [];
|
||||
this.state = config.state || getDefaultState();
|
||||
this.meta = config.meta;
|
||||
}
|
||||
|
||||
var _proto = Mutation.prototype;
|
||||
|
||||
_proto.setState = function setState(state) {
|
||||
this.dispatch({
|
||||
type: 'setState',
|
||||
state: state
|
||||
});
|
||||
};
|
||||
|
||||
_proto.addObserver = function addObserver(observer) {
|
||||
if (this.observers.indexOf(observer) === -1) {
|
||||
this.observers.push(observer);
|
||||
}
|
||||
};
|
||||
|
||||
_proto.removeObserver = function removeObserver(observer) {
|
||||
this.observers = this.observers.filter(function (x) {
|
||||
return x !== observer;
|
||||
});
|
||||
};
|
||||
|
||||
_proto.cancel = function cancel() {
|
||||
if (this.retryer) {
|
||||
this.retryer.cancel();
|
||||
return this.retryer.promise.then(noop).catch(noop);
|
||||
}
|
||||
|
||||
return Promise.resolve();
|
||||
};
|
||||
|
||||
_proto.continue = function _continue() {
|
||||
if (this.retryer) {
|
||||
this.retryer.continue();
|
||||
return this.retryer.promise;
|
||||
}
|
||||
|
||||
return this.execute();
|
||||
};
|
||||
|
||||
_proto.execute = function execute() {
|
||||
var _this = this;
|
||||
|
||||
var data;
|
||||
var restored = this.state.status === 'loading';
|
||||
var promise = Promise.resolve();
|
||||
|
||||
if (!restored) {
|
||||
this.dispatch({
|
||||
type: 'loading',
|
||||
variables: this.options.variables
|
||||
});
|
||||
promise = promise.then(function () {
|
||||
// Notify cache callback
|
||||
_this.mutationCache.config.onMutate == null ? void 0 : _this.mutationCache.config.onMutate(_this.state.variables, _this);
|
||||
}).then(function () {
|
||||
return _this.options.onMutate == null ? void 0 : _this.options.onMutate(_this.state.variables);
|
||||
}).then(function (context) {
|
||||
if (context !== _this.state.context) {
|
||||
_this.dispatch({
|
||||
type: 'loading',
|
||||
context: context,
|
||||
variables: _this.state.variables
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return promise.then(function () {
|
||||
return _this.executeMutation();
|
||||
}).then(function (result) {
|
||||
data = result; // Notify cache callback
|
||||
|
||||
_this.mutationCache.config.onSuccess == null ? void 0 : _this.mutationCache.config.onSuccess(data, _this.state.variables, _this.state.context, _this);
|
||||
}).then(function () {
|
||||
return _this.options.onSuccess == null ? void 0 : _this.options.onSuccess(data, _this.state.variables, _this.state.context);
|
||||
}).then(function () {
|
||||
return _this.options.onSettled == null ? void 0 : _this.options.onSettled(data, null, _this.state.variables, _this.state.context);
|
||||
}).then(function () {
|
||||
_this.dispatch({
|
||||
type: 'success',
|
||||
data: data
|
||||
});
|
||||
|
||||
return data;
|
||||
}).catch(function (error) {
|
||||
// Notify cache callback
|
||||
_this.mutationCache.config.onError == null ? void 0 : _this.mutationCache.config.onError(error, _this.state.variables, _this.state.context, _this); // Log error
|
||||
|
||||
getLogger().error(error);
|
||||
return Promise.resolve().then(function () {
|
||||
return _this.options.onError == null ? void 0 : _this.options.onError(error, _this.state.variables, _this.state.context);
|
||||
}).then(function () {
|
||||
return _this.options.onSettled == null ? void 0 : _this.options.onSettled(undefined, error, _this.state.variables, _this.state.context);
|
||||
}).then(function () {
|
||||
_this.dispatch({
|
||||
type: 'error',
|
||||
error: error
|
||||
});
|
||||
|
||||
throw error;
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
_proto.executeMutation = function executeMutation() {
|
||||
var _this2 = this,
|
||||
_this$options$retry;
|
||||
|
||||
this.retryer = new Retryer({
|
||||
fn: function fn() {
|
||||
if (!_this2.options.mutationFn) {
|
||||
return Promise.reject('No mutationFn found');
|
||||
}
|
||||
|
||||
return _this2.options.mutationFn(_this2.state.variables);
|
||||
},
|
||||
onFail: function onFail() {
|
||||
_this2.dispatch({
|
||||
type: 'failed'
|
||||
});
|
||||
},
|
||||
onPause: function onPause() {
|
||||
_this2.dispatch({
|
||||
type: 'pause'
|
||||
});
|
||||
},
|
||||
onContinue: function onContinue() {
|
||||
_this2.dispatch({
|
||||
type: 'continue'
|
||||
});
|
||||
},
|
||||
retry: (_this$options$retry = this.options.retry) != null ? _this$options$retry : 0,
|
||||
retryDelay: this.options.retryDelay
|
||||
});
|
||||
return this.retryer.promise;
|
||||
};
|
||||
|
||||
_proto.dispatch = function dispatch(action) {
|
||||
var _this3 = this;
|
||||
|
||||
this.state = reducer(this.state, action);
|
||||
notifyManager.batch(function () {
|
||||
_this3.observers.forEach(function (observer) {
|
||||
observer.onMutationUpdate(action);
|
||||
});
|
||||
|
||||
_this3.mutationCache.notify(_this3);
|
||||
});
|
||||
};
|
||||
|
||||
return Mutation;
|
||||
}();
|
||||
export function getDefaultState() {
|
||||
return {
|
||||
context: undefined,
|
||||
data: undefined,
|
||||
error: null,
|
||||
failureCount: 0,
|
||||
isPaused: false,
|
||||
status: 'idle',
|
||||
variables: undefined
|
||||
};
|
||||
}
|
||||
|
||||
function reducer(state, action) {
|
||||
switch (action.type) {
|
||||
case 'failed':
|
||||
return _extends({}, state, {
|
||||
failureCount: state.failureCount + 1
|
||||
});
|
||||
|
||||
case 'pause':
|
||||
return _extends({}, state, {
|
||||
isPaused: true
|
||||
});
|
||||
|
||||
case 'continue':
|
||||
return _extends({}, state, {
|
||||
isPaused: false
|
||||
});
|
||||
|
||||
case 'loading':
|
||||
return _extends({}, state, {
|
||||
context: action.context,
|
||||
data: undefined,
|
||||
error: null,
|
||||
isPaused: false,
|
||||
status: 'loading',
|
||||
variables: action.variables
|
||||
});
|
||||
|
||||
case 'success':
|
||||
return _extends({}, state, {
|
||||
data: action.data,
|
||||
error: null,
|
||||
status: 'success',
|
||||
isPaused: false
|
||||
});
|
||||
|
||||
case 'error':
|
||||
return _extends({}, state, {
|
||||
data: undefined,
|
||||
error: action.error,
|
||||
failureCount: state.failureCount + 1,
|
||||
isPaused: false,
|
||||
status: 'error'
|
||||
});
|
||||
|
||||
case 'setState':
|
||||
return _extends({}, state, action.state);
|
||||
|
||||
default:
|
||||
return state;
|
||||
}
|
||||
}
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
import _inheritsLoose from "@babel/runtime/helpers/esm/inheritsLoose";
|
||||
import { notifyManager } from './notifyManager';
|
||||
import { Mutation } from './mutation';
|
||||
import { matchMutation, noop } from './utils';
|
||||
import { Subscribable } from './subscribable'; // TYPES
|
||||
|
||||
// CLASS
|
||||
export var MutationCache = /*#__PURE__*/function (_Subscribable) {
|
||||
_inheritsLoose(MutationCache, _Subscribable);
|
||||
|
||||
function MutationCache(config) {
|
||||
var _this;
|
||||
|
||||
_this = _Subscribable.call(this) || this;
|
||||
_this.config = config || {};
|
||||
_this.mutations = [];
|
||||
_this.mutationId = 0;
|
||||
return _this;
|
||||
}
|
||||
|
||||
var _proto = MutationCache.prototype;
|
||||
|
||||
_proto.build = function build(client, options, state) {
|
||||
var mutation = new Mutation({
|
||||
mutationCache: this,
|
||||
mutationId: ++this.mutationId,
|
||||
options: client.defaultMutationOptions(options),
|
||||
state: state,
|
||||
defaultOptions: options.mutationKey ? client.getMutationDefaults(options.mutationKey) : undefined,
|
||||
meta: options.meta
|
||||
});
|
||||
this.add(mutation);
|
||||
return mutation;
|
||||
};
|
||||
|
||||
_proto.add = function add(mutation) {
|
||||
this.mutations.push(mutation);
|
||||
this.notify(mutation);
|
||||
};
|
||||
|
||||
_proto.remove = function remove(mutation) {
|
||||
this.mutations = this.mutations.filter(function (x) {
|
||||
return x !== mutation;
|
||||
});
|
||||
mutation.cancel();
|
||||
this.notify(mutation);
|
||||
};
|
||||
|
||||
_proto.clear = function clear() {
|
||||
var _this2 = this;
|
||||
|
||||
notifyManager.batch(function () {
|
||||
_this2.mutations.forEach(function (mutation) {
|
||||
_this2.remove(mutation);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
_proto.getAll = function getAll() {
|
||||
return this.mutations;
|
||||
};
|
||||
|
||||
_proto.find = function find(filters) {
|
||||
if (typeof filters.exact === 'undefined') {
|
||||
filters.exact = true;
|
||||
}
|
||||
|
||||
return this.mutations.find(function (mutation) {
|
||||
return matchMutation(filters, mutation);
|
||||
});
|
||||
};
|
||||
|
||||
_proto.findAll = function findAll(filters) {
|
||||
return this.mutations.filter(function (mutation) {
|
||||
return matchMutation(filters, mutation);
|
||||
});
|
||||
};
|
||||
|
||||
_proto.notify = function notify(mutation) {
|
||||
var _this3 = this;
|
||||
|
||||
notifyManager.batch(function () {
|
||||
_this3.listeners.forEach(function (listener) {
|
||||
listener(mutation);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
_proto.onFocus = function onFocus() {
|
||||
this.resumePausedMutations();
|
||||
};
|
||||
|
||||
_proto.onOnline = function onOnline() {
|
||||
this.resumePausedMutations();
|
||||
};
|
||||
|
||||
_proto.resumePausedMutations = function resumePausedMutations() {
|
||||
var pausedMutations = this.mutations.filter(function (x) {
|
||||
return x.state.isPaused;
|
||||
});
|
||||
return notifyManager.batch(function () {
|
||||
return pausedMutations.reduce(function (promise, mutation) {
|
||||
return promise.then(function () {
|
||||
return mutation.continue().catch(noop);
|
||||
});
|
||||
}, Promise.resolve());
|
||||
});
|
||||
};
|
||||
|
||||
return MutationCache;
|
||||
}(Subscribable);
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
import _extends from "@babel/runtime/helpers/esm/extends";
|
||||
import _inheritsLoose from "@babel/runtime/helpers/esm/inheritsLoose";
|
||||
import { getDefaultState } from './mutation';
|
||||
import { notifyManager } from './notifyManager';
|
||||
import { Subscribable } from './subscribable';
|
||||
// CLASS
|
||||
export var MutationObserver = /*#__PURE__*/function (_Subscribable) {
|
||||
_inheritsLoose(MutationObserver, _Subscribable);
|
||||
|
||||
function MutationObserver(client, options) {
|
||||
var _this;
|
||||
|
||||
_this = _Subscribable.call(this) || this;
|
||||
_this.client = client;
|
||||
|
||||
_this.setOptions(options);
|
||||
|
||||
_this.bindMethods();
|
||||
|
||||
_this.updateResult();
|
||||
|
||||
return _this;
|
||||
}
|
||||
|
||||
var _proto = MutationObserver.prototype;
|
||||
|
||||
_proto.bindMethods = function bindMethods() {
|
||||
this.mutate = this.mutate.bind(this);
|
||||
this.reset = this.reset.bind(this);
|
||||
};
|
||||
|
||||
_proto.setOptions = function setOptions(options) {
|
||||
this.options = this.client.defaultMutationOptions(options);
|
||||
};
|
||||
|
||||
_proto.onUnsubscribe = function onUnsubscribe() {
|
||||
if (!this.listeners.length) {
|
||||
var _this$currentMutation;
|
||||
|
||||
(_this$currentMutation = this.currentMutation) == null ? void 0 : _this$currentMutation.removeObserver(this);
|
||||
}
|
||||
};
|
||||
|
||||
_proto.onMutationUpdate = function onMutationUpdate(action) {
|
||||
this.updateResult(); // Determine which callbacks to trigger
|
||||
|
||||
var notifyOptions = {
|
||||
listeners: true
|
||||
};
|
||||
|
||||
if (action.type === 'success') {
|
||||
notifyOptions.onSuccess = true;
|
||||
} else if (action.type === 'error') {
|
||||
notifyOptions.onError = true;
|
||||
}
|
||||
|
||||
this.notify(notifyOptions);
|
||||
};
|
||||
|
||||
_proto.getCurrentResult = function getCurrentResult() {
|
||||
return this.currentResult;
|
||||
};
|
||||
|
||||
_proto.reset = function reset() {
|
||||
this.currentMutation = undefined;
|
||||
this.updateResult();
|
||||
this.notify({
|
||||
listeners: true
|
||||
});
|
||||
};
|
||||
|
||||
_proto.mutate = function mutate(variables, options) {
|
||||
this.mutateOptions = options;
|
||||
|
||||
if (this.currentMutation) {
|
||||
this.currentMutation.removeObserver(this);
|
||||
}
|
||||
|
||||
this.currentMutation = this.client.getMutationCache().build(this.client, _extends({}, this.options, {
|
||||
variables: typeof variables !== 'undefined' ? variables : this.options.variables
|
||||
}));
|
||||
this.currentMutation.addObserver(this);
|
||||
return this.currentMutation.execute();
|
||||
};
|
||||
|
||||
_proto.updateResult = function updateResult() {
|
||||
var state = this.currentMutation ? this.currentMutation.state : getDefaultState();
|
||||
|
||||
var result = _extends({}, state, {
|
||||
isLoading: state.status === 'loading',
|
||||
isSuccess: state.status === 'success',
|
||||
isError: state.status === 'error',
|
||||
isIdle: state.status === 'idle',
|
||||
mutate: this.mutate,
|
||||
reset: this.reset
|
||||
});
|
||||
|
||||
this.currentResult = result;
|
||||
};
|
||||
|
||||
_proto.notify = function notify(options) {
|
||||
var _this2 = this;
|
||||
|
||||
notifyManager.batch(function () {
|
||||
// First trigger the mutate callbacks
|
||||
if (_this2.mutateOptions) {
|
||||
if (options.onSuccess) {
|
||||
_this2.mutateOptions.onSuccess == null ? void 0 : _this2.mutateOptions.onSuccess(_this2.currentResult.data, _this2.currentResult.variables, _this2.currentResult.context);
|
||||
_this2.mutateOptions.onSettled == null ? void 0 : _this2.mutateOptions.onSettled(_this2.currentResult.data, null, _this2.currentResult.variables, _this2.currentResult.context);
|
||||
} else if (options.onError) {
|
||||
_this2.mutateOptions.onError == null ? void 0 : _this2.mutateOptions.onError(_this2.currentResult.error, _this2.currentResult.variables, _this2.currentResult.context);
|
||||
_this2.mutateOptions.onSettled == null ? void 0 : _this2.mutateOptions.onSettled(undefined, _this2.currentResult.error, _this2.currentResult.variables, _this2.currentResult.context);
|
||||
}
|
||||
} // Then trigger the listeners
|
||||
|
||||
|
||||
if (options.listeners) {
|
||||
_this2.listeners.forEach(function (listener) {
|
||||
listener(_this2.currentResult);
|
||||
});
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
return MutationObserver;
|
||||
}(Subscribable);
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
import { scheduleMicrotask } from './utils'; // TYPES
|
||||
|
||||
// CLASS
|
||||
export var NotifyManager = /*#__PURE__*/function () {
|
||||
function NotifyManager() {
|
||||
this.queue = [];
|
||||
this.transactions = 0;
|
||||
|
||||
this.notifyFn = function (callback) {
|
||||
callback();
|
||||
};
|
||||
|
||||
this.batchNotifyFn = function (callback) {
|
||||
callback();
|
||||
};
|
||||
}
|
||||
|
||||
var _proto = NotifyManager.prototype;
|
||||
|
||||
_proto.batch = function batch(callback) {
|
||||
var result;
|
||||
this.transactions++;
|
||||
|
||||
try {
|
||||
result = callback();
|
||||
} finally {
|
||||
this.transactions--;
|
||||
|
||||
if (!this.transactions) {
|
||||
this.flush();
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
_proto.schedule = function schedule(callback) {
|
||||
var _this = this;
|
||||
|
||||
if (this.transactions) {
|
||||
this.queue.push(callback);
|
||||
} else {
|
||||
scheduleMicrotask(function () {
|
||||
_this.notifyFn(callback);
|
||||
});
|
||||
}
|
||||
}
|
||||
/**
|
||||
* All calls to the wrapped function will be batched.
|
||||
*/
|
||||
;
|
||||
|
||||
_proto.batchCalls = function batchCalls(callback) {
|
||||
var _this2 = this;
|
||||
|
||||
return function () {
|
||||
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
|
||||
args[_key] = arguments[_key];
|
||||
}
|
||||
|
||||
_this2.schedule(function () {
|
||||
callback.apply(void 0, args);
|
||||
});
|
||||
};
|
||||
};
|
||||
|
||||
_proto.flush = function flush() {
|
||||
var _this3 = this;
|
||||
|
||||
var queue = this.queue;
|
||||
this.queue = [];
|
||||
|
||||
if (queue.length) {
|
||||
scheduleMicrotask(function () {
|
||||
_this3.batchNotifyFn(function () {
|
||||
queue.forEach(function (callback) {
|
||||
_this3.notifyFn(callback);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Use this method to set a custom notify function.
|
||||
* This can be used to for example wrap notifications with `React.act` while running tests.
|
||||
*/
|
||||
;
|
||||
|
||||
_proto.setNotifyFunction = function setNotifyFunction(fn) {
|
||||
this.notifyFn = fn;
|
||||
}
|
||||
/**
|
||||
* Use this method to set a custom function to batch notifications together into a single tick.
|
||||
* By default React Query will use the batch function provided by ReactDOM or React Native.
|
||||
*/
|
||||
;
|
||||
|
||||
_proto.setBatchNotifyFunction = function setBatchNotifyFunction(fn) {
|
||||
this.batchNotifyFn = fn;
|
||||
};
|
||||
|
||||
return NotifyManager;
|
||||
}(); // SINGLETON
|
||||
|
||||
export var notifyManager = new NotifyManager();
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
import _inheritsLoose from "@babel/runtime/helpers/esm/inheritsLoose";
|
||||
import { Subscribable } from './subscribable';
|
||||
import { isServer } from './utils';
|
||||
export var OnlineManager = /*#__PURE__*/function (_Subscribable) {
|
||||
_inheritsLoose(OnlineManager, _Subscribable);
|
||||
|
||||
function OnlineManager() {
|
||||
var _this;
|
||||
|
||||
_this = _Subscribable.call(this) || this;
|
||||
|
||||
_this.setup = function (onOnline) {
|
||||
var _window;
|
||||
|
||||
if (!isServer && ((_window = window) == null ? void 0 : _window.addEventListener)) {
|
||||
var listener = function listener() {
|
||||
return onOnline();
|
||||
}; // Listen to online
|
||||
|
||||
|
||||
window.addEventListener('online', listener, false);
|
||||
window.addEventListener('offline', listener, false);
|
||||
return function () {
|
||||
// Be sure to unsubscribe if a new handler is set
|
||||
window.removeEventListener('online', listener);
|
||||
window.removeEventListener('offline', listener);
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
return _this;
|
||||
}
|
||||
|
||||
var _proto = OnlineManager.prototype;
|
||||
|
||||
_proto.onSubscribe = function onSubscribe() {
|
||||
if (!this.cleanup) {
|
||||
this.setEventListener(this.setup);
|
||||
}
|
||||
};
|
||||
|
||||
_proto.onUnsubscribe = function onUnsubscribe() {
|
||||
if (!this.hasListeners()) {
|
||||
var _this$cleanup;
|
||||
|
||||
(_this$cleanup = this.cleanup) == null ? void 0 : _this$cleanup.call(this);
|
||||
this.cleanup = undefined;
|
||||
}
|
||||
};
|
||||
|
||||
_proto.setEventListener = function setEventListener(setup) {
|
||||
var _this$cleanup2,
|
||||
_this2 = this;
|
||||
|
||||
this.setup = setup;
|
||||
(_this$cleanup2 = this.cleanup) == null ? void 0 : _this$cleanup2.call(this);
|
||||
this.cleanup = setup(function (online) {
|
||||
if (typeof online === 'boolean') {
|
||||
_this2.setOnline(online);
|
||||
} else {
|
||||
_this2.onOnline();
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
_proto.setOnline = function setOnline(online) {
|
||||
this.online = online;
|
||||
|
||||
if (online) {
|
||||
this.onOnline();
|
||||
}
|
||||
};
|
||||
|
||||
_proto.onOnline = function onOnline() {
|
||||
this.listeners.forEach(function (listener) {
|
||||
listener();
|
||||
});
|
||||
};
|
||||
|
||||
_proto.isOnline = function isOnline() {
|
||||
if (typeof this.online === 'boolean') {
|
||||
return this.online;
|
||||
}
|
||||
|
||||
if (typeof navigator === 'undefined' || typeof navigator.onLine === 'undefined') {
|
||||
return true;
|
||||
}
|
||||
|
||||
return navigator.onLine;
|
||||
};
|
||||
|
||||
return OnlineManager;
|
||||
}(Subscribable);
|
||||
export var onlineManager = new OnlineManager();
|
||||
+202
@@ -0,0 +1,202 @@
|
||||
import _inheritsLoose from "@babel/runtime/helpers/esm/inheritsLoose";
|
||||
import { difference, replaceAt } from './utils';
|
||||
import { notifyManager } from './notifyManager';
|
||||
import { QueryObserver } from './queryObserver';
|
||||
import { Subscribable } from './subscribable';
|
||||
export var QueriesObserver = /*#__PURE__*/function (_Subscribable) {
|
||||
_inheritsLoose(QueriesObserver, _Subscribable);
|
||||
|
||||
function QueriesObserver(client, queries) {
|
||||
var _this;
|
||||
|
||||
_this = _Subscribable.call(this) || this;
|
||||
_this.client = client;
|
||||
_this.queries = [];
|
||||
_this.result = [];
|
||||
_this.observers = [];
|
||||
_this.observersMap = {};
|
||||
|
||||
if (queries) {
|
||||
_this.setQueries(queries);
|
||||
}
|
||||
|
||||
return _this;
|
||||
}
|
||||
|
||||
var _proto = QueriesObserver.prototype;
|
||||
|
||||
_proto.onSubscribe = function onSubscribe() {
|
||||
var _this2 = this;
|
||||
|
||||
if (this.listeners.length === 1) {
|
||||
this.observers.forEach(function (observer) {
|
||||
observer.subscribe(function (result) {
|
||||
_this2.onUpdate(observer, result);
|
||||
});
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
_proto.onUnsubscribe = function onUnsubscribe() {
|
||||
if (!this.listeners.length) {
|
||||
this.destroy();
|
||||
}
|
||||
};
|
||||
|
||||
_proto.destroy = function destroy() {
|
||||
this.listeners = [];
|
||||
this.observers.forEach(function (observer) {
|
||||
observer.destroy();
|
||||
});
|
||||
};
|
||||
|
||||
_proto.setQueries = function setQueries(queries, notifyOptions) {
|
||||
this.queries = queries;
|
||||
this.updateObservers(notifyOptions);
|
||||
};
|
||||
|
||||
_proto.getCurrentResult = function getCurrentResult() {
|
||||
return this.result;
|
||||
};
|
||||
|
||||
_proto.getOptimisticResult = function getOptimisticResult(queries) {
|
||||
return this.findMatchingObservers(queries).map(function (match) {
|
||||
return match.observer.getOptimisticResult(match.defaultedQueryOptions);
|
||||
});
|
||||
};
|
||||
|
||||
_proto.findMatchingObservers = function findMatchingObservers(queries) {
|
||||
var _this3 = this;
|
||||
|
||||
var prevObservers = this.observers;
|
||||
var defaultedQueryOptions = queries.map(function (options) {
|
||||
return _this3.client.defaultQueryObserverOptions(options);
|
||||
});
|
||||
var matchingObservers = defaultedQueryOptions.flatMap(function (defaultedOptions) {
|
||||
var match = prevObservers.find(function (observer) {
|
||||
return observer.options.queryHash === defaultedOptions.queryHash;
|
||||
});
|
||||
|
||||
if (match != null) {
|
||||
return [{
|
||||
defaultedQueryOptions: defaultedOptions,
|
||||
observer: match
|
||||
}];
|
||||
}
|
||||
|
||||
return [];
|
||||
});
|
||||
var matchedQueryHashes = matchingObservers.map(function (match) {
|
||||
return match.defaultedQueryOptions.queryHash;
|
||||
});
|
||||
var unmatchedQueries = defaultedQueryOptions.filter(function (defaultedOptions) {
|
||||
return !matchedQueryHashes.includes(defaultedOptions.queryHash);
|
||||
});
|
||||
var unmatchedObservers = prevObservers.filter(function (prevObserver) {
|
||||
return !matchingObservers.some(function (match) {
|
||||
return match.observer === prevObserver;
|
||||
});
|
||||
});
|
||||
var newOrReusedObservers = unmatchedQueries.map(function (options, index) {
|
||||
if (options.keepPreviousData) {
|
||||
// return previous data from one of the observers that no longer match
|
||||
var previouslyUsedObserver = unmatchedObservers[index];
|
||||
|
||||
if (previouslyUsedObserver !== undefined) {
|
||||
return {
|
||||
defaultedQueryOptions: options,
|
||||
observer: previouslyUsedObserver
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
defaultedQueryOptions: options,
|
||||
observer: _this3.getObserver(options)
|
||||
};
|
||||
});
|
||||
|
||||
var sortMatchesByOrderOfQueries = function sortMatchesByOrderOfQueries(a, b) {
|
||||
return defaultedQueryOptions.indexOf(a.defaultedQueryOptions) - defaultedQueryOptions.indexOf(b.defaultedQueryOptions);
|
||||
};
|
||||
|
||||
return matchingObservers.concat(newOrReusedObservers).sort(sortMatchesByOrderOfQueries);
|
||||
};
|
||||
|
||||
_proto.getObserver = function getObserver(options) {
|
||||
var defaultedOptions = this.client.defaultQueryObserverOptions(options);
|
||||
var currentObserver = this.observersMap[defaultedOptions.queryHash];
|
||||
return currentObserver != null ? currentObserver : new QueryObserver(this.client, defaultedOptions);
|
||||
};
|
||||
|
||||
_proto.updateObservers = function updateObservers(notifyOptions) {
|
||||
var _this4 = this;
|
||||
|
||||
notifyManager.batch(function () {
|
||||
var prevObservers = _this4.observers;
|
||||
|
||||
var newObserverMatches = _this4.findMatchingObservers(_this4.queries); // set options for the new observers to notify of changes
|
||||
|
||||
|
||||
newObserverMatches.forEach(function (match) {
|
||||
return match.observer.setOptions(match.defaultedQueryOptions, notifyOptions);
|
||||
});
|
||||
var newObservers = newObserverMatches.map(function (match) {
|
||||
return match.observer;
|
||||
});
|
||||
var newObserversMap = Object.fromEntries(newObservers.map(function (observer) {
|
||||
return [observer.options.queryHash, observer];
|
||||
}));
|
||||
var newResult = newObservers.map(function (observer) {
|
||||
return observer.getCurrentResult();
|
||||
});
|
||||
var hasIndexChange = newObservers.some(function (observer, index) {
|
||||
return observer !== prevObservers[index];
|
||||
});
|
||||
|
||||
if (prevObservers.length === newObservers.length && !hasIndexChange) {
|
||||
return;
|
||||
}
|
||||
|
||||
_this4.observers = newObservers;
|
||||
_this4.observersMap = newObserversMap;
|
||||
_this4.result = newResult;
|
||||
|
||||
if (!_this4.hasListeners()) {
|
||||
return;
|
||||
}
|
||||
|
||||
difference(prevObservers, newObservers).forEach(function (observer) {
|
||||
observer.destroy();
|
||||
});
|
||||
difference(newObservers, prevObservers).forEach(function (observer) {
|
||||
observer.subscribe(function (result) {
|
||||
_this4.onUpdate(observer, result);
|
||||
});
|
||||
});
|
||||
|
||||
_this4.notify();
|
||||
});
|
||||
};
|
||||
|
||||
_proto.onUpdate = function onUpdate(observer, result) {
|
||||
var index = this.observers.indexOf(observer);
|
||||
|
||||
if (index !== -1) {
|
||||
this.result = replaceAt(this.result, index, result);
|
||||
this.notify();
|
||||
}
|
||||
};
|
||||
|
||||
_proto.notify = function notify() {
|
||||
var _this5 = this;
|
||||
|
||||
notifyManager.batch(function () {
|
||||
_this5.listeners.forEach(function (listener) {
|
||||
listener(_this5.result);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
return QueriesObserver;
|
||||
}(Subscribable);
|
||||
+500
@@ -0,0 +1,500 @@
|
||||
import _extends from "@babel/runtime/helpers/esm/extends";
|
||||
import { getAbortController, functionalUpdate, isValidTimeout, noop, replaceEqualDeep, timeUntilStale, ensureQueryKeyArray } from './utils';
|
||||
import { notifyManager } from './notifyManager';
|
||||
import { getLogger } from './logger';
|
||||
import { Retryer, isCancelledError } from './retryer'; // TYPES
|
||||
|
||||
// CLASS
|
||||
export var Query = /*#__PURE__*/function () {
|
||||
function Query(config) {
|
||||
this.abortSignalConsumed = false;
|
||||
this.hadObservers = false;
|
||||
this.defaultOptions = config.defaultOptions;
|
||||
this.setOptions(config.options);
|
||||
this.observers = [];
|
||||
this.cache = config.cache;
|
||||
this.queryKey = config.queryKey;
|
||||
this.queryHash = config.queryHash;
|
||||
this.initialState = config.state || this.getDefaultState(this.options);
|
||||
this.state = this.initialState;
|
||||
this.meta = config.meta;
|
||||
this.scheduleGc();
|
||||
}
|
||||
|
||||
var _proto = Query.prototype;
|
||||
|
||||
_proto.setOptions = function setOptions(options) {
|
||||
var _this$options$cacheTi;
|
||||
|
||||
this.options = _extends({}, this.defaultOptions, options);
|
||||
this.meta = options == null ? void 0 : options.meta; // Default to 5 minutes if not cache time is set
|
||||
|
||||
this.cacheTime = Math.max(this.cacheTime || 0, (_this$options$cacheTi = this.options.cacheTime) != null ? _this$options$cacheTi : 5 * 60 * 1000);
|
||||
};
|
||||
|
||||
_proto.setDefaultOptions = function setDefaultOptions(options) {
|
||||
this.defaultOptions = options;
|
||||
};
|
||||
|
||||
_proto.scheduleGc = function scheduleGc() {
|
||||
var _this = this;
|
||||
|
||||
this.clearGcTimeout();
|
||||
|
||||
if (isValidTimeout(this.cacheTime)) {
|
||||
this.gcTimeout = setTimeout(function () {
|
||||
_this.optionalRemove();
|
||||
}, this.cacheTime);
|
||||
}
|
||||
};
|
||||
|
||||
_proto.clearGcTimeout = function clearGcTimeout() {
|
||||
if (this.gcTimeout) {
|
||||
clearTimeout(this.gcTimeout);
|
||||
this.gcTimeout = undefined;
|
||||
}
|
||||
};
|
||||
|
||||
_proto.optionalRemove = function optionalRemove() {
|
||||
if (!this.observers.length) {
|
||||
if (this.state.isFetching) {
|
||||
if (this.hadObservers) {
|
||||
this.scheduleGc();
|
||||
}
|
||||
} else {
|
||||
this.cache.remove(this);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
_proto.setData = function setData(updater, options) {
|
||||
var _this$options$isDataE, _this$options;
|
||||
|
||||
var prevData = this.state.data; // Get the new data
|
||||
|
||||
var data = functionalUpdate(updater, prevData); // Use prev data if an isDataEqual function is defined and returns `true`
|
||||
|
||||
if ((_this$options$isDataE = (_this$options = this.options).isDataEqual) == null ? void 0 : _this$options$isDataE.call(_this$options, prevData, data)) {
|
||||
data = prevData;
|
||||
} else if (this.options.structuralSharing !== false) {
|
||||
// Structurally share data between prev and new data if needed
|
||||
data = replaceEqualDeep(prevData, data);
|
||||
} // Set data and mark it as cached
|
||||
|
||||
|
||||
this.dispatch({
|
||||
data: data,
|
||||
type: 'success',
|
||||
dataUpdatedAt: options == null ? void 0 : options.updatedAt
|
||||
});
|
||||
return data;
|
||||
};
|
||||
|
||||
_proto.setState = function setState(state, setStateOptions) {
|
||||
this.dispatch({
|
||||
type: 'setState',
|
||||
state: state,
|
||||
setStateOptions: setStateOptions
|
||||
});
|
||||
};
|
||||
|
||||
_proto.cancel = function cancel(options) {
|
||||
var _this$retryer;
|
||||
|
||||
var promise = this.promise;
|
||||
(_this$retryer = this.retryer) == null ? void 0 : _this$retryer.cancel(options);
|
||||
return promise ? promise.then(noop).catch(noop) : Promise.resolve();
|
||||
};
|
||||
|
||||
_proto.destroy = function destroy() {
|
||||
this.clearGcTimeout();
|
||||
this.cancel({
|
||||
silent: true
|
||||
});
|
||||
};
|
||||
|
||||
_proto.reset = function reset() {
|
||||
this.destroy();
|
||||
this.setState(this.initialState);
|
||||
};
|
||||
|
||||
_proto.isActive = function isActive() {
|
||||
return this.observers.some(function (observer) {
|
||||
return observer.options.enabled !== false;
|
||||
});
|
||||
};
|
||||
|
||||
_proto.isFetching = function isFetching() {
|
||||
return this.state.isFetching;
|
||||
};
|
||||
|
||||
_proto.isStale = function isStale() {
|
||||
return this.state.isInvalidated || !this.state.dataUpdatedAt || this.observers.some(function (observer) {
|
||||
return observer.getCurrentResult().isStale;
|
||||
});
|
||||
};
|
||||
|
||||
_proto.isStaleByTime = function isStaleByTime(staleTime) {
|
||||
if (staleTime === void 0) {
|
||||
staleTime = 0;
|
||||
}
|
||||
|
||||
return this.state.isInvalidated || !this.state.dataUpdatedAt || !timeUntilStale(this.state.dataUpdatedAt, staleTime);
|
||||
};
|
||||
|
||||
_proto.onFocus = function onFocus() {
|
||||
var _this$retryer2;
|
||||
|
||||
var observer = this.observers.find(function (x) {
|
||||
return x.shouldFetchOnWindowFocus();
|
||||
});
|
||||
|
||||
if (observer) {
|
||||
observer.refetch();
|
||||
} // Continue fetch if currently paused
|
||||
|
||||
|
||||
(_this$retryer2 = this.retryer) == null ? void 0 : _this$retryer2.continue();
|
||||
};
|
||||
|
||||
_proto.onOnline = function onOnline() {
|
||||
var _this$retryer3;
|
||||
|
||||
var observer = this.observers.find(function (x) {
|
||||
return x.shouldFetchOnReconnect();
|
||||
});
|
||||
|
||||
if (observer) {
|
||||
observer.refetch();
|
||||
} // Continue fetch if currently paused
|
||||
|
||||
|
||||
(_this$retryer3 = this.retryer) == null ? void 0 : _this$retryer3.continue();
|
||||
};
|
||||
|
||||
_proto.addObserver = function addObserver(observer) {
|
||||
if (this.observers.indexOf(observer) === -1) {
|
||||
this.observers.push(observer);
|
||||
this.hadObservers = true; // Stop the query from being garbage collected
|
||||
|
||||
this.clearGcTimeout();
|
||||
this.cache.notify({
|
||||
type: 'observerAdded',
|
||||
query: this,
|
||||
observer: observer
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
_proto.removeObserver = function removeObserver(observer) {
|
||||
if (this.observers.indexOf(observer) !== -1) {
|
||||
this.observers = this.observers.filter(function (x) {
|
||||
return x !== observer;
|
||||
});
|
||||
|
||||
if (!this.observers.length) {
|
||||
// If the transport layer does not support cancellation
|
||||
// we'll let the query continue so the result can be cached
|
||||
if (this.retryer) {
|
||||
if (this.retryer.isTransportCancelable || this.abortSignalConsumed) {
|
||||
this.retryer.cancel({
|
||||
revert: true
|
||||
});
|
||||
} else {
|
||||
this.retryer.cancelRetry();
|
||||
}
|
||||
}
|
||||
|
||||
if (this.cacheTime) {
|
||||
this.scheduleGc();
|
||||
} else {
|
||||
this.cache.remove(this);
|
||||
}
|
||||
}
|
||||
|
||||
this.cache.notify({
|
||||
type: 'observerRemoved',
|
||||
query: this,
|
||||
observer: observer
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
_proto.getObserversCount = function getObserversCount() {
|
||||
return this.observers.length;
|
||||
};
|
||||
|
||||
_proto.invalidate = function invalidate() {
|
||||
if (!this.state.isInvalidated) {
|
||||
this.dispatch({
|
||||
type: 'invalidate'
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
_proto.fetch = function fetch(options, fetchOptions) {
|
||||
var _this2 = this,
|
||||
_this$options$behavio,
|
||||
_context$fetchOptions,
|
||||
_abortController$abor;
|
||||
|
||||
if (this.state.isFetching) {
|
||||
if (this.state.dataUpdatedAt && (fetchOptions == null ? void 0 : fetchOptions.cancelRefetch)) {
|
||||
// Silently cancel current fetch if the user wants to cancel refetches
|
||||
this.cancel({
|
||||
silent: true
|
||||
});
|
||||
} else if (this.promise) {
|
||||
var _this$retryer4;
|
||||
|
||||
// make sure that retries that were potentially cancelled due to unmounts can continue
|
||||
(_this$retryer4 = this.retryer) == null ? void 0 : _this$retryer4.continueRetry(); // Return current promise if we are already fetching
|
||||
|
||||
return this.promise;
|
||||
}
|
||||
} // Update config if passed, otherwise the config from the last execution is used
|
||||
|
||||
|
||||
if (options) {
|
||||
this.setOptions(options);
|
||||
} // Use the options from the first observer with a query function if no function is found.
|
||||
// This can happen when the query is hydrated or created with setQueryData.
|
||||
|
||||
|
||||
if (!this.options.queryFn) {
|
||||
var observer = this.observers.find(function (x) {
|
||||
return x.options.queryFn;
|
||||
});
|
||||
|
||||
if (observer) {
|
||||
this.setOptions(observer.options);
|
||||
}
|
||||
}
|
||||
|
||||
var queryKey = ensureQueryKeyArray(this.queryKey);
|
||||
var abortController = getAbortController(); // Create query function context
|
||||
|
||||
var queryFnContext = {
|
||||
queryKey: queryKey,
|
||||
pageParam: undefined,
|
||||
meta: this.meta
|
||||
};
|
||||
Object.defineProperty(queryFnContext, 'signal', {
|
||||
enumerable: true,
|
||||
get: function get() {
|
||||
if (abortController) {
|
||||
_this2.abortSignalConsumed = true;
|
||||
return abortController.signal;
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
}); // Create fetch function
|
||||
|
||||
var fetchFn = function fetchFn() {
|
||||
if (!_this2.options.queryFn) {
|
||||
return Promise.reject('Missing queryFn');
|
||||
}
|
||||
|
||||
_this2.abortSignalConsumed = false;
|
||||
return _this2.options.queryFn(queryFnContext);
|
||||
}; // Trigger behavior hook
|
||||
|
||||
|
||||
var context = {
|
||||
fetchOptions: fetchOptions,
|
||||
options: this.options,
|
||||
queryKey: queryKey,
|
||||
state: this.state,
|
||||
fetchFn: fetchFn,
|
||||
meta: this.meta
|
||||
};
|
||||
|
||||
if ((_this$options$behavio = this.options.behavior) == null ? void 0 : _this$options$behavio.onFetch) {
|
||||
var _this$options$behavio2;
|
||||
|
||||
(_this$options$behavio2 = this.options.behavior) == null ? void 0 : _this$options$behavio2.onFetch(context);
|
||||
} // Store state in case the current fetch needs to be reverted
|
||||
|
||||
|
||||
this.revertState = this.state; // Set to fetching state if not already in it
|
||||
|
||||
if (!this.state.isFetching || this.state.fetchMeta !== ((_context$fetchOptions = context.fetchOptions) == null ? void 0 : _context$fetchOptions.meta)) {
|
||||
var _context$fetchOptions2;
|
||||
|
||||
this.dispatch({
|
||||
type: 'fetch',
|
||||
meta: (_context$fetchOptions2 = context.fetchOptions) == null ? void 0 : _context$fetchOptions2.meta
|
||||
});
|
||||
} // Try to fetch the data
|
||||
|
||||
|
||||
this.retryer = new Retryer({
|
||||
fn: context.fetchFn,
|
||||
abort: abortController == null ? void 0 : (_abortController$abor = abortController.abort) == null ? void 0 : _abortController$abor.bind(abortController),
|
||||
onSuccess: function onSuccess(data) {
|
||||
_this2.setData(data); // Notify cache callback
|
||||
|
||||
|
||||
_this2.cache.config.onSuccess == null ? void 0 : _this2.cache.config.onSuccess(data, _this2); // Remove query after fetching if cache time is 0
|
||||
|
||||
if (_this2.cacheTime === 0) {
|
||||
_this2.optionalRemove();
|
||||
}
|
||||
},
|
||||
onError: function onError(error) {
|
||||
// Optimistically update state if needed
|
||||
if (!(isCancelledError(error) && error.silent)) {
|
||||
_this2.dispatch({
|
||||
type: 'error',
|
||||
error: error
|
||||
});
|
||||
}
|
||||
|
||||
if (!isCancelledError(error)) {
|
||||
// Notify cache callback
|
||||
_this2.cache.config.onError == null ? void 0 : _this2.cache.config.onError(error, _this2); // Log error
|
||||
|
||||
getLogger().error(error);
|
||||
} // Remove query after fetching if cache time is 0
|
||||
|
||||
|
||||
if (_this2.cacheTime === 0) {
|
||||
_this2.optionalRemove();
|
||||
}
|
||||
},
|
||||
onFail: function onFail() {
|
||||
_this2.dispatch({
|
||||
type: 'failed'
|
||||
});
|
||||
},
|
||||
onPause: function onPause() {
|
||||
_this2.dispatch({
|
||||
type: 'pause'
|
||||
});
|
||||
},
|
||||
onContinue: function onContinue() {
|
||||
_this2.dispatch({
|
||||
type: 'continue'
|
||||
});
|
||||
},
|
||||
retry: context.options.retry,
|
||||
retryDelay: context.options.retryDelay
|
||||
});
|
||||
this.promise = this.retryer.promise;
|
||||
return this.promise;
|
||||
};
|
||||
|
||||
_proto.dispatch = function dispatch(action) {
|
||||
var _this3 = this;
|
||||
|
||||
this.state = this.reducer(this.state, action);
|
||||
notifyManager.batch(function () {
|
||||
_this3.observers.forEach(function (observer) {
|
||||
observer.onQueryUpdate(action);
|
||||
});
|
||||
|
||||
_this3.cache.notify({
|
||||
query: _this3,
|
||||
type: 'queryUpdated',
|
||||
action: action
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
_proto.getDefaultState = function getDefaultState(options) {
|
||||
var data = typeof options.initialData === 'function' ? options.initialData() : options.initialData;
|
||||
var hasInitialData = typeof options.initialData !== 'undefined';
|
||||
var initialDataUpdatedAt = hasInitialData ? typeof options.initialDataUpdatedAt === 'function' ? options.initialDataUpdatedAt() : options.initialDataUpdatedAt : 0;
|
||||
var hasData = typeof data !== 'undefined';
|
||||
return {
|
||||
data: data,
|
||||
dataUpdateCount: 0,
|
||||
dataUpdatedAt: hasData ? initialDataUpdatedAt != null ? initialDataUpdatedAt : Date.now() : 0,
|
||||
error: null,
|
||||
errorUpdateCount: 0,
|
||||
errorUpdatedAt: 0,
|
||||
fetchFailureCount: 0,
|
||||
fetchMeta: null,
|
||||
isFetching: false,
|
||||
isInvalidated: false,
|
||||
isPaused: false,
|
||||
status: hasData ? 'success' : 'idle'
|
||||
};
|
||||
};
|
||||
|
||||
_proto.reducer = function reducer(state, action) {
|
||||
var _action$meta, _action$dataUpdatedAt;
|
||||
|
||||
switch (action.type) {
|
||||
case 'failed':
|
||||
return _extends({}, state, {
|
||||
fetchFailureCount: state.fetchFailureCount + 1
|
||||
});
|
||||
|
||||
case 'pause':
|
||||
return _extends({}, state, {
|
||||
isPaused: true
|
||||
});
|
||||
|
||||
case 'continue':
|
||||
return _extends({}, state, {
|
||||
isPaused: false
|
||||
});
|
||||
|
||||
case 'fetch':
|
||||
return _extends({}, state, {
|
||||
fetchFailureCount: 0,
|
||||
fetchMeta: (_action$meta = action.meta) != null ? _action$meta : null,
|
||||
isFetching: true,
|
||||
isPaused: false
|
||||
}, !state.dataUpdatedAt && {
|
||||
error: null,
|
||||
status: 'loading'
|
||||
});
|
||||
|
||||
case 'success':
|
||||
return _extends({}, state, {
|
||||
data: action.data,
|
||||
dataUpdateCount: state.dataUpdateCount + 1,
|
||||
dataUpdatedAt: (_action$dataUpdatedAt = action.dataUpdatedAt) != null ? _action$dataUpdatedAt : Date.now(),
|
||||
error: null,
|
||||
fetchFailureCount: 0,
|
||||
isFetching: false,
|
||||
isInvalidated: false,
|
||||
isPaused: false,
|
||||
status: 'success'
|
||||
});
|
||||
|
||||
case 'error':
|
||||
var error = action.error;
|
||||
|
||||
if (isCancelledError(error) && error.revert && this.revertState) {
|
||||
return _extends({}, this.revertState);
|
||||
}
|
||||
|
||||
return _extends({}, state, {
|
||||
error: error,
|
||||
errorUpdateCount: state.errorUpdateCount + 1,
|
||||
errorUpdatedAt: Date.now(),
|
||||
fetchFailureCount: state.fetchFailureCount + 1,
|
||||
isFetching: false,
|
||||
isPaused: false,
|
||||
status: 'error'
|
||||
});
|
||||
|
||||
case 'invalidate':
|
||||
return _extends({}, state, {
|
||||
isInvalidated: true
|
||||
});
|
||||
|
||||
case 'setState':
|
||||
return _extends({}, state, action.state);
|
||||
|
||||
default:
|
||||
return state;
|
||||
}
|
||||
};
|
||||
|
||||
return Query;
|
||||
}();
|
||||
+147
@@ -0,0 +1,147 @@
|
||||
import _inheritsLoose from "@babel/runtime/helpers/esm/inheritsLoose";
|
||||
import { hashQueryKeyByOptions, matchQuery, parseFilterArgs } from './utils';
|
||||
import { Query } from './query';
|
||||
import { notifyManager } from './notifyManager';
|
||||
import { Subscribable } from './subscribable';
|
||||
// CLASS
|
||||
export var QueryCache = /*#__PURE__*/function (_Subscribable) {
|
||||
_inheritsLoose(QueryCache, _Subscribable);
|
||||
|
||||
function QueryCache(config) {
|
||||
var _this;
|
||||
|
||||
_this = _Subscribable.call(this) || this;
|
||||
_this.config = config || {};
|
||||
_this.queries = [];
|
||||
_this.queriesMap = {};
|
||||
return _this;
|
||||
}
|
||||
|
||||
var _proto = QueryCache.prototype;
|
||||
|
||||
_proto.build = function build(client, options, state) {
|
||||
var _options$queryHash;
|
||||
|
||||
var queryKey = options.queryKey;
|
||||
var queryHash = (_options$queryHash = options.queryHash) != null ? _options$queryHash : hashQueryKeyByOptions(queryKey, options);
|
||||
var query = this.get(queryHash);
|
||||
|
||||
if (!query) {
|
||||
query = new Query({
|
||||
cache: this,
|
||||
queryKey: queryKey,
|
||||
queryHash: queryHash,
|
||||
options: client.defaultQueryOptions(options),
|
||||
state: state,
|
||||
defaultOptions: client.getQueryDefaults(queryKey),
|
||||
meta: options.meta
|
||||
});
|
||||
this.add(query);
|
||||
}
|
||||
|
||||
return query;
|
||||
};
|
||||
|
||||
_proto.add = function add(query) {
|
||||
if (!this.queriesMap[query.queryHash]) {
|
||||
this.queriesMap[query.queryHash] = query;
|
||||
this.queries.push(query);
|
||||
this.notify({
|
||||
type: 'queryAdded',
|
||||
query: query
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
_proto.remove = function remove(query) {
|
||||
var queryInMap = this.queriesMap[query.queryHash];
|
||||
|
||||
if (queryInMap) {
|
||||
query.destroy();
|
||||
this.queries = this.queries.filter(function (x) {
|
||||
return x !== query;
|
||||
});
|
||||
|
||||
if (queryInMap === query) {
|
||||
delete this.queriesMap[query.queryHash];
|
||||
}
|
||||
|
||||
this.notify({
|
||||
type: 'queryRemoved',
|
||||
query: query
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
_proto.clear = function clear() {
|
||||
var _this2 = this;
|
||||
|
||||
notifyManager.batch(function () {
|
||||
_this2.queries.forEach(function (query) {
|
||||
_this2.remove(query);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
_proto.get = function get(queryHash) {
|
||||
return this.queriesMap[queryHash];
|
||||
};
|
||||
|
||||
_proto.getAll = function getAll() {
|
||||
return this.queries;
|
||||
};
|
||||
|
||||
_proto.find = function find(arg1, arg2) {
|
||||
var _parseFilterArgs = parseFilterArgs(arg1, arg2),
|
||||
filters = _parseFilterArgs[0];
|
||||
|
||||
if (typeof filters.exact === 'undefined') {
|
||||
filters.exact = true;
|
||||
}
|
||||
|
||||
return this.queries.find(function (query) {
|
||||
return matchQuery(filters, query);
|
||||
});
|
||||
};
|
||||
|
||||
_proto.findAll = function findAll(arg1, arg2) {
|
||||
var _parseFilterArgs2 = parseFilterArgs(arg1, arg2),
|
||||
filters = _parseFilterArgs2[0];
|
||||
|
||||
return Object.keys(filters).length > 0 ? this.queries.filter(function (query) {
|
||||
return matchQuery(filters, query);
|
||||
}) : this.queries;
|
||||
};
|
||||
|
||||
_proto.notify = function notify(event) {
|
||||
var _this3 = this;
|
||||
|
||||
notifyManager.batch(function () {
|
||||
_this3.listeners.forEach(function (listener) {
|
||||
listener(event);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
_proto.onFocus = function onFocus() {
|
||||
var _this4 = this;
|
||||
|
||||
notifyManager.batch(function () {
|
||||
_this4.queries.forEach(function (query) {
|
||||
query.onFocus();
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
_proto.onOnline = function onOnline() {
|
||||
var _this5 = this;
|
||||
|
||||
notifyManager.batch(function () {
|
||||
_this5.queries.forEach(function (query) {
|
||||
query.onOnline();
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
return QueryCache;
|
||||
}(Subscribable);
|
||||
+350
@@ -0,0 +1,350 @@
|
||||
import _extends from "@babel/runtime/helpers/esm/extends";
|
||||
import { hashQueryKey, noop, parseFilterArgs, parseQueryArgs, partialMatchKey, hashQueryKeyByOptions } from './utils';
|
||||
import { QueryCache } from './queryCache';
|
||||
import { MutationCache } from './mutationCache';
|
||||
import { focusManager } from './focusManager';
|
||||
import { onlineManager } from './onlineManager';
|
||||
import { notifyManager } from './notifyManager';
|
||||
import { infiniteQueryBehavior } from './infiniteQueryBehavior';
|
||||
// CLASS
|
||||
export var QueryClient = /*#__PURE__*/function () {
|
||||
function QueryClient(config) {
|
||||
if (config === void 0) {
|
||||
config = {};
|
||||
}
|
||||
|
||||
this.queryCache = config.queryCache || new QueryCache();
|
||||
this.mutationCache = config.mutationCache || new MutationCache();
|
||||
this.defaultOptions = config.defaultOptions || {};
|
||||
this.queryDefaults = [];
|
||||
this.mutationDefaults = [];
|
||||
}
|
||||
|
||||
var _proto = QueryClient.prototype;
|
||||
|
||||
_proto.mount = function mount() {
|
||||
var _this = this;
|
||||
|
||||
this.unsubscribeFocus = focusManager.subscribe(function () {
|
||||
if (focusManager.isFocused() && onlineManager.isOnline()) {
|
||||
_this.mutationCache.onFocus();
|
||||
|
||||
_this.queryCache.onFocus();
|
||||
}
|
||||
});
|
||||
this.unsubscribeOnline = onlineManager.subscribe(function () {
|
||||
if (focusManager.isFocused() && onlineManager.isOnline()) {
|
||||
_this.mutationCache.onOnline();
|
||||
|
||||
_this.queryCache.onOnline();
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
_proto.unmount = function unmount() {
|
||||
var _this$unsubscribeFocu, _this$unsubscribeOnli;
|
||||
|
||||
(_this$unsubscribeFocu = this.unsubscribeFocus) == null ? void 0 : _this$unsubscribeFocu.call(this);
|
||||
(_this$unsubscribeOnli = this.unsubscribeOnline) == null ? void 0 : _this$unsubscribeOnli.call(this);
|
||||
};
|
||||
|
||||
_proto.isFetching = function isFetching(arg1, arg2) {
|
||||
var _parseFilterArgs = parseFilterArgs(arg1, arg2),
|
||||
filters = _parseFilterArgs[0];
|
||||
|
||||
filters.fetching = true;
|
||||
return this.queryCache.findAll(filters).length;
|
||||
};
|
||||
|
||||
_proto.isMutating = function isMutating(filters) {
|
||||
return this.mutationCache.findAll(_extends({}, filters, {
|
||||
fetching: true
|
||||
})).length;
|
||||
};
|
||||
|
||||
_proto.getQueryData = function getQueryData(queryKey, filters) {
|
||||
var _this$queryCache$find;
|
||||
|
||||
return (_this$queryCache$find = this.queryCache.find(queryKey, filters)) == null ? void 0 : _this$queryCache$find.state.data;
|
||||
};
|
||||
|
||||
_proto.getQueriesData = function getQueriesData(queryKeyOrFilters) {
|
||||
return this.getQueryCache().findAll(queryKeyOrFilters).map(function (_ref) {
|
||||
var queryKey = _ref.queryKey,
|
||||
state = _ref.state;
|
||||
var data = state.data;
|
||||
return [queryKey, data];
|
||||
});
|
||||
};
|
||||
|
||||
_proto.setQueryData = function setQueryData(queryKey, updater, options) {
|
||||
var parsedOptions = parseQueryArgs(queryKey);
|
||||
var defaultedOptions = this.defaultQueryOptions(parsedOptions);
|
||||
return this.queryCache.build(this, defaultedOptions).setData(updater, options);
|
||||
};
|
||||
|
||||
_proto.setQueriesData = function setQueriesData(queryKeyOrFilters, updater, options) {
|
||||
var _this2 = this;
|
||||
|
||||
return notifyManager.batch(function () {
|
||||
return _this2.getQueryCache().findAll(queryKeyOrFilters).map(function (_ref2) {
|
||||
var queryKey = _ref2.queryKey;
|
||||
return [queryKey, _this2.setQueryData(queryKey, updater, options)];
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
_proto.getQueryState = function getQueryState(queryKey, filters) {
|
||||
var _this$queryCache$find2;
|
||||
|
||||
return (_this$queryCache$find2 = this.queryCache.find(queryKey, filters)) == null ? void 0 : _this$queryCache$find2.state;
|
||||
};
|
||||
|
||||
_proto.removeQueries = function removeQueries(arg1, arg2) {
|
||||
var _parseFilterArgs2 = parseFilterArgs(arg1, arg2),
|
||||
filters = _parseFilterArgs2[0];
|
||||
|
||||
var queryCache = this.queryCache;
|
||||
notifyManager.batch(function () {
|
||||
queryCache.findAll(filters).forEach(function (query) {
|
||||
queryCache.remove(query);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
_proto.resetQueries = function resetQueries(arg1, arg2, arg3) {
|
||||
var _this3 = this;
|
||||
|
||||
var _parseFilterArgs3 = parseFilterArgs(arg1, arg2, arg3),
|
||||
filters = _parseFilterArgs3[0],
|
||||
options = _parseFilterArgs3[1];
|
||||
|
||||
var queryCache = this.queryCache;
|
||||
|
||||
var refetchFilters = _extends({}, filters, {
|
||||
active: true
|
||||
});
|
||||
|
||||
return notifyManager.batch(function () {
|
||||
queryCache.findAll(filters).forEach(function (query) {
|
||||
query.reset();
|
||||
});
|
||||
return _this3.refetchQueries(refetchFilters, options);
|
||||
});
|
||||
};
|
||||
|
||||
_proto.cancelQueries = function cancelQueries(arg1, arg2, arg3) {
|
||||
var _this4 = this;
|
||||
|
||||
var _parseFilterArgs4 = parseFilterArgs(arg1, arg2, arg3),
|
||||
filters = _parseFilterArgs4[0],
|
||||
_parseFilterArgs4$ = _parseFilterArgs4[1],
|
||||
cancelOptions = _parseFilterArgs4$ === void 0 ? {} : _parseFilterArgs4$;
|
||||
|
||||
if (typeof cancelOptions.revert === 'undefined') {
|
||||
cancelOptions.revert = true;
|
||||
}
|
||||
|
||||
var promises = notifyManager.batch(function () {
|
||||
return _this4.queryCache.findAll(filters).map(function (query) {
|
||||
return query.cancel(cancelOptions);
|
||||
});
|
||||
});
|
||||
return Promise.all(promises).then(noop).catch(noop);
|
||||
};
|
||||
|
||||
_proto.invalidateQueries = function invalidateQueries(arg1, arg2, arg3) {
|
||||
var _ref3,
|
||||
_filters$refetchActiv,
|
||||
_filters$refetchInact,
|
||||
_this5 = this;
|
||||
|
||||
var _parseFilterArgs5 = parseFilterArgs(arg1, arg2, arg3),
|
||||
filters = _parseFilterArgs5[0],
|
||||
options = _parseFilterArgs5[1];
|
||||
|
||||
var refetchFilters = _extends({}, filters, {
|
||||
// if filters.refetchActive is not provided and filters.active is explicitly false,
|
||||
// e.g. invalidateQueries({ active: false }), we don't want to refetch active queries
|
||||
active: (_ref3 = (_filters$refetchActiv = filters.refetchActive) != null ? _filters$refetchActiv : filters.active) != null ? _ref3 : true,
|
||||
inactive: (_filters$refetchInact = filters.refetchInactive) != null ? _filters$refetchInact : false
|
||||
});
|
||||
|
||||
return notifyManager.batch(function () {
|
||||
_this5.queryCache.findAll(filters).forEach(function (query) {
|
||||
query.invalidate();
|
||||
});
|
||||
|
||||
return _this5.refetchQueries(refetchFilters, options);
|
||||
});
|
||||
};
|
||||
|
||||
_proto.refetchQueries = function refetchQueries(arg1, arg2, arg3) {
|
||||
var _this6 = this;
|
||||
|
||||
var _parseFilterArgs6 = parseFilterArgs(arg1, arg2, arg3),
|
||||
filters = _parseFilterArgs6[0],
|
||||
options = _parseFilterArgs6[1];
|
||||
|
||||
var promises = notifyManager.batch(function () {
|
||||
return _this6.queryCache.findAll(filters).map(function (query) {
|
||||
return query.fetch(undefined, _extends({}, options, {
|
||||
meta: {
|
||||
refetchPage: filters == null ? void 0 : filters.refetchPage
|
||||
}
|
||||
}));
|
||||
});
|
||||
});
|
||||
var promise = Promise.all(promises).then(noop);
|
||||
|
||||
if (!(options == null ? void 0 : options.throwOnError)) {
|
||||
promise = promise.catch(noop);
|
||||
}
|
||||
|
||||
return promise;
|
||||
};
|
||||
|
||||
_proto.fetchQuery = function fetchQuery(arg1, arg2, arg3) {
|
||||
var parsedOptions = parseQueryArgs(arg1, arg2, arg3);
|
||||
var defaultedOptions = this.defaultQueryOptions(parsedOptions); // https://github.com/tannerlinsley/react-query/issues/652
|
||||
|
||||
if (typeof defaultedOptions.retry === 'undefined') {
|
||||
defaultedOptions.retry = false;
|
||||
}
|
||||
|
||||
var query = this.queryCache.build(this, defaultedOptions);
|
||||
return query.isStaleByTime(defaultedOptions.staleTime) ? query.fetch(defaultedOptions) : Promise.resolve(query.state.data);
|
||||
};
|
||||
|
||||
_proto.prefetchQuery = function prefetchQuery(arg1, arg2, arg3) {
|
||||
return this.fetchQuery(arg1, arg2, arg3).then(noop).catch(noop);
|
||||
};
|
||||
|
||||
_proto.fetchInfiniteQuery = function fetchInfiniteQuery(arg1, arg2, arg3) {
|
||||
var parsedOptions = parseQueryArgs(arg1, arg2, arg3);
|
||||
parsedOptions.behavior = infiniteQueryBehavior();
|
||||
return this.fetchQuery(parsedOptions);
|
||||
};
|
||||
|
||||
_proto.prefetchInfiniteQuery = function prefetchInfiniteQuery(arg1, arg2, arg3) {
|
||||
return this.fetchInfiniteQuery(arg1, arg2, arg3).then(noop).catch(noop);
|
||||
};
|
||||
|
||||
_proto.cancelMutations = function cancelMutations() {
|
||||
var _this7 = this;
|
||||
|
||||
var promises = notifyManager.batch(function () {
|
||||
return _this7.mutationCache.getAll().map(function (mutation) {
|
||||
return mutation.cancel();
|
||||
});
|
||||
});
|
||||
return Promise.all(promises).then(noop).catch(noop);
|
||||
};
|
||||
|
||||
_proto.resumePausedMutations = function resumePausedMutations() {
|
||||
return this.getMutationCache().resumePausedMutations();
|
||||
};
|
||||
|
||||
_proto.executeMutation = function executeMutation(options) {
|
||||
return this.mutationCache.build(this, options).execute();
|
||||
};
|
||||
|
||||
_proto.getQueryCache = function getQueryCache() {
|
||||
return this.queryCache;
|
||||
};
|
||||
|
||||
_proto.getMutationCache = function getMutationCache() {
|
||||
return this.mutationCache;
|
||||
};
|
||||
|
||||
_proto.getDefaultOptions = function getDefaultOptions() {
|
||||
return this.defaultOptions;
|
||||
};
|
||||
|
||||
_proto.setDefaultOptions = function setDefaultOptions(options) {
|
||||
this.defaultOptions = options;
|
||||
};
|
||||
|
||||
_proto.setQueryDefaults = function setQueryDefaults(queryKey, options) {
|
||||
var result = this.queryDefaults.find(function (x) {
|
||||
return hashQueryKey(queryKey) === hashQueryKey(x.queryKey);
|
||||
});
|
||||
|
||||
if (result) {
|
||||
result.defaultOptions = options;
|
||||
} else {
|
||||
this.queryDefaults.push({
|
||||
queryKey: queryKey,
|
||||
defaultOptions: options
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
_proto.getQueryDefaults = function getQueryDefaults(queryKey) {
|
||||
var _this$queryDefaults$f;
|
||||
|
||||
return queryKey ? (_this$queryDefaults$f = this.queryDefaults.find(function (x) {
|
||||
return partialMatchKey(queryKey, x.queryKey);
|
||||
})) == null ? void 0 : _this$queryDefaults$f.defaultOptions : undefined;
|
||||
};
|
||||
|
||||
_proto.setMutationDefaults = function setMutationDefaults(mutationKey, options) {
|
||||
var result = this.mutationDefaults.find(function (x) {
|
||||
return hashQueryKey(mutationKey) === hashQueryKey(x.mutationKey);
|
||||
});
|
||||
|
||||
if (result) {
|
||||
result.defaultOptions = options;
|
||||
} else {
|
||||
this.mutationDefaults.push({
|
||||
mutationKey: mutationKey,
|
||||
defaultOptions: options
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
_proto.getMutationDefaults = function getMutationDefaults(mutationKey) {
|
||||
var _this$mutationDefault;
|
||||
|
||||
return mutationKey ? (_this$mutationDefault = this.mutationDefaults.find(function (x) {
|
||||
return partialMatchKey(mutationKey, x.mutationKey);
|
||||
})) == null ? void 0 : _this$mutationDefault.defaultOptions : undefined;
|
||||
};
|
||||
|
||||
_proto.defaultQueryOptions = function defaultQueryOptions(options) {
|
||||
if (options == null ? void 0 : options._defaulted) {
|
||||
return options;
|
||||
}
|
||||
|
||||
var defaultedOptions = _extends({}, this.defaultOptions.queries, this.getQueryDefaults(options == null ? void 0 : options.queryKey), options, {
|
||||
_defaulted: true
|
||||
});
|
||||
|
||||
if (!defaultedOptions.queryHash && defaultedOptions.queryKey) {
|
||||
defaultedOptions.queryHash = hashQueryKeyByOptions(defaultedOptions.queryKey, defaultedOptions);
|
||||
}
|
||||
|
||||
return defaultedOptions;
|
||||
};
|
||||
|
||||
_proto.defaultQueryObserverOptions = function defaultQueryObserverOptions(options) {
|
||||
return this.defaultQueryOptions(options);
|
||||
};
|
||||
|
||||
_proto.defaultMutationOptions = function defaultMutationOptions(options) {
|
||||
if (options == null ? void 0 : options._defaulted) {
|
||||
return options;
|
||||
}
|
||||
|
||||
return _extends({}, this.defaultOptions.mutations, this.getMutationDefaults(options == null ? void 0 : options.mutationKey), options, {
|
||||
_defaulted: true
|
||||
});
|
||||
};
|
||||
|
||||
_proto.clear = function clear() {
|
||||
this.queryCache.clear();
|
||||
this.mutationCache.clear();
|
||||
};
|
||||
|
||||
return QueryClient;
|
||||
}();
|
||||
+549
@@ -0,0 +1,549 @@
|
||||
import _extends from "@babel/runtime/helpers/esm/extends";
|
||||
import _inheritsLoose from "@babel/runtime/helpers/esm/inheritsLoose";
|
||||
import { isServer, isValidTimeout, noop, replaceEqualDeep, shallowEqualObjects, timeUntilStale } from './utils';
|
||||
import { notifyManager } from './notifyManager';
|
||||
import { focusManager } from './focusManager';
|
||||
import { Subscribable } from './subscribable';
|
||||
import { getLogger } from './logger';
|
||||
import { isCancelledError } from './retryer';
|
||||
export var QueryObserver = /*#__PURE__*/function (_Subscribable) {
|
||||
_inheritsLoose(QueryObserver, _Subscribable);
|
||||
|
||||
function QueryObserver(client, options) {
|
||||
var _this;
|
||||
|
||||
_this = _Subscribable.call(this) || this;
|
||||
_this.client = client;
|
||||
_this.options = options;
|
||||
_this.trackedProps = [];
|
||||
_this.selectError = null;
|
||||
|
||||
_this.bindMethods();
|
||||
|
||||
_this.setOptions(options);
|
||||
|
||||
return _this;
|
||||
}
|
||||
|
||||
var _proto = QueryObserver.prototype;
|
||||
|
||||
_proto.bindMethods = function bindMethods() {
|
||||
this.remove = this.remove.bind(this);
|
||||
this.refetch = this.refetch.bind(this);
|
||||
};
|
||||
|
||||
_proto.onSubscribe = function onSubscribe() {
|
||||
if (this.listeners.length === 1) {
|
||||
this.currentQuery.addObserver(this);
|
||||
|
||||
if (shouldFetchOnMount(this.currentQuery, this.options)) {
|
||||
this.executeFetch();
|
||||
}
|
||||
|
||||
this.updateTimers();
|
||||
}
|
||||
};
|
||||
|
||||
_proto.onUnsubscribe = function onUnsubscribe() {
|
||||
if (!this.listeners.length) {
|
||||
this.destroy();
|
||||
}
|
||||
};
|
||||
|
||||
_proto.shouldFetchOnReconnect = function shouldFetchOnReconnect() {
|
||||
return shouldFetchOn(this.currentQuery, this.options, this.options.refetchOnReconnect);
|
||||
};
|
||||
|
||||
_proto.shouldFetchOnWindowFocus = function shouldFetchOnWindowFocus() {
|
||||
return shouldFetchOn(this.currentQuery, this.options, this.options.refetchOnWindowFocus);
|
||||
};
|
||||
|
||||
_proto.destroy = function destroy() {
|
||||
this.listeners = [];
|
||||
this.clearTimers();
|
||||
this.currentQuery.removeObserver(this);
|
||||
};
|
||||
|
||||
_proto.setOptions = function setOptions(options, notifyOptions) {
|
||||
var prevOptions = this.options;
|
||||
var prevQuery = this.currentQuery;
|
||||
this.options = this.client.defaultQueryObserverOptions(options);
|
||||
|
||||
if (typeof this.options.enabled !== 'undefined' && typeof this.options.enabled !== 'boolean') {
|
||||
throw new Error('Expected enabled to be a boolean');
|
||||
} // Keep previous query key if the user does not supply one
|
||||
|
||||
|
||||
if (!this.options.queryKey) {
|
||||
this.options.queryKey = prevOptions.queryKey;
|
||||
}
|
||||
|
||||
this.updateQuery();
|
||||
var mounted = this.hasListeners(); // Fetch if there are subscribers
|
||||
|
||||
if (mounted && shouldFetchOptionally(this.currentQuery, prevQuery, this.options, prevOptions)) {
|
||||
this.executeFetch();
|
||||
} // Update result
|
||||
|
||||
|
||||
this.updateResult(notifyOptions); // Update stale interval if needed
|
||||
|
||||
if (mounted && (this.currentQuery !== prevQuery || this.options.enabled !== prevOptions.enabled || this.options.staleTime !== prevOptions.staleTime)) {
|
||||
this.updateStaleTimeout();
|
||||
}
|
||||
|
||||
var nextRefetchInterval = this.computeRefetchInterval(); // Update refetch interval if needed
|
||||
|
||||
if (mounted && (this.currentQuery !== prevQuery || this.options.enabled !== prevOptions.enabled || nextRefetchInterval !== this.currentRefetchInterval)) {
|
||||
this.updateRefetchInterval(nextRefetchInterval);
|
||||
}
|
||||
};
|
||||
|
||||
_proto.getOptimisticResult = function getOptimisticResult(options) {
|
||||
var defaultedOptions = this.client.defaultQueryObserverOptions(options);
|
||||
var query = this.client.getQueryCache().build(this.client, defaultedOptions);
|
||||
return this.createResult(query, defaultedOptions);
|
||||
};
|
||||
|
||||
_proto.getCurrentResult = function getCurrentResult() {
|
||||
return this.currentResult;
|
||||
};
|
||||
|
||||
_proto.trackResult = function trackResult(result, defaultedOptions) {
|
||||
var _this2 = this;
|
||||
|
||||
var trackedResult = {};
|
||||
|
||||
var trackProp = function trackProp(key) {
|
||||
if (!_this2.trackedProps.includes(key)) {
|
||||
_this2.trackedProps.push(key);
|
||||
}
|
||||
};
|
||||
|
||||
Object.keys(result).forEach(function (key) {
|
||||
Object.defineProperty(trackedResult, key, {
|
||||
configurable: false,
|
||||
enumerable: true,
|
||||
get: function get() {
|
||||
trackProp(key);
|
||||
return result[key];
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
if (defaultedOptions.useErrorBoundary || defaultedOptions.suspense) {
|
||||
trackProp('error');
|
||||
}
|
||||
|
||||
return trackedResult;
|
||||
};
|
||||
|
||||
_proto.getNextResult = function getNextResult(options) {
|
||||
var _this3 = this;
|
||||
|
||||
return new Promise(function (resolve, reject) {
|
||||
var unsubscribe = _this3.subscribe(function (result) {
|
||||
if (!result.isFetching) {
|
||||
unsubscribe();
|
||||
|
||||
if (result.isError && (options == null ? void 0 : options.throwOnError)) {
|
||||
reject(result.error);
|
||||
} else {
|
||||
resolve(result);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
_proto.getCurrentQuery = function getCurrentQuery() {
|
||||
return this.currentQuery;
|
||||
};
|
||||
|
||||
_proto.remove = function remove() {
|
||||
this.client.getQueryCache().remove(this.currentQuery);
|
||||
};
|
||||
|
||||
_proto.refetch = function refetch(options) {
|
||||
return this.fetch(_extends({}, options, {
|
||||
meta: {
|
||||
refetchPage: options == null ? void 0 : options.refetchPage
|
||||
}
|
||||
}));
|
||||
};
|
||||
|
||||
_proto.fetchOptimistic = function fetchOptimistic(options) {
|
||||
var _this4 = this;
|
||||
|
||||
var defaultedOptions = this.client.defaultQueryObserverOptions(options);
|
||||
var query = this.client.getQueryCache().build(this.client, defaultedOptions);
|
||||
return query.fetch().then(function () {
|
||||
return _this4.createResult(query, defaultedOptions);
|
||||
});
|
||||
};
|
||||
|
||||
_proto.fetch = function fetch(fetchOptions) {
|
||||
var _this5 = this;
|
||||
|
||||
return this.executeFetch(fetchOptions).then(function () {
|
||||
_this5.updateResult();
|
||||
|
||||
return _this5.currentResult;
|
||||
});
|
||||
};
|
||||
|
||||
_proto.executeFetch = function executeFetch(fetchOptions) {
|
||||
// Make sure we reference the latest query as the current one might have been removed
|
||||
this.updateQuery(); // Fetch
|
||||
|
||||
var promise = this.currentQuery.fetch(this.options, fetchOptions);
|
||||
|
||||
if (!(fetchOptions == null ? void 0 : fetchOptions.throwOnError)) {
|
||||
promise = promise.catch(noop);
|
||||
}
|
||||
|
||||
return promise;
|
||||
};
|
||||
|
||||
_proto.updateStaleTimeout = function updateStaleTimeout() {
|
||||
var _this6 = this;
|
||||
|
||||
this.clearStaleTimeout();
|
||||
|
||||
if (isServer || this.currentResult.isStale || !isValidTimeout(this.options.staleTime)) {
|
||||
return;
|
||||
}
|
||||
|
||||
var time = timeUntilStale(this.currentResult.dataUpdatedAt, this.options.staleTime); // The timeout is sometimes triggered 1 ms before the stale time expiration.
|
||||
// To mitigate this issue we always add 1 ms to the timeout.
|
||||
|
||||
var timeout = time + 1;
|
||||
this.staleTimeoutId = setTimeout(function () {
|
||||
if (!_this6.currentResult.isStale) {
|
||||
_this6.updateResult();
|
||||
}
|
||||
}, timeout);
|
||||
};
|
||||
|
||||
_proto.computeRefetchInterval = function computeRefetchInterval() {
|
||||
var _this$options$refetch;
|
||||
|
||||
return typeof this.options.refetchInterval === 'function' ? this.options.refetchInterval(this.currentResult.data, this.currentQuery) : (_this$options$refetch = this.options.refetchInterval) != null ? _this$options$refetch : false;
|
||||
};
|
||||
|
||||
_proto.updateRefetchInterval = function updateRefetchInterval(nextInterval) {
|
||||
var _this7 = this;
|
||||
|
||||
this.clearRefetchInterval();
|
||||
this.currentRefetchInterval = nextInterval;
|
||||
|
||||
if (isServer || this.options.enabled === false || !isValidTimeout(this.currentRefetchInterval) || this.currentRefetchInterval === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.refetchIntervalId = setInterval(function () {
|
||||
if (_this7.options.refetchIntervalInBackground || focusManager.isFocused()) {
|
||||
_this7.executeFetch();
|
||||
}
|
||||
}, this.currentRefetchInterval);
|
||||
};
|
||||
|
||||
_proto.updateTimers = function updateTimers() {
|
||||
this.updateStaleTimeout();
|
||||
this.updateRefetchInterval(this.computeRefetchInterval());
|
||||
};
|
||||
|
||||
_proto.clearTimers = function clearTimers() {
|
||||
this.clearStaleTimeout();
|
||||
this.clearRefetchInterval();
|
||||
};
|
||||
|
||||
_proto.clearStaleTimeout = function clearStaleTimeout() {
|
||||
if (this.staleTimeoutId) {
|
||||
clearTimeout(this.staleTimeoutId);
|
||||
this.staleTimeoutId = undefined;
|
||||
}
|
||||
};
|
||||
|
||||
_proto.clearRefetchInterval = function clearRefetchInterval() {
|
||||
if (this.refetchIntervalId) {
|
||||
clearInterval(this.refetchIntervalId);
|
||||
this.refetchIntervalId = undefined;
|
||||
}
|
||||
};
|
||||
|
||||
_proto.createResult = function createResult(query, options) {
|
||||
var prevQuery = this.currentQuery;
|
||||
var prevOptions = this.options;
|
||||
var prevResult = this.currentResult;
|
||||
var prevResultState = this.currentResultState;
|
||||
var prevResultOptions = this.currentResultOptions;
|
||||
var queryChange = query !== prevQuery;
|
||||
var queryInitialState = queryChange ? query.state : this.currentQueryInitialState;
|
||||
var prevQueryResult = queryChange ? this.currentResult : this.previousQueryResult;
|
||||
var state = query.state;
|
||||
var dataUpdatedAt = state.dataUpdatedAt,
|
||||
error = state.error,
|
||||
errorUpdatedAt = state.errorUpdatedAt,
|
||||
isFetching = state.isFetching,
|
||||
status = state.status;
|
||||
var isPreviousData = false;
|
||||
var isPlaceholderData = false;
|
||||
var data; // Optimistically set result in fetching state if needed
|
||||
|
||||
if (options.optimisticResults) {
|
||||
var mounted = this.hasListeners();
|
||||
var fetchOnMount = !mounted && shouldFetchOnMount(query, options);
|
||||
var fetchOptionally = mounted && shouldFetchOptionally(query, prevQuery, options, prevOptions);
|
||||
|
||||
if (fetchOnMount || fetchOptionally) {
|
||||
isFetching = true;
|
||||
|
||||
if (!dataUpdatedAt) {
|
||||
status = 'loading';
|
||||
}
|
||||
}
|
||||
} // Keep previous data if needed
|
||||
|
||||
|
||||
if (options.keepPreviousData && !state.dataUpdateCount && (prevQueryResult == null ? void 0 : prevQueryResult.isSuccess) && status !== 'error') {
|
||||
data = prevQueryResult.data;
|
||||
dataUpdatedAt = prevQueryResult.dataUpdatedAt;
|
||||
status = prevQueryResult.status;
|
||||
isPreviousData = true;
|
||||
} // Select data if needed
|
||||
else if (options.select && typeof state.data !== 'undefined') {
|
||||
// Memoize select result
|
||||
if (prevResult && state.data === (prevResultState == null ? void 0 : prevResultState.data) && options.select === this.selectFn) {
|
||||
data = this.selectResult;
|
||||
} else {
|
||||
try {
|
||||
this.selectFn = options.select;
|
||||
data = options.select(state.data);
|
||||
|
||||
if (options.structuralSharing !== false) {
|
||||
data = replaceEqualDeep(prevResult == null ? void 0 : prevResult.data, data);
|
||||
}
|
||||
|
||||
this.selectResult = data;
|
||||
this.selectError = null;
|
||||
} catch (selectError) {
|
||||
getLogger().error(selectError);
|
||||
this.selectError = selectError;
|
||||
}
|
||||
}
|
||||
} // Use query data
|
||||
else {
|
||||
data = state.data;
|
||||
} // Show placeholder data if needed
|
||||
|
||||
|
||||
if (typeof options.placeholderData !== 'undefined' && typeof data === 'undefined' && (status === 'loading' || status === 'idle')) {
|
||||
var placeholderData; // Memoize placeholder data
|
||||
|
||||
if ((prevResult == null ? void 0 : prevResult.isPlaceholderData) && options.placeholderData === (prevResultOptions == null ? void 0 : prevResultOptions.placeholderData)) {
|
||||
placeholderData = prevResult.data;
|
||||
} else {
|
||||
placeholderData = typeof options.placeholderData === 'function' ? options.placeholderData() : options.placeholderData;
|
||||
|
||||
if (options.select && typeof placeholderData !== 'undefined') {
|
||||
try {
|
||||
placeholderData = options.select(placeholderData);
|
||||
|
||||
if (options.structuralSharing !== false) {
|
||||
placeholderData = replaceEqualDeep(prevResult == null ? void 0 : prevResult.data, placeholderData);
|
||||
}
|
||||
|
||||
this.selectError = null;
|
||||
} catch (selectError) {
|
||||
getLogger().error(selectError);
|
||||
this.selectError = selectError;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof placeholderData !== 'undefined') {
|
||||
status = 'success';
|
||||
data = placeholderData;
|
||||
isPlaceholderData = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (this.selectError) {
|
||||
error = this.selectError;
|
||||
data = this.selectResult;
|
||||
errorUpdatedAt = Date.now();
|
||||
status = 'error';
|
||||
}
|
||||
|
||||
var result = {
|
||||
status: status,
|
||||
isLoading: status === 'loading',
|
||||
isSuccess: status === 'success',
|
||||
isError: status === 'error',
|
||||
isIdle: status === 'idle',
|
||||
data: data,
|
||||
dataUpdatedAt: dataUpdatedAt,
|
||||
error: error,
|
||||
errorUpdatedAt: errorUpdatedAt,
|
||||
failureCount: state.fetchFailureCount,
|
||||
errorUpdateCount: state.errorUpdateCount,
|
||||
isFetched: state.dataUpdateCount > 0 || state.errorUpdateCount > 0,
|
||||
isFetchedAfterMount: state.dataUpdateCount > queryInitialState.dataUpdateCount || state.errorUpdateCount > queryInitialState.errorUpdateCount,
|
||||
isFetching: isFetching,
|
||||
isRefetching: isFetching && status !== 'loading',
|
||||
isLoadingError: status === 'error' && state.dataUpdatedAt === 0,
|
||||
isPlaceholderData: isPlaceholderData,
|
||||
isPreviousData: isPreviousData,
|
||||
isRefetchError: status === 'error' && state.dataUpdatedAt !== 0,
|
||||
isStale: isStale(query, options),
|
||||
refetch: this.refetch,
|
||||
remove: this.remove
|
||||
};
|
||||
return result;
|
||||
};
|
||||
|
||||
_proto.shouldNotifyListeners = function shouldNotifyListeners(result, prevResult) {
|
||||
if (!prevResult) {
|
||||
return true;
|
||||
}
|
||||
|
||||
var _this$options = this.options,
|
||||
notifyOnChangeProps = _this$options.notifyOnChangeProps,
|
||||
notifyOnChangePropsExclusions = _this$options.notifyOnChangePropsExclusions;
|
||||
|
||||
if (!notifyOnChangeProps && !notifyOnChangePropsExclusions) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (notifyOnChangeProps === 'tracked' && !this.trackedProps.length) {
|
||||
return true;
|
||||
}
|
||||
|
||||
var includedProps = notifyOnChangeProps === 'tracked' ? this.trackedProps : notifyOnChangeProps;
|
||||
return Object.keys(result).some(function (key) {
|
||||
var typedKey = key;
|
||||
var changed = result[typedKey] !== prevResult[typedKey];
|
||||
var isIncluded = includedProps == null ? void 0 : includedProps.some(function (x) {
|
||||
return x === key;
|
||||
});
|
||||
var isExcluded = notifyOnChangePropsExclusions == null ? void 0 : notifyOnChangePropsExclusions.some(function (x) {
|
||||
return x === key;
|
||||
});
|
||||
return changed && !isExcluded && (!includedProps || isIncluded);
|
||||
});
|
||||
};
|
||||
|
||||
_proto.updateResult = function updateResult(notifyOptions) {
|
||||
var prevResult = this.currentResult;
|
||||
this.currentResult = this.createResult(this.currentQuery, this.options);
|
||||
this.currentResultState = this.currentQuery.state;
|
||||
this.currentResultOptions = this.options; // Only notify if something has changed
|
||||
|
||||
if (shallowEqualObjects(this.currentResult, prevResult)) {
|
||||
return;
|
||||
} // Determine which callbacks to trigger
|
||||
|
||||
|
||||
var defaultNotifyOptions = {
|
||||
cache: true
|
||||
};
|
||||
|
||||
if ((notifyOptions == null ? void 0 : notifyOptions.listeners) !== false && this.shouldNotifyListeners(this.currentResult, prevResult)) {
|
||||
defaultNotifyOptions.listeners = true;
|
||||
}
|
||||
|
||||
this.notify(_extends({}, defaultNotifyOptions, notifyOptions));
|
||||
};
|
||||
|
||||
_proto.updateQuery = function updateQuery() {
|
||||
var query = this.client.getQueryCache().build(this.client, this.options);
|
||||
|
||||
if (query === this.currentQuery) {
|
||||
return;
|
||||
}
|
||||
|
||||
var prevQuery = this.currentQuery;
|
||||
this.currentQuery = query;
|
||||
this.currentQueryInitialState = query.state;
|
||||
this.previousQueryResult = this.currentResult;
|
||||
|
||||
if (this.hasListeners()) {
|
||||
prevQuery == null ? void 0 : prevQuery.removeObserver(this);
|
||||
query.addObserver(this);
|
||||
}
|
||||
};
|
||||
|
||||
_proto.onQueryUpdate = function onQueryUpdate(action) {
|
||||
var notifyOptions = {};
|
||||
|
||||
if (action.type === 'success') {
|
||||
notifyOptions.onSuccess = true;
|
||||
} else if (action.type === 'error' && !isCancelledError(action.error)) {
|
||||
notifyOptions.onError = true;
|
||||
}
|
||||
|
||||
this.updateResult(notifyOptions);
|
||||
|
||||
if (this.hasListeners()) {
|
||||
this.updateTimers();
|
||||
}
|
||||
};
|
||||
|
||||
_proto.notify = function notify(notifyOptions) {
|
||||
var _this8 = this;
|
||||
|
||||
notifyManager.batch(function () {
|
||||
// First trigger the configuration callbacks
|
||||
if (notifyOptions.onSuccess) {
|
||||
_this8.options.onSuccess == null ? void 0 : _this8.options.onSuccess(_this8.currentResult.data);
|
||||
_this8.options.onSettled == null ? void 0 : _this8.options.onSettled(_this8.currentResult.data, null);
|
||||
} else if (notifyOptions.onError) {
|
||||
_this8.options.onError == null ? void 0 : _this8.options.onError(_this8.currentResult.error);
|
||||
_this8.options.onSettled == null ? void 0 : _this8.options.onSettled(undefined, _this8.currentResult.error);
|
||||
} // Then trigger the listeners
|
||||
|
||||
|
||||
if (notifyOptions.listeners) {
|
||||
_this8.listeners.forEach(function (listener) {
|
||||
listener(_this8.currentResult);
|
||||
});
|
||||
} // Then the cache listeners
|
||||
|
||||
|
||||
if (notifyOptions.cache) {
|
||||
_this8.client.getQueryCache().notify({
|
||||
query: _this8.currentQuery,
|
||||
type: 'observerResultsUpdated'
|
||||
});
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
return QueryObserver;
|
||||
}(Subscribable);
|
||||
|
||||
function shouldLoadOnMount(query, options) {
|
||||
return options.enabled !== false && !query.state.dataUpdatedAt && !(query.state.status === 'error' && options.retryOnMount === false);
|
||||
}
|
||||
|
||||
function shouldFetchOnMount(query, options) {
|
||||
return shouldLoadOnMount(query, options) || query.state.dataUpdatedAt > 0 && shouldFetchOn(query, options, options.refetchOnMount);
|
||||
}
|
||||
|
||||
function shouldFetchOn(query, options, field) {
|
||||
if (options.enabled !== false) {
|
||||
var value = typeof field === 'function' ? field(query) : field;
|
||||
return value === 'always' || value !== false && isStale(query, options);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
function shouldFetchOptionally(query, prevQuery, options, prevOptions) {
|
||||
return options.enabled !== false && (query !== prevQuery || prevOptions.enabled === false) && (!options.suspense || query.state.status !== 'error') && isStale(query, options);
|
||||
}
|
||||
|
||||
function isStale(query, options) {
|
||||
return query.isStaleByTime(options.staleTime);
|
||||
}
|
||||
+157
@@ -0,0 +1,157 @@
|
||||
import { focusManager } from './focusManager';
|
||||
import { onlineManager } from './onlineManager';
|
||||
import { sleep } from './utils';
|
||||
|
||||
function defaultRetryDelay(failureCount) {
|
||||
return Math.min(1000 * Math.pow(2, failureCount), 30000);
|
||||
}
|
||||
|
||||
export function isCancelable(value) {
|
||||
return typeof (value == null ? void 0 : value.cancel) === 'function';
|
||||
}
|
||||
export var CancelledError = function CancelledError(options) {
|
||||
this.revert = options == null ? void 0 : options.revert;
|
||||
this.silent = options == null ? void 0 : options.silent;
|
||||
};
|
||||
export function isCancelledError(value) {
|
||||
return value instanceof CancelledError;
|
||||
} // CLASS
|
||||
|
||||
export var Retryer = function Retryer(config) {
|
||||
var _this = this;
|
||||
|
||||
var cancelRetry = false;
|
||||
var cancelFn;
|
||||
var continueFn;
|
||||
var promiseResolve;
|
||||
var promiseReject;
|
||||
this.abort = config.abort;
|
||||
|
||||
this.cancel = function (cancelOptions) {
|
||||
return cancelFn == null ? void 0 : cancelFn(cancelOptions);
|
||||
};
|
||||
|
||||
this.cancelRetry = function () {
|
||||
cancelRetry = true;
|
||||
};
|
||||
|
||||
this.continueRetry = function () {
|
||||
cancelRetry = false;
|
||||
};
|
||||
|
||||
this.continue = function () {
|
||||
return continueFn == null ? void 0 : continueFn();
|
||||
};
|
||||
|
||||
this.failureCount = 0;
|
||||
this.isPaused = false;
|
||||
this.isResolved = false;
|
||||
this.isTransportCancelable = false;
|
||||
this.promise = new Promise(function (outerResolve, outerReject) {
|
||||
promiseResolve = outerResolve;
|
||||
promiseReject = outerReject;
|
||||
});
|
||||
|
||||
var resolve = function resolve(value) {
|
||||
if (!_this.isResolved) {
|
||||
_this.isResolved = true;
|
||||
config.onSuccess == null ? void 0 : config.onSuccess(value);
|
||||
continueFn == null ? void 0 : continueFn();
|
||||
promiseResolve(value);
|
||||
}
|
||||
};
|
||||
|
||||
var reject = function reject(value) {
|
||||
if (!_this.isResolved) {
|
||||
_this.isResolved = true;
|
||||
config.onError == null ? void 0 : config.onError(value);
|
||||
continueFn == null ? void 0 : continueFn();
|
||||
promiseReject(value);
|
||||
}
|
||||
};
|
||||
|
||||
var pause = function pause() {
|
||||
return new Promise(function (continueResolve) {
|
||||
continueFn = continueResolve;
|
||||
_this.isPaused = true;
|
||||
config.onPause == null ? void 0 : config.onPause();
|
||||
}).then(function () {
|
||||
continueFn = undefined;
|
||||
_this.isPaused = false;
|
||||
config.onContinue == null ? void 0 : config.onContinue();
|
||||
});
|
||||
}; // Create loop function
|
||||
|
||||
|
||||
var run = function run() {
|
||||
// Do nothing if already resolved
|
||||
if (_this.isResolved) {
|
||||
return;
|
||||
}
|
||||
|
||||
var promiseOrValue; // Execute query
|
||||
|
||||
try {
|
||||
promiseOrValue = config.fn();
|
||||
} catch (error) {
|
||||
promiseOrValue = Promise.reject(error);
|
||||
} // Create callback to cancel this fetch
|
||||
|
||||
|
||||
cancelFn = function cancelFn(cancelOptions) {
|
||||
if (!_this.isResolved) {
|
||||
reject(new CancelledError(cancelOptions));
|
||||
_this.abort == null ? void 0 : _this.abort(); // Cancel transport if supported
|
||||
|
||||
if (isCancelable(promiseOrValue)) {
|
||||
try {
|
||||
promiseOrValue.cancel();
|
||||
} catch (_unused) {}
|
||||
}
|
||||
}
|
||||
}; // Check if the transport layer support cancellation
|
||||
|
||||
|
||||
_this.isTransportCancelable = isCancelable(promiseOrValue);
|
||||
Promise.resolve(promiseOrValue).then(resolve).catch(function (error) {
|
||||
var _config$retry, _config$retryDelay;
|
||||
|
||||
// Stop if the fetch is already resolved
|
||||
if (_this.isResolved) {
|
||||
return;
|
||||
} // Do we need to retry the request?
|
||||
|
||||
|
||||
var retry = (_config$retry = config.retry) != null ? _config$retry : 3;
|
||||
var retryDelay = (_config$retryDelay = config.retryDelay) != null ? _config$retryDelay : defaultRetryDelay;
|
||||
var delay = typeof retryDelay === 'function' ? retryDelay(_this.failureCount, error) : retryDelay;
|
||||
var shouldRetry = retry === true || typeof retry === 'number' && _this.failureCount < retry || typeof retry === 'function' && retry(_this.failureCount, error);
|
||||
|
||||
if (cancelRetry || !shouldRetry) {
|
||||
// We are done if the query does not need to be retried
|
||||
reject(error);
|
||||
return;
|
||||
}
|
||||
|
||||
_this.failureCount++; // Notify on fail
|
||||
|
||||
config.onFail == null ? void 0 : config.onFail(_this.failureCount, error); // Delay
|
||||
|
||||
sleep(delay) // Pause if the document is not visible or when the device is offline
|
||||
.then(function () {
|
||||
if (!focusManager.isFocused() || !onlineManager.isOnline()) {
|
||||
return pause();
|
||||
}
|
||||
}).then(function () {
|
||||
if (cancelRetry) {
|
||||
reject(error);
|
||||
} else {
|
||||
run();
|
||||
}
|
||||
});
|
||||
});
|
||||
}; // Start loop
|
||||
|
||||
|
||||
run();
|
||||
};
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
export var Subscribable = /*#__PURE__*/function () {
|
||||
function Subscribable() {
|
||||
this.listeners = [];
|
||||
}
|
||||
|
||||
var _proto = Subscribable.prototype;
|
||||
|
||||
_proto.subscribe = function subscribe(listener) {
|
||||
var _this = this;
|
||||
|
||||
var callback = listener || function () {
|
||||
return undefined;
|
||||
};
|
||||
|
||||
this.listeners.push(callback);
|
||||
this.onSubscribe();
|
||||
return function () {
|
||||
_this.listeners = _this.listeners.filter(function (x) {
|
||||
return x !== callback;
|
||||
});
|
||||
|
||||
_this.onUnsubscribe();
|
||||
};
|
||||
};
|
||||
|
||||
_proto.hasListeners = function hasListeners() {
|
||||
return this.listeners.length > 0;
|
||||
};
|
||||
|
||||
_proto.onSubscribe = function onSubscribe() {// Do nothing
|
||||
};
|
||||
|
||||
_proto.onUnsubscribe = function onUnsubscribe() {// Do nothing
|
||||
};
|
||||
|
||||
return Subscribable;
|
||||
}();
|
||||
+332
@@ -0,0 +1,332 @@
|
||||
import _extends from "@babel/runtime/helpers/esm/extends";
|
||||
// TYPES
|
||||
// UTILS
|
||||
export var isServer = typeof window === 'undefined';
|
||||
export function noop() {
|
||||
return undefined;
|
||||
}
|
||||
export function functionalUpdate(updater, input) {
|
||||
return typeof updater === 'function' ? updater(input) : updater;
|
||||
}
|
||||
export function isValidTimeout(value) {
|
||||
return typeof value === 'number' && value >= 0 && value !== Infinity;
|
||||
}
|
||||
export function ensureQueryKeyArray(value) {
|
||||
return Array.isArray(value) ? value : [value];
|
||||
}
|
||||
export function difference(array1, array2) {
|
||||
return array1.filter(function (x) {
|
||||
return array2.indexOf(x) === -1;
|
||||
});
|
||||
}
|
||||
export function replaceAt(array, index, value) {
|
||||
var copy = array.slice(0);
|
||||
copy[index] = value;
|
||||
return copy;
|
||||
}
|
||||
export function timeUntilStale(updatedAt, staleTime) {
|
||||
return Math.max(updatedAt + (staleTime || 0) - Date.now(), 0);
|
||||
}
|
||||
export function parseQueryArgs(arg1, arg2, arg3) {
|
||||
if (!isQueryKey(arg1)) {
|
||||
return arg1;
|
||||
}
|
||||
|
||||
if (typeof arg2 === 'function') {
|
||||
return _extends({}, arg3, {
|
||||
queryKey: arg1,
|
||||
queryFn: arg2
|
||||
});
|
||||
}
|
||||
|
||||
return _extends({}, arg2, {
|
||||
queryKey: arg1
|
||||
});
|
||||
}
|
||||
export function parseMutationArgs(arg1, arg2, arg3) {
|
||||
if (isQueryKey(arg1)) {
|
||||
if (typeof arg2 === 'function') {
|
||||
return _extends({}, arg3, {
|
||||
mutationKey: arg1,
|
||||
mutationFn: arg2
|
||||
});
|
||||
}
|
||||
|
||||
return _extends({}, arg2, {
|
||||
mutationKey: arg1
|
||||
});
|
||||
}
|
||||
|
||||
if (typeof arg1 === 'function') {
|
||||
return _extends({}, arg2, {
|
||||
mutationFn: arg1
|
||||
});
|
||||
}
|
||||
|
||||
return _extends({}, arg1);
|
||||
}
|
||||
export function parseFilterArgs(arg1, arg2, arg3) {
|
||||
return isQueryKey(arg1) ? [_extends({}, arg2, {
|
||||
queryKey: arg1
|
||||
}), arg3] : [arg1 || {}, arg2];
|
||||
}
|
||||
export function parseMutationFilterArgs(arg1, arg2) {
|
||||
return isQueryKey(arg1) ? _extends({}, arg2, {
|
||||
mutationKey: arg1
|
||||
}) : arg1;
|
||||
}
|
||||
export function mapQueryStatusFilter(active, inactive) {
|
||||
if (active === true && inactive === true || active == null && inactive == null) {
|
||||
return 'all';
|
||||
} else if (active === false && inactive === false) {
|
||||
return 'none';
|
||||
} else {
|
||||
// At this point, active|inactive can only be true|false or false|true
|
||||
// so, when only one value is provided, the missing one has to be the negated value
|
||||
var isActive = active != null ? active : !inactive;
|
||||
return isActive ? 'active' : 'inactive';
|
||||
}
|
||||
}
|
||||
export function matchQuery(filters, query) {
|
||||
var active = filters.active,
|
||||
exact = filters.exact,
|
||||
fetching = filters.fetching,
|
||||
inactive = filters.inactive,
|
||||
predicate = filters.predicate,
|
||||
queryKey = filters.queryKey,
|
||||
stale = filters.stale;
|
||||
|
||||
if (isQueryKey(queryKey)) {
|
||||
if (exact) {
|
||||
if (query.queryHash !== hashQueryKeyByOptions(queryKey, query.options)) {
|
||||
return false;
|
||||
}
|
||||
} else if (!partialMatchKey(query.queryKey, queryKey)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
var queryStatusFilter = mapQueryStatusFilter(active, inactive);
|
||||
|
||||
if (queryStatusFilter === 'none') {
|
||||
return false;
|
||||
} else if (queryStatusFilter !== 'all') {
|
||||
var isActive = query.isActive();
|
||||
|
||||
if (queryStatusFilter === 'active' && !isActive) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (queryStatusFilter === 'inactive' && isActive) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof stale === 'boolean' && query.isStale() !== stale) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (typeof fetching === 'boolean' && query.isFetching() !== fetching) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (predicate && !predicate(query)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
export function matchMutation(filters, mutation) {
|
||||
var exact = filters.exact,
|
||||
fetching = filters.fetching,
|
||||
predicate = filters.predicate,
|
||||
mutationKey = filters.mutationKey;
|
||||
|
||||
if (isQueryKey(mutationKey)) {
|
||||
if (!mutation.options.mutationKey) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (exact) {
|
||||
if (hashQueryKey(mutation.options.mutationKey) !== hashQueryKey(mutationKey)) {
|
||||
return false;
|
||||
}
|
||||
} else if (!partialMatchKey(mutation.options.mutationKey, mutationKey)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof fetching === 'boolean' && mutation.state.status === 'loading' !== fetching) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (predicate && !predicate(mutation)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
export function hashQueryKeyByOptions(queryKey, options) {
|
||||
var hashFn = (options == null ? void 0 : options.queryKeyHashFn) || hashQueryKey;
|
||||
return hashFn(queryKey);
|
||||
}
|
||||
/**
|
||||
* Default query keys hash function.
|
||||
*/
|
||||
|
||||
export function hashQueryKey(queryKey) {
|
||||
var asArray = ensureQueryKeyArray(queryKey);
|
||||
return stableValueHash(asArray);
|
||||
}
|
||||
/**
|
||||
* Hashes the value into a stable hash.
|
||||
*/
|
||||
|
||||
export function stableValueHash(value) {
|
||||
return JSON.stringify(value, function (_, val) {
|
||||
return isPlainObject(val) ? Object.keys(val).sort().reduce(function (result, key) {
|
||||
result[key] = val[key];
|
||||
return result;
|
||||
}, {}) : val;
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Checks if key `b` partially matches with key `a`.
|
||||
*/
|
||||
|
||||
export function partialMatchKey(a, b) {
|
||||
return partialDeepEqual(ensureQueryKeyArray(a), ensureQueryKeyArray(b));
|
||||
}
|
||||
/**
|
||||
* Checks if `b` partially matches with `a`.
|
||||
*/
|
||||
|
||||
export function partialDeepEqual(a, b) {
|
||||
if (a === b) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (typeof a !== typeof b) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (a && b && typeof a === 'object' && typeof b === 'object') {
|
||||
return !Object.keys(b).some(function (key) {
|
||||
return !partialDeepEqual(a[key], b[key]);
|
||||
});
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
/**
|
||||
* This function returns `a` if `b` is deeply equal.
|
||||
* If not, it will replace any deeply equal children of `b` with those of `a`.
|
||||
* This can be used for structural sharing between JSON values for example.
|
||||
*/
|
||||
|
||||
export function replaceEqualDeep(a, b) {
|
||||
if (a === b) {
|
||||
return a;
|
||||
}
|
||||
|
||||
var array = Array.isArray(a) && Array.isArray(b);
|
||||
|
||||
if (array || isPlainObject(a) && isPlainObject(b)) {
|
||||
var aSize = array ? a.length : Object.keys(a).length;
|
||||
var bItems = array ? b : Object.keys(b);
|
||||
var bSize = bItems.length;
|
||||
var copy = array ? [] : {};
|
||||
var equalItems = 0;
|
||||
|
||||
for (var i = 0; i < bSize; i++) {
|
||||
var key = array ? i : bItems[i];
|
||||
copy[key] = replaceEqualDeep(a[key], b[key]);
|
||||
|
||||
if (copy[key] === a[key]) {
|
||||
equalItems++;
|
||||
}
|
||||
}
|
||||
|
||||
return aSize === bSize && equalItems === aSize ? a : copy;
|
||||
}
|
||||
|
||||
return b;
|
||||
}
|
||||
/**
|
||||
* Shallow compare objects. Only works with objects that always have the same properties.
|
||||
*/
|
||||
|
||||
export function shallowEqualObjects(a, b) {
|
||||
if (a && !b || b && !a) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (var key in a) {
|
||||
if (a[key] !== b[key]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
} // Copied from: https://github.com/jonschlinkert/is-plain-object
|
||||
|
||||
export function isPlainObject(o) {
|
||||
if (!hasObjectPrototype(o)) {
|
||||
return false;
|
||||
} // If has modified constructor
|
||||
|
||||
|
||||
var ctor = o.constructor;
|
||||
|
||||
if (typeof ctor === 'undefined') {
|
||||
return true;
|
||||
} // If has modified prototype
|
||||
|
||||
|
||||
var prot = ctor.prototype;
|
||||
|
||||
if (!hasObjectPrototype(prot)) {
|
||||
return false;
|
||||
} // If constructor does not have an Object-specific method
|
||||
|
||||
|
||||
if (!prot.hasOwnProperty('isPrototypeOf')) {
|
||||
return false;
|
||||
} // Most likely a plain Object
|
||||
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
function hasObjectPrototype(o) {
|
||||
return Object.prototype.toString.call(o) === '[object Object]';
|
||||
}
|
||||
|
||||
export function isQueryKey(value) {
|
||||
return typeof value === 'string' || Array.isArray(value);
|
||||
}
|
||||
export function isError(value) {
|
||||
return value instanceof Error;
|
||||
}
|
||||
export function sleep(timeout) {
|
||||
return new Promise(function (resolve) {
|
||||
setTimeout(resolve, timeout);
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Schedules a microtask.
|
||||
* This can be useful to schedule state updates after rendering.
|
||||
*/
|
||||
|
||||
export function scheduleMicrotask(callback) {
|
||||
Promise.resolve().then(callback).catch(function (error) {
|
||||
return setTimeout(function () {
|
||||
throw error;
|
||||
});
|
||||
});
|
||||
}
|
||||
export function getAbortController() {
|
||||
if (typeof AbortController === 'function') {
|
||||
return new AbortController();
|
||||
}
|
||||
}
|
||||
Generated
Vendored
+124
@@ -0,0 +1,124 @@
|
||||
function _await(value, then, direct) {
|
||||
if (direct) {
|
||||
return then ? then(value) : value;
|
||||
}
|
||||
|
||||
if (!value || !value.then) {
|
||||
value = Promise.resolve(value);
|
||||
}
|
||||
|
||||
return then ? value.then(then) : value;
|
||||
}
|
||||
|
||||
function _async(f) {
|
||||
return function () {
|
||||
for (var args = [], i = 0; i < arguments.length; i++) {
|
||||
args[i] = arguments[i];
|
||||
}
|
||||
|
||||
try {
|
||||
return Promise.resolve(f.apply(this, args));
|
||||
} catch (e) {
|
||||
return Promise.reject(e);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function _empty() {}
|
||||
|
||||
function _invokeIgnored(body) {
|
||||
var result = body();
|
||||
|
||||
if (result && result.then) {
|
||||
return result.then(_empty);
|
||||
}
|
||||
}
|
||||
|
||||
export var createAsyncStoragePersistor = function createAsyncStoragePersistor(_ref) {
|
||||
var storage = _ref.storage,
|
||||
_ref$key = _ref.key,
|
||||
key = _ref$key === void 0 ? "REACT_QUERY_OFFLINE_CACHE" : _ref$key,
|
||||
_ref$throttleTime = _ref.throttleTime,
|
||||
throttleTime = _ref$throttleTime === void 0 ? 1000 : _ref$throttleTime,
|
||||
_ref$serialize = _ref.serialize,
|
||||
serialize = _ref$serialize === void 0 ? JSON.stringify : _ref$serialize,
|
||||
_ref$deserialize = _ref.deserialize,
|
||||
deserialize = _ref$deserialize === void 0 ? JSON.parse : _ref$deserialize;
|
||||
return {
|
||||
persistClient: asyncThrottle(function (persistedClient) {
|
||||
return storage.setItem(key, serialize(persistedClient));
|
||||
}, {
|
||||
interval: throttleTime
|
||||
}),
|
||||
restoreClient: _async(function () {
|
||||
return _await(storage.getItem(key), function (cacheString) {
|
||||
if (!cacheString) {
|
||||
return;
|
||||
}
|
||||
|
||||
return deserialize(cacheString);
|
||||
});
|
||||
}),
|
||||
removeClient: function removeClient() {
|
||||
return storage.removeItem(key);
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
function asyncThrottle(func, _temp) {
|
||||
var _ref2 = _temp === void 0 ? {} : _temp,
|
||||
_ref2$interval = _ref2.interval,
|
||||
interval = _ref2$interval === void 0 ? 1000 : _ref2$interval,
|
||||
_ref2$limit = _ref2.limit,
|
||||
limit = _ref2$limit === void 0 ? 1 : _ref2$limit;
|
||||
|
||||
if (typeof func !== 'function') throw new Error('argument is not function.');
|
||||
var running = {
|
||||
current: false
|
||||
};
|
||||
var lastTime = 0;
|
||||
var timeout;
|
||||
var queue = [];
|
||||
return function () {
|
||||
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
|
||||
args[_key] = arguments[_key];
|
||||
}
|
||||
|
||||
return _async(function () {
|
||||
if (running.current) {
|
||||
lastTime = Date.now();
|
||||
|
||||
if (queue.length > limit) {
|
||||
queue.shift();
|
||||
}
|
||||
|
||||
queue.push(args);
|
||||
clearTimeout(timeout);
|
||||
}
|
||||
|
||||
return _invokeIgnored(function () {
|
||||
if (Date.now() - lastTime > interval) {
|
||||
running.current = true;
|
||||
return _await(func.apply(void 0, args), function () {
|
||||
lastTime = Date.now();
|
||||
running.current = false;
|
||||
});
|
||||
} else {
|
||||
if (queue.length > 0) {
|
||||
var lastArgs = queue[queue.length - 1];
|
||||
timeout = setTimeout(_async(function () {
|
||||
return _invokeIgnored(function () {
|
||||
if (!running.current) {
|
||||
running.current = true;
|
||||
return _await(func.apply(void 0, lastArgs), function () {
|
||||
running.current = false;
|
||||
});
|
||||
}
|
||||
});
|
||||
}), interval);
|
||||
}
|
||||
}
|
||||
});
|
||||
})();
|
||||
};
|
||||
}
|
||||
Generated
Vendored
+114
@@ -0,0 +1,114 @@
|
||||
import _extends from "@babel/runtime/helpers/esm/extends";
|
||||
import { noop } from '../core/utils';
|
||||
export function createWebStoragePersistor(_ref) {
|
||||
var storage = _ref.storage,
|
||||
_ref$key = _ref.key,
|
||||
key = _ref$key === void 0 ? "REACT_QUERY_OFFLINE_CACHE" : _ref$key,
|
||||
_ref$throttleTime = _ref.throttleTime,
|
||||
throttleTime = _ref$throttleTime === void 0 ? 1000 : _ref$throttleTime,
|
||||
_ref$serialize = _ref.serialize,
|
||||
serialize = _ref$serialize === void 0 ? JSON.stringify : _ref$serialize,
|
||||
_ref$deserialize = _ref.deserialize,
|
||||
deserialize = _ref$deserialize === void 0 ? JSON.parse : _ref$deserialize;
|
||||
|
||||
//try to save data to storage
|
||||
function trySave(persistedClient) {
|
||||
try {
|
||||
storage.setItem(key, serialize(persistedClient));
|
||||
} catch (_unused) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
if (typeof storage !== 'undefined') {
|
||||
return {
|
||||
persistClient: throttle(function (persistedClient) {
|
||||
if (trySave(persistedClient) !== true) {
|
||||
var mutations = [].concat(persistedClient.clientState.mutations);
|
||||
var queries = [].concat(persistedClient.clientState.queries);
|
||||
|
||||
var _client = _extends({}, persistedClient, {
|
||||
clientState: {
|
||||
mutations: mutations,
|
||||
queries: queries
|
||||
}
|
||||
}); // sort queries by dataUpdatedAt (oldest first)
|
||||
|
||||
|
||||
var sortedQueries = [].concat(queries).sort(function (a, b) {
|
||||
return a.state.dataUpdatedAt - b.state.dataUpdatedAt;
|
||||
}); // clean old queries and try to save
|
||||
|
||||
var _loop = function _loop() {
|
||||
var oldestData = sortedQueries.shift();
|
||||
_client.clientState.queries = queries.filter(function (q) {
|
||||
return q !== oldestData;
|
||||
});
|
||||
|
||||
if (trySave(_client)) {
|
||||
return {
|
||||
v: void 0
|
||||
}; // save success
|
||||
}
|
||||
};
|
||||
|
||||
while (sortedQueries.length > 0) {
|
||||
var _ret = _loop();
|
||||
|
||||
if (typeof _ret === "object") return _ret.v;
|
||||
} // clean mutations and try to save
|
||||
|
||||
|
||||
while (mutations.shift()) {
|
||||
if (trySave(_client)) {
|
||||
return; // save success
|
||||
}
|
||||
}
|
||||
}
|
||||
}, throttleTime),
|
||||
restoreClient: function restoreClient() {
|
||||
var cacheString = storage.getItem(key);
|
||||
|
||||
if (!cacheString) {
|
||||
return;
|
||||
}
|
||||
|
||||
return deserialize(cacheString);
|
||||
},
|
||||
removeClient: function removeClient() {
|
||||
storage.removeItem(key);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
persistClient: noop,
|
||||
restoreClient: noop,
|
||||
removeClient: noop
|
||||
};
|
||||
}
|
||||
|
||||
function throttle(func, wait) {
|
||||
if (wait === void 0) {
|
||||
wait = 100;
|
||||
}
|
||||
|
||||
var timer = null;
|
||||
var params;
|
||||
return function () {
|
||||
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
|
||||
args[_key] = arguments[_key];
|
||||
}
|
||||
|
||||
params = args;
|
||||
|
||||
if (timer === null) {
|
||||
timer = setTimeout(function () {
|
||||
func.apply(void 0, params);
|
||||
timer = null;
|
||||
}, wait);
|
||||
}
|
||||
};
|
||||
}
|
||||
+208
@@ -0,0 +1,208 @@
|
||||
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
|
||||
import _extends from "@babel/runtime/helpers/esm/extends";
|
||||
import React from 'react';
|
||||
import { displayValue, styled } from './utils';
|
||||
export var Entry = styled('div', {
|
||||
fontFamily: 'Menlo, monospace',
|
||||
fontSize: '1em',
|
||||
lineHeight: '1.7',
|
||||
outline: 'none',
|
||||
wordBreak: 'break-word'
|
||||
});
|
||||
export var Label = styled('span', {
|
||||
color: 'white'
|
||||
});
|
||||
export var LabelButton = styled('button', {
|
||||
cursor: 'pointer',
|
||||
color: 'white'
|
||||
});
|
||||
export var ExpandButton = styled('button', {
|
||||
cursor: 'pointer',
|
||||
color: 'inherit',
|
||||
font: 'inherit',
|
||||
outline: 'inherit',
|
||||
background: 'transparent',
|
||||
border: 'none',
|
||||
padding: 0
|
||||
});
|
||||
export var Value = styled('span', function (_props, theme) {
|
||||
return {
|
||||
color: theme.danger
|
||||
};
|
||||
});
|
||||
export var SubEntries = styled('div', {
|
||||
marginLeft: '.1em',
|
||||
paddingLeft: '1em',
|
||||
borderLeft: '2px solid rgba(0,0,0,.15)'
|
||||
});
|
||||
export var Info = styled('span', {
|
||||
color: 'grey',
|
||||
fontSize: '.7em'
|
||||
});
|
||||
export var Expander = function Expander(_ref) {
|
||||
var expanded = _ref.expanded,
|
||||
_ref$style = _ref.style,
|
||||
style = _ref$style === void 0 ? {} : _ref$style;
|
||||
return /*#__PURE__*/React.createElement("span", {
|
||||
style: _extends({
|
||||
display: 'inline-block',
|
||||
transition: 'all .1s ease',
|
||||
transform: "rotate(" + (expanded ? 90 : 0) + "deg) " + (style.transform || '')
|
||||
}, style)
|
||||
}, "\u25B6");
|
||||
};
|
||||
|
||||
/**
|
||||
* Chunk elements in the array by size
|
||||
*
|
||||
* when the array cannot be chunked evenly by size, the last chunk will be
|
||||
* filled with the remaining elements
|
||||
*
|
||||
* @example
|
||||
* chunkArray(['a','b', 'c', 'd', 'e'], 2) // returns [['a','b'], ['c', 'd'], ['e']]
|
||||
*/
|
||||
export function chunkArray(array, size) {
|
||||
if (size < 1) return [];
|
||||
var i = 0;
|
||||
var result = [];
|
||||
|
||||
while (i < array.length) {
|
||||
result.push(array.slice(i, i + size));
|
||||
i = i + size;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
export var DefaultRenderer = function DefaultRenderer(_ref2) {
|
||||
var HandleEntry = _ref2.HandleEntry,
|
||||
label = _ref2.label,
|
||||
value = _ref2.value,
|
||||
_ref2$subEntries = _ref2.subEntries,
|
||||
subEntries = _ref2$subEntries === void 0 ? [] : _ref2$subEntries,
|
||||
_ref2$subEntryPages = _ref2.subEntryPages,
|
||||
subEntryPages = _ref2$subEntryPages === void 0 ? [] : _ref2$subEntryPages,
|
||||
type = _ref2.type,
|
||||
_ref2$expanded = _ref2.expanded,
|
||||
expanded = _ref2$expanded === void 0 ? false : _ref2$expanded,
|
||||
toggleExpanded = _ref2.toggleExpanded,
|
||||
pageSize = _ref2.pageSize;
|
||||
|
||||
var _React$useState = React.useState([]),
|
||||
expandedPages = _React$useState[0],
|
||||
setExpandedPages = _React$useState[1];
|
||||
|
||||
return /*#__PURE__*/React.createElement(Entry, {
|
||||
key: label
|
||||
}, (subEntryPages == null ? void 0 : subEntryPages.length) ? /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(ExpandButton, {
|
||||
onClick: function onClick() {
|
||||
return toggleExpanded();
|
||||
}
|
||||
}, /*#__PURE__*/React.createElement(Expander, {
|
||||
expanded: expanded
|
||||
}), " ", label, ' ', /*#__PURE__*/React.createElement(Info, null, String(type).toLowerCase() === 'iterable' ? '(Iterable) ' : '', subEntries.length, " ", subEntries.length > 1 ? "items" : "item")), expanded ? subEntryPages.length === 1 ? /*#__PURE__*/React.createElement(SubEntries, null, subEntries.map(function (entry) {
|
||||
return /*#__PURE__*/React.createElement(HandleEntry, {
|
||||
key: entry.label,
|
||||
entry: entry
|
||||
});
|
||||
})) : /*#__PURE__*/React.createElement(SubEntries, null, subEntryPages.map(function (entries, index) {
|
||||
return /*#__PURE__*/React.createElement("div", {
|
||||
key: index
|
||||
}, /*#__PURE__*/React.createElement(Entry, null, /*#__PURE__*/React.createElement(LabelButton, {
|
||||
onClick: function onClick() {
|
||||
return setExpandedPages(function (old) {
|
||||
return old.includes(index) ? old.filter(function (d) {
|
||||
return d !== index;
|
||||
}) : [].concat(old, [index]);
|
||||
});
|
||||
}
|
||||
}, /*#__PURE__*/React.createElement(Expander, {
|
||||
expanded: expanded
|
||||
}), " [", index * pageSize, " ...", ' ', index * pageSize + pageSize - 1, "]"), expandedPages.includes(index) ? /*#__PURE__*/React.createElement(SubEntries, null, entries.map(function (entry) {
|
||||
return /*#__PURE__*/React.createElement(HandleEntry, {
|
||||
key: entry.label,
|
||||
entry: entry
|
||||
});
|
||||
})) : null));
|
||||
})) : null) : /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Label, null, label, ":"), " ", /*#__PURE__*/React.createElement(Value, null, displayValue(value))));
|
||||
};
|
||||
|
||||
function isIterable(x) {
|
||||
return Symbol.iterator in x;
|
||||
}
|
||||
|
||||
export default function Explorer(_ref3) {
|
||||
var value = _ref3.value,
|
||||
defaultExpanded = _ref3.defaultExpanded,
|
||||
_ref3$renderer = _ref3.renderer,
|
||||
renderer = _ref3$renderer === void 0 ? DefaultRenderer : _ref3$renderer,
|
||||
_ref3$pageSize = _ref3.pageSize,
|
||||
pageSize = _ref3$pageSize === void 0 ? 100 : _ref3$pageSize,
|
||||
rest = _objectWithoutPropertiesLoose(_ref3, ["value", "defaultExpanded", "renderer", "pageSize"]);
|
||||
|
||||
var _React$useState2 = React.useState(Boolean(defaultExpanded)),
|
||||
expanded = _React$useState2[0],
|
||||
setExpanded = _React$useState2[1];
|
||||
|
||||
var toggleExpanded = React.useCallback(function () {
|
||||
return setExpanded(function (old) {
|
||||
return !old;
|
||||
});
|
||||
}, []);
|
||||
var type = typeof value;
|
||||
var subEntries = [];
|
||||
|
||||
var makeProperty = function makeProperty(sub) {
|
||||
var _ref4;
|
||||
|
||||
var subDefaultExpanded = defaultExpanded === true ? (_ref4 = {}, _ref4[sub.label] = true, _ref4) : defaultExpanded == null ? void 0 : defaultExpanded[sub.label];
|
||||
return _extends({}, sub, {
|
||||
defaultExpanded: subDefaultExpanded
|
||||
});
|
||||
};
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
type = 'array';
|
||||
subEntries = value.map(function (d, i) {
|
||||
return makeProperty({
|
||||
label: i.toString(),
|
||||
value: d
|
||||
});
|
||||
});
|
||||
} else if (value !== null && typeof value === 'object' && isIterable(value) && typeof value[Symbol.iterator] === 'function') {
|
||||
type = 'Iterable';
|
||||
subEntries = Array.from(value, function (val, i) {
|
||||
return makeProperty({
|
||||
label: i.toString(),
|
||||
value: val
|
||||
});
|
||||
});
|
||||
} else if (typeof value === 'object' && value !== null) {
|
||||
type = 'object';
|
||||
subEntries = Object.entries(value).map(function (_ref5) {
|
||||
var key = _ref5[0],
|
||||
val = _ref5[1];
|
||||
return makeProperty({
|
||||
label: key,
|
||||
value: val
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
var subEntryPages = chunkArray(subEntries, pageSize);
|
||||
return renderer(_extends({
|
||||
HandleEntry: function HandleEntry(_ref6) {
|
||||
var entry = _ref6.entry;
|
||||
return /*#__PURE__*/React.createElement(Explorer, _extends({
|
||||
value: value,
|
||||
renderer: renderer
|
||||
}, rest, entry));
|
||||
},
|
||||
type: type,
|
||||
subEntries: subEntries,
|
||||
subEntryPages: subEntryPages,
|
||||
value: value,
|
||||
expanded: expanded,
|
||||
toggleExpanded: toggleExpanded,
|
||||
pageSize: pageSize
|
||||
}, rest));
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
import _extends from "@babel/runtime/helpers/esm/extends";
|
||||
import * as React from 'react';
|
||||
export default function Logo(props) {
|
||||
return /*#__PURE__*/React.createElement("svg", _extends({
|
||||
width: "40px",
|
||||
height: "40px",
|
||||
viewBox: "0 0 190 190",
|
||||
version: "1.1"
|
||||
}, props), /*#__PURE__*/React.createElement("g", {
|
||||
stroke: "none",
|
||||
strokeWidth: "1",
|
||||
fill: "none",
|
||||
fillRule: "evenodd"
|
||||
}, /*#__PURE__*/React.createElement("g", {
|
||||
transform: "translate(-33.000000, 0.000000)"
|
||||
}, /*#__PURE__*/React.createElement("path", {
|
||||
d: "M72.7239712,61.3436237 C69.631224,46.362877 68.9675112,34.8727722 70.9666331,26.5293551 C72.1555965,21.5671678 74.3293088,17.5190846 77.6346064,14.5984631 C81.1241394,11.5150478 85.5360327,10.0020122 90.493257,10.0020122 C98.6712013,10.0020122 107.26826,13.7273214 116.455725,20.8044264 C120.20312,23.6910458 124.092437,27.170411 128.131651,31.2444746 C128.45314,30.8310265 128.816542,30.4410453 129.22143,30.0806152 C140.64098,19.9149716 150.255245,13.5989272 158.478408,11.1636507 C163.367899,9.715636 167.958526,9.57768202 172.138936,10.983031 C176.551631,12.4664684 180.06766,15.5329489 182.548314,19.8281091 C186.642288,26.9166735 187.721918,36.2310983 186.195595,47.7320243 C185.573451,52.4199112 184.50985,57.5263831 183.007094,63.0593153 C183.574045,63.1277086 184.142416,63.2532808 184.705041,63.4395297 C199.193932,68.2358678 209.453582,73.3937462 215.665021,79.2882839 C219.360669,82.7953831 221.773972,86.6998434 222.646365,91.0218204 C223.567176,95.5836746 222.669313,100.159332 220.191548,104.451297 C216.105211,111.529614 208.591643,117.11221 197.887587,121.534031 C193.589552,123.309539 188.726579,124.917559 183.293259,126.363748 C183.541176,126.92292 183.733521,127.516759 183.862138,128.139758 C186.954886,143.120505 187.618598,154.61061 185.619477,162.954027 C184.430513,167.916214 182.256801,171.964297 178.951503,174.884919 C175.46197,177.968334 171.050077,179.48137 166.092853,179.48137 C157.914908,179.48137 149.31785,175.756061 140.130385,168.678956 C136.343104,165.761613 132.410866,162.238839 128.325434,158.108619 C127.905075,158.765474 127.388968,159.376011 126.77857,159.919385 C115.35902,170.085028 105.744755,176.401073 97.5215915,178.836349 C92.6321009,180.284364 88.0414736,180.422318 83.8610636,179.016969 C79.4483686,177.533532 75.9323404,174.467051 73.4516862,170.171891 C69.3577116,163.083327 68.2780823,153.768902 69.8044053,142.267976 C70.449038,137.410634 71.56762,132.103898 73.1575891,126.339009 C72.5361041,126.276104 71.9120754,126.144816 71.2949591,125.940529 C56.8060684,121.144191 46.5464184,115.986312 40.3349789,110.091775 C36.6393312,106.584675 34.2260275,102.680215 33.3536352,98.3582381 C32.4328237,93.7963839 33.3306866,89.2207269 35.8084524,84.9287618 C39.8947886,77.8504443 47.4083565,72.2678481 58.1124133,67.8460273 C62.5385143,66.0176154 67.5637208,64.366822 73.1939394,62.8874674 C72.9933393,62.3969171 72.8349374,61.8811235 72.7239712,61.3436237 Z",
|
||||
fill: "#002C4B",
|
||||
fillRule: "nonzero",
|
||||
transform: "translate(128.000000, 95.000000) scale(-1, 1) translate(-128.000000, -95.000000) "
|
||||
}), /*#__PURE__*/React.createElement("path", {
|
||||
d: "M113.396882,64 L142.608177,64 C144.399254,64 146.053521,64.958025 146.944933,66.5115174 L161.577138,92.0115174 C162.461464,93.5526583 162.461464,95.4473417 161.577138,96.9884826 L146.944933,122.488483 C146.053521,124.041975 144.399254,125 142.608177,125 L113.396882,125 C111.605806,125 109.951539,124.041975 109.060126,122.488483 L94.4279211,96.9884826 C93.543596,95.4473417 93.543596,93.5526583 94.4279211,92.0115174 L109.060126,66.5115174 C109.951539,64.958025 111.605806,64 113.396882,64 Z M138.987827,70.2765273 C140.779849,70.2765273 142.434839,71.2355558 143.325899,72.7903404 L154.343038,92.0138131 C155.225607,93.5537825 155.225607,95.4462175 154.343038,96.9861869 L143.325899,116.20966 C142.434839,117.764444 140.779849,118.723473 138.987827,118.723473 L117.017233,118.723473 C115.225211,118.723473 113.570221,117.764444 112.67916,116.20966 L101.662022,96.9861869 C100.779452,95.4462175 100.779452,93.5537825 101.662022,92.0138131 L112.67916,72.7903404 C113.570221,71.2355558 115.225211,70.2765273 117.017233,70.2765273 L138.987827,70.2765273 Z M135.080648,77.1414791 L120.924411,77.1414791 C119.134228,77.1414791 117.480644,78.0985567 116.5889,79.6508285 L116.5889,79.6508285 L109.489217,92.0093494 C108.603232,93.5515958 108.603232,95.4484042 109.489217,96.9906506 L109.489217,96.9906506 L116.5889,109.349172 C117.480644,110.901443 119.134228,111.858521 120.924411,111.858521 L120.924411,111.858521 L135.080648,111.858521 C136.870831,111.858521 138.524416,110.901443 139.41616,109.349172 L139.41616,109.349172 L146.515843,96.9906506 C147.401828,95.4484042 147.401828,93.5515958 146.515843,92.0093494 L146.515843,92.0093494 L139.41616,79.6508285 C138.524416,78.0985567 136.870831,77.1414791 135.080648,77.1414791 L135.080648,77.1414791 Z M131.319186,83.7122186 C133.108028,83.7122186 134.760587,84.6678753 135.652827,86.2183156 L138.983552,92.0060969 C139.87203,93.5500005 139.87203,95.4499995 138.983552,96.9939031 L135.652827,102.781684 C134.760587,104.332125 133.108028,105.287781 131.319186,105.287781 L124.685874,105.287781 C122.897032,105.287781 121.244473,104.332125 120.352233,102.781684 L117.021508,96.9939031 C116.13303,95.4499995 116.13303,93.5500005 117.021508,92.0060969 L120.352233,86.2183156 C121.244473,84.6678753 122.897032,83.7122186 124.685874,83.7122186 L131.319186,83.7122186 Z M128.003794,90.1848875 C126.459294,90.1848875 125.034382,91.0072828 124.263005,92.3424437 C123.491732,93.6774232 123.491732,95.3225768 124.263005,96.6575563 C125.034382,97.9927172 126.459294,98.8151125 128.001266,98.8151125 L128.001266,98.8151125 C129.545766,98.8151125 130.970678,97.9927172 131.742055,96.6575563 C132.513327,95.3225768 132.513327,93.6774232 131.742055,92.3424437 C130.970678,91.0072828 129.545766,90.1848875 128.003794,90.1848875 L128.003794,90.1848875 Z M93,94.5009646 L100.767764,94.5009646",
|
||||
fill: "#FFD94C"
|
||||
}), /*#__PURE__*/React.createElement("path", {
|
||||
d: "M87.8601729,108.357758 C89.1715224,107.608286 90.8360246,108.074601 91.5779424,109.399303 L91.5779424,109.399303 L92.0525843,110.24352 C95.8563392,116.982993 99.8190116,123.380176 103.940602,129.435068 C108.807881,136.585427 114.28184,143.82411 120.362479,151.151115 C121.316878,152.30114 121.184944,154.011176 120.065686,154.997937 L120.065686,154.997937 L119.454208,155.534625 C99.3465389,173.103314 86.2778188,176.612552 80.2480482,166.062341 C74.3500652,155.742717 76.4844915,136.982888 86.6513274,109.782853 C86.876818,109.179582 87.3045861,108.675291 87.8601729,108.357758 Z M173.534177,129.041504 C174.986131,128.785177 176.375496,129.742138 176.65963,131.194242 L176.65963,131.194242 L176.812815,131.986376 C181.782365,157.995459 178.283348,171 166.315764,171 C154.609745,171 139.708724,159.909007 121.612702,137.727022 C121.211349,137.235047 120.994572,136.617371 121,135.981509 C121.013158,134.480686 122.235785,133.274651 123.730918,133.287756 L123.730918,133.287756 L124.684654,133.294531 C132.305698,133.335994 139.714387,133.071591 146.910723,132.501323 C155.409039,131.82788 164.283523,130.674607 173.534177,129.041504 Z M180.408726,73.8119663 C180.932139,72.4026903 182.508386,71.6634537 183.954581,72.149012 L183.954581,72.149012 L184.742552,72.4154854 C210.583763,81.217922 220.402356,90.8916805 214.198332,101.436761 C208.129904,111.751366 190.484347,119.260339 161.26166,123.963678 C160.613529,124.067994 159.948643,123.945969 159.382735,123.618843 C158.047025,122.846729 157.602046,121.158214 158.388848,119.847438 L158.388848,119.847438 L158.889328,119.0105 C162.877183,112.31633 166.481358,105.654262 169.701854,99.0242957 C173.50501,91.1948179 177.073967,82.7907081 180.408726,73.8119663 Z M94.7383398,66.0363218 C95.3864708,65.9320063 96.0513565,66.0540315 96.6172646,66.3811573 C97.9529754,67.153271 98.3979538,68.8417862 97.6111517,70.1525615 L97.6111517,70.1525615 L97.1106718,70.9895001 C93.1228168,77.6836699 89.5186416,84.3457379 86.2981462,90.9757043 C82.49499,98.8051821 78.9260328,107.209292 75.5912744,116.188034 C75.0678608,117.59731 73.4916142,118.336546 72.045419,117.850988 L72.045419,117.850988 L71.2574475,117.584515 C45.4162372,108.782078 35.597644,99.1083195 41.8016679,88.5632391 C47.8700957,78.2486335 65.515653,70.7396611 94.7383398,66.0363218 Z M136.545792,34.4653746 C156.653461,16.8966864 169.722181,13.3874478 175.751952,23.9376587 C181.649935,34.2572826 179.515508,53.0171122 169.348673,80.2171474 C169.123182,80.8204179 168.695414,81.324709 168.139827,81.6422422 C166.828478,82.3917144 165.163975,81.9253986 164.422058,80.6006966 L164.422058,80.6006966 L163.947416,79.7564798 C160.143661,73.0170065 156.180988,66.6198239 152.059398,60.564932 C147.192119,53.4145727 141.71816,46.1758903 135.637521,38.8488847 C134.683122,37.6988602 134.815056,35.9888243 135.934314,35.0020629 L135.934314,35.0020629 Z M90.6842361,18 C102.390255,18 117.291276,29.0909926 135.387298,51.2729777 C135.788651,51.7649527 136.005428,52.3826288 136,53.0184911 C135.986842,54.5193144 134.764215,55.7253489 133.269082,55.7122445 L133.269082,55.7122445 L132.315346,55.7054689 C124.694302,55.6640063 117.285613,55.9284091 110.089277,56.4986773 C101.590961,57.17212 92.7164767,58.325393 83.4658235,59.9584962 C82.0138691,60.2148231 80.6245044,59.2578618 80.3403697,57.805758 L80.3403697,57.805758 L80.1871846,57.0136235 C75.2176347,31.0045412 78.7166519,18 90.6842361,18 Z",
|
||||
fill: "#FF4154"
|
||||
}))));
|
||||
}
|
||||
+693
@@ -0,0 +1,693 @@
|
||||
import _extends from "@babel/runtime/helpers/esm/extends";
|
||||
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
|
||||
import React from 'react';
|
||||
import { useQueryClient } from 'react-query';
|
||||
import { matchSorter } from 'match-sorter';
|
||||
import useLocalStorage from './useLocalStorage';
|
||||
import { useIsMounted, useSafeState } from './utils';
|
||||
import { Panel, QueryKeys, QueryKey, Button, Code, Input, Select, ActiveQueryPanel } from './styledComponents';
|
||||
import { ThemeProvider, defaultTheme as theme } from './theme';
|
||||
import { getQueryStatusLabel, getQueryStatusColor } from './utils';
|
||||
import Explorer from './Explorer';
|
||||
import Logo from './Logo';
|
||||
import { noop } from '../core/utils';
|
||||
var isServer = typeof window === 'undefined';
|
||||
export function ReactQueryDevtools(_ref) {
|
||||
var initialIsOpen = _ref.initialIsOpen,
|
||||
_ref$panelProps = _ref.panelProps,
|
||||
panelProps = _ref$panelProps === void 0 ? {} : _ref$panelProps,
|
||||
_ref$closeButtonProps = _ref.closeButtonProps,
|
||||
closeButtonProps = _ref$closeButtonProps === void 0 ? {} : _ref$closeButtonProps,
|
||||
_ref$toggleButtonProp = _ref.toggleButtonProps,
|
||||
toggleButtonProps = _ref$toggleButtonProp === void 0 ? {} : _ref$toggleButtonProp,
|
||||
_ref$position = _ref.position,
|
||||
position = _ref$position === void 0 ? 'bottom-left' : _ref$position,
|
||||
_ref$containerElement = _ref.containerElement,
|
||||
Container = _ref$containerElement === void 0 ? 'aside' : _ref$containerElement,
|
||||
styleNonce = _ref.styleNonce;
|
||||
var rootRef = React.useRef(null);
|
||||
var panelRef = React.useRef(null);
|
||||
|
||||
var _useLocalStorage = useLocalStorage('reactQueryDevtoolsOpen', initialIsOpen),
|
||||
isOpen = _useLocalStorage[0],
|
||||
setIsOpen = _useLocalStorage[1];
|
||||
|
||||
var _useLocalStorage2 = useLocalStorage('reactQueryDevtoolsHeight', null),
|
||||
devtoolsHeight = _useLocalStorage2[0],
|
||||
setDevtoolsHeight = _useLocalStorage2[1];
|
||||
|
||||
var _useSafeState = useSafeState(false),
|
||||
isResolvedOpen = _useSafeState[0],
|
||||
setIsResolvedOpen = _useSafeState[1];
|
||||
|
||||
var _useSafeState2 = useSafeState(false),
|
||||
isResizing = _useSafeState2[0],
|
||||
setIsResizing = _useSafeState2[1];
|
||||
|
||||
var isMounted = useIsMounted();
|
||||
|
||||
var _handleDragStart = function handleDragStart(panelElement, startEvent) {
|
||||
var _panelElement$getBoun;
|
||||
|
||||
if (startEvent.button !== 0) return; // Only allow left click for drag
|
||||
|
||||
setIsResizing(true);
|
||||
var dragInfo = {
|
||||
originalHeight: (_panelElement$getBoun = panelElement == null ? void 0 : panelElement.getBoundingClientRect().height) != null ? _panelElement$getBoun : 0,
|
||||
pageY: startEvent.pageY
|
||||
};
|
||||
|
||||
var run = function run(moveEvent) {
|
||||
var delta = dragInfo.pageY - moveEvent.pageY;
|
||||
var newHeight = (dragInfo == null ? void 0 : dragInfo.originalHeight) + delta;
|
||||
setDevtoolsHeight(newHeight);
|
||||
|
||||
if (newHeight < 70) {
|
||||
setIsOpen(false);
|
||||
} else {
|
||||
setIsOpen(true);
|
||||
}
|
||||
};
|
||||
|
||||
var unsub = function unsub() {
|
||||
setIsResizing(false);
|
||||
document.removeEventListener('mousemove', run);
|
||||
document.removeEventListener('mouseUp', unsub);
|
||||
};
|
||||
|
||||
document.addEventListener('mousemove', run);
|
||||
document.addEventListener('mouseup', unsub);
|
||||
};
|
||||
|
||||
React.useEffect(function () {
|
||||
setIsResolvedOpen(isOpen != null ? isOpen : false);
|
||||
}, [isOpen, isResolvedOpen, setIsResolvedOpen]); // Toggle panel visibility before/after transition (depending on direction).
|
||||
// Prevents focusing in a closed panel.
|
||||
|
||||
React.useEffect(function () {
|
||||
var ref = panelRef.current;
|
||||
|
||||
if (ref) {
|
||||
var handlePanelTransitionStart = function handlePanelTransitionStart() {
|
||||
if (ref && isResolvedOpen) {
|
||||
ref.style.visibility = 'visible';
|
||||
}
|
||||
};
|
||||
|
||||
var handlePanelTransitionEnd = function handlePanelTransitionEnd() {
|
||||
if (ref && !isResolvedOpen) {
|
||||
ref.style.visibility = 'hidden';
|
||||
}
|
||||
};
|
||||
|
||||
ref.addEventListener('transitionstart', handlePanelTransitionStart);
|
||||
ref.addEventListener('transitionend', handlePanelTransitionEnd);
|
||||
return function () {
|
||||
ref.removeEventListener('transitionstart', handlePanelTransitionStart);
|
||||
ref.removeEventListener('transitionend', handlePanelTransitionEnd);
|
||||
};
|
||||
}
|
||||
}, [isResolvedOpen]);
|
||||
React[isServer ? 'useEffect' : 'useLayoutEffect'](function () {
|
||||
if (isResolvedOpen) {
|
||||
var _rootRef$current, _rootRef$current$pare;
|
||||
|
||||
var previousValue = (_rootRef$current = rootRef.current) == null ? void 0 : (_rootRef$current$pare = _rootRef$current.parentElement) == null ? void 0 : _rootRef$current$pare.style.paddingBottom;
|
||||
|
||||
var run = function run() {
|
||||
var _panelRef$current, _rootRef$current2;
|
||||
|
||||
var containerHeight = (_panelRef$current = panelRef.current) == null ? void 0 : _panelRef$current.getBoundingClientRect().height;
|
||||
|
||||
if ((_rootRef$current2 = rootRef.current) == null ? void 0 : _rootRef$current2.parentElement) {
|
||||
rootRef.current.parentElement.style.paddingBottom = containerHeight + "px";
|
||||
}
|
||||
};
|
||||
|
||||
run();
|
||||
|
||||
if (typeof window !== 'undefined') {
|
||||
window.addEventListener('resize', run);
|
||||
return function () {
|
||||
var _rootRef$current3;
|
||||
|
||||
window.removeEventListener('resize', run);
|
||||
|
||||
if (((_rootRef$current3 = rootRef.current) == null ? void 0 : _rootRef$current3.parentElement) && typeof previousValue === 'string') {
|
||||
rootRef.current.parentElement.style.paddingBottom = previousValue;
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
}, [isResolvedOpen]);
|
||||
|
||||
var _panelProps$style = panelProps.style,
|
||||
panelStyle = _panelProps$style === void 0 ? {} : _panelProps$style,
|
||||
otherPanelProps = _objectWithoutPropertiesLoose(panelProps, ["style"]);
|
||||
|
||||
var _closeButtonProps$sty = closeButtonProps.style,
|
||||
closeButtonStyle = _closeButtonProps$sty === void 0 ? {} : _closeButtonProps$sty,
|
||||
onCloseClick = closeButtonProps.onClick,
|
||||
otherCloseButtonProps = _objectWithoutPropertiesLoose(closeButtonProps, ["style", "onClick"]);
|
||||
|
||||
var _toggleButtonProps$st = toggleButtonProps.style,
|
||||
toggleButtonStyle = _toggleButtonProps$st === void 0 ? {} : _toggleButtonProps$st,
|
||||
onToggleClick = toggleButtonProps.onClick,
|
||||
otherToggleButtonProps = _objectWithoutPropertiesLoose(toggleButtonProps, ["style", "onClick"]); // Do not render on the server
|
||||
|
||||
|
||||
if (!isMounted()) return null;
|
||||
return /*#__PURE__*/React.createElement(Container, {
|
||||
ref: rootRef,
|
||||
className: "ReactQueryDevtools",
|
||||
"aria-label": "React Query Devtools"
|
||||
}, /*#__PURE__*/React.createElement(ThemeProvider, {
|
||||
theme: theme
|
||||
}, /*#__PURE__*/React.createElement(ReactQueryDevtoolsPanel, _extends({
|
||||
ref: panelRef,
|
||||
styleNonce: styleNonce
|
||||
}, otherPanelProps, {
|
||||
style: _extends({
|
||||
position: 'fixed',
|
||||
bottom: '0',
|
||||
right: '0',
|
||||
zIndex: 99999,
|
||||
width: '100%',
|
||||
height: devtoolsHeight != null ? devtoolsHeight : 500,
|
||||
maxHeight: '90%',
|
||||
boxShadow: '0 0 20px rgba(0,0,0,.3)',
|
||||
borderTop: "1px solid " + theme.gray,
|
||||
transformOrigin: 'top',
|
||||
// visibility will be toggled after transitions, but set initial state here
|
||||
visibility: isOpen ? 'visible' : 'hidden'
|
||||
}, panelStyle, isResizing ? {
|
||||
transition: "none"
|
||||
} : {
|
||||
transition: "all .2s ease"
|
||||
}, isResolvedOpen ? {
|
||||
opacity: 1,
|
||||
pointerEvents: 'all',
|
||||
transform: "translateY(0) scale(1)"
|
||||
} : {
|
||||
opacity: 0,
|
||||
pointerEvents: 'none',
|
||||
transform: "translateY(15px) scale(1.02)"
|
||||
}),
|
||||
isOpen: isResolvedOpen,
|
||||
setIsOpen: setIsOpen,
|
||||
handleDragStart: function handleDragStart(e) {
|
||||
return _handleDragStart(panelRef.current, e);
|
||||
}
|
||||
})), isResolvedOpen ? /*#__PURE__*/React.createElement(Button, _extends({
|
||||
type: "button",
|
||||
"aria-controls": "ReactQueryDevtoolsPanel",
|
||||
"aria-haspopup": "true",
|
||||
"aria-expanded": "true"
|
||||
}, otherCloseButtonProps, {
|
||||
onClick: function onClick(e) {
|
||||
setIsOpen(false);
|
||||
onCloseClick && onCloseClick(e);
|
||||
},
|
||||
style: _extends({
|
||||
position: 'fixed',
|
||||
zIndex: 99999,
|
||||
margin: '.5em',
|
||||
bottom: 0
|
||||
}, position === 'top-right' ? {
|
||||
right: '0'
|
||||
} : position === 'top-left' ? {
|
||||
left: '0'
|
||||
} : position === 'bottom-right' ? {
|
||||
right: '0'
|
||||
} : {
|
||||
left: '0'
|
||||
}, closeButtonStyle)
|
||||
}), "Close") : null), !isResolvedOpen ? /*#__PURE__*/React.createElement("button", _extends({
|
||||
type: "button"
|
||||
}, otherToggleButtonProps, {
|
||||
"aria-label": "Open React Query Devtools",
|
||||
"aria-controls": "ReactQueryDevtoolsPanel",
|
||||
"aria-haspopup": "true",
|
||||
"aria-expanded": "false",
|
||||
onClick: function onClick(e) {
|
||||
setIsOpen(true);
|
||||
onToggleClick && onToggleClick(e);
|
||||
},
|
||||
style: _extends({
|
||||
background: 'none',
|
||||
border: 0,
|
||||
padding: 0,
|
||||
position: 'fixed',
|
||||
zIndex: 99999,
|
||||
display: 'inline-flex',
|
||||
fontSize: '1.5em',
|
||||
margin: '.5em',
|
||||
cursor: 'pointer',
|
||||
width: 'fit-content'
|
||||
}, position === 'top-right' ? {
|
||||
top: '0',
|
||||
right: '0'
|
||||
} : position === 'top-left' ? {
|
||||
top: '0',
|
||||
left: '0'
|
||||
} : position === 'bottom-right' ? {
|
||||
bottom: '0',
|
||||
right: '0'
|
||||
} : {
|
||||
bottom: '0',
|
||||
left: '0'
|
||||
}, toggleButtonStyle)
|
||||
}), /*#__PURE__*/React.createElement(Logo, {
|
||||
"aria-hidden": true
|
||||
})) : null);
|
||||
}
|
||||
|
||||
var getStatusRank = function getStatusRank(q) {
|
||||
return q.state.isFetching ? 0 : !q.getObserversCount() ? 3 : q.isStale() ? 2 : 1;
|
||||
};
|
||||
|
||||
var sortFns = {
|
||||
'Status > Last Updated': function StatusLastUpdated(a, b) {
|
||||
var _sortFns$LastUpdated;
|
||||
|
||||
return getStatusRank(a) === getStatusRank(b) ? (_sortFns$LastUpdated = sortFns['Last Updated']) == null ? void 0 : _sortFns$LastUpdated.call(sortFns, a, b) : getStatusRank(a) > getStatusRank(b) ? 1 : -1;
|
||||
},
|
||||
'Query Hash': function QueryHash(a, b) {
|
||||
return a.queryHash > b.queryHash ? 1 : -1;
|
||||
},
|
||||
'Last Updated': function LastUpdated(a, b) {
|
||||
return a.state.dataUpdatedAt < b.state.dataUpdatedAt ? 1 : -1;
|
||||
}
|
||||
};
|
||||
export var ReactQueryDevtoolsPanel = /*#__PURE__*/React.forwardRef(function ReactQueryDevtoolsPanel(props, ref) {
|
||||
var _activeQuery$state;
|
||||
|
||||
var _props$isOpen = props.isOpen,
|
||||
isOpen = _props$isOpen === void 0 ? true : _props$isOpen,
|
||||
styleNonce = props.styleNonce,
|
||||
setIsOpen = props.setIsOpen,
|
||||
handleDragStart = props.handleDragStart,
|
||||
panelProps = _objectWithoutPropertiesLoose(props, ["isOpen", "styleNonce", "setIsOpen", "handleDragStart"]);
|
||||
|
||||
var queryClient = useQueryClient();
|
||||
var queryCache = queryClient.getQueryCache();
|
||||
|
||||
var _useLocalStorage3 = useLocalStorage('reactQueryDevtoolsSortFn', Object.keys(sortFns)[0]),
|
||||
sort = _useLocalStorage3[0],
|
||||
setSort = _useLocalStorage3[1];
|
||||
|
||||
var _useLocalStorage4 = useLocalStorage('reactQueryDevtoolsFilter', ''),
|
||||
filter = _useLocalStorage4[0],
|
||||
setFilter = _useLocalStorage4[1];
|
||||
|
||||
var _useLocalStorage5 = useLocalStorage('reactQueryDevtoolsSortDesc', false),
|
||||
sortDesc = _useLocalStorage5[0],
|
||||
setSortDesc = _useLocalStorage5[1];
|
||||
|
||||
var sortFn = React.useMemo(function () {
|
||||
return sortFns[sort];
|
||||
}, [sort]);
|
||||
React[isServer ? 'useEffect' : 'useLayoutEffect'](function () {
|
||||
if (!sortFn) {
|
||||
setSort(Object.keys(sortFns)[0]);
|
||||
}
|
||||
}, [setSort, sortFn]);
|
||||
|
||||
var _useSafeState3 = useSafeState(Object.values(queryCache.findAll())),
|
||||
unsortedQueries = _useSafeState3[0],
|
||||
setUnsortedQueries = _useSafeState3[1];
|
||||
|
||||
var _useLocalStorage6 = useLocalStorage('reactQueryDevtoolsActiveQueryHash', ''),
|
||||
activeQueryHash = _useLocalStorage6[0],
|
||||
setActiveQueryHash = _useLocalStorage6[1];
|
||||
|
||||
var queries = React.useMemo(function () {
|
||||
var sorted = [].concat(unsortedQueries).sort(sortFn);
|
||||
|
||||
if (sortDesc) {
|
||||
sorted.reverse();
|
||||
}
|
||||
|
||||
if (!filter) {
|
||||
return sorted;
|
||||
}
|
||||
|
||||
return matchSorter(sorted, filter, {
|
||||
keys: ['queryHash']
|
||||
}).filter(function (d) {
|
||||
return d.queryHash;
|
||||
});
|
||||
}, [sortDesc, sortFn, unsortedQueries, filter]);
|
||||
var activeQuery = React.useMemo(function () {
|
||||
return queries.find(function (query) {
|
||||
return query.queryHash === activeQueryHash;
|
||||
});
|
||||
}, [activeQueryHash, queries]);
|
||||
var hasFresh = queries.filter(function (q) {
|
||||
return getQueryStatusLabel(q) === 'fresh';
|
||||
}).length;
|
||||
var hasFetching = queries.filter(function (q) {
|
||||
return getQueryStatusLabel(q) === 'fetching';
|
||||
}).length;
|
||||
var hasStale = queries.filter(function (q) {
|
||||
return getQueryStatusLabel(q) === 'stale';
|
||||
}).length;
|
||||
var hasInactive = queries.filter(function (q) {
|
||||
return getQueryStatusLabel(q) === 'inactive';
|
||||
}).length;
|
||||
React.useEffect(function () {
|
||||
if (isOpen) {
|
||||
var unsubscribe = queryCache.subscribe(function () {
|
||||
setUnsortedQueries(Object.values(queryCache.getAll()));
|
||||
}); // re-subscribing after the panel is closed and re-opened won't trigger the callback,
|
||||
// So we'll manually populate our state
|
||||
|
||||
setUnsortedQueries(Object.values(queryCache.getAll()));
|
||||
return unsubscribe;
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}, [isOpen, sort, sortFn, sortDesc, setUnsortedQueries, queryCache]);
|
||||
|
||||
var handleRefetch = function handleRefetch() {
|
||||
var promise = activeQuery == null ? void 0 : activeQuery.fetch();
|
||||
promise == null ? void 0 : promise.catch(noop);
|
||||
};
|
||||
|
||||
return /*#__PURE__*/React.createElement(ThemeProvider, {
|
||||
theme: theme
|
||||
}, /*#__PURE__*/React.createElement(Panel, _extends({
|
||||
ref: ref,
|
||||
className: "ReactQueryDevtoolsPanel",
|
||||
"aria-label": "React Query Devtools Panel",
|
||||
id: "ReactQueryDevtoolsPanel"
|
||||
}, panelProps), /*#__PURE__*/React.createElement("style", {
|
||||
nonce: styleNonce,
|
||||
dangerouslySetInnerHTML: {
|
||||
__html: "\n .ReactQueryDevtoolsPanel * {\n scrollbar-color: " + theme.backgroundAlt + " " + theme.gray + ";\n }\n\n .ReactQueryDevtoolsPanel *::-webkit-scrollbar, .ReactQueryDevtoolsPanel scrollbar {\n width: 1em;\n height: 1em;\n }\n\n .ReactQueryDevtoolsPanel *::-webkit-scrollbar-track, .ReactQueryDevtoolsPanel scrollbar-track {\n background: " + theme.backgroundAlt + ";\n }\n\n .ReactQueryDevtoolsPanel *::-webkit-scrollbar-thumb, .ReactQueryDevtoolsPanel scrollbar-thumb {\n background: " + theme.gray + ";\n border-radius: .5em;\n border: 3px solid " + theme.backgroundAlt + ";\n }\n "
|
||||
}
|
||||
}), /*#__PURE__*/React.createElement("div", {
|
||||
style: {
|
||||
position: 'absolute',
|
||||
left: 0,
|
||||
top: 0,
|
||||
width: '100%',
|
||||
height: '4px',
|
||||
marginBottom: '-4px',
|
||||
cursor: 'row-resize',
|
||||
zIndex: 100000
|
||||
},
|
||||
onMouseDown: handleDragStart
|
||||
}), /*#__PURE__*/React.createElement("div", {
|
||||
style: {
|
||||
flex: '1 1 500px',
|
||||
minHeight: '40%',
|
||||
maxHeight: '100%',
|
||||
overflow: 'auto',
|
||||
borderRight: "1px solid " + theme.grayAlt,
|
||||
display: isOpen ? 'flex' : 'none',
|
||||
flexDirection: 'column'
|
||||
}
|
||||
}, /*#__PURE__*/React.createElement("div", {
|
||||
style: {
|
||||
padding: '.5em',
|
||||
background: theme.backgroundAlt,
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center'
|
||||
}
|
||||
}, /*#__PURE__*/React.createElement("button", {
|
||||
type: "button",
|
||||
"aria-label": "Close React Query Devtools",
|
||||
"aria-controls": "ReactQueryDevtoolsPanel",
|
||||
"aria-haspopup": "true",
|
||||
"aria-expanded": "true",
|
||||
onClick: function onClick() {
|
||||
return setIsOpen(false);
|
||||
},
|
||||
style: {
|
||||
display: 'inline-flex',
|
||||
background: 'none',
|
||||
border: 0,
|
||||
padding: 0,
|
||||
marginRight: '.5em',
|
||||
cursor: 'pointer'
|
||||
}
|
||||
}, /*#__PURE__*/React.createElement(Logo, {
|
||||
"aria-hidden": true
|
||||
})), /*#__PURE__*/React.createElement("div", {
|
||||
style: {
|
||||
display: 'flex',
|
||||
flexDirection: 'column'
|
||||
}
|
||||
}, /*#__PURE__*/React.createElement(QueryKeys, {
|
||||
style: {
|
||||
marginBottom: '.5em'
|
||||
}
|
||||
}, /*#__PURE__*/React.createElement(QueryKey, {
|
||||
style: {
|
||||
background: theme.success,
|
||||
opacity: hasFresh ? 1 : 0.3
|
||||
}
|
||||
}, "fresh ", /*#__PURE__*/React.createElement(Code, null, "(", hasFresh, ")")), ' ', /*#__PURE__*/React.createElement(QueryKey, {
|
||||
style: {
|
||||
background: theme.active,
|
||||
opacity: hasFetching ? 1 : 0.3
|
||||
}
|
||||
}, "fetching ", /*#__PURE__*/React.createElement(Code, null, "(", hasFetching, ")")), ' ', /*#__PURE__*/React.createElement(QueryKey, {
|
||||
style: {
|
||||
background: theme.warning,
|
||||
color: 'black',
|
||||
textShadow: '0',
|
||||
opacity: hasStale ? 1 : 0.3
|
||||
}
|
||||
}, "stale ", /*#__PURE__*/React.createElement(Code, null, "(", hasStale, ")")), ' ', /*#__PURE__*/React.createElement(QueryKey, {
|
||||
style: {
|
||||
background: theme.gray,
|
||||
opacity: hasInactive ? 1 : 0.3
|
||||
}
|
||||
}, "inactive ", /*#__PURE__*/React.createElement(Code, null, "(", hasInactive, ")"))), /*#__PURE__*/React.createElement("div", {
|
||||
style: {
|
||||
display: 'flex',
|
||||
alignItems: 'center'
|
||||
}
|
||||
}, /*#__PURE__*/React.createElement(Input, {
|
||||
placeholder: "Filter",
|
||||
"aria-label": "Filter by queryhash",
|
||||
value: filter != null ? filter : '',
|
||||
onChange: function onChange(e) {
|
||||
return setFilter(e.target.value);
|
||||
},
|
||||
onKeyDown: function onKeyDown(e) {
|
||||
if (e.key === 'Escape') setFilter('');
|
||||
},
|
||||
style: {
|
||||
flex: '1',
|
||||
marginRight: '.5em',
|
||||
width: '100%'
|
||||
}
|
||||
}), !filter ? /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Select, {
|
||||
"aria-label": "Sort queries",
|
||||
value: sort,
|
||||
onChange: function onChange(e) {
|
||||
return setSort(e.target.value);
|
||||
},
|
||||
style: {
|
||||
flex: '1',
|
||||
minWidth: 75,
|
||||
marginRight: '.5em'
|
||||
}
|
||||
}, Object.keys(sortFns).map(function (key) {
|
||||
return /*#__PURE__*/React.createElement("option", {
|
||||
key: key,
|
||||
value: key
|
||||
}, "Sort by ", key);
|
||||
})), /*#__PURE__*/React.createElement(Button, {
|
||||
type: "button",
|
||||
onClick: function onClick() {
|
||||
return setSortDesc(function (old) {
|
||||
return !old;
|
||||
});
|
||||
},
|
||||
style: {
|
||||
padding: '.3em .4em'
|
||||
}
|
||||
}, sortDesc ? '⬇ Desc' : '⬆ Asc')) : null))), /*#__PURE__*/React.createElement("div", {
|
||||
style: {
|
||||
overflowY: 'auto',
|
||||
flex: '1'
|
||||
}
|
||||
}, queries.map(function (query, i) {
|
||||
var isDisabled = query.getObserversCount() > 0 && !query.isActive();
|
||||
return /*#__PURE__*/React.createElement("div", {
|
||||
key: query.queryHash || i,
|
||||
role: "button",
|
||||
"aria-label": "Open query details for " + query.queryHash,
|
||||
onClick: function onClick() {
|
||||
return setActiveQueryHash(activeQueryHash === query.queryHash ? '' : query.queryHash);
|
||||
},
|
||||
style: {
|
||||
display: 'flex',
|
||||
borderBottom: "solid 1px " + theme.grayAlt,
|
||||
cursor: 'pointer',
|
||||
background: query === activeQuery ? 'rgba(255,255,255,.1)' : undefined
|
||||
}
|
||||
}, /*#__PURE__*/React.createElement("div", {
|
||||
style: {
|
||||
flex: '0 0 auto',
|
||||
width: '2em',
|
||||
height: '2em',
|
||||
background: getQueryStatusColor(query, theme),
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
fontWeight: 'bold',
|
||||
textShadow: getQueryStatusLabel(query) === 'stale' ? '0' : '0 0 10px black',
|
||||
color: getQueryStatusLabel(query) === 'stale' ? 'black' : 'white'
|
||||
}
|
||||
}, query.getObserversCount()), isDisabled ? /*#__PURE__*/React.createElement("div", {
|
||||
style: {
|
||||
flex: '0 0 auto',
|
||||
height: '2em',
|
||||
background: theme.gray,
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
fontWeight: 'bold',
|
||||
padding: '0 0.5em'
|
||||
}
|
||||
}, "disabled") : null, /*#__PURE__*/React.createElement(Code, {
|
||||
style: {
|
||||
padding: '.5em'
|
||||
}
|
||||
}, "" + query.queryHash));
|
||||
}))), activeQuery ? /*#__PURE__*/React.createElement(ActiveQueryPanel, null, /*#__PURE__*/React.createElement("div", {
|
||||
style: {
|
||||
padding: '.5em',
|
||||
background: theme.backgroundAlt,
|
||||
position: 'sticky',
|
||||
top: 0,
|
||||
zIndex: 1
|
||||
}
|
||||
}, "Query Details"), /*#__PURE__*/React.createElement("div", {
|
||||
style: {
|
||||
padding: '.5em'
|
||||
}
|
||||
}, /*#__PURE__*/React.createElement("div", {
|
||||
style: {
|
||||
marginBottom: '.5em',
|
||||
display: 'flex',
|
||||
alignItems: 'start',
|
||||
justifyContent: 'space-between'
|
||||
}
|
||||
}, /*#__PURE__*/React.createElement(Code, {
|
||||
style: {
|
||||
lineHeight: '1.8em'
|
||||
}
|
||||
}, /*#__PURE__*/React.createElement("pre", {
|
||||
style: {
|
||||
margin: 0,
|
||||
padding: 0,
|
||||
overflow: 'auto'
|
||||
}
|
||||
}, JSON.stringify(activeQuery.queryKey, null, 2))), /*#__PURE__*/React.createElement("span", {
|
||||
style: {
|
||||
padding: '0.3em .6em',
|
||||
borderRadius: '0.4em',
|
||||
fontWeight: 'bold',
|
||||
textShadow: '0 2px 10px black',
|
||||
background: getQueryStatusColor(activeQuery, theme),
|
||||
flexShrink: 0
|
||||
}
|
||||
}, getQueryStatusLabel(activeQuery))), /*#__PURE__*/React.createElement("div", {
|
||||
style: {
|
||||
marginBottom: '.5em',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'space-between'
|
||||
}
|
||||
}, "Observers: ", /*#__PURE__*/React.createElement(Code, null, activeQuery.getObserversCount())), /*#__PURE__*/React.createElement("div", {
|
||||
style: {
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'space-between'
|
||||
}
|
||||
}, "Last Updated:", ' ', /*#__PURE__*/React.createElement(Code, null, new Date(activeQuery.state.dataUpdatedAt).toLocaleTimeString()))), /*#__PURE__*/React.createElement("div", {
|
||||
style: {
|
||||
background: theme.backgroundAlt,
|
||||
padding: '.5em',
|
||||
position: 'sticky',
|
||||
top: 0,
|
||||
zIndex: 1
|
||||
}
|
||||
}, "Actions"), /*#__PURE__*/React.createElement("div", {
|
||||
style: {
|
||||
padding: '0.5em'
|
||||
}
|
||||
}, /*#__PURE__*/React.createElement(Button, {
|
||||
type: "button",
|
||||
onClick: handleRefetch,
|
||||
disabled: activeQuery.state.isFetching,
|
||||
style: {
|
||||
background: theme.active
|
||||
}
|
||||
}, "Refetch"), ' ', /*#__PURE__*/React.createElement(Button, {
|
||||
type: "button",
|
||||
onClick: function onClick() {
|
||||
return queryClient.invalidateQueries(activeQuery);
|
||||
},
|
||||
style: {
|
||||
background: theme.warning,
|
||||
color: theme.inputTextColor
|
||||
}
|
||||
}, "Invalidate"), ' ', /*#__PURE__*/React.createElement(Button, {
|
||||
type: "button",
|
||||
onClick: function onClick() {
|
||||
return queryClient.resetQueries(activeQuery);
|
||||
},
|
||||
style: {
|
||||
background: theme.gray
|
||||
}
|
||||
}, "Reset"), ' ', /*#__PURE__*/React.createElement(Button, {
|
||||
type: "button",
|
||||
onClick: function onClick() {
|
||||
return queryClient.removeQueries(activeQuery);
|
||||
},
|
||||
style: {
|
||||
background: theme.danger
|
||||
}
|
||||
}, "Remove")), /*#__PURE__*/React.createElement("div", {
|
||||
style: {
|
||||
background: theme.backgroundAlt,
|
||||
padding: '.5em',
|
||||
position: 'sticky',
|
||||
top: 0,
|
||||
zIndex: 1
|
||||
}
|
||||
}, "Data Explorer"), /*#__PURE__*/React.createElement("div", {
|
||||
style: {
|
||||
padding: '.5em'
|
||||
}
|
||||
}, /*#__PURE__*/React.createElement(Explorer, {
|
||||
label: "Data",
|
||||
value: activeQuery == null ? void 0 : (_activeQuery$state = activeQuery.state) == null ? void 0 : _activeQuery$state.data,
|
||||
defaultExpanded: {}
|
||||
})), /*#__PURE__*/React.createElement("div", {
|
||||
style: {
|
||||
background: theme.backgroundAlt,
|
||||
padding: '.5em',
|
||||
position: 'sticky',
|
||||
top: 0,
|
||||
zIndex: 1
|
||||
}
|
||||
}, "Query Explorer"), /*#__PURE__*/React.createElement("div", {
|
||||
style: {
|
||||
padding: '.5em'
|
||||
}
|
||||
}, /*#__PURE__*/React.createElement(Explorer, {
|
||||
label: "Query",
|
||||
value: activeQuery,
|
||||
defaultExpanded: {
|
||||
queryKey: true
|
||||
}
|
||||
}))) : null));
|
||||
});
|
||||
+1
@@ -0,0 +1 @@
|
||||
export * from './devtools';
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
import { styled } from './utils';
|
||||
export var Panel = styled('div', function (_props, theme) {
|
||||
return {
|
||||
fontSize: 'clamp(12px, 1.5vw, 14px)',
|
||||
fontFamily: "sans-serif",
|
||||
display: 'flex',
|
||||
backgroundColor: theme.background,
|
||||
color: theme.foreground
|
||||
};
|
||||
}, {
|
||||
'(max-width: 700px)': {
|
||||
flexDirection: 'column'
|
||||
},
|
||||
'(max-width: 600px)': {
|
||||
fontSize: '.9em' // flexDirection: 'column',
|
||||
|
||||
}
|
||||
});
|
||||
export var ActiveQueryPanel = styled('div', function () {
|
||||
return {
|
||||
flex: '1 1 500px',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
overflow: 'auto',
|
||||
height: '100%'
|
||||
};
|
||||
}, {
|
||||
'(max-width: 700px)': function maxWidth700px(_props, theme) {
|
||||
return {
|
||||
borderTop: "2px solid " + theme.gray
|
||||
};
|
||||
}
|
||||
});
|
||||
export var Button = styled('button', function (props, theme) {
|
||||
return {
|
||||
appearance: 'none',
|
||||
fontSize: '.9em',
|
||||
fontWeight: 'bold',
|
||||
background: theme.gray,
|
||||
border: '0',
|
||||
borderRadius: '.3em',
|
||||
color: 'white',
|
||||
padding: '.5em',
|
||||
opacity: props.disabled ? '.5' : undefined,
|
||||
cursor: 'pointer'
|
||||
};
|
||||
});
|
||||
export var QueryKeys = styled('span', {
|
||||
display: 'inline-block',
|
||||
fontSize: '0.9em'
|
||||
});
|
||||
export var QueryKey = styled('span', {
|
||||
display: 'inline-flex',
|
||||
alignItems: 'center',
|
||||
padding: '.2em .4em',
|
||||
fontWeight: 'bold',
|
||||
textShadow: '0 0 10px black',
|
||||
borderRadius: '.2em'
|
||||
});
|
||||
export var Code = styled('code', {
|
||||
fontSize: '.9em',
|
||||
color: 'inherit',
|
||||
background: 'inherit'
|
||||
});
|
||||
export var Input = styled('input', function (_props, theme) {
|
||||
return {
|
||||
backgroundColor: theme.inputBackgroundColor,
|
||||
border: 0,
|
||||
borderRadius: '.2em',
|
||||
color: theme.inputTextColor,
|
||||
fontSize: '.9em',
|
||||
lineHeight: "1.3",
|
||||
padding: '.3em .4em'
|
||||
};
|
||||
});
|
||||
export var Select = styled('select', function (_props, theme) {
|
||||
return {
|
||||
display: "inline-block",
|
||||
fontSize: ".9em",
|
||||
fontFamily: "sans-serif",
|
||||
fontWeight: 'normal',
|
||||
lineHeight: "1.3",
|
||||
padding: ".3em 1.5em .3em .5em",
|
||||
height: 'auto',
|
||||
border: 0,
|
||||
borderRadius: ".2em",
|
||||
appearance: "none",
|
||||
WebkitAppearance: 'none',
|
||||
backgroundColor: theme.inputBackgroundColor,
|
||||
backgroundImage: "url(\"data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='100' height='100' fill='%23444444'><polygon points='0,25 100,25 50,75'/></svg>\")",
|
||||
backgroundRepeat: "no-repeat",
|
||||
backgroundPosition: "right .55em center",
|
||||
backgroundSize: ".65em auto, 100%",
|
||||
color: theme.inputTextColor
|
||||
};
|
||||
}, {
|
||||
'(max-width: 500px)': {
|
||||
display: 'none'
|
||||
}
|
||||
});
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
import _extends from "@babel/runtime/helpers/esm/extends";
|
||||
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
|
||||
import React from 'react';
|
||||
export var defaultTheme = {
|
||||
background: '#0b1521',
|
||||
backgroundAlt: '#132337',
|
||||
foreground: 'white',
|
||||
gray: '#3f4e60',
|
||||
grayAlt: '#222e3e',
|
||||
inputBackgroundColor: '#fff',
|
||||
inputTextColor: '#000',
|
||||
success: '#00ab52',
|
||||
danger: '#ff0085',
|
||||
active: '#006bff',
|
||||
warning: '#ffb200'
|
||||
};
|
||||
var ThemeContext = /*#__PURE__*/React.createContext(defaultTheme);
|
||||
export function ThemeProvider(_ref) {
|
||||
var theme = _ref.theme,
|
||||
rest = _objectWithoutPropertiesLoose(_ref, ["theme"]);
|
||||
|
||||
return /*#__PURE__*/React.createElement(ThemeContext.Provider, _extends({
|
||||
value: theme
|
||||
}, rest));
|
||||
}
|
||||
export function useTheme() {
|
||||
return React.useContext(ThemeContext);
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
import React from 'react';
|
||||
|
||||
var getItem = function getItem(key) {
|
||||
try {
|
||||
var itemValue = localStorage.getItem(key);
|
||||
|
||||
if (typeof itemValue === 'string') {
|
||||
return JSON.parse(itemValue);
|
||||
}
|
||||
|
||||
return undefined;
|
||||
} catch (_unused) {
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
|
||||
export default function useLocalStorage(key, defaultValue) {
|
||||
var _React$useState = React.useState(),
|
||||
value = _React$useState[0],
|
||||
setValue = _React$useState[1];
|
||||
|
||||
React.useEffect(function () {
|
||||
var initialValue = getItem(key);
|
||||
|
||||
if (typeof initialValue === 'undefined' || initialValue === null) {
|
||||
setValue(typeof defaultValue === 'function' ? defaultValue() : defaultValue);
|
||||
} else {
|
||||
setValue(initialValue);
|
||||
}
|
||||
}, [defaultValue, key]);
|
||||
var setter = React.useCallback(function (updater) {
|
||||
setValue(function (old) {
|
||||
var newVal = updater;
|
||||
|
||||
if (typeof updater == 'function') {
|
||||
newVal = updater(old);
|
||||
}
|
||||
|
||||
try {
|
||||
localStorage.setItem(key, JSON.stringify(newVal));
|
||||
} catch (_unused2) {}
|
||||
|
||||
return newVal;
|
||||
});
|
||||
}, [key]);
|
||||
return [value, setter];
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
import React from 'react';
|
||||
export default function useMediaQuery(query) {
|
||||
// Keep track of the preference in state, start with the current match
|
||||
var _React$useState = React.useState(function () {
|
||||
if (typeof window !== 'undefined') {
|
||||
return window.matchMedia && window.matchMedia(query).matches;
|
||||
}
|
||||
}),
|
||||
isMatch = _React$useState[0],
|
||||
setIsMatch = _React$useState[1]; // Watch for changes
|
||||
|
||||
|
||||
React.useEffect(function () {
|
||||
if (typeof window !== 'undefined') {
|
||||
if (!window.matchMedia) {
|
||||
return;
|
||||
} // Create a matcher
|
||||
|
||||
|
||||
var matcher = window.matchMedia(query); // Create our handler
|
||||
|
||||
var onChange = function onChange(_ref) {
|
||||
var matches = _ref.matches;
|
||||
return setIsMatch(matches);
|
||||
}; // Listen for changes
|
||||
|
||||
|
||||
matcher.addListener(onChange);
|
||||
return function () {
|
||||
// Stop listening for changes
|
||||
matcher.removeListener(onChange);
|
||||
};
|
||||
}
|
||||
}, [isMatch, query, setIsMatch]);
|
||||
return isMatch;
|
||||
}
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
import _extends from "@babel/runtime/helpers/esm/extends";
|
||||
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
|
||||
import React from 'react';
|
||||
import { useTheme } from './theme';
|
||||
import useMediaQuery from './useMediaQuery';
|
||||
export var isServer = typeof window === 'undefined';
|
||||
export function getQueryStatusColor(query, theme) {
|
||||
return query.state.isFetching ? theme.active : !query.getObserversCount() ? theme.gray : query.isStale() ? theme.warning : theme.success;
|
||||
}
|
||||
export function getQueryStatusLabel(query) {
|
||||
return query.state.isFetching ? 'fetching' : !query.getObserversCount() ? 'inactive' : query.isStale() ? 'stale' : 'fresh';
|
||||
}
|
||||
export function styled(type, newStyles, queries) {
|
||||
if (queries === void 0) {
|
||||
queries = {};
|
||||
}
|
||||
|
||||
return /*#__PURE__*/React.forwardRef(function (_ref, ref) {
|
||||
var style = _ref.style,
|
||||
rest = _objectWithoutPropertiesLoose(_ref, ["style"]);
|
||||
|
||||
var theme = useTheme();
|
||||
var mediaStyles = Object.entries(queries).reduce(function (current, _ref2) {
|
||||
var key = _ref2[0],
|
||||
value = _ref2[1];
|
||||
// eslint-disable-next-line react-hooks/rules-of-hooks
|
||||
return useMediaQuery(key) ? _extends({}, current, typeof value === 'function' ? value(rest, theme) : value) : current;
|
||||
}, {});
|
||||
return /*#__PURE__*/React.createElement(type, _extends({}, rest, {
|
||||
style: _extends({}, typeof newStyles === 'function' ? newStyles(rest, theme) : newStyles, style, mediaStyles),
|
||||
ref: ref
|
||||
}));
|
||||
});
|
||||
}
|
||||
export function useIsMounted() {
|
||||
var mountedRef = React.useRef(false);
|
||||
var isMounted = React.useCallback(function () {
|
||||
return mountedRef.current;
|
||||
}, []);
|
||||
React[isServer ? 'useEffect' : 'useLayoutEffect'](function () {
|
||||
mountedRef.current = true;
|
||||
return function () {
|
||||
mountedRef.current = false;
|
||||
};
|
||||
}, []);
|
||||
return isMounted;
|
||||
}
|
||||
/**
|
||||
* This hook is a safe useState version which schedules state updates in microtasks
|
||||
* to prevent updating a component state while React is rendering different components
|
||||
* or when the component is not mounted anymore.
|
||||
*/
|
||||
|
||||
export function useSafeState(initialState) {
|
||||
var isMounted = useIsMounted();
|
||||
|
||||
var _React$useState = React.useState(initialState),
|
||||
state = _React$useState[0],
|
||||
setState = _React$useState[1];
|
||||
|
||||
var safeSetState = React.useCallback(function (value) {
|
||||
scheduleMicrotask(function () {
|
||||
if (isMounted()) {
|
||||
setState(value);
|
||||
}
|
||||
});
|
||||
}, [isMounted]);
|
||||
return [state, safeSetState];
|
||||
}
|
||||
/**
|
||||
* Displays a string regardless the type of the data
|
||||
* @param {unknown} value Value to be stringified
|
||||
*/
|
||||
|
||||
export var displayValue = function displayValue(value) {
|
||||
var name = Object.getOwnPropertyNames(Object(value));
|
||||
var newValue = typeof value === 'bigint' ? value.toString() + "n" : value;
|
||||
return JSON.stringify(newValue, name);
|
||||
};
|
||||
/**
|
||||
* Schedules a microtask.
|
||||
* This can be useful to schedule state updates after rendering.
|
||||
*/
|
||||
|
||||
function scheduleMicrotask(callback) {
|
||||
Promise.resolve().then(callback).catch(function (error) {
|
||||
return setTimeout(function () {
|
||||
throw error;
|
||||
});
|
||||
});
|
||||
}
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
// This package once contained these functions, but they have now been moved
|
||||
// into the core and react packages.
|
||||
// They are re-exported here to avoid a breaking change, but this package
|
||||
// should be considered deprecated and removed in a future major version.
|
||||
export { dehydrate, hydrate, useHydrate, Hydrate } from 'react-query'; // Types
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
export * from './core';
|
||||
export * from './react';
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
import { getLogger } from '../core/logger';
|
||||
import { dehydrate, hydrate } from 'react-query';
|
||||
|
||||
function _await(value, then, direct) {
|
||||
if (direct) {
|
||||
return then ? then(value) : value;
|
||||
}
|
||||
|
||||
if (!value || !value.then) {
|
||||
value = Promise.resolve(value);
|
||||
}
|
||||
|
||||
return then ? value.then(then) : value;
|
||||
}
|
||||
|
||||
function _catch(body, recover) {
|
||||
try {
|
||||
var result = body();
|
||||
} catch (e) {
|
||||
return recover(e);
|
||||
}
|
||||
|
||||
if (result && result.then) {
|
||||
return result.then(void 0, recover);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function _continue(value, then) {
|
||||
return value && value.then ? value.then(then) : then(value);
|
||||
}
|
||||
|
||||
function _empty() {}
|
||||
|
||||
function _invokeIgnored(body) {
|
||||
var result = body();
|
||||
|
||||
if (result && result.then) {
|
||||
return result.then(_empty);
|
||||
}
|
||||
}
|
||||
|
||||
function _async(f) {
|
||||
return function () {
|
||||
for (var args = [], i = 0; i < arguments.length; i++) {
|
||||
args[i] = arguments[i];
|
||||
}
|
||||
|
||||
try {
|
||||
return Promise.resolve(f.apply(this, args));
|
||||
} catch (e) {
|
||||
return Promise.reject(e);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export var persistQueryClient = _async(function (_ref) {
|
||||
var queryClient = _ref.queryClient,
|
||||
persistor = _ref.persistor,
|
||||
_ref$maxAge = _ref.maxAge,
|
||||
maxAge = _ref$maxAge === void 0 ? 1000 * 60 * 60 * 24 : _ref$maxAge,
|
||||
_ref$buster = _ref.buster,
|
||||
buster = _ref$buster === void 0 ? '' : _ref$buster,
|
||||
hydrateOptions = _ref.hydrateOptions,
|
||||
dehydrateOptions = _ref.dehydrateOptions;
|
||||
return _invokeIgnored(function () {
|
||||
if (typeof window !== 'undefined') {
|
||||
// Subscribe to changes
|
||||
var saveClient = function saveClient() {
|
||||
var persistClient = {
|
||||
buster: buster,
|
||||
timestamp: Date.now(),
|
||||
clientState: dehydrate(queryClient, dehydrateOptions)
|
||||
};
|
||||
persistor.persistClient(persistClient);
|
||||
}; // Attempt restore
|
||||
|
||||
|
||||
return _continue(_catch(function () {
|
||||
return _await(persistor.restoreClient(), function (persistedClient) {
|
||||
if (persistedClient) {
|
||||
if (persistedClient.timestamp) {
|
||||
var expired = Date.now() - persistedClient.timestamp > maxAge;
|
||||
var busted = persistedClient.buster !== buster;
|
||||
|
||||
if (expired || busted) {
|
||||
persistor.removeClient();
|
||||
} else {
|
||||
hydrate(queryClient, persistedClient.clientState, hydrateOptions);
|
||||
}
|
||||
} else {
|
||||
persistor.removeClient();
|
||||
}
|
||||
}
|
||||
});
|
||||
}, function (err) {
|
||||
getLogger().error(err);
|
||||
getLogger().warn('Encountered an error attempting to restore client cache from persisted location. As a precaution, the persisted cache will be discarded.');
|
||||
persistor.removeClient();
|
||||
}), function () {
|
||||
// Subscribe to changes in the query cache to trigger the save
|
||||
queryClient.getQueryCache().subscribe(saveClient);
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
import React from 'react';
|
||||
import { hydrate } from '../core';
|
||||
import { useQueryClient } from './QueryClientProvider';
|
||||
export function useHydrate(state, options) {
|
||||
var queryClient = useQueryClient();
|
||||
var optionsRef = React.useRef(options);
|
||||
optionsRef.current = options; // Running hydrate again with the same queries is safe,
|
||||
// it wont overwrite or initialize existing queries,
|
||||
// relying on useMemo here is only a performance optimization.
|
||||
// hydrate can and should be run *during* render here for SSR to work properly
|
||||
|
||||
React.useMemo(function () {
|
||||
if (state) {
|
||||
hydrate(queryClient, state, optionsRef.current);
|
||||
}
|
||||
}, [queryClient, state]);
|
||||
}
|
||||
export var Hydrate = function Hydrate(_ref) {
|
||||
var children = _ref.children,
|
||||
options = _ref.options,
|
||||
state = _ref.state;
|
||||
useHydrate(state, options);
|
||||
return children;
|
||||
};
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
import React from 'react';
|
||||
var defaultContext = /*#__PURE__*/React.createContext(undefined);
|
||||
var QueryClientSharingContext = /*#__PURE__*/React.createContext(false); // if contextSharing is on, we share the first and at least one
|
||||
// instance of the context across the window
|
||||
// to ensure that if React Query is used across
|
||||
// different bundles or microfrontends they will
|
||||
// all use the same **instance** of context, regardless
|
||||
// of module scoping.
|
||||
|
||||
function getQueryClientContext(contextSharing) {
|
||||
if (contextSharing && typeof window !== 'undefined') {
|
||||
if (!window.ReactQueryClientContext) {
|
||||
window.ReactQueryClientContext = defaultContext;
|
||||
}
|
||||
|
||||
return window.ReactQueryClientContext;
|
||||
}
|
||||
|
||||
return defaultContext;
|
||||
}
|
||||
|
||||
export var useQueryClient = function useQueryClient() {
|
||||
var queryClient = React.useContext(getQueryClientContext(React.useContext(QueryClientSharingContext)));
|
||||
|
||||
if (!queryClient) {
|
||||
throw new Error('No QueryClient set, use QueryClientProvider to set one');
|
||||
}
|
||||
|
||||
return queryClient;
|
||||
};
|
||||
export var QueryClientProvider = function QueryClientProvider(_ref) {
|
||||
var client = _ref.client,
|
||||
_ref$contextSharing = _ref.contextSharing,
|
||||
contextSharing = _ref$contextSharing === void 0 ? false : _ref$contextSharing,
|
||||
children = _ref.children;
|
||||
React.useEffect(function () {
|
||||
client.mount();
|
||||
return function () {
|
||||
client.unmount();
|
||||
};
|
||||
}, [client]);
|
||||
var Context = getQueryClientContext(contextSharing);
|
||||
return /*#__PURE__*/React.createElement(QueryClientSharingContext.Provider, {
|
||||
value: contextSharing
|
||||
}, /*#__PURE__*/React.createElement(Context.Provider, {
|
||||
value: client
|
||||
}, children));
|
||||
};
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
import React from 'react'; // CONTEXT
|
||||
|
||||
function createValue() {
|
||||
var _isReset = false;
|
||||
return {
|
||||
clearReset: function clearReset() {
|
||||
_isReset = false;
|
||||
},
|
||||
reset: function reset() {
|
||||
_isReset = true;
|
||||
},
|
||||
isReset: function isReset() {
|
||||
return _isReset;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
var QueryErrorResetBoundaryContext = /*#__PURE__*/React.createContext(createValue()); // HOOK
|
||||
|
||||
export var useQueryErrorResetBoundary = function useQueryErrorResetBoundary() {
|
||||
return React.useContext(QueryErrorResetBoundaryContext);
|
||||
}; // COMPONENT
|
||||
|
||||
export var QueryErrorResetBoundary = function QueryErrorResetBoundary(_ref) {
|
||||
var children = _ref.children;
|
||||
var value = React.useMemo(function () {
|
||||
return createValue();
|
||||
}, []);
|
||||
return /*#__PURE__*/React.createElement(QueryErrorResetBoundaryContext.Provider, {
|
||||
value: value
|
||||
}, typeof children === 'function' ? children(value) : children);
|
||||
};
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
// Side effects
|
||||
import './setBatchUpdatesFn';
|
||||
import './setLogger';
|
||||
export { QueryClientProvider, useQueryClient } from './QueryClientProvider';
|
||||
export { QueryErrorResetBoundary, useQueryErrorResetBoundary } from './QueryErrorResetBoundary';
|
||||
export { useIsFetching } from './useIsFetching';
|
||||
export { useIsMutating } from './useIsMutating';
|
||||
export { useMutation } from './useMutation';
|
||||
export { useQuery } from './useQuery';
|
||||
export { useQueries } from './useQueries';
|
||||
export { useInfiniteQuery } from './useInfiniteQuery';
|
||||
export { useHydrate, Hydrate } from './Hydrate'; // Types
|
||||
|
||||
export * from './types';
|
||||
+1
@@ -0,0 +1 @@
|
||||
export var logger = console;
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
export var logger = {
|
||||
log: console.log,
|
||||
warn: console.warn,
|
||||
error: console.warn
|
||||
};
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
import ReactDOM from 'react-dom';
|
||||
export var unstable_batchedUpdates = ReactDOM.unstable_batchedUpdates;
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
// @ts-ignore
|
||||
// eslint-disable-next-line import/no-unresolved
|
||||
import { unstable_batchedUpdates } from 'react-native';
|
||||
export { unstable_batchedUpdates };
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
import { notifyManager } from '../core';
|
||||
import { unstable_batchedUpdates } from './reactBatchedUpdates';
|
||||
notifyManager.setBatchNotifyFunction(unstable_batchedUpdates);
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
import { setLogger } from '../core';
|
||||
import { logger } from './logger';
|
||||
setLogger(logger);
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
import React from 'react';
|
||||
import { notifyManager } from '../core/notifyManager';
|
||||
import { useQueryErrorResetBoundary } from './QueryErrorResetBoundary';
|
||||
import { useQueryClient } from './QueryClientProvider';
|
||||
import { shouldThrowError } from './utils';
|
||||
export function useBaseQuery(options, Observer) {
|
||||
var mountedRef = React.useRef(false);
|
||||
|
||||
var _React$useState = React.useState(0),
|
||||
forceUpdate = _React$useState[1];
|
||||
|
||||
var queryClient = useQueryClient();
|
||||
var errorResetBoundary = useQueryErrorResetBoundary();
|
||||
var defaultedOptions = queryClient.defaultQueryObserverOptions(options); // Make sure results are optimistically set in fetching state before subscribing or updating options
|
||||
|
||||
defaultedOptions.optimisticResults = true; // Include callbacks in batch renders
|
||||
|
||||
if (defaultedOptions.onError) {
|
||||
defaultedOptions.onError = notifyManager.batchCalls(defaultedOptions.onError);
|
||||
}
|
||||
|
||||
if (defaultedOptions.onSuccess) {
|
||||
defaultedOptions.onSuccess = notifyManager.batchCalls(defaultedOptions.onSuccess);
|
||||
}
|
||||
|
||||
if (defaultedOptions.onSettled) {
|
||||
defaultedOptions.onSettled = notifyManager.batchCalls(defaultedOptions.onSettled);
|
||||
}
|
||||
|
||||
if (defaultedOptions.suspense) {
|
||||
// Always set stale time when using suspense to prevent
|
||||
// fetching again when directly mounting after suspending
|
||||
if (typeof defaultedOptions.staleTime !== 'number') {
|
||||
defaultedOptions.staleTime = 1000;
|
||||
} // Set cache time to 1 if the option has been set to 0
|
||||
// when using suspense to prevent infinite loop of fetches
|
||||
|
||||
|
||||
if (defaultedOptions.cacheTime === 0) {
|
||||
defaultedOptions.cacheTime = 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (defaultedOptions.suspense || defaultedOptions.useErrorBoundary) {
|
||||
// Prevent retrying failed query if the error boundary has not been reset yet
|
||||
if (!errorResetBoundary.isReset()) {
|
||||
defaultedOptions.retryOnMount = false;
|
||||
}
|
||||
}
|
||||
|
||||
var _React$useState2 = React.useState(function () {
|
||||
return new Observer(queryClient, defaultedOptions);
|
||||
}),
|
||||
observer = _React$useState2[0];
|
||||
|
||||
var result = observer.getOptimisticResult(defaultedOptions);
|
||||
React.useEffect(function () {
|
||||
mountedRef.current = true;
|
||||
errorResetBoundary.clearReset();
|
||||
var unsubscribe = observer.subscribe(notifyManager.batchCalls(function () {
|
||||
if (mountedRef.current) {
|
||||
forceUpdate(function (x) {
|
||||
return x + 1;
|
||||
});
|
||||
}
|
||||
})); // Update result to make sure we did not miss any query updates
|
||||
// between creating the observer and subscribing to it.
|
||||
|
||||
observer.updateResult();
|
||||
return function () {
|
||||
mountedRef.current = false;
|
||||
unsubscribe();
|
||||
};
|
||||
}, [errorResetBoundary, observer]);
|
||||
React.useEffect(function () {
|
||||
// Do not notify on updates because of changes in the options because
|
||||
// these changes should already be reflected in the optimistic result.
|
||||
observer.setOptions(defaultedOptions, {
|
||||
listeners: false
|
||||
});
|
||||
}, [defaultedOptions, observer]); // Handle suspense
|
||||
|
||||
if (defaultedOptions.suspense && result.isLoading) {
|
||||
throw observer.fetchOptimistic(defaultedOptions).then(function (_ref) {
|
||||
var data = _ref.data;
|
||||
defaultedOptions.onSuccess == null ? void 0 : defaultedOptions.onSuccess(data);
|
||||
defaultedOptions.onSettled == null ? void 0 : defaultedOptions.onSettled(data, null);
|
||||
}).catch(function (error) {
|
||||
errorResetBoundary.clearReset();
|
||||
defaultedOptions.onError == null ? void 0 : defaultedOptions.onError(error);
|
||||
defaultedOptions.onSettled == null ? void 0 : defaultedOptions.onSettled(undefined, error);
|
||||
});
|
||||
} // Handle error boundary
|
||||
|
||||
|
||||
if (result.isError && !errorResetBoundary.isReset() && !result.isFetching && shouldThrowError(defaultedOptions.suspense, defaultedOptions.useErrorBoundary, [result.error, observer.getCurrentQuery()])) {
|
||||
throw result.error;
|
||||
} // Handle result property usage tracking
|
||||
|
||||
|
||||
if (defaultedOptions.notifyOnChangeProps === 'tracked') {
|
||||
result = observer.trackResult(result, defaultedOptions);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
import { InfiniteQueryObserver } from '../core/infiniteQueryObserver';
|
||||
import { parseQueryArgs } from '../core/utils';
|
||||
import { useBaseQuery } from './useBaseQuery'; // HOOK
|
||||
|
||||
export function useInfiniteQuery(arg1, arg2, arg3) {
|
||||
var options = parseQueryArgs(arg1, arg2, arg3);
|
||||
return useBaseQuery(options, InfiniteQueryObserver);
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
import React from 'react';
|
||||
import { notifyManager } from '../core/notifyManager';
|
||||
import { parseFilterArgs } from '../core/utils';
|
||||
import { useQueryClient } from './QueryClientProvider';
|
||||
|
||||
var checkIsFetching = function checkIsFetching(queryClient, filters, isFetching, setIsFetching) {
|
||||
var newIsFetching = queryClient.isFetching(filters);
|
||||
|
||||
if (isFetching !== newIsFetching) {
|
||||
setIsFetching(newIsFetching);
|
||||
}
|
||||
};
|
||||
|
||||
export function useIsFetching(arg1, arg2) {
|
||||
var mountedRef = React.useRef(false);
|
||||
var queryClient = useQueryClient();
|
||||
|
||||
var _parseFilterArgs = parseFilterArgs(arg1, arg2),
|
||||
filters = _parseFilterArgs[0];
|
||||
|
||||
var _React$useState = React.useState(queryClient.isFetching(filters)),
|
||||
isFetching = _React$useState[0],
|
||||
setIsFetching = _React$useState[1];
|
||||
|
||||
var filtersRef = React.useRef(filters);
|
||||
filtersRef.current = filters;
|
||||
var isFetchingRef = React.useRef(isFetching);
|
||||
isFetchingRef.current = isFetching;
|
||||
React.useEffect(function () {
|
||||
mountedRef.current = true;
|
||||
checkIsFetching(queryClient, filtersRef.current, isFetchingRef.current, setIsFetching);
|
||||
var unsubscribe = queryClient.getQueryCache().subscribe(notifyManager.batchCalls(function () {
|
||||
if (mountedRef.current) {
|
||||
checkIsFetching(queryClient, filtersRef.current, isFetchingRef.current, setIsFetching);
|
||||
}
|
||||
}));
|
||||
return function () {
|
||||
mountedRef.current = false;
|
||||
unsubscribe();
|
||||
};
|
||||
}, [queryClient]);
|
||||
return isFetching;
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
import React from 'react';
|
||||
import { notifyManager } from '../core/notifyManager';
|
||||
import { parseMutationFilterArgs } from '../core/utils';
|
||||
import { useQueryClient } from './QueryClientProvider';
|
||||
export function useIsMutating(arg1, arg2) {
|
||||
var mountedRef = React.useRef(false);
|
||||
var filters = parseMutationFilterArgs(arg1, arg2);
|
||||
var queryClient = useQueryClient();
|
||||
|
||||
var _React$useState = React.useState(queryClient.isMutating(filters)),
|
||||
isMutating = _React$useState[0],
|
||||
setIsMutating = _React$useState[1];
|
||||
|
||||
var filtersRef = React.useRef(filters);
|
||||
filtersRef.current = filters;
|
||||
var isMutatingRef = React.useRef(isMutating);
|
||||
isMutatingRef.current = isMutating;
|
||||
React.useEffect(function () {
|
||||
mountedRef.current = true;
|
||||
var unsubscribe = queryClient.getMutationCache().subscribe(notifyManager.batchCalls(function () {
|
||||
if (mountedRef.current) {
|
||||
var newIsMutating = queryClient.isMutating(filtersRef.current);
|
||||
|
||||
if (isMutatingRef.current !== newIsMutating) {
|
||||
setIsMutating(newIsMutating);
|
||||
}
|
||||
}
|
||||
}));
|
||||
return function () {
|
||||
mountedRef.current = false;
|
||||
unsubscribe();
|
||||
};
|
||||
}, [queryClient]);
|
||||
return isMutating;
|
||||
}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
import _extends from "@babel/runtime/helpers/esm/extends";
|
||||
import React from 'react';
|
||||
import { notifyManager } from '../core/notifyManager';
|
||||
import { noop, parseMutationArgs } from '../core/utils';
|
||||
import { MutationObserver } from '../core/mutationObserver';
|
||||
import { useQueryClient } from './QueryClientProvider';
|
||||
import { shouldThrowError } from './utils'; // HOOK
|
||||
|
||||
export function useMutation(arg1, arg2, arg3) {
|
||||
var mountedRef = React.useRef(false);
|
||||
|
||||
var _React$useState = React.useState(0),
|
||||
forceUpdate = _React$useState[1];
|
||||
|
||||
var options = parseMutationArgs(arg1, arg2, arg3);
|
||||
var queryClient = useQueryClient();
|
||||
var obsRef = React.useRef();
|
||||
|
||||
if (!obsRef.current) {
|
||||
obsRef.current = new MutationObserver(queryClient, options);
|
||||
} else {
|
||||
obsRef.current.setOptions(options);
|
||||
}
|
||||
|
||||
var currentResult = obsRef.current.getCurrentResult();
|
||||
React.useEffect(function () {
|
||||
mountedRef.current = true;
|
||||
var unsubscribe = obsRef.current.subscribe(notifyManager.batchCalls(function () {
|
||||
if (mountedRef.current) {
|
||||
forceUpdate(function (x) {
|
||||
return x + 1;
|
||||
});
|
||||
}
|
||||
}));
|
||||
return function () {
|
||||
mountedRef.current = false;
|
||||
unsubscribe();
|
||||
};
|
||||
}, []);
|
||||
var mutate = React.useCallback(function (variables, mutateOptions) {
|
||||
obsRef.current.mutate(variables, mutateOptions).catch(noop);
|
||||
}, []);
|
||||
|
||||
if (currentResult.error && shouldThrowError(undefined, obsRef.current.options.useErrorBoundary, [currentResult.error])) {
|
||||
throw currentResult.error;
|
||||
}
|
||||
|
||||
return _extends({}, currentResult, {
|
||||
mutate: mutate,
|
||||
mutateAsync: currentResult.mutate
|
||||
});
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
import React, { useMemo } from 'react';
|
||||
import { notifyManager } from '../core/notifyManager';
|
||||
import { QueriesObserver } from '../core/queriesObserver';
|
||||
import { useQueryClient } from './QueryClientProvider';
|
||||
export function useQueries(queries) {
|
||||
var mountedRef = React.useRef(false);
|
||||
|
||||
var _React$useState = React.useState(0),
|
||||
forceUpdate = _React$useState[1];
|
||||
|
||||
var queryClient = useQueryClient();
|
||||
var defaultedQueries = useMemo(function () {
|
||||
return queries.map(function (options) {
|
||||
var defaultedOptions = queryClient.defaultQueryObserverOptions(options); // Make sure the results are already in fetching state before subscribing or updating options
|
||||
|
||||
defaultedOptions.optimisticResults = true;
|
||||
return defaultedOptions;
|
||||
});
|
||||
}, [queries, queryClient]);
|
||||
|
||||
var _React$useState2 = React.useState(function () {
|
||||
return new QueriesObserver(queryClient, defaultedQueries);
|
||||
}),
|
||||
observer = _React$useState2[0];
|
||||
|
||||
var result = observer.getOptimisticResult(defaultedQueries);
|
||||
React.useEffect(function () {
|
||||
mountedRef.current = true;
|
||||
var unsubscribe = observer.subscribe(notifyManager.batchCalls(function () {
|
||||
if (mountedRef.current) {
|
||||
forceUpdate(function (x) {
|
||||
return x + 1;
|
||||
});
|
||||
}
|
||||
}));
|
||||
return function () {
|
||||
mountedRef.current = false;
|
||||
unsubscribe();
|
||||
};
|
||||
}, [observer]);
|
||||
React.useEffect(function () {
|
||||
// Do not notify on updates because of changes in the options because
|
||||
// these changes should already be reflected in the optimistic result.
|
||||
observer.setQueries(defaultedQueries, {
|
||||
listeners: false
|
||||
});
|
||||
}, [defaultedQueries, observer]);
|
||||
return result;
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
import { QueryObserver } from '../core';
|
||||
import { parseQueryArgs } from '../core/utils';
|
||||
import { useBaseQuery } from './useBaseQuery'; // HOOK
|
||||
|
||||
export function useQuery(arg1, arg2, arg3) {
|
||||
var parsedOptions = parseQueryArgs(arg1, arg2, arg3);
|
||||
return useBaseQuery(parsedOptions, QueryObserver);
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
export function shouldThrowError(suspense, _useErrorBoundary, params) {
|
||||
// Allow useErrorBoundary function to override throwing behavior on a per-error basis
|
||||
if (typeof _useErrorBoundary === 'function') {
|
||||
return _useErrorBoundary.apply(void 0, params);
|
||||
} // Allow useErrorBoundary to override suspense's throwing behavior
|
||||
|
||||
|
||||
if (typeof _useErrorBoundary === 'boolean') return _useErrorBoundary; // If suspense is enabled default to throwing errors
|
||||
|
||||
return !!suspense;
|
||||
}
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
import { useQueries } from './useQueries';
|
||||
export { useQueries };
|
||||
export * from '..';
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"internal": true,
|
||||
"main": "../lib/hydration/index.js",
|
||||
"module": "../es/hydration/index.js",
|
||||
"types": "../types/hydration/index.d.ts"
|
||||
}
|
||||
Generated
Vendored
+86
@@ -0,0 +1,86 @@
|
||||
"use strict";
|
||||
|
||||
exports.__esModule = true;
|
||||
exports.broadcastQueryClient = broadcastQueryClient;
|
||||
|
||||
var _broadcastChannel = require("broadcast-channel");
|
||||
|
||||
function broadcastQueryClient(_ref) {
|
||||
var queryClient = _ref.queryClient,
|
||||
_ref$broadcastChannel = _ref.broadcastChannel,
|
||||
broadcastChannel = _ref$broadcastChannel === void 0 ? 'react-query' : _ref$broadcastChannel;
|
||||
var transaction = false;
|
||||
|
||||
var tx = function tx(cb) {
|
||||
transaction = true;
|
||||
cb();
|
||||
transaction = false;
|
||||
};
|
||||
|
||||
var channel = new _broadcastChannel.BroadcastChannel(broadcastChannel, {
|
||||
webWorkerSupport: false
|
||||
});
|
||||
var queryCache = queryClient.getQueryCache();
|
||||
queryClient.getQueryCache().subscribe(function (queryEvent) {
|
||||
var _queryEvent$action;
|
||||
|
||||
if (transaction || !(queryEvent == null ? void 0 : queryEvent.query)) {
|
||||
return;
|
||||
}
|
||||
|
||||
var _queryEvent$query = queryEvent.query,
|
||||
queryHash = _queryEvent$query.queryHash,
|
||||
queryKey = _queryEvent$query.queryKey,
|
||||
state = _queryEvent$query.state;
|
||||
|
||||
if (queryEvent.type === 'queryUpdated' && ((_queryEvent$action = queryEvent.action) == null ? void 0 : _queryEvent$action.type) === 'success') {
|
||||
channel.postMessage({
|
||||
type: 'queryUpdated',
|
||||
queryHash: queryHash,
|
||||
queryKey: queryKey,
|
||||
state: state
|
||||
});
|
||||
}
|
||||
|
||||
if (queryEvent.type === 'queryRemoved') {
|
||||
channel.postMessage({
|
||||
type: 'queryRemoved',
|
||||
queryHash: queryHash,
|
||||
queryKey: queryKey
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
channel.onmessage = function (action) {
|
||||
if (!(action == null ? void 0 : action.type)) {
|
||||
return;
|
||||
}
|
||||
|
||||
tx(function () {
|
||||
var type = action.type,
|
||||
queryHash = action.queryHash,
|
||||
queryKey = action.queryKey,
|
||||
state = action.state;
|
||||
|
||||
if (type === 'queryUpdated') {
|
||||
var query = queryCache.get(queryHash);
|
||||
|
||||
if (query) {
|
||||
query.setState(state);
|
||||
return;
|
||||
}
|
||||
|
||||
queryCache.build(queryClient, {
|
||||
queryKey: queryKey,
|
||||
queryHash: queryHash
|
||||
}, state);
|
||||
} else if (type === 'queryRemoved') {
|
||||
var _query = queryCache.get(queryHash);
|
||||
|
||||
if (_query) {
|
||||
queryCache.remove(_query);
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
}
|
||||
+108
@@ -0,0 +1,108 @@
|
||||
"use strict";
|
||||
|
||||
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
|
||||
|
||||
exports.__esModule = true;
|
||||
exports.focusManager = exports.FocusManager = void 0;
|
||||
|
||||
var _inheritsLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/inheritsLoose"));
|
||||
|
||||
var _subscribable = require("./subscribable");
|
||||
|
||||
var _utils = require("./utils");
|
||||
|
||||
var FocusManager = /*#__PURE__*/function (_Subscribable) {
|
||||
(0, _inheritsLoose2.default)(FocusManager, _Subscribable);
|
||||
|
||||
function FocusManager() {
|
||||
var _this;
|
||||
|
||||
_this = _Subscribable.call(this) || this;
|
||||
|
||||
_this.setup = function (onFocus) {
|
||||
var _window;
|
||||
|
||||
if (!_utils.isServer && ((_window = window) == null ? void 0 : _window.addEventListener)) {
|
||||
var listener = function listener() {
|
||||
return onFocus();
|
||||
}; // Listen to visibillitychange and focus
|
||||
|
||||
|
||||
window.addEventListener('visibilitychange', listener, false);
|
||||
window.addEventListener('focus', listener, false);
|
||||
return function () {
|
||||
// Be sure to unsubscribe if a new handler is set
|
||||
window.removeEventListener('visibilitychange', listener);
|
||||
window.removeEventListener('focus', listener);
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
return _this;
|
||||
}
|
||||
|
||||
var _proto = FocusManager.prototype;
|
||||
|
||||
_proto.onSubscribe = function onSubscribe() {
|
||||
if (!this.cleanup) {
|
||||
this.setEventListener(this.setup);
|
||||
}
|
||||
};
|
||||
|
||||
_proto.onUnsubscribe = function onUnsubscribe() {
|
||||
if (!this.hasListeners()) {
|
||||
var _this$cleanup;
|
||||
|
||||
(_this$cleanup = this.cleanup) == null ? void 0 : _this$cleanup.call(this);
|
||||
this.cleanup = undefined;
|
||||
}
|
||||
};
|
||||
|
||||
_proto.setEventListener = function setEventListener(setup) {
|
||||
var _this$cleanup2,
|
||||
_this2 = this;
|
||||
|
||||
this.setup = setup;
|
||||
(_this$cleanup2 = this.cleanup) == null ? void 0 : _this$cleanup2.call(this);
|
||||
this.cleanup = setup(function (focused) {
|
||||
if (typeof focused === 'boolean') {
|
||||
_this2.setFocused(focused);
|
||||
} else {
|
||||
_this2.onFocus();
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
_proto.setFocused = function setFocused(focused) {
|
||||
this.focused = focused;
|
||||
|
||||
if (focused) {
|
||||
this.onFocus();
|
||||
}
|
||||
};
|
||||
|
||||
_proto.onFocus = function onFocus() {
|
||||
this.listeners.forEach(function (listener) {
|
||||
listener();
|
||||
});
|
||||
};
|
||||
|
||||
_proto.isFocused = function isFocused() {
|
||||
if (typeof this.focused === 'boolean') {
|
||||
return this.focused;
|
||||
} // document global can be unavailable in react native
|
||||
|
||||
|
||||
if (typeof document === 'undefined') {
|
||||
return true;
|
||||
}
|
||||
|
||||
return [undefined, 'visible', 'prerender'].includes(document.visibilityState);
|
||||
};
|
||||
|
||||
return FocusManager;
|
||||
}(_subscribable.Subscribable);
|
||||
|
||||
exports.FocusManager = FocusManager;
|
||||
var focusManager = new FocusManager();
|
||||
exports.focusManager = focusManager;
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
"use strict";
|
||||
|
||||
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
|
||||
|
||||
exports.__esModule = true;
|
||||
exports.dehydrate = dehydrate;
|
||||
exports.hydrate = hydrate;
|
||||
|
||||
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
|
||||
|
||||
// TYPES
|
||||
// FUNCTIONS
|
||||
function dehydrateMutation(mutation) {
|
||||
return {
|
||||
mutationKey: mutation.options.mutationKey,
|
||||
state: mutation.state
|
||||
};
|
||||
} // Most config is not dehydrated but instead meant to configure again when
|
||||
// consuming the de/rehydrated data, typically with useQuery on the client.
|
||||
// Sometimes it might make sense to prefetch data on the server and include
|
||||
// in the html-payload, but not consume it on the initial render.
|
||||
|
||||
|
||||
function dehydrateQuery(query) {
|
||||
return {
|
||||
state: query.state,
|
||||
queryKey: query.queryKey,
|
||||
queryHash: query.queryHash
|
||||
};
|
||||
}
|
||||
|
||||
function defaultShouldDehydrateMutation(mutation) {
|
||||
return mutation.state.isPaused;
|
||||
}
|
||||
|
||||
function defaultShouldDehydrateQuery(query) {
|
||||
return query.state.status === 'success';
|
||||
}
|
||||
|
||||
function dehydrate(client, options) {
|
||||
var _options, _options2;
|
||||
|
||||
options = options || {};
|
||||
var mutations = [];
|
||||
var queries = [];
|
||||
|
||||
if (((_options = options) == null ? void 0 : _options.dehydrateMutations) !== false) {
|
||||
var shouldDehydrateMutation = options.shouldDehydrateMutation || defaultShouldDehydrateMutation;
|
||||
client.getMutationCache().getAll().forEach(function (mutation) {
|
||||
if (shouldDehydrateMutation(mutation)) {
|
||||
mutations.push(dehydrateMutation(mutation));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (((_options2 = options) == null ? void 0 : _options2.dehydrateQueries) !== false) {
|
||||
var shouldDehydrateQuery = options.shouldDehydrateQuery || defaultShouldDehydrateQuery;
|
||||
client.getQueryCache().getAll().forEach(function (query) {
|
||||
if (shouldDehydrateQuery(query)) {
|
||||
queries.push(dehydrateQuery(query));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
mutations: mutations,
|
||||
queries: queries
|
||||
};
|
||||
}
|
||||
|
||||
function hydrate(client, dehydratedState, options) {
|
||||
if (typeof dehydratedState !== 'object' || dehydratedState === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
var mutationCache = client.getMutationCache();
|
||||
var queryCache = client.getQueryCache();
|
||||
var mutations = dehydratedState.mutations || [];
|
||||
var queries = dehydratedState.queries || [];
|
||||
mutations.forEach(function (dehydratedMutation) {
|
||||
var _options$defaultOptio;
|
||||
|
||||
mutationCache.build(client, (0, _extends2.default)({}, options == null ? void 0 : (_options$defaultOptio = options.defaultOptions) == null ? void 0 : _options$defaultOptio.mutations, {
|
||||
mutationKey: dehydratedMutation.mutationKey
|
||||
}), dehydratedMutation.state);
|
||||
});
|
||||
queries.forEach(function (dehydratedQuery) {
|
||||
var _options$defaultOptio2;
|
||||
|
||||
var query = queryCache.get(dehydratedQuery.queryHash); // Do not hydrate if an existing query exists with newer data
|
||||
|
||||
if (query) {
|
||||
if (query.state.dataUpdatedAt < dehydratedQuery.state.dataUpdatedAt) {
|
||||
query.setState(dehydratedQuery.state);
|
||||
}
|
||||
|
||||
return;
|
||||
} // Restore query
|
||||
|
||||
|
||||
queryCache.build(client, (0, _extends2.default)({}, options == null ? void 0 : (_options$defaultOptio2 = options.defaultOptions) == null ? void 0 : _options$defaultOptio2.queries, {
|
||||
queryKey: dehydratedQuery.queryKey,
|
||||
queryHash: dehydratedQuery.queryHash
|
||||
}), dehydratedQuery.state);
|
||||
});
|
||||
}
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
"use strict";
|
||||
|
||||
exports.__esModule = true;
|
||||
var _exportNames = {
|
||||
CancelledError: true,
|
||||
QueryCache: true,
|
||||
QueryClient: true,
|
||||
QueryObserver: true,
|
||||
QueriesObserver: true,
|
||||
InfiniteQueryObserver: true,
|
||||
MutationCache: true,
|
||||
MutationObserver: true,
|
||||
setLogger: true,
|
||||
notifyManager: true,
|
||||
focusManager: true,
|
||||
onlineManager: true,
|
||||
hashQueryKey: true,
|
||||
isError: true,
|
||||
isCancelledError: true,
|
||||
dehydrate: true,
|
||||
hydrate: true
|
||||
};
|
||||
exports.hydrate = exports.dehydrate = exports.isCancelledError = exports.isError = exports.hashQueryKey = exports.onlineManager = exports.focusManager = exports.notifyManager = exports.setLogger = exports.MutationObserver = exports.MutationCache = exports.InfiniteQueryObserver = exports.QueriesObserver = exports.QueryObserver = exports.QueryClient = exports.QueryCache = exports.CancelledError = void 0;
|
||||
|
||||
var _retryer = require("./retryer");
|
||||
|
||||
exports.CancelledError = _retryer.CancelledError;
|
||||
exports.isCancelledError = _retryer.isCancelledError;
|
||||
|
||||
var _queryCache = require("./queryCache");
|
||||
|
||||
exports.QueryCache = _queryCache.QueryCache;
|
||||
|
||||
var _queryClient = require("./queryClient");
|
||||
|
||||
exports.QueryClient = _queryClient.QueryClient;
|
||||
|
||||
var _queryObserver = require("./queryObserver");
|
||||
|
||||
exports.QueryObserver = _queryObserver.QueryObserver;
|
||||
|
||||
var _queriesObserver = require("./queriesObserver");
|
||||
|
||||
exports.QueriesObserver = _queriesObserver.QueriesObserver;
|
||||
|
||||
var _infiniteQueryObserver = require("./infiniteQueryObserver");
|
||||
|
||||
exports.InfiniteQueryObserver = _infiniteQueryObserver.InfiniteQueryObserver;
|
||||
|
||||
var _mutationCache = require("./mutationCache");
|
||||
|
||||
exports.MutationCache = _mutationCache.MutationCache;
|
||||
|
||||
var _mutationObserver = require("./mutationObserver");
|
||||
|
||||
exports.MutationObserver = _mutationObserver.MutationObserver;
|
||||
|
||||
var _logger = require("./logger");
|
||||
|
||||
exports.setLogger = _logger.setLogger;
|
||||
|
||||
var _notifyManager = require("./notifyManager");
|
||||
|
||||
exports.notifyManager = _notifyManager.notifyManager;
|
||||
|
||||
var _focusManager = require("./focusManager");
|
||||
|
||||
exports.focusManager = _focusManager.focusManager;
|
||||
|
||||
var _onlineManager = require("./onlineManager");
|
||||
|
||||
exports.onlineManager = _onlineManager.onlineManager;
|
||||
|
||||
var _utils = require("./utils");
|
||||
|
||||
exports.hashQueryKey = _utils.hashQueryKey;
|
||||
exports.isError = _utils.isError;
|
||||
|
||||
var _hydration = require("./hydration");
|
||||
|
||||
exports.dehydrate = _hydration.dehydrate;
|
||||
exports.hydrate = _hydration.hydrate;
|
||||
|
||||
var _types = require("./types");
|
||||
|
||||
Object.keys(_types).forEach(function (key) {
|
||||
if (key === "default" || key === "__esModule") return;
|
||||
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
|
||||
exports[key] = _types[key];
|
||||
});
|
||||
+168
@@ -0,0 +1,168 @@
|
||||
"use strict";
|
||||
|
||||
exports.__esModule = true;
|
||||
exports.infiniteQueryBehavior = infiniteQueryBehavior;
|
||||
exports.getNextPageParam = getNextPageParam;
|
||||
exports.getPreviousPageParam = getPreviousPageParam;
|
||||
exports.hasNextPage = hasNextPage;
|
||||
exports.hasPreviousPage = hasPreviousPage;
|
||||
|
||||
var _retryer = require("./retryer");
|
||||
|
||||
var _utils = require("./utils");
|
||||
|
||||
function infiniteQueryBehavior() {
|
||||
return {
|
||||
onFetch: function onFetch(context) {
|
||||
context.fetchFn = function () {
|
||||
var _context$fetchOptions, _context$fetchOptions2, _context$fetchOptions3, _context$fetchOptions4, _context$state$data, _context$state$data2;
|
||||
|
||||
var refetchPage = (_context$fetchOptions = context.fetchOptions) == null ? void 0 : (_context$fetchOptions2 = _context$fetchOptions.meta) == null ? void 0 : _context$fetchOptions2.refetchPage;
|
||||
var fetchMore = (_context$fetchOptions3 = context.fetchOptions) == null ? void 0 : (_context$fetchOptions4 = _context$fetchOptions3.meta) == null ? void 0 : _context$fetchOptions4.fetchMore;
|
||||
var pageParam = fetchMore == null ? void 0 : fetchMore.pageParam;
|
||||
var isFetchingNextPage = (fetchMore == null ? void 0 : fetchMore.direction) === 'forward';
|
||||
var isFetchingPreviousPage = (fetchMore == null ? void 0 : fetchMore.direction) === 'backward';
|
||||
var oldPages = ((_context$state$data = context.state.data) == null ? void 0 : _context$state$data.pages) || [];
|
||||
var oldPageParams = ((_context$state$data2 = context.state.data) == null ? void 0 : _context$state$data2.pageParams) || [];
|
||||
var abortController = (0, _utils.getAbortController)();
|
||||
var abortSignal = abortController == null ? void 0 : abortController.signal;
|
||||
var newPageParams = oldPageParams;
|
||||
var cancelled = false; // Get query function
|
||||
|
||||
var queryFn = context.options.queryFn || function () {
|
||||
return Promise.reject('Missing queryFn');
|
||||
};
|
||||
|
||||
var buildNewPages = function buildNewPages(pages, param, page, previous) {
|
||||
newPageParams = previous ? [param].concat(newPageParams) : [].concat(newPageParams, [param]);
|
||||
return previous ? [page].concat(pages) : [].concat(pages, [page]);
|
||||
}; // Create function to fetch a page
|
||||
|
||||
|
||||
var fetchPage = function fetchPage(pages, manual, param, previous) {
|
||||
if (cancelled) {
|
||||
return Promise.reject('Cancelled');
|
||||
}
|
||||
|
||||
if (typeof param === 'undefined' && !manual && pages.length) {
|
||||
return Promise.resolve(pages);
|
||||
}
|
||||
|
||||
var queryFnContext = {
|
||||
queryKey: context.queryKey,
|
||||
signal: abortSignal,
|
||||
pageParam: param,
|
||||
meta: context.meta
|
||||
};
|
||||
var queryFnResult = queryFn(queryFnContext);
|
||||
var promise = Promise.resolve(queryFnResult).then(function (page) {
|
||||
return buildNewPages(pages, param, page, previous);
|
||||
});
|
||||
|
||||
if ((0, _retryer.isCancelable)(queryFnResult)) {
|
||||
var promiseAsAny = promise;
|
||||
promiseAsAny.cancel = queryFnResult.cancel;
|
||||
}
|
||||
|
||||
return promise;
|
||||
};
|
||||
|
||||
var promise; // Fetch first page?
|
||||
|
||||
if (!oldPages.length) {
|
||||
promise = fetchPage([]);
|
||||
} // Fetch next page?
|
||||
else if (isFetchingNextPage) {
|
||||
var manual = typeof pageParam !== 'undefined';
|
||||
var param = manual ? pageParam : getNextPageParam(context.options, oldPages);
|
||||
promise = fetchPage(oldPages, manual, param);
|
||||
} // Fetch previous page?
|
||||
else if (isFetchingPreviousPage) {
|
||||
var _manual = typeof pageParam !== 'undefined';
|
||||
|
||||
var _param = _manual ? pageParam : getPreviousPageParam(context.options, oldPages);
|
||||
|
||||
promise = fetchPage(oldPages, _manual, _param, true);
|
||||
} // Refetch pages
|
||||
else {
|
||||
(function () {
|
||||
newPageParams = [];
|
||||
var manual = typeof context.options.getNextPageParam === 'undefined';
|
||||
var shouldFetchFirstPage = refetchPage && oldPages[0] ? refetchPage(oldPages[0], 0, oldPages) : true; // Fetch first page
|
||||
|
||||
promise = shouldFetchFirstPage ? fetchPage([], manual, oldPageParams[0]) : Promise.resolve(buildNewPages([], oldPageParams[0], oldPages[0])); // Fetch remaining pages
|
||||
|
||||
var _loop = function _loop(i) {
|
||||
promise = promise.then(function (pages) {
|
||||
var shouldFetchNextPage = refetchPage && oldPages[i] ? refetchPage(oldPages[i], i, oldPages) : true;
|
||||
|
||||
if (shouldFetchNextPage) {
|
||||
var _param2 = manual ? oldPageParams[i] : getNextPageParam(context.options, pages);
|
||||
|
||||
return fetchPage(pages, manual, _param2);
|
||||
}
|
||||
|
||||
return Promise.resolve(buildNewPages(pages, oldPageParams[i], oldPages[i]));
|
||||
});
|
||||
};
|
||||
|
||||
for (var i = 1; i < oldPages.length; i++) {
|
||||
_loop(i);
|
||||
}
|
||||
})();
|
||||
}
|
||||
|
||||
var finalPromise = promise.then(function (pages) {
|
||||
return {
|
||||
pages: pages,
|
||||
pageParams: newPageParams
|
||||
};
|
||||
});
|
||||
var finalPromiseAsAny = finalPromise;
|
||||
|
||||
finalPromiseAsAny.cancel = function () {
|
||||
cancelled = true;
|
||||
abortController == null ? void 0 : abortController.abort();
|
||||
|
||||
if ((0, _retryer.isCancelable)(promise)) {
|
||||
promise.cancel();
|
||||
}
|
||||
};
|
||||
|
||||
return finalPromise;
|
||||
};
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function getNextPageParam(options, pages) {
|
||||
return options.getNextPageParam == null ? void 0 : options.getNextPageParam(pages[pages.length - 1], pages);
|
||||
}
|
||||
|
||||
function getPreviousPageParam(options, pages) {
|
||||
return options.getPreviousPageParam == null ? void 0 : options.getPreviousPageParam(pages[0], pages);
|
||||
}
|
||||
/**
|
||||
* Checks if there is a next page.
|
||||
* Returns `undefined` if it cannot be determined.
|
||||
*/
|
||||
|
||||
|
||||
function hasNextPage(options, pages) {
|
||||
if (options.getNextPageParam && Array.isArray(pages)) {
|
||||
var nextPageParam = getNextPageParam(options, pages);
|
||||
return typeof nextPageParam !== 'undefined' && nextPageParam !== null && nextPageParam !== false;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Checks if there is a previous page.
|
||||
* Returns `undefined` if it cannot be determined.
|
||||
*/
|
||||
|
||||
|
||||
function hasPreviousPage(options, pages) {
|
||||
if (options.getPreviousPageParam && Array.isArray(pages)) {
|
||||
var previousPageParam = getPreviousPageParam(options, pages);
|
||||
return typeof previousPageParam !== 'undefined' && previousPageParam !== null && previousPageParam !== false;
|
||||
}
|
||||
}
|
||||
+99
@@ -0,0 +1,99 @@
|
||||
"use strict";
|
||||
|
||||
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
|
||||
|
||||
exports.__esModule = true;
|
||||
exports.InfiniteQueryObserver = void 0;
|
||||
|
||||
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
|
||||
|
||||
var _inheritsLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/inheritsLoose"));
|
||||
|
||||
var _queryObserver = require("./queryObserver");
|
||||
|
||||
var _infiniteQueryBehavior = require("./infiniteQueryBehavior");
|
||||
|
||||
var InfiniteQueryObserver = /*#__PURE__*/function (_QueryObserver) {
|
||||
(0, _inheritsLoose2.default)(InfiniteQueryObserver, _QueryObserver);
|
||||
|
||||
// Type override
|
||||
// Type override
|
||||
// Type override
|
||||
// eslint-disable-next-line @typescript-eslint/no-useless-constructor
|
||||
function InfiniteQueryObserver(client, options) {
|
||||
return _QueryObserver.call(this, client, options) || this;
|
||||
}
|
||||
|
||||
var _proto = InfiniteQueryObserver.prototype;
|
||||
|
||||
_proto.bindMethods = function bindMethods() {
|
||||
_QueryObserver.prototype.bindMethods.call(this);
|
||||
|
||||
this.fetchNextPage = this.fetchNextPage.bind(this);
|
||||
this.fetchPreviousPage = this.fetchPreviousPage.bind(this);
|
||||
};
|
||||
|
||||
_proto.setOptions = function setOptions(options, notifyOptions) {
|
||||
_QueryObserver.prototype.setOptions.call(this, (0, _extends2.default)({}, options, {
|
||||
behavior: (0, _infiniteQueryBehavior.infiniteQueryBehavior)()
|
||||
}), notifyOptions);
|
||||
};
|
||||
|
||||
_proto.getOptimisticResult = function getOptimisticResult(options) {
|
||||
options.behavior = (0, _infiniteQueryBehavior.infiniteQueryBehavior)();
|
||||
return _QueryObserver.prototype.getOptimisticResult.call(this, options);
|
||||
};
|
||||
|
||||
_proto.fetchNextPage = function fetchNextPage(options) {
|
||||
var _options$cancelRefetc;
|
||||
|
||||
return this.fetch({
|
||||
// TODO consider removing `?? true` in future breaking change, to be consistent with `refetch` API (see https://github.com/tannerlinsley/react-query/issues/2617)
|
||||
cancelRefetch: (_options$cancelRefetc = options == null ? void 0 : options.cancelRefetch) != null ? _options$cancelRefetc : true,
|
||||
throwOnError: options == null ? void 0 : options.throwOnError,
|
||||
meta: {
|
||||
fetchMore: {
|
||||
direction: 'forward',
|
||||
pageParam: options == null ? void 0 : options.pageParam
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
_proto.fetchPreviousPage = function fetchPreviousPage(options) {
|
||||
var _options$cancelRefetc2;
|
||||
|
||||
return this.fetch({
|
||||
// TODO consider removing `?? true` in future breaking change, to be consistent with `refetch` API (see https://github.com/tannerlinsley/react-query/issues/2617)
|
||||
cancelRefetch: (_options$cancelRefetc2 = options == null ? void 0 : options.cancelRefetch) != null ? _options$cancelRefetc2 : true,
|
||||
throwOnError: options == null ? void 0 : options.throwOnError,
|
||||
meta: {
|
||||
fetchMore: {
|
||||
direction: 'backward',
|
||||
pageParam: options == null ? void 0 : options.pageParam
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
_proto.createResult = function createResult(query, options) {
|
||||
var _state$data, _state$data2, _state$fetchMeta, _state$fetchMeta$fetc, _state$fetchMeta2, _state$fetchMeta2$fet;
|
||||
|
||||
var state = query.state;
|
||||
|
||||
var result = _QueryObserver.prototype.createResult.call(this, query, options);
|
||||
|
||||
return (0, _extends2.default)({}, result, {
|
||||
fetchNextPage: this.fetchNextPage,
|
||||
fetchPreviousPage: this.fetchPreviousPage,
|
||||
hasNextPage: (0, _infiniteQueryBehavior.hasNextPage)(options, (_state$data = state.data) == null ? void 0 : _state$data.pages),
|
||||
hasPreviousPage: (0, _infiniteQueryBehavior.hasPreviousPage)(options, (_state$data2 = state.data) == null ? void 0 : _state$data2.pages),
|
||||
isFetchingNextPage: state.isFetching && ((_state$fetchMeta = state.fetchMeta) == null ? void 0 : (_state$fetchMeta$fetc = _state$fetchMeta.fetchMore) == null ? void 0 : _state$fetchMeta$fetc.direction) === 'forward',
|
||||
isFetchingPreviousPage: state.isFetching && ((_state$fetchMeta2 = state.fetchMeta) == null ? void 0 : (_state$fetchMeta2$fet = _state$fetchMeta2.fetchMore) == null ? void 0 : _state$fetchMeta2$fet.direction) === 'backward'
|
||||
});
|
||||
};
|
||||
|
||||
return InfiniteQueryObserver;
|
||||
}(_queryObserver.QueryObserver);
|
||||
|
||||
exports.InfiniteQueryObserver = InfiniteQueryObserver;
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
"use strict";
|
||||
|
||||
exports.__esModule = true;
|
||||
exports.getLogger = getLogger;
|
||||
exports.setLogger = setLogger;
|
||||
// TYPES
|
||||
// FUNCTIONS
|
||||
var logger = console;
|
||||
|
||||
function getLogger() {
|
||||
return logger;
|
||||
}
|
||||
|
||||
function setLogger(newLogger) {
|
||||
logger = newLogger;
|
||||
}
|
||||
+248
@@ -0,0 +1,248 @@
|
||||
"use strict";
|
||||
|
||||
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
|
||||
|
||||
exports.__esModule = true;
|
||||
exports.getDefaultState = getDefaultState;
|
||||
exports.Mutation = void 0;
|
||||
|
||||
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
|
||||
|
||||
var _logger = require("./logger");
|
||||
|
||||
var _notifyManager = require("./notifyManager");
|
||||
|
||||
var _retryer = require("./retryer");
|
||||
|
||||
var _utils = require("./utils");
|
||||
|
||||
// CLASS
|
||||
var Mutation = /*#__PURE__*/function () {
|
||||
function Mutation(config) {
|
||||
this.options = (0, _extends2.default)({}, config.defaultOptions, config.options);
|
||||
this.mutationId = config.mutationId;
|
||||
this.mutationCache = config.mutationCache;
|
||||
this.observers = [];
|
||||
this.state = config.state || getDefaultState();
|
||||
this.meta = config.meta;
|
||||
}
|
||||
|
||||
var _proto = Mutation.prototype;
|
||||
|
||||
_proto.setState = function setState(state) {
|
||||
this.dispatch({
|
||||
type: 'setState',
|
||||
state: state
|
||||
});
|
||||
};
|
||||
|
||||
_proto.addObserver = function addObserver(observer) {
|
||||
if (this.observers.indexOf(observer) === -1) {
|
||||
this.observers.push(observer);
|
||||
}
|
||||
};
|
||||
|
||||
_proto.removeObserver = function removeObserver(observer) {
|
||||
this.observers = this.observers.filter(function (x) {
|
||||
return x !== observer;
|
||||
});
|
||||
};
|
||||
|
||||
_proto.cancel = function cancel() {
|
||||
if (this.retryer) {
|
||||
this.retryer.cancel();
|
||||
return this.retryer.promise.then(_utils.noop).catch(_utils.noop);
|
||||
}
|
||||
|
||||
return Promise.resolve();
|
||||
};
|
||||
|
||||
_proto.continue = function _continue() {
|
||||
if (this.retryer) {
|
||||
this.retryer.continue();
|
||||
return this.retryer.promise;
|
||||
}
|
||||
|
||||
return this.execute();
|
||||
};
|
||||
|
||||
_proto.execute = function execute() {
|
||||
var _this = this;
|
||||
|
||||
var data;
|
||||
var restored = this.state.status === 'loading';
|
||||
var promise = Promise.resolve();
|
||||
|
||||
if (!restored) {
|
||||
this.dispatch({
|
||||
type: 'loading',
|
||||
variables: this.options.variables
|
||||
});
|
||||
promise = promise.then(function () {
|
||||
// Notify cache callback
|
||||
_this.mutationCache.config.onMutate == null ? void 0 : _this.mutationCache.config.onMutate(_this.state.variables, _this);
|
||||
}).then(function () {
|
||||
return _this.options.onMutate == null ? void 0 : _this.options.onMutate(_this.state.variables);
|
||||
}).then(function (context) {
|
||||
if (context !== _this.state.context) {
|
||||
_this.dispatch({
|
||||
type: 'loading',
|
||||
context: context,
|
||||
variables: _this.state.variables
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return promise.then(function () {
|
||||
return _this.executeMutation();
|
||||
}).then(function (result) {
|
||||
data = result; // Notify cache callback
|
||||
|
||||
_this.mutationCache.config.onSuccess == null ? void 0 : _this.mutationCache.config.onSuccess(data, _this.state.variables, _this.state.context, _this);
|
||||
}).then(function () {
|
||||
return _this.options.onSuccess == null ? void 0 : _this.options.onSuccess(data, _this.state.variables, _this.state.context);
|
||||
}).then(function () {
|
||||
return _this.options.onSettled == null ? void 0 : _this.options.onSettled(data, null, _this.state.variables, _this.state.context);
|
||||
}).then(function () {
|
||||
_this.dispatch({
|
||||
type: 'success',
|
||||
data: data
|
||||
});
|
||||
|
||||
return data;
|
||||
}).catch(function (error) {
|
||||
// Notify cache callback
|
||||
_this.mutationCache.config.onError == null ? void 0 : _this.mutationCache.config.onError(error, _this.state.variables, _this.state.context, _this); // Log error
|
||||
|
||||
(0, _logger.getLogger)().error(error);
|
||||
return Promise.resolve().then(function () {
|
||||
return _this.options.onError == null ? void 0 : _this.options.onError(error, _this.state.variables, _this.state.context);
|
||||
}).then(function () {
|
||||
return _this.options.onSettled == null ? void 0 : _this.options.onSettled(undefined, error, _this.state.variables, _this.state.context);
|
||||
}).then(function () {
|
||||
_this.dispatch({
|
||||
type: 'error',
|
||||
error: error
|
||||
});
|
||||
|
||||
throw error;
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
_proto.executeMutation = function executeMutation() {
|
||||
var _this2 = this,
|
||||
_this$options$retry;
|
||||
|
||||
this.retryer = new _retryer.Retryer({
|
||||
fn: function fn() {
|
||||
if (!_this2.options.mutationFn) {
|
||||
return Promise.reject('No mutationFn found');
|
||||
}
|
||||
|
||||
return _this2.options.mutationFn(_this2.state.variables);
|
||||
},
|
||||
onFail: function onFail() {
|
||||
_this2.dispatch({
|
||||
type: 'failed'
|
||||
});
|
||||
},
|
||||
onPause: function onPause() {
|
||||
_this2.dispatch({
|
||||
type: 'pause'
|
||||
});
|
||||
},
|
||||
onContinue: function onContinue() {
|
||||
_this2.dispatch({
|
||||
type: 'continue'
|
||||
});
|
||||
},
|
||||
retry: (_this$options$retry = this.options.retry) != null ? _this$options$retry : 0,
|
||||
retryDelay: this.options.retryDelay
|
||||
});
|
||||
return this.retryer.promise;
|
||||
};
|
||||
|
||||
_proto.dispatch = function dispatch(action) {
|
||||
var _this3 = this;
|
||||
|
||||
this.state = reducer(this.state, action);
|
||||
|
||||
_notifyManager.notifyManager.batch(function () {
|
||||
_this3.observers.forEach(function (observer) {
|
||||
observer.onMutationUpdate(action);
|
||||
});
|
||||
|
||||
_this3.mutationCache.notify(_this3);
|
||||
});
|
||||
};
|
||||
|
||||
return Mutation;
|
||||
}();
|
||||
|
||||
exports.Mutation = Mutation;
|
||||
|
||||
function getDefaultState() {
|
||||
return {
|
||||
context: undefined,
|
||||
data: undefined,
|
||||
error: null,
|
||||
failureCount: 0,
|
||||
isPaused: false,
|
||||
status: 'idle',
|
||||
variables: undefined
|
||||
};
|
||||
}
|
||||
|
||||
function reducer(state, action) {
|
||||
switch (action.type) {
|
||||
case 'failed':
|
||||
return (0, _extends2.default)({}, state, {
|
||||
failureCount: state.failureCount + 1
|
||||
});
|
||||
|
||||
case 'pause':
|
||||
return (0, _extends2.default)({}, state, {
|
||||
isPaused: true
|
||||
});
|
||||
|
||||
case 'continue':
|
||||
return (0, _extends2.default)({}, state, {
|
||||
isPaused: false
|
||||
});
|
||||
|
||||
case 'loading':
|
||||
return (0, _extends2.default)({}, state, {
|
||||
context: action.context,
|
||||
data: undefined,
|
||||
error: null,
|
||||
isPaused: false,
|
||||
status: 'loading',
|
||||
variables: action.variables
|
||||
});
|
||||
|
||||
case 'success':
|
||||
return (0, _extends2.default)({}, state, {
|
||||
data: action.data,
|
||||
error: null,
|
||||
status: 'success',
|
||||
isPaused: false
|
||||
});
|
||||
|
||||
case 'error':
|
||||
return (0, _extends2.default)({}, state, {
|
||||
data: undefined,
|
||||
error: action.error,
|
||||
failureCount: state.failureCount + 1,
|
||||
isPaused: false,
|
||||
status: 'error'
|
||||
});
|
||||
|
||||
case 'setState':
|
||||
return (0, _extends2.default)({}, state, action.state);
|
||||
|
||||
default:
|
||||
return state;
|
||||
}
|
||||
}
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
"use strict";
|
||||
|
||||
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
|
||||
|
||||
exports.__esModule = true;
|
||||
exports.MutationCache = void 0;
|
||||
|
||||
var _inheritsLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/inheritsLoose"));
|
||||
|
||||
var _notifyManager = require("./notifyManager");
|
||||
|
||||
var _mutation = require("./mutation");
|
||||
|
||||
var _utils = require("./utils");
|
||||
|
||||
var _subscribable = require("./subscribable");
|
||||
|
||||
// CLASS
|
||||
var MutationCache = /*#__PURE__*/function (_Subscribable) {
|
||||
(0, _inheritsLoose2.default)(MutationCache, _Subscribable);
|
||||
|
||||
function MutationCache(config) {
|
||||
var _this;
|
||||
|
||||
_this = _Subscribable.call(this) || this;
|
||||
_this.config = config || {};
|
||||
_this.mutations = [];
|
||||
_this.mutationId = 0;
|
||||
return _this;
|
||||
}
|
||||
|
||||
var _proto = MutationCache.prototype;
|
||||
|
||||
_proto.build = function build(client, options, state) {
|
||||
var mutation = new _mutation.Mutation({
|
||||
mutationCache: this,
|
||||
mutationId: ++this.mutationId,
|
||||
options: client.defaultMutationOptions(options),
|
||||
state: state,
|
||||
defaultOptions: options.mutationKey ? client.getMutationDefaults(options.mutationKey) : undefined,
|
||||
meta: options.meta
|
||||
});
|
||||
this.add(mutation);
|
||||
return mutation;
|
||||
};
|
||||
|
||||
_proto.add = function add(mutation) {
|
||||
this.mutations.push(mutation);
|
||||
this.notify(mutation);
|
||||
};
|
||||
|
||||
_proto.remove = function remove(mutation) {
|
||||
this.mutations = this.mutations.filter(function (x) {
|
||||
return x !== mutation;
|
||||
});
|
||||
mutation.cancel();
|
||||
this.notify(mutation);
|
||||
};
|
||||
|
||||
_proto.clear = function clear() {
|
||||
var _this2 = this;
|
||||
|
||||
_notifyManager.notifyManager.batch(function () {
|
||||
_this2.mutations.forEach(function (mutation) {
|
||||
_this2.remove(mutation);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
_proto.getAll = function getAll() {
|
||||
return this.mutations;
|
||||
};
|
||||
|
||||
_proto.find = function find(filters) {
|
||||
if (typeof filters.exact === 'undefined') {
|
||||
filters.exact = true;
|
||||
}
|
||||
|
||||
return this.mutations.find(function (mutation) {
|
||||
return (0, _utils.matchMutation)(filters, mutation);
|
||||
});
|
||||
};
|
||||
|
||||
_proto.findAll = function findAll(filters) {
|
||||
return this.mutations.filter(function (mutation) {
|
||||
return (0, _utils.matchMutation)(filters, mutation);
|
||||
});
|
||||
};
|
||||
|
||||
_proto.notify = function notify(mutation) {
|
||||
var _this3 = this;
|
||||
|
||||
_notifyManager.notifyManager.batch(function () {
|
||||
_this3.listeners.forEach(function (listener) {
|
||||
listener(mutation);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
_proto.onFocus = function onFocus() {
|
||||
this.resumePausedMutations();
|
||||
};
|
||||
|
||||
_proto.onOnline = function onOnline() {
|
||||
this.resumePausedMutations();
|
||||
};
|
||||
|
||||
_proto.resumePausedMutations = function resumePausedMutations() {
|
||||
var pausedMutations = this.mutations.filter(function (x) {
|
||||
return x.state.isPaused;
|
||||
});
|
||||
return _notifyManager.notifyManager.batch(function () {
|
||||
return pausedMutations.reduce(function (promise, mutation) {
|
||||
return promise.then(function () {
|
||||
return mutation.continue().catch(_utils.noop);
|
||||
});
|
||||
}, Promise.resolve());
|
||||
});
|
||||
};
|
||||
|
||||
return MutationCache;
|
||||
}(_subscribable.Subscribable);
|
||||
|
||||
exports.MutationCache = MutationCache;
|
||||
+138
@@ -0,0 +1,138 @@
|
||||
"use strict";
|
||||
|
||||
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
|
||||
|
||||
exports.__esModule = true;
|
||||
exports.MutationObserver = void 0;
|
||||
|
||||
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
|
||||
|
||||
var _inheritsLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/inheritsLoose"));
|
||||
|
||||
var _mutation = require("./mutation");
|
||||
|
||||
var _notifyManager = require("./notifyManager");
|
||||
|
||||
var _subscribable = require("./subscribable");
|
||||
|
||||
// CLASS
|
||||
var MutationObserver = /*#__PURE__*/function (_Subscribable) {
|
||||
(0, _inheritsLoose2.default)(MutationObserver, _Subscribable);
|
||||
|
||||
function MutationObserver(client, options) {
|
||||
var _this;
|
||||
|
||||
_this = _Subscribable.call(this) || this;
|
||||
_this.client = client;
|
||||
|
||||
_this.setOptions(options);
|
||||
|
||||
_this.bindMethods();
|
||||
|
||||
_this.updateResult();
|
||||
|
||||
return _this;
|
||||
}
|
||||
|
||||
var _proto = MutationObserver.prototype;
|
||||
|
||||
_proto.bindMethods = function bindMethods() {
|
||||
this.mutate = this.mutate.bind(this);
|
||||
this.reset = this.reset.bind(this);
|
||||
};
|
||||
|
||||
_proto.setOptions = function setOptions(options) {
|
||||
this.options = this.client.defaultMutationOptions(options);
|
||||
};
|
||||
|
||||
_proto.onUnsubscribe = function onUnsubscribe() {
|
||||
if (!this.listeners.length) {
|
||||
var _this$currentMutation;
|
||||
|
||||
(_this$currentMutation = this.currentMutation) == null ? void 0 : _this$currentMutation.removeObserver(this);
|
||||
}
|
||||
};
|
||||
|
||||
_proto.onMutationUpdate = function onMutationUpdate(action) {
|
||||
this.updateResult(); // Determine which callbacks to trigger
|
||||
|
||||
var notifyOptions = {
|
||||
listeners: true
|
||||
};
|
||||
|
||||
if (action.type === 'success') {
|
||||
notifyOptions.onSuccess = true;
|
||||
} else if (action.type === 'error') {
|
||||
notifyOptions.onError = true;
|
||||
}
|
||||
|
||||
this.notify(notifyOptions);
|
||||
};
|
||||
|
||||
_proto.getCurrentResult = function getCurrentResult() {
|
||||
return this.currentResult;
|
||||
};
|
||||
|
||||
_proto.reset = function reset() {
|
||||
this.currentMutation = undefined;
|
||||
this.updateResult();
|
||||
this.notify({
|
||||
listeners: true
|
||||
});
|
||||
};
|
||||
|
||||
_proto.mutate = function mutate(variables, options) {
|
||||
this.mutateOptions = options;
|
||||
|
||||
if (this.currentMutation) {
|
||||
this.currentMutation.removeObserver(this);
|
||||
}
|
||||
|
||||
this.currentMutation = this.client.getMutationCache().build(this.client, (0, _extends2.default)({}, this.options, {
|
||||
variables: typeof variables !== 'undefined' ? variables : this.options.variables
|
||||
}));
|
||||
this.currentMutation.addObserver(this);
|
||||
return this.currentMutation.execute();
|
||||
};
|
||||
|
||||
_proto.updateResult = function updateResult() {
|
||||
var state = this.currentMutation ? this.currentMutation.state : (0, _mutation.getDefaultState)();
|
||||
var result = (0, _extends2.default)({}, state, {
|
||||
isLoading: state.status === 'loading',
|
||||
isSuccess: state.status === 'success',
|
||||
isError: state.status === 'error',
|
||||
isIdle: state.status === 'idle',
|
||||
mutate: this.mutate,
|
||||
reset: this.reset
|
||||
});
|
||||
this.currentResult = result;
|
||||
};
|
||||
|
||||
_proto.notify = function notify(options) {
|
||||
var _this2 = this;
|
||||
|
||||
_notifyManager.notifyManager.batch(function () {
|
||||
// First trigger the mutate callbacks
|
||||
if (_this2.mutateOptions) {
|
||||
if (options.onSuccess) {
|
||||
_this2.mutateOptions.onSuccess == null ? void 0 : _this2.mutateOptions.onSuccess(_this2.currentResult.data, _this2.currentResult.variables, _this2.currentResult.context);
|
||||
_this2.mutateOptions.onSettled == null ? void 0 : _this2.mutateOptions.onSettled(_this2.currentResult.data, null, _this2.currentResult.variables, _this2.currentResult.context);
|
||||
} else if (options.onError) {
|
||||
_this2.mutateOptions.onError == null ? void 0 : _this2.mutateOptions.onError(_this2.currentResult.error, _this2.currentResult.variables, _this2.currentResult.context);
|
||||
_this2.mutateOptions.onSettled == null ? void 0 : _this2.mutateOptions.onSettled(undefined, _this2.currentResult.error, _this2.currentResult.variables, _this2.currentResult.context);
|
||||
}
|
||||
} // Then trigger the listeners
|
||||
|
||||
|
||||
if (options.listeners) {
|
||||
_this2.listeners.forEach(function (listener) {
|
||||
listener(_this2.currentResult);
|
||||
});
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
return MutationObserver;
|
||||
}(_subscribable.Subscribable);
|
||||
|
||||
exports.MutationObserver = MutationObserver;
|
||||
+113
@@ -0,0 +1,113 @@
|
||||
"use strict";
|
||||
|
||||
exports.__esModule = true;
|
||||
exports.notifyManager = exports.NotifyManager = void 0;
|
||||
|
||||
var _utils = require("./utils");
|
||||
|
||||
// CLASS
|
||||
var NotifyManager = /*#__PURE__*/function () {
|
||||
function NotifyManager() {
|
||||
this.queue = [];
|
||||
this.transactions = 0;
|
||||
|
||||
this.notifyFn = function (callback) {
|
||||
callback();
|
||||
};
|
||||
|
||||
this.batchNotifyFn = function (callback) {
|
||||
callback();
|
||||
};
|
||||
}
|
||||
|
||||
var _proto = NotifyManager.prototype;
|
||||
|
||||
_proto.batch = function batch(callback) {
|
||||
var result;
|
||||
this.transactions++;
|
||||
|
||||
try {
|
||||
result = callback();
|
||||
} finally {
|
||||
this.transactions--;
|
||||
|
||||
if (!this.transactions) {
|
||||
this.flush();
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
_proto.schedule = function schedule(callback) {
|
||||
var _this = this;
|
||||
|
||||
if (this.transactions) {
|
||||
this.queue.push(callback);
|
||||
} else {
|
||||
(0, _utils.scheduleMicrotask)(function () {
|
||||
_this.notifyFn(callback);
|
||||
});
|
||||
}
|
||||
}
|
||||
/**
|
||||
* All calls to the wrapped function will be batched.
|
||||
*/
|
||||
;
|
||||
|
||||
_proto.batchCalls = function batchCalls(callback) {
|
||||
var _this2 = this;
|
||||
|
||||
return function () {
|
||||
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
|
||||
args[_key] = arguments[_key];
|
||||
}
|
||||
|
||||
_this2.schedule(function () {
|
||||
callback.apply(void 0, args);
|
||||
});
|
||||
};
|
||||
};
|
||||
|
||||
_proto.flush = function flush() {
|
||||
var _this3 = this;
|
||||
|
||||
var queue = this.queue;
|
||||
this.queue = [];
|
||||
|
||||
if (queue.length) {
|
||||
(0, _utils.scheduleMicrotask)(function () {
|
||||
_this3.batchNotifyFn(function () {
|
||||
queue.forEach(function (callback) {
|
||||
_this3.notifyFn(callback);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Use this method to set a custom notify function.
|
||||
* This can be used to for example wrap notifications with `React.act` while running tests.
|
||||
*/
|
||||
;
|
||||
|
||||
_proto.setNotifyFunction = function setNotifyFunction(fn) {
|
||||
this.notifyFn = fn;
|
||||
}
|
||||
/**
|
||||
* Use this method to set a custom function to batch notifications together into a single tick.
|
||||
* By default React Query will use the batch function provided by ReactDOM or React Native.
|
||||
*/
|
||||
;
|
||||
|
||||
_proto.setBatchNotifyFunction = function setBatchNotifyFunction(fn) {
|
||||
this.batchNotifyFn = fn;
|
||||
};
|
||||
|
||||
return NotifyManager;
|
||||
}(); // SINGLETON
|
||||
|
||||
|
||||
exports.NotifyManager = NotifyManager;
|
||||
var notifyManager = new NotifyManager();
|
||||
exports.notifyManager = notifyManager;
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
"use strict";
|
||||
|
||||
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
|
||||
|
||||
exports.__esModule = true;
|
||||
exports.onlineManager = exports.OnlineManager = void 0;
|
||||
|
||||
var _inheritsLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/inheritsLoose"));
|
||||
|
||||
var _subscribable = require("./subscribable");
|
||||
|
||||
var _utils = require("./utils");
|
||||
|
||||
var OnlineManager = /*#__PURE__*/function (_Subscribable) {
|
||||
(0, _inheritsLoose2.default)(OnlineManager, _Subscribable);
|
||||
|
||||
function OnlineManager() {
|
||||
var _this;
|
||||
|
||||
_this = _Subscribable.call(this) || this;
|
||||
|
||||
_this.setup = function (onOnline) {
|
||||
var _window;
|
||||
|
||||
if (!_utils.isServer && ((_window = window) == null ? void 0 : _window.addEventListener)) {
|
||||
var listener = function listener() {
|
||||
return onOnline();
|
||||
}; // Listen to online
|
||||
|
||||
|
||||
window.addEventListener('online', listener, false);
|
||||
window.addEventListener('offline', listener, false);
|
||||
return function () {
|
||||
// Be sure to unsubscribe if a new handler is set
|
||||
window.removeEventListener('online', listener);
|
||||
window.removeEventListener('offline', listener);
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
return _this;
|
||||
}
|
||||
|
||||
var _proto = OnlineManager.prototype;
|
||||
|
||||
_proto.onSubscribe = function onSubscribe() {
|
||||
if (!this.cleanup) {
|
||||
this.setEventListener(this.setup);
|
||||
}
|
||||
};
|
||||
|
||||
_proto.onUnsubscribe = function onUnsubscribe() {
|
||||
if (!this.hasListeners()) {
|
||||
var _this$cleanup;
|
||||
|
||||
(_this$cleanup = this.cleanup) == null ? void 0 : _this$cleanup.call(this);
|
||||
this.cleanup = undefined;
|
||||
}
|
||||
};
|
||||
|
||||
_proto.setEventListener = function setEventListener(setup) {
|
||||
var _this$cleanup2,
|
||||
_this2 = this;
|
||||
|
||||
this.setup = setup;
|
||||
(_this$cleanup2 = this.cleanup) == null ? void 0 : _this$cleanup2.call(this);
|
||||
this.cleanup = setup(function (online) {
|
||||
if (typeof online === 'boolean') {
|
||||
_this2.setOnline(online);
|
||||
} else {
|
||||
_this2.onOnline();
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
_proto.setOnline = function setOnline(online) {
|
||||
this.online = online;
|
||||
|
||||
if (online) {
|
||||
this.onOnline();
|
||||
}
|
||||
};
|
||||
|
||||
_proto.onOnline = function onOnline() {
|
||||
this.listeners.forEach(function (listener) {
|
||||
listener();
|
||||
});
|
||||
};
|
||||
|
||||
_proto.isOnline = function isOnline() {
|
||||
if (typeof this.online === 'boolean') {
|
||||
return this.online;
|
||||
}
|
||||
|
||||
if (typeof navigator === 'undefined' || typeof navigator.onLine === 'undefined') {
|
||||
return true;
|
||||
}
|
||||
|
||||
return navigator.onLine;
|
||||
};
|
||||
|
||||
return OnlineManager;
|
||||
}(_subscribable.Subscribable);
|
||||
|
||||
exports.OnlineManager = OnlineManager;
|
||||
var onlineManager = new OnlineManager();
|
||||
exports.onlineManager = onlineManager;
|
||||
+216
@@ -0,0 +1,216 @@
|
||||
"use strict";
|
||||
|
||||
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
|
||||
|
||||
exports.__esModule = true;
|
||||
exports.QueriesObserver = void 0;
|
||||
|
||||
var _inheritsLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/inheritsLoose"));
|
||||
|
||||
var _utils = require("./utils");
|
||||
|
||||
var _notifyManager = require("./notifyManager");
|
||||
|
||||
var _queryObserver = require("./queryObserver");
|
||||
|
||||
var _subscribable = require("./subscribable");
|
||||
|
||||
var QueriesObserver = /*#__PURE__*/function (_Subscribable) {
|
||||
(0, _inheritsLoose2.default)(QueriesObserver, _Subscribable);
|
||||
|
||||
function QueriesObserver(client, queries) {
|
||||
var _this;
|
||||
|
||||
_this = _Subscribable.call(this) || this;
|
||||
_this.client = client;
|
||||
_this.queries = [];
|
||||
_this.result = [];
|
||||
_this.observers = [];
|
||||
_this.observersMap = {};
|
||||
|
||||
if (queries) {
|
||||
_this.setQueries(queries);
|
||||
}
|
||||
|
||||
return _this;
|
||||
}
|
||||
|
||||
var _proto = QueriesObserver.prototype;
|
||||
|
||||
_proto.onSubscribe = function onSubscribe() {
|
||||
var _this2 = this;
|
||||
|
||||
if (this.listeners.length === 1) {
|
||||
this.observers.forEach(function (observer) {
|
||||
observer.subscribe(function (result) {
|
||||
_this2.onUpdate(observer, result);
|
||||
});
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
_proto.onUnsubscribe = function onUnsubscribe() {
|
||||
if (!this.listeners.length) {
|
||||
this.destroy();
|
||||
}
|
||||
};
|
||||
|
||||
_proto.destroy = function destroy() {
|
||||
this.listeners = [];
|
||||
this.observers.forEach(function (observer) {
|
||||
observer.destroy();
|
||||
});
|
||||
};
|
||||
|
||||
_proto.setQueries = function setQueries(queries, notifyOptions) {
|
||||
this.queries = queries;
|
||||
this.updateObservers(notifyOptions);
|
||||
};
|
||||
|
||||
_proto.getCurrentResult = function getCurrentResult() {
|
||||
return this.result;
|
||||
};
|
||||
|
||||
_proto.getOptimisticResult = function getOptimisticResult(queries) {
|
||||
return this.findMatchingObservers(queries).map(function (match) {
|
||||
return match.observer.getOptimisticResult(match.defaultedQueryOptions);
|
||||
});
|
||||
};
|
||||
|
||||
_proto.findMatchingObservers = function findMatchingObservers(queries) {
|
||||
var _this3 = this;
|
||||
|
||||
var prevObservers = this.observers;
|
||||
var defaultedQueryOptions = queries.map(function (options) {
|
||||
return _this3.client.defaultQueryObserverOptions(options);
|
||||
});
|
||||
var matchingObservers = defaultedQueryOptions.flatMap(function (defaultedOptions) {
|
||||
var match = prevObservers.find(function (observer) {
|
||||
return observer.options.queryHash === defaultedOptions.queryHash;
|
||||
});
|
||||
|
||||
if (match != null) {
|
||||
return [{
|
||||
defaultedQueryOptions: defaultedOptions,
|
||||
observer: match
|
||||
}];
|
||||
}
|
||||
|
||||
return [];
|
||||
});
|
||||
var matchedQueryHashes = matchingObservers.map(function (match) {
|
||||
return match.defaultedQueryOptions.queryHash;
|
||||
});
|
||||
var unmatchedQueries = defaultedQueryOptions.filter(function (defaultedOptions) {
|
||||
return !matchedQueryHashes.includes(defaultedOptions.queryHash);
|
||||
});
|
||||
var unmatchedObservers = prevObservers.filter(function (prevObserver) {
|
||||
return !matchingObservers.some(function (match) {
|
||||
return match.observer === prevObserver;
|
||||
});
|
||||
});
|
||||
var newOrReusedObservers = unmatchedQueries.map(function (options, index) {
|
||||
if (options.keepPreviousData) {
|
||||
// return previous data from one of the observers that no longer match
|
||||
var previouslyUsedObserver = unmatchedObservers[index];
|
||||
|
||||
if (previouslyUsedObserver !== undefined) {
|
||||
return {
|
||||
defaultedQueryOptions: options,
|
||||
observer: previouslyUsedObserver
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
defaultedQueryOptions: options,
|
||||
observer: _this3.getObserver(options)
|
||||
};
|
||||
});
|
||||
|
||||
var sortMatchesByOrderOfQueries = function sortMatchesByOrderOfQueries(a, b) {
|
||||
return defaultedQueryOptions.indexOf(a.defaultedQueryOptions) - defaultedQueryOptions.indexOf(b.defaultedQueryOptions);
|
||||
};
|
||||
|
||||
return matchingObservers.concat(newOrReusedObservers).sort(sortMatchesByOrderOfQueries);
|
||||
};
|
||||
|
||||
_proto.getObserver = function getObserver(options) {
|
||||
var defaultedOptions = this.client.defaultQueryObserverOptions(options);
|
||||
var currentObserver = this.observersMap[defaultedOptions.queryHash];
|
||||
return currentObserver != null ? currentObserver : new _queryObserver.QueryObserver(this.client, defaultedOptions);
|
||||
};
|
||||
|
||||
_proto.updateObservers = function updateObservers(notifyOptions) {
|
||||
var _this4 = this;
|
||||
|
||||
_notifyManager.notifyManager.batch(function () {
|
||||
var prevObservers = _this4.observers;
|
||||
|
||||
var newObserverMatches = _this4.findMatchingObservers(_this4.queries); // set options for the new observers to notify of changes
|
||||
|
||||
|
||||
newObserverMatches.forEach(function (match) {
|
||||
return match.observer.setOptions(match.defaultedQueryOptions, notifyOptions);
|
||||
});
|
||||
var newObservers = newObserverMatches.map(function (match) {
|
||||
return match.observer;
|
||||
});
|
||||
var newObserversMap = Object.fromEntries(newObservers.map(function (observer) {
|
||||
return [observer.options.queryHash, observer];
|
||||
}));
|
||||
var newResult = newObservers.map(function (observer) {
|
||||
return observer.getCurrentResult();
|
||||
});
|
||||
var hasIndexChange = newObservers.some(function (observer, index) {
|
||||
return observer !== prevObservers[index];
|
||||
});
|
||||
|
||||
if (prevObservers.length === newObservers.length && !hasIndexChange) {
|
||||
return;
|
||||
}
|
||||
|
||||
_this4.observers = newObservers;
|
||||
_this4.observersMap = newObserversMap;
|
||||
_this4.result = newResult;
|
||||
|
||||
if (!_this4.hasListeners()) {
|
||||
return;
|
||||
}
|
||||
|
||||
(0, _utils.difference)(prevObservers, newObservers).forEach(function (observer) {
|
||||
observer.destroy();
|
||||
});
|
||||
(0, _utils.difference)(newObservers, prevObservers).forEach(function (observer) {
|
||||
observer.subscribe(function (result) {
|
||||
_this4.onUpdate(observer, result);
|
||||
});
|
||||
});
|
||||
|
||||
_this4.notify();
|
||||
});
|
||||
};
|
||||
|
||||
_proto.onUpdate = function onUpdate(observer, result) {
|
||||
var index = this.observers.indexOf(observer);
|
||||
|
||||
if (index !== -1) {
|
||||
this.result = (0, _utils.replaceAt)(this.result, index, result);
|
||||
this.notify();
|
||||
}
|
||||
};
|
||||
|
||||
_proto.notify = function notify() {
|
||||
var _this5 = this;
|
||||
|
||||
_notifyManager.notifyManager.batch(function () {
|
||||
_this5.listeners.forEach(function (listener) {
|
||||
listener(_this5.result);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
return QueriesObserver;
|
||||
}(_subscribable.Subscribable);
|
||||
|
||||
exports.QueriesObserver = QueriesObserver;
|
||||
+514
@@ -0,0 +1,514 @@
|
||||
"use strict";
|
||||
|
||||
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
|
||||
|
||||
exports.__esModule = true;
|
||||
exports.Query = void 0;
|
||||
|
||||
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
|
||||
|
||||
var _utils = require("./utils");
|
||||
|
||||
var _notifyManager = require("./notifyManager");
|
||||
|
||||
var _logger = require("./logger");
|
||||
|
||||
var _retryer = require("./retryer");
|
||||
|
||||
// CLASS
|
||||
var Query = /*#__PURE__*/function () {
|
||||
function Query(config) {
|
||||
this.abortSignalConsumed = false;
|
||||
this.hadObservers = false;
|
||||
this.defaultOptions = config.defaultOptions;
|
||||
this.setOptions(config.options);
|
||||
this.observers = [];
|
||||
this.cache = config.cache;
|
||||
this.queryKey = config.queryKey;
|
||||
this.queryHash = config.queryHash;
|
||||
this.initialState = config.state || this.getDefaultState(this.options);
|
||||
this.state = this.initialState;
|
||||
this.meta = config.meta;
|
||||
this.scheduleGc();
|
||||
}
|
||||
|
||||
var _proto = Query.prototype;
|
||||
|
||||
_proto.setOptions = function setOptions(options) {
|
||||
var _this$options$cacheTi;
|
||||
|
||||
this.options = (0, _extends2.default)({}, this.defaultOptions, options);
|
||||
this.meta = options == null ? void 0 : options.meta; // Default to 5 minutes if not cache time is set
|
||||
|
||||
this.cacheTime = Math.max(this.cacheTime || 0, (_this$options$cacheTi = this.options.cacheTime) != null ? _this$options$cacheTi : 5 * 60 * 1000);
|
||||
};
|
||||
|
||||
_proto.setDefaultOptions = function setDefaultOptions(options) {
|
||||
this.defaultOptions = options;
|
||||
};
|
||||
|
||||
_proto.scheduleGc = function scheduleGc() {
|
||||
var _this = this;
|
||||
|
||||
this.clearGcTimeout();
|
||||
|
||||
if ((0, _utils.isValidTimeout)(this.cacheTime)) {
|
||||
this.gcTimeout = setTimeout(function () {
|
||||
_this.optionalRemove();
|
||||
}, this.cacheTime);
|
||||
}
|
||||
};
|
||||
|
||||
_proto.clearGcTimeout = function clearGcTimeout() {
|
||||
if (this.gcTimeout) {
|
||||
clearTimeout(this.gcTimeout);
|
||||
this.gcTimeout = undefined;
|
||||
}
|
||||
};
|
||||
|
||||
_proto.optionalRemove = function optionalRemove() {
|
||||
if (!this.observers.length) {
|
||||
if (this.state.isFetching) {
|
||||
if (this.hadObservers) {
|
||||
this.scheduleGc();
|
||||
}
|
||||
} else {
|
||||
this.cache.remove(this);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
_proto.setData = function setData(updater, options) {
|
||||
var _this$options$isDataE, _this$options;
|
||||
|
||||
var prevData = this.state.data; // Get the new data
|
||||
|
||||
var data = (0, _utils.functionalUpdate)(updater, prevData); // Use prev data if an isDataEqual function is defined and returns `true`
|
||||
|
||||
if ((_this$options$isDataE = (_this$options = this.options).isDataEqual) == null ? void 0 : _this$options$isDataE.call(_this$options, prevData, data)) {
|
||||
data = prevData;
|
||||
} else if (this.options.structuralSharing !== false) {
|
||||
// Structurally share data between prev and new data if needed
|
||||
data = (0, _utils.replaceEqualDeep)(prevData, data);
|
||||
} // Set data and mark it as cached
|
||||
|
||||
|
||||
this.dispatch({
|
||||
data: data,
|
||||
type: 'success',
|
||||
dataUpdatedAt: options == null ? void 0 : options.updatedAt
|
||||
});
|
||||
return data;
|
||||
};
|
||||
|
||||
_proto.setState = function setState(state, setStateOptions) {
|
||||
this.dispatch({
|
||||
type: 'setState',
|
||||
state: state,
|
||||
setStateOptions: setStateOptions
|
||||
});
|
||||
};
|
||||
|
||||
_proto.cancel = function cancel(options) {
|
||||
var _this$retryer;
|
||||
|
||||
var promise = this.promise;
|
||||
(_this$retryer = this.retryer) == null ? void 0 : _this$retryer.cancel(options);
|
||||
return promise ? promise.then(_utils.noop).catch(_utils.noop) : Promise.resolve();
|
||||
};
|
||||
|
||||
_proto.destroy = function destroy() {
|
||||
this.clearGcTimeout();
|
||||
this.cancel({
|
||||
silent: true
|
||||
});
|
||||
};
|
||||
|
||||
_proto.reset = function reset() {
|
||||
this.destroy();
|
||||
this.setState(this.initialState);
|
||||
};
|
||||
|
||||
_proto.isActive = function isActive() {
|
||||
return this.observers.some(function (observer) {
|
||||
return observer.options.enabled !== false;
|
||||
});
|
||||
};
|
||||
|
||||
_proto.isFetching = function isFetching() {
|
||||
return this.state.isFetching;
|
||||
};
|
||||
|
||||
_proto.isStale = function isStale() {
|
||||
return this.state.isInvalidated || !this.state.dataUpdatedAt || this.observers.some(function (observer) {
|
||||
return observer.getCurrentResult().isStale;
|
||||
});
|
||||
};
|
||||
|
||||
_proto.isStaleByTime = function isStaleByTime(staleTime) {
|
||||
if (staleTime === void 0) {
|
||||
staleTime = 0;
|
||||
}
|
||||
|
||||
return this.state.isInvalidated || !this.state.dataUpdatedAt || !(0, _utils.timeUntilStale)(this.state.dataUpdatedAt, staleTime);
|
||||
};
|
||||
|
||||
_proto.onFocus = function onFocus() {
|
||||
var _this$retryer2;
|
||||
|
||||
var observer = this.observers.find(function (x) {
|
||||
return x.shouldFetchOnWindowFocus();
|
||||
});
|
||||
|
||||
if (observer) {
|
||||
observer.refetch();
|
||||
} // Continue fetch if currently paused
|
||||
|
||||
|
||||
(_this$retryer2 = this.retryer) == null ? void 0 : _this$retryer2.continue();
|
||||
};
|
||||
|
||||
_proto.onOnline = function onOnline() {
|
||||
var _this$retryer3;
|
||||
|
||||
var observer = this.observers.find(function (x) {
|
||||
return x.shouldFetchOnReconnect();
|
||||
});
|
||||
|
||||
if (observer) {
|
||||
observer.refetch();
|
||||
} // Continue fetch if currently paused
|
||||
|
||||
|
||||
(_this$retryer3 = this.retryer) == null ? void 0 : _this$retryer3.continue();
|
||||
};
|
||||
|
||||
_proto.addObserver = function addObserver(observer) {
|
||||
if (this.observers.indexOf(observer) === -1) {
|
||||
this.observers.push(observer);
|
||||
this.hadObservers = true; // Stop the query from being garbage collected
|
||||
|
||||
this.clearGcTimeout();
|
||||
this.cache.notify({
|
||||
type: 'observerAdded',
|
||||
query: this,
|
||||
observer: observer
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
_proto.removeObserver = function removeObserver(observer) {
|
||||
if (this.observers.indexOf(observer) !== -1) {
|
||||
this.observers = this.observers.filter(function (x) {
|
||||
return x !== observer;
|
||||
});
|
||||
|
||||
if (!this.observers.length) {
|
||||
// If the transport layer does not support cancellation
|
||||
// we'll let the query continue so the result can be cached
|
||||
if (this.retryer) {
|
||||
if (this.retryer.isTransportCancelable || this.abortSignalConsumed) {
|
||||
this.retryer.cancel({
|
||||
revert: true
|
||||
});
|
||||
} else {
|
||||
this.retryer.cancelRetry();
|
||||
}
|
||||
}
|
||||
|
||||
if (this.cacheTime) {
|
||||
this.scheduleGc();
|
||||
} else {
|
||||
this.cache.remove(this);
|
||||
}
|
||||
}
|
||||
|
||||
this.cache.notify({
|
||||
type: 'observerRemoved',
|
||||
query: this,
|
||||
observer: observer
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
_proto.getObserversCount = function getObserversCount() {
|
||||
return this.observers.length;
|
||||
};
|
||||
|
||||
_proto.invalidate = function invalidate() {
|
||||
if (!this.state.isInvalidated) {
|
||||
this.dispatch({
|
||||
type: 'invalidate'
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
_proto.fetch = function fetch(options, fetchOptions) {
|
||||
var _this2 = this,
|
||||
_this$options$behavio,
|
||||
_context$fetchOptions,
|
||||
_abortController$abor;
|
||||
|
||||
if (this.state.isFetching) {
|
||||
if (this.state.dataUpdatedAt && (fetchOptions == null ? void 0 : fetchOptions.cancelRefetch)) {
|
||||
// Silently cancel current fetch if the user wants to cancel refetches
|
||||
this.cancel({
|
||||
silent: true
|
||||
});
|
||||
} else if (this.promise) {
|
||||
var _this$retryer4;
|
||||
|
||||
// make sure that retries that were potentially cancelled due to unmounts can continue
|
||||
(_this$retryer4 = this.retryer) == null ? void 0 : _this$retryer4.continueRetry(); // Return current promise if we are already fetching
|
||||
|
||||
return this.promise;
|
||||
}
|
||||
} // Update config if passed, otherwise the config from the last execution is used
|
||||
|
||||
|
||||
if (options) {
|
||||
this.setOptions(options);
|
||||
} // Use the options from the first observer with a query function if no function is found.
|
||||
// This can happen when the query is hydrated or created with setQueryData.
|
||||
|
||||
|
||||
if (!this.options.queryFn) {
|
||||
var observer = this.observers.find(function (x) {
|
||||
return x.options.queryFn;
|
||||
});
|
||||
|
||||
if (observer) {
|
||||
this.setOptions(observer.options);
|
||||
}
|
||||
}
|
||||
|
||||
var queryKey = (0, _utils.ensureQueryKeyArray)(this.queryKey);
|
||||
var abortController = (0, _utils.getAbortController)(); // Create query function context
|
||||
|
||||
var queryFnContext = {
|
||||
queryKey: queryKey,
|
||||
pageParam: undefined,
|
||||
meta: this.meta
|
||||
};
|
||||
Object.defineProperty(queryFnContext, 'signal', {
|
||||
enumerable: true,
|
||||
get: function get() {
|
||||
if (abortController) {
|
||||
_this2.abortSignalConsumed = true;
|
||||
return abortController.signal;
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
}); // Create fetch function
|
||||
|
||||
var fetchFn = function fetchFn() {
|
||||
if (!_this2.options.queryFn) {
|
||||
return Promise.reject('Missing queryFn');
|
||||
}
|
||||
|
||||
_this2.abortSignalConsumed = false;
|
||||
return _this2.options.queryFn(queryFnContext);
|
||||
}; // Trigger behavior hook
|
||||
|
||||
|
||||
var context = {
|
||||
fetchOptions: fetchOptions,
|
||||
options: this.options,
|
||||
queryKey: queryKey,
|
||||
state: this.state,
|
||||
fetchFn: fetchFn,
|
||||
meta: this.meta
|
||||
};
|
||||
|
||||
if ((_this$options$behavio = this.options.behavior) == null ? void 0 : _this$options$behavio.onFetch) {
|
||||
var _this$options$behavio2;
|
||||
|
||||
(_this$options$behavio2 = this.options.behavior) == null ? void 0 : _this$options$behavio2.onFetch(context);
|
||||
} // Store state in case the current fetch needs to be reverted
|
||||
|
||||
|
||||
this.revertState = this.state; // Set to fetching state if not already in it
|
||||
|
||||
if (!this.state.isFetching || this.state.fetchMeta !== ((_context$fetchOptions = context.fetchOptions) == null ? void 0 : _context$fetchOptions.meta)) {
|
||||
var _context$fetchOptions2;
|
||||
|
||||
this.dispatch({
|
||||
type: 'fetch',
|
||||
meta: (_context$fetchOptions2 = context.fetchOptions) == null ? void 0 : _context$fetchOptions2.meta
|
||||
});
|
||||
} // Try to fetch the data
|
||||
|
||||
|
||||
this.retryer = new _retryer.Retryer({
|
||||
fn: context.fetchFn,
|
||||
abort: abortController == null ? void 0 : (_abortController$abor = abortController.abort) == null ? void 0 : _abortController$abor.bind(abortController),
|
||||
onSuccess: function onSuccess(data) {
|
||||
_this2.setData(data); // Notify cache callback
|
||||
|
||||
|
||||
_this2.cache.config.onSuccess == null ? void 0 : _this2.cache.config.onSuccess(data, _this2); // Remove query after fetching if cache time is 0
|
||||
|
||||
if (_this2.cacheTime === 0) {
|
||||
_this2.optionalRemove();
|
||||
}
|
||||
},
|
||||
onError: function onError(error) {
|
||||
// Optimistically update state if needed
|
||||
if (!((0, _retryer.isCancelledError)(error) && error.silent)) {
|
||||
_this2.dispatch({
|
||||
type: 'error',
|
||||
error: error
|
||||
});
|
||||
}
|
||||
|
||||
if (!(0, _retryer.isCancelledError)(error)) {
|
||||
// Notify cache callback
|
||||
_this2.cache.config.onError == null ? void 0 : _this2.cache.config.onError(error, _this2); // Log error
|
||||
|
||||
(0, _logger.getLogger)().error(error);
|
||||
} // Remove query after fetching if cache time is 0
|
||||
|
||||
|
||||
if (_this2.cacheTime === 0) {
|
||||
_this2.optionalRemove();
|
||||
}
|
||||
},
|
||||
onFail: function onFail() {
|
||||
_this2.dispatch({
|
||||
type: 'failed'
|
||||
});
|
||||
},
|
||||
onPause: function onPause() {
|
||||
_this2.dispatch({
|
||||
type: 'pause'
|
||||
});
|
||||
},
|
||||
onContinue: function onContinue() {
|
||||
_this2.dispatch({
|
||||
type: 'continue'
|
||||
});
|
||||
},
|
||||
retry: context.options.retry,
|
||||
retryDelay: context.options.retryDelay
|
||||
});
|
||||
this.promise = this.retryer.promise;
|
||||
return this.promise;
|
||||
};
|
||||
|
||||
_proto.dispatch = function dispatch(action) {
|
||||
var _this3 = this;
|
||||
|
||||
this.state = this.reducer(this.state, action);
|
||||
|
||||
_notifyManager.notifyManager.batch(function () {
|
||||
_this3.observers.forEach(function (observer) {
|
||||
observer.onQueryUpdate(action);
|
||||
});
|
||||
|
||||
_this3.cache.notify({
|
||||
query: _this3,
|
||||
type: 'queryUpdated',
|
||||
action: action
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
_proto.getDefaultState = function getDefaultState(options) {
|
||||
var data = typeof options.initialData === 'function' ? options.initialData() : options.initialData;
|
||||
var hasInitialData = typeof options.initialData !== 'undefined';
|
||||
var initialDataUpdatedAt = hasInitialData ? typeof options.initialDataUpdatedAt === 'function' ? options.initialDataUpdatedAt() : options.initialDataUpdatedAt : 0;
|
||||
var hasData = typeof data !== 'undefined';
|
||||
return {
|
||||
data: data,
|
||||
dataUpdateCount: 0,
|
||||
dataUpdatedAt: hasData ? initialDataUpdatedAt != null ? initialDataUpdatedAt : Date.now() : 0,
|
||||
error: null,
|
||||
errorUpdateCount: 0,
|
||||
errorUpdatedAt: 0,
|
||||
fetchFailureCount: 0,
|
||||
fetchMeta: null,
|
||||
isFetching: false,
|
||||
isInvalidated: false,
|
||||
isPaused: false,
|
||||
status: hasData ? 'success' : 'idle'
|
||||
};
|
||||
};
|
||||
|
||||
_proto.reducer = function reducer(state, action) {
|
||||
var _action$meta, _action$dataUpdatedAt;
|
||||
|
||||
switch (action.type) {
|
||||
case 'failed':
|
||||
return (0, _extends2.default)({}, state, {
|
||||
fetchFailureCount: state.fetchFailureCount + 1
|
||||
});
|
||||
|
||||
case 'pause':
|
||||
return (0, _extends2.default)({}, state, {
|
||||
isPaused: true
|
||||
});
|
||||
|
||||
case 'continue':
|
||||
return (0, _extends2.default)({}, state, {
|
||||
isPaused: false
|
||||
});
|
||||
|
||||
case 'fetch':
|
||||
return (0, _extends2.default)({}, state, {
|
||||
fetchFailureCount: 0,
|
||||
fetchMeta: (_action$meta = action.meta) != null ? _action$meta : null,
|
||||
isFetching: true,
|
||||
isPaused: false
|
||||
}, !state.dataUpdatedAt && {
|
||||
error: null,
|
||||
status: 'loading'
|
||||
});
|
||||
|
||||
case 'success':
|
||||
return (0, _extends2.default)({}, state, {
|
||||
data: action.data,
|
||||
dataUpdateCount: state.dataUpdateCount + 1,
|
||||
dataUpdatedAt: (_action$dataUpdatedAt = action.dataUpdatedAt) != null ? _action$dataUpdatedAt : Date.now(),
|
||||
error: null,
|
||||
fetchFailureCount: 0,
|
||||
isFetching: false,
|
||||
isInvalidated: false,
|
||||
isPaused: false,
|
||||
status: 'success'
|
||||
});
|
||||
|
||||
case 'error':
|
||||
var error = action.error;
|
||||
|
||||
if ((0, _retryer.isCancelledError)(error) && error.revert && this.revertState) {
|
||||
return (0, _extends2.default)({}, this.revertState);
|
||||
}
|
||||
|
||||
return (0, _extends2.default)({}, state, {
|
||||
error: error,
|
||||
errorUpdateCount: state.errorUpdateCount + 1,
|
||||
errorUpdatedAt: Date.now(),
|
||||
fetchFailureCount: state.fetchFailureCount + 1,
|
||||
isFetching: false,
|
||||
isPaused: false,
|
||||
status: 'error'
|
||||
});
|
||||
|
||||
case 'invalidate':
|
||||
return (0, _extends2.default)({}, state, {
|
||||
isInvalidated: true
|
||||
});
|
||||
|
||||
case 'setState':
|
||||
return (0, _extends2.default)({}, state, action.state);
|
||||
|
||||
default:
|
||||
return state;
|
||||
}
|
||||
};
|
||||
|
||||
return Query;
|
||||
}();
|
||||
|
||||
exports.Query = Query;
|
||||
+161
@@ -0,0 +1,161 @@
|
||||
"use strict";
|
||||
|
||||
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
|
||||
|
||||
exports.__esModule = true;
|
||||
exports.QueryCache = void 0;
|
||||
|
||||
var _inheritsLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/inheritsLoose"));
|
||||
|
||||
var _utils = require("./utils");
|
||||
|
||||
var _query = require("./query");
|
||||
|
||||
var _notifyManager = require("./notifyManager");
|
||||
|
||||
var _subscribable = require("./subscribable");
|
||||
|
||||
// CLASS
|
||||
var QueryCache = /*#__PURE__*/function (_Subscribable) {
|
||||
(0, _inheritsLoose2.default)(QueryCache, _Subscribable);
|
||||
|
||||
function QueryCache(config) {
|
||||
var _this;
|
||||
|
||||
_this = _Subscribable.call(this) || this;
|
||||
_this.config = config || {};
|
||||
_this.queries = [];
|
||||
_this.queriesMap = {};
|
||||
return _this;
|
||||
}
|
||||
|
||||
var _proto = QueryCache.prototype;
|
||||
|
||||
_proto.build = function build(client, options, state) {
|
||||
var _options$queryHash;
|
||||
|
||||
var queryKey = options.queryKey;
|
||||
var queryHash = (_options$queryHash = options.queryHash) != null ? _options$queryHash : (0, _utils.hashQueryKeyByOptions)(queryKey, options);
|
||||
var query = this.get(queryHash);
|
||||
|
||||
if (!query) {
|
||||
query = new _query.Query({
|
||||
cache: this,
|
||||
queryKey: queryKey,
|
||||
queryHash: queryHash,
|
||||
options: client.defaultQueryOptions(options),
|
||||
state: state,
|
||||
defaultOptions: client.getQueryDefaults(queryKey),
|
||||
meta: options.meta
|
||||
});
|
||||
this.add(query);
|
||||
}
|
||||
|
||||
return query;
|
||||
};
|
||||
|
||||
_proto.add = function add(query) {
|
||||
if (!this.queriesMap[query.queryHash]) {
|
||||
this.queriesMap[query.queryHash] = query;
|
||||
this.queries.push(query);
|
||||
this.notify({
|
||||
type: 'queryAdded',
|
||||
query: query
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
_proto.remove = function remove(query) {
|
||||
var queryInMap = this.queriesMap[query.queryHash];
|
||||
|
||||
if (queryInMap) {
|
||||
query.destroy();
|
||||
this.queries = this.queries.filter(function (x) {
|
||||
return x !== query;
|
||||
});
|
||||
|
||||
if (queryInMap === query) {
|
||||
delete this.queriesMap[query.queryHash];
|
||||
}
|
||||
|
||||
this.notify({
|
||||
type: 'queryRemoved',
|
||||
query: query
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
_proto.clear = function clear() {
|
||||
var _this2 = this;
|
||||
|
||||
_notifyManager.notifyManager.batch(function () {
|
||||
_this2.queries.forEach(function (query) {
|
||||
_this2.remove(query);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
_proto.get = function get(queryHash) {
|
||||
return this.queriesMap[queryHash];
|
||||
};
|
||||
|
||||
_proto.getAll = function getAll() {
|
||||
return this.queries;
|
||||
};
|
||||
|
||||
_proto.find = function find(arg1, arg2) {
|
||||
var _parseFilterArgs = (0, _utils.parseFilterArgs)(arg1, arg2),
|
||||
filters = _parseFilterArgs[0];
|
||||
|
||||
if (typeof filters.exact === 'undefined') {
|
||||
filters.exact = true;
|
||||
}
|
||||
|
||||
return this.queries.find(function (query) {
|
||||
return (0, _utils.matchQuery)(filters, query);
|
||||
});
|
||||
};
|
||||
|
||||
_proto.findAll = function findAll(arg1, arg2) {
|
||||
var _parseFilterArgs2 = (0, _utils.parseFilterArgs)(arg1, arg2),
|
||||
filters = _parseFilterArgs2[0];
|
||||
|
||||
return Object.keys(filters).length > 0 ? this.queries.filter(function (query) {
|
||||
return (0, _utils.matchQuery)(filters, query);
|
||||
}) : this.queries;
|
||||
};
|
||||
|
||||
_proto.notify = function notify(event) {
|
||||
var _this3 = this;
|
||||
|
||||
_notifyManager.notifyManager.batch(function () {
|
||||
_this3.listeners.forEach(function (listener) {
|
||||
listener(event);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
_proto.onFocus = function onFocus() {
|
||||
var _this4 = this;
|
||||
|
||||
_notifyManager.notifyManager.batch(function () {
|
||||
_this4.queries.forEach(function (query) {
|
||||
query.onFocus();
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
_proto.onOnline = function onOnline() {
|
||||
var _this5 = this;
|
||||
|
||||
_notifyManager.notifyManager.batch(function () {
|
||||
_this5.queries.forEach(function (query) {
|
||||
query.onOnline();
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
return QueryCache;
|
||||
}(_subscribable.Subscribable);
|
||||
|
||||
exports.QueryCache = QueryCache;
|
||||
+368
@@ -0,0 +1,368 @@
|
||||
"use strict";
|
||||
|
||||
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
|
||||
|
||||
exports.__esModule = true;
|
||||
exports.QueryClient = void 0;
|
||||
|
||||
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
|
||||
|
||||
var _utils = require("./utils");
|
||||
|
||||
var _queryCache = require("./queryCache");
|
||||
|
||||
var _mutationCache = require("./mutationCache");
|
||||
|
||||
var _focusManager = require("./focusManager");
|
||||
|
||||
var _onlineManager = require("./onlineManager");
|
||||
|
||||
var _notifyManager = require("./notifyManager");
|
||||
|
||||
var _infiniteQueryBehavior = require("./infiniteQueryBehavior");
|
||||
|
||||
// CLASS
|
||||
var QueryClient = /*#__PURE__*/function () {
|
||||
function QueryClient(config) {
|
||||
if (config === void 0) {
|
||||
config = {};
|
||||
}
|
||||
|
||||
this.queryCache = config.queryCache || new _queryCache.QueryCache();
|
||||
this.mutationCache = config.mutationCache || new _mutationCache.MutationCache();
|
||||
this.defaultOptions = config.defaultOptions || {};
|
||||
this.queryDefaults = [];
|
||||
this.mutationDefaults = [];
|
||||
}
|
||||
|
||||
var _proto = QueryClient.prototype;
|
||||
|
||||
_proto.mount = function mount() {
|
||||
var _this = this;
|
||||
|
||||
this.unsubscribeFocus = _focusManager.focusManager.subscribe(function () {
|
||||
if (_focusManager.focusManager.isFocused() && _onlineManager.onlineManager.isOnline()) {
|
||||
_this.mutationCache.onFocus();
|
||||
|
||||
_this.queryCache.onFocus();
|
||||
}
|
||||
});
|
||||
this.unsubscribeOnline = _onlineManager.onlineManager.subscribe(function () {
|
||||
if (_focusManager.focusManager.isFocused() && _onlineManager.onlineManager.isOnline()) {
|
||||
_this.mutationCache.onOnline();
|
||||
|
||||
_this.queryCache.onOnline();
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
_proto.unmount = function unmount() {
|
||||
var _this$unsubscribeFocu, _this$unsubscribeOnli;
|
||||
|
||||
(_this$unsubscribeFocu = this.unsubscribeFocus) == null ? void 0 : _this$unsubscribeFocu.call(this);
|
||||
(_this$unsubscribeOnli = this.unsubscribeOnline) == null ? void 0 : _this$unsubscribeOnli.call(this);
|
||||
};
|
||||
|
||||
_proto.isFetching = function isFetching(arg1, arg2) {
|
||||
var _parseFilterArgs = (0, _utils.parseFilterArgs)(arg1, arg2),
|
||||
filters = _parseFilterArgs[0];
|
||||
|
||||
filters.fetching = true;
|
||||
return this.queryCache.findAll(filters).length;
|
||||
};
|
||||
|
||||
_proto.isMutating = function isMutating(filters) {
|
||||
return this.mutationCache.findAll((0, _extends2.default)({}, filters, {
|
||||
fetching: true
|
||||
})).length;
|
||||
};
|
||||
|
||||
_proto.getQueryData = function getQueryData(queryKey, filters) {
|
||||
var _this$queryCache$find;
|
||||
|
||||
return (_this$queryCache$find = this.queryCache.find(queryKey, filters)) == null ? void 0 : _this$queryCache$find.state.data;
|
||||
};
|
||||
|
||||
_proto.getQueriesData = function getQueriesData(queryKeyOrFilters) {
|
||||
return this.getQueryCache().findAll(queryKeyOrFilters).map(function (_ref) {
|
||||
var queryKey = _ref.queryKey,
|
||||
state = _ref.state;
|
||||
var data = state.data;
|
||||
return [queryKey, data];
|
||||
});
|
||||
};
|
||||
|
||||
_proto.setQueryData = function setQueryData(queryKey, updater, options) {
|
||||
var parsedOptions = (0, _utils.parseQueryArgs)(queryKey);
|
||||
var defaultedOptions = this.defaultQueryOptions(parsedOptions);
|
||||
return this.queryCache.build(this, defaultedOptions).setData(updater, options);
|
||||
};
|
||||
|
||||
_proto.setQueriesData = function setQueriesData(queryKeyOrFilters, updater, options) {
|
||||
var _this2 = this;
|
||||
|
||||
return _notifyManager.notifyManager.batch(function () {
|
||||
return _this2.getQueryCache().findAll(queryKeyOrFilters).map(function (_ref2) {
|
||||
var queryKey = _ref2.queryKey;
|
||||
return [queryKey, _this2.setQueryData(queryKey, updater, options)];
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
_proto.getQueryState = function getQueryState(queryKey, filters) {
|
||||
var _this$queryCache$find2;
|
||||
|
||||
return (_this$queryCache$find2 = this.queryCache.find(queryKey, filters)) == null ? void 0 : _this$queryCache$find2.state;
|
||||
};
|
||||
|
||||
_proto.removeQueries = function removeQueries(arg1, arg2) {
|
||||
var _parseFilterArgs2 = (0, _utils.parseFilterArgs)(arg1, arg2),
|
||||
filters = _parseFilterArgs2[0];
|
||||
|
||||
var queryCache = this.queryCache;
|
||||
|
||||
_notifyManager.notifyManager.batch(function () {
|
||||
queryCache.findAll(filters).forEach(function (query) {
|
||||
queryCache.remove(query);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
_proto.resetQueries = function resetQueries(arg1, arg2, arg3) {
|
||||
var _this3 = this;
|
||||
|
||||
var _parseFilterArgs3 = (0, _utils.parseFilterArgs)(arg1, arg2, arg3),
|
||||
filters = _parseFilterArgs3[0],
|
||||
options = _parseFilterArgs3[1];
|
||||
|
||||
var queryCache = this.queryCache;
|
||||
var refetchFilters = (0, _extends2.default)({}, filters, {
|
||||
active: true
|
||||
});
|
||||
return _notifyManager.notifyManager.batch(function () {
|
||||
queryCache.findAll(filters).forEach(function (query) {
|
||||
query.reset();
|
||||
});
|
||||
return _this3.refetchQueries(refetchFilters, options);
|
||||
});
|
||||
};
|
||||
|
||||
_proto.cancelQueries = function cancelQueries(arg1, arg2, arg3) {
|
||||
var _this4 = this;
|
||||
|
||||
var _parseFilterArgs4 = (0, _utils.parseFilterArgs)(arg1, arg2, arg3),
|
||||
filters = _parseFilterArgs4[0],
|
||||
_parseFilterArgs4$ = _parseFilterArgs4[1],
|
||||
cancelOptions = _parseFilterArgs4$ === void 0 ? {} : _parseFilterArgs4$;
|
||||
|
||||
if (typeof cancelOptions.revert === 'undefined') {
|
||||
cancelOptions.revert = true;
|
||||
}
|
||||
|
||||
var promises = _notifyManager.notifyManager.batch(function () {
|
||||
return _this4.queryCache.findAll(filters).map(function (query) {
|
||||
return query.cancel(cancelOptions);
|
||||
});
|
||||
});
|
||||
|
||||
return Promise.all(promises).then(_utils.noop).catch(_utils.noop);
|
||||
};
|
||||
|
||||
_proto.invalidateQueries = function invalidateQueries(arg1, arg2, arg3) {
|
||||
var _ref3,
|
||||
_filters$refetchActiv,
|
||||
_filters$refetchInact,
|
||||
_this5 = this;
|
||||
|
||||
var _parseFilterArgs5 = (0, _utils.parseFilterArgs)(arg1, arg2, arg3),
|
||||
filters = _parseFilterArgs5[0],
|
||||
options = _parseFilterArgs5[1];
|
||||
|
||||
var refetchFilters = (0, _extends2.default)({}, filters, {
|
||||
// if filters.refetchActive is not provided and filters.active is explicitly false,
|
||||
// e.g. invalidateQueries({ active: false }), we don't want to refetch active queries
|
||||
active: (_ref3 = (_filters$refetchActiv = filters.refetchActive) != null ? _filters$refetchActiv : filters.active) != null ? _ref3 : true,
|
||||
inactive: (_filters$refetchInact = filters.refetchInactive) != null ? _filters$refetchInact : false
|
||||
});
|
||||
return _notifyManager.notifyManager.batch(function () {
|
||||
_this5.queryCache.findAll(filters).forEach(function (query) {
|
||||
query.invalidate();
|
||||
});
|
||||
|
||||
return _this5.refetchQueries(refetchFilters, options);
|
||||
});
|
||||
};
|
||||
|
||||
_proto.refetchQueries = function refetchQueries(arg1, arg2, arg3) {
|
||||
var _this6 = this;
|
||||
|
||||
var _parseFilterArgs6 = (0, _utils.parseFilterArgs)(arg1, arg2, arg3),
|
||||
filters = _parseFilterArgs6[0],
|
||||
options = _parseFilterArgs6[1];
|
||||
|
||||
var promises = _notifyManager.notifyManager.batch(function () {
|
||||
return _this6.queryCache.findAll(filters).map(function (query) {
|
||||
return query.fetch(undefined, (0, _extends2.default)({}, options, {
|
||||
meta: {
|
||||
refetchPage: filters == null ? void 0 : filters.refetchPage
|
||||
}
|
||||
}));
|
||||
});
|
||||
});
|
||||
|
||||
var promise = Promise.all(promises).then(_utils.noop);
|
||||
|
||||
if (!(options == null ? void 0 : options.throwOnError)) {
|
||||
promise = promise.catch(_utils.noop);
|
||||
}
|
||||
|
||||
return promise;
|
||||
};
|
||||
|
||||
_proto.fetchQuery = function fetchQuery(arg1, arg2, arg3) {
|
||||
var parsedOptions = (0, _utils.parseQueryArgs)(arg1, arg2, arg3);
|
||||
var defaultedOptions = this.defaultQueryOptions(parsedOptions); // https://github.com/tannerlinsley/react-query/issues/652
|
||||
|
||||
if (typeof defaultedOptions.retry === 'undefined') {
|
||||
defaultedOptions.retry = false;
|
||||
}
|
||||
|
||||
var query = this.queryCache.build(this, defaultedOptions);
|
||||
return query.isStaleByTime(defaultedOptions.staleTime) ? query.fetch(defaultedOptions) : Promise.resolve(query.state.data);
|
||||
};
|
||||
|
||||
_proto.prefetchQuery = function prefetchQuery(arg1, arg2, arg3) {
|
||||
return this.fetchQuery(arg1, arg2, arg3).then(_utils.noop).catch(_utils.noop);
|
||||
};
|
||||
|
||||
_proto.fetchInfiniteQuery = function fetchInfiniteQuery(arg1, arg2, arg3) {
|
||||
var parsedOptions = (0, _utils.parseQueryArgs)(arg1, arg2, arg3);
|
||||
parsedOptions.behavior = (0, _infiniteQueryBehavior.infiniteQueryBehavior)();
|
||||
return this.fetchQuery(parsedOptions);
|
||||
};
|
||||
|
||||
_proto.prefetchInfiniteQuery = function prefetchInfiniteQuery(arg1, arg2, arg3) {
|
||||
return this.fetchInfiniteQuery(arg1, arg2, arg3).then(_utils.noop).catch(_utils.noop);
|
||||
};
|
||||
|
||||
_proto.cancelMutations = function cancelMutations() {
|
||||
var _this7 = this;
|
||||
|
||||
var promises = _notifyManager.notifyManager.batch(function () {
|
||||
return _this7.mutationCache.getAll().map(function (mutation) {
|
||||
return mutation.cancel();
|
||||
});
|
||||
});
|
||||
|
||||
return Promise.all(promises).then(_utils.noop).catch(_utils.noop);
|
||||
};
|
||||
|
||||
_proto.resumePausedMutations = function resumePausedMutations() {
|
||||
return this.getMutationCache().resumePausedMutations();
|
||||
};
|
||||
|
||||
_proto.executeMutation = function executeMutation(options) {
|
||||
return this.mutationCache.build(this, options).execute();
|
||||
};
|
||||
|
||||
_proto.getQueryCache = function getQueryCache() {
|
||||
return this.queryCache;
|
||||
};
|
||||
|
||||
_proto.getMutationCache = function getMutationCache() {
|
||||
return this.mutationCache;
|
||||
};
|
||||
|
||||
_proto.getDefaultOptions = function getDefaultOptions() {
|
||||
return this.defaultOptions;
|
||||
};
|
||||
|
||||
_proto.setDefaultOptions = function setDefaultOptions(options) {
|
||||
this.defaultOptions = options;
|
||||
};
|
||||
|
||||
_proto.setQueryDefaults = function setQueryDefaults(queryKey, options) {
|
||||
var result = this.queryDefaults.find(function (x) {
|
||||
return (0, _utils.hashQueryKey)(queryKey) === (0, _utils.hashQueryKey)(x.queryKey);
|
||||
});
|
||||
|
||||
if (result) {
|
||||
result.defaultOptions = options;
|
||||
} else {
|
||||
this.queryDefaults.push({
|
||||
queryKey: queryKey,
|
||||
defaultOptions: options
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
_proto.getQueryDefaults = function getQueryDefaults(queryKey) {
|
||||
var _this$queryDefaults$f;
|
||||
|
||||
return queryKey ? (_this$queryDefaults$f = this.queryDefaults.find(function (x) {
|
||||
return (0, _utils.partialMatchKey)(queryKey, x.queryKey);
|
||||
})) == null ? void 0 : _this$queryDefaults$f.defaultOptions : undefined;
|
||||
};
|
||||
|
||||
_proto.setMutationDefaults = function setMutationDefaults(mutationKey, options) {
|
||||
var result = this.mutationDefaults.find(function (x) {
|
||||
return (0, _utils.hashQueryKey)(mutationKey) === (0, _utils.hashQueryKey)(x.mutationKey);
|
||||
});
|
||||
|
||||
if (result) {
|
||||
result.defaultOptions = options;
|
||||
} else {
|
||||
this.mutationDefaults.push({
|
||||
mutationKey: mutationKey,
|
||||
defaultOptions: options
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
_proto.getMutationDefaults = function getMutationDefaults(mutationKey) {
|
||||
var _this$mutationDefault;
|
||||
|
||||
return mutationKey ? (_this$mutationDefault = this.mutationDefaults.find(function (x) {
|
||||
return (0, _utils.partialMatchKey)(mutationKey, x.mutationKey);
|
||||
})) == null ? void 0 : _this$mutationDefault.defaultOptions : undefined;
|
||||
};
|
||||
|
||||
_proto.defaultQueryOptions = function defaultQueryOptions(options) {
|
||||
if (options == null ? void 0 : options._defaulted) {
|
||||
return options;
|
||||
}
|
||||
|
||||
var defaultedOptions = (0, _extends2.default)({}, this.defaultOptions.queries, this.getQueryDefaults(options == null ? void 0 : options.queryKey), options, {
|
||||
_defaulted: true
|
||||
});
|
||||
|
||||
if (!defaultedOptions.queryHash && defaultedOptions.queryKey) {
|
||||
defaultedOptions.queryHash = (0, _utils.hashQueryKeyByOptions)(defaultedOptions.queryKey, defaultedOptions);
|
||||
}
|
||||
|
||||
return defaultedOptions;
|
||||
};
|
||||
|
||||
_proto.defaultQueryObserverOptions = function defaultQueryObserverOptions(options) {
|
||||
return this.defaultQueryOptions(options);
|
||||
};
|
||||
|
||||
_proto.defaultMutationOptions = function defaultMutationOptions(options) {
|
||||
if (options == null ? void 0 : options._defaulted) {
|
||||
return options;
|
||||
}
|
||||
|
||||
return (0, _extends2.default)({}, this.defaultOptions.mutations, this.getMutationDefaults(options == null ? void 0 : options.mutationKey), options, {
|
||||
_defaulted: true
|
||||
});
|
||||
};
|
||||
|
||||
_proto.clear = function clear() {
|
||||
this.queryCache.clear();
|
||||
this.mutationCache.clear();
|
||||
};
|
||||
|
||||
return QueryClient;
|
||||
}();
|
||||
|
||||
exports.QueryClient = QueryClient;
|
||||
+566
@@ -0,0 +1,566 @@
|
||||
"use strict";
|
||||
|
||||
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
|
||||
|
||||
exports.__esModule = true;
|
||||
exports.QueryObserver = void 0;
|
||||
|
||||
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
|
||||
|
||||
var _inheritsLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/inheritsLoose"));
|
||||
|
||||
var _utils = require("./utils");
|
||||
|
||||
var _notifyManager = require("./notifyManager");
|
||||
|
||||
var _focusManager = require("./focusManager");
|
||||
|
||||
var _subscribable = require("./subscribable");
|
||||
|
||||
var _logger = require("./logger");
|
||||
|
||||
var _retryer = require("./retryer");
|
||||
|
||||
var QueryObserver = /*#__PURE__*/function (_Subscribable) {
|
||||
(0, _inheritsLoose2.default)(QueryObserver, _Subscribable);
|
||||
|
||||
function QueryObserver(client, options) {
|
||||
var _this;
|
||||
|
||||
_this = _Subscribable.call(this) || this;
|
||||
_this.client = client;
|
||||
_this.options = options;
|
||||
_this.trackedProps = [];
|
||||
_this.selectError = null;
|
||||
|
||||
_this.bindMethods();
|
||||
|
||||
_this.setOptions(options);
|
||||
|
||||
return _this;
|
||||
}
|
||||
|
||||
var _proto = QueryObserver.prototype;
|
||||
|
||||
_proto.bindMethods = function bindMethods() {
|
||||
this.remove = this.remove.bind(this);
|
||||
this.refetch = this.refetch.bind(this);
|
||||
};
|
||||
|
||||
_proto.onSubscribe = function onSubscribe() {
|
||||
if (this.listeners.length === 1) {
|
||||
this.currentQuery.addObserver(this);
|
||||
|
||||
if (shouldFetchOnMount(this.currentQuery, this.options)) {
|
||||
this.executeFetch();
|
||||
}
|
||||
|
||||
this.updateTimers();
|
||||
}
|
||||
};
|
||||
|
||||
_proto.onUnsubscribe = function onUnsubscribe() {
|
||||
if (!this.listeners.length) {
|
||||
this.destroy();
|
||||
}
|
||||
};
|
||||
|
||||
_proto.shouldFetchOnReconnect = function shouldFetchOnReconnect() {
|
||||
return shouldFetchOn(this.currentQuery, this.options, this.options.refetchOnReconnect);
|
||||
};
|
||||
|
||||
_proto.shouldFetchOnWindowFocus = function shouldFetchOnWindowFocus() {
|
||||
return shouldFetchOn(this.currentQuery, this.options, this.options.refetchOnWindowFocus);
|
||||
};
|
||||
|
||||
_proto.destroy = function destroy() {
|
||||
this.listeners = [];
|
||||
this.clearTimers();
|
||||
this.currentQuery.removeObserver(this);
|
||||
};
|
||||
|
||||
_proto.setOptions = function setOptions(options, notifyOptions) {
|
||||
var prevOptions = this.options;
|
||||
var prevQuery = this.currentQuery;
|
||||
this.options = this.client.defaultQueryObserverOptions(options);
|
||||
|
||||
if (typeof this.options.enabled !== 'undefined' && typeof this.options.enabled !== 'boolean') {
|
||||
throw new Error('Expected enabled to be a boolean');
|
||||
} // Keep previous query key if the user does not supply one
|
||||
|
||||
|
||||
if (!this.options.queryKey) {
|
||||
this.options.queryKey = prevOptions.queryKey;
|
||||
}
|
||||
|
||||
this.updateQuery();
|
||||
var mounted = this.hasListeners(); // Fetch if there are subscribers
|
||||
|
||||
if (mounted && shouldFetchOptionally(this.currentQuery, prevQuery, this.options, prevOptions)) {
|
||||
this.executeFetch();
|
||||
} // Update result
|
||||
|
||||
|
||||
this.updateResult(notifyOptions); // Update stale interval if needed
|
||||
|
||||
if (mounted && (this.currentQuery !== prevQuery || this.options.enabled !== prevOptions.enabled || this.options.staleTime !== prevOptions.staleTime)) {
|
||||
this.updateStaleTimeout();
|
||||
}
|
||||
|
||||
var nextRefetchInterval = this.computeRefetchInterval(); // Update refetch interval if needed
|
||||
|
||||
if (mounted && (this.currentQuery !== prevQuery || this.options.enabled !== prevOptions.enabled || nextRefetchInterval !== this.currentRefetchInterval)) {
|
||||
this.updateRefetchInterval(nextRefetchInterval);
|
||||
}
|
||||
};
|
||||
|
||||
_proto.getOptimisticResult = function getOptimisticResult(options) {
|
||||
var defaultedOptions = this.client.defaultQueryObserverOptions(options);
|
||||
var query = this.client.getQueryCache().build(this.client, defaultedOptions);
|
||||
return this.createResult(query, defaultedOptions);
|
||||
};
|
||||
|
||||
_proto.getCurrentResult = function getCurrentResult() {
|
||||
return this.currentResult;
|
||||
};
|
||||
|
||||
_proto.trackResult = function trackResult(result, defaultedOptions) {
|
||||
var _this2 = this;
|
||||
|
||||
var trackedResult = {};
|
||||
|
||||
var trackProp = function trackProp(key) {
|
||||
if (!_this2.trackedProps.includes(key)) {
|
||||
_this2.trackedProps.push(key);
|
||||
}
|
||||
};
|
||||
|
||||
Object.keys(result).forEach(function (key) {
|
||||
Object.defineProperty(trackedResult, key, {
|
||||
configurable: false,
|
||||
enumerable: true,
|
||||
get: function get() {
|
||||
trackProp(key);
|
||||
return result[key];
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
if (defaultedOptions.useErrorBoundary || defaultedOptions.suspense) {
|
||||
trackProp('error');
|
||||
}
|
||||
|
||||
return trackedResult;
|
||||
};
|
||||
|
||||
_proto.getNextResult = function getNextResult(options) {
|
||||
var _this3 = this;
|
||||
|
||||
return new Promise(function (resolve, reject) {
|
||||
var unsubscribe = _this3.subscribe(function (result) {
|
||||
if (!result.isFetching) {
|
||||
unsubscribe();
|
||||
|
||||
if (result.isError && (options == null ? void 0 : options.throwOnError)) {
|
||||
reject(result.error);
|
||||
} else {
|
||||
resolve(result);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
_proto.getCurrentQuery = function getCurrentQuery() {
|
||||
return this.currentQuery;
|
||||
};
|
||||
|
||||
_proto.remove = function remove() {
|
||||
this.client.getQueryCache().remove(this.currentQuery);
|
||||
};
|
||||
|
||||
_proto.refetch = function refetch(options) {
|
||||
return this.fetch((0, _extends2.default)({}, options, {
|
||||
meta: {
|
||||
refetchPage: options == null ? void 0 : options.refetchPage
|
||||
}
|
||||
}));
|
||||
};
|
||||
|
||||
_proto.fetchOptimistic = function fetchOptimistic(options) {
|
||||
var _this4 = this;
|
||||
|
||||
var defaultedOptions = this.client.defaultQueryObserverOptions(options);
|
||||
var query = this.client.getQueryCache().build(this.client, defaultedOptions);
|
||||
return query.fetch().then(function () {
|
||||
return _this4.createResult(query, defaultedOptions);
|
||||
});
|
||||
};
|
||||
|
||||
_proto.fetch = function fetch(fetchOptions) {
|
||||
var _this5 = this;
|
||||
|
||||
return this.executeFetch(fetchOptions).then(function () {
|
||||
_this5.updateResult();
|
||||
|
||||
return _this5.currentResult;
|
||||
});
|
||||
};
|
||||
|
||||
_proto.executeFetch = function executeFetch(fetchOptions) {
|
||||
// Make sure we reference the latest query as the current one might have been removed
|
||||
this.updateQuery(); // Fetch
|
||||
|
||||
var promise = this.currentQuery.fetch(this.options, fetchOptions);
|
||||
|
||||
if (!(fetchOptions == null ? void 0 : fetchOptions.throwOnError)) {
|
||||
promise = promise.catch(_utils.noop);
|
||||
}
|
||||
|
||||
return promise;
|
||||
};
|
||||
|
||||
_proto.updateStaleTimeout = function updateStaleTimeout() {
|
||||
var _this6 = this;
|
||||
|
||||
this.clearStaleTimeout();
|
||||
|
||||
if (_utils.isServer || this.currentResult.isStale || !(0, _utils.isValidTimeout)(this.options.staleTime)) {
|
||||
return;
|
||||
}
|
||||
|
||||
var time = (0, _utils.timeUntilStale)(this.currentResult.dataUpdatedAt, this.options.staleTime); // The timeout is sometimes triggered 1 ms before the stale time expiration.
|
||||
// To mitigate this issue we always add 1 ms to the timeout.
|
||||
|
||||
var timeout = time + 1;
|
||||
this.staleTimeoutId = setTimeout(function () {
|
||||
if (!_this6.currentResult.isStale) {
|
||||
_this6.updateResult();
|
||||
}
|
||||
}, timeout);
|
||||
};
|
||||
|
||||
_proto.computeRefetchInterval = function computeRefetchInterval() {
|
||||
var _this$options$refetch;
|
||||
|
||||
return typeof this.options.refetchInterval === 'function' ? this.options.refetchInterval(this.currentResult.data, this.currentQuery) : (_this$options$refetch = this.options.refetchInterval) != null ? _this$options$refetch : false;
|
||||
};
|
||||
|
||||
_proto.updateRefetchInterval = function updateRefetchInterval(nextInterval) {
|
||||
var _this7 = this;
|
||||
|
||||
this.clearRefetchInterval();
|
||||
this.currentRefetchInterval = nextInterval;
|
||||
|
||||
if (_utils.isServer || this.options.enabled === false || !(0, _utils.isValidTimeout)(this.currentRefetchInterval) || this.currentRefetchInterval === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.refetchIntervalId = setInterval(function () {
|
||||
if (_this7.options.refetchIntervalInBackground || _focusManager.focusManager.isFocused()) {
|
||||
_this7.executeFetch();
|
||||
}
|
||||
}, this.currentRefetchInterval);
|
||||
};
|
||||
|
||||
_proto.updateTimers = function updateTimers() {
|
||||
this.updateStaleTimeout();
|
||||
this.updateRefetchInterval(this.computeRefetchInterval());
|
||||
};
|
||||
|
||||
_proto.clearTimers = function clearTimers() {
|
||||
this.clearStaleTimeout();
|
||||
this.clearRefetchInterval();
|
||||
};
|
||||
|
||||
_proto.clearStaleTimeout = function clearStaleTimeout() {
|
||||
if (this.staleTimeoutId) {
|
||||
clearTimeout(this.staleTimeoutId);
|
||||
this.staleTimeoutId = undefined;
|
||||
}
|
||||
};
|
||||
|
||||
_proto.clearRefetchInterval = function clearRefetchInterval() {
|
||||
if (this.refetchIntervalId) {
|
||||
clearInterval(this.refetchIntervalId);
|
||||
this.refetchIntervalId = undefined;
|
||||
}
|
||||
};
|
||||
|
||||
_proto.createResult = function createResult(query, options) {
|
||||
var prevQuery = this.currentQuery;
|
||||
var prevOptions = this.options;
|
||||
var prevResult = this.currentResult;
|
||||
var prevResultState = this.currentResultState;
|
||||
var prevResultOptions = this.currentResultOptions;
|
||||
var queryChange = query !== prevQuery;
|
||||
var queryInitialState = queryChange ? query.state : this.currentQueryInitialState;
|
||||
var prevQueryResult = queryChange ? this.currentResult : this.previousQueryResult;
|
||||
var state = query.state;
|
||||
var dataUpdatedAt = state.dataUpdatedAt,
|
||||
error = state.error,
|
||||
errorUpdatedAt = state.errorUpdatedAt,
|
||||
isFetching = state.isFetching,
|
||||
status = state.status;
|
||||
var isPreviousData = false;
|
||||
var isPlaceholderData = false;
|
||||
var data; // Optimistically set result in fetching state if needed
|
||||
|
||||
if (options.optimisticResults) {
|
||||
var mounted = this.hasListeners();
|
||||
var fetchOnMount = !mounted && shouldFetchOnMount(query, options);
|
||||
var fetchOptionally = mounted && shouldFetchOptionally(query, prevQuery, options, prevOptions);
|
||||
|
||||
if (fetchOnMount || fetchOptionally) {
|
||||
isFetching = true;
|
||||
|
||||
if (!dataUpdatedAt) {
|
||||
status = 'loading';
|
||||
}
|
||||
}
|
||||
} // Keep previous data if needed
|
||||
|
||||
|
||||
if (options.keepPreviousData && !state.dataUpdateCount && (prevQueryResult == null ? void 0 : prevQueryResult.isSuccess) && status !== 'error') {
|
||||
data = prevQueryResult.data;
|
||||
dataUpdatedAt = prevQueryResult.dataUpdatedAt;
|
||||
status = prevQueryResult.status;
|
||||
isPreviousData = true;
|
||||
} // Select data if needed
|
||||
else if (options.select && typeof state.data !== 'undefined') {
|
||||
// Memoize select result
|
||||
if (prevResult && state.data === (prevResultState == null ? void 0 : prevResultState.data) && options.select === this.selectFn) {
|
||||
data = this.selectResult;
|
||||
} else {
|
||||
try {
|
||||
this.selectFn = options.select;
|
||||
data = options.select(state.data);
|
||||
|
||||
if (options.structuralSharing !== false) {
|
||||
data = (0, _utils.replaceEqualDeep)(prevResult == null ? void 0 : prevResult.data, data);
|
||||
}
|
||||
|
||||
this.selectResult = data;
|
||||
this.selectError = null;
|
||||
} catch (selectError) {
|
||||
(0, _logger.getLogger)().error(selectError);
|
||||
this.selectError = selectError;
|
||||
}
|
||||
}
|
||||
} // Use query data
|
||||
else {
|
||||
data = state.data;
|
||||
} // Show placeholder data if needed
|
||||
|
||||
|
||||
if (typeof options.placeholderData !== 'undefined' && typeof data === 'undefined' && (status === 'loading' || status === 'idle')) {
|
||||
var placeholderData; // Memoize placeholder data
|
||||
|
||||
if ((prevResult == null ? void 0 : prevResult.isPlaceholderData) && options.placeholderData === (prevResultOptions == null ? void 0 : prevResultOptions.placeholderData)) {
|
||||
placeholderData = prevResult.data;
|
||||
} else {
|
||||
placeholderData = typeof options.placeholderData === 'function' ? options.placeholderData() : options.placeholderData;
|
||||
|
||||
if (options.select && typeof placeholderData !== 'undefined') {
|
||||
try {
|
||||
placeholderData = options.select(placeholderData);
|
||||
|
||||
if (options.structuralSharing !== false) {
|
||||
placeholderData = (0, _utils.replaceEqualDeep)(prevResult == null ? void 0 : prevResult.data, placeholderData);
|
||||
}
|
||||
|
||||
this.selectError = null;
|
||||
} catch (selectError) {
|
||||
(0, _logger.getLogger)().error(selectError);
|
||||
this.selectError = selectError;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof placeholderData !== 'undefined') {
|
||||
status = 'success';
|
||||
data = placeholderData;
|
||||
isPlaceholderData = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (this.selectError) {
|
||||
error = this.selectError;
|
||||
data = this.selectResult;
|
||||
errorUpdatedAt = Date.now();
|
||||
status = 'error';
|
||||
}
|
||||
|
||||
var result = {
|
||||
status: status,
|
||||
isLoading: status === 'loading',
|
||||
isSuccess: status === 'success',
|
||||
isError: status === 'error',
|
||||
isIdle: status === 'idle',
|
||||
data: data,
|
||||
dataUpdatedAt: dataUpdatedAt,
|
||||
error: error,
|
||||
errorUpdatedAt: errorUpdatedAt,
|
||||
failureCount: state.fetchFailureCount,
|
||||
errorUpdateCount: state.errorUpdateCount,
|
||||
isFetched: state.dataUpdateCount > 0 || state.errorUpdateCount > 0,
|
||||
isFetchedAfterMount: state.dataUpdateCount > queryInitialState.dataUpdateCount || state.errorUpdateCount > queryInitialState.errorUpdateCount,
|
||||
isFetching: isFetching,
|
||||
isRefetching: isFetching && status !== 'loading',
|
||||
isLoadingError: status === 'error' && state.dataUpdatedAt === 0,
|
||||
isPlaceholderData: isPlaceholderData,
|
||||
isPreviousData: isPreviousData,
|
||||
isRefetchError: status === 'error' && state.dataUpdatedAt !== 0,
|
||||
isStale: isStale(query, options),
|
||||
refetch: this.refetch,
|
||||
remove: this.remove
|
||||
};
|
||||
return result;
|
||||
};
|
||||
|
||||
_proto.shouldNotifyListeners = function shouldNotifyListeners(result, prevResult) {
|
||||
if (!prevResult) {
|
||||
return true;
|
||||
}
|
||||
|
||||
var _this$options = this.options,
|
||||
notifyOnChangeProps = _this$options.notifyOnChangeProps,
|
||||
notifyOnChangePropsExclusions = _this$options.notifyOnChangePropsExclusions;
|
||||
|
||||
if (!notifyOnChangeProps && !notifyOnChangePropsExclusions) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (notifyOnChangeProps === 'tracked' && !this.trackedProps.length) {
|
||||
return true;
|
||||
}
|
||||
|
||||
var includedProps = notifyOnChangeProps === 'tracked' ? this.trackedProps : notifyOnChangeProps;
|
||||
return Object.keys(result).some(function (key) {
|
||||
var typedKey = key;
|
||||
var changed = result[typedKey] !== prevResult[typedKey];
|
||||
var isIncluded = includedProps == null ? void 0 : includedProps.some(function (x) {
|
||||
return x === key;
|
||||
});
|
||||
var isExcluded = notifyOnChangePropsExclusions == null ? void 0 : notifyOnChangePropsExclusions.some(function (x) {
|
||||
return x === key;
|
||||
});
|
||||
return changed && !isExcluded && (!includedProps || isIncluded);
|
||||
});
|
||||
};
|
||||
|
||||
_proto.updateResult = function updateResult(notifyOptions) {
|
||||
var prevResult = this.currentResult;
|
||||
this.currentResult = this.createResult(this.currentQuery, this.options);
|
||||
this.currentResultState = this.currentQuery.state;
|
||||
this.currentResultOptions = this.options; // Only notify if something has changed
|
||||
|
||||
if ((0, _utils.shallowEqualObjects)(this.currentResult, prevResult)) {
|
||||
return;
|
||||
} // Determine which callbacks to trigger
|
||||
|
||||
|
||||
var defaultNotifyOptions = {
|
||||
cache: true
|
||||
};
|
||||
|
||||
if ((notifyOptions == null ? void 0 : notifyOptions.listeners) !== false && this.shouldNotifyListeners(this.currentResult, prevResult)) {
|
||||
defaultNotifyOptions.listeners = true;
|
||||
}
|
||||
|
||||
this.notify((0, _extends2.default)({}, defaultNotifyOptions, notifyOptions));
|
||||
};
|
||||
|
||||
_proto.updateQuery = function updateQuery() {
|
||||
var query = this.client.getQueryCache().build(this.client, this.options);
|
||||
|
||||
if (query === this.currentQuery) {
|
||||
return;
|
||||
}
|
||||
|
||||
var prevQuery = this.currentQuery;
|
||||
this.currentQuery = query;
|
||||
this.currentQueryInitialState = query.state;
|
||||
this.previousQueryResult = this.currentResult;
|
||||
|
||||
if (this.hasListeners()) {
|
||||
prevQuery == null ? void 0 : prevQuery.removeObserver(this);
|
||||
query.addObserver(this);
|
||||
}
|
||||
};
|
||||
|
||||
_proto.onQueryUpdate = function onQueryUpdate(action) {
|
||||
var notifyOptions = {};
|
||||
|
||||
if (action.type === 'success') {
|
||||
notifyOptions.onSuccess = true;
|
||||
} else if (action.type === 'error' && !(0, _retryer.isCancelledError)(action.error)) {
|
||||
notifyOptions.onError = true;
|
||||
}
|
||||
|
||||
this.updateResult(notifyOptions);
|
||||
|
||||
if (this.hasListeners()) {
|
||||
this.updateTimers();
|
||||
}
|
||||
};
|
||||
|
||||
_proto.notify = function notify(notifyOptions) {
|
||||
var _this8 = this;
|
||||
|
||||
_notifyManager.notifyManager.batch(function () {
|
||||
// First trigger the configuration callbacks
|
||||
if (notifyOptions.onSuccess) {
|
||||
_this8.options.onSuccess == null ? void 0 : _this8.options.onSuccess(_this8.currentResult.data);
|
||||
_this8.options.onSettled == null ? void 0 : _this8.options.onSettled(_this8.currentResult.data, null);
|
||||
} else if (notifyOptions.onError) {
|
||||
_this8.options.onError == null ? void 0 : _this8.options.onError(_this8.currentResult.error);
|
||||
_this8.options.onSettled == null ? void 0 : _this8.options.onSettled(undefined, _this8.currentResult.error);
|
||||
} // Then trigger the listeners
|
||||
|
||||
|
||||
if (notifyOptions.listeners) {
|
||||
_this8.listeners.forEach(function (listener) {
|
||||
listener(_this8.currentResult);
|
||||
});
|
||||
} // Then the cache listeners
|
||||
|
||||
|
||||
if (notifyOptions.cache) {
|
||||
_this8.client.getQueryCache().notify({
|
||||
query: _this8.currentQuery,
|
||||
type: 'observerResultsUpdated'
|
||||
});
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
return QueryObserver;
|
||||
}(_subscribable.Subscribable);
|
||||
|
||||
exports.QueryObserver = QueryObserver;
|
||||
|
||||
function shouldLoadOnMount(query, options) {
|
||||
return options.enabled !== false && !query.state.dataUpdatedAt && !(query.state.status === 'error' && options.retryOnMount === false);
|
||||
}
|
||||
|
||||
function shouldFetchOnMount(query, options) {
|
||||
return shouldLoadOnMount(query, options) || query.state.dataUpdatedAt > 0 && shouldFetchOn(query, options, options.refetchOnMount);
|
||||
}
|
||||
|
||||
function shouldFetchOn(query, options, field) {
|
||||
if (options.enabled !== false) {
|
||||
var value = typeof field === 'function' ? field(query) : field;
|
||||
return value === 'always' || value !== false && isStale(query, options);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
function shouldFetchOptionally(query, prevQuery, options, prevOptions) {
|
||||
return options.enabled !== false && (query !== prevQuery || prevOptions.enabled === false) && (!options.suspense || query.state.status !== 'error') && isStale(query, options);
|
||||
}
|
||||
|
||||
function isStale(query, options) {
|
||||
return query.isStaleByTime(options.staleTime);
|
||||
}
|
||||
+173
@@ -0,0 +1,173 @@
|
||||
"use strict";
|
||||
|
||||
exports.__esModule = true;
|
||||
exports.isCancelable = isCancelable;
|
||||
exports.isCancelledError = isCancelledError;
|
||||
exports.Retryer = exports.CancelledError = void 0;
|
||||
|
||||
var _focusManager = require("./focusManager");
|
||||
|
||||
var _onlineManager = require("./onlineManager");
|
||||
|
||||
var _utils = require("./utils");
|
||||
|
||||
function defaultRetryDelay(failureCount) {
|
||||
return Math.min(1000 * Math.pow(2, failureCount), 30000);
|
||||
}
|
||||
|
||||
function isCancelable(value) {
|
||||
return typeof (value == null ? void 0 : value.cancel) === 'function';
|
||||
}
|
||||
|
||||
var CancelledError = function CancelledError(options) {
|
||||
this.revert = options == null ? void 0 : options.revert;
|
||||
this.silent = options == null ? void 0 : options.silent;
|
||||
};
|
||||
|
||||
exports.CancelledError = CancelledError;
|
||||
|
||||
function isCancelledError(value) {
|
||||
return value instanceof CancelledError;
|
||||
} // CLASS
|
||||
|
||||
|
||||
var Retryer = function Retryer(config) {
|
||||
var _this = this;
|
||||
|
||||
var cancelRetry = false;
|
||||
var cancelFn;
|
||||
var continueFn;
|
||||
var promiseResolve;
|
||||
var promiseReject;
|
||||
this.abort = config.abort;
|
||||
|
||||
this.cancel = function (cancelOptions) {
|
||||
return cancelFn == null ? void 0 : cancelFn(cancelOptions);
|
||||
};
|
||||
|
||||
this.cancelRetry = function () {
|
||||
cancelRetry = true;
|
||||
};
|
||||
|
||||
this.continueRetry = function () {
|
||||
cancelRetry = false;
|
||||
};
|
||||
|
||||
this.continue = function () {
|
||||
return continueFn == null ? void 0 : continueFn();
|
||||
};
|
||||
|
||||
this.failureCount = 0;
|
||||
this.isPaused = false;
|
||||
this.isResolved = false;
|
||||
this.isTransportCancelable = false;
|
||||
this.promise = new Promise(function (outerResolve, outerReject) {
|
||||
promiseResolve = outerResolve;
|
||||
promiseReject = outerReject;
|
||||
});
|
||||
|
||||
var resolve = function resolve(value) {
|
||||
if (!_this.isResolved) {
|
||||
_this.isResolved = true;
|
||||
config.onSuccess == null ? void 0 : config.onSuccess(value);
|
||||
continueFn == null ? void 0 : continueFn();
|
||||
promiseResolve(value);
|
||||
}
|
||||
};
|
||||
|
||||
var reject = function reject(value) {
|
||||
if (!_this.isResolved) {
|
||||
_this.isResolved = true;
|
||||
config.onError == null ? void 0 : config.onError(value);
|
||||
continueFn == null ? void 0 : continueFn();
|
||||
promiseReject(value);
|
||||
}
|
||||
};
|
||||
|
||||
var pause = function pause() {
|
||||
return new Promise(function (continueResolve) {
|
||||
continueFn = continueResolve;
|
||||
_this.isPaused = true;
|
||||
config.onPause == null ? void 0 : config.onPause();
|
||||
}).then(function () {
|
||||
continueFn = undefined;
|
||||
_this.isPaused = false;
|
||||
config.onContinue == null ? void 0 : config.onContinue();
|
||||
});
|
||||
}; // Create loop function
|
||||
|
||||
|
||||
var run = function run() {
|
||||
// Do nothing if already resolved
|
||||
if (_this.isResolved) {
|
||||
return;
|
||||
}
|
||||
|
||||
var promiseOrValue; // Execute query
|
||||
|
||||
try {
|
||||
promiseOrValue = config.fn();
|
||||
} catch (error) {
|
||||
promiseOrValue = Promise.reject(error);
|
||||
} // Create callback to cancel this fetch
|
||||
|
||||
|
||||
cancelFn = function cancelFn(cancelOptions) {
|
||||
if (!_this.isResolved) {
|
||||
reject(new CancelledError(cancelOptions));
|
||||
_this.abort == null ? void 0 : _this.abort(); // Cancel transport if supported
|
||||
|
||||
if (isCancelable(promiseOrValue)) {
|
||||
try {
|
||||
promiseOrValue.cancel();
|
||||
} catch (_unused) {}
|
||||
}
|
||||
}
|
||||
}; // Check if the transport layer support cancellation
|
||||
|
||||
|
||||
_this.isTransportCancelable = isCancelable(promiseOrValue);
|
||||
Promise.resolve(promiseOrValue).then(resolve).catch(function (error) {
|
||||
var _config$retry, _config$retryDelay;
|
||||
|
||||
// Stop if the fetch is already resolved
|
||||
if (_this.isResolved) {
|
||||
return;
|
||||
} // Do we need to retry the request?
|
||||
|
||||
|
||||
var retry = (_config$retry = config.retry) != null ? _config$retry : 3;
|
||||
var retryDelay = (_config$retryDelay = config.retryDelay) != null ? _config$retryDelay : defaultRetryDelay;
|
||||
var delay = typeof retryDelay === 'function' ? retryDelay(_this.failureCount, error) : retryDelay;
|
||||
var shouldRetry = retry === true || typeof retry === 'number' && _this.failureCount < retry || typeof retry === 'function' && retry(_this.failureCount, error);
|
||||
|
||||
if (cancelRetry || !shouldRetry) {
|
||||
// We are done if the query does not need to be retried
|
||||
reject(error);
|
||||
return;
|
||||
}
|
||||
|
||||
_this.failureCount++; // Notify on fail
|
||||
|
||||
config.onFail == null ? void 0 : config.onFail(_this.failureCount, error); // Delay
|
||||
|
||||
(0, _utils.sleep)(delay) // Pause if the document is not visible or when the device is offline
|
||||
.then(function () {
|
||||
if (!_focusManager.focusManager.isFocused() || !_onlineManager.onlineManager.isOnline()) {
|
||||
return pause();
|
||||
}
|
||||
}).then(function () {
|
||||
if (cancelRetry) {
|
||||
reject(error);
|
||||
} else {
|
||||
run();
|
||||
}
|
||||
});
|
||||
});
|
||||
}; // Start loop
|
||||
|
||||
|
||||
run();
|
||||
};
|
||||
|
||||
exports.Retryer = Retryer;
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
"use strict";
|
||||
|
||||
exports.__esModule = true;
|
||||
exports.Subscribable = void 0;
|
||||
|
||||
var Subscribable = /*#__PURE__*/function () {
|
||||
function Subscribable() {
|
||||
this.listeners = [];
|
||||
}
|
||||
|
||||
var _proto = Subscribable.prototype;
|
||||
|
||||
_proto.subscribe = function subscribe(listener) {
|
||||
var _this = this;
|
||||
|
||||
var callback = listener || function () {
|
||||
return undefined;
|
||||
};
|
||||
|
||||
this.listeners.push(callback);
|
||||
this.onSubscribe();
|
||||
return function () {
|
||||
_this.listeners = _this.listeners.filter(function (x) {
|
||||
return x !== callback;
|
||||
});
|
||||
|
||||
_this.onUnsubscribe();
|
||||
};
|
||||
};
|
||||
|
||||
_proto.hasListeners = function hasListeners() {
|
||||
return this.listeners.length > 0;
|
||||
};
|
||||
|
||||
_proto.onSubscribe = function onSubscribe() {// Do nothing
|
||||
};
|
||||
|
||||
_proto.onUnsubscribe = function onUnsubscribe() {// Do nothing
|
||||
};
|
||||
|
||||
return Subscribable;
|
||||
}();
|
||||
|
||||
exports.Subscribable = Subscribable;
|
||||
+1
@@ -0,0 +1 @@
|
||||
"use strict";
|
||||
+394
@@ -0,0 +1,394 @@
|
||||
"use strict";
|
||||
|
||||
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
|
||||
|
||||
exports.__esModule = true;
|
||||
exports.noop = noop;
|
||||
exports.functionalUpdate = functionalUpdate;
|
||||
exports.isValidTimeout = isValidTimeout;
|
||||
exports.ensureQueryKeyArray = ensureQueryKeyArray;
|
||||
exports.difference = difference;
|
||||
exports.replaceAt = replaceAt;
|
||||
exports.timeUntilStale = timeUntilStale;
|
||||
exports.parseQueryArgs = parseQueryArgs;
|
||||
exports.parseMutationArgs = parseMutationArgs;
|
||||
exports.parseFilterArgs = parseFilterArgs;
|
||||
exports.parseMutationFilterArgs = parseMutationFilterArgs;
|
||||
exports.mapQueryStatusFilter = mapQueryStatusFilter;
|
||||
exports.matchQuery = matchQuery;
|
||||
exports.matchMutation = matchMutation;
|
||||
exports.hashQueryKeyByOptions = hashQueryKeyByOptions;
|
||||
exports.hashQueryKey = hashQueryKey;
|
||||
exports.stableValueHash = stableValueHash;
|
||||
exports.partialMatchKey = partialMatchKey;
|
||||
exports.partialDeepEqual = partialDeepEqual;
|
||||
exports.replaceEqualDeep = replaceEqualDeep;
|
||||
exports.shallowEqualObjects = shallowEqualObjects;
|
||||
exports.isPlainObject = isPlainObject;
|
||||
exports.isQueryKey = isQueryKey;
|
||||
exports.isError = isError;
|
||||
exports.sleep = sleep;
|
||||
exports.scheduleMicrotask = scheduleMicrotask;
|
||||
exports.getAbortController = getAbortController;
|
||||
exports.isServer = void 0;
|
||||
|
||||
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
|
||||
|
||||
// TYPES
|
||||
// UTILS
|
||||
var isServer = typeof window === 'undefined';
|
||||
exports.isServer = isServer;
|
||||
|
||||
function noop() {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function functionalUpdate(updater, input) {
|
||||
return typeof updater === 'function' ? updater(input) : updater;
|
||||
}
|
||||
|
||||
function isValidTimeout(value) {
|
||||
return typeof value === 'number' && value >= 0 && value !== Infinity;
|
||||
}
|
||||
|
||||
function ensureQueryKeyArray(value) {
|
||||
return Array.isArray(value) ? value : [value];
|
||||
}
|
||||
|
||||
function difference(array1, array2) {
|
||||
return array1.filter(function (x) {
|
||||
return array2.indexOf(x) === -1;
|
||||
});
|
||||
}
|
||||
|
||||
function replaceAt(array, index, value) {
|
||||
var copy = array.slice(0);
|
||||
copy[index] = value;
|
||||
return copy;
|
||||
}
|
||||
|
||||
function timeUntilStale(updatedAt, staleTime) {
|
||||
return Math.max(updatedAt + (staleTime || 0) - Date.now(), 0);
|
||||
}
|
||||
|
||||
function parseQueryArgs(arg1, arg2, arg3) {
|
||||
if (!isQueryKey(arg1)) {
|
||||
return arg1;
|
||||
}
|
||||
|
||||
if (typeof arg2 === 'function') {
|
||||
return (0, _extends2.default)({}, arg3, {
|
||||
queryKey: arg1,
|
||||
queryFn: arg2
|
||||
});
|
||||
}
|
||||
|
||||
return (0, _extends2.default)({}, arg2, {
|
||||
queryKey: arg1
|
||||
});
|
||||
}
|
||||
|
||||
function parseMutationArgs(arg1, arg2, arg3) {
|
||||
if (isQueryKey(arg1)) {
|
||||
if (typeof arg2 === 'function') {
|
||||
return (0, _extends2.default)({}, arg3, {
|
||||
mutationKey: arg1,
|
||||
mutationFn: arg2
|
||||
});
|
||||
}
|
||||
|
||||
return (0, _extends2.default)({}, arg2, {
|
||||
mutationKey: arg1
|
||||
});
|
||||
}
|
||||
|
||||
if (typeof arg1 === 'function') {
|
||||
return (0, _extends2.default)({}, arg2, {
|
||||
mutationFn: arg1
|
||||
});
|
||||
}
|
||||
|
||||
return (0, _extends2.default)({}, arg1);
|
||||
}
|
||||
|
||||
function parseFilterArgs(arg1, arg2, arg3) {
|
||||
return isQueryKey(arg1) ? [(0, _extends2.default)({}, arg2, {
|
||||
queryKey: arg1
|
||||
}), arg3] : [arg1 || {}, arg2];
|
||||
}
|
||||
|
||||
function parseMutationFilterArgs(arg1, arg2) {
|
||||
return isQueryKey(arg1) ? (0, _extends2.default)({}, arg2, {
|
||||
mutationKey: arg1
|
||||
}) : arg1;
|
||||
}
|
||||
|
||||
function mapQueryStatusFilter(active, inactive) {
|
||||
if (active === true && inactive === true || active == null && inactive == null) {
|
||||
return 'all';
|
||||
} else if (active === false && inactive === false) {
|
||||
return 'none';
|
||||
} else {
|
||||
// At this point, active|inactive can only be true|false or false|true
|
||||
// so, when only one value is provided, the missing one has to be the negated value
|
||||
var isActive = active != null ? active : !inactive;
|
||||
return isActive ? 'active' : 'inactive';
|
||||
}
|
||||
}
|
||||
|
||||
function matchQuery(filters, query) {
|
||||
var active = filters.active,
|
||||
exact = filters.exact,
|
||||
fetching = filters.fetching,
|
||||
inactive = filters.inactive,
|
||||
predicate = filters.predicate,
|
||||
queryKey = filters.queryKey,
|
||||
stale = filters.stale;
|
||||
|
||||
if (isQueryKey(queryKey)) {
|
||||
if (exact) {
|
||||
if (query.queryHash !== hashQueryKeyByOptions(queryKey, query.options)) {
|
||||
return false;
|
||||
}
|
||||
} else if (!partialMatchKey(query.queryKey, queryKey)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
var queryStatusFilter = mapQueryStatusFilter(active, inactive);
|
||||
|
||||
if (queryStatusFilter === 'none') {
|
||||
return false;
|
||||
} else if (queryStatusFilter !== 'all') {
|
||||
var isActive = query.isActive();
|
||||
|
||||
if (queryStatusFilter === 'active' && !isActive) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (queryStatusFilter === 'inactive' && isActive) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof stale === 'boolean' && query.isStale() !== stale) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (typeof fetching === 'boolean' && query.isFetching() !== fetching) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (predicate && !predicate(query)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
function matchMutation(filters, mutation) {
|
||||
var exact = filters.exact,
|
||||
fetching = filters.fetching,
|
||||
predicate = filters.predicate,
|
||||
mutationKey = filters.mutationKey;
|
||||
|
||||
if (isQueryKey(mutationKey)) {
|
||||
if (!mutation.options.mutationKey) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (exact) {
|
||||
if (hashQueryKey(mutation.options.mutationKey) !== hashQueryKey(mutationKey)) {
|
||||
return false;
|
||||
}
|
||||
} else if (!partialMatchKey(mutation.options.mutationKey, mutationKey)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof fetching === 'boolean' && mutation.state.status === 'loading' !== fetching) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (predicate && !predicate(mutation)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
function hashQueryKeyByOptions(queryKey, options) {
|
||||
var hashFn = (options == null ? void 0 : options.queryKeyHashFn) || hashQueryKey;
|
||||
return hashFn(queryKey);
|
||||
}
|
||||
/**
|
||||
* Default query keys hash function.
|
||||
*/
|
||||
|
||||
|
||||
function hashQueryKey(queryKey) {
|
||||
var asArray = ensureQueryKeyArray(queryKey);
|
||||
return stableValueHash(asArray);
|
||||
}
|
||||
/**
|
||||
* Hashes the value into a stable hash.
|
||||
*/
|
||||
|
||||
|
||||
function stableValueHash(value) {
|
||||
return JSON.stringify(value, function (_, val) {
|
||||
return isPlainObject(val) ? Object.keys(val).sort().reduce(function (result, key) {
|
||||
result[key] = val[key];
|
||||
return result;
|
||||
}, {}) : val;
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Checks if key `b` partially matches with key `a`.
|
||||
*/
|
||||
|
||||
|
||||
function partialMatchKey(a, b) {
|
||||
return partialDeepEqual(ensureQueryKeyArray(a), ensureQueryKeyArray(b));
|
||||
}
|
||||
/**
|
||||
* Checks if `b` partially matches with `a`.
|
||||
*/
|
||||
|
||||
|
||||
function partialDeepEqual(a, b) {
|
||||
if (a === b) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (typeof a !== typeof b) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (a && b && typeof a === 'object' && typeof b === 'object') {
|
||||
return !Object.keys(b).some(function (key) {
|
||||
return !partialDeepEqual(a[key], b[key]);
|
||||
});
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
/**
|
||||
* This function returns `a` if `b` is deeply equal.
|
||||
* If not, it will replace any deeply equal children of `b` with those of `a`.
|
||||
* This can be used for structural sharing between JSON values for example.
|
||||
*/
|
||||
|
||||
|
||||
function replaceEqualDeep(a, b) {
|
||||
if (a === b) {
|
||||
return a;
|
||||
}
|
||||
|
||||
var array = Array.isArray(a) && Array.isArray(b);
|
||||
|
||||
if (array || isPlainObject(a) && isPlainObject(b)) {
|
||||
var aSize = array ? a.length : Object.keys(a).length;
|
||||
var bItems = array ? b : Object.keys(b);
|
||||
var bSize = bItems.length;
|
||||
var copy = array ? [] : {};
|
||||
var equalItems = 0;
|
||||
|
||||
for (var i = 0; i < bSize; i++) {
|
||||
var key = array ? i : bItems[i];
|
||||
copy[key] = replaceEqualDeep(a[key], b[key]);
|
||||
|
||||
if (copy[key] === a[key]) {
|
||||
equalItems++;
|
||||
}
|
||||
}
|
||||
|
||||
return aSize === bSize && equalItems === aSize ? a : copy;
|
||||
}
|
||||
|
||||
return b;
|
||||
}
|
||||
/**
|
||||
* Shallow compare objects. Only works with objects that always have the same properties.
|
||||
*/
|
||||
|
||||
|
||||
function shallowEqualObjects(a, b) {
|
||||
if (a && !b || b && !a) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (var key in a) {
|
||||
if (a[key] !== b[key]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
} // Copied from: https://github.com/jonschlinkert/is-plain-object
|
||||
|
||||
|
||||
function isPlainObject(o) {
|
||||
if (!hasObjectPrototype(o)) {
|
||||
return false;
|
||||
} // If has modified constructor
|
||||
|
||||
|
||||
var ctor = o.constructor;
|
||||
|
||||
if (typeof ctor === 'undefined') {
|
||||
return true;
|
||||
} // If has modified prototype
|
||||
|
||||
|
||||
var prot = ctor.prototype;
|
||||
|
||||
if (!hasObjectPrototype(prot)) {
|
||||
return false;
|
||||
} // If constructor does not have an Object-specific method
|
||||
|
||||
|
||||
if (!prot.hasOwnProperty('isPrototypeOf')) {
|
||||
return false;
|
||||
} // Most likely a plain Object
|
||||
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
function hasObjectPrototype(o) {
|
||||
return Object.prototype.toString.call(o) === '[object Object]';
|
||||
}
|
||||
|
||||
function isQueryKey(value) {
|
||||
return typeof value === 'string' || Array.isArray(value);
|
||||
}
|
||||
|
||||
function isError(value) {
|
||||
return value instanceof Error;
|
||||
}
|
||||
|
||||
function sleep(timeout) {
|
||||
return new Promise(function (resolve) {
|
||||
setTimeout(resolve, timeout);
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Schedules a microtask.
|
||||
* This can be useful to schedule state updates after rendering.
|
||||
*/
|
||||
|
||||
|
||||
function scheduleMicrotask(callback) {
|
||||
Promise.resolve().then(callback).catch(function (error) {
|
||||
return setTimeout(function () {
|
||||
throw error;
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function getAbortController() {
|
||||
if (typeof AbortController === 'function') {
|
||||
return new AbortController();
|
||||
}
|
||||
}
|
||||
Generated
Vendored
+131
@@ -0,0 +1,131 @@
|
||||
"use strict";
|
||||
|
||||
exports.__esModule = true;
|
||||
exports.createAsyncStoragePersistor = void 0;
|
||||
|
||||
function _await(value, then, direct) {
|
||||
if (direct) {
|
||||
return then ? then(value) : value;
|
||||
}
|
||||
|
||||
if (!value || !value.then) {
|
||||
value = Promise.resolve(value);
|
||||
}
|
||||
|
||||
return then ? value.then(then) : value;
|
||||
}
|
||||
|
||||
function _async(f) {
|
||||
return function () {
|
||||
for (var args = [], i = 0; i < arguments.length; i++) {
|
||||
args[i] = arguments[i];
|
||||
}
|
||||
|
||||
try {
|
||||
return Promise.resolve(f.apply(this, args));
|
||||
} catch (e) {
|
||||
return Promise.reject(e);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function _empty() {}
|
||||
|
||||
function _invokeIgnored(body) {
|
||||
var result = body();
|
||||
|
||||
if (result && result.then) {
|
||||
return result.then(_empty);
|
||||
}
|
||||
}
|
||||
|
||||
var createAsyncStoragePersistor = function createAsyncStoragePersistor(_ref) {
|
||||
var storage = _ref.storage,
|
||||
_ref$key = _ref.key,
|
||||
key = _ref$key === void 0 ? "REACT_QUERY_OFFLINE_CACHE" : _ref$key,
|
||||
_ref$throttleTime = _ref.throttleTime,
|
||||
throttleTime = _ref$throttleTime === void 0 ? 1000 : _ref$throttleTime,
|
||||
_ref$serialize = _ref.serialize,
|
||||
serialize = _ref$serialize === void 0 ? JSON.stringify : _ref$serialize,
|
||||
_ref$deserialize = _ref.deserialize,
|
||||
deserialize = _ref$deserialize === void 0 ? JSON.parse : _ref$deserialize;
|
||||
return {
|
||||
persistClient: asyncThrottle(function (persistedClient) {
|
||||
return storage.setItem(key, serialize(persistedClient));
|
||||
}, {
|
||||
interval: throttleTime
|
||||
}),
|
||||
restoreClient: _async(function () {
|
||||
return _await(storage.getItem(key), function (cacheString) {
|
||||
if (!cacheString) {
|
||||
return;
|
||||
}
|
||||
|
||||
return deserialize(cacheString);
|
||||
});
|
||||
}),
|
||||
removeClient: function removeClient() {
|
||||
return storage.removeItem(key);
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
exports.createAsyncStoragePersistor = createAsyncStoragePersistor;
|
||||
|
||||
function asyncThrottle(func, _temp) {
|
||||
var _ref2 = _temp === void 0 ? {} : _temp,
|
||||
_ref2$interval = _ref2.interval,
|
||||
interval = _ref2$interval === void 0 ? 1000 : _ref2$interval,
|
||||
_ref2$limit = _ref2.limit,
|
||||
limit = _ref2$limit === void 0 ? 1 : _ref2$limit;
|
||||
|
||||
if (typeof func !== 'function') throw new Error('argument is not function.');
|
||||
var running = {
|
||||
current: false
|
||||
};
|
||||
var lastTime = 0;
|
||||
var timeout;
|
||||
var queue = [];
|
||||
return function () {
|
||||
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
|
||||
args[_key] = arguments[_key];
|
||||
}
|
||||
|
||||
return _async(function () {
|
||||
if (running.current) {
|
||||
lastTime = Date.now();
|
||||
|
||||
if (queue.length > limit) {
|
||||
queue.shift();
|
||||
}
|
||||
|
||||
queue.push(args);
|
||||
clearTimeout(timeout);
|
||||
}
|
||||
|
||||
return _invokeIgnored(function () {
|
||||
if (Date.now() - lastTime > interval) {
|
||||
running.current = true;
|
||||
return _await(func.apply(void 0, args), function () {
|
||||
lastTime = Date.now();
|
||||
running.current = false;
|
||||
});
|
||||
} else {
|
||||
if (queue.length > 0) {
|
||||
var lastArgs = queue[queue.length - 1];
|
||||
timeout = setTimeout(_async(function () {
|
||||
return _invokeIgnored(function () {
|
||||
if (!running.current) {
|
||||
running.current = true;
|
||||
return _await(func.apply(void 0, lastArgs), function () {
|
||||
running.current = false;
|
||||
});
|
||||
}
|
||||
});
|
||||
}), interval);
|
||||
}
|
||||
}
|
||||
});
|
||||
})();
|
||||
};
|
||||
}
|
||||
Generated
Vendored
+123
@@ -0,0 +1,123 @@
|
||||
"use strict";
|
||||
|
||||
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
|
||||
|
||||
exports.__esModule = true;
|
||||
exports.createWebStoragePersistor = createWebStoragePersistor;
|
||||
|
||||
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
|
||||
|
||||
var _utils = require("../core/utils");
|
||||
|
||||
function createWebStoragePersistor(_ref) {
|
||||
var storage = _ref.storage,
|
||||
_ref$key = _ref.key,
|
||||
key = _ref$key === void 0 ? "REACT_QUERY_OFFLINE_CACHE" : _ref$key,
|
||||
_ref$throttleTime = _ref.throttleTime,
|
||||
throttleTime = _ref$throttleTime === void 0 ? 1000 : _ref$throttleTime,
|
||||
_ref$serialize = _ref.serialize,
|
||||
serialize = _ref$serialize === void 0 ? JSON.stringify : _ref$serialize,
|
||||
_ref$deserialize = _ref.deserialize,
|
||||
deserialize = _ref$deserialize === void 0 ? JSON.parse : _ref$deserialize;
|
||||
|
||||
//try to save data to storage
|
||||
function trySave(persistedClient) {
|
||||
try {
|
||||
storage.setItem(key, serialize(persistedClient));
|
||||
} catch (_unused) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
if (typeof storage !== 'undefined') {
|
||||
return {
|
||||
persistClient: throttle(function (persistedClient) {
|
||||
if (trySave(persistedClient) !== true) {
|
||||
var mutations = [].concat(persistedClient.clientState.mutations);
|
||||
var queries = [].concat(persistedClient.clientState.queries);
|
||||
|
||||
var _client = (0, _extends2.default)({}, persistedClient, {
|
||||
clientState: {
|
||||
mutations: mutations,
|
||||
queries: queries
|
||||
}
|
||||
}); // sort queries by dataUpdatedAt (oldest first)
|
||||
|
||||
|
||||
var sortedQueries = [].concat(queries).sort(function (a, b) {
|
||||
return a.state.dataUpdatedAt - b.state.dataUpdatedAt;
|
||||
}); // clean old queries and try to save
|
||||
|
||||
var _loop = function _loop() {
|
||||
var oldestData = sortedQueries.shift();
|
||||
_client.clientState.queries = queries.filter(function (q) {
|
||||
return q !== oldestData;
|
||||
});
|
||||
|
||||
if (trySave(_client)) {
|
||||
return {
|
||||
v: void 0
|
||||
}; // save success
|
||||
}
|
||||
};
|
||||
|
||||
while (sortedQueries.length > 0) {
|
||||
var _ret = _loop();
|
||||
|
||||
if (typeof _ret === "object") return _ret.v;
|
||||
} // clean mutations and try to save
|
||||
|
||||
|
||||
while (mutations.shift()) {
|
||||
if (trySave(_client)) {
|
||||
return; // save success
|
||||
}
|
||||
}
|
||||
}
|
||||
}, throttleTime),
|
||||
restoreClient: function restoreClient() {
|
||||
var cacheString = storage.getItem(key);
|
||||
|
||||
if (!cacheString) {
|
||||
return;
|
||||
}
|
||||
|
||||
return deserialize(cacheString);
|
||||
},
|
||||
removeClient: function removeClient() {
|
||||
storage.removeItem(key);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
persistClient: _utils.noop,
|
||||
restoreClient: _utils.noop,
|
||||
removeClient: _utils.noop
|
||||
};
|
||||
}
|
||||
|
||||
function throttle(func, wait) {
|
||||
if (wait === void 0) {
|
||||
wait = 100;
|
||||
}
|
||||
|
||||
var timer = null;
|
||||
var params;
|
||||
return function () {
|
||||
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
|
||||
args[_key] = arguments[_key];
|
||||
}
|
||||
|
||||
params = args;
|
||||
|
||||
if (timer === null) {
|
||||
timer = setTimeout(function () {
|
||||
func.apply(void 0, params);
|
||||
timer = null;
|
||||
}, wait);
|
||||
}
|
||||
};
|
||||
}
|
||||
+235
@@ -0,0 +1,235 @@
|
||||
"use strict";
|
||||
|
||||
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
|
||||
|
||||
exports.__esModule = true;
|
||||
exports.chunkArray = chunkArray;
|
||||
exports.default = Explorer;
|
||||
exports.DefaultRenderer = exports.Expander = exports.Info = exports.SubEntries = exports.Value = exports.ExpandButton = exports.LabelButton = exports.Label = exports.Entry = void 0;
|
||||
|
||||
var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));
|
||||
|
||||
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
|
||||
|
||||
var _react = _interopRequireDefault(require("react"));
|
||||
|
||||
var _utils = require("./utils");
|
||||
|
||||
var Entry = (0, _utils.styled)('div', {
|
||||
fontFamily: 'Menlo, monospace',
|
||||
fontSize: '1em',
|
||||
lineHeight: '1.7',
|
||||
outline: 'none',
|
||||
wordBreak: 'break-word'
|
||||
});
|
||||
exports.Entry = Entry;
|
||||
var Label = (0, _utils.styled)('span', {
|
||||
color: 'white'
|
||||
});
|
||||
exports.Label = Label;
|
||||
var LabelButton = (0, _utils.styled)('button', {
|
||||
cursor: 'pointer',
|
||||
color: 'white'
|
||||
});
|
||||
exports.LabelButton = LabelButton;
|
||||
var ExpandButton = (0, _utils.styled)('button', {
|
||||
cursor: 'pointer',
|
||||
color: 'inherit',
|
||||
font: 'inherit',
|
||||
outline: 'inherit',
|
||||
background: 'transparent',
|
||||
border: 'none',
|
||||
padding: 0
|
||||
});
|
||||
exports.ExpandButton = ExpandButton;
|
||||
var Value = (0, _utils.styled)('span', function (_props, theme) {
|
||||
return {
|
||||
color: theme.danger
|
||||
};
|
||||
});
|
||||
exports.Value = Value;
|
||||
var SubEntries = (0, _utils.styled)('div', {
|
||||
marginLeft: '.1em',
|
||||
paddingLeft: '1em',
|
||||
borderLeft: '2px solid rgba(0,0,0,.15)'
|
||||
});
|
||||
exports.SubEntries = SubEntries;
|
||||
var Info = (0, _utils.styled)('span', {
|
||||
color: 'grey',
|
||||
fontSize: '.7em'
|
||||
});
|
||||
exports.Info = Info;
|
||||
|
||||
var Expander = function Expander(_ref) {
|
||||
var expanded = _ref.expanded,
|
||||
_ref$style = _ref.style,
|
||||
style = _ref$style === void 0 ? {} : _ref$style;
|
||||
return /*#__PURE__*/_react.default.createElement("span", {
|
||||
style: (0, _extends2.default)({
|
||||
display: 'inline-block',
|
||||
transition: 'all .1s ease',
|
||||
transform: "rotate(" + (expanded ? 90 : 0) + "deg) " + (style.transform || '')
|
||||
}, style)
|
||||
}, "\u25B6");
|
||||
};
|
||||
|
||||
exports.Expander = Expander;
|
||||
|
||||
/**
|
||||
* Chunk elements in the array by size
|
||||
*
|
||||
* when the array cannot be chunked evenly by size, the last chunk will be
|
||||
* filled with the remaining elements
|
||||
*
|
||||
* @example
|
||||
* chunkArray(['a','b', 'c', 'd', 'e'], 2) // returns [['a','b'], ['c', 'd'], ['e']]
|
||||
*/
|
||||
function chunkArray(array, size) {
|
||||
if (size < 1) return [];
|
||||
var i = 0;
|
||||
var result = [];
|
||||
|
||||
while (i < array.length) {
|
||||
result.push(array.slice(i, i + size));
|
||||
i = i + size;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
var DefaultRenderer = function DefaultRenderer(_ref2) {
|
||||
var HandleEntry = _ref2.HandleEntry,
|
||||
label = _ref2.label,
|
||||
value = _ref2.value,
|
||||
_ref2$subEntries = _ref2.subEntries,
|
||||
subEntries = _ref2$subEntries === void 0 ? [] : _ref2$subEntries,
|
||||
_ref2$subEntryPages = _ref2.subEntryPages,
|
||||
subEntryPages = _ref2$subEntryPages === void 0 ? [] : _ref2$subEntryPages,
|
||||
type = _ref2.type,
|
||||
_ref2$expanded = _ref2.expanded,
|
||||
expanded = _ref2$expanded === void 0 ? false : _ref2$expanded,
|
||||
toggleExpanded = _ref2.toggleExpanded,
|
||||
pageSize = _ref2.pageSize;
|
||||
|
||||
var _React$useState = _react.default.useState([]),
|
||||
expandedPages = _React$useState[0],
|
||||
setExpandedPages = _React$useState[1];
|
||||
|
||||
return /*#__PURE__*/_react.default.createElement(Entry, {
|
||||
key: label
|
||||
}, (subEntryPages == null ? void 0 : subEntryPages.length) ? /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(ExpandButton, {
|
||||
onClick: function onClick() {
|
||||
return toggleExpanded();
|
||||
}
|
||||
}, /*#__PURE__*/_react.default.createElement(Expander, {
|
||||
expanded: expanded
|
||||
}), " ", label, ' ', /*#__PURE__*/_react.default.createElement(Info, null, String(type).toLowerCase() === 'iterable' ? '(Iterable) ' : '', subEntries.length, " ", subEntries.length > 1 ? "items" : "item")), expanded ? subEntryPages.length === 1 ? /*#__PURE__*/_react.default.createElement(SubEntries, null, subEntries.map(function (entry) {
|
||||
return /*#__PURE__*/_react.default.createElement(HandleEntry, {
|
||||
key: entry.label,
|
||||
entry: entry
|
||||
});
|
||||
})) : /*#__PURE__*/_react.default.createElement(SubEntries, null, subEntryPages.map(function (entries, index) {
|
||||
return /*#__PURE__*/_react.default.createElement("div", {
|
||||
key: index
|
||||
}, /*#__PURE__*/_react.default.createElement(Entry, null, /*#__PURE__*/_react.default.createElement(LabelButton, {
|
||||
onClick: function onClick() {
|
||||
return setExpandedPages(function (old) {
|
||||
return old.includes(index) ? old.filter(function (d) {
|
||||
return d !== index;
|
||||
}) : [].concat(old, [index]);
|
||||
});
|
||||
}
|
||||
}, /*#__PURE__*/_react.default.createElement(Expander, {
|
||||
expanded: expanded
|
||||
}), " [", index * pageSize, " ...", ' ', index * pageSize + pageSize - 1, "]"), expandedPages.includes(index) ? /*#__PURE__*/_react.default.createElement(SubEntries, null, entries.map(function (entry) {
|
||||
return /*#__PURE__*/_react.default.createElement(HandleEntry, {
|
||||
key: entry.label,
|
||||
entry: entry
|
||||
});
|
||||
})) : null));
|
||||
})) : null) : /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(Label, null, label, ":"), " ", /*#__PURE__*/_react.default.createElement(Value, null, (0, _utils.displayValue)(value))));
|
||||
};
|
||||
|
||||
exports.DefaultRenderer = DefaultRenderer;
|
||||
|
||||
function isIterable(x) {
|
||||
return Symbol.iterator in x;
|
||||
}
|
||||
|
||||
function Explorer(_ref3) {
|
||||
var value = _ref3.value,
|
||||
defaultExpanded = _ref3.defaultExpanded,
|
||||
_ref3$renderer = _ref3.renderer,
|
||||
renderer = _ref3$renderer === void 0 ? DefaultRenderer : _ref3$renderer,
|
||||
_ref3$pageSize = _ref3.pageSize,
|
||||
pageSize = _ref3$pageSize === void 0 ? 100 : _ref3$pageSize,
|
||||
rest = (0, _objectWithoutPropertiesLoose2.default)(_ref3, ["value", "defaultExpanded", "renderer", "pageSize"]);
|
||||
|
||||
var _React$useState2 = _react.default.useState(Boolean(defaultExpanded)),
|
||||
expanded = _React$useState2[0],
|
||||
setExpanded = _React$useState2[1];
|
||||
|
||||
var toggleExpanded = _react.default.useCallback(function () {
|
||||
return setExpanded(function (old) {
|
||||
return !old;
|
||||
});
|
||||
}, []);
|
||||
|
||||
var type = typeof value;
|
||||
var subEntries = [];
|
||||
|
||||
var makeProperty = function makeProperty(sub) {
|
||||
var _ref4;
|
||||
|
||||
var subDefaultExpanded = defaultExpanded === true ? (_ref4 = {}, _ref4[sub.label] = true, _ref4) : defaultExpanded == null ? void 0 : defaultExpanded[sub.label];
|
||||
return (0, _extends2.default)({}, sub, {
|
||||
defaultExpanded: subDefaultExpanded
|
||||
});
|
||||
};
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
type = 'array';
|
||||
subEntries = value.map(function (d, i) {
|
||||
return makeProperty({
|
||||
label: i.toString(),
|
||||
value: d
|
||||
});
|
||||
});
|
||||
} else if (value !== null && typeof value === 'object' && isIterable(value) && typeof value[Symbol.iterator] === 'function') {
|
||||
type = 'Iterable';
|
||||
subEntries = Array.from(value, function (val, i) {
|
||||
return makeProperty({
|
||||
label: i.toString(),
|
||||
value: val
|
||||
});
|
||||
});
|
||||
} else if (typeof value === 'object' && value !== null) {
|
||||
type = 'object';
|
||||
subEntries = Object.entries(value).map(function (_ref5) {
|
||||
var key = _ref5[0],
|
||||
val = _ref5[1];
|
||||
return makeProperty({
|
||||
label: key,
|
||||
value: val
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
var subEntryPages = chunkArray(subEntries, pageSize);
|
||||
return renderer((0, _extends2.default)({
|
||||
HandleEntry: function HandleEntry(_ref6) {
|
||||
var entry = _ref6.entry;
|
||||
return /*#__PURE__*/_react.default.createElement(Explorer, (0, _extends2.default)({
|
||||
value: value,
|
||||
renderer: renderer
|
||||
}, rest, entry));
|
||||
},
|
||||
type: type,
|
||||
subEntries: subEntries,
|
||||
subEntryPages: subEntryPages,
|
||||
value: value,
|
||||
expanded: expanded,
|
||||
toggleExpanded: toggleExpanded,
|
||||
pageSize: pageSize
|
||||
}, rest));
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
"use strict";
|
||||
|
||||
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
|
||||
|
||||
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
|
||||
|
||||
exports.__esModule = true;
|
||||
exports.default = Logo;
|
||||
|
||||
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
|
||||
|
||||
var React = _interopRequireWildcard(require("react"));
|
||||
|
||||
function Logo(props) {
|
||||
return /*#__PURE__*/React.createElement("svg", (0, _extends2.default)({
|
||||
width: "40px",
|
||||
height: "40px",
|
||||
viewBox: "0 0 190 190",
|
||||
version: "1.1"
|
||||
}, props), /*#__PURE__*/React.createElement("g", {
|
||||
stroke: "none",
|
||||
strokeWidth: "1",
|
||||
fill: "none",
|
||||
fillRule: "evenodd"
|
||||
}, /*#__PURE__*/React.createElement("g", {
|
||||
transform: "translate(-33.000000, 0.000000)"
|
||||
}, /*#__PURE__*/React.createElement("path", {
|
||||
d: "M72.7239712,61.3436237 C69.631224,46.362877 68.9675112,34.8727722 70.9666331,26.5293551 C72.1555965,21.5671678 74.3293088,17.5190846 77.6346064,14.5984631 C81.1241394,11.5150478 85.5360327,10.0020122 90.493257,10.0020122 C98.6712013,10.0020122 107.26826,13.7273214 116.455725,20.8044264 C120.20312,23.6910458 124.092437,27.170411 128.131651,31.2444746 C128.45314,30.8310265 128.816542,30.4410453 129.22143,30.0806152 C140.64098,19.9149716 150.255245,13.5989272 158.478408,11.1636507 C163.367899,9.715636 167.958526,9.57768202 172.138936,10.983031 C176.551631,12.4664684 180.06766,15.5329489 182.548314,19.8281091 C186.642288,26.9166735 187.721918,36.2310983 186.195595,47.7320243 C185.573451,52.4199112 184.50985,57.5263831 183.007094,63.0593153 C183.574045,63.1277086 184.142416,63.2532808 184.705041,63.4395297 C199.193932,68.2358678 209.453582,73.3937462 215.665021,79.2882839 C219.360669,82.7953831 221.773972,86.6998434 222.646365,91.0218204 C223.567176,95.5836746 222.669313,100.159332 220.191548,104.451297 C216.105211,111.529614 208.591643,117.11221 197.887587,121.534031 C193.589552,123.309539 188.726579,124.917559 183.293259,126.363748 C183.541176,126.92292 183.733521,127.516759 183.862138,128.139758 C186.954886,143.120505 187.618598,154.61061 185.619477,162.954027 C184.430513,167.916214 182.256801,171.964297 178.951503,174.884919 C175.46197,177.968334 171.050077,179.48137 166.092853,179.48137 C157.914908,179.48137 149.31785,175.756061 140.130385,168.678956 C136.343104,165.761613 132.410866,162.238839 128.325434,158.108619 C127.905075,158.765474 127.388968,159.376011 126.77857,159.919385 C115.35902,170.085028 105.744755,176.401073 97.5215915,178.836349 C92.6321009,180.284364 88.0414736,180.422318 83.8610636,179.016969 C79.4483686,177.533532 75.9323404,174.467051 73.4516862,170.171891 C69.3577116,163.083327 68.2780823,153.768902 69.8044053,142.267976 C70.449038,137.410634 71.56762,132.103898 73.1575891,126.339009 C72.5361041,126.276104 71.9120754,126.144816 71.2949591,125.940529 C56.8060684,121.144191 46.5464184,115.986312 40.3349789,110.091775 C36.6393312,106.584675 34.2260275,102.680215 33.3536352,98.3582381 C32.4328237,93.7963839 33.3306866,89.2207269 35.8084524,84.9287618 C39.8947886,77.8504443 47.4083565,72.2678481 58.1124133,67.8460273 C62.5385143,66.0176154 67.5637208,64.366822 73.1939394,62.8874674 C72.9933393,62.3969171 72.8349374,61.8811235 72.7239712,61.3436237 Z",
|
||||
fill: "#002C4B",
|
||||
fillRule: "nonzero",
|
||||
transform: "translate(128.000000, 95.000000) scale(-1, 1) translate(-128.000000, -95.000000) "
|
||||
}), /*#__PURE__*/React.createElement("path", {
|
||||
d: "M113.396882,64 L142.608177,64 C144.399254,64 146.053521,64.958025 146.944933,66.5115174 L161.577138,92.0115174 C162.461464,93.5526583 162.461464,95.4473417 161.577138,96.9884826 L146.944933,122.488483 C146.053521,124.041975 144.399254,125 142.608177,125 L113.396882,125 C111.605806,125 109.951539,124.041975 109.060126,122.488483 L94.4279211,96.9884826 C93.543596,95.4473417 93.543596,93.5526583 94.4279211,92.0115174 L109.060126,66.5115174 C109.951539,64.958025 111.605806,64 113.396882,64 Z M138.987827,70.2765273 C140.779849,70.2765273 142.434839,71.2355558 143.325899,72.7903404 L154.343038,92.0138131 C155.225607,93.5537825 155.225607,95.4462175 154.343038,96.9861869 L143.325899,116.20966 C142.434839,117.764444 140.779849,118.723473 138.987827,118.723473 L117.017233,118.723473 C115.225211,118.723473 113.570221,117.764444 112.67916,116.20966 L101.662022,96.9861869 C100.779452,95.4462175 100.779452,93.5537825 101.662022,92.0138131 L112.67916,72.7903404 C113.570221,71.2355558 115.225211,70.2765273 117.017233,70.2765273 L138.987827,70.2765273 Z M135.080648,77.1414791 L120.924411,77.1414791 C119.134228,77.1414791 117.480644,78.0985567 116.5889,79.6508285 L116.5889,79.6508285 L109.489217,92.0093494 C108.603232,93.5515958 108.603232,95.4484042 109.489217,96.9906506 L109.489217,96.9906506 L116.5889,109.349172 C117.480644,110.901443 119.134228,111.858521 120.924411,111.858521 L120.924411,111.858521 L135.080648,111.858521 C136.870831,111.858521 138.524416,110.901443 139.41616,109.349172 L139.41616,109.349172 L146.515843,96.9906506 C147.401828,95.4484042 147.401828,93.5515958 146.515843,92.0093494 L146.515843,92.0093494 L139.41616,79.6508285 C138.524416,78.0985567 136.870831,77.1414791 135.080648,77.1414791 L135.080648,77.1414791 Z M131.319186,83.7122186 C133.108028,83.7122186 134.760587,84.6678753 135.652827,86.2183156 L138.983552,92.0060969 C139.87203,93.5500005 139.87203,95.4499995 138.983552,96.9939031 L135.652827,102.781684 C134.760587,104.332125 133.108028,105.287781 131.319186,105.287781 L124.685874,105.287781 C122.897032,105.287781 121.244473,104.332125 120.352233,102.781684 L117.021508,96.9939031 C116.13303,95.4499995 116.13303,93.5500005 117.021508,92.0060969 L120.352233,86.2183156 C121.244473,84.6678753 122.897032,83.7122186 124.685874,83.7122186 L131.319186,83.7122186 Z M128.003794,90.1848875 C126.459294,90.1848875 125.034382,91.0072828 124.263005,92.3424437 C123.491732,93.6774232 123.491732,95.3225768 124.263005,96.6575563 C125.034382,97.9927172 126.459294,98.8151125 128.001266,98.8151125 L128.001266,98.8151125 C129.545766,98.8151125 130.970678,97.9927172 131.742055,96.6575563 C132.513327,95.3225768 132.513327,93.6774232 131.742055,92.3424437 C130.970678,91.0072828 129.545766,90.1848875 128.003794,90.1848875 L128.003794,90.1848875 Z M93,94.5009646 L100.767764,94.5009646",
|
||||
fill: "#FFD94C"
|
||||
}), /*#__PURE__*/React.createElement("path", {
|
||||
d: "M87.8601729,108.357758 C89.1715224,107.608286 90.8360246,108.074601 91.5779424,109.399303 L91.5779424,109.399303 L92.0525843,110.24352 C95.8563392,116.982993 99.8190116,123.380176 103.940602,129.435068 C108.807881,136.585427 114.28184,143.82411 120.362479,151.151115 C121.316878,152.30114 121.184944,154.011176 120.065686,154.997937 L120.065686,154.997937 L119.454208,155.534625 C99.3465389,173.103314 86.2778188,176.612552 80.2480482,166.062341 C74.3500652,155.742717 76.4844915,136.982888 86.6513274,109.782853 C86.876818,109.179582 87.3045861,108.675291 87.8601729,108.357758 Z M173.534177,129.041504 C174.986131,128.785177 176.375496,129.742138 176.65963,131.194242 L176.65963,131.194242 L176.812815,131.986376 C181.782365,157.995459 178.283348,171 166.315764,171 C154.609745,171 139.708724,159.909007 121.612702,137.727022 C121.211349,137.235047 120.994572,136.617371 121,135.981509 C121.013158,134.480686 122.235785,133.274651 123.730918,133.287756 L123.730918,133.287756 L124.684654,133.294531 C132.305698,133.335994 139.714387,133.071591 146.910723,132.501323 C155.409039,131.82788 164.283523,130.674607 173.534177,129.041504 Z M180.408726,73.8119663 C180.932139,72.4026903 182.508386,71.6634537 183.954581,72.149012 L183.954581,72.149012 L184.742552,72.4154854 C210.583763,81.217922 220.402356,90.8916805 214.198332,101.436761 C208.129904,111.751366 190.484347,119.260339 161.26166,123.963678 C160.613529,124.067994 159.948643,123.945969 159.382735,123.618843 C158.047025,122.846729 157.602046,121.158214 158.388848,119.847438 L158.388848,119.847438 L158.889328,119.0105 C162.877183,112.31633 166.481358,105.654262 169.701854,99.0242957 C173.50501,91.1948179 177.073967,82.7907081 180.408726,73.8119663 Z M94.7383398,66.0363218 C95.3864708,65.9320063 96.0513565,66.0540315 96.6172646,66.3811573 C97.9529754,67.153271 98.3979538,68.8417862 97.6111517,70.1525615 L97.6111517,70.1525615 L97.1106718,70.9895001 C93.1228168,77.6836699 89.5186416,84.3457379 86.2981462,90.9757043 C82.49499,98.8051821 78.9260328,107.209292 75.5912744,116.188034 C75.0678608,117.59731 73.4916142,118.336546 72.045419,117.850988 L72.045419,117.850988 L71.2574475,117.584515 C45.4162372,108.782078 35.597644,99.1083195 41.8016679,88.5632391 C47.8700957,78.2486335 65.515653,70.7396611 94.7383398,66.0363218 Z M136.545792,34.4653746 C156.653461,16.8966864 169.722181,13.3874478 175.751952,23.9376587 C181.649935,34.2572826 179.515508,53.0171122 169.348673,80.2171474 C169.123182,80.8204179 168.695414,81.324709 168.139827,81.6422422 C166.828478,82.3917144 165.163975,81.9253986 164.422058,80.6006966 L164.422058,80.6006966 L163.947416,79.7564798 C160.143661,73.0170065 156.180988,66.6198239 152.059398,60.564932 C147.192119,53.4145727 141.71816,46.1758903 135.637521,38.8488847 C134.683122,37.6988602 134.815056,35.9888243 135.934314,35.0020629 L135.934314,35.0020629 Z M90.6842361,18 C102.390255,18 117.291276,29.0909926 135.387298,51.2729777 C135.788651,51.7649527 136.005428,52.3826288 136,53.0184911 C135.986842,54.5193144 134.764215,55.7253489 133.269082,55.7122445 L133.269082,55.7122445 L132.315346,55.7054689 C124.694302,55.6640063 117.285613,55.9284091 110.089277,56.4986773 C101.590961,57.17212 92.7164767,58.325393 83.4658235,59.9584962 C82.0138691,60.2148231 80.6245044,59.2578618 80.3403697,57.805758 L80.3403697,57.805758 L80.1871846,57.0136235 C75.2176347,31.0045412 78.7166519,18 90.6842361,18 Z",
|
||||
fill: "#FF4154"
|
||||
}))));
|
||||
}
|
||||
+720
@@ -0,0 +1,720 @@
|
||||
"use strict";
|
||||
|
||||
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
|
||||
|
||||
exports.__esModule = true;
|
||||
exports.ReactQueryDevtools = ReactQueryDevtools;
|
||||
exports.ReactQueryDevtoolsPanel = void 0;
|
||||
|
||||
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
|
||||
|
||||
var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));
|
||||
|
||||
var _react = _interopRequireDefault(require("react"));
|
||||
|
||||
var _reactQuery = require("react-query");
|
||||
|
||||
var _matchSorter = require("match-sorter");
|
||||
|
||||
var _useLocalStorage7 = _interopRequireDefault(require("./useLocalStorage"));
|
||||
|
||||
var _utils = require("./utils");
|
||||
|
||||
var _styledComponents = require("./styledComponents");
|
||||
|
||||
var _theme = require("./theme");
|
||||
|
||||
var _Explorer = _interopRequireDefault(require("./Explorer"));
|
||||
|
||||
var _Logo = _interopRequireDefault(require("./Logo"));
|
||||
|
||||
var _utils2 = require("../core/utils");
|
||||
|
||||
var isServer = typeof window === 'undefined';
|
||||
|
||||
function ReactQueryDevtools(_ref) {
|
||||
var initialIsOpen = _ref.initialIsOpen,
|
||||
_ref$panelProps = _ref.panelProps,
|
||||
panelProps = _ref$panelProps === void 0 ? {} : _ref$panelProps,
|
||||
_ref$closeButtonProps = _ref.closeButtonProps,
|
||||
closeButtonProps = _ref$closeButtonProps === void 0 ? {} : _ref$closeButtonProps,
|
||||
_ref$toggleButtonProp = _ref.toggleButtonProps,
|
||||
toggleButtonProps = _ref$toggleButtonProp === void 0 ? {} : _ref$toggleButtonProp,
|
||||
_ref$position = _ref.position,
|
||||
position = _ref$position === void 0 ? 'bottom-left' : _ref$position,
|
||||
_ref$containerElement = _ref.containerElement,
|
||||
Container = _ref$containerElement === void 0 ? 'aside' : _ref$containerElement,
|
||||
styleNonce = _ref.styleNonce;
|
||||
|
||||
var rootRef = _react.default.useRef(null);
|
||||
|
||||
var panelRef = _react.default.useRef(null);
|
||||
|
||||
var _useLocalStorage = (0, _useLocalStorage7.default)('reactQueryDevtoolsOpen', initialIsOpen),
|
||||
isOpen = _useLocalStorage[0],
|
||||
setIsOpen = _useLocalStorage[1];
|
||||
|
||||
var _useLocalStorage2 = (0, _useLocalStorage7.default)('reactQueryDevtoolsHeight', null),
|
||||
devtoolsHeight = _useLocalStorage2[0],
|
||||
setDevtoolsHeight = _useLocalStorage2[1];
|
||||
|
||||
var _useSafeState = (0, _utils.useSafeState)(false),
|
||||
isResolvedOpen = _useSafeState[0],
|
||||
setIsResolvedOpen = _useSafeState[1];
|
||||
|
||||
var _useSafeState2 = (0, _utils.useSafeState)(false),
|
||||
isResizing = _useSafeState2[0],
|
||||
setIsResizing = _useSafeState2[1];
|
||||
|
||||
var isMounted = (0, _utils.useIsMounted)();
|
||||
|
||||
var _handleDragStart = function handleDragStart(panelElement, startEvent) {
|
||||
var _panelElement$getBoun;
|
||||
|
||||
if (startEvent.button !== 0) return; // Only allow left click for drag
|
||||
|
||||
setIsResizing(true);
|
||||
var dragInfo = {
|
||||
originalHeight: (_panelElement$getBoun = panelElement == null ? void 0 : panelElement.getBoundingClientRect().height) != null ? _panelElement$getBoun : 0,
|
||||
pageY: startEvent.pageY
|
||||
};
|
||||
|
||||
var run = function run(moveEvent) {
|
||||
var delta = dragInfo.pageY - moveEvent.pageY;
|
||||
var newHeight = (dragInfo == null ? void 0 : dragInfo.originalHeight) + delta;
|
||||
setDevtoolsHeight(newHeight);
|
||||
|
||||
if (newHeight < 70) {
|
||||
setIsOpen(false);
|
||||
} else {
|
||||
setIsOpen(true);
|
||||
}
|
||||
};
|
||||
|
||||
var unsub = function unsub() {
|
||||
setIsResizing(false);
|
||||
document.removeEventListener('mousemove', run);
|
||||
document.removeEventListener('mouseUp', unsub);
|
||||
};
|
||||
|
||||
document.addEventListener('mousemove', run);
|
||||
document.addEventListener('mouseup', unsub);
|
||||
};
|
||||
|
||||
_react.default.useEffect(function () {
|
||||
setIsResolvedOpen(isOpen != null ? isOpen : false);
|
||||
}, [isOpen, isResolvedOpen, setIsResolvedOpen]); // Toggle panel visibility before/after transition (depending on direction).
|
||||
// Prevents focusing in a closed panel.
|
||||
|
||||
|
||||
_react.default.useEffect(function () {
|
||||
var ref = panelRef.current;
|
||||
|
||||
if (ref) {
|
||||
var handlePanelTransitionStart = function handlePanelTransitionStart() {
|
||||
if (ref && isResolvedOpen) {
|
||||
ref.style.visibility = 'visible';
|
||||
}
|
||||
};
|
||||
|
||||
var handlePanelTransitionEnd = function handlePanelTransitionEnd() {
|
||||
if (ref && !isResolvedOpen) {
|
||||
ref.style.visibility = 'hidden';
|
||||
}
|
||||
};
|
||||
|
||||
ref.addEventListener('transitionstart', handlePanelTransitionStart);
|
||||
ref.addEventListener('transitionend', handlePanelTransitionEnd);
|
||||
return function () {
|
||||
ref.removeEventListener('transitionstart', handlePanelTransitionStart);
|
||||
ref.removeEventListener('transitionend', handlePanelTransitionEnd);
|
||||
};
|
||||
}
|
||||
}, [isResolvedOpen]);
|
||||
|
||||
_react.default[isServer ? 'useEffect' : 'useLayoutEffect'](function () {
|
||||
if (isResolvedOpen) {
|
||||
var _rootRef$current, _rootRef$current$pare;
|
||||
|
||||
var previousValue = (_rootRef$current = rootRef.current) == null ? void 0 : (_rootRef$current$pare = _rootRef$current.parentElement) == null ? void 0 : _rootRef$current$pare.style.paddingBottom;
|
||||
|
||||
var run = function run() {
|
||||
var _panelRef$current, _rootRef$current2;
|
||||
|
||||
var containerHeight = (_panelRef$current = panelRef.current) == null ? void 0 : _panelRef$current.getBoundingClientRect().height;
|
||||
|
||||
if ((_rootRef$current2 = rootRef.current) == null ? void 0 : _rootRef$current2.parentElement) {
|
||||
rootRef.current.parentElement.style.paddingBottom = containerHeight + "px";
|
||||
}
|
||||
};
|
||||
|
||||
run();
|
||||
|
||||
if (typeof window !== 'undefined') {
|
||||
window.addEventListener('resize', run);
|
||||
return function () {
|
||||
var _rootRef$current3;
|
||||
|
||||
window.removeEventListener('resize', run);
|
||||
|
||||
if (((_rootRef$current3 = rootRef.current) == null ? void 0 : _rootRef$current3.parentElement) && typeof previousValue === 'string') {
|
||||
rootRef.current.parentElement.style.paddingBottom = previousValue;
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
}, [isResolvedOpen]);
|
||||
|
||||
var _panelProps$style = panelProps.style,
|
||||
panelStyle = _panelProps$style === void 0 ? {} : _panelProps$style,
|
||||
otherPanelProps = (0, _objectWithoutPropertiesLoose2.default)(panelProps, ["style"]);
|
||||
var _closeButtonProps$sty = closeButtonProps.style,
|
||||
closeButtonStyle = _closeButtonProps$sty === void 0 ? {} : _closeButtonProps$sty,
|
||||
onCloseClick = closeButtonProps.onClick,
|
||||
otherCloseButtonProps = (0, _objectWithoutPropertiesLoose2.default)(closeButtonProps, ["style", "onClick"]);
|
||||
var _toggleButtonProps$st = toggleButtonProps.style,
|
||||
toggleButtonStyle = _toggleButtonProps$st === void 0 ? {} : _toggleButtonProps$st,
|
||||
onToggleClick = toggleButtonProps.onClick,
|
||||
otherToggleButtonProps = (0, _objectWithoutPropertiesLoose2.default)(toggleButtonProps, ["style", "onClick"]); // Do not render on the server
|
||||
|
||||
if (!isMounted()) return null;
|
||||
return /*#__PURE__*/_react.default.createElement(Container, {
|
||||
ref: rootRef,
|
||||
className: "ReactQueryDevtools",
|
||||
"aria-label": "React Query Devtools"
|
||||
}, /*#__PURE__*/_react.default.createElement(_theme.ThemeProvider, {
|
||||
theme: _theme.defaultTheme
|
||||
}, /*#__PURE__*/_react.default.createElement(ReactQueryDevtoolsPanel, (0, _extends2.default)({
|
||||
ref: panelRef,
|
||||
styleNonce: styleNonce
|
||||
}, otherPanelProps, {
|
||||
style: (0, _extends2.default)({
|
||||
position: 'fixed',
|
||||
bottom: '0',
|
||||
right: '0',
|
||||
zIndex: 99999,
|
||||
width: '100%',
|
||||
height: devtoolsHeight != null ? devtoolsHeight : 500,
|
||||
maxHeight: '90%',
|
||||
boxShadow: '0 0 20px rgba(0,0,0,.3)',
|
||||
borderTop: "1px solid " + _theme.defaultTheme.gray,
|
||||
transformOrigin: 'top',
|
||||
// visibility will be toggled after transitions, but set initial state here
|
||||
visibility: isOpen ? 'visible' : 'hidden'
|
||||
}, panelStyle, isResizing ? {
|
||||
transition: "none"
|
||||
} : {
|
||||
transition: "all .2s ease"
|
||||
}, isResolvedOpen ? {
|
||||
opacity: 1,
|
||||
pointerEvents: 'all',
|
||||
transform: "translateY(0) scale(1)"
|
||||
} : {
|
||||
opacity: 0,
|
||||
pointerEvents: 'none',
|
||||
transform: "translateY(15px) scale(1.02)"
|
||||
}),
|
||||
isOpen: isResolvedOpen,
|
||||
setIsOpen: setIsOpen,
|
||||
handleDragStart: function handleDragStart(e) {
|
||||
return _handleDragStart(panelRef.current, e);
|
||||
}
|
||||
})), isResolvedOpen ? /*#__PURE__*/_react.default.createElement(_styledComponents.Button, (0, _extends2.default)({
|
||||
type: "button",
|
||||
"aria-controls": "ReactQueryDevtoolsPanel",
|
||||
"aria-haspopup": "true",
|
||||
"aria-expanded": "true"
|
||||
}, otherCloseButtonProps, {
|
||||
onClick: function onClick(e) {
|
||||
setIsOpen(false);
|
||||
onCloseClick && onCloseClick(e);
|
||||
},
|
||||
style: (0, _extends2.default)({
|
||||
position: 'fixed',
|
||||
zIndex: 99999,
|
||||
margin: '.5em',
|
||||
bottom: 0
|
||||
}, position === 'top-right' ? {
|
||||
right: '0'
|
||||
} : position === 'top-left' ? {
|
||||
left: '0'
|
||||
} : position === 'bottom-right' ? {
|
||||
right: '0'
|
||||
} : {
|
||||
left: '0'
|
||||
}, closeButtonStyle)
|
||||
}), "Close") : null), !isResolvedOpen ? /*#__PURE__*/_react.default.createElement("button", (0, _extends2.default)({
|
||||
type: "button"
|
||||
}, otherToggleButtonProps, {
|
||||
"aria-label": "Open React Query Devtools",
|
||||
"aria-controls": "ReactQueryDevtoolsPanel",
|
||||
"aria-haspopup": "true",
|
||||
"aria-expanded": "false",
|
||||
onClick: function onClick(e) {
|
||||
setIsOpen(true);
|
||||
onToggleClick && onToggleClick(e);
|
||||
},
|
||||
style: (0, _extends2.default)({
|
||||
background: 'none',
|
||||
border: 0,
|
||||
padding: 0,
|
||||
position: 'fixed',
|
||||
zIndex: 99999,
|
||||
display: 'inline-flex',
|
||||
fontSize: '1.5em',
|
||||
margin: '.5em',
|
||||
cursor: 'pointer',
|
||||
width: 'fit-content'
|
||||
}, position === 'top-right' ? {
|
||||
top: '0',
|
||||
right: '0'
|
||||
} : position === 'top-left' ? {
|
||||
top: '0',
|
||||
left: '0'
|
||||
} : position === 'bottom-right' ? {
|
||||
bottom: '0',
|
||||
right: '0'
|
||||
} : {
|
||||
bottom: '0',
|
||||
left: '0'
|
||||
}, toggleButtonStyle)
|
||||
}), /*#__PURE__*/_react.default.createElement(_Logo.default, {
|
||||
"aria-hidden": true
|
||||
})) : null);
|
||||
}
|
||||
|
||||
var getStatusRank = function getStatusRank(q) {
|
||||
return q.state.isFetching ? 0 : !q.getObserversCount() ? 3 : q.isStale() ? 2 : 1;
|
||||
};
|
||||
|
||||
var sortFns = {
|
||||
'Status > Last Updated': function StatusLastUpdated(a, b) {
|
||||
var _sortFns$LastUpdated;
|
||||
|
||||
return getStatusRank(a) === getStatusRank(b) ? (_sortFns$LastUpdated = sortFns['Last Updated']) == null ? void 0 : _sortFns$LastUpdated.call(sortFns, a, b) : getStatusRank(a) > getStatusRank(b) ? 1 : -1;
|
||||
},
|
||||
'Query Hash': function QueryHash(a, b) {
|
||||
return a.queryHash > b.queryHash ? 1 : -1;
|
||||
},
|
||||
'Last Updated': function LastUpdated(a, b) {
|
||||
return a.state.dataUpdatedAt < b.state.dataUpdatedAt ? 1 : -1;
|
||||
}
|
||||
};
|
||||
|
||||
var ReactQueryDevtoolsPanel = /*#__PURE__*/_react.default.forwardRef(function ReactQueryDevtoolsPanel(props, ref) {
|
||||
var _activeQuery$state;
|
||||
|
||||
var _props$isOpen = props.isOpen,
|
||||
isOpen = _props$isOpen === void 0 ? true : _props$isOpen,
|
||||
styleNonce = props.styleNonce,
|
||||
setIsOpen = props.setIsOpen,
|
||||
handleDragStart = props.handleDragStart,
|
||||
panelProps = (0, _objectWithoutPropertiesLoose2.default)(props, ["isOpen", "styleNonce", "setIsOpen", "handleDragStart"]);
|
||||
var queryClient = (0, _reactQuery.useQueryClient)();
|
||||
var queryCache = queryClient.getQueryCache();
|
||||
|
||||
var _useLocalStorage3 = (0, _useLocalStorage7.default)('reactQueryDevtoolsSortFn', Object.keys(sortFns)[0]),
|
||||
sort = _useLocalStorage3[0],
|
||||
setSort = _useLocalStorage3[1];
|
||||
|
||||
var _useLocalStorage4 = (0, _useLocalStorage7.default)('reactQueryDevtoolsFilter', ''),
|
||||
filter = _useLocalStorage4[0],
|
||||
setFilter = _useLocalStorage4[1];
|
||||
|
||||
var _useLocalStorage5 = (0, _useLocalStorage7.default)('reactQueryDevtoolsSortDesc', false),
|
||||
sortDesc = _useLocalStorage5[0],
|
||||
setSortDesc = _useLocalStorage5[1];
|
||||
|
||||
var sortFn = _react.default.useMemo(function () {
|
||||
return sortFns[sort];
|
||||
}, [sort]);
|
||||
|
||||
_react.default[isServer ? 'useEffect' : 'useLayoutEffect'](function () {
|
||||
if (!sortFn) {
|
||||
setSort(Object.keys(sortFns)[0]);
|
||||
}
|
||||
}, [setSort, sortFn]);
|
||||
|
||||
var _useSafeState3 = (0, _utils.useSafeState)(Object.values(queryCache.findAll())),
|
||||
unsortedQueries = _useSafeState3[0],
|
||||
setUnsortedQueries = _useSafeState3[1];
|
||||
|
||||
var _useLocalStorage6 = (0, _useLocalStorage7.default)('reactQueryDevtoolsActiveQueryHash', ''),
|
||||
activeQueryHash = _useLocalStorage6[0],
|
||||
setActiveQueryHash = _useLocalStorage6[1];
|
||||
|
||||
var queries = _react.default.useMemo(function () {
|
||||
var sorted = [].concat(unsortedQueries).sort(sortFn);
|
||||
|
||||
if (sortDesc) {
|
||||
sorted.reverse();
|
||||
}
|
||||
|
||||
if (!filter) {
|
||||
return sorted;
|
||||
}
|
||||
|
||||
return (0, _matchSorter.matchSorter)(sorted, filter, {
|
||||
keys: ['queryHash']
|
||||
}).filter(function (d) {
|
||||
return d.queryHash;
|
||||
});
|
||||
}, [sortDesc, sortFn, unsortedQueries, filter]);
|
||||
|
||||
var activeQuery = _react.default.useMemo(function () {
|
||||
return queries.find(function (query) {
|
||||
return query.queryHash === activeQueryHash;
|
||||
});
|
||||
}, [activeQueryHash, queries]);
|
||||
|
||||
var hasFresh = queries.filter(function (q) {
|
||||
return (0, _utils.getQueryStatusLabel)(q) === 'fresh';
|
||||
}).length;
|
||||
var hasFetching = queries.filter(function (q) {
|
||||
return (0, _utils.getQueryStatusLabel)(q) === 'fetching';
|
||||
}).length;
|
||||
var hasStale = queries.filter(function (q) {
|
||||
return (0, _utils.getQueryStatusLabel)(q) === 'stale';
|
||||
}).length;
|
||||
var hasInactive = queries.filter(function (q) {
|
||||
return (0, _utils.getQueryStatusLabel)(q) === 'inactive';
|
||||
}).length;
|
||||
|
||||
_react.default.useEffect(function () {
|
||||
if (isOpen) {
|
||||
var unsubscribe = queryCache.subscribe(function () {
|
||||
setUnsortedQueries(Object.values(queryCache.getAll()));
|
||||
}); // re-subscribing after the panel is closed and re-opened won't trigger the callback,
|
||||
// So we'll manually populate our state
|
||||
|
||||
setUnsortedQueries(Object.values(queryCache.getAll()));
|
||||
return unsubscribe;
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}, [isOpen, sort, sortFn, sortDesc, setUnsortedQueries, queryCache]);
|
||||
|
||||
var handleRefetch = function handleRefetch() {
|
||||
var promise = activeQuery == null ? void 0 : activeQuery.fetch();
|
||||
promise == null ? void 0 : promise.catch(_utils2.noop);
|
||||
};
|
||||
|
||||
return /*#__PURE__*/_react.default.createElement(_theme.ThemeProvider, {
|
||||
theme: _theme.defaultTheme
|
||||
}, /*#__PURE__*/_react.default.createElement(_styledComponents.Panel, (0, _extends2.default)({
|
||||
ref: ref,
|
||||
className: "ReactQueryDevtoolsPanel",
|
||||
"aria-label": "React Query Devtools Panel",
|
||||
id: "ReactQueryDevtoolsPanel"
|
||||
}, panelProps), /*#__PURE__*/_react.default.createElement("style", {
|
||||
nonce: styleNonce,
|
||||
dangerouslySetInnerHTML: {
|
||||
__html: "\n .ReactQueryDevtoolsPanel * {\n scrollbar-color: " + _theme.defaultTheme.backgroundAlt + " " + _theme.defaultTheme.gray + ";\n }\n\n .ReactQueryDevtoolsPanel *::-webkit-scrollbar, .ReactQueryDevtoolsPanel scrollbar {\n width: 1em;\n height: 1em;\n }\n\n .ReactQueryDevtoolsPanel *::-webkit-scrollbar-track, .ReactQueryDevtoolsPanel scrollbar-track {\n background: " + _theme.defaultTheme.backgroundAlt + ";\n }\n\n .ReactQueryDevtoolsPanel *::-webkit-scrollbar-thumb, .ReactQueryDevtoolsPanel scrollbar-thumb {\n background: " + _theme.defaultTheme.gray + ";\n border-radius: .5em;\n border: 3px solid " + _theme.defaultTheme.backgroundAlt + ";\n }\n "
|
||||
}
|
||||
}), /*#__PURE__*/_react.default.createElement("div", {
|
||||
style: {
|
||||
position: 'absolute',
|
||||
left: 0,
|
||||
top: 0,
|
||||
width: '100%',
|
||||
height: '4px',
|
||||
marginBottom: '-4px',
|
||||
cursor: 'row-resize',
|
||||
zIndex: 100000
|
||||
},
|
||||
onMouseDown: handleDragStart
|
||||
}), /*#__PURE__*/_react.default.createElement("div", {
|
||||
style: {
|
||||
flex: '1 1 500px',
|
||||
minHeight: '40%',
|
||||
maxHeight: '100%',
|
||||
overflow: 'auto',
|
||||
borderRight: "1px solid " + _theme.defaultTheme.grayAlt,
|
||||
display: isOpen ? 'flex' : 'none',
|
||||
flexDirection: 'column'
|
||||
}
|
||||
}, /*#__PURE__*/_react.default.createElement("div", {
|
||||
style: {
|
||||
padding: '.5em',
|
||||
background: _theme.defaultTheme.backgroundAlt,
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center'
|
||||
}
|
||||
}, /*#__PURE__*/_react.default.createElement("button", {
|
||||
type: "button",
|
||||
"aria-label": "Close React Query Devtools",
|
||||
"aria-controls": "ReactQueryDevtoolsPanel",
|
||||
"aria-haspopup": "true",
|
||||
"aria-expanded": "true",
|
||||
onClick: function onClick() {
|
||||
return setIsOpen(false);
|
||||
},
|
||||
style: {
|
||||
display: 'inline-flex',
|
||||
background: 'none',
|
||||
border: 0,
|
||||
padding: 0,
|
||||
marginRight: '.5em',
|
||||
cursor: 'pointer'
|
||||
}
|
||||
}, /*#__PURE__*/_react.default.createElement(_Logo.default, {
|
||||
"aria-hidden": true
|
||||
})), /*#__PURE__*/_react.default.createElement("div", {
|
||||
style: {
|
||||
display: 'flex',
|
||||
flexDirection: 'column'
|
||||
}
|
||||
}, /*#__PURE__*/_react.default.createElement(_styledComponents.QueryKeys, {
|
||||
style: {
|
||||
marginBottom: '.5em'
|
||||
}
|
||||
}, /*#__PURE__*/_react.default.createElement(_styledComponents.QueryKey, {
|
||||
style: {
|
||||
background: _theme.defaultTheme.success,
|
||||
opacity: hasFresh ? 1 : 0.3
|
||||
}
|
||||
}, "fresh ", /*#__PURE__*/_react.default.createElement(_styledComponents.Code, null, "(", hasFresh, ")")), ' ', /*#__PURE__*/_react.default.createElement(_styledComponents.QueryKey, {
|
||||
style: {
|
||||
background: _theme.defaultTheme.active,
|
||||
opacity: hasFetching ? 1 : 0.3
|
||||
}
|
||||
}, "fetching ", /*#__PURE__*/_react.default.createElement(_styledComponents.Code, null, "(", hasFetching, ")")), ' ', /*#__PURE__*/_react.default.createElement(_styledComponents.QueryKey, {
|
||||
style: {
|
||||
background: _theme.defaultTheme.warning,
|
||||
color: 'black',
|
||||
textShadow: '0',
|
||||
opacity: hasStale ? 1 : 0.3
|
||||
}
|
||||
}, "stale ", /*#__PURE__*/_react.default.createElement(_styledComponents.Code, null, "(", hasStale, ")")), ' ', /*#__PURE__*/_react.default.createElement(_styledComponents.QueryKey, {
|
||||
style: {
|
||||
background: _theme.defaultTheme.gray,
|
||||
opacity: hasInactive ? 1 : 0.3
|
||||
}
|
||||
}, "inactive ", /*#__PURE__*/_react.default.createElement(_styledComponents.Code, null, "(", hasInactive, ")"))), /*#__PURE__*/_react.default.createElement("div", {
|
||||
style: {
|
||||
display: 'flex',
|
||||
alignItems: 'center'
|
||||
}
|
||||
}, /*#__PURE__*/_react.default.createElement(_styledComponents.Input, {
|
||||
placeholder: "Filter",
|
||||
"aria-label": "Filter by queryhash",
|
||||
value: filter != null ? filter : '',
|
||||
onChange: function onChange(e) {
|
||||
return setFilter(e.target.value);
|
||||
},
|
||||
onKeyDown: function onKeyDown(e) {
|
||||
if (e.key === 'Escape') setFilter('');
|
||||
},
|
||||
style: {
|
||||
flex: '1',
|
||||
marginRight: '.5em',
|
||||
width: '100%'
|
||||
}
|
||||
}), !filter ? /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_styledComponents.Select, {
|
||||
"aria-label": "Sort queries",
|
||||
value: sort,
|
||||
onChange: function onChange(e) {
|
||||
return setSort(e.target.value);
|
||||
},
|
||||
style: {
|
||||
flex: '1',
|
||||
minWidth: 75,
|
||||
marginRight: '.5em'
|
||||
}
|
||||
}, Object.keys(sortFns).map(function (key) {
|
||||
return /*#__PURE__*/_react.default.createElement("option", {
|
||||
key: key,
|
||||
value: key
|
||||
}, "Sort by ", key);
|
||||
})), /*#__PURE__*/_react.default.createElement(_styledComponents.Button, {
|
||||
type: "button",
|
||||
onClick: function onClick() {
|
||||
return setSortDesc(function (old) {
|
||||
return !old;
|
||||
});
|
||||
},
|
||||
style: {
|
||||
padding: '.3em .4em'
|
||||
}
|
||||
}, sortDesc ? '⬇ Desc' : '⬆ Asc')) : null))), /*#__PURE__*/_react.default.createElement("div", {
|
||||
style: {
|
||||
overflowY: 'auto',
|
||||
flex: '1'
|
||||
}
|
||||
}, queries.map(function (query, i) {
|
||||
var isDisabled = query.getObserversCount() > 0 && !query.isActive();
|
||||
return /*#__PURE__*/_react.default.createElement("div", {
|
||||
key: query.queryHash || i,
|
||||
role: "button",
|
||||
"aria-label": "Open query details for " + query.queryHash,
|
||||
onClick: function onClick() {
|
||||
return setActiveQueryHash(activeQueryHash === query.queryHash ? '' : query.queryHash);
|
||||
},
|
||||
style: {
|
||||
display: 'flex',
|
||||
borderBottom: "solid 1px " + _theme.defaultTheme.grayAlt,
|
||||
cursor: 'pointer',
|
||||
background: query === activeQuery ? 'rgba(255,255,255,.1)' : undefined
|
||||
}
|
||||
}, /*#__PURE__*/_react.default.createElement("div", {
|
||||
style: {
|
||||
flex: '0 0 auto',
|
||||
width: '2em',
|
||||
height: '2em',
|
||||
background: (0, _utils.getQueryStatusColor)(query, _theme.defaultTheme),
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
fontWeight: 'bold',
|
||||
textShadow: (0, _utils.getQueryStatusLabel)(query) === 'stale' ? '0' : '0 0 10px black',
|
||||
color: (0, _utils.getQueryStatusLabel)(query) === 'stale' ? 'black' : 'white'
|
||||
}
|
||||
}, query.getObserversCount()), isDisabled ? /*#__PURE__*/_react.default.createElement("div", {
|
||||
style: {
|
||||
flex: '0 0 auto',
|
||||
height: '2em',
|
||||
background: _theme.defaultTheme.gray,
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
fontWeight: 'bold',
|
||||
padding: '0 0.5em'
|
||||
}
|
||||
}, "disabled") : null, /*#__PURE__*/_react.default.createElement(_styledComponents.Code, {
|
||||
style: {
|
||||
padding: '.5em'
|
||||
}
|
||||
}, "" + query.queryHash));
|
||||
}))), activeQuery ? /*#__PURE__*/_react.default.createElement(_styledComponents.ActiveQueryPanel, null, /*#__PURE__*/_react.default.createElement("div", {
|
||||
style: {
|
||||
padding: '.5em',
|
||||
background: _theme.defaultTheme.backgroundAlt,
|
||||
position: 'sticky',
|
||||
top: 0,
|
||||
zIndex: 1
|
||||
}
|
||||
}, "Query Details"), /*#__PURE__*/_react.default.createElement("div", {
|
||||
style: {
|
||||
padding: '.5em'
|
||||
}
|
||||
}, /*#__PURE__*/_react.default.createElement("div", {
|
||||
style: {
|
||||
marginBottom: '.5em',
|
||||
display: 'flex',
|
||||
alignItems: 'start',
|
||||
justifyContent: 'space-between'
|
||||
}
|
||||
}, /*#__PURE__*/_react.default.createElement(_styledComponents.Code, {
|
||||
style: {
|
||||
lineHeight: '1.8em'
|
||||
}
|
||||
}, /*#__PURE__*/_react.default.createElement("pre", {
|
||||
style: {
|
||||
margin: 0,
|
||||
padding: 0,
|
||||
overflow: 'auto'
|
||||
}
|
||||
}, JSON.stringify(activeQuery.queryKey, null, 2))), /*#__PURE__*/_react.default.createElement("span", {
|
||||
style: {
|
||||
padding: '0.3em .6em',
|
||||
borderRadius: '0.4em',
|
||||
fontWeight: 'bold',
|
||||
textShadow: '0 2px 10px black',
|
||||
background: (0, _utils.getQueryStatusColor)(activeQuery, _theme.defaultTheme),
|
||||
flexShrink: 0
|
||||
}
|
||||
}, (0, _utils.getQueryStatusLabel)(activeQuery))), /*#__PURE__*/_react.default.createElement("div", {
|
||||
style: {
|
||||
marginBottom: '.5em',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'space-between'
|
||||
}
|
||||
}, "Observers: ", /*#__PURE__*/_react.default.createElement(_styledComponents.Code, null, activeQuery.getObserversCount())), /*#__PURE__*/_react.default.createElement("div", {
|
||||
style: {
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'space-between'
|
||||
}
|
||||
}, "Last Updated:", ' ', /*#__PURE__*/_react.default.createElement(_styledComponents.Code, null, new Date(activeQuery.state.dataUpdatedAt).toLocaleTimeString()))), /*#__PURE__*/_react.default.createElement("div", {
|
||||
style: {
|
||||
background: _theme.defaultTheme.backgroundAlt,
|
||||
padding: '.5em',
|
||||
position: 'sticky',
|
||||
top: 0,
|
||||
zIndex: 1
|
||||
}
|
||||
}, "Actions"), /*#__PURE__*/_react.default.createElement("div", {
|
||||
style: {
|
||||
padding: '0.5em'
|
||||
}
|
||||
}, /*#__PURE__*/_react.default.createElement(_styledComponents.Button, {
|
||||
type: "button",
|
||||
onClick: handleRefetch,
|
||||
disabled: activeQuery.state.isFetching,
|
||||
style: {
|
||||
background: _theme.defaultTheme.active
|
||||
}
|
||||
}, "Refetch"), ' ', /*#__PURE__*/_react.default.createElement(_styledComponents.Button, {
|
||||
type: "button",
|
||||
onClick: function onClick() {
|
||||
return queryClient.invalidateQueries(activeQuery);
|
||||
},
|
||||
style: {
|
||||
background: _theme.defaultTheme.warning,
|
||||
color: _theme.defaultTheme.inputTextColor
|
||||
}
|
||||
}, "Invalidate"), ' ', /*#__PURE__*/_react.default.createElement(_styledComponents.Button, {
|
||||
type: "button",
|
||||
onClick: function onClick() {
|
||||
return queryClient.resetQueries(activeQuery);
|
||||
},
|
||||
style: {
|
||||
background: _theme.defaultTheme.gray
|
||||
}
|
||||
}, "Reset"), ' ', /*#__PURE__*/_react.default.createElement(_styledComponents.Button, {
|
||||
type: "button",
|
||||
onClick: function onClick() {
|
||||
return queryClient.removeQueries(activeQuery);
|
||||
},
|
||||
style: {
|
||||
background: _theme.defaultTheme.danger
|
||||
}
|
||||
}, "Remove")), /*#__PURE__*/_react.default.createElement("div", {
|
||||
style: {
|
||||
background: _theme.defaultTheme.backgroundAlt,
|
||||
padding: '.5em',
|
||||
position: 'sticky',
|
||||
top: 0,
|
||||
zIndex: 1
|
||||
}
|
||||
}, "Data Explorer"), /*#__PURE__*/_react.default.createElement("div", {
|
||||
style: {
|
||||
padding: '.5em'
|
||||
}
|
||||
}, /*#__PURE__*/_react.default.createElement(_Explorer.default, {
|
||||
label: "Data",
|
||||
value: activeQuery == null ? void 0 : (_activeQuery$state = activeQuery.state) == null ? void 0 : _activeQuery$state.data,
|
||||
defaultExpanded: {}
|
||||
})), /*#__PURE__*/_react.default.createElement("div", {
|
||||
style: {
|
||||
background: _theme.defaultTheme.backgroundAlt,
|
||||
padding: '.5em',
|
||||
position: 'sticky',
|
||||
top: 0,
|
||||
zIndex: 1
|
||||
}
|
||||
}, "Query Explorer"), /*#__PURE__*/_react.default.createElement("div", {
|
||||
style: {
|
||||
padding: '.5em'
|
||||
}
|
||||
}, /*#__PURE__*/_react.default.createElement(_Explorer.default, {
|
||||
label: "Query",
|
||||
value: activeQuery,
|
||||
defaultExpanded: {
|
||||
queryKey: true
|
||||
}
|
||||
}))) : null));
|
||||
});
|
||||
|
||||
exports.ReactQueryDevtoolsPanel = ReactQueryDevtoolsPanel;
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
"use strict";
|
||||
|
||||
exports.__esModule = true;
|
||||
|
||||
var _devtools = require("./devtools");
|
||||
|
||||
Object.keys(_devtools).forEach(function (key) {
|
||||
if (key === "default" || key === "__esModule") return;
|
||||
exports[key] = _devtools[key];
|
||||
});
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
"use strict";
|
||||
|
||||
exports.__esModule = true;
|
||||
exports.Select = exports.Input = exports.Code = exports.QueryKey = exports.QueryKeys = exports.Button = exports.ActiveQueryPanel = exports.Panel = void 0;
|
||||
|
||||
var _utils = require("./utils");
|
||||
|
||||
var Panel = (0, _utils.styled)('div', function (_props, theme) {
|
||||
return {
|
||||
fontSize: 'clamp(12px, 1.5vw, 14px)',
|
||||
fontFamily: "sans-serif",
|
||||
display: 'flex',
|
||||
backgroundColor: theme.background,
|
||||
color: theme.foreground
|
||||
};
|
||||
}, {
|
||||
'(max-width: 700px)': {
|
||||
flexDirection: 'column'
|
||||
},
|
||||
'(max-width: 600px)': {
|
||||
fontSize: '.9em' // flexDirection: 'column',
|
||||
|
||||
}
|
||||
});
|
||||
exports.Panel = Panel;
|
||||
var ActiveQueryPanel = (0, _utils.styled)('div', function () {
|
||||
return {
|
||||
flex: '1 1 500px',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
overflow: 'auto',
|
||||
height: '100%'
|
||||
};
|
||||
}, {
|
||||
'(max-width: 700px)': function maxWidth700px(_props, theme) {
|
||||
return {
|
||||
borderTop: "2px solid " + theme.gray
|
||||
};
|
||||
}
|
||||
});
|
||||
exports.ActiveQueryPanel = ActiveQueryPanel;
|
||||
var Button = (0, _utils.styled)('button', function (props, theme) {
|
||||
return {
|
||||
appearance: 'none',
|
||||
fontSize: '.9em',
|
||||
fontWeight: 'bold',
|
||||
background: theme.gray,
|
||||
border: '0',
|
||||
borderRadius: '.3em',
|
||||
color: 'white',
|
||||
padding: '.5em',
|
||||
opacity: props.disabled ? '.5' : undefined,
|
||||
cursor: 'pointer'
|
||||
};
|
||||
});
|
||||
exports.Button = Button;
|
||||
var QueryKeys = (0, _utils.styled)('span', {
|
||||
display: 'inline-block',
|
||||
fontSize: '0.9em'
|
||||
});
|
||||
exports.QueryKeys = QueryKeys;
|
||||
var QueryKey = (0, _utils.styled)('span', {
|
||||
display: 'inline-flex',
|
||||
alignItems: 'center',
|
||||
padding: '.2em .4em',
|
||||
fontWeight: 'bold',
|
||||
textShadow: '0 0 10px black',
|
||||
borderRadius: '.2em'
|
||||
});
|
||||
exports.QueryKey = QueryKey;
|
||||
var Code = (0, _utils.styled)('code', {
|
||||
fontSize: '.9em',
|
||||
color: 'inherit',
|
||||
background: 'inherit'
|
||||
});
|
||||
exports.Code = Code;
|
||||
var Input = (0, _utils.styled)('input', function (_props, theme) {
|
||||
return {
|
||||
backgroundColor: theme.inputBackgroundColor,
|
||||
border: 0,
|
||||
borderRadius: '.2em',
|
||||
color: theme.inputTextColor,
|
||||
fontSize: '.9em',
|
||||
lineHeight: "1.3",
|
||||
padding: '.3em .4em'
|
||||
};
|
||||
});
|
||||
exports.Input = Input;
|
||||
var Select = (0, _utils.styled)('select', function (_props, theme) {
|
||||
return {
|
||||
display: "inline-block",
|
||||
fontSize: ".9em",
|
||||
fontFamily: "sans-serif",
|
||||
fontWeight: 'normal',
|
||||
lineHeight: "1.3",
|
||||
padding: ".3em 1.5em .3em .5em",
|
||||
height: 'auto',
|
||||
border: 0,
|
||||
borderRadius: ".2em",
|
||||
appearance: "none",
|
||||
WebkitAppearance: 'none',
|
||||
backgroundColor: theme.inputBackgroundColor,
|
||||
backgroundImage: "url(\"data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='100' height='100' fill='%23444444'><polygon points='0,25 100,25 50,75'/></svg>\")",
|
||||
backgroundRepeat: "no-repeat",
|
||||
backgroundPosition: "right .55em center",
|
||||
backgroundSize: ".65em auto, 100%",
|
||||
color: theme.inputTextColor
|
||||
};
|
||||
}, {
|
||||
'(max-width: 500px)': {
|
||||
display: 'none'
|
||||
}
|
||||
});
|
||||
exports.Select = Select;
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
"use strict";
|
||||
|
||||
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
|
||||
|
||||
exports.__esModule = true;
|
||||
exports.ThemeProvider = ThemeProvider;
|
||||
exports.useTheme = useTheme;
|
||||
exports.defaultTheme = void 0;
|
||||
|
||||
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
|
||||
|
||||
var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));
|
||||
|
||||
var _react = _interopRequireDefault(require("react"));
|
||||
|
||||
var defaultTheme = {
|
||||
background: '#0b1521',
|
||||
backgroundAlt: '#132337',
|
||||
foreground: 'white',
|
||||
gray: '#3f4e60',
|
||||
grayAlt: '#222e3e',
|
||||
inputBackgroundColor: '#fff',
|
||||
inputTextColor: '#000',
|
||||
success: '#00ab52',
|
||||
danger: '#ff0085',
|
||||
active: '#006bff',
|
||||
warning: '#ffb200'
|
||||
};
|
||||
exports.defaultTheme = defaultTheme;
|
||||
|
||||
var ThemeContext = /*#__PURE__*/_react.default.createContext(defaultTheme);
|
||||
|
||||
function ThemeProvider(_ref) {
|
||||
var theme = _ref.theme,
|
||||
rest = (0, _objectWithoutPropertiesLoose2.default)(_ref, ["theme"]);
|
||||
return /*#__PURE__*/_react.default.createElement(ThemeContext.Provider, (0, _extends2.default)({
|
||||
value: theme
|
||||
}, rest));
|
||||
}
|
||||
|
||||
function useTheme() {
|
||||
return _react.default.useContext(ThemeContext);
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
"use strict";
|
||||
|
||||
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
|
||||
|
||||
exports.__esModule = true;
|
||||
exports.default = useLocalStorage;
|
||||
|
||||
var _react = _interopRequireDefault(require("react"));
|
||||
|
||||
var getItem = function getItem(key) {
|
||||
try {
|
||||
var itemValue = localStorage.getItem(key);
|
||||
|
||||
if (typeof itemValue === 'string') {
|
||||
return JSON.parse(itemValue);
|
||||
}
|
||||
|
||||
return undefined;
|
||||
} catch (_unused) {
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
|
||||
function useLocalStorage(key, defaultValue) {
|
||||
var _React$useState = _react.default.useState(),
|
||||
value = _React$useState[0],
|
||||
setValue = _React$useState[1];
|
||||
|
||||
_react.default.useEffect(function () {
|
||||
var initialValue = getItem(key);
|
||||
|
||||
if (typeof initialValue === 'undefined' || initialValue === null) {
|
||||
setValue(typeof defaultValue === 'function' ? defaultValue() : defaultValue);
|
||||
} else {
|
||||
setValue(initialValue);
|
||||
}
|
||||
}, [defaultValue, key]);
|
||||
|
||||
var setter = _react.default.useCallback(function (updater) {
|
||||
setValue(function (old) {
|
||||
var newVal = updater;
|
||||
|
||||
if (typeof updater == 'function') {
|
||||
newVal = updater(old);
|
||||
}
|
||||
|
||||
try {
|
||||
localStorage.setItem(key, JSON.stringify(newVal));
|
||||
} catch (_unused2) {}
|
||||
|
||||
return newVal;
|
||||
});
|
||||
}, [key]);
|
||||
|
||||
return [value, setter];
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
"use strict";
|
||||
|
||||
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
|
||||
|
||||
exports.__esModule = true;
|
||||
exports.default = useMediaQuery;
|
||||
|
||||
var _react = _interopRequireDefault(require("react"));
|
||||
|
||||
function useMediaQuery(query) {
|
||||
// Keep track of the preference in state, start with the current match
|
||||
var _React$useState = _react.default.useState(function () {
|
||||
if (typeof window !== 'undefined') {
|
||||
return window.matchMedia && window.matchMedia(query).matches;
|
||||
}
|
||||
}),
|
||||
isMatch = _React$useState[0],
|
||||
setIsMatch = _React$useState[1]; // Watch for changes
|
||||
|
||||
|
||||
_react.default.useEffect(function () {
|
||||
if (typeof window !== 'undefined') {
|
||||
if (!window.matchMedia) {
|
||||
return;
|
||||
} // Create a matcher
|
||||
|
||||
|
||||
var matcher = window.matchMedia(query); // Create our handler
|
||||
|
||||
var onChange = function onChange(_ref) {
|
||||
var matches = _ref.matches;
|
||||
return setIsMatch(matches);
|
||||
}; // Listen for changes
|
||||
|
||||
|
||||
matcher.addListener(onChange);
|
||||
return function () {
|
||||
// Stop listening for changes
|
||||
matcher.removeListener(onChange);
|
||||
};
|
||||
}
|
||||
}, [isMatch, query, setIsMatch]);
|
||||
|
||||
return isMatch;
|
||||
}
|
||||
+121
@@ -0,0 +1,121 @@
|
||||
"use strict";
|
||||
|
||||
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
|
||||
|
||||
exports.__esModule = true;
|
||||
exports.getQueryStatusColor = getQueryStatusColor;
|
||||
exports.getQueryStatusLabel = getQueryStatusLabel;
|
||||
exports.styled = styled;
|
||||
exports.useIsMounted = useIsMounted;
|
||||
exports.useSafeState = useSafeState;
|
||||
exports.displayValue = exports.isServer = void 0;
|
||||
|
||||
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
|
||||
|
||||
var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));
|
||||
|
||||
var _react = _interopRequireDefault(require("react"));
|
||||
|
||||
var _theme = require("./theme");
|
||||
|
||||
var _useMediaQuery = _interopRequireDefault(require("./useMediaQuery"));
|
||||
|
||||
var isServer = typeof window === 'undefined';
|
||||
exports.isServer = isServer;
|
||||
|
||||
function getQueryStatusColor(query, theme) {
|
||||
return query.state.isFetching ? theme.active : !query.getObserversCount() ? theme.gray : query.isStale() ? theme.warning : theme.success;
|
||||
}
|
||||
|
||||
function getQueryStatusLabel(query) {
|
||||
return query.state.isFetching ? 'fetching' : !query.getObserversCount() ? 'inactive' : query.isStale() ? 'stale' : 'fresh';
|
||||
}
|
||||
|
||||
function styled(type, newStyles, queries) {
|
||||
if (queries === void 0) {
|
||||
queries = {};
|
||||
}
|
||||
|
||||
return /*#__PURE__*/_react.default.forwardRef(function (_ref, ref) {
|
||||
var style = _ref.style,
|
||||
rest = (0, _objectWithoutPropertiesLoose2.default)(_ref, ["style"]);
|
||||
var theme = (0, _theme.useTheme)();
|
||||
var mediaStyles = Object.entries(queries).reduce(function (current, _ref2) {
|
||||
var key = _ref2[0],
|
||||
value = _ref2[1];
|
||||
// eslint-disable-next-line react-hooks/rules-of-hooks
|
||||
return (0, _useMediaQuery.default)(key) ? (0, _extends2.default)({}, current, typeof value === 'function' ? value(rest, theme) : value) : current;
|
||||
}, {});
|
||||
return /*#__PURE__*/_react.default.createElement(type, (0, _extends2.default)({}, rest, {
|
||||
style: (0, _extends2.default)({}, typeof newStyles === 'function' ? newStyles(rest, theme) : newStyles, style, mediaStyles),
|
||||
ref: ref
|
||||
}));
|
||||
});
|
||||
}
|
||||
|
||||
function useIsMounted() {
|
||||
var mountedRef = _react.default.useRef(false);
|
||||
|
||||
var isMounted = _react.default.useCallback(function () {
|
||||
return mountedRef.current;
|
||||
}, []);
|
||||
|
||||
_react.default[isServer ? 'useEffect' : 'useLayoutEffect'](function () {
|
||||
mountedRef.current = true;
|
||||
return function () {
|
||||
mountedRef.current = false;
|
||||
};
|
||||
}, []);
|
||||
|
||||
return isMounted;
|
||||
}
|
||||
/**
|
||||
* This hook is a safe useState version which schedules state updates in microtasks
|
||||
* to prevent updating a component state while React is rendering different components
|
||||
* or when the component is not mounted anymore.
|
||||
*/
|
||||
|
||||
|
||||
function useSafeState(initialState) {
|
||||
var isMounted = useIsMounted();
|
||||
|
||||
var _React$useState = _react.default.useState(initialState),
|
||||
state = _React$useState[0],
|
||||
setState = _React$useState[1];
|
||||
|
||||
var safeSetState = _react.default.useCallback(function (value) {
|
||||
scheduleMicrotask(function () {
|
||||
if (isMounted()) {
|
||||
setState(value);
|
||||
}
|
||||
});
|
||||
}, [isMounted]);
|
||||
|
||||
return [state, safeSetState];
|
||||
}
|
||||
/**
|
||||
* Displays a string regardless the type of the data
|
||||
* @param {unknown} value Value to be stringified
|
||||
*/
|
||||
|
||||
|
||||
var displayValue = function displayValue(value) {
|
||||
var name = Object.getOwnPropertyNames(Object(value));
|
||||
var newValue = typeof value === 'bigint' ? value.toString() + "n" : value;
|
||||
return JSON.stringify(newValue, name);
|
||||
};
|
||||
/**
|
||||
* Schedules a microtask.
|
||||
* This can be useful to schedule state updates after rendering.
|
||||
*/
|
||||
|
||||
|
||||
exports.displayValue = displayValue;
|
||||
|
||||
function scheduleMicrotask(callback) {
|
||||
Promise.resolve().then(callback).catch(function (error) {
|
||||
return setTimeout(function () {
|
||||
throw error;
|
||||
});
|
||||
});
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
"use strict";
|
||||
|
||||
exports.__esModule = true;
|
||||
exports.Hydrate = exports.useHydrate = exports.hydrate = exports.dehydrate = void 0;
|
||||
|
||||
var _reactQuery = require("react-query");
|
||||
|
||||
exports.dehydrate = _reactQuery.dehydrate;
|
||||
exports.hydrate = _reactQuery.hydrate;
|
||||
exports.useHydrate = _reactQuery.useHydrate;
|
||||
exports.Hydrate = _reactQuery.Hydrate;
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
"use strict";
|
||||
|
||||
exports.__esModule = true;
|
||||
|
||||
var _core = require("./core");
|
||||
|
||||
Object.keys(_core).forEach(function (key) {
|
||||
if (key === "default" || key === "__esModule") return;
|
||||
exports[key] = _core[key];
|
||||
});
|
||||
|
||||
var _react = require("./react");
|
||||
|
||||
Object.keys(_react).forEach(function (key) {
|
||||
if (key === "default" || key === "__esModule") return;
|
||||
exports[key] = _react[key];
|
||||
});
|
||||
Generated
Vendored
+115
@@ -0,0 +1,115 @@
|
||||
"use strict";
|
||||
|
||||
exports.__esModule = true;
|
||||
exports.persistQueryClient = void 0;
|
||||
|
||||
var _logger = require("../core/logger");
|
||||
|
||||
var _reactQuery = require("react-query");
|
||||
|
||||
function _await(value, then, direct) {
|
||||
if (direct) {
|
||||
return then ? then(value) : value;
|
||||
}
|
||||
|
||||
if (!value || !value.then) {
|
||||
value = Promise.resolve(value);
|
||||
}
|
||||
|
||||
return then ? value.then(then) : value;
|
||||
}
|
||||
|
||||
function _catch(body, recover) {
|
||||
try {
|
||||
var result = body();
|
||||
} catch (e) {
|
||||
return recover(e);
|
||||
}
|
||||
|
||||
if (result && result.then) {
|
||||
return result.then(void 0, recover);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function _continue(value, then) {
|
||||
return value && value.then ? value.then(then) : then(value);
|
||||
}
|
||||
|
||||
function _empty() {}
|
||||
|
||||
function _invokeIgnored(body) {
|
||||
var result = body();
|
||||
|
||||
if (result && result.then) {
|
||||
return result.then(_empty);
|
||||
}
|
||||
}
|
||||
|
||||
function _async(f) {
|
||||
return function () {
|
||||
for (var args = [], i = 0; i < arguments.length; i++) {
|
||||
args[i] = arguments[i];
|
||||
}
|
||||
|
||||
try {
|
||||
return Promise.resolve(f.apply(this, args));
|
||||
} catch (e) {
|
||||
return Promise.reject(e);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
var persistQueryClient = _async(function (_ref) {
|
||||
var queryClient = _ref.queryClient,
|
||||
persistor = _ref.persistor,
|
||||
_ref$maxAge = _ref.maxAge,
|
||||
maxAge = _ref$maxAge === void 0 ? 1000 * 60 * 60 * 24 : _ref$maxAge,
|
||||
_ref$buster = _ref.buster,
|
||||
buster = _ref$buster === void 0 ? '' : _ref$buster,
|
||||
hydrateOptions = _ref.hydrateOptions,
|
||||
dehydrateOptions = _ref.dehydrateOptions;
|
||||
return _invokeIgnored(function () {
|
||||
if (typeof window !== 'undefined') {
|
||||
// Subscribe to changes
|
||||
var saveClient = function saveClient() {
|
||||
var persistClient = {
|
||||
buster: buster,
|
||||
timestamp: Date.now(),
|
||||
clientState: (0, _reactQuery.dehydrate)(queryClient, dehydrateOptions)
|
||||
};
|
||||
persistor.persistClient(persistClient);
|
||||
}; // Attempt restore
|
||||
|
||||
|
||||
return _continue(_catch(function () {
|
||||
return _await(persistor.restoreClient(), function (persistedClient) {
|
||||
if (persistedClient) {
|
||||
if (persistedClient.timestamp) {
|
||||
var expired = Date.now() - persistedClient.timestamp > maxAge;
|
||||
var busted = persistedClient.buster !== buster;
|
||||
|
||||
if (expired || busted) {
|
||||
persistor.removeClient();
|
||||
} else {
|
||||
(0, _reactQuery.hydrate)(queryClient, persistedClient.clientState, hydrateOptions);
|
||||
}
|
||||
} else {
|
||||
persistor.removeClient();
|
||||
}
|
||||
}
|
||||
});
|
||||
}, function (err) {
|
||||
(0, _logger.getLogger)().error(err);
|
||||
(0, _logger.getLogger)().warn('Encountered an error attempting to restore client cache from persisted location. As a precaution, the persisted cache will be discarded.');
|
||||
persistor.removeClient();
|
||||
}), function () {
|
||||
// Subscribe to changes in the query cache to trigger the save
|
||||
queryClient.getQueryCache().subscribe(saveClient);
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
exports.persistQueryClient = persistQueryClient;
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
"use strict";
|
||||
|
||||
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
|
||||
|
||||
exports.__esModule = true;
|
||||
exports.useHydrate = useHydrate;
|
||||
exports.Hydrate = void 0;
|
||||
|
||||
var _react = _interopRequireDefault(require("react"));
|
||||
|
||||
var _core = require("../core");
|
||||
|
||||
var _QueryClientProvider = require("./QueryClientProvider");
|
||||
|
||||
function useHydrate(state, options) {
|
||||
var queryClient = (0, _QueryClientProvider.useQueryClient)();
|
||||
|
||||
var optionsRef = _react.default.useRef(options);
|
||||
|
||||
optionsRef.current = options; // Running hydrate again with the same queries is safe,
|
||||
// it wont overwrite or initialize existing queries,
|
||||
// relying on useMemo here is only a performance optimization.
|
||||
// hydrate can and should be run *during* render here for SSR to work properly
|
||||
|
||||
_react.default.useMemo(function () {
|
||||
if (state) {
|
||||
(0, _core.hydrate)(queryClient, state, optionsRef.current);
|
||||
}
|
||||
}, [queryClient, state]);
|
||||
}
|
||||
|
||||
var Hydrate = function Hydrate(_ref) {
|
||||
var children = _ref.children,
|
||||
options = _ref.options,
|
||||
state = _ref.state;
|
||||
useHydrate(state, options);
|
||||
return children;
|
||||
};
|
||||
|
||||
exports.Hydrate = Hydrate;
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
"use strict";
|
||||
|
||||
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
|
||||
|
||||
exports.__esModule = true;
|
||||
exports.QueryClientProvider = exports.useQueryClient = void 0;
|
||||
|
||||
var _react = _interopRequireDefault(require("react"));
|
||||
|
||||
var defaultContext = /*#__PURE__*/_react.default.createContext(undefined);
|
||||
|
||||
var QueryClientSharingContext = /*#__PURE__*/_react.default.createContext(false); // if contextSharing is on, we share the first and at least one
|
||||
// instance of the context across the window
|
||||
// to ensure that if React Query is used across
|
||||
// different bundles or microfrontends they will
|
||||
// all use the same **instance** of context, regardless
|
||||
// of module scoping.
|
||||
|
||||
|
||||
function getQueryClientContext(contextSharing) {
|
||||
if (contextSharing && typeof window !== 'undefined') {
|
||||
if (!window.ReactQueryClientContext) {
|
||||
window.ReactQueryClientContext = defaultContext;
|
||||
}
|
||||
|
||||
return window.ReactQueryClientContext;
|
||||
}
|
||||
|
||||
return defaultContext;
|
||||
}
|
||||
|
||||
var useQueryClient = function useQueryClient() {
|
||||
var queryClient = _react.default.useContext(getQueryClientContext(_react.default.useContext(QueryClientSharingContext)));
|
||||
|
||||
if (!queryClient) {
|
||||
throw new Error('No QueryClient set, use QueryClientProvider to set one');
|
||||
}
|
||||
|
||||
return queryClient;
|
||||
};
|
||||
|
||||
exports.useQueryClient = useQueryClient;
|
||||
|
||||
var QueryClientProvider = function QueryClientProvider(_ref) {
|
||||
var client = _ref.client,
|
||||
_ref$contextSharing = _ref.contextSharing,
|
||||
contextSharing = _ref$contextSharing === void 0 ? false : _ref$contextSharing,
|
||||
children = _ref.children;
|
||||
|
||||
_react.default.useEffect(function () {
|
||||
client.mount();
|
||||
return function () {
|
||||
client.unmount();
|
||||
};
|
||||
}, [client]);
|
||||
|
||||
var Context = getQueryClientContext(contextSharing);
|
||||
return /*#__PURE__*/_react.default.createElement(QueryClientSharingContext.Provider, {
|
||||
value: contextSharing
|
||||
}, /*#__PURE__*/_react.default.createElement(Context.Provider, {
|
||||
value: client
|
||||
}, children));
|
||||
};
|
||||
|
||||
exports.QueryClientProvider = QueryClientProvider;
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
"use strict";
|
||||
|
||||
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
|
||||
|
||||
exports.__esModule = true;
|
||||
exports.QueryErrorResetBoundary = exports.useQueryErrorResetBoundary = void 0;
|
||||
|
||||
var _react = _interopRequireDefault(require("react"));
|
||||
|
||||
function createValue() {
|
||||
var _isReset = false;
|
||||
return {
|
||||
clearReset: function clearReset() {
|
||||
_isReset = false;
|
||||
},
|
||||
reset: function reset() {
|
||||
_isReset = true;
|
||||
},
|
||||
isReset: function isReset() {
|
||||
return _isReset;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
var QueryErrorResetBoundaryContext = /*#__PURE__*/_react.default.createContext(createValue()); // HOOK
|
||||
|
||||
|
||||
var useQueryErrorResetBoundary = function useQueryErrorResetBoundary() {
|
||||
return _react.default.useContext(QueryErrorResetBoundaryContext);
|
||||
}; // COMPONENT
|
||||
|
||||
|
||||
exports.useQueryErrorResetBoundary = useQueryErrorResetBoundary;
|
||||
|
||||
var QueryErrorResetBoundary = function QueryErrorResetBoundary(_ref) {
|
||||
var children = _ref.children;
|
||||
|
||||
var value = _react.default.useMemo(function () {
|
||||
return createValue();
|
||||
}, []);
|
||||
|
||||
return /*#__PURE__*/_react.default.createElement(QueryErrorResetBoundaryContext.Provider, {
|
||||
value: value
|
||||
}, typeof children === 'function' ? children(value) : children);
|
||||
};
|
||||
|
||||
exports.QueryErrorResetBoundary = QueryErrorResetBoundary;
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
"use strict";
|
||||
|
||||
exports.__esModule = true;
|
||||
var _exportNames = {
|
||||
QueryClientProvider: true,
|
||||
useQueryClient: true,
|
||||
QueryErrorResetBoundary: true,
|
||||
useQueryErrorResetBoundary: true,
|
||||
useIsFetching: true,
|
||||
useIsMutating: true,
|
||||
useMutation: true,
|
||||
useQuery: true,
|
||||
useQueries: true,
|
||||
useInfiniteQuery: true,
|
||||
useHydrate: true,
|
||||
Hydrate: true
|
||||
};
|
||||
exports.Hydrate = exports.useHydrate = exports.useInfiniteQuery = exports.useQueries = exports.useQuery = exports.useMutation = exports.useIsMutating = exports.useIsFetching = exports.useQueryErrorResetBoundary = exports.QueryErrorResetBoundary = exports.useQueryClient = exports.QueryClientProvider = void 0;
|
||||
|
||||
require("./setBatchUpdatesFn");
|
||||
|
||||
require("./setLogger");
|
||||
|
||||
var _QueryClientProvider = require("./QueryClientProvider");
|
||||
|
||||
exports.QueryClientProvider = _QueryClientProvider.QueryClientProvider;
|
||||
exports.useQueryClient = _QueryClientProvider.useQueryClient;
|
||||
|
||||
var _QueryErrorResetBoundary = require("./QueryErrorResetBoundary");
|
||||
|
||||
exports.QueryErrorResetBoundary = _QueryErrorResetBoundary.QueryErrorResetBoundary;
|
||||
exports.useQueryErrorResetBoundary = _QueryErrorResetBoundary.useQueryErrorResetBoundary;
|
||||
|
||||
var _useIsFetching = require("./useIsFetching");
|
||||
|
||||
exports.useIsFetching = _useIsFetching.useIsFetching;
|
||||
|
||||
var _useIsMutating = require("./useIsMutating");
|
||||
|
||||
exports.useIsMutating = _useIsMutating.useIsMutating;
|
||||
|
||||
var _useMutation = require("./useMutation");
|
||||
|
||||
exports.useMutation = _useMutation.useMutation;
|
||||
|
||||
var _useQuery = require("./useQuery");
|
||||
|
||||
exports.useQuery = _useQuery.useQuery;
|
||||
|
||||
var _useQueries = require("./useQueries");
|
||||
|
||||
exports.useQueries = _useQueries.useQueries;
|
||||
|
||||
var _useInfiniteQuery = require("./useInfiniteQuery");
|
||||
|
||||
exports.useInfiniteQuery = _useInfiniteQuery.useInfiniteQuery;
|
||||
|
||||
var _Hydrate = require("./Hydrate");
|
||||
|
||||
exports.useHydrate = _Hydrate.useHydrate;
|
||||
exports.Hydrate = _Hydrate.Hydrate;
|
||||
|
||||
var _types = require("./types");
|
||||
|
||||
Object.keys(_types).forEach(function (key) {
|
||||
if (key === "default" || key === "__esModule") return;
|
||||
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
|
||||
exports[key] = _types[key];
|
||||
});
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
"use strict";
|
||||
|
||||
exports.__esModule = true;
|
||||
exports.logger = void 0;
|
||||
var logger = console;
|
||||
exports.logger = logger;
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
"use strict";
|
||||
|
||||
exports.__esModule = true;
|
||||
exports.logger = void 0;
|
||||
var logger = {
|
||||
log: console.log,
|
||||
warn: console.warn,
|
||||
error: console.warn
|
||||
};
|
||||
exports.logger = logger;
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
"use strict";
|
||||
|
||||
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
|
||||
|
||||
exports.__esModule = true;
|
||||
exports.unstable_batchedUpdates = void 0;
|
||||
|
||||
var _reactDom = _interopRequireDefault(require("react-dom"));
|
||||
|
||||
var unstable_batchedUpdates = _reactDom.default.unstable_batchedUpdates;
|
||||
exports.unstable_batchedUpdates = unstable_batchedUpdates;
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
"use strict";
|
||||
|
||||
exports.__esModule = true;
|
||||
|
||||
var _reactNative = require("react-native");
|
||||
|
||||
exports.unstable_batchedUpdates = _reactNative.unstable_batchedUpdates;
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
"use strict";
|
||||
|
||||
var _core = require("../core");
|
||||
|
||||
var _reactBatchedUpdates = require("./reactBatchedUpdates");
|
||||
|
||||
_core.notifyManager.setBatchNotifyFunction(_reactBatchedUpdates.unstable_batchedUpdates);
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
"use strict";
|
||||
|
||||
var _core = require("../core");
|
||||
|
||||
var _logger = require("./logger");
|
||||
|
||||
(0, _core.setLogger)(_logger.logger);
|
||||
+1
@@ -0,0 +1 @@
|
||||
"use strict";
|
||||
+121
@@ -0,0 +1,121 @@
|
||||
"use strict";
|
||||
|
||||
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
|
||||
|
||||
exports.__esModule = true;
|
||||
exports.useBaseQuery = useBaseQuery;
|
||||
|
||||
var _react = _interopRequireDefault(require("react"));
|
||||
|
||||
var _notifyManager = require("../core/notifyManager");
|
||||
|
||||
var _QueryErrorResetBoundary = require("./QueryErrorResetBoundary");
|
||||
|
||||
var _QueryClientProvider = require("./QueryClientProvider");
|
||||
|
||||
var _utils = require("./utils");
|
||||
|
||||
function useBaseQuery(options, Observer) {
|
||||
var mountedRef = _react.default.useRef(false);
|
||||
|
||||
var _React$useState = _react.default.useState(0),
|
||||
forceUpdate = _React$useState[1];
|
||||
|
||||
var queryClient = (0, _QueryClientProvider.useQueryClient)();
|
||||
var errorResetBoundary = (0, _QueryErrorResetBoundary.useQueryErrorResetBoundary)();
|
||||
var defaultedOptions = queryClient.defaultQueryObserverOptions(options); // Make sure results are optimistically set in fetching state before subscribing or updating options
|
||||
|
||||
defaultedOptions.optimisticResults = true; // Include callbacks in batch renders
|
||||
|
||||
if (defaultedOptions.onError) {
|
||||
defaultedOptions.onError = _notifyManager.notifyManager.batchCalls(defaultedOptions.onError);
|
||||
}
|
||||
|
||||
if (defaultedOptions.onSuccess) {
|
||||
defaultedOptions.onSuccess = _notifyManager.notifyManager.batchCalls(defaultedOptions.onSuccess);
|
||||
}
|
||||
|
||||
if (defaultedOptions.onSettled) {
|
||||
defaultedOptions.onSettled = _notifyManager.notifyManager.batchCalls(defaultedOptions.onSettled);
|
||||
}
|
||||
|
||||
if (defaultedOptions.suspense) {
|
||||
// Always set stale time when using suspense to prevent
|
||||
// fetching again when directly mounting after suspending
|
||||
if (typeof defaultedOptions.staleTime !== 'number') {
|
||||
defaultedOptions.staleTime = 1000;
|
||||
} // Set cache time to 1 if the option has been set to 0
|
||||
// when using suspense to prevent infinite loop of fetches
|
||||
|
||||
|
||||
if (defaultedOptions.cacheTime === 0) {
|
||||
defaultedOptions.cacheTime = 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (defaultedOptions.suspense || defaultedOptions.useErrorBoundary) {
|
||||
// Prevent retrying failed query if the error boundary has not been reset yet
|
||||
if (!errorResetBoundary.isReset()) {
|
||||
defaultedOptions.retryOnMount = false;
|
||||
}
|
||||
}
|
||||
|
||||
var _React$useState2 = _react.default.useState(function () {
|
||||
return new Observer(queryClient, defaultedOptions);
|
||||
}),
|
||||
observer = _React$useState2[0];
|
||||
|
||||
var result = observer.getOptimisticResult(defaultedOptions);
|
||||
|
||||
_react.default.useEffect(function () {
|
||||
mountedRef.current = true;
|
||||
errorResetBoundary.clearReset();
|
||||
var unsubscribe = observer.subscribe(_notifyManager.notifyManager.batchCalls(function () {
|
||||
if (mountedRef.current) {
|
||||
forceUpdate(function (x) {
|
||||
return x + 1;
|
||||
});
|
||||
}
|
||||
})); // Update result to make sure we did not miss any query updates
|
||||
// between creating the observer and subscribing to it.
|
||||
|
||||
observer.updateResult();
|
||||
return function () {
|
||||
mountedRef.current = false;
|
||||
unsubscribe();
|
||||
};
|
||||
}, [errorResetBoundary, observer]);
|
||||
|
||||
_react.default.useEffect(function () {
|
||||
// Do not notify on updates because of changes in the options because
|
||||
// these changes should already be reflected in the optimistic result.
|
||||
observer.setOptions(defaultedOptions, {
|
||||
listeners: false
|
||||
});
|
||||
}, [defaultedOptions, observer]); // Handle suspense
|
||||
|
||||
|
||||
if (defaultedOptions.suspense && result.isLoading) {
|
||||
throw observer.fetchOptimistic(defaultedOptions).then(function (_ref) {
|
||||
var data = _ref.data;
|
||||
defaultedOptions.onSuccess == null ? void 0 : defaultedOptions.onSuccess(data);
|
||||
defaultedOptions.onSettled == null ? void 0 : defaultedOptions.onSettled(data, null);
|
||||
}).catch(function (error) {
|
||||
errorResetBoundary.clearReset();
|
||||
defaultedOptions.onError == null ? void 0 : defaultedOptions.onError(error);
|
||||
defaultedOptions.onSettled == null ? void 0 : defaultedOptions.onSettled(undefined, error);
|
||||
});
|
||||
} // Handle error boundary
|
||||
|
||||
|
||||
if (result.isError && !errorResetBoundary.isReset() && !result.isFetching && (0, _utils.shouldThrowError)(defaultedOptions.suspense, defaultedOptions.useErrorBoundary, [result.error, observer.getCurrentQuery()])) {
|
||||
throw result.error;
|
||||
} // Handle result property usage tracking
|
||||
|
||||
|
||||
if (defaultedOptions.notifyOnChangeProps === 'tracked') {
|
||||
result = observer.trackResult(result, defaultedOptions);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
"use strict";
|
||||
|
||||
exports.__esModule = true;
|
||||
exports.useInfiniteQuery = useInfiniteQuery;
|
||||
|
||||
var _infiniteQueryObserver = require("../core/infiniteQueryObserver");
|
||||
|
||||
var _utils = require("../core/utils");
|
||||
|
||||
var _useBaseQuery = require("./useBaseQuery");
|
||||
|
||||
function useInfiniteQuery(arg1, arg2, arg3) {
|
||||
var options = (0, _utils.parseQueryArgs)(arg1, arg2, arg3);
|
||||
return (0, _useBaseQuery.useBaseQuery)(options, _infiniteQueryObserver.InfiniteQueryObserver);
|
||||
}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
"use strict";
|
||||
|
||||
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
|
||||
|
||||
exports.__esModule = true;
|
||||
exports.useIsFetching = useIsFetching;
|
||||
|
||||
var _react = _interopRequireDefault(require("react"));
|
||||
|
||||
var _notifyManager = require("../core/notifyManager");
|
||||
|
||||
var _utils = require("../core/utils");
|
||||
|
||||
var _QueryClientProvider = require("./QueryClientProvider");
|
||||
|
||||
var checkIsFetching = function checkIsFetching(queryClient, filters, isFetching, setIsFetching) {
|
||||
var newIsFetching = queryClient.isFetching(filters);
|
||||
|
||||
if (isFetching !== newIsFetching) {
|
||||
setIsFetching(newIsFetching);
|
||||
}
|
||||
};
|
||||
|
||||
function useIsFetching(arg1, arg2) {
|
||||
var mountedRef = _react.default.useRef(false);
|
||||
|
||||
var queryClient = (0, _QueryClientProvider.useQueryClient)();
|
||||
|
||||
var _parseFilterArgs = (0, _utils.parseFilterArgs)(arg1, arg2),
|
||||
filters = _parseFilterArgs[0];
|
||||
|
||||
var _React$useState = _react.default.useState(queryClient.isFetching(filters)),
|
||||
isFetching = _React$useState[0],
|
||||
setIsFetching = _React$useState[1];
|
||||
|
||||
var filtersRef = _react.default.useRef(filters);
|
||||
|
||||
filtersRef.current = filters;
|
||||
|
||||
var isFetchingRef = _react.default.useRef(isFetching);
|
||||
|
||||
isFetchingRef.current = isFetching;
|
||||
|
||||
_react.default.useEffect(function () {
|
||||
mountedRef.current = true;
|
||||
checkIsFetching(queryClient, filtersRef.current, isFetchingRef.current, setIsFetching);
|
||||
var unsubscribe = queryClient.getQueryCache().subscribe(_notifyManager.notifyManager.batchCalls(function () {
|
||||
if (mountedRef.current) {
|
||||
checkIsFetching(queryClient, filtersRef.current, isFetchingRef.current, setIsFetching);
|
||||
}
|
||||
}));
|
||||
return function () {
|
||||
mountedRef.current = false;
|
||||
unsubscribe();
|
||||
};
|
||||
}, [queryClient]);
|
||||
|
||||
return isFetching;
|
||||
}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
"use strict";
|
||||
|
||||
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
|
||||
|
||||
exports.__esModule = true;
|
||||
exports.useIsMutating = useIsMutating;
|
||||
|
||||
var _react = _interopRequireDefault(require("react"));
|
||||
|
||||
var _notifyManager = require("../core/notifyManager");
|
||||
|
||||
var _utils = require("../core/utils");
|
||||
|
||||
var _QueryClientProvider = require("./QueryClientProvider");
|
||||
|
||||
function useIsMutating(arg1, arg2) {
|
||||
var mountedRef = _react.default.useRef(false);
|
||||
|
||||
var filters = (0, _utils.parseMutationFilterArgs)(arg1, arg2);
|
||||
var queryClient = (0, _QueryClientProvider.useQueryClient)();
|
||||
|
||||
var _React$useState = _react.default.useState(queryClient.isMutating(filters)),
|
||||
isMutating = _React$useState[0],
|
||||
setIsMutating = _React$useState[1];
|
||||
|
||||
var filtersRef = _react.default.useRef(filters);
|
||||
|
||||
filtersRef.current = filters;
|
||||
|
||||
var isMutatingRef = _react.default.useRef(isMutating);
|
||||
|
||||
isMutatingRef.current = isMutating;
|
||||
|
||||
_react.default.useEffect(function () {
|
||||
mountedRef.current = true;
|
||||
var unsubscribe = queryClient.getMutationCache().subscribe(_notifyManager.notifyManager.batchCalls(function () {
|
||||
if (mountedRef.current) {
|
||||
var newIsMutating = queryClient.isMutating(filtersRef.current);
|
||||
|
||||
if (isMutatingRef.current !== newIsMutating) {
|
||||
setIsMutating(newIsMutating);
|
||||
}
|
||||
}
|
||||
}));
|
||||
return function () {
|
||||
mountedRef.current = false;
|
||||
unsubscribe();
|
||||
};
|
||||
}, [queryClient]);
|
||||
|
||||
return isMutating;
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
"use strict";
|
||||
|
||||
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
|
||||
|
||||
exports.__esModule = true;
|
||||
exports.useMutation = useMutation;
|
||||
|
||||
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
|
||||
|
||||
var _react = _interopRequireDefault(require("react"));
|
||||
|
||||
var _notifyManager = require("../core/notifyManager");
|
||||
|
||||
var _utils = require("../core/utils");
|
||||
|
||||
var _mutationObserver = require("../core/mutationObserver");
|
||||
|
||||
var _QueryClientProvider = require("./QueryClientProvider");
|
||||
|
||||
var _utils2 = require("./utils");
|
||||
|
||||
function useMutation(arg1, arg2, arg3) {
|
||||
var mountedRef = _react.default.useRef(false);
|
||||
|
||||
var _React$useState = _react.default.useState(0),
|
||||
forceUpdate = _React$useState[1];
|
||||
|
||||
var options = (0, _utils.parseMutationArgs)(arg1, arg2, arg3);
|
||||
var queryClient = (0, _QueryClientProvider.useQueryClient)();
|
||||
|
||||
var obsRef = _react.default.useRef();
|
||||
|
||||
if (!obsRef.current) {
|
||||
obsRef.current = new _mutationObserver.MutationObserver(queryClient, options);
|
||||
} else {
|
||||
obsRef.current.setOptions(options);
|
||||
}
|
||||
|
||||
var currentResult = obsRef.current.getCurrentResult();
|
||||
|
||||
_react.default.useEffect(function () {
|
||||
mountedRef.current = true;
|
||||
var unsubscribe = obsRef.current.subscribe(_notifyManager.notifyManager.batchCalls(function () {
|
||||
if (mountedRef.current) {
|
||||
forceUpdate(function (x) {
|
||||
return x + 1;
|
||||
});
|
||||
}
|
||||
}));
|
||||
return function () {
|
||||
mountedRef.current = false;
|
||||
unsubscribe();
|
||||
};
|
||||
}, []);
|
||||
|
||||
var mutate = _react.default.useCallback(function (variables, mutateOptions) {
|
||||
obsRef.current.mutate(variables, mutateOptions).catch(_utils.noop);
|
||||
}, []);
|
||||
|
||||
if (currentResult.error && (0, _utils2.shouldThrowError)(undefined, obsRef.current.options.useErrorBoundary, [currentResult.error])) {
|
||||
throw currentResult.error;
|
||||
}
|
||||
|
||||
return (0, _extends2.default)({}, currentResult, {
|
||||
mutate: mutate,
|
||||
mutateAsync: currentResult.mutate
|
||||
});
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
"use strict";
|
||||
|
||||
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
|
||||
|
||||
exports.__esModule = true;
|
||||
exports.useQueries = useQueries;
|
||||
|
||||
var _react = _interopRequireWildcard(require("react"));
|
||||
|
||||
var _notifyManager = require("../core/notifyManager");
|
||||
|
||||
var _queriesObserver = require("../core/queriesObserver");
|
||||
|
||||
var _QueryClientProvider = require("./QueryClientProvider");
|
||||
|
||||
function useQueries(queries) {
|
||||
var mountedRef = _react.default.useRef(false);
|
||||
|
||||
var _React$useState = _react.default.useState(0),
|
||||
forceUpdate = _React$useState[1];
|
||||
|
||||
var queryClient = (0, _QueryClientProvider.useQueryClient)();
|
||||
var defaultedQueries = (0, _react.useMemo)(function () {
|
||||
return queries.map(function (options) {
|
||||
var defaultedOptions = queryClient.defaultQueryObserverOptions(options); // Make sure the results are already in fetching state before subscribing or updating options
|
||||
|
||||
defaultedOptions.optimisticResults = true;
|
||||
return defaultedOptions;
|
||||
});
|
||||
}, [queries, queryClient]);
|
||||
|
||||
var _React$useState2 = _react.default.useState(function () {
|
||||
return new _queriesObserver.QueriesObserver(queryClient, defaultedQueries);
|
||||
}),
|
||||
observer = _React$useState2[0];
|
||||
|
||||
var result = observer.getOptimisticResult(defaultedQueries);
|
||||
|
||||
_react.default.useEffect(function () {
|
||||
mountedRef.current = true;
|
||||
var unsubscribe = observer.subscribe(_notifyManager.notifyManager.batchCalls(function () {
|
||||
if (mountedRef.current) {
|
||||
forceUpdate(function (x) {
|
||||
return x + 1;
|
||||
});
|
||||
}
|
||||
}));
|
||||
return function () {
|
||||
mountedRef.current = false;
|
||||
unsubscribe();
|
||||
};
|
||||
}, [observer]);
|
||||
|
||||
_react.default.useEffect(function () {
|
||||
// Do not notify on updates because of changes in the options because
|
||||
// these changes should already be reflected in the optimistic result.
|
||||
observer.setQueries(defaultedQueries, {
|
||||
listeners: false
|
||||
});
|
||||
}, [defaultedQueries, observer]);
|
||||
|
||||
return result;
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
"use strict";
|
||||
|
||||
exports.__esModule = true;
|
||||
exports.useQuery = useQuery;
|
||||
|
||||
var _core = require("../core");
|
||||
|
||||
var _utils = require("../core/utils");
|
||||
|
||||
var _useBaseQuery = require("./useBaseQuery");
|
||||
|
||||
function useQuery(arg1, arg2, arg3) {
|
||||
var parsedOptions = (0, _utils.parseQueryArgs)(arg1, arg2, arg3);
|
||||
return (0, _useBaseQuery.useBaseQuery)(parsedOptions, _core.QueryObserver);
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
"use strict";
|
||||
|
||||
exports.__esModule = true;
|
||||
exports.shouldThrowError = shouldThrowError;
|
||||
|
||||
function shouldThrowError(suspense, _useErrorBoundary, params) {
|
||||
// Allow useErrorBoundary function to override throwing behavior on a per-error basis
|
||||
if (typeof _useErrorBoundary === 'function') {
|
||||
return _useErrorBoundary.apply(void 0, params);
|
||||
} // Allow useErrorBoundary to override suspense's throwing behavior
|
||||
|
||||
|
||||
if (typeof _useErrorBoundary === 'boolean') return _useErrorBoundary; // If suspense is enabled default to throwing errors
|
||||
|
||||
return !!suspense;
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
"use strict";
|
||||
|
||||
exports.__esModule = true;
|
||||
var _exportNames = {
|
||||
useQueries: true
|
||||
};
|
||||
|
||||
var _useQueries = require("./useQueries");
|
||||
|
||||
exports.useQueries = _useQueries.useQueries;
|
||||
|
||||
var _ = require("..");
|
||||
|
||||
Object.keys(_).forEach(function (key) {
|
||||
if (key === "default" || key === "__esModule") return;
|
||||
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
|
||||
exports[key] = _[key];
|
||||
});
|
||||
+1
@@ -0,0 +1 @@
|
||||
"use strict";
|
||||
+157
@@ -0,0 +1,157 @@
|
||||
{
|
||||
"name": "react-query",
|
||||
"version": "3.39.3",
|
||||
"description": "Hooks for managing, caching and syncing asynchronous and remote data in React",
|
||||
"author": "tannerlinsley",
|
||||
"license": "MIT",
|
||||
"repository": "tannerlinsley/react-query",
|
||||
"homepage": "https://github.com/tannerlinsley/react-query#readme",
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/tannerlinsley"
|
||||
},
|
||||
"main": "lib/index.js",
|
||||
"unpkg": "dist/react-query.development.js",
|
||||
"types": "types/index.d.ts",
|
||||
"module": "es/index.js",
|
||||
"sideEffects": [
|
||||
"es/index.js",
|
||||
"es/react/index.js",
|
||||
"es/react/setBatchUpdatesFn.js",
|
||||
"es/react/setLogger.js",
|
||||
"lib/index.js",
|
||||
"lib/react/index.js",
|
||||
"lib/react/setBatchUpdatesFn.js",
|
||||
"lib/react/setLogger.js"
|
||||
],
|
||||
"scripts": {
|
||||
"test": "is-ci \"test:ci\" \"test:dev\"",
|
||||
"test:dev": "npm run test:types && npm run test:format && npm run test:eslint && jest --watch",
|
||||
"test:ci": "npm run test:types && npm run test:format && npm run test:eslint && jest",
|
||||
"test:coverage": "yarn test:ci; open coverage/lcov-report/index.html",
|
||||
"test:format": "yarn prettier --check",
|
||||
"test:types": "tsc",
|
||||
"test:eslint": "eslint --ext .ts,.tsx ./src",
|
||||
"test:size": "yarn build:umd && bundlewatch",
|
||||
"build": "yarn build:commonjs && yarn build:es && yarn build:umd && yarn build:types",
|
||||
"build:commonjs": "rimraf ./lib && cross-env BABEL_ENV=commonjs babel --extensions .ts,.tsx --ignore ./src/**/tests/**/* ./src --out-dir lib",
|
||||
"build:es": "rimraf ./es && babel --extensions .ts,.tsx --ignore ./src/**/tests/**/* ./src --out-dir es",
|
||||
"build:umd": "rimraf ./dist && cross-env NODE_ENV=production rollup -c && rollup-plugin-visualizer stats-react.json",
|
||||
"build:types": "rimraf ./types && tsc --project ./tsconfig.types.json && replace 'import type' 'import' ./types -r --silent && replace 'export type' 'export' ./types -r --silent",
|
||||
"watch": "yarn watch:commonjs & yarn watch:es & yarn watch:umd & yarn watch:types",
|
||||
"watch:commonjs": "rimraf ./lib && cross-env BABEL_ENV=commonjs babel --watch --extensions .ts,.tsx --ignore ./src/**/tests/**/* ./src --out-dir lib",
|
||||
"watch:es": "rimraf ./es && babel --watch --extensions .ts,.tsx --ignore ./src/**/tests/**/* ./src --out-dir es",
|
||||
"watch:umd": "rimraf ./dist && cross-env NODE_ENV=production rollup -w -c && rollup-plugin-visualizer stats-react.json",
|
||||
"watch:types": "rimraf ./types && tsc --watch --project ./tsconfig.types.json && replace 'import type' 'import' ./types -r --silent && replace 'export type' 'export' ./types -r --silent",
|
||||
"now-build": "yarn && cd www && yarn && yarn build",
|
||||
"prettier": "prettier \"{.,src,src/**,example/src,example/src/**,types}/*.{md,js,jsx,ts,tsx,json}\"",
|
||||
"start": "yarn watch",
|
||||
"format": "yarn prettier --write",
|
||||
"stats": "open ./stats.html"
|
||||
},
|
||||
"files": [
|
||||
"core",
|
||||
"dist",
|
||||
"es",
|
||||
"hydration",
|
||||
"devtools",
|
||||
"persistQueryClient-experimental",
|
||||
"createWebStoragePersistor-experimental",
|
||||
"createAsyncStoragePersistor-experimental",
|
||||
"broadcastQueryClient-experimental",
|
||||
"lib",
|
||||
"react",
|
||||
"scripts",
|
||||
"types"
|
||||
],
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.5.5",
|
||||
"broadcast-channel": "^3.4.1",
|
||||
"match-sorter": "^6.0.2"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": "^16.8.0 || ^17.0.0 || ^18.0.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"react-dom": {
|
||||
"optional": true
|
||||
},
|
||||
"react-native": {
|
||||
"optional": true
|
||||
}
|
||||
},
|
||||
"typesVersions": {
|
||||
"<4.1": { "types/*": ["types/ts3.8/*"] }
|
||||
},
|
||||
"devDependencies": {
|
||||
"@babel/cli": "^7.11.6",
|
||||
"@babel/core": "^7.11.6",
|
||||
"@babel/plugin-transform-runtime": "^7.11.5",
|
||||
"@babel/preset-env": "^7.11.5",
|
||||
"@babel/preset-react": "^7.10.4",
|
||||
"@babel/preset-typescript": "^7.10.4",
|
||||
"@rollup/plugin-replace": "^2.3.3",
|
||||
"@svgr/rollup": "^5.4.0",
|
||||
"@testing-library/react": "^10.4.7",
|
||||
"@testing-library/jest-dom": "^5.14.1",
|
||||
"@types/jest": "^26.0.4",
|
||||
"@types/react": "^16.9.41",
|
||||
"@types/react-dom": "^16.9.8",
|
||||
"@typescript-eslint/eslint-plugin": "^4.8.1",
|
||||
"@typescript-eslint/parser": "^4.8.1",
|
||||
"babel-eslint": "^10.1.0",
|
||||
"babel-jest": "^26.0.1",
|
||||
"babel-plugin-const-enum": "^1.0.1",
|
||||
"babel-plugin-transform-async-to-promises": "^0.8.15",
|
||||
"bundlewatch": "^0.3.2",
|
||||
"cross-env": "^7.0.2",
|
||||
"eslint": "7.x",
|
||||
"eslint-config-prettier": "^6.11.0",
|
||||
"eslint-config-react-app": "^5.2.1",
|
||||
"eslint-config-standard": "^14.1.1",
|
||||
"eslint-config-standard-react": "^9.2.0",
|
||||
"eslint-plugin-flowtype": "5.x",
|
||||
"eslint-plugin-import": "^2.22.1",
|
||||
"eslint-plugin-jsx-a11y": "6.x",
|
||||
"eslint-plugin-node": "^11.1.0",
|
||||
"eslint-plugin-prettier": "^3.1.3",
|
||||
"eslint-plugin-promise": "^4.2.1",
|
||||
"eslint-plugin-react": "7.20.0",
|
||||
"eslint-plugin-react-hooks": "4.2.0",
|
||||
"eslint-plugin-standard": "^4.0.1",
|
||||
"is-ci-cli": "^2.1.1",
|
||||
"jest": "^26.0.1",
|
||||
"prettier": "2.2.1",
|
||||
"react": "^16.13.0",
|
||||
"react-dom": "^16.13.1",
|
||||
"react-error-boundary": "^2.2.2",
|
||||
"replace": "^1.2.0",
|
||||
"rimraf": "^3.0.2",
|
||||
"rollup": "^2.16.1",
|
||||
"rollup-plugin-babel": "^4.4.0",
|
||||
"rollup-plugin-commonjs": "^10.1.0",
|
||||
"rollup-plugin-jscc": "^1.0.0",
|
||||
"rollup-plugin-node-resolve": "^5.2.0",
|
||||
"rollup-plugin-peer-deps-external": "^2.2.2",
|
||||
"rollup-plugin-prettier": "^2.1.0",
|
||||
"rollup-plugin-size": "^0.2.2",
|
||||
"rollup-plugin-terser": "^6.1.0",
|
||||
"rollup-plugin-visualizer": "^4.0.4",
|
||||
"type-fest": "^0.21.0",
|
||||
"typescript": "^4.1.2"
|
||||
},
|
||||
"resolutions": {
|
||||
"@types/react": "^16.9.41",
|
||||
"@types/react-dom": "^16.9.8"
|
||||
},
|
||||
"release": {
|
||||
"branches": ["main"]
|
||||
},
|
||||
"bundlewatch": {
|
||||
"files": [
|
||||
{
|
||||
"path": "dist/*.production.min.js"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
Generated
Vendored
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"internal": true,
|
||||
"main": "../lib/persistQueryClient-experimental/index.js",
|
||||
"module": "../es/persistQueryClient-experimental/index.js",
|
||||
"types": "../types/persistQueryClient-experimental/index.d.ts"
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"internal": true,
|
||||
"main": "../lib/react/index.js",
|
||||
"module": "../es/react/index.js",
|
||||
"types": "../types/react/index.d.ts"
|
||||
}
|
||||
Generated
Vendored
+7
@@ -0,0 +1,7 @@
|
||||
import { QueryClient } from '../core';
|
||||
interface BroadcastQueryClientOptions {
|
||||
queryClient: QueryClient;
|
||||
broadcastChannel?: string;
|
||||
}
|
||||
export declare function broadcastQueryClient({ queryClient, broadcastChannel, }: BroadcastQueryClientOptions): void;
|
||||
export {};
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
import { Subscribable } from './subscribable';
|
||||
declare type SetupFn = (setFocused: (focused?: boolean) => void) => (() => void) | undefined;
|
||||
export declare class FocusManager extends Subscribable {
|
||||
private focused?;
|
||||
private cleanup?;
|
||||
private setup;
|
||||
constructor();
|
||||
protected onSubscribe(): void;
|
||||
protected onUnsubscribe(): void;
|
||||
setEventListener(setup: SetupFn): void;
|
||||
setFocused(focused?: boolean): void;
|
||||
onFocus(): void;
|
||||
isFocused(): boolean;
|
||||
}
|
||||
export declare const focusManager: FocusManager;
|
||||
export {};
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
import { QueryClient } from './queryClient';
|
||||
import { Query, QueryState } from './query';
|
||||
import { MutationKey, MutationOptions, QueryKey, QueryOptions } from './types';
|
||||
import { Mutation, MutationState } from './mutation';
|
||||
export interface DehydrateOptions {
|
||||
dehydrateMutations?: boolean;
|
||||
dehydrateQueries?: boolean;
|
||||
shouldDehydrateMutation?: ShouldDehydrateMutationFunction;
|
||||
shouldDehydrateQuery?: ShouldDehydrateQueryFunction;
|
||||
}
|
||||
export interface HydrateOptions {
|
||||
defaultOptions?: {
|
||||
queries?: QueryOptions;
|
||||
mutations?: MutationOptions;
|
||||
};
|
||||
}
|
||||
interface DehydratedMutation {
|
||||
mutationKey?: MutationKey;
|
||||
state: MutationState;
|
||||
}
|
||||
interface DehydratedQuery {
|
||||
queryHash: string;
|
||||
queryKey: QueryKey;
|
||||
state: QueryState;
|
||||
}
|
||||
export interface DehydratedState {
|
||||
mutations: DehydratedMutation[];
|
||||
queries: DehydratedQuery[];
|
||||
}
|
||||
export declare type ShouldDehydrateQueryFunction = (query: Query) => boolean;
|
||||
export declare type ShouldDehydrateMutationFunction = (mutation: Mutation) => boolean;
|
||||
export declare function dehydrate(client: QueryClient, options?: DehydrateOptions): DehydratedState;
|
||||
export declare function hydrate(client: QueryClient, dehydratedState: unknown, options?: HydrateOptions): void;
|
||||
export {};
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
export { CancelledError } from './retryer';
|
||||
export { QueryCache } from './queryCache';
|
||||
export { QueryClient } from './queryClient';
|
||||
export { QueryObserver } from './queryObserver';
|
||||
export { QueriesObserver } from './queriesObserver';
|
||||
export { InfiniteQueryObserver } from './infiniteQueryObserver';
|
||||
export { MutationCache } from './mutationCache';
|
||||
export { MutationObserver } from './mutationObserver';
|
||||
export { setLogger } from './logger';
|
||||
export { notifyManager } from './notifyManager';
|
||||
export { focusManager } from './focusManager';
|
||||
export { onlineManager } from './onlineManager';
|
||||
export { hashQueryKey, isError } from './utils';
|
||||
export { isCancelledError } from './retryer';
|
||||
export { dehydrate, hydrate } from './hydration';
|
||||
export * from './types';
|
||||
export { Query } from './query';
|
||||
export { Mutation } from './mutation';
|
||||
export { Logger } from './logger';
|
||||
export { DehydrateOptions, DehydratedState, HydrateOptions, ShouldDehydrateMutationFunction, ShouldDehydrateQueryFunction, } from './hydration';
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
import { QueryBehavior } from './query';
|
||||
import { InfiniteData, QueryOptions } from './types';
|
||||
export declare function infiniteQueryBehavior<TQueryFnData, TError, TData>(): QueryBehavior<TQueryFnData, TError, InfiniteData<TData>>;
|
||||
export declare function getNextPageParam(options: QueryOptions<any, any>, pages: unknown[]): unknown | undefined;
|
||||
export declare function getPreviousPageParam(options: QueryOptions<any, any>, pages: unknown[]): unknown | undefined;
|
||||
/**
|
||||
* Checks if there is a next page.
|
||||
* Returns `undefined` if it cannot be determined.
|
||||
*/
|
||||
export declare function hasNextPage(options: QueryOptions<any, any>, pages?: unknown): boolean | undefined;
|
||||
/**
|
||||
* Checks if there is a previous page.
|
||||
* Returns `undefined` if it cannot be determined.
|
||||
*/
|
||||
export declare function hasPreviousPage(options: QueryOptions<any, any>, pages?: unknown): boolean | undefined;
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
import { FetchNextPageOptions, FetchPreviousPageOptions, InfiniteData, InfiniteQueryObserverOptions, InfiniteQueryObserverResult } from './types';
|
||||
import { QueryClient } from './queryClient';
|
||||
import { NotifyOptions, ObserverFetchOptions, QueryObserver } from './queryObserver';
|
||||
import { Query } from './query';
|
||||
declare type InfiniteQueryObserverListener<TData, TError> = (result: InfiniteQueryObserverResult<TData, TError>) => void;
|
||||
export declare class InfiniteQueryObserver<TQueryFnData = unknown, TError = unknown, TData = TQueryFnData, TQueryData = TQueryFnData> extends QueryObserver<TQueryFnData, TError, InfiniteData<TData>, InfiniteData<TQueryData>> {
|
||||
subscribe: (listener?: InfiniteQueryObserverListener<TData, TError>) => () => void;
|
||||
getCurrentResult: () => InfiniteQueryObserverResult<TData, TError>;
|
||||
protected fetch: (fetchOptions?: ObserverFetchOptions) => Promise<InfiniteQueryObserverResult<TData, TError>>;
|
||||
constructor(client: QueryClient, options: InfiniteQueryObserverOptions<TQueryFnData, TError, TData, TQueryData>);
|
||||
protected bindMethods(): void;
|
||||
setOptions(options?: InfiniteQueryObserverOptions<TQueryFnData, TError, TData, TQueryData>, notifyOptions?: NotifyOptions): void;
|
||||
getOptimisticResult(options: InfiniteQueryObserverOptions<TQueryFnData, TError, TData, TQueryData>): InfiniteQueryObserverResult<TData, TError>;
|
||||
fetchNextPage(options?: FetchNextPageOptions): Promise<InfiniteQueryObserverResult<TData, TError>>;
|
||||
fetchPreviousPage(options?: FetchPreviousPageOptions): Promise<InfiniteQueryObserverResult<TData, TError>>;
|
||||
protected createResult(query: Query<TQueryFnData, TError, InfiniteData<TQueryData>>, options: InfiniteQueryObserverOptions<TQueryFnData, TError, TData, TQueryData>): InfiniteQueryObserverResult<TData, TError>;
|
||||
}
|
||||
export {};
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
export interface Logger {
|
||||
log: LogFunction;
|
||||
warn: LogFunction;
|
||||
error: LogFunction;
|
||||
}
|
||||
declare type LogFunction = (...args: any[]) => void;
|
||||
export declare function getLogger(): Logger;
|
||||
export declare function setLogger(newLogger: Logger): void;
|
||||
export {};
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
import { MutationOptions, MutationStatus, MutationMeta } from './types';
|
||||
import { MutationCache } from './mutationCache';
|
||||
import { MutationObserver } from './mutationObserver';
|
||||
interface MutationConfig<TData, TError, TVariables, TContext> {
|
||||
mutationId: number;
|
||||
mutationCache: MutationCache;
|
||||
options: MutationOptions<TData, TError, TVariables, TContext>;
|
||||
defaultOptions?: MutationOptions<TData, TError, TVariables, TContext>;
|
||||
state?: MutationState<TData, TError, TVariables, TContext>;
|
||||
meta?: MutationMeta;
|
||||
}
|
||||
export interface MutationState<TData = unknown, TError = unknown, TVariables = void, TContext = unknown> {
|
||||
context: TContext | undefined;
|
||||
data: TData | undefined;
|
||||
error: TError | null;
|
||||
failureCount: number;
|
||||
isPaused: boolean;
|
||||
status: MutationStatus;
|
||||
variables: TVariables | undefined;
|
||||
}
|
||||
interface FailedAction {
|
||||
type: 'failed';
|
||||
}
|
||||
interface LoadingAction<TVariables, TContext> {
|
||||
type: 'loading';
|
||||
variables?: TVariables;
|
||||
context?: TContext;
|
||||
}
|
||||
interface SuccessAction<TData> {
|
||||
type: 'success';
|
||||
data: TData;
|
||||
}
|
||||
interface ErrorAction<TError> {
|
||||
type: 'error';
|
||||
error: TError;
|
||||
}
|
||||
interface PauseAction {
|
||||
type: 'pause';
|
||||
}
|
||||
interface ContinueAction {
|
||||
type: 'continue';
|
||||
}
|
||||
interface SetStateAction<TData, TError, TVariables, TContext> {
|
||||
type: 'setState';
|
||||
state: MutationState<TData, TError, TVariables, TContext>;
|
||||
}
|
||||
export declare type Action<TData, TError, TVariables, TContext> = ContinueAction | ErrorAction<TError> | FailedAction | LoadingAction<TVariables, TContext> | PauseAction | SetStateAction<TData, TError, TVariables, TContext> | SuccessAction<TData>;
|
||||
export declare class Mutation<TData = unknown, TError = unknown, TVariables = void, TContext = unknown> {
|
||||
state: MutationState<TData, TError, TVariables, TContext>;
|
||||
options: MutationOptions<TData, TError, TVariables, TContext>;
|
||||
mutationId: number;
|
||||
meta: MutationMeta | undefined;
|
||||
private observers;
|
||||
private mutationCache;
|
||||
private retryer?;
|
||||
constructor(config: MutationConfig<TData, TError, TVariables, TContext>);
|
||||
setState(state: MutationState<TData, TError, TVariables, TContext>): void;
|
||||
addObserver(observer: MutationObserver<any, any, any, any>): void;
|
||||
removeObserver(observer: MutationObserver<any, any, any, any>): void;
|
||||
cancel(): Promise<void>;
|
||||
continue(): Promise<TData>;
|
||||
execute(): Promise<TData>;
|
||||
private executeMutation;
|
||||
private dispatch;
|
||||
}
|
||||
export declare function getDefaultState<TData, TError, TVariables, TContext>(): MutationState<TData, TError, TVariables, TContext>;
|
||||
export {};
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
import { MutationOptions } from './types';
|
||||
import { QueryClient } from './queryClient';
|
||||
import { Mutation, MutationState } from './mutation';
|
||||
import { MutationFilters } from './utils';
|
||||
import { Subscribable } from './subscribable';
|
||||
interface MutationCacheConfig {
|
||||
onError?: (error: unknown, variables: unknown, context: unknown, mutation: Mutation<unknown, unknown, unknown, unknown>) => void;
|
||||
onSuccess?: (data: unknown, variables: unknown, context: unknown, mutation: Mutation<unknown, unknown, unknown, unknown>) => void;
|
||||
onMutate?: (variables: unknown, mutation: Mutation<unknown, unknown, unknown, unknown>) => void;
|
||||
}
|
||||
declare type MutationCacheListener = (mutation?: Mutation) => void;
|
||||
export declare class MutationCache extends Subscribable<MutationCacheListener> {
|
||||
config: MutationCacheConfig;
|
||||
private mutations;
|
||||
private mutationId;
|
||||
constructor(config?: MutationCacheConfig);
|
||||
build<TData, TError, TVariables, TContext>(client: QueryClient, options: MutationOptions<TData, TError, TVariables, TContext>, state?: MutationState<TData, TError, TVariables, TContext>): Mutation<TData, TError, TVariables, TContext>;
|
||||
add(mutation: Mutation<any, any, any, any>): void;
|
||||
remove(mutation: Mutation<any, any, any, any>): void;
|
||||
clear(): void;
|
||||
getAll(): Mutation[];
|
||||
find<TData = unknown, TError = unknown, TVariables = any, TContext = unknown>(filters: MutationFilters): Mutation<TData, TError, TVariables, TContext> | undefined;
|
||||
findAll(filters: MutationFilters): Mutation[];
|
||||
notify(mutation?: Mutation<any, any, any, any>): void;
|
||||
onFocus(): void;
|
||||
onOnline(): void;
|
||||
resumePausedMutations(): Promise<void>;
|
||||
}
|
||||
export {};
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
import { Action } from './mutation';
|
||||
import { QueryClient } from './queryClient';
|
||||
import { Subscribable } from './subscribable';
|
||||
import { MutateOptions, MutationObserverResult, MutationObserverOptions } from './types';
|
||||
declare type MutationObserverListener<TData, TError, TVariables, TContext> = (result: MutationObserverResult<TData, TError, TVariables, TContext>) => void;
|
||||
export declare class MutationObserver<TData = unknown, TError = unknown, TVariables = void, TContext = unknown> extends Subscribable<MutationObserverListener<TData, TError, TVariables, TContext>> {
|
||||
options: MutationObserverOptions<TData, TError, TVariables, TContext>;
|
||||
private client;
|
||||
private currentResult;
|
||||
private currentMutation?;
|
||||
private mutateOptions?;
|
||||
constructor(client: QueryClient, options: MutationObserverOptions<TData, TError, TVariables, TContext>);
|
||||
protected bindMethods(): void;
|
||||
setOptions(options?: MutationObserverOptions<TData, TError, TVariables, TContext>): void;
|
||||
protected onUnsubscribe(): void;
|
||||
onMutationUpdate(action: Action<TData, TError, TVariables, TContext>): void;
|
||||
getCurrentResult(): MutationObserverResult<TData, TError, TVariables, TContext>;
|
||||
reset(): void;
|
||||
mutate(variables?: TVariables, options?: MutateOptions<TData, TError, TVariables, TContext>): Promise<TData>;
|
||||
private updateResult;
|
||||
private notify;
|
||||
}
|
||||
export {};
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
declare type NotifyCallback = () => void;
|
||||
declare type NotifyFunction = (callback: () => void) => void;
|
||||
declare type BatchNotifyFunction = (callback: () => void) => void;
|
||||
export declare class NotifyManager {
|
||||
private queue;
|
||||
private transactions;
|
||||
private notifyFn;
|
||||
private batchNotifyFn;
|
||||
constructor();
|
||||
batch<T>(callback: () => T): T;
|
||||
schedule(callback: NotifyCallback): void;
|
||||
/**
|
||||
* All calls to the wrapped function will be batched.
|
||||
*/
|
||||
batchCalls<T extends Function>(callback: T): T;
|
||||
flush(): void;
|
||||
/**
|
||||
* Use this method to set a custom notify function.
|
||||
* This can be used to for example wrap notifications with `React.act` while running tests.
|
||||
*/
|
||||
setNotifyFunction(fn: NotifyFunction): void;
|
||||
/**
|
||||
* Use this method to set a custom function to batch notifications together into a single tick.
|
||||
* By default React Query will use the batch function provided by ReactDOM or React Native.
|
||||
*/
|
||||
setBatchNotifyFunction(fn: BatchNotifyFunction): void;
|
||||
}
|
||||
export declare const notifyManager: NotifyManager;
|
||||
export {};
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
import { Subscribable } from './subscribable';
|
||||
declare type SetupFn = (setOnline: (online?: boolean) => void) => (() => void) | undefined;
|
||||
export declare class OnlineManager extends Subscribable {
|
||||
private online?;
|
||||
private cleanup?;
|
||||
private setup;
|
||||
constructor();
|
||||
protected onSubscribe(): void;
|
||||
protected onUnsubscribe(): void;
|
||||
setEventListener(setup: SetupFn): void;
|
||||
setOnline(online?: boolean): void;
|
||||
onOnline(): void;
|
||||
isOnline(): boolean;
|
||||
}
|
||||
export declare const onlineManager: OnlineManager;
|
||||
export {};
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
import { QueryObserverOptions, QueryObserverResult } from './types';
|
||||
import { QueryClient } from './queryClient';
|
||||
import { NotifyOptions } from './queryObserver';
|
||||
import { Subscribable } from './subscribable';
|
||||
declare type QueriesObserverListener = (result: QueryObserverResult[]) => void;
|
||||
export declare class QueriesObserver extends Subscribable<QueriesObserverListener> {
|
||||
private client;
|
||||
private result;
|
||||
private queries;
|
||||
private observers;
|
||||
private observersMap;
|
||||
constructor(client: QueryClient, queries?: QueryObserverOptions[]);
|
||||
protected onSubscribe(): void;
|
||||
protected onUnsubscribe(): void;
|
||||
destroy(): void;
|
||||
setQueries(queries: QueryObserverOptions[], notifyOptions?: NotifyOptions): void;
|
||||
getCurrentResult(): QueryObserverResult[];
|
||||
getOptimisticResult(queries: QueryObserverOptions[]): QueryObserverResult[];
|
||||
private findMatchingObservers;
|
||||
private getObserver;
|
||||
private updateObservers;
|
||||
private onUpdate;
|
||||
private notify;
|
||||
}
|
||||
export {};
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
import { Updater } from './utils';
|
||||
import { QueryKey, QueryOptions, QueryStatus, EnsuredQueryKey, QueryMeta, CancelOptions, SetDataOptions } from './types';
|
||||
import { QueryCache } from './queryCache';
|
||||
import { QueryObserver } from './queryObserver';
|
||||
interface QueryConfig<TQueryFnData, TError, TData, TQueryKey extends QueryKey = QueryKey> {
|
||||
cache: QueryCache;
|
||||
queryKey: TQueryKey;
|
||||
queryHash: string;
|
||||
options?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>;
|
||||
defaultOptions?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>;
|
||||
state?: QueryState<TData, TError>;
|
||||
meta: QueryMeta | undefined;
|
||||
}
|
||||
export interface QueryState<TData = unknown, TError = unknown> {
|
||||
data: TData | undefined;
|
||||
dataUpdateCount: number;
|
||||
dataUpdatedAt: number;
|
||||
error: TError | null;
|
||||
errorUpdateCount: number;
|
||||
errorUpdatedAt: number;
|
||||
fetchFailureCount: number;
|
||||
fetchMeta: any;
|
||||
isFetching: boolean;
|
||||
isInvalidated: boolean;
|
||||
isPaused: boolean;
|
||||
status: QueryStatus;
|
||||
}
|
||||
export interface FetchContext<TQueryFnData, TError, TData, TQueryKey extends QueryKey = QueryKey> {
|
||||
fetchFn: () => unknown | Promise<unknown>;
|
||||
fetchOptions?: FetchOptions;
|
||||
options: QueryOptions<TQueryFnData, TError, TData, any>;
|
||||
queryKey: EnsuredQueryKey<TQueryKey>;
|
||||
state: QueryState<TData, TError>;
|
||||
meta: QueryMeta | undefined;
|
||||
}
|
||||
export interface QueryBehavior<TQueryFnData = unknown, TError = unknown, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey> {
|
||||
onFetch: (context: FetchContext<TQueryFnData, TError, TData, TQueryKey>) => void;
|
||||
}
|
||||
export interface FetchOptions {
|
||||
cancelRefetch?: boolean;
|
||||
meta?: any;
|
||||
}
|
||||
interface FailedAction {
|
||||
type: 'failed';
|
||||
}
|
||||
interface FetchAction {
|
||||
type: 'fetch';
|
||||
meta?: any;
|
||||
}
|
||||
interface SuccessAction<TData> {
|
||||
data: TData | undefined;
|
||||
type: 'success';
|
||||
dataUpdatedAt?: number;
|
||||
}
|
||||
interface ErrorAction<TError> {
|
||||
type: 'error';
|
||||
error: TError;
|
||||
}
|
||||
interface InvalidateAction {
|
||||
type: 'invalidate';
|
||||
}
|
||||
interface PauseAction {
|
||||
type: 'pause';
|
||||
}
|
||||
interface ContinueAction {
|
||||
type: 'continue';
|
||||
}
|
||||
interface SetStateAction<TData, TError> {
|
||||
type: 'setState';
|
||||
state: QueryState<TData, TError>;
|
||||
setStateOptions?: SetStateOptions;
|
||||
}
|
||||
export declare type Action<TData, TError> = ContinueAction | ErrorAction<TError> | FailedAction | FetchAction | InvalidateAction | PauseAction | SetStateAction<TData, TError> | SuccessAction<TData>;
|
||||
export interface SetStateOptions {
|
||||
meta?: any;
|
||||
}
|
||||
export declare class Query<TQueryFnData = unknown, TError = unknown, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey> {
|
||||
queryKey: TQueryKey;
|
||||
queryHash: string;
|
||||
options: QueryOptions<TQueryFnData, TError, TData, TQueryKey>;
|
||||
initialState: QueryState<TData, TError>;
|
||||
revertState?: QueryState<TData, TError>;
|
||||
state: QueryState<TData, TError>;
|
||||
cacheTime: number;
|
||||
meta: QueryMeta | undefined;
|
||||
private cache;
|
||||
private promise?;
|
||||
private gcTimeout?;
|
||||
private retryer?;
|
||||
private observers;
|
||||
private defaultOptions?;
|
||||
private abortSignalConsumed;
|
||||
private hadObservers;
|
||||
constructor(config: QueryConfig<TQueryFnData, TError, TData, TQueryKey>);
|
||||
private setOptions;
|
||||
setDefaultOptions(options: QueryOptions<TQueryFnData, TError, TData, TQueryKey>): void;
|
||||
private scheduleGc;
|
||||
private clearGcTimeout;
|
||||
private optionalRemove;
|
||||
setData(updater: Updater<TData | undefined, TData>, options?: SetDataOptions): TData;
|
||||
setState(state: QueryState<TData, TError>, setStateOptions?: SetStateOptions): void;
|
||||
cancel(options?: CancelOptions): Promise<void>;
|
||||
destroy(): void;
|
||||
reset(): void;
|
||||
isActive(): boolean;
|
||||
isFetching(): boolean;
|
||||
isStale(): boolean;
|
||||
isStaleByTime(staleTime?: number): boolean;
|
||||
onFocus(): void;
|
||||
onOnline(): void;
|
||||
addObserver(observer: QueryObserver<any, any, any, any, any>): void;
|
||||
removeObserver(observer: QueryObserver<any, any, any, any, any>): void;
|
||||
getObserversCount(): number;
|
||||
invalidate(): void;
|
||||
fetch(options?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>, fetchOptions?: FetchOptions): Promise<TData>;
|
||||
private dispatch;
|
||||
protected getDefaultState(options: QueryOptions<TQueryFnData, TError, TData, TQueryKey>): QueryState<TData, TError>;
|
||||
protected reducer(state: QueryState<TData, TError>, action: Action<TData, TError>): QueryState<TData, TError>;
|
||||
}
|
||||
export {};
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
import { QueryFilters } from './utils';
|
||||
import { Action, Query, QueryState } from './query';
|
||||
import { QueryKey, QueryOptions } from './types';
|
||||
import { QueryClient } from './queryClient';
|
||||
import { Subscribable } from './subscribable';
|
||||
import { QueryObserver } from './queryObserver';
|
||||
interface QueryCacheConfig {
|
||||
onError?: (error: unknown, query: Query<unknown, unknown, unknown>) => void;
|
||||
onSuccess?: (data: unknown, query: Query<unknown, unknown, unknown>) => void;
|
||||
}
|
||||
interface NotifyEventQueryAdded {
|
||||
type: 'queryAdded';
|
||||
query: Query<any, any, any, any>;
|
||||
}
|
||||
interface NotifyEventQueryRemoved {
|
||||
type: 'queryRemoved';
|
||||
query: Query<any, any, any, any>;
|
||||
}
|
||||
interface NotifyEventQueryUpdated {
|
||||
type: 'queryUpdated';
|
||||
query: Query<any, any, any, any>;
|
||||
action: Action<any, any>;
|
||||
}
|
||||
interface NotifyEventObserverAdded {
|
||||
type: 'observerAdded';
|
||||
query: Query<any, any, any, any>;
|
||||
observer: QueryObserver<any, any, any, any, any>;
|
||||
}
|
||||
interface NotifyEventObserverRemoved {
|
||||
type: 'observerRemoved';
|
||||
query: Query<any, any, any, any>;
|
||||
observer: QueryObserver<any, any, any, any, any>;
|
||||
}
|
||||
interface NotifyEventObserverResultsUpdated {
|
||||
type: 'observerResultsUpdated';
|
||||
query: Query<any, any, any, any>;
|
||||
}
|
||||
declare type QueryCacheNotifyEvent = NotifyEventQueryAdded | NotifyEventQueryRemoved | NotifyEventQueryUpdated | NotifyEventObserverAdded | NotifyEventObserverRemoved | NotifyEventObserverResultsUpdated;
|
||||
declare type QueryCacheListener = (event?: QueryCacheNotifyEvent) => void;
|
||||
export declare class QueryCache extends Subscribable<QueryCacheListener> {
|
||||
config: QueryCacheConfig;
|
||||
private queries;
|
||||
private queriesMap;
|
||||
constructor(config?: QueryCacheConfig);
|
||||
build<TQueryFnData, TError, TData, TQueryKey extends QueryKey>(client: QueryClient, options: QueryOptions<TQueryFnData, TError, TData, TQueryKey>, state?: QueryState<TData, TError>): Query<TQueryFnData, TError, TData, TQueryKey>;
|
||||
add(query: Query<any, any, any, any>): void;
|
||||
remove(query: Query<any, any, any, any>): void;
|
||||
clear(): void;
|
||||
get<TQueryFnData = unknown, TError = unknown, TData = TQueryFnData, TQueyKey extends QueryKey = QueryKey>(queryHash: string): Query<TQueryFnData, TError, TData, TQueyKey> | undefined;
|
||||
getAll(): Query[];
|
||||
find<TQueryFnData = unknown, TError = unknown, TData = TQueryFnData>(arg1: QueryKey, arg2?: QueryFilters): Query<TQueryFnData, TError, TData> | undefined;
|
||||
findAll(queryKey?: QueryKey, filters?: QueryFilters): Query[];
|
||||
findAll(filters?: QueryFilters): Query[];
|
||||
findAll(arg1?: QueryKey | QueryFilters, arg2?: QueryFilters): Query[];
|
||||
notify(event: QueryCacheNotifyEvent): void;
|
||||
onFocus(): void;
|
||||
onOnline(): void;
|
||||
}
|
||||
export {};
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
import { QueryFilters, Updater, MutationFilters } from './utils';
|
||||
import { QueryClientConfig, DefaultOptions, FetchInfiniteQueryOptions, FetchQueryOptions, InfiniteData, InvalidateOptions, InvalidateQueryFilters, MutationKey, MutationObserverOptions, MutationOptions, QueryFunction, QueryKey, QueryObserverOptions, RefetchOptions, RefetchQueryFilters, ResetOptions, ResetQueryFilters, SetDataOptions } from './types';
|
||||
import { QueryState } from './query';
|
||||
import { QueryCache } from './queryCache';
|
||||
import { MutationCache } from './mutationCache';
|
||||
import { CancelOptions } from './types';
|
||||
export declare class QueryClient {
|
||||
private queryCache;
|
||||
private mutationCache;
|
||||
private defaultOptions;
|
||||
private queryDefaults;
|
||||
private mutationDefaults;
|
||||
private unsubscribeFocus?;
|
||||
private unsubscribeOnline?;
|
||||
constructor(config?: QueryClientConfig);
|
||||
mount(): void;
|
||||
unmount(): void;
|
||||
isFetching(filters?: QueryFilters): number;
|
||||
isFetching(queryKey?: QueryKey, filters?: QueryFilters): number;
|
||||
isMutating(filters?: MutationFilters): number;
|
||||
getQueryData<TData = unknown>(queryKey: QueryKey, filters?: QueryFilters): TData | undefined;
|
||||
getQueriesData<TData = unknown>(queryKey: QueryKey): [QueryKey, TData][];
|
||||
getQueriesData<TData = unknown>(filters: QueryFilters): [QueryKey, TData][];
|
||||
setQueryData<TData>(queryKey: QueryKey, updater: Updater<TData | undefined, TData>, options?: SetDataOptions): TData;
|
||||
setQueriesData<TData>(queryKey: QueryKey, updater: Updater<TData | undefined, TData>, options?: SetDataOptions): [QueryKey, TData][];
|
||||
setQueriesData<TData>(filters: QueryFilters, updater: Updater<TData | undefined, TData>, options?: SetDataOptions): [QueryKey, TData][];
|
||||
getQueryState<TData = unknown, TError = undefined>(queryKey: QueryKey, filters?: QueryFilters): QueryState<TData, TError> | undefined;
|
||||
removeQueries(filters?: QueryFilters): void;
|
||||
removeQueries(queryKey?: QueryKey, filters?: QueryFilters): void;
|
||||
resetQueries<TPageData = unknown>(filters?: ResetQueryFilters<TPageData>, options?: ResetOptions): Promise<void>;
|
||||
resetQueries<TPageData = unknown>(queryKey?: QueryKey, filters?: ResetQueryFilters<TPageData>, options?: ResetOptions): Promise<void>;
|
||||
cancelQueries(filters?: QueryFilters, options?: CancelOptions): Promise<void>;
|
||||
cancelQueries(queryKey?: QueryKey, filters?: QueryFilters, options?: CancelOptions): Promise<void>;
|
||||
invalidateQueries<TPageData = unknown>(filters?: InvalidateQueryFilters<TPageData>, options?: InvalidateOptions): Promise<void>;
|
||||
invalidateQueries<TPageData = unknown>(queryKey?: QueryKey, filters?: InvalidateQueryFilters<TPageData>, options?: InvalidateOptions): Promise<void>;
|
||||
refetchQueries<TPageData = unknown>(filters?: RefetchQueryFilters<TPageData>, options?: RefetchOptions): Promise<void>;
|
||||
refetchQueries<TPageData = unknown>(queryKey?: QueryKey, filters?: RefetchQueryFilters<TPageData>, options?: RefetchOptions): Promise<void>;
|
||||
fetchQuery<TQueryFnData = unknown, TError = unknown, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey>(options: FetchQueryOptions<TQueryFnData, TError, TData, TQueryKey>): Promise<TData>;
|
||||
fetchQuery<TQueryFnData = unknown, TError = unknown, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey>(queryKey: TQueryKey, options?: FetchQueryOptions<TQueryFnData, TError, TData, TQueryKey>): Promise<TData>;
|
||||
fetchQuery<TQueryFnData = unknown, TError = unknown, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey>(queryKey: TQueryKey, queryFn: QueryFunction<TQueryFnData, TQueryKey>, options?: FetchQueryOptions<TQueryFnData, TError, TData, TQueryKey>): Promise<TData>;
|
||||
prefetchQuery<TQueryFnData = unknown, TError = unknown, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey>(options: FetchQueryOptions<TQueryFnData, TError, TData, TQueryKey>): Promise<void>;
|
||||
prefetchQuery<TQueryFnData = unknown, TError = unknown, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey>(queryKey: TQueryKey, options?: FetchQueryOptions<TQueryFnData, TError, TData, TQueryKey>): Promise<void>;
|
||||
prefetchQuery<TQueryFnData = unknown, TError = unknown, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey>(queryKey: TQueryKey, queryFn: QueryFunction<TQueryFnData, TQueryKey>, options?: FetchQueryOptions<TQueryFnData, TError, TData, TQueryKey>): Promise<void>;
|
||||
fetchInfiniteQuery<TQueryFnData = unknown, TError = unknown, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey>(options: FetchInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey>): Promise<InfiniteData<TData>>;
|
||||
fetchInfiniteQuery<TQueryFnData = unknown, TError = unknown, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey>(queryKey: TQueryKey, options?: FetchInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey>): Promise<InfiniteData<TData>>;
|
||||
fetchInfiniteQuery<TQueryFnData = unknown, TError = unknown, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey>(queryKey: TQueryKey, queryFn: QueryFunction<TQueryFnData, TQueryKey>, options?: FetchInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey>): Promise<InfiniteData<TData>>;
|
||||
prefetchInfiniteQuery<TQueryFnData = unknown, TError = unknown, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey>(options: FetchInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey>): Promise<void>;
|
||||
prefetchInfiniteQuery<TQueryFnData = unknown, TError = unknown, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey>(queryKey: TQueryKey, options?: FetchInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey>): Promise<void>;
|
||||
prefetchInfiniteQuery<TQueryFnData = unknown, TError = unknown, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey>(queryKey: TQueryKey, queryFn: QueryFunction<TQueryFnData, TQueryKey>, options?: FetchInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey>): Promise<void>;
|
||||
cancelMutations(): Promise<void>;
|
||||
resumePausedMutations(): Promise<void>;
|
||||
executeMutation<TData = unknown, TError = unknown, TVariables = void, TContext = unknown>(options: MutationOptions<TData, TError, TVariables, TContext>): Promise<TData>;
|
||||
getQueryCache(): QueryCache;
|
||||
getMutationCache(): MutationCache;
|
||||
getDefaultOptions(): DefaultOptions;
|
||||
setDefaultOptions(options: DefaultOptions): void;
|
||||
setQueryDefaults(queryKey: QueryKey, options: QueryObserverOptions<any, any, any, any>): void;
|
||||
getQueryDefaults(queryKey?: QueryKey): QueryObserverOptions<any, any, any, any, any> | undefined;
|
||||
setMutationDefaults(mutationKey: MutationKey, options: MutationObserverOptions<any, any, any, any>): void;
|
||||
getMutationDefaults(mutationKey?: MutationKey): MutationObserverOptions<any, any, any, any> | undefined;
|
||||
defaultQueryOptions<TQueryFnData, TError, TData, TQueryData, TQueryKey extends QueryKey>(options?: QueryObserverOptions<TQueryFnData, TError, TData, TQueryData, TQueryKey>): QueryObserverOptions<TQueryFnData, TError, TData, TQueryData, TQueryKey>;
|
||||
defaultQueryObserverOptions<TQueryFnData, TError, TData, TQueryData, TQueryKey extends QueryKey>(options?: QueryObserverOptions<TQueryFnData, TError, TData, TQueryData, TQueryKey>): QueryObserverOptions<TQueryFnData, TError, TData, TQueryData, TQueryKey>;
|
||||
defaultMutationOptions<T extends MutationOptions<any, any, any, any>>(options?: T): T;
|
||||
clear(): void;
|
||||
}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
import { RefetchQueryFilters } from './types';
|
||||
import { QueryKey, QueryObserverOptions, QueryObserverResult, RefetchOptions, ResultOptions } from './types';
|
||||
import { Query, Action, FetchOptions } from './query';
|
||||
import { QueryClient } from './queryClient';
|
||||
import { Subscribable } from './subscribable';
|
||||
declare type QueryObserverListener<TData, TError> = (result: QueryObserverResult<TData, TError>) => void;
|
||||
export interface NotifyOptions {
|
||||
cache?: boolean;
|
||||
listeners?: boolean;
|
||||
onError?: boolean;
|
||||
onSuccess?: boolean;
|
||||
}
|
||||
export interface ObserverFetchOptions extends FetchOptions {
|
||||
throwOnError?: boolean;
|
||||
}
|
||||
export declare class QueryObserver<TQueryFnData = unknown, TError = unknown, TData = TQueryFnData, TQueryData = TQueryFnData, TQueryKey extends QueryKey = QueryKey> extends Subscribable<QueryObserverListener<TData, TError>> {
|
||||
options: QueryObserverOptions<TQueryFnData, TError, TData, TQueryData, TQueryKey>;
|
||||
private client;
|
||||
private currentQuery;
|
||||
private currentQueryInitialState;
|
||||
private currentResult;
|
||||
private currentResultState?;
|
||||
private currentResultOptions?;
|
||||
private previousQueryResult?;
|
||||
private selectError;
|
||||
private selectFn?;
|
||||
private selectResult?;
|
||||
private staleTimeoutId?;
|
||||
private refetchIntervalId?;
|
||||
private currentRefetchInterval?;
|
||||
private trackedProps;
|
||||
constructor(client: QueryClient, options: QueryObserverOptions<TQueryFnData, TError, TData, TQueryData, TQueryKey>);
|
||||
protected bindMethods(): void;
|
||||
protected onSubscribe(): void;
|
||||
protected onUnsubscribe(): void;
|
||||
shouldFetchOnReconnect(): boolean;
|
||||
shouldFetchOnWindowFocus(): boolean;
|
||||
destroy(): void;
|
||||
setOptions(options?: QueryObserverOptions<TQueryFnData, TError, TData, TQueryData, TQueryKey>, notifyOptions?: NotifyOptions): void;
|
||||
getOptimisticResult(options: QueryObserverOptions<TQueryFnData, TError, TData, TQueryData, TQueryKey>): QueryObserverResult<TData, TError>;
|
||||
getCurrentResult(): QueryObserverResult<TData, TError>;
|
||||
trackResult(result: QueryObserverResult<TData, TError>, defaultedOptions: QueryObserverOptions<TQueryFnData, TError, TData, TQueryData, TQueryKey>): QueryObserverResult<TData, TError>;
|
||||
getNextResult(options?: ResultOptions): Promise<QueryObserverResult<TData, TError>>;
|
||||
getCurrentQuery(): Query<TQueryFnData, TError, TQueryData, TQueryKey>;
|
||||
remove(): void;
|
||||
refetch<TPageData>(options?: RefetchOptions & RefetchQueryFilters<TPageData>): Promise<QueryObserverResult<TData, TError>>;
|
||||
fetchOptimistic(options: QueryObserverOptions<TQueryFnData, TError, TData, TQueryData, TQueryKey>): Promise<QueryObserverResult<TData, TError>>;
|
||||
protected fetch(fetchOptions?: ObserverFetchOptions): Promise<QueryObserverResult<TData, TError>>;
|
||||
private executeFetch;
|
||||
private updateStaleTimeout;
|
||||
private computeRefetchInterval;
|
||||
private updateRefetchInterval;
|
||||
private updateTimers;
|
||||
private clearTimers;
|
||||
private clearStaleTimeout;
|
||||
private clearRefetchInterval;
|
||||
protected createResult(query: Query<TQueryFnData, TError, TQueryData, TQueryKey>, options: QueryObserverOptions<TQueryFnData, TError, TData, TQueryData, TQueryKey>): QueryObserverResult<TData, TError>;
|
||||
private shouldNotifyListeners;
|
||||
updateResult(notifyOptions?: NotifyOptions): void;
|
||||
private updateQuery;
|
||||
onQueryUpdate(action: Action<TData, TError>): void;
|
||||
private notify;
|
||||
}
|
||||
export {};
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
import { CancelOptions } from './types';
|
||||
interface RetryerConfig<TData = unknown, TError = unknown> {
|
||||
fn: () => TData | Promise<TData>;
|
||||
abort?: () => void;
|
||||
onError?: (error: TError) => void;
|
||||
onSuccess?: (data: TData) => void;
|
||||
onFail?: (failureCount: number, error: TError) => void;
|
||||
onPause?: () => void;
|
||||
onContinue?: () => void;
|
||||
retry?: RetryValue<TError>;
|
||||
retryDelay?: RetryDelayValue<TError>;
|
||||
}
|
||||
export declare type RetryValue<TError> = boolean | number | ShouldRetryFunction<TError>;
|
||||
declare type ShouldRetryFunction<TError = unknown> = (failureCount: number, error: TError) => boolean;
|
||||
export declare type RetryDelayValue<TError> = number | RetryDelayFunction<TError>;
|
||||
declare type RetryDelayFunction<TError = unknown> = (failureCount: number, error: TError) => number;
|
||||
interface Cancelable {
|
||||
cancel(): void;
|
||||
}
|
||||
export declare function isCancelable(value: any): value is Cancelable;
|
||||
export declare class CancelledError {
|
||||
revert?: boolean;
|
||||
silent?: boolean;
|
||||
constructor(options?: CancelOptions);
|
||||
}
|
||||
export declare function isCancelledError(value: any): value is CancelledError;
|
||||
export declare class Retryer<TData = unknown, TError = unknown> {
|
||||
cancel: (options?: CancelOptions) => void;
|
||||
cancelRetry: () => void;
|
||||
continueRetry: () => void;
|
||||
continue: () => void;
|
||||
failureCount: number;
|
||||
isPaused: boolean;
|
||||
isResolved: boolean;
|
||||
isTransportCancelable: boolean;
|
||||
promise: Promise<TData>;
|
||||
private abort?;
|
||||
constructor(config: RetryerConfig<TData, TError>);
|
||||
}
|
||||
export {};
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
declare type Listener = () => void;
|
||||
export declare class Subscribable<TListener extends Function = Listener> {
|
||||
protected listeners: TListener[];
|
||||
constructor();
|
||||
subscribe(listener?: TListener): () => void;
|
||||
hasListeners(): boolean;
|
||||
protected onSubscribe(): void;
|
||||
protected onUnsubscribe(): void;
|
||||
}
|
||||
export {};
|
||||
+445
@@ -0,0 +1,445 @@
|
||||
import { MutationState } from './mutation';
|
||||
import { QueryBehavior, Query } from './query';
|
||||
import { RetryValue, RetryDelayValue } from './retryer';
|
||||
import { QueryFilters } from './utils';
|
||||
import { QueryCache } from './queryCache';
|
||||
import { MutationCache } from './mutationCache';
|
||||
export declare type QueryKey = string | readonly unknown[];
|
||||
export declare type EnsuredQueryKey<T extends QueryKey> = T extends string ? [T] : Exclude<T, string>;
|
||||
export declare type QueryFunction<T = unknown, TQueryKey extends QueryKey = QueryKey> = (context: QueryFunctionContext<TQueryKey>) => T | Promise<T>;
|
||||
export interface QueryFunctionContext<TQueryKey extends QueryKey = QueryKey, TPageParam = any> {
|
||||
queryKey: EnsuredQueryKey<TQueryKey>;
|
||||
signal?: AbortSignal;
|
||||
pageParam?: TPageParam;
|
||||
meta: QueryMeta | undefined;
|
||||
}
|
||||
export declare type InitialDataFunction<T> = () => T | undefined;
|
||||
export declare type PlaceholderDataFunction<TResult> = () => TResult | undefined;
|
||||
export declare type QueryKeyHashFunction<TQueryKey extends QueryKey> = (queryKey: TQueryKey) => string;
|
||||
export declare type GetPreviousPageParamFunction<TQueryFnData = unknown> = (firstPage: TQueryFnData, allPages: TQueryFnData[]) => unknown;
|
||||
export declare type GetNextPageParamFunction<TQueryFnData = unknown> = (lastPage: TQueryFnData, allPages: TQueryFnData[]) => unknown;
|
||||
export interface InfiniteData<TData> {
|
||||
pages: TData[];
|
||||
pageParams: unknown[];
|
||||
}
|
||||
export declare type QueryMeta = Record<string, unknown>;
|
||||
export interface QueryOptions<TQueryFnData = unknown, TError = unknown, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey> {
|
||||
/**
|
||||
* If `false`, failed queries will not retry by default.
|
||||
* If `true`, failed queries will retry infinitely., failureCount: num
|
||||
* If set to an integer number, e.g. 3, failed queries will retry until the failed query count meets that number.
|
||||
* If set to a function `(failureCount, error) => boolean` failed queries will retry until the function returns false.
|
||||
*/
|
||||
retry?: RetryValue<TError>;
|
||||
retryDelay?: RetryDelayValue<TError>;
|
||||
cacheTime?: number;
|
||||
isDataEqual?: (oldData: TData | undefined, newData: TData) => boolean;
|
||||
queryFn?: QueryFunction<TQueryFnData, TQueryKey>;
|
||||
queryHash?: string;
|
||||
queryKey?: TQueryKey;
|
||||
queryKeyHashFn?: QueryKeyHashFunction<TQueryKey>;
|
||||
initialData?: TData | InitialDataFunction<TData>;
|
||||
initialDataUpdatedAt?: number | (() => number | undefined);
|
||||
behavior?: QueryBehavior<TQueryFnData, TError, TData>;
|
||||
/**
|
||||
* Set this to `false` to disable structural sharing between query results.
|
||||
* Defaults to `true`.
|
||||
*/
|
||||
structuralSharing?: boolean;
|
||||
/**
|
||||
* This function can be set to automatically get the previous cursor for infinite queries.
|
||||
* The result will also be used to determine the value of `hasPreviousPage`.
|
||||
*/
|
||||
getPreviousPageParam?: GetPreviousPageParamFunction<TQueryFnData>;
|
||||
/**
|
||||
* This function can be set to automatically get the next cursor for infinite queries.
|
||||
* The result will also be used to determine the value of `hasNextPage`.
|
||||
*/
|
||||
getNextPageParam?: GetNextPageParamFunction<TQueryFnData>;
|
||||
_defaulted?: boolean;
|
||||
/**
|
||||
* Additional payload to be stored on each query.
|
||||
* Use this property to pass information that can be used in other places.
|
||||
*/
|
||||
meta?: QueryMeta;
|
||||
}
|
||||
export interface QueryObserverOptions<TQueryFnData = unknown, TError = unknown, TData = TQueryFnData, TQueryData = TQueryFnData, TQueryKey extends QueryKey = QueryKey> extends QueryOptions<TQueryFnData, TError, TQueryData, TQueryKey> {
|
||||
/**
|
||||
* Set this to `false` to disable automatic refetching when the query mounts or changes query keys.
|
||||
* To refetch the query, use the `refetch` method returned from the `useQuery` instance.
|
||||
* Defaults to `true`.
|
||||
*/
|
||||
enabled?: boolean;
|
||||
/**
|
||||
* The time in milliseconds after data is considered stale.
|
||||
* If set to `Infinity`, the data will never be considered stale.
|
||||
*/
|
||||
staleTime?: number;
|
||||
/**
|
||||
* If set to a number, the query will continuously refetch at this frequency in milliseconds.
|
||||
* If set to a function, the function will be executed with the latest data and query to compute a frequency
|
||||
* Defaults to `false`.
|
||||
*/
|
||||
refetchInterval?: number | false | ((data: TData | undefined, query: Query<TQueryFnData, TError, TQueryData, TQueryKey>) => number | false);
|
||||
/**
|
||||
* If set to `true`, the query will continue to refetch while their tab/window is in the background.
|
||||
* Defaults to `false`.
|
||||
*/
|
||||
refetchIntervalInBackground?: boolean;
|
||||
/**
|
||||
* If set to `true`, the query will refetch on window focus if the data is stale.
|
||||
* If set to `false`, the query will not refetch on window focus.
|
||||
* If set to `'always'`, the query will always refetch on window focus.
|
||||
* If set to a function, the function will be executed with the latest data and query to compute the value.
|
||||
* Defaults to `true`.
|
||||
*/
|
||||
refetchOnWindowFocus?: boolean | 'always' | ((query: Query<TQueryFnData, TError, TQueryData, TQueryKey>) => boolean | 'always');
|
||||
/**
|
||||
* If set to `true`, the query will refetch on reconnect if the data is stale.
|
||||
* If set to `false`, the query will not refetch on reconnect.
|
||||
* If set to `'always'`, the query will always refetch on reconnect.
|
||||
* If set to a function, the function will be executed with the latest data and query to compute the value.
|
||||
* Defaults to `true`.
|
||||
*/
|
||||
refetchOnReconnect?: boolean | 'always' | ((query: Query<TQueryFnData, TError, TQueryData, TQueryKey>) => boolean | 'always');
|
||||
/**
|
||||
* If set to `true`, the query will refetch on mount if the data is stale.
|
||||
* If set to `false`, will disable additional instances of a query to trigger background refetches.
|
||||
* If set to `'always'`, the query will always refetch on mount.
|
||||
* If set to a function, the function will be executed with the latest data and query to compute the value
|
||||
* Defaults to `true`.
|
||||
*/
|
||||
refetchOnMount?: boolean | 'always' | ((query: Query<TQueryFnData, TError, TQueryData, TQueryKey>) => boolean | 'always');
|
||||
/**
|
||||
* If set to `false`, the query will not be retried on mount if it contains an error.
|
||||
* Defaults to `true`.
|
||||
*/
|
||||
retryOnMount?: boolean;
|
||||
/**
|
||||
* If set, the component will only re-render if any of the listed properties change.
|
||||
* When set to `['data', 'error']`, the component will only re-render when the `data` or `error` properties change.
|
||||
* When set to `tracked`, access to properties will be tracked, and the component will only re-render when one of the tracked properties change.
|
||||
*/
|
||||
notifyOnChangeProps?: Array<keyof InfiniteQueryObserverResult> | 'tracked';
|
||||
/**
|
||||
* If set, the component will not re-render if any of the listed properties change.
|
||||
*/
|
||||
notifyOnChangePropsExclusions?: Array<keyof InfiniteQueryObserverResult>;
|
||||
/**
|
||||
* This callback will fire any time the query successfully fetches new data or the cache is updated via `setQueryData`.
|
||||
*/
|
||||
onSuccess?: (data: TData) => void;
|
||||
/**
|
||||
* This callback will fire if the query encounters an error and will be passed the error.
|
||||
*/
|
||||
onError?: (err: TError) => void;
|
||||
/**
|
||||
* This callback will fire any time the query is either successfully fetched or errors and be passed either the data or error.
|
||||
*/
|
||||
onSettled?: (data: TData | undefined, error: TError | null) => void;
|
||||
/**
|
||||
* Whether errors should be thrown instead of setting the `error` property.
|
||||
* If set to `true` or `suspense` is `true`, all errors will be thrown to the error boundary.
|
||||
* If set to `false` and `suspense` is `false`, errors are returned as state.
|
||||
* If set to a function, it will be passed the error and the query, and it should return a boolean indicating whether to show the error in an error boundary (`true`) or return the error as state (`false`).
|
||||
* Defaults to `false`.
|
||||
*/
|
||||
useErrorBoundary?: boolean | ((error: TError, query: Query<TQueryFnData, TError, TQueryData, TQueryKey>) => boolean);
|
||||
/**
|
||||
* This option can be used to transform or select a part of the data returned by the query function.
|
||||
*/
|
||||
select?: (data: TQueryData) => TData;
|
||||
/**
|
||||
* If set to `true`, the query will suspend when `status === 'loading'`
|
||||
* and throw errors when `status === 'error'`.
|
||||
* Defaults to `false`.
|
||||
*/
|
||||
suspense?: boolean;
|
||||
/**
|
||||
* Set this to `true` to keep the previous `data` when fetching based on a new query key.
|
||||
* Defaults to `false`.
|
||||
*/
|
||||
keepPreviousData?: boolean;
|
||||
/**
|
||||
* If set, this value will be used as the placeholder data for this particular query observer while the query is still in the `loading` data and no initialData has been provided.
|
||||
*/
|
||||
placeholderData?: TQueryData | PlaceholderDataFunction<TQueryData>;
|
||||
/**
|
||||
* If set, the observer will optimistically set the result in fetching state before the query has actually started fetching.
|
||||
* This is to make sure the results are not lagging behind.
|
||||
* Defaults to `true`.
|
||||
*/
|
||||
optimisticResults?: boolean;
|
||||
}
|
||||
export interface InfiniteQueryObserverOptions<TQueryFnData = unknown, TError = unknown, TData = TQueryFnData, TQueryData = TQueryFnData, TQueryKey extends QueryKey = QueryKey> extends QueryObserverOptions<TQueryFnData, TError, InfiniteData<TData>, InfiniteData<TQueryData>, TQueryKey> {
|
||||
}
|
||||
export interface FetchQueryOptions<TQueryFnData = unknown, TError = unknown, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey> extends QueryOptions<TQueryFnData, TError, TData, TQueryKey> {
|
||||
/**
|
||||
* The time in milliseconds after data is considered stale.
|
||||
* If the data is fresh it will be returned from the cache.
|
||||
*/
|
||||
staleTime?: number;
|
||||
}
|
||||
export interface FetchInfiniteQueryOptions<TQueryFnData = unknown, TError = unknown, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey> extends FetchQueryOptions<TQueryFnData, TError, InfiniteData<TData>, TQueryKey> {
|
||||
}
|
||||
export interface ResultOptions {
|
||||
throwOnError?: boolean;
|
||||
}
|
||||
export interface RefetchPageFilters<TPageData = unknown> {
|
||||
refetchPage?: (lastPage: TPageData, index: number, allPages: TPageData[]) => boolean;
|
||||
}
|
||||
export interface RefetchOptions extends ResultOptions {
|
||||
cancelRefetch?: boolean;
|
||||
}
|
||||
export interface InvalidateQueryFilters<TPageData = unknown> extends QueryFilters, RefetchPageFilters<TPageData> {
|
||||
refetchActive?: boolean;
|
||||
refetchInactive?: boolean;
|
||||
}
|
||||
export interface RefetchQueryFilters<TPageData = unknown> extends QueryFilters, RefetchPageFilters<TPageData> {
|
||||
}
|
||||
export interface ResetQueryFilters<TPageData = unknown> extends QueryFilters, RefetchPageFilters<TPageData> {
|
||||
}
|
||||
export interface InvalidateOptions extends RefetchOptions {
|
||||
}
|
||||
export interface ResetOptions extends RefetchOptions {
|
||||
}
|
||||
export interface FetchNextPageOptions extends ResultOptions {
|
||||
cancelRefetch?: boolean;
|
||||
pageParam?: unknown;
|
||||
}
|
||||
export interface FetchPreviousPageOptions extends ResultOptions {
|
||||
cancelRefetch?: boolean;
|
||||
pageParam?: unknown;
|
||||
}
|
||||
export declare type QueryStatus = 'idle' | 'loading' | 'error' | 'success';
|
||||
export interface QueryObserverBaseResult<TData = unknown, TError = unknown> {
|
||||
data: TData | undefined;
|
||||
dataUpdatedAt: number;
|
||||
error: TError | null;
|
||||
errorUpdatedAt: number;
|
||||
failureCount: number;
|
||||
errorUpdateCount: number;
|
||||
isError: boolean;
|
||||
isFetched: boolean;
|
||||
isFetchedAfterMount: boolean;
|
||||
isFetching: boolean;
|
||||
isIdle: boolean;
|
||||
isLoading: boolean;
|
||||
isLoadingError: boolean;
|
||||
isPlaceholderData: boolean;
|
||||
isPreviousData: boolean;
|
||||
isRefetchError: boolean;
|
||||
isRefetching: boolean;
|
||||
isStale: boolean;
|
||||
isSuccess: boolean;
|
||||
refetch: <TPageData>(options?: RefetchOptions & RefetchQueryFilters<TPageData>) => Promise<QueryObserverResult<TData, TError>>;
|
||||
remove: () => void;
|
||||
status: QueryStatus;
|
||||
}
|
||||
export interface QueryObserverIdleResult<TData = unknown, TError = unknown> extends QueryObserverBaseResult<TData, TError> {
|
||||
data: undefined;
|
||||
error: null;
|
||||
isError: false;
|
||||
isIdle: true;
|
||||
isLoading: false;
|
||||
isLoadingError: false;
|
||||
isRefetchError: false;
|
||||
isSuccess: false;
|
||||
status: 'idle';
|
||||
}
|
||||
export interface QueryObserverLoadingResult<TData = unknown, TError = unknown> extends QueryObserverBaseResult<TData, TError> {
|
||||
data: undefined;
|
||||
error: null;
|
||||
isError: false;
|
||||
isIdle: false;
|
||||
isLoading: true;
|
||||
isLoadingError: false;
|
||||
isRefetchError: false;
|
||||
isSuccess: false;
|
||||
status: 'loading';
|
||||
}
|
||||
export interface QueryObserverLoadingErrorResult<TData = unknown, TError = unknown> extends QueryObserverBaseResult<TData, TError> {
|
||||
data: undefined;
|
||||
error: TError;
|
||||
isError: true;
|
||||
isIdle: false;
|
||||
isLoading: false;
|
||||
isLoadingError: true;
|
||||
isRefetchError: false;
|
||||
isSuccess: false;
|
||||
status: 'error';
|
||||
}
|
||||
export interface QueryObserverRefetchErrorResult<TData = unknown, TError = unknown> extends QueryObserverBaseResult<TData, TError> {
|
||||
data: TData;
|
||||
error: TError;
|
||||
isError: true;
|
||||
isIdle: false;
|
||||
isLoading: false;
|
||||
isLoadingError: false;
|
||||
isRefetchError: true;
|
||||
isSuccess: false;
|
||||
status: 'error';
|
||||
}
|
||||
export interface QueryObserverSuccessResult<TData = unknown, TError = unknown> extends QueryObserverBaseResult<TData, TError> {
|
||||
data: TData;
|
||||
error: null;
|
||||
isError: false;
|
||||
isIdle: false;
|
||||
isLoading: false;
|
||||
isLoadingError: false;
|
||||
isRefetchError: false;
|
||||
isSuccess: true;
|
||||
status: 'success';
|
||||
}
|
||||
export declare type QueryObserverResult<TData = unknown, TError = unknown> = QueryObserverIdleResult<TData, TError> | QueryObserverLoadingErrorResult<TData, TError> | QueryObserverLoadingResult<TData, TError> | QueryObserverRefetchErrorResult<TData, TError> | QueryObserverSuccessResult<TData, TError>;
|
||||
export interface InfiniteQueryObserverBaseResult<TData = unknown, TError = unknown> extends QueryObserverBaseResult<InfiniteData<TData>, TError> {
|
||||
fetchNextPage: (options?: FetchNextPageOptions) => Promise<InfiniteQueryObserverResult<TData, TError>>;
|
||||
fetchPreviousPage: (options?: FetchPreviousPageOptions) => Promise<InfiniteQueryObserverResult<TData, TError>>;
|
||||
hasNextPage?: boolean;
|
||||
hasPreviousPage?: boolean;
|
||||
isFetchingNextPage: boolean;
|
||||
isFetchingPreviousPage: boolean;
|
||||
}
|
||||
export interface InfiniteQueryObserverIdleResult<TData = unknown, TError = unknown> extends InfiniteQueryObserverBaseResult<TData, TError> {
|
||||
data: undefined;
|
||||
error: null;
|
||||
isError: false;
|
||||
isIdle: true;
|
||||
isLoading: false;
|
||||
isLoadingError: false;
|
||||
isRefetchError: false;
|
||||
isSuccess: false;
|
||||
status: 'idle';
|
||||
}
|
||||
export interface InfiniteQueryObserverLoadingResult<TData = unknown, TError = unknown> extends InfiniteQueryObserverBaseResult<TData, TError> {
|
||||
data: undefined;
|
||||
error: null;
|
||||
isError: false;
|
||||
isIdle: false;
|
||||
isLoading: true;
|
||||
isLoadingError: false;
|
||||
isRefetchError: false;
|
||||
isSuccess: false;
|
||||
status: 'loading';
|
||||
}
|
||||
export interface InfiniteQueryObserverLoadingErrorResult<TData = unknown, TError = unknown> extends InfiniteQueryObserverBaseResult<TData, TError> {
|
||||
data: undefined;
|
||||
error: TError;
|
||||
isError: true;
|
||||
isIdle: false;
|
||||
isLoading: false;
|
||||
isLoadingError: true;
|
||||
isRefetchError: false;
|
||||
isSuccess: false;
|
||||
status: 'error';
|
||||
}
|
||||
export interface InfiniteQueryObserverRefetchErrorResult<TData = unknown, TError = unknown> extends InfiniteQueryObserverBaseResult<TData, TError> {
|
||||
data: InfiniteData<TData>;
|
||||
error: TError;
|
||||
isError: true;
|
||||
isIdle: false;
|
||||
isLoading: false;
|
||||
isLoadingError: false;
|
||||
isRefetchError: true;
|
||||
isSuccess: false;
|
||||
status: 'error';
|
||||
}
|
||||
export interface InfiniteQueryObserverSuccessResult<TData = unknown, TError = unknown> extends InfiniteQueryObserverBaseResult<TData, TError> {
|
||||
data: InfiniteData<TData>;
|
||||
error: null;
|
||||
isError: false;
|
||||
isIdle: false;
|
||||
isLoading: false;
|
||||
isLoadingError: false;
|
||||
isRefetchError: false;
|
||||
isSuccess: true;
|
||||
status: 'success';
|
||||
}
|
||||
export declare type InfiniteQueryObserverResult<TData = unknown, TError = unknown> = InfiniteQueryObserverIdleResult<TData, TError> | InfiniteQueryObserverLoadingErrorResult<TData, TError> | InfiniteQueryObserverLoadingResult<TData, TError> | InfiniteQueryObserverRefetchErrorResult<TData, TError> | InfiniteQueryObserverSuccessResult<TData, TError>;
|
||||
export declare type MutationKey = string | readonly unknown[];
|
||||
export declare type MutationStatus = 'idle' | 'loading' | 'success' | 'error';
|
||||
export declare type MutationMeta = Record<string, unknown>;
|
||||
export declare type MutationFunction<TData = unknown, TVariables = unknown> = (variables: TVariables) => Promise<TData>;
|
||||
export interface MutationOptions<TData = unknown, TError = unknown, TVariables = void, TContext = unknown> {
|
||||
mutationFn?: MutationFunction<TData, TVariables>;
|
||||
mutationKey?: MutationKey;
|
||||
variables?: TVariables;
|
||||
onMutate?: (variables: TVariables) => Promise<TContext | undefined> | TContext | undefined;
|
||||
onSuccess?: (data: TData, variables: TVariables, context: TContext | undefined) => Promise<unknown> | void;
|
||||
onError?: (error: TError, variables: TVariables, context: TContext | undefined) => Promise<unknown> | void;
|
||||
onSettled?: (data: TData | undefined, error: TError | null, variables: TVariables, context: TContext | undefined) => Promise<unknown> | void;
|
||||
retry?: RetryValue<TError>;
|
||||
retryDelay?: RetryDelayValue<TError>;
|
||||
_defaulted?: boolean;
|
||||
meta?: MutationMeta;
|
||||
}
|
||||
export interface MutationObserverOptions<TData = unknown, TError = unknown, TVariables = void, TContext = unknown> extends MutationOptions<TData, TError, TVariables, TContext> {
|
||||
useErrorBoundary?: boolean | ((error: TError) => boolean);
|
||||
}
|
||||
export interface MutateOptions<TData = unknown, TError = unknown, TVariables = void, TContext = unknown> {
|
||||
onSuccess?: (data: TData, variables: TVariables, context: TContext) => Promise<unknown> | void;
|
||||
onError?: (error: TError, variables: TVariables, context: TContext | undefined) => Promise<unknown> | void;
|
||||
onSettled?: (data: TData | undefined, error: TError | null, variables: TVariables, context: TContext | undefined) => Promise<unknown> | void;
|
||||
}
|
||||
export declare type MutateFunction<TData = unknown, TError = unknown, TVariables = void, TContext = unknown> = (variables: TVariables, options?: MutateOptions<TData, TError, TVariables, TContext>) => Promise<TData>;
|
||||
export interface MutationObserverBaseResult<TData = unknown, TError = unknown, TVariables = void, TContext = unknown> extends MutationState<TData, TError, TVariables, TContext> {
|
||||
isError: boolean;
|
||||
isIdle: boolean;
|
||||
isLoading: boolean;
|
||||
isSuccess: boolean;
|
||||
mutate: MutateFunction<TData, TError, TVariables, TContext>;
|
||||
reset: () => void;
|
||||
}
|
||||
export interface MutationObserverIdleResult<TData = unknown, TError = unknown, TVariables = void, TContext = unknown> extends MutationObserverBaseResult<TData, TError, TVariables, TContext> {
|
||||
data: undefined;
|
||||
error: null;
|
||||
isError: false;
|
||||
isIdle: true;
|
||||
isLoading: false;
|
||||
isSuccess: false;
|
||||
status: 'idle';
|
||||
}
|
||||
export interface MutationObserverLoadingResult<TData = unknown, TError = unknown, TVariables = void, TContext = unknown> extends MutationObserverBaseResult<TData, TError, TVariables, TContext> {
|
||||
data: undefined;
|
||||
error: null;
|
||||
isError: false;
|
||||
isIdle: false;
|
||||
isLoading: true;
|
||||
isSuccess: false;
|
||||
status: 'loading';
|
||||
}
|
||||
export interface MutationObserverErrorResult<TData = unknown, TError = unknown, TVariables = void, TContext = unknown> extends MutationObserverBaseResult<TData, TError, TVariables, TContext> {
|
||||
data: undefined;
|
||||
error: TError;
|
||||
isError: true;
|
||||
isIdle: false;
|
||||
isLoading: false;
|
||||
isSuccess: false;
|
||||
status: 'error';
|
||||
}
|
||||
export interface MutationObserverSuccessResult<TData = unknown, TError = unknown, TVariables = void, TContext = unknown> extends MutationObserverBaseResult<TData, TError, TVariables, TContext> {
|
||||
data: TData;
|
||||
error: null;
|
||||
isError: false;
|
||||
isIdle: false;
|
||||
isLoading: false;
|
||||
isSuccess: true;
|
||||
status: 'success';
|
||||
}
|
||||
export declare type MutationObserverResult<TData = unknown, TError = unknown, TVariables = void, TContext = unknown> = MutationObserverIdleResult<TData, TError, TVariables, TContext> | MutationObserverLoadingResult<TData, TError, TVariables, TContext> | MutationObserverErrorResult<TData, TError, TVariables, TContext> | MutationObserverSuccessResult<TData, TError, TVariables, TContext>;
|
||||
export interface QueryClientConfig {
|
||||
queryCache?: QueryCache;
|
||||
mutationCache?: MutationCache;
|
||||
defaultOptions?: DefaultOptions;
|
||||
}
|
||||
export interface DefaultOptions<TError = unknown> {
|
||||
queries?: QueryObserverOptions<unknown, TError>;
|
||||
mutations?: MutationObserverOptions<unknown, TError, unknown, unknown>;
|
||||
}
|
||||
export interface CancelOptions {
|
||||
revert?: boolean;
|
||||
silent?: boolean;
|
||||
}
|
||||
export interface SetDataOptions {
|
||||
updatedAt?: number;
|
||||
}
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
import { Mutation } from './mutation';
|
||||
import { Query } from './query';
|
||||
import { EnsuredQueryKey } from './types';
|
||||
import { MutationFunction, MutationKey, MutationOptions, QueryFunction, QueryKey, QueryOptions } from './types';
|
||||
export interface QueryFilters {
|
||||
/**
|
||||
* Include or exclude active queries
|
||||
*/
|
||||
active?: boolean;
|
||||
/**
|
||||
* Match query key exactly
|
||||
*/
|
||||
exact?: boolean;
|
||||
/**
|
||||
* Include or exclude inactive queries
|
||||
*/
|
||||
inactive?: boolean;
|
||||
/**
|
||||
* Include queries matching this predicate function
|
||||
*/
|
||||
predicate?: (query: Query) => boolean;
|
||||
/**
|
||||
* Include queries matching this query key
|
||||
*/
|
||||
queryKey?: QueryKey;
|
||||
/**
|
||||
* Include or exclude stale queries
|
||||
*/
|
||||
stale?: boolean;
|
||||
/**
|
||||
* Include or exclude fetching queries
|
||||
*/
|
||||
fetching?: boolean;
|
||||
}
|
||||
export interface MutationFilters {
|
||||
/**
|
||||
* Match mutation key exactly
|
||||
*/
|
||||
exact?: boolean;
|
||||
/**
|
||||
* Include mutations matching this predicate function
|
||||
*/
|
||||
predicate?: (mutation: Mutation<any, any, any>) => boolean;
|
||||
/**
|
||||
* Include mutations matching this mutation key
|
||||
*/
|
||||
mutationKey?: MutationKey;
|
||||
/**
|
||||
* Include or exclude fetching mutations
|
||||
*/
|
||||
fetching?: boolean;
|
||||
}
|
||||
export declare type DataUpdateFunction<TInput, TOutput> = (input: TInput) => TOutput;
|
||||
export declare type Updater<TInput, TOutput> = TOutput | DataUpdateFunction<TInput, TOutput>;
|
||||
export declare type QueryStatusFilter = 'all' | 'active' | 'inactive' | 'none';
|
||||
export declare const isServer: boolean;
|
||||
export declare function noop(): undefined;
|
||||
export declare function functionalUpdate<TInput, TOutput>(updater: Updater<TInput, TOutput>, input: TInput): TOutput;
|
||||
export declare function isValidTimeout(value: unknown): value is number;
|
||||
export declare function ensureQueryKeyArray<T extends QueryKey>(value: T): EnsuredQueryKey<T>;
|
||||
export declare function difference<T>(array1: T[], array2: T[]): T[];
|
||||
export declare function replaceAt<T>(array: T[], index: number, value: T): T[];
|
||||
export declare function timeUntilStale(updatedAt: number, staleTime?: number): number;
|
||||
export declare function parseQueryArgs<TOptions extends QueryOptions<any, any, any, TQueryKey>, TQueryKey extends QueryKey = QueryKey>(arg1: TQueryKey | TOptions, arg2?: QueryFunction<any, TQueryKey> | TOptions, arg3?: TOptions): TOptions;
|
||||
export declare function parseMutationArgs<TOptions extends MutationOptions<any, any, any, any>>(arg1: MutationKey | MutationFunction<any, any> | TOptions, arg2?: MutationFunction<any, any> | TOptions, arg3?: TOptions): TOptions;
|
||||
export declare function parseFilterArgs<TFilters extends QueryFilters, TOptions = unknown>(arg1?: QueryKey | TFilters, arg2?: TFilters | TOptions, arg3?: TOptions): [TFilters, TOptions | undefined];
|
||||
export declare function parseMutationFilterArgs(arg1?: QueryKey | MutationFilters, arg2?: MutationFilters): MutationFilters | undefined;
|
||||
export declare function mapQueryStatusFilter(active?: boolean, inactive?: boolean): QueryStatusFilter;
|
||||
export declare function matchQuery(filters: QueryFilters, query: Query<any, any, any, any>): boolean;
|
||||
export declare function matchMutation(filters: MutationFilters, mutation: Mutation<any, any>): boolean;
|
||||
export declare function hashQueryKeyByOptions<TQueryKey extends QueryKey = QueryKey>(queryKey: TQueryKey, options?: QueryOptions<any, any, any, TQueryKey>): string;
|
||||
/**
|
||||
* Default query keys hash function.
|
||||
*/
|
||||
export declare function hashQueryKey(queryKey: QueryKey): string;
|
||||
/**
|
||||
* Hashes the value into a stable hash.
|
||||
*/
|
||||
export declare function stableValueHash(value: any): string;
|
||||
/**
|
||||
* Checks if key `b` partially matches with key `a`.
|
||||
*/
|
||||
export declare function partialMatchKey(a: QueryKey, b: QueryKey): boolean;
|
||||
/**
|
||||
* Checks if `b` partially matches with `a`.
|
||||
*/
|
||||
export declare function partialDeepEqual(a: any, b: any): boolean;
|
||||
/**
|
||||
* This function returns `a` if `b` is deeply equal.
|
||||
* If not, it will replace any deeply equal children of `b` with those of `a`.
|
||||
* This can be used for structural sharing between JSON values for example.
|
||||
*/
|
||||
export declare function replaceEqualDeep<T>(a: unknown, b: T): T;
|
||||
/**
|
||||
* Shallow compare objects. Only works with objects that always have the same properties.
|
||||
*/
|
||||
export declare function shallowEqualObjects<T>(a: T, b: T): boolean;
|
||||
export declare function isPlainObject(o: any): o is Object;
|
||||
export declare function isQueryKey(value: any): value is QueryKey;
|
||||
export declare function isError(value: any): value is Error;
|
||||
export declare function sleep(timeout: number): Promise<void>;
|
||||
/**
|
||||
* Schedules a microtask.
|
||||
* This can be useful to schedule state updates after rendering.
|
||||
*/
|
||||
export declare function scheduleMicrotask(callback: () => void): void;
|
||||
export declare function getAbortController(): AbortController | undefined;
|
||||
Generated
Vendored
+27
@@ -0,0 +1,27 @@
|
||||
import { PersistedClient, Persistor } from '../persistQueryClient-experimental';
|
||||
interface AsyncStorage {
|
||||
getItem: (key: string) => Promise<string | null>;
|
||||
setItem: (key: string, value: string) => Promise<void>;
|
||||
removeItem: (key: string) => Promise<void>;
|
||||
}
|
||||
interface CreateAsyncStoragePersistorOptions {
|
||||
/** The storage client used for setting an retrieving items from cache */
|
||||
storage: AsyncStorage;
|
||||
/** The key to use when storing the cache */
|
||||
key?: string;
|
||||
/** To avoid spamming,
|
||||
* pass a time in ms to throttle saving the cache to disk */
|
||||
throttleTime?: number;
|
||||
/**
|
||||
* How to serialize the data to storage.
|
||||
* @default `JSON.stringify`
|
||||
*/
|
||||
serialize?: (client: PersistedClient) => string;
|
||||
/**
|
||||
* How to deserialize the data from storage.
|
||||
* @default `JSON.parse`
|
||||
*/
|
||||
deserialize?: (cachedString: string) => PersistedClient;
|
||||
}
|
||||
export declare const createAsyncStoragePersistor: ({ storage, key, throttleTime, serialize, deserialize, }: CreateAsyncStoragePersistorOptions) => Persistor;
|
||||
export {};
|
||||
Generated
Vendored
+22
@@ -0,0 +1,22 @@
|
||||
import { PersistedClient, Persistor } from '../persistQueryClient-experimental';
|
||||
interface CreateWebStoragePersistorOptions {
|
||||
/** The storage client used for setting an retrieving items from cache */
|
||||
storage: Storage;
|
||||
/** The key to use when storing the cache */
|
||||
key?: string;
|
||||
/** To avoid spamming,
|
||||
* pass a time in ms to throttle saving the cache to disk */
|
||||
throttleTime?: number;
|
||||
/**
|
||||
* How to serialize the data to storage.
|
||||
* @default `JSON.stringify`
|
||||
*/
|
||||
serialize?: (client: PersistedClient) => string;
|
||||
/**
|
||||
* How to deserialize the data from storage.
|
||||
* @default `JSON.parse`
|
||||
*/
|
||||
deserialize?: (cachedString: string) => PersistedClient;
|
||||
}
|
||||
export declare function createWebStoragePersistor({ storage, key, throttleTime, serialize, deserialize, }: CreateWebStoragePersistorOptions): Persistor;
|
||||
export {};
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
import React from 'react';
|
||||
export declare const Entry: React.ForwardRefExoticComponent<React.HTMLAttributes<HTMLDivElement> & React.RefAttributes<HTMLDivElement>>;
|
||||
export declare const Label: React.ForwardRefExoticComponent<React.HTMLAttributes<HTMLSpanElement> & React.RefAttributes<HTMLSpanElement>>;
|
||||
export declare const LabelButton: React.ForwardRefExoticComponent<Pick<React.DetailedHTMLProps<React.ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>, "hidden" | "children" | "value" | "form" | "slot" | "style" | "title" | "onError" | "dir" | "color" | "key" | "autoFocus" | "disabled" | "formAction" | "formEncType" | "formMethod" | "formNoValidate" | "formTarget" | "name" | "type" | "defaultChecked" | "defaultValue" | "suppressContentEditableWarning" | "suppressHydrationWarning" | "accessKey" | "className" | "contentEditable" | "contextMenu" | "draggable" | "id" | "lang" | "placeholder" | "spellCheck" | "tabIndex" | "translate" | "radioGroup" | "role" | "about" | "datatype" | "inlist" | "prefix" | "property" | "resource" | "typeof" | "vocab" | "autoCapitalize" | "autoCorrect" | "autoSave" | "itemProp" | "itemScope" | "itemType" | "itemID" | "itemRef" | "results" | "security" | "unselectable" | "inputMode" | "is" | "aria-activedescendant" | "aria-atomic" | "aria-autocomplete" | "aria-busy" | "aria-checked" | "aria-colcount" | "aria-colindex" | "aria-colspan" | "aria-controls" | "aria-current" | "aria-describedby" | "aria-details" | "aria-disabled" | "aria-dropeffect" | "aria-errormessage" | "aria-expanded" | "aria-flowto" | "aria-grabbed" | "aria-haspopup" | "aria-hidden" | "aria-invalid" | "aria-keyshortcuts" | "aria-label" | "aria-labelledby" | "aria-level" | "aria-live" | "aria-modal" | "aria-multiline" | "aria-multiselectable" | "aria-orientation" | "aria-owns" | "aria-placeholder" | "aria-posinset" | "aria-pressed" | "aria-readonly" | "aria-relevant" | "aria-required" | "aria-roledescription" | "aria-rowcount" | "aria-rowindex" | "aria-rowspan" | "aria-selected" | "aria-setsize" | "aria-sort" | "aria-valuemax" | "aria-valuemin" | "aria-valuenow" | "aria-valuetext" | "dangerouslySetInnerHTML" | "onCopy" | "onCopyCapture" | "onCut" | "onCutCapture" | "onPaste" | "onPasteCapture" | "onCompositionEnd" | "onCompositionEndCapture" | "onCompositionStart" | "onCompositionStartCapture" | "onCompositionUpdate" | "onCompositionUpdateCapture" | "onFocus" | "onFocusCapture" | "onBlur" | "onBlurCapture" | "onChange" | "onChangeCapture" | "onBeforeInput" | "onBeforeInputCapture" | "onInput" | "onInputCapture" | "onReset" | "onResetCapture" | "onSubmit" | "onSubmitCapture" | "onInvalid" | "onInvalidCapture" | "onLoad" | "onLoadCapture" | "onErrorCapture" | "onKeyDown" | "onKeyDownCapture" | "onKeyPress" | "onKeyPressCapture" | "onKeyUp" | "onKeyUpCapture" | "onAbort" | "onAbortCapture" | "onCanPlay" | "onCanPlayCapture" | "onCanPlayThrough" | "onCanPlayThroughCapture" | "onDurationChange" | "onDurationChangeCapture" | "onEmptied" | "onEmptiedCapture" | "onEncrypted" | "onEncryptedCapture" | "onEnded" | "onEndedCapture" | "onLoadedData" | "onLoadedDataCapture" | "onLoadedMetadata" | "onLoadedMetadataCapture" | "onLoadStart" | "onLoadStartCapture" | "onPause" | "onPauseCapture" | "onPlay" | "onPlayCapture" | "onPlaying" | "onPlayingCapture" | "onProgress" | "onProgressCapture" | "onRateChange" | "onRateChangeCapture" | "onSeeked" | "onSeekedCapture" | "onSeeking" | "onSeekingCapture" | "onStalled" | "onStalledCapture" | "onSuspend" | "onSuspendCapture" | "onTimeUpdate" | "onTimeUpdateCapture" | "onVolumeChange" | "onVolumeChangeCapture" | "onWaiting" | "onWaitingCapture" | "onAuxClick" | "onAuxClickCapture" | "onClick" | "onClickCapture" | "onContextMenu" | "onContextMenuCapture" | "onDoubleClick" | "onDoubleClickCapture" | "onDrag" | "onDragCapture" | "onDragEnd" | "onDragEndCapture" | "onDragEnter" | "onDragEnterCapture" | "onDragExit" | "onDragExitCapture" | "onDragLeave" | "onDragLeaveCapture" | "onDragOver" | "onDragOverCapture" | "onDragStart" | "onDragStartCapture" | "onDrop" | "onDropCapture" | "onMouseDown" | "onMouseDownCapture" | "onMouseEnter" | "onMouseLeave" | "onMouseMove" | "onMouseMoveCapture" | "onMouseOut" | "onMouseOutCapture" | "onMouseOver" | "onMouseOverCapture" | "onMouseUp" | "onMouseUpCapture" | "onSelect" | "onSelectCapture" | "onTouchCancel" | "onTouchCancelCapture" | "onTouchEnd" | "onTouchEndCapture" | "onTouchMove" | "onTouchMoveCapture" | "onTouchStart" | "onTouchStartCapture" | "onPointerDown" | "onPointerDownCapture" | "onPointerMove" | "onPointerMoveCapture" | "onPointerUp" | "onPointerUpCapture" | "onPointerCancel" | "onPointerCancelCapture" | "onPointerEnter" | "onPointerEnterCapture" | "onPointerLeave" | "onPointerLeaveCapture" | "onPointerOver" | "onPointerOverCapture" | "onPointerOut" | "onPointerOutCapture" | "onGotPointerCapture" | "onGotPointerCaptureCapture" | "onLostPointerCapture" | "onLostPointerCaptureCapture" | "onScroll" | "onScrollCapture" | "onWheel" | "onWheelCapture" | "onAnimationStart" | "onAnimationStartCapture" | "onAnimationEnd" | "onAnimationEndCapture" | "onAnimationIteration" | "onAnimationIterationCapture" | "onTransitionEnd" | "onTransitionEndCapture"> & React.RefAttributes<HTMLButtonElement>>;
|
||||
export declare const ExpandButton: React.ForwardRefExoticComponent<Pick<React.DetailedHTMLProps<React.ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>, "hidden" | "children" | "value" | "form" | "slot" | "style" | "title" | "onError" | "dir" | "color" | "key" | "autoFocus" | "disabled" | "formAction" | "formEncType" | "formMethod" | "formNoValidate" | "formTarget" | "name" | "type" | "defaultChecked" | "defaultValue" | "suppressContentEditableWarning" | "suppressHydrationWarning" | "accessKey" | "className" | "contentEditable" | "contextMenu" | "draggable" | "id" | "lang" | "placeholder" | "spellCheck" | "tabIndex" | "translate" | "radioGroup" | "role" | "about" | "datatype" | "inlist" | "prefix" | "property" | "resource" | "typeof" | "vocab" | "autoCapitalize" | "autoCorrect" | "autoSave" | "itemProp" | "itemScope" | "itemType" | "itemID" | "itemRef" | "results" | "security" | "unselectable" | "inputMode" | "is" | "aria-activedescendant" | "aria-atomic" | "aria-autocomplete" | "aria-busy" | "aria-checked" | "aria-colcount" | "aria-colindex" | "aria-colspan" | "aria-controls" | "aria-current" | "aria-describedby" | "aria-details" | "aria-disabled" | "aria-dropeffect" | "aria-errormessage" | "aria-expanded" | "aria-flowto" | "aria-grabbed" | "aria-haspopup" | "aria-hidden" | "aria-invalid" | "aria-keyshortcuts" | "aria-label" | "aria-labelledby" | "aria-level" | "aria-live" | "aria-modal" | "aria-multiline" | "aria-multiselectable" | "aria-orientation" | "aria-owns" | "aria-placeholder" | "aria-posinset" | "aria-pressed" | "aria-readonly" | "aria-relevant" | "aria-required" | "aria-roledescription" | "aria-rowcount" | "aria-rowindex" | "aria-rowspan" | "aria-selected" | "aria-setsize" | "aria-sort" | "aria-valuemax" | "aria-valuemin" | "aria-valuenow" | "aria-valuetext" | "dangerouslySetInnerHTML" | "onCopy" | "onCopyCapture" | "onCut" | "onCutCapture" | "onPaste" | "onPasteCapture" | "onCompositionEnd" | "onCompositionEndCapture" | "onCompositionStart" | "onCompositionStartCapture" | "onCompositionUpdate" | "onCompositionUpdateCapture" | "onFocus" | "onFocusCapture" | "onBlur" | "onBlurCapture" | "onChange" | "onChangeCapture" | "onBeforeInput" | "onBeforeInputCapture" | "onInput" | "onInputCapture" | "onReset" | "onResetCapture" | "onSubmit" | "onSubmitCapture" | "onInvalid" | "onInvalidCapture" | "onLoad" | "onLoadCapture" | "onErrorCapture" | "onKeyDown" | "onKeyDownCapture" | "onKeyPress" | "onKeyPressCapture" | "onKeyUp" | "onKeyUpCapture" | "onAbort" | "onAbortCapture" | "onCanPlay" | "onCanPlayCapture" | "onCanPlayThrough" | "onCanPlayThroughCapture" | "onDurationChange" | "onDurationChangeCapture" | "onEmptied" | "onEmptiedCapture" | "onEncrypted" | "onEncryptedCapture" | "onEnded" | "onEndedCapture" | "onLoadedData" | "onLoadedDataCapture" | "onLoadedMetadata" | "onLoadedMetadataCapture" | "onLoadStart" | "onLoadStartCapture" | "onPause" | "onPauseCapture" | "onPlay" | "onPlayCapture" | "onPlaying" | "onPlayingCapture" | "onProgress" | "onProgressCapture" | "onRateChange" | "onRateChangeCapture" | "onSeeked" | "onSeekedCapture" | "onSeeking" | "onSeekingCapture" | "onStalled" | "onStalledCapture" | "onSuspend" | "onSuspendCapture" | "onTimeUpdate" | "onTimeUpdateCapture" | "onVolumeChange" | "onVolumeChangeCapture" | "onWaiting" | "onWaitingCapture" | "onAuxClick" | "onAuxClickCapture" | "onClick" | "onClickCapture" | "onContextMenu" | "onContextMenuCapture" | "onDoubleClick" | "onDoubleClickCapture" | "onDrag" | "onDragCapture" | "onDragEnd" | "onDragEndCapture" | "onDragEnter" | "onDragEnterCapture" | "onDragExit" | "onDragExitCapture" | "onDragLeave" | "onDragLeaveCapture" | "onDragOver" | "onDragOverCapture" | "onDragStart" | "onDragStartCapture" | "onDrop" | "onDropCapture" | "onMouseDown" | "onMouseDownCapture" | "onMouseEnter" | "onMouseLeave" | "onMouseMove" | "onMouseMoveCapture" | "onMouseOut" | "onMouseOutCapture" | "onMouseOver" | "onMouseOverCapture" | "onMouseUp" | "onMouseUpCapture" | "onSelect" | "onSelectCapture" | "onTouchCancel" | "onTouchCancelCapture" | "onTouchEnd" | "onTouchEndCapture" | "onTouchMove" | "onTouchMoveCapture" | "onTouchStart" | "onTouchStartCapture" | "onPointerDown" | "onPointerDownCapture" | "onPointerMove" | "onPointerMoveCapture" | "onPointerUp" | "onPointerUpCapture" | "onPointerCancel" | "onPointerCancelCapture" | "onPointerEnter" | "onPointerEnterCapture" | "onPointerLeave" | "onPointerLeaveCapture" | "onPointerOver" | "onPointerOverCapture" | "onPointerOut" | "onPointerOutCapture" | "onGotPointerCapture" | "onGotPointerCaptureCapture" | "onLostPointerCapture" | "onLostPointerCaptureCapture" | "onScroll" | "onScrollCapture" | "onWheel" | "onWheelCapture" | "onAnimationStart" | "onAnimationStartCapture" | "onAnimationEnd" | "onAnimationEndCapture" | "onAnimationIteration" | "onAnimationIterationCapture" | "onTransitionEnd" | "onTransitionEndCapture"> & React.RefAttributes<HTMLButtonElement>>;
|
||||
export declare const Value: React.ForwardRefExoticComponent<React.HTMLAttributes<HTMLSpanElement> & React.RefAttributes<HTMLSpanElement>>;
|
||||
export declare const SubEntries: React.ForwardRefExoticComponent<React.HTMLAttributes<HTMLDivElement> & React.RefAttributes<HTMLDivElement>>;
|
||||
export declare const Info: React.ForwardRefExoticComponent<React.HTMLAttributes<HTMLSpanElement> & React.RefAttributes<HTMLSpanElement>>;
|
||||
declare type ExpanderProps = {
|
||||
expanded: boolean;
|
||||
style?: React.CSSProperties;
|
||||
};
|
||||
export declare const Expander: ({ expanded, style }: ExpanderProps) => JSX.Element;
|
||||
declare type Entry = {
|
||||
label: string;
|
||||
};
|
||||
declare type RendererProps = {
|
||||
HandleEntry: HandleEntryComponent;
|
||||
label?: string;
|
||||
value: unknown;
|
||||
subEntries: Entry[];
|
||||
subEntryPages: Entry[][];
|
||||
type: string;
|
||||
expanded: boolean;
|
||||
toggleExpanded: () => void;
|
||||
pageSize: number;
|
||||
};
|
||||
/**
|
||||
* Chunk elements in the array by size
|
||||
*
|
||||
* when the array cannot be chunked evenly by size, the last chunk will be
|
||||
* filled with the remaining elements
|
||||
*
|
||||
* @example
|
||||
* chunkArray(['a','b', 'c', 'd', 'e'], 2) // returns [['a','b'], ['c', 'd'], ['e']]
|
||||
*/
|
||||
export declare function chunkArray<T>(array: T[], size: number): T[][];
|
||||
declare type Renderer = (props: RendererProps) => JSX.Element;
|
||||
export declare const DefaultRenderer: Renderer;
|
||||
declare type HandleEntryComponent = (props: {
|
||||
entry: Entry;
|
||||
}) => JSX.Element;
|
||||
declare type ExplorerProps = Partial<RendererProps> & {
|
||||
renderer?: Renderer;
|
||||
defaultExpanded?: true | Record<string, boolean>;
|
||||
};
|
||||
export default function Explorer({ value, defaultExpanded, renderer, pageSize, ...rest }: ExplorerProps): JSX.Element;
|
||||
export {};
|
||||
+1
@@ -0,0 +1 @@
|
||||
export default function Logo(props: any): JSX.Element;
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
import React from 'react';
|
||||
interface DevtoolsOptions {
|
||||
/**
|
||||
* Set this true if you want the dev tools to default to being open
|
||||
*/
|
||||
initialIsOpen?: boolean;
|
||||
/**
|
||||
* Use this to add props to the panel. For example, you can add className, style (merge and override default style), etc.
|
||||
*/
|
||||
panelProps?: React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>;
|
||||
/**
|
||||
* Use this to add props to the close button. For example, you can add className, style (merge and override default style), onClick (extend default handler), etc.
|
||||
*/
|
||||
closeButtonProps?: React.DetailedHTMLProps<React.ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>;
|
||||
/**
|
||||
* Use this to add props to the toggle button. For example, you can add className, style (merge and override default style), onClick (extend default handler), etc.
|
||||
*/
|
||||
toggleButtonProps?: React.DetailedHTMLProps<React.ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>;
|
||||
/**
|
||||
* The position of the React Query logo to open and close the devtools panel.
|
||||
* Defaults to 'bottom-left'.
|
||||
*/
|
||||
position?: 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right';
|
||||
/**
|
||||
* Use this to render the devtools inside a different type of container element for a11y purposes.
|
||||
* Any string which corresponds to a valid intrinsic JSX element is allowed.
|
||||
* Defaults to 'aside'.
|
||||
*/
|
||||
containerElement?: string | any;
|
||||
/**
|
||||
* nonce for style element for CSP
|
||||
*/
|
||||
styleNonce?: string;
|
||||
}
|
||||
interface DevtoolsPanelOptions {
|
||||
/**
|
||||
* The standard React style object used to style a component with inline styles
|
||||
*/
|
||||
style?: React.CSSProperties;
|
||||
/**
|
||||
* The standard React className property used to style a component with classes
|
||||
*/
|
||||
className?: string;
|
||||
/**
|
||||
* A boolean variable indicating whether the panel is open or closed
|
||||
*/
|
||||
isOpen?: boolean;
|
||||
/**
|
||||
* nonce for style element for CSP
|
||||
*/
|
||||
styleNonce?: string;
|
||||
/**
|
||||
* A function that toggles the open and close state of the panel
|
||||
*/
|
||||
setIsOpen: (isOpen: boolean) => void;
|
||||
/**
|
||||
* Handles the opening and closing the devtools panel
|
||||
*/
|
||||
handleDragStart: (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => void;
|
||||
}
|
||||
export declare function ReactQueryDevtools({ initialIsOpen, panelProps, closeButtonProps, toggleButtonProps, position, containerElement: Container, styleNonce, }: DevtoolsOptions): React.ReactElement | null;
|
||||
export declare const ReactQueryDevtoolsPanel: React.ForwardRefExoticComponent<DevtoolsPanelOptions & React.RefAttributes<HTMLDivElement>>;
|
||||
export {};
|
||||
+1
@@ -0,0 +1 @@
|
||||
export * from './devtools';
|
||||
+8
File diff suppressed because one or more lines are too long
+34
@@ -0,0 +1,34 @@
|
||||
import React from 'react';
|
||||
export declare const defaultTheme: {
|
||||
readonly background: "#0b1521";
|
||||
readonly backgroundAlt: "#132337";
|
||||
readonly foreground: "white";
|
||||
readonly gray: "#3f4e60";
|
||||
readonly grayAlt: "#222e3e";
|
||||
readonly inputBackgroundColor: "#fff";
|
||||
readonly inputTextColor: "#000";
|
||||
readonly success: "#00ab52";
|
||||
readonly danger: "#ff0085";
|
||||
readonly active: "#006bff";
|
||||
readonly warning: "#ffb200";
|
||||
};
|
||||
export declare type Theme = typeof defaultTheme;
|
||||
interface ProviderProps {
|
||||
theme: Theme;
|
||||
children?: React.ReactNode;
|
||||
}
|
||||
export declare function ThemeProvider({ theme, ...rest }: ProviderProps): JSX.Element;
|
||||
export declare function useTheme(): {
|
||||
readonly background: "#0b1521";
|
||||
readonly backgroundAlt: "#132337";
|
||||
readonly foreground: "white";
|
||||
readonly gray: "#3f4e60";
|
||||
readonly grayAlt: "#222e3e";
|
||||
readonly inputBackgroundColor: "#fff";
|
||||
readonly inputTextColor: "#000";
|
||||
readonly success: "#00ab52";
|
||||
readonly danger: "#ff0085";
|
||||
readonly active: "#006bff";
|
||||
readonly warning: "#ffb200";
|
||||
};
|
||||
export {};
|
||||
+1
@@ -0,0 +1 @@
|
||||
export default function useLocalStorage<T>(key: string, defaultValue: T | undefined): [T | undefined, (newVal: T | ((prevVal: T) => T)) => void];
|
||||
+1
@@ -0,0 +1 @@
|
||||
export default function useMediaQuery(query: string): boolean | undefined;
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
import React from 'react';
|
||||
import { Query } from '../core';
|
||||
import { Theme } from './theme';
|
||||
export declare const isServer: boolean;
|
||||
declare type StyledComponent<T> = T extends 'button' ? React.DetailedHTMLProps<React.ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement> : T extends 'input' ? React.DetailedHTMLProps<React.InputHTMLAttributes<HTMLInputElement>, HTMLInputElement> : T extends 'select' ? React.DetailedHTMLProps<React.SelectHTMLAttributes<HTMLSelectElement>, HTMLSelectElement> : T extends keyof HTMLElementTagNameMap ? React.HTMLAttributes<HTMLElementTagNameMap[T]> : never;
|
||||
export declare function getQueryStatusColor(query: Query, theme: Theme): "#3f4e60" | "#00ab52" | "#006bff" | "#ffb200";
|
||||
export declare function getQueryStatusLabel(query: Query): "inactive" | "fetching" | "stale" | "fresh";
|
||||
declare type Styles = React.CSSProperties | ((props: Record<string, any>, theme: Theme) => React.CSSProperties);
|
||||
export declare function styled<T extends keyof HTMLElementTagNameMap>(type: T, newStyles: Styles, queries?: Record<string, Styles>): React.ForwardRefExoticComponent<React.PropsWithoutRef<StyledComponent<T>> & React.RefAttributes<HTMLElementTagNameMap[T]>>;
|
||||
export declare function useIsMounted(): () => boolean;
|
||||
/**
|
||||
* This hook is a safe useState version which schedules state updates in microtasks
|
||||
* to prevent updating a component state while React is rendering different components
|
||||
* or when the component is not mounted anymore.
|
||||
*/
|
||||
export declare function useSafeState<T>(initialState: T): [T, (value: T) => void];
|
||||
/**
|
||||
* Displays a string regardless the type of the data
|
||||
* @param {unknown} value Value to be stringified
|
||||
*/
|
||||
export declare const displayValue: (value: unknown) => string;
|
||||
export {};
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
export { dehydrate, hydrate, useHydrate, Hydrate } from 'react-query';
|
||||
export { DehydrateOptions, DehydratedState, HydrateOptions, ShouldDehydrateMutationFunction, ShouldDehydrateQueryFunction, } from '../core/hydration';
|
||||
export { HydrateProps } from '../react/Hydrate';
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
export * from './core';
|
||||
export * from './react';
|
||||
Generated
Vendored
+32
@@ -0,0 +1,32 @@
|
||||
import { QueryClient } from '../core';
|
||||
import { DehydratedState, DehydrateOptions, HydrateOptions } from 'react-query';
|
||||
import { Promisable } from 'type-fest';
|
||||
export interface Persistor {
|
||||
persistClient(persistClient: PersistedClient): Promisable<void>;
|
||||
restoreClient(): Promisable<PersistedClient | undefined>;
|
||||
removeClient(): Promisable<void>;
|
||||
}
|
||||
export interface PersistedClient {
|
||||
timestamp: number;
|
||||
buster: string;
|
||||
clientState: DehydratedState;
|
||||
}
|
||||
export interface PersistQueryClientOptions {
|
||||
/** The QueryClient to persist */
|
||||
queryClient: QueryClient;
|
||||
/** The Persistor interface for storing and restoring the cache
|
||||
* to/from a persisted location */
|
||||
persistor: Persistor;
|
||||
/** The max-allowed age of the cache.
|
||||
* If a persisted cache is found that is older than this
|
||||
* time, it will be discarded */
|
||||
maxAge?: number;
|
||||
/** A unique string that can be used to forcefully
|
||||
* invalidate existing caches if they do not share the same buster string */
|
||||
buster?: string;
|
||||
/** The options passed to the hydrate function */
|
||||
hydrateOptions?: HydrateOptions;
|
||||
/** The options passed to the dehydrate function */
|
||||
dehydrateOptions?: DehydrateOptions;
|
||||
}
|
||||
export declare function persistQueryClient({ queryClient, persistor, maxAge, buster, hydrateOptions, dehydrateOptions, }: PersistQueryClientOptions): Promise<void>;
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
import React from 'react';
|
||||
import { HydrateOptions } from '../core';
|
||||
export declare function useHydrate(state: unknown, options?: HydrateOptions): void;
|
||||
export interface HydrateProps {
|
||||
state?: unknown;
|
||||
options?: HydrateOptions;
|
||||
children?: React.ReactNode;
|
||||
}
|
||||
export declare const Hydrate: ({ children, options, state }: HydrateProps) => React.ReactElement<any, string | ((props: any) => React.ReactElement<any, any> | null) | (new (props: any) => React.Component<any, any, any>)>;
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import React from 'react';
|
||||
import { QueryClient } from '../core';
|
||||
declare global {
|
||||
interface Window {
|
||||
ReactQueryClientContext?: React.Context<QueryClient | undefined>;
|
||||
}
|
||||
}
|
||||
export declare const useQueryClient: () => QueryClient;
|
||||
export interface QueryClientProviderProps {
|
||||
client: QueryClient;
|
||||
contextSharing?: boolean;
|
||||
children?: React.ReactNode;
|
||||
}
|
||||
export declare const QueryClientProvider: ({ client, contextSharing, children, }: QueryClientProviderProps) => JSX.Element;
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
import React from 'react';
|
||||
interface QueryErrorResetBoundaryValue {
|
||||
clearReset: () => void;
|
||||
isReset: () => boolean;
|
||||
reset: () => void;
|
||||
}
|
||||
export declare const useQueryErrorResetBoundary: () => QueryErrorResetBoundaryValue;
|
||||
export interface QueryErrorResetBoundaryProps {
|
||||
children: ((value: QueryErrorResetBoundaryValue) => React.ReactNode) | React.ReactNode;
|
||||
}
|
||||
export declare const QueryErrorResetBoundary: ({ children, }: QueryErrorResetBoundaryProps) => JSX.Element;
|
||||
export {};
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
import './setBatchUpdatesFn';
|
||||
import './setLogger';
|
||||
export { QueryClientProvider, useQueryClient } from './QueryClientProvider';
|
||||
export { QueryErrorResetBoundary, useQueryErrorResetBoundary, } from './QueryErrorResetBoundary';
|
||||
export { useIsFetching } from './useIsFetching';
|
||||
export { useIsMutating } from './useIsMutating';
|
||||
export { useMutation } from './useMutation';
|
||||
export { useQuery } from './useQuery';
|
||||
export { useQueries } from './useQueries';
|
||||
export { useInfiniteQuery } from './useInfiniteQuery';
|
||||
export { useHydrate, Hydrate } from './Hydrate';
|
||||
export * from './types';
|
||||
export { QueryClientProviderProps } from './QueryClientProvider';
|
||||
export { QueryErrorResetBoundaryProps } from './QueryErrorResetBoundary';
|
||||
export { HydrateProps } from './Hydrate';
|
||||
export { QueriesOptions, QueriesResults } from './useQueries';
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
import { Logger } from '../core/logger';
|
||||
export declare const logger: Logger;
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
import ReactDOM from 'react-dom';
|
||||
export declare const unstable_batchedUpdates: typeof ReactDOM.unstable_batchedUpdates;
|
||||
+1
@@ -0,0 +1 @@
|
||||
export {};
|
||||
+1
@@ -0,0 +1 @@
|
||||
export {};
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user