UNPKG

1.84 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 {AriaLabelingProps, DOMProps} from '@react-types/shared';
14
15const DOMPropNames = new Set([
16 'id'
17]);
18
19const labelablePropNames = new Set([
20 'aria-label',
21 'aria-labelledby',
22 'aria-describedby',
23 'aria-details'
24]);
25
26interface Options {
27 /**
28 * If labelling associated aria properties should be included in the filter.
29 */
30 labelable?: boolean,
31 /**
32 * A Set of other property names that should be included in the filter.
33 */
34 propNames?: Set<string>
35}
36
37const propRe = /^(data-.*)$/;
38
39/**
40 * Filters out all props that aren't valid DOM props or defined via override prop obj.
41 * @param props - The component props to be filtered.
42 * @param opts - Props to override.
43 */
44export function filterDOMProps(props: DOMProps & AriaLabelingProps, opts: Options = {}): DOMProps & AriaLabelingProps {
45 let {labelable, propNames} = opts;
46 let filteredProps = {};
47
48 for (const prop in props) {
49 if (
50 Object.prototype.hasOwnProperty.call(props, prop) && (
51 DOMPropNames.has(prop) ||
52 (labelable && labelablePropNames.has(prop)) ||
53 propNames?.has(prop) ||
54 propRe.test(prop)
55 )
56 ) {
57 filteredProps[prop] = props[prop];
58 }
59 }
60
61 return filteredProps;
62}