@bigbinary/neeto-commons-frontend 2.0.104 → 2.0.106

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/react-utils.d.ts CHANGED
@@ -3,6 +3,7 @@ import { RouteProps } from "react-router-dom";
3
3
  import { Notice } from "@honeybadger-io/js/dist/server/types/core/types";
4
4
  import { History } from "history";
5
5
  import { StoreApi, UseBoundStore } from "zustand";
6
+ import { UseQueryOptions, UseQueryResult } from "react-query";
6
7
  /**
7
8
  *
8
9
  * ErrorBoundary which reports frontend errors to HoneyBadger
@@ -119,11 +120,11 @@ export function useIsElementVisibleInDom(target: Element | null, options?: Optio
119
120
  *
120
121
  * until the updates are stopped. We can use this to limit the number of API calls
121
122
  *
122
- * triggered from a user input like search box. The value returned by the
123
+ * triggered from a user input like search box. The value returned by the hook will
123
124
  *
124
- * hook will only reflect the latest value when the hook has not been called for
125
+ * only reflect the latest value when the hook has not been called for the
125
126
  *
126
- * the specified time period delay.
127
+ * specified time period delay.
127
128
  *
128
129
  * @example
129
130
  *
@@ -146,9 +147,9 @@ export function useDebounce<T>(value: T, delay?: number): T;
146
147
  *
147
148
  * function will be executed only when the dependencies stops changing for a while.
148
149
  *
149
- * The debounced function comes with a cancel method which can
150
+ * The debounced function comes with a cancel method which can be used to cancel
150
151
  *
151
- * be used to cancel the delayed function invocation.
152
+ * the delayed function invocation.
152
153
  *
153
154
  * @example
154
155
  *
@@ -251,7 +252,7 @@ export function usePrevious<T>(value: T): T;
251
252
  * @example
252
253
  *
253
254
  * useUpdateEffect(() => {
254
- * setTitle(value)
255
+ * setTitle(value);
255
256
  * }, [value]);
256
257
  * @endexample
257
258
  */
@@ -394,9 +395,9 @@ export declare type ZustandStoreHook = UseBoundStore<StoreApi<any>> & {
394
395
  *
395
396
  * will not submit when Shift + Enter is pressed. Shift + Enter can be used to
396
397
  *
397
- * add new lines to text area in the form. The hook returns a ref. This need to be
398
+ * add new lines to text area in the form. The hook returns a ref. This need to
398
399
  *
399
- * attached to the input element to be listened to.
400
+ * be attached to the input element to be listened to.
400
401
  *
401
402
  * @example
402
403
  *
@@ -653,9 +654,11 @@ export function useHotKeys(hotkey: string | string[], handler: (event: React.Key
653
654
  export function useStateWithDependency<T>(defaultValue: T, dependencies?: any[]): T;
654
655
  /**
655
656
  *
656
- * This hook will store the path as the value for the key in a Zustand store. This
657
+ * This hook will store the path as the value for the key in a Zustand store.
657
658
  *
658
- * registered checkpoint can be retrieved using the useNavigationCheckpoints hook.
659
+ * This registered checkpoint can be retrieved using the useNavigationCheckpoints
660
+ *
661
+ * hook.
659
662
  *
660
663
  * @example
661
664
  *
@@ -669,7 +672,10 @@ export function useRegisterNavigationCheckpoint(key: string, path: string): void
669
672
  *
670
673
  * @example
671
674
  *
672
- * const navigationCheckpoints = useNavigationCheckpoints(checkpointKey1, checkpointKey2);
675
+ * const navigationCheckpoints = useNavigationCheckpoints(
676
+ * checkpointKey1,
677
+ * checkpointKey2
678
+ * );
673
679
  *
674
680
  * return (
675
681
  * <>
@@ -681,6 +687,67 @@ export function useRegisterNavigationCheckpoint(key: string, path: string): void
681
687
  export function useNavigationCheckpoints(...keys: string[]): {
682
688
  [key: string]: string;
683
689
  };
690
+ /**
691
+ *
692
+ * usePersistedQuery is an wrapper function around useQuery hook from
693
+ *
694
+ * react-query. In addition to all the functionalities offered useQuery, this
695
+ *
696
+ * hook also stores the received response in localStorage. For subsequent page
697
+ *
698
+ * loads, the hook will be serving data from localStorage until the API response
699
+ *
700
+ * is received.
701
+ *
702
+ * usePersistedQuery will use the staleTime config from options parameter (if
703
+ *
704
+ * present) to determine the expiry of the localStorage cache. The hook will not
705
+ *
706
+ * return data from localStorage if it is expired. Instead it will wait for the
707
+ *
708
+ * API response to become available.
709
+ *
710
+ * You can use isFreshLoading property from the return value of the hook to know
711
+ *
712
+ * whether the hook is waiting for the API. data won't be available (will be
713
+ *
714
+ * undefined) until isFreshLoading turns to false.
715
+ *
716
+ * @example
717
+ *
718
+ * const useFetchUsers = options =>
719
+ * usePersistedQuery(QUERY_KEYS.FETCH_USERS, usersApi.fetch, options);
720
+ *
721
+ * // Now we can use useFetchUsers as:
722
+ * const { data, isLoading, isFreshLoading } = useFetchUsers();
723
+ * @endexample
724
+ */
725
+ export function usePersistedQuery<T>(queryKey: string | unknown[], fetch: () => Promise<T>, options?: UseQueryOptions): UseQueryResult<T> & {
726
+ isFreshLoading: boolean;
727
+ };
728
+ /**
729
+ *
730
+ * This hook fetches the list of neetoApps and isOwner flag from
731
+ *
732
+ * neeto_apps_controller.
733
+ *
734
+ * This hook uses usePersistedQuery under the hood. So data will be immediately
735
+ *
736
+ * available except for the first page load.
737
+ *
738
+ * @example
739
+ *
740
+ * const { neetoApps, isOwner } = useFetchNeetoApps();
741
+ * @endexample
742
+ */
743
+ export function useFetchNeetoApps(options?: UseQueryOptions): ReturnType<typeof usePersistedQuery<{
744
+ neetoApps: {
745
+ description: string;
746
+ name: string;
747
+ url: string;
748
+ }[];
749
+ isOwner: boolean;
750
+ }>>;
684
751
  /**
685
752
  *
686
753
  * An HOC which provides the t function from react-i18next to the wrapped
package/react-utils.js CHANGED
@@ -7,6 +7,7 @@ import { useTranslation, Trans, withTranslation } from 'react-i18next';
7
7
  import ErrorPage from '@bigbinary/neeto-molecules/ErrorPage';
8
8
  import { Route, Redirect } from 'react-router-dom';
9
9
  import axios from 'axios';
10
+ import { useQuery } from 'react-query';
10
11
  import { Helmet } from 'react-helmet';
11
12
 
12
13
  var _path, _path2, _path3, _path4, _path5, _path6;
@@ -185,6 +186,112 @@ var PrivateRoute = function PrivateRoute(_ref) {
185
186
  });
186
187
  };
187
188
 
189
+ function _typeof$1(obj) {
190
+ "@babel/helpers - typeof";
191
+
192
+ return _typeof$1 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) {
193
+ return typeof obj;
194
+ } : function (obj) {
195
+ return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
196
+ }, _typeof$1(obj);
197
+ }
198
+
199
+ function _toPrimitive(input, hint) {
200
+ if (_typeof$1(input) !== "object" || input === null) return input;
201
+ var prim = input[Symbol.toPrimitive];
202
+ if (prim !== undefined) {
203
+ var res = prim.call(input, hint || "default");
204
+ if (_typeof$1(res) !== "object") return res;
205
+ throw new TypeError("@@toPrimitive must return a primitive value.");
206
+ }
207
+ return (hint === "string" ? String : Number)(input);
208
+ }
209
+
210
+ function _toPropertyKey(arg) {
211
+ var key = _toPrimitive(arg, "string");
212
+ return _typeof$1(key) === "symbol" ? key : String(key);
213
+ }
214
+
215
+ function _defineProperty(obj, key, value) {
216
+ key = _toPropertyKey(key);
217
+ if (key in obj) {
218
+ Object.defineProperty(obj, key, {
219
+ value: value,
220
+ enumerable: true,
221
+ configurable: true,
222
+ writable: true
223
+ });
224
+ } else {
225
+ obj[key] = value;
226
+ }
227
+ return obj;
228
+ }
229
+
230
+ var fetch = function fetch() {
231
+ return axios.get("/api/v1/neeto_apps");
232
+ };
233
+ var neetoAppsApi = {
234
+ fetch: fetch
235
+ };
236
+
237
+ var QUERY_KEYS = {
238
+ NEETO_APPS_LIST: "neeto-apps-list"
239
+ };
240
+
241
+ var QUERY_CACHE_NAME_SPACE = "queryCache";
242
+ var NEETO_APPS_LIST_STALE_TIME = 30 * 24 * 60 * 60 * 1000; // 30 days
243
+
244
+ function ownKeys$1(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
245
+ function _objectSpread$1(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$1(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
246
+ var localStorageQueryCache = {
247
+ set: function set(key, data) {
248
+ var cache = localStorageQueryCache.getAll();
249
+ var newCache = _objectSpread$1(_objectSpread$1({}, cache), {}, _defineProperty({}, key, {
250
+ data: data,
251
+ modifiedAt: Date.now()
252
+ }));
253
+ localStorage.setItem(QUERY_CACHE_NAME_SPACE, JSON.stringify(newCache));
254
+ },
255
+ getAll: function getAll() {
256
+ var cache = localStorage.getItem(QUERY_CACHE_NAME_SPACE);
257
+ if (!cache) return {};
258
+ return JSON.parse(cache);
259
+ },
260
+ get: function get(key) {
261
+ return localStorageQueryCache.getAll()[key];
262
+ }
263
+ };
264
+ var isOutdated = function isOutdated(localCache, staleTime) {
265
+ if (isNil(localCache)) return true;
266
+ if (isNil(staleTime)) return false;
267
+ return localCache.modifiedAt <= Date.now() - staleTime;
268
+ };
269
+ var usePersistedQuery = function usePersistedQuery(queryKey, fetch, options) {
270
+ var queryResult = useQuery(queryKey, fetch, options);
271
+ var localCache = localStorageQueryCache.get(queryKey);
272
+ useEffect(function () {
273
+ if (!queryResult.isSuccess) return;
274
+ localStorageQueryCache.set(queryKey, queryResult.data);
275
+ }, [queryKey, queryResult.data, queryResult.isSuccess]);
276
+ if (isOutdated(localCache, options === null || options === void 0 ? void 0 : options.staleTime)) {
277
+ return _objectSpread$1(_objectSpread$1({}, queryResult), {}, {
278
+ isFreshLoading: queryResult.isLoading
279
+ });
280
+ }
281
+ return _objectSpread$1(_objectSpread$1({}, queryResult), {}, {
282
+ data: queryResult.data || localCache.data,
283
+ isFreshLoading: false
284
+ });
285
+ };
286
+
287
+ function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
288
+ function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
289
+ var useFetchNeetoApps = function useFetchNeetoApps(options) {
290
+ return usePersistedQuery(QUERY_KEYS.NEETO_APPS_LIST, neetoAppsApi.fetch, _objectSpread({
291
+ staleTime: NEETO_APPS_LIST_STALE_TIME
292
+ }, options));
293
+ };
294
+
188
295
  function _arrayWithHoles(arr) {
189
296
  if (Array.isArray(arr)) return arr;
190
297
  }
@@ -3454,47 +3561,6 @@ var usePrevious = function usePrevious(value) {
3454
3561
  return ref.current;
3455
3562
  };
3456
3563
 
3457
- function _typeof$1(obj) {
3458
- "@babel/helpers - typeof";
3459
-
3460
- return _typeof$1 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) {
3461
- return typeof obj;
3462
- } : function (obj) {
3463
- return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
3464
- }, _typeof$1(obj);
3465
- }
3466
-
3467
- function _toPrimitive(input, hint) {
3468
- if (_typeof$1(input) !== "object" || input === null) return input;
3469
- var prim = input[Symbol.toPrimitive];
3470
- if (prim !== undefined) {
3471
- var res = prim.call(input, hint || "default");
3472
- if (_typeof$1(res) !== "object") return res;
3473
- throw new TypeError("@@toPrimitive must return a primitive value.");
3474
- }
3475
- return (hint === "string" ? String : Number)(input);
3476
- }
3477
-
3478
- function _toPropertyKey(arg) {
3479
- var key = _toPrimitive(arg, "string");
3480
- return _typeof$1(key) === "symbol" ? key : String(key);
3481
- }
3482
-
3483
- function _defineProperty(obj, key, value) {
3484
- key = _toPropertyKey(key);
3485
- if (key in obj) {
3486
- Object.defineProperty(obj, key, {
3487
- value: value,
3488
- enumerable: true,
3489
- configurable: true,
3490
- writable: true
3491
- });
3492
- } else {
3493
- obj[key] = value;
3494
- }
3495
- return obj;
3496
- }
3497
-
3498
3564
  function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
3499
3565
  try {
3500
3566
  var info = gen[key](arg);
@@ -4717,5 +4783,5 @@ var useUpdateEffect = function useUpdateEffect(callback) {
4717
4783
  }, dependencies);
4718
4784
  };
4719
4785
 
4720
- export { HoneybadgerErrorBoundary, PrivateRoute, destroyBrowserSubscription, handleMetaClick, isMetaKeyPressed, registerBrowserNotifications, useDebounce, useDisplayErrorPage, useErrorDisplayStore, useFuncDebounce, useHotKeys, useIsElementVisibleInDom, useKeyboardShortcutsPaneState, useLocalStorage, useNavigationCheckpoints, useOnClickOutside, usePrevious, useRegisterNavigationCheckpoint, useStateWithDependency, useTimer, useUpdateEffect, withImmutableActions, withT, withTitle };
4786
+ export { HoneybadgerErrorBoundary, PrivateRoute, destroyBrowserSubscription, handleMetaClick, isMetaKeyPressed, registerBrowserNotifications, useDebounce, useDisplayErrorPage, useErrorDisplayStore, useFetchNeetoApps, useFuncDebounce, useHotKeys, useIsElementVisibleInDom, useKeyboardShortcutsPaneState, useLocalStorage, useNavigationCheckpoints, useOnClickOutside, usePersistedQuery, usePrevious, useRegisterNavigationCheckpoint, useStateWithDependency, useTimer, useUpdateEffect, withImmutableActions, withT, withTitle };
4721
4787
  //# sourceMappingURL=react-utils.js.map