-
-
Notifications
You must be signed in to change notification settings - Fork 129
/
attributes-to-props.js
83 lines (73 loc) · 2.25 KB
/
attributes-to-props.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
var DOMProperty = require('react-dom-core/lib/DOMProperty');
var propertyConfig = require('./property-config');
var styleToObject = require('style-to-object');
var utilities = require('./utilities');
var config = propertyConfig.config;
var isCustomAttribute = propertyConfig.HTMLDOMPropertyConfig.isCustomAttribute;
DOMProperty.injection.injectDOMPropertyConfig(
propertyConfig.HTMLDOMPropertyConfig
);
/**
* Makes attributes compatible with React props.
*
* @param {Object} attributes - The attributes.
* @return {Object} - The props.
*/
function attributesToProps(attributes) {
attributes = attributes || {};
var props = {};
var propertyName;
var propertyValue;
var reactProperty;
for (propertyName in attributes) {
propertyValue = attributes[propertyName];
// custom attributes (`data-` and `aria-`)
if (isCustomAttribute(propertyName)) {
props[propertyName] = propertyValue;
continue;
}
// make HTML DOM attribute/property consistent with React attribute/property
reactProperty = config.html[propertyName.toLowerCase()];
if (reactProperty) {
if (
DOMProperty.properties.hasOwnProperty(reactProperty) &&
DOMProperty.properties[reactProperty].hasBooleanValue
) {
props[reactProperty] = true;
} else {
props[reactProperty] = propertyValue;
}
continue;
}
// make SVG DOM attribute/property consistent with React attribute/property
reactProperty = config.svg[propertyName];
if (reactProperty) {
props[reactProperty] = propertyValue;
}
}
// convert inline style to object
if (attributes.style != null) {
props.style = cssToJs(attributes.style);
}
return props;
}
/**
* Converts CSS style string to JS style object.
*
* @param {String} style - The CSS style.
* @return {Object} - The JS style object.
*/
function cssToJs(style) {
if (typeof style !== 'string') {
throw new TypeError('First argument must be a string.');
}
var styleObj = {};
styleToObject(style, function(propName, propValue) {
// Check if it's not a comment node
if (propName && propValue) {
styleObj[utilities.camelCase(propName)] = propValue;
}
});
return styleObj;
}
module.exports = attributesToProps;