forked from FormidableLabs/radium
-
Notifications
You must be signed in to change notification settings - Fork 2
/
style-keeper.js
52 lines (44 loc) · 1.13 KB
/
style-keeper.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
/* @flow */
export default class StyleKeeper {
_userAgent: string | typeof undefined;
_listeners: Array<() => void>;
_cssSet: {[id: string]: boolean};
constructor(userAgent?: string) {
this._userAgent = userAgent;
this._listeners = [];
this._cssSet = {};
}
subscribe(listener: () => void): {remove: () => void} {
if (this._listeners.indexOf(listener) === -1) {
this._listeners.push(listener);
}
return {
// Must be fat arrow to capture `this`
remove: () => {
const listenerIndex = this._listeners.indexOf(listener);
if (listenerIndex > -1) {
this._listeners.splice(listenerIndex, 1);
}
},
};
}
addCSS(css: string): {remove: () => void} {
if (!this._cssSet[css]) {
this._cssSet[css] = true;
this._emitChange();
}
return {
// Must be fat arrow to capture `this`
remove: () => {
delete this._cssSet[css];
this._emitChange();
},
};
}
getCSS(): string {
return Object.keys(this._cssSet).join('\n');
}
_emitChange() {
this._listeners.forEach((listener) => listener());
}
}