UNPKG

2.96 kBPlain TextView Raw
1/*
2 * Copyright 2020 Adobe. All rights reserved.
3 * This file is licensed to you under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License. You may obtain a copy
5 * of the License at http://www.apache.org/licenses/LICENSE-2.0
6 *
7 * Unless required by applicable law or agreed to in writing, software distributed under
8 * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
9 * OF ANY KIND, either express or implied. See the License for the specific language
10 * governing permissions and limitations under the License.
11 */
12
13import {chain} from './chain';
14import clsx from 'clsx';
15import {mergeIds} from './useId';
16
17interface Props {
18 [key: string]: any
19}
20
21type PropsArg = Props | null | undefined;
22
23// taken from: https://stackoverflow.com/questions/51603250/typescript-3-parameter-list-intersection-type/51604379#51604379
24type TupleTypes<T> = { [P in keyof T]: T[P] } extends { [key: number]: infer V } ? NullToObject<V> : never;
25type NullToObject<T> = T extends (null | undefined) ? {} : T;
26// eslint-disable-next-line no-undef, @typescript-eslint/no-unused-vars
27type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;
28
29/**
30 * Merges multiple props objects together. Event handlers are chained,
31 * classNames are combined, and ids are deduplicated - different ids
32 * will trigger a side-effect and re-render components hooked up with `useId`.
33 * For all other props, the last prop object overrides all previous ones.
34 * @param args - Multiple sets of props to merge together.
35 */
36export function mergeProps<T extends PropsArg[]>(...args: T): UnionToIntersection<TupleTypes<T>> {
37 // Start with a base clone of the first argument. This is a lot faster than starting
38 // with an empty object and adding properties as we go.
39 let result: Props = {...args[0]};
40 for (let i = 1; i < args.length; i++) {
41 let props = args[i];
42 for (let key in props) {
43 let a = result[key];
44 let b = props[key];
45
46 // Chain events
47 if (
48 typeof a === 'function' &&
49 typeof b === 'function' &&
50 // This is a lot faster than a regex.
51 key[0] === 'o' &&
52 key[1] === 'n' &&
53 key.charCodeAt(2) >= /* 'A' */ 65 &&
54 key.charCodeAt(2) <= /* 'Z' */ 90
55 ) {
56 result[key] = chain(a, b);
57
58 // Merge classnames, sometimes classNames are empty string which eval to false, so we just need to do a type check
59 } else if (
60 (key === 'className' || key === 'UNSAFE_className') &&
61 typeof a === 'string' &&
62 typeof b === 'string'
63 ) {
64 result[key] = clsx(a, b);
65 } else if (key === 'id' && a && b) {
66 result.id = mergeIds(a, b);
67 // Override others
68 } else {
69 result[key] = b !== undefined ? b : a;
70 }
71 }
72 }
73
74 return result as UnionToIntersection<TupleTypes<T>>;
75}
76
\No newline at end of file