-
-
Notifications
You must be signed in to change notification settings - Fork 389
Expand file tree
/
Copy pathindex.js
More file actions
80 lines (66 loc) · 2.07 KB
/
index.js
File metadata and controls
80 lines (66 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
80
/* @flow */
import $$observable from 'symbol-observable'
import {
createRule,
type StyleRule,
type Rule,
type RuleOptions,
type JssStyle,
type UpdateOptions
} from 'jss'
import type {Observable} from './types'
const isObservable = (value: any) => value && value[$$observable] && value === value[$$observable]()
export type Options = UpdateOptions
function getObservableStyles(styles: Object): Object | null {
let to = null
for (const key in styles) {
const value = styles[key]
const type = typeof value
if (isObservable(value)) {
if (!to) to = {}
to[key] = value
} else if (type === 'object' && value !== null && !Array.isArray(value)) {
const extracted = getObservableStyles(value)
if (extracted) {
if (!to) to = {}
to[key] = extracted
}
}
}
return to
}
export {isObservable, getObservableStyles}
export default function observablePlugin(updateOptions?: Options) {
return {
onCreateRule(name?: string, decl: JssStyle, options: RuleOptions): Rule | null {
if (!isObservable(decl)) return null
// Cast `decl` to `Observable`, since it passed the type guard.
const style$ = (decl: Observable<{[string]: string | number}>)
const rule = ((createRule(name, {}, options): any): StyleRule)
// TODO
// Call `stream.subscribe()` returns a subscription, which should be explicitly
// unsubscribed from when we know this sheet is no longer needed.
style$.subscribe((style: JssStyle) => {
for (const prop in style) {
rule.prop(prop, style[prop], updateOptions)
}
})
return rule
},
onProcessRule(rule: Rule) {
if (rule && rule.type !== 'style') return
const styleRule = ((rule: any): StyleRule)
const {style} = styleRule
for (const prop in style) {
const value = style[prop]
if (!isObservable(value)) continue
delete style[prop]
value.subscribe({
next: nextValue => {
styleRule.prop(prop, nextValue, updateOptions)
}
})
}
}
}
}