forked from jaredly/treed
-
Notifications
You must be signed in to change notification settings - Fork 0
/
classy.js
114 lines (90 loc) · 2.55 KB
/
classy.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
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
/**
* Quickstart entry point. If you want to configure things, you're probably
* better off going custom.
*/
var extend = require('./util/extend')
var keyHandlers = require('./key-handlers')
var baseKeys = require('./stores/keys')
var KeyManager = require('./key-manager')
var MainStore = require('./stores/main')
var Db = require('./db')
class Treed {
constructor(options) {
this.options = extend({
plugins: [],
}, options || {})
this.keyManager = new KeyManager()
}
initStore(data, options) {
var options = extend({
PL: require('./pl/mem'), // TODO make it mandatory to have a PL? and remove this dep
pl: null,
actions: null,
}, options)
var pl = this.pl = options.pl || new options.PL()
var db = this.db = new Db(pl, pluginType(this.options.plugins, 'db'))
return new Promise((resolve, reject) => {
db.init(data, err => {
if (err) return reject(err)
var store = this.store = new MainStore({
actions: options.actions,
// plugins: pluginType(this.options.plugins, 'store'),
// allPlugins: this.options.plugins,
db: db
})
store.init(this.options.plugins, this.options.pluginConfig, (err) => {
if (err) return reject(err)
this.keyManager.attach(store)
resolve(store)
})
})
})
}
on (what, handler) {
this.store.on(what, handler)
}
off (what, handler) {
this.store.on(what, handler)
}
removeView(id) {
this.store.unregisterView(id)
}
addView(options) {
options = extend({
actions: null,
keys: {},
root: null,
}, options)
var storeView = this.store.registerView(options.root, options.actions)
var allKeys = extend({}, flattenKeySections(baseKeys), flattenKeySections(options.keys))
var props = {
plugins: pluginType(this.options.plugins, 'view'),
nodePlugins: pluginType(this.options.plugins, 'node'),
store: storeView,
}
var keys = keyHandlers(
allKeys,
storeView.actions,
pluginType(this.options.plugins, 'keys'),
this.options.plugins)
this.keyManager.addView(storeView.id, keys)
return props
}
}
function flattenKeySections(keys) {
var ret = {}
for (var name in keys) {
for (var sub in keys[name]) {
ret[sub] = keys[name][sub]
}
}
return ret
}
function pluginType(plugins, type) {
if (!plugins) return []
return plugins.reduce((list, plugin) => {
if (plugin[type]) list.unshift(plugin[type])
return list
}, [])
}
module.exports = Treed