UNPKG

2.6 kBJavaScriptView Raw
1var React = require('react');
2var styleToJS = require('style-to-js').default;
3
4/**
5 * Swap key with value in an object.
6 *
7 * @param {Object} obj - The object.
8 * @param {Function} [override] - The override method.
9 * @return {Object} - The inverted object.
10 */
11function invertObject(obj, override) {
12 if (!obj || typeof obj !== 'object') {
13 throw new TypeError('First argument must be an object');
14 }
15
16 var key;
17 var value;
18 var isOverridePresent = typeof override === 'function';
19 var overrides = {};
20 var result = {};
21
22 for (key in obj) {
23 value = obj[key];
24
25 if (isOverridePresent) {
26 overrides = override(key, value);
27 if (overrides && overrides.length === 2) {
28 result[overrides[0]] = overrides[1];
29 continue;
30 }
31 }
32
33 if (typeof value === 'string') {
34 result[value] = key;
35 }
36 }
37
38 return result;
39}
40
41/**
42 * Check if a given tag is a custom component.
43 *
44 * @see {@link https://github.com/facebook/react/blob/v16.6.3/packages/react-dom/src/shared/isCustomComponent.js}
45 *
46 * @param {string} tagName - The name of the html tag.
47 * @param {Object} props - The props being passed to the element.
48 * @return {boolean}
49 */
50function isCustomComponent(tagName, props) {
51 if (tagName.indexOf('-') === -1) {
52 return props && typeof props.is === 'string';
53 }
54
55 switch (tagName) {
56 // These are reserved SVG and MathML elements.
57 // We don't mind this whitelist too much because we expect it to never grow.
58 // The alternative is to track the namespace in a few places which is convoluted.
59 // https://w3c.github.io/webcomponents/spec/custom/#custom-elements-core-concepts
60 case 'annotation-xml':
61 case 'color-profile':
62 case 'font-face':
63 case 'font-face-src':
64 case 'font-face-uri':
65 case 'font-face-format':
66 case 'font-face-name':
67 case 'missing-glyph':
68 return false;
69 default:
70 return true;
71 }
72}
73
74var styleToJSOptions = { reactCompat: true };
75
76/**
77 * Sets style prop.
78 *
79 * @param {null|undefined|string} style
80 * @param {object} props
81 */
82function setStyleProp(style, props) {
83 if (style === null || style === undefined) {
84 return;
85 }
86 props.style = styleToJS(style, styleToJSOptions);
87}
88
89/**
90 * @constant {boolean}
91 * @see {@link https://reactjs.org/blog/2017/09/08/dom-attributes-in-react-16.html}
92 */
93var PRESERVE_CUSTOM_ATTRIBUTES = React.version.split('.')[0] >= 16;
94
95module.exports = {
96 PRESERVE_CUSTOM_ATTRIBUTES: PRESERVE_CUSTOM_ATTRIBUTES,
97 invertObject: invertObject,
98 isCustomComponent: isCustomComponent,
99 setStyleProp: setStyleProp
100};