-
Notifications
You must be signed in to change notification settings - Fork 0
/
component.js
89 lines (70 loc) · 1.92 KB
/
component.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
'use strict';
import Schema from 'schema-js';
import dashify from 'dashify';
import {getPrototypeChain} from './util';
const Component = function (properties) {
const uid = [
dashify(this.constructor.name),
Date.now().toString(16).slice(-4),
Math.random().toString(16).substr(2, 4)
].join('-');
Object.assign(this, {
dependencies: [],
uid,
properties: {
id: uid,
...properties
}
});
};
Component.prototype.getResources = function () {
return {};
};
Component.prototype.getSchema = function () {
return new Schema({
id: {
type: String,
required: true
}
});
};
Component.prototype.getMergedSchema = function () {
const prototypes = getPrototypeChain(this);
return prototypes
.map(prototype => this::prototype.getSchema())
.reverse()
.reduce((current, next) => current.extend(next));
};
Component.prototype.validateProperties = function () {
const schema = this.getMergedSchema();
schema.validate(this.properties);
};
Component.prototype.getDependencies = function () {
return this.dependencies;
};
Component.prototype.flattenTree = function (visited = new Set()) {
const {uid} = this;
if (visited.has(uid)) {
return [];
}
visited.add(uid);
this.validateProperties();
const components = this.getDependencies()
.filter(component => component instanceof Component)
.map(component => component.flattenTree(visited))
.reduce((current, next) => [...current, ...next], []);
return [this, ...components];
};
Component.prototype.compose = function () {
const components = this.flattenTree();
const resources = components
.map(component => component.getResources())
.reduce((current, next) => Object.assign(current, next), {});
return resources;
};
Component.resolve = function (component) {
return component instanceof Component ?
{get_resource: component.properties.id} :
component
};
export default Component;