Blame view

天文台pc/tianwentai-ui/node_modules/use-callback-ref/dist/es5/refToCallback.js 1.41 KB
bc518174   王天杨   提交两个项目文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
  "use strict";
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.useRefToCallback = exports.refToCallback = void 0;
  /**
   * Unmemoized version of {@link useRefToCallback}
   * @see {@link useRefToCallback}
   * @param ref
   */
  function refToCallback(ref) {
      return function (newValue) {
          if (typeof ref === 'function') {
              ref(newValue);
          }
          else if (ref) {
              ref.current = newValue;
          }
      };
  }
  exports.refToCallback = refToCallback;
  var nullCallback = function () { return null; };
  // lets maintain a weak ref to, well, ref :)
  // not using `kashe` to keep this package small
  var weakMem = new WeakMap();
  var weakMemoize = function (ref) {
      var usedRef = ref || nullCallback;
      var storedRef = weakMem.get(usedRef);
      if (storedRef) {
          return storedRef;
      }
      var cb = refToCallback(usedRef);
      weakMem.set(usedRef, cb);
      return cb;
  };
  /**
   * Transforms a given `ref` into `callback`.
   *
   * To transform `callback` into ref use {@link useCallbackRef|useCallbackRef(undefined, callback)}
   *
   * @param {ReactRef} ref
   * @returns {Function}
   *
   * @see https://github.com/theKashey/use-callback-ref#reftocallback
   *
   * @example
   * const ref = useRef(0);
   * const setRef = useRefToCallback(ref);
   * 👉 setRef(10);
   *  ref.current === 10
   */
  function useRefToCallback(ref) {
      return weakMemoize(ref);
  }
  exports.useRefToCallback = useRefToCallback;