UNPKG

2.19 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, LinkDOMProps} 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
26// See LinkDOMProps in dom.d.ts.
27const linkPropNames = new Set([
28 'href',
29 'hrefLang',
30 'target',
31 'rel',
32 'download',
33 'ping',
34 'referrerPolicy'
35]);
36
37interface Options {
38 /**
39 * If labelling associated aria properties should be included in the filter.
40 */
41 labelable?: boolean,
42 /** Whether the element is a link and should include DOM props for <a> elements. */
43 isLink?: boolean,
44 /**
45 * A Set of other property names that should be included in the filter.
46 */
47 propNames?: Set<string>
48}
49
50const propRe = /^(data-.*)$/;
51
52/**
53 * Filters out all props that aren't valid DOM props or defined via override prop obj.
54 * @param props - The component props to be filtered.
55 * @param opts - Props to override.
56 */
57export function filterDOMProps(props: DOMProps & AriaLabelingProps & LinkDOMProps, opts: Options = {}): DOMProps & AriaLabelingProps {
58 let {labelable, isLink, propNames} = opts;
59 let filteredProps = {};
60
61 for (const prop in props) {
62 if (
63 Object.prototype.hasOwnProperty.call(props, prop) && (
64 DOMPropNames.has(prop) ||
65 (labelable && labelablePropNames.has(prop)) ||
66 (isLink && linkPropNames.has(prop)) ||
67 propNames?.has(prop) ||
68 propRe.test(prop)
69 )
70 ) {
71 filteredProps[prop] = props[prop];
72 }
73 }
74
75 return filteredProps;
76}