-
-
Notifications
You must be signed in to change notification settings - Fork 389
Expand file tree
/
Copy pathindex.js
More file actions
92 lines (81 loc) · 2.87 KB
/
index.js
File metadata and controls
92 lines (81 loc) · 2.87 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
80
81
82
83
84
85
86
87
88
89
90
91
92
/* @flow */
import warning from 'tiny-warning'
import {
createRule,
RuleList,
type Rule,
type JssStyle,
type RuleOptions,
type UpdateOptions,
type StyleRule,
type StyleSheet
} from 'jss'
// A symbol replacement.
let now = Date.now()
const fnValuesNs = `fnValues${now}`
const fnRuleNs = `fnStyle${++now}`
type StyleRuleWithRuleFunction = StyleRule & {[key: string]: Function}
export default function functionPlugin() {
return {
onCreateRule(name?: string, decl: JssStyle, options: RuleOptions): Rule | null {
if (typeof decl !== 'function') return null
const rule: StyleRuleWithRuleFunction = (createRule(name, {}, options): any)
if (rule.type == 'global')
rule.updateFun = data => {
// compute styles
let styles = decl(data)
// Build a new RuleList that replaces the former one
rule.rules = new RuleList({
...rule.options,
parent: rule
})
for (const selector in styles) rule.rules.add(selector, styles[selector])
rule.rules.process()
}
else rule[fnRuleNs] = decl
return rule
},
onProcessStyle(style: JssStyle, rule: Rule): JssStyle {
// We need to extract function values from the declaration, so that we can keep core unaware of them.
// We need to do that only once.
// We don't need to extract functions on each style update, since this can happen only once.
// We don't support function values inside of function rules.
if (fnValuesNs in rule || fnRuleNs in rule) return style
const fnValues = {}
for (const prop in style) {
const value = style[prop]
if (typeof value !== 'function') continue
delete style[prop]
fnValues[prop] = value
}
rule[fnValuesNs] = fnValues
return style
},
onUpdate(data: Object, rule: Rule, sheet: StyleSheet, options: UpdateOptions) {
const styleRule: StyleRule = (rule: any)
const fnRule = styleRule[fnRuleNs]
// If we have a style function, the entire rule is dynamic and style object
// will be returned from that function.
if (fnRule) {
// Empty object will remove all currently defined props
// in case function rule returns a falsy value.
styleRule.style = fnRule(data) || {}
if (process.env.NODE_ENV === 'development') {
for (const prop in styleRule.style) {
if (typeof styleRule.style[prop] === 'function') {
warning(false, '[JSS] Function values inside function rules are not supported.')
break
}
}
}
}
const fnValues = styleRule[fnValuesNs]
// If we have a fn values map, it is a rule with function values.
if (fnValues) {
for (const prop in fnValues) {
styleRule.prop(prop, fnValues[prop](data), options)
}
}
}
}
}