UNPKG

2.37 kBJavaScriptView Raw
1/*
2 * Copyright 2020 Palantir Technologies, Inc. All rights reserved.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16export function isRefObject(value) {
17 return value != null && typeof value !== "function";
18}
19export function isRefCallback(value) {
20 return typeof value === "function";
21}
22/**
23 * Assign the given ref to a target, either a React ref object or a callback which takes the ref as its first argument.
24 */
25export function setRef(refTarget, ref) {
26 if (isRefObject(refTarget)) {
27 // HACKHACK: .current property is readonly
28 refTarget.current = ref;
29 }
30 else if (isRefCallback(refTarget)) {
31 refTarget(ref);
32 }
33}
34/** @deprecated use mergeRefs() instead */
35export function combineRefs(ref1, ref2) {
36 return mergeRefs(ref1, ref2);
37}
38/**
39 * Utility for merging refs into one singular callback ref.
40 * If using in a functional component, would recomend using `useMemo` to preserve function identity.
41 */
42export function mergeRefs() {
43 var refs = [];
44 for (var _i = 0; _i < arguments.length; _i++) {
45 refs[_i] = arguments[_i];
46 }
47 return function (value) {
48 refs.forEach(function (ref) {
49 setRef(ref, value);
50 });
51 };
52}
53export function getRef(ref) {
54 var _a;
55 if (ref === null) {
56 return null;
57 }
58 return (_a = ref.current) !== null && _a !== void 0 ? _a : ref;
59}
60/**
61 * Creates a ref handler which assigns the ref returned by React for a mounted component to a field on the target object.
62 * The target object is usually a component class.
63 *
64 * If provided, it will also update the given `refProp` with the value of the ref.
65 */
66export function refHandler(refTargetParent, refTargetKey, refProp) {
67 return function (ref) {
68 refTargetParent[refTargetKey] = ref;
69 setRef(refProp, ref);
70 };
71}
72//# sourceMappingURL=refs.js.map
\No newline at end of file