UNPKG

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