forked from cssinjs/jss
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtoCss.js
More file actions
69 lines (60 loc) · 1.76 KB
/
toCss.js
File metadata and controls
69 lines (60 loc) · 1.76 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
/* @flow */
import toCssValue from './toCssValue'
import type {ToCssOptions as Options, JssStyle} from '../types'
/**
* Indent a string.
* http://jsperf.com/array-join-vs-for
*/
function indentStr(str: string, indent: number): string {
let result = ''
for (let index = 0; index < indent; index++) result += ' '
return result + str
}
/**
* Converts a Rule to CSS string.
*/
export default function toCss(selector: string, style: JssStyle, options: Options = {}): string {
let {indent = 0} = options
const {fallbacks} = style
let result = ''
indent++
// Apply fallbacks first.
if (fallbacks) {
// Array syntax {fallbacks: [{prop: value}]}
if (Array.isArray(fallbacks)) {
for (let index = 0; index < fallbacks.length; index++) {
const fallback = fallbacks[index]
for (const prop in fallback) {
const value = fallback[prop]
if (value != null) {
result += `\n${indentStr(`${prop}: ${toCssValue(value)};`, indent)}`
}
}
}
}
// Object syntax {fallbacks: {prop: value}}
else {
for (const prop in fallbacks) {
const value = fallbacks[prop]
if (value != null) {
result += `\n${indentStr(`${prop}: ${toCssValue(value)};`, indent)}`
}
}
}
}
let hasFunctionValue = false
for (const prop in style) {
let value = style[prop]
if (typeof value === 'function') {
value = style[`$${prop}`]
hasFunctionValue = true
}
if (value != null && prop !== 'fallbacks') {
result += `\n${indentStr(`${prop}: ${toCssValue(value)};`, indent)}`
}
}
if (!result && !hasFunctionValue) return result
indent--
result = indentStr(`${selector} {${result}\n`, indent) + indentStr('}', indent)
return result
}