-
Notifications
You must be signed in to change notification settings - Fork 0
/
model-collection.js
97 lines (81 loc) · 1.92 KB
/
model-collection.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
const ModelGroup = require('./model-group')
const nunjucks = require('nunjucks')
const split = expr => expr.match(/[a-zA-Z0-9]+|[^a-zA-Z0-9]+/g)
const escapeHtml = require('escape-html')
class ModelCollection {
/**
* @param {Model[]} models
*/
constructor (models = []) {
this.models = []
this.groups = {}
this.modelMap = {}
models.forEach(model => {
this.add(model)
})
}
/**
* Sorts the models.
*/
sort () {
this.models.sort((x, y) => x.compare(y))
Object.keys(this.groups).forEach(key => {
this.groups[key].models.sort((x, y) => x.compare(y))
})
}
getGroups () {
return Object.keys(this.groups).map(label => this.groups[label])
}
/**
* @param {Model}
* @return {Model[]}
*/
getOwners (child) {
return this.models.filter(parent => parent.has(child))
}
/**
* @param {string} name The name of the model
*/
getByName (name) {
return this.modelMap[name]
}
createGroupOfLabel (label, color) {
this.groups[label] = new ModelGroup({ label, color })
}
/**
* @param {Model} model
*/
add (model) {
this.models.push(model)
this.modelMap[model.name] = model
if (model.aliases) {
model.aliases.forEach(alias => {
this.modelMap[alias] = model
})
}
if (!this.groups[model.groupLabel]) {
this.createGroupOfLabel(model.groupLabel, model.groupColor)
}
this.groups[model.groupLabel].add(model)
}
/**
* @param {string} text
* @param {string} basepath
* @param {string} tmpl nunjucks template
*/
linkType (text, basepath, tmpl) {
return split(text)
.map(expr => {
const model = this.getByName(expr)
if (!model) {
return escapeHtml(expr)
}
return nunjucks.renderString(tmpl, {
href: model.getHref(basepath),
type: expr
})
})
.join('')
}
}
module.exports = ModelCollection