-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
97 lines (89 loc) · 2.75 KB
/
index.js
File metadata and controls
97 lines (89 loc) · 2.75 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
93
94
95
96
97
import ObjectStateStorage from 'object-state-storage';
import React from 'react';
import ReactDOM from 'react-dom';
export class Controller {
constructor(context) {
this.context = context;
}
get name() {
throw new Error('Implement name getter');
}
controllerWillMount() {
throw new Error(`Implement controllerWillMount() function for ${this.name}`);
}
dispose() {
throw new Error(`Implement dispose() function for ${this.name}`);
}
}
export class Session {
constructor(mountPoint, controllers) {
if (!mountPoint) {
throw new Error('"mountPoint" property is not defined');
}
if (Object.keys(controllers).length === 0) {
throw new Error('"controllers" property cannot be empty');
}
this.mountPoint = mountPoint;
this.controllers = controllers;
this.isMounting = false;
this.context = {
store: new ObjectStateStorage({}),
mountController: this.mountController.bind(this),
};
this.subscribeRenderer();
}
subscribeRenderer() {
this.context.store.subscribe(() => {
if (this.isMounting === false) {
this.render();
}
});
}
mountController(controllerName, payload = {}) {
if (this.isMounting === true) {
// cannot set new controller while mounting new controller
return Promise.resolve();
}
this.isMounting = true;
if (this.controller) {
if (this.controller.name === controllerName) {
// if controller remains the same
this.controller.controllerWillMount(payload);
this.isMounting = false;
this.render();
return Promise.resolve(this.controller);
} else {
// otherwise dispose current controller
this.controller.dispose();
}
}
const importController = this.controllers[controllerName];
const importErrorController = this.controllers.ErrorController;
return new Promise((resolve, reject) => {
importController()
.then(({ default: Controller }) => {
this.controller = new Controller(this.context);
this.controller.controllerWillMount(payload);
this.isMounting = false;
this.render();
resolve(this.controller);
})
.catch(err => {
if (importErrorController) {
importErrorController().then(({ default: ErrorController }) => {
this.controller = new ErrorController(this.context);
this.controller.controllerWillMount({ error: err });
this.isMounting = false;
this.render();
resolve(this.controller);
});
} else {
reject(err);
}
});
});
}
render() {
ReactDOM.render(React.createElement(this.controller.view), this.mountPoint);
}
}