-
-
Notifications
You must be signed in to change notification settings - Fork 389
Expand file tree
/
Copy pathindex.js
More file actions
79 lines (65 loc) · 2.07 KB
/
index.js
File metadata and controls
79 lines (65 loc) · 2.07 KB
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
// @flow
import type {Plugin} from 'jss'
import defaultUnits, {px} from './defaultUnits'
export type Options = {[key: string]: string | ((val: number) => string)}
/**
* Clones the object and adds a camel cased property version.
*/
function addCamelCasedVersion(obj) {
const regExp = /(-[a-z])/g
const replace = str => str[1].toUpperCase()
const newObj = {}
for (const key in obj) {
newObj[key] = obj[key]
newObj[key.replace(regExp, replace)] = obj[key]
}
return newObj
}
const units = addCamelCasedVersion(defaultUnits)
/**
* Recursive deep style passing function
*/
function iterate(prop: string, value: any, options: Options) {
if (value == null) return value
if (Array.isArray(value)) {
for (let i = 0; i < value.length; i++) {
value[i] = iterate(prop, value[i], options)
}
} else if (typeof value === 'object') {
if (prop === 'fallbacks') {
for (const innerProp in value) {
value[innerProp] = iterate(innerProp, value[innerProp], options)
}
} else {
for (const innerProp in value) {
value[innerProp] = iterate(`${prop}-${innerProp}`, value[innerProp], options)
}
}
// eslint-disable-next-line no-restricted-globals
} else if (typeof value === 'number' && isNaN(value) === false) {
const unit = options[prop] || units[prop]
// Add the unit if available, except for the special case of 0px.
if (unit && !(value === 0 && unit === px)) {
return typeof unit === 'function' ? unit(value).toString() : `${value}${unit}`
}
return value.toString()
}
return value
}
/**
* Add unit to numeric values.
*/
export default function defaultUnit(options: Options = {}): Plugin {
const camelCasedOptions = addCamelCasedVersion(options)
function onProcessStyle(style, rule) {
if (rule.type !== 'style') return style
for (const prop in style) {
style[prop] = iterate(prop, style[prop], camelCasedOptions)
}
return style
}
function onChangeValue(value, prop) {
return iterate(prop, value, camelCasedOptions)
}
return {onProcessStyle, onChangeValue}
}