UNPKG

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