/
custom-element-widget.js
280 lines (260 loc) · 9.46 KB
/
custom-element-widget.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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
'use strict';
let Rx = require('rx');
const ALL_PROPS = '*';
const PROPS_DRIVER_NAME = 'props';
const EVENTS_SINK_NAME = 'events';
function makeDispatchFunction(element, eventName) {
return function dispatchCustomEvent(evData) {
//console.log('%cdispatchCustomEvent ' + eventName,
// 'background-color: #CCCCFF; color: black');
let event;
try {
event = new Event(eventName);
} catch (err) {
event = document.createEvent('Event');
event.initEvent(eventName, true, true);
}
event.detail = evData;
element.dispatchEvent(event);
};
}
function subscribeDispatchers(element) {
let {customEvents} = element.cycleCustomElementMetadata;
let disposables = new Rx.CompositeDisposable();
for (let name in customEvents) { if (customEvents.hasOwnProperty(name)) {
if (typeof customEvents[name].subscribe === 'function') {
let disposable = customEvents[name].subscribe(
makeDispatchFunction(element, name)
);
disposables.add(disposable);
}
}}
return disposables;
}
function subscribeDispatchersWhenRootChanges(metadata) {
return metadata.rootElem$
.distinctUntilChanged(Rx.helpers.identity,
(x, y) => (x && y && x.isEqualNode && x.isEqualNode(y))
)
.subscribe(function resubscribeDispatchers(rootElem) {
if (metadata.eventDispatchingSubscription) {
metadata.eventDispatchingSubscription.dispose();
}
metadata.eventDispatchingSubscription = subscribeDispatchers(rootElem);
});
}
function subscribeEventDispatchingSink(element, widget) {
element.cycleCustomElementMetadata.eventDispatchingSubscription =
subscribeDispatchers(element);
widget.disposables.add(
element.cycleCustomElementMetadata.eventDispatchingSubscription
);
widget.disposables.add(
subscribeDispatchersWhenRootChanges(element.cycleCustomElementMetadata)
);
}
function makePropertiesDriver() {
let propertiesDriver = {};
let defaultComparer = Rx.helpers.defaultComparer;
Object.defineProperty(propertiesDriver, 'type', {
enumerable: false,
value: 'PropertiesDriver'
});
Object.defineProperty(propertiesDriver, 'get', {
enumerable: false,
value: function get(streamKey, comparer = defaultComparer) {
if (typeof streamKey === 'undefined') {
throw new Error('Custom element driver `props.get()` expects an ' +
'argument in the getter.');
}
if (typeof this[streamKey] === 'undefined') {
this[streamKey] = new Rx.ReplaySubject(1);
}
return this[streamKey]
.distinctUntilChanged(Rx.helpers.identity, comparer);
}
});
Object.defineProperty(propertiesDriver, 'getAll', {
enumerable: false,
value: function getAll() {
return this.get(ALL_PROPS);
}
});
return propertiesDriver;
}
function createContainerElement(tagName, vtreeProperties) {
let element = document.createElement('div');
element.id = vtreeProperties.id || '';
element.className = vtreeProperties.className || '';
element.className += ' cycleCustomElement-' + tagName.toUpperCase();
return element;
}
function warnIfVTreeHasNoKey(vtree) {
if (typeof vtree.key === 'undefined') {
console.warn('Missing `key` property for Cycle custom element ' +
vtree.tagName);
}
}
function throwIfVTreeHasPropertyChildren(vtree) {
if (typeof vtree.properties.children !== 'undefined') {
throw new Error('Custom element should not have property `children`. ' +
'It is reserved for children elements nested into this custom element.');
}
}
function makeCustomElementInput(domOutput, propertiesDriver, domDriverName) {
return {
[domDriverName]: domOutput,
[PROPS_DRIVER_NAME]: propertiesDriver
};
}
function makeConstructor() {
return function customElementConstructor(vtree, CERegistry, driverName) {
//console.log('%cnew (constructor) custom element ' + vtree.tagName,
// 'color: #880088');
warnIfVTreeHasNoKey(vtree);
throwIfVTreeHasPropertyChildren(vtree);
this.type = 'Widget';
this.properties = vtree.properties;
this.properties.children = vtree.children;
this.key = vtree.key;
this.isCustomElementWidget = true;
this.customElementsRegistry = CERegistry;
this.driverName = driverName;
this.firstRootElem$ = new Rx.ReplaySubject(1);
this.disposables = new Rx.CompositeDisposable();
};
}
function validateDefFnOutput(defFnOutput, domDriverName, tagName) {
if (typeof defFnOutput !== 'object') {
throw new Error(`Custom element definition function for '${tagName}' ` +
' should output an object.');
}
if (typeof defFnOutput[domDriverName] === 'undefined') {
throw new Error(`Custom element definition function for '${tagName}' ` +
`should output an object containing '${domDriverName}'.`);
}
if (typeof defFnOutput[domDriverName].subscribe !== 'function') {
throw new Error(`Custom element definition function for '${tagName}' ` +
`should output an object containing an Observable of VTree, named ` +
`'${domDriverName}'.`);
}
for (let name in defFnOutput) { if (defFnOutput.hasOwnProperty(name)) {
if (name !== domDriverName && name !== EVENTS_SINK_NAME) {
throw new Error(`Unknown '${name}' found on custom element ` +
`'${tagName}'s definition function's output.`);
}
}}
}
function makeInit(tagName, definitionFn) {
let {makeDOMDriverWithRegistry} = require('./render-dom');
return function initCustomElement() {
//console.log('%cInit() custom element ' + tagName, 'color: #880088');
let widget = this;
let driverName = widget.driverName;
let registry = widget.customElementsRegistry;
let element = createContainerElement(tagName, widget.properties);
let proxyVTree$$ = new Rx.AsyncSubject();
let domDriver = makeDOMDriverWithRegistry(element, registry);
let propertiesDriver = makePropertiesDriver();
let domResponse = domDriver(proxyVTree$$.mergeAll(), driverName);
let rootElem$ = domResponse.get(':root');
let defFnInput = makeCustomElementInput(
domResponse, propertiesDriver, driverName
);
let requests = definitionFn(defFnInput);
validateDefFnOutput(requests, driverName, tagName);
proxyVTree$$.onNext(requests[driverName].shareReplay(1));
proxyVTree$$.onCompleted();
rootElem$.subscribe(widget.firstRootElem$.asObserver());
element.cycleCustomElementMetadata = {
propertiesDriver,
rootElem$,
customEvents: requests.events,
eventDispatchingSubscription: false
};
subscribeEventDispatchingSink(element, widget);
widget.disposables.add(widget.firstRootElem$);
widget.disposables.add(proxyVTree$$);
widget.disposables.add(domResponse);
widget.update(null, element);
return element;
};
}
function validatePropertiesDriverInMetadata(element, fnName) {
if (!element) {
throw new Error(`Missing DOM element when calling ${fnName} on custom ` +
'element Widget.');
}
if (!element.cycleCustomElementMetadata) {
throw new Error('Missing custom element metadata on DOM element when ' +
'calling ' + fnName + ' on custom element Widget.');
}
let metadata = element.cycleCustomElementMetadata;
if (metadata.propertiesDriver.type !== 'PropertiesDriver') {
throw new Error('Custom element metadata\'s propertiesDriver type is ' +
'invalid: ' + metadata.propertiesDriver.type + '.');
}
}
function updateCustomElement(previous, element) {
if (previous) {
this.disposables = previous.disposables;
this.firstRootElem$.onNext(0);
this.firstRootElem$.onCompleted();
}
validatePropertiesDriverInMetadata(element, 'update()');
//console.log(`%cupdate() ${element.className}`, 'color: #880088');
let propsDriver = element.cycleCustomElementMetadata.propertiesDriver;
if (propsDriver.hasOwnProperty(ALL_PROPS)) {
propsDriver[ALL_PROPS].onNext(this.properties);
}
for (let prop in propsDriver) { if (propsDriver.hasOwnProperty(prop)) {
if (this.properties.hasOwnProperty(prop)) {
propsDriver[prop].onNext(this.properties[prop]);
}
}}
}
function destroyCustomElement(element) {
//console.log(`%cdestroy() custom el ${element.className}`, 'color: #808');
// Dispose propertiesDriver
let propsDriver = element.cycleCustomElementMetadata.propertiesDriver;
for (let prop in propsDriver) { if (propsDriver.hasOwnProperty(prop)) {
this.disposables.add(propsDriver[prop]);
}}
if (element.cycleCustomElementMetadata.eventDispatchingSubscription) {
// This subscription has to be disposed.
// Because disposing subscribeDispatchersWhenRootChanges only
// is not enough.
this.disposables.add(
element.cycleCustomElementMetadata.eventDispatchingSubscription
);
}
this.disposables.dispose();
}
function makeWidgetClass(tagName, definitionFn) {
if (typeof definitionFn !== 'function') {
throw new Error('A custom element definition given to the DOM driver ' +
'should be a function.');
}
let WidgetClass = makeConstructor();
WidgetClass.definitionFn = definitionFn; // needed by renderAsHTML
WidgetClass.prototype.init = makeInit(tagName, definitionFn);
WidgetClass.prototype.update = updateCustomElement;
WidgetClass.prototype.destroy = destroyCustomElement;
return WidgetClass;
}
module.exports = {
makeDispatchFunction,
subscribeDispatchers,
subscribeDispatchersWhenRootChanges,
makePropertiesDriver,
createContainerElement,
warnIfVTreeHasNoKey,
throwIfVTreeHasPropertyChildren,
makeConstructor,
makeInit,
updateCustomElement,
destroyCustomElement,
ALL_PROPS,
makeCustomElementInput,
makeWidgetClass
};