-
Notifications
You must be signed in to change notification settings - Fork 21
/
styleRuleConverter.js
90 lines (77 loc) · 2.29 KB
/
styleRuleConverter.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
84
85
86
87
88
89
90
var escape = require('escape-html');
var mediaQueryValidator = require('valid-media-queries');
var styleRuleValidator = require('./styleRuleValidator');
var _uppercasePattern = /([A-Z])/g;
var msPattern = /^ms-/;
function hyphenateProp(string) {
// MozTransition -> -moz-transition
// msTransition -> -ms-transition. Notice the lower case m
// http://modernizr.com/docs/#prefixed
// thanks a lot IE
return string.replace(_uppercasePattern, '-$1')
.toLowerCase()
.replace(msPattern, '-ms-');
}
function escapeValueForProp(value, prop) {
// 'content' is a special property that must be quoted
if (prop === 'content') {
return '"' + value + '"';
}
return escape(value);
}
function ruleToString(propName, value) {
var cssPropName = hyphenateProp(propName);
if (!styleRuleValidator.isValidProp(cssPropName)) {
console.warn(
'%s (transformed into %s) is not a valid CSS property name.', propName, cssPropName
);
return '';
}
if (!styleRuleValidator.isValidValue(value)) {
return '';
}
return cssPropName + ':' + escapeValueForProp(value, cssPropName) + ';';
}
function _rulesToStringHeadless(styleObj) {
var markup = '';
for (var key in styleObj) {
if (!styleObj.hasOwnProperty(key)) {
continue;
}
if (key[0] === ':' || key.substring(0, 6) === '@media') {
continue;
}
markup += ruleToString(key, styleObj[key]);
}
return markup;
}
function rulesToString(className, styleObj) {
var markup = '';
var pseudos = '';
var mediaQueries = '';
for (var key in styleObj) {
if (!styleObj.hasOwnProperty(key)) {
continue;
}
// Skipping the special pseudo-selectors and media queries.
if (key[0] === ':') {
pseudos += '.' + className + key + '{' +
_rulesToStringHeadless(styleObj[key]) + '}';
} else if (key.substring(0, 6) === '@media') {
if (!mediaQueryValidator(key)) {
console.log('%s is not a valid media query.', key);
continue;
}
mediaQueries += key + '{' + rulesToString(className, styleObj[key]) + '}';
} else {
markup += ruleToString(key, styleObj[key]);
}
}
if (markup !== '') {
markup = '.' + className + '{' + markup + '}';
}
return markup + pseudos + mediaQueries;
}
module.exports = {
rulesToString: rulesToString
};