/
app.manager.ts
76 lines (63 loc) · 2.22 KB
/
app.manager.ts
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
import EventEmitter from "events";
import { appManagerInitialOptions, AppManagerOptionsType, getAppManagerEvents, hasDocument } from "managers";
/**
* App manager handles main application states - focus and online. Those two values can answer questions:
* - Is the tab or current view instance focused and visible for user?
* - Is our application online or offline?
* With the app manager it is not a problem to get the valid answer for this question.
*
* @caution
* Make sure to apply valid focus/online handlers for different environments like for example for native mobile applications.
*/
export class AppManager {
emitter = new EventEmitter();
events = getAppManagerEvents(this.emitter);
isNodeJs: boolean;
isOnline: boolean;
isFocused: boolean;
constructor(public options?: AppManagerOptionsType) {
const {
focusEvent = appManagerInitialOptions.focusEvent,
onlineEvent = appManagerInitialOptions.onlineEvent,
initiallyFocused = appManagerInitialOptions.initiallyFocused,
initiallyOnline = appManagerInitialOptions.initiallyOnline,
} = this.options || appManagerInitialOptions;
this.setInitialFocus(initiallyFocused);
this.setInitialOnline(initiallyOnline);
focusEvent(this.setFocused);
onlineEvent(this.setOnline);
this.isNodeJs = !hasDocument();
}
private setInitialFocus = async (initValue: Exclude<AppManagerOptionsType["initiallyFocused"], undefined>) => {
if (typeof initValue === "function") {
this.isFocused = false;
this.isFocused = await initValue();
} else {
this.isFocused = initValue;
}
};
private setInitialOnline = async (initValue: Exclude<AppManagerOptionsType["initiallyOnline"], undefined>) => {
if (typeof initValue === "function") {
this.isOnline = false;
this.isOnline = await initValue();
} else {
this.isOnline = initValue;
}
};
setFocused = (isFocused: boolean) => {
this.isFocused = isFocused;
if (isFocused) {
this.events.emitFocus();
} else {
this.events.emitBlur();
}
};
setOnline = (isOnline: boolean) => {
this.isOnline = isOnline;
if (isOnline) {
this.events.emitOnline();
} else {
this.events.emitOffline();
}
};
}