UNPKG

2.25 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/**
35 * Utility for merging refs into one singular callback ref.
36 * If using in a functional component, would recomend using `useMemo` to preserve function identity.
37 */
38export function mergeRefs() {
39 var refs = [];
40 for (var _i = 0; _i < arguments.length; _i++) {
41 refs[_i] = arguments[_i];
42 }
43 return function (value) {
44 refs.forEach(function (ref) {
45 setRef(ref, value);
46 });
47 };
48}
49export function getRef(ref) {
50 var _a;
51 if (ref === null) {
52 return null;
53 }
54 return (_a = ref.current) !== null && _a !== void 0 ? _a : ref;
55}
56/**
57 * Creates a ref handler which assigns the ref returned by React for a mounted component to a field on the target object.
58 * The target object is usually a component class.
59 *
60 * If provided, it will also update the given `refProp` with the value of the ref.
61 */
62export function refHandler(refTargetParent, refTargetKey, refProp) {
63 return function (ref) {
64 refTargetParent[refTargetKey] = ref;
65 setRef(refProp, ref);
66 };
67}
68//# sourceMappingURL=refs.js.map
\No newline at end of file