-
Notifications
You must be signed in to change notification settings - Fork 247
/
Copy pathcomponent.js
591 lines (467 loc) · 18 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
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
/* @flow */
/* eslint max-lines: 0 */
import { setup as setupPostRobot, on, send, bridge, toProxyWindow, destroy as destroyPostRobot } from 'post-robot/src';
import { ZalgoPromise } from 'zalgo-promise/src';
import { isWindow, getDomain, matchDomain, type CrossDomainWindowType, type DomainMatcher } from 'cross-domain-utils/src';
import { noop, isElement, cleanup, memoize, identity, extend, uniqueID } from 'belter/src';
import { childComponent, type ChildComponent } from '../child';
import { type RenderOptionsType, type ParentHelpers, parentComponent } from '../parent/parent';
import { ZOID, CONTEXT, POST_MESSAGE, WILDCARD, METHOD, PROP_TYPE } from '../constants';
import { react, angular, vue, vue3, angular2 } from '../drivers';
import { getGlobal, destroyGlobal, getInitialParentPayload, isChildComponentWindow } from '../lib';
import type { CssDimensionsType, StringMatcherType, ContainerReferenceType } from '../types';
import { validateOptions } from './validate';
import { defaultContainerTemplate, defaultPrerenderTemplate } from './templates';
import { getBuiltInProps, type UserPropsDefinitionType, type PropsDefinitionType, type PropsInputType,
type PropsType, type ParentPropType, type exportPropType, type DEFINITION_TYPE } from './props';
type LoggerPayload = { [string] : ?string | ?boolean };
// eslint-disable-next-line flowtype/require-exact-type
type Logger = {
info : (event : string, payload? : LoggerPayload) => any // eslint-disable-line flowtype/no-weak-types
};
/* Component
---------
This is the spec for the component. The idea is, when I call zoid.create(), it will create a new instance
of Component with the blueprint needed to set up ParentComponents and ChildComponents.
This is the one portion of code which is required by -- and shared to -- both the parent and child windows, and
contains all of the configuration needed for them to set themselves up.
*/
type Attributes = {|
iframe? : { [string] : string },
popup? : { [string] : string }
|};
export type ExportsConfigDefinition = {|
[string] : {|
type : DEFINITION_TYPE
|}
|};
export type ExportsMapperDefinition<X> = ({|
getExports : () => ZalgoPromise<X>
|}) => X;
export type ExportsDefinition<X> = ExportsConfigDefinition | ExportsMapperDefinition<X>;
export type ComponentOptionsType<P, X, C> = {|
tag : string,
url : string | ({| props : PropsType<P> |}) => string,
domain? : DomainMatcher,
bridgeUrl? : string,
method? : $Values<typeof METHOD>,
props? : UserPropsDefinitionType<P, X>,
dimensions? : CssDimensionsType | ({| props : PropsType<P> |}) => CssDimensionsType,
autoResize? : {| width? : boolean, height? : boolean, element? : string |},
allowedParentDomains? : StringMatcherType,
attributes? : Attributes | ({| props : PropsType<P> |}) => Attributes,
eligible? : ({| props : PropsInputType<P> |}) => {| eligible : boolean, reason? : string |},
defaultContext? : $Values<typeof CONTEXT>,
containerTemplate? : (RenderOptionsType<P>) => ?HTMLElement,
prerenderTemplate? : (RenderOptionsType<P>) => ?HTMLElement,
validate? : ({| props : PropsInputType<P> |}) => void,
logger? : Logger,
children? : () => C,
exports? : ExportsDefinition<X>
|};
export type AttributesType = {|
iframe? : { [string] : string },
popup? : { [string] : string }
|};
type AutoResizeType = {|
width? : boolean,
height? : boolean,
element? : string
|};
export type NormalizedComponentOptionsType<P, X, C> = {|
tag : string,
name : string,
url : string | ({| props : PropsType<P> |}) => string,
domain : ?DomainMatcher,
bridgeUrl : ?string,
method : ?$Values<typeof METHOD>,
propsDef : PropsDefinitionType<P, X>,
dimensions : CssDimensionsType | ({| props : PropsType<P> |}) => CssDimensionsType,
autoResize : AutoResizeType,
allowedParentDomains : StringMatcherType,
attributes : AttributesType | ({| props : PropsType<P> |}) => AttributesType,
eligible : ({| props : PropsInputType<P> |}) => {| eligible : boolean, reason? : string |},
defaultContext : $Values<typeof CONTEXT>,
containerTemplate : (RenderOptionsType<P>) => ?HTMLElement,
prerenderTemplate : ?(RenderOptionsType<P>) => ?HTMLElement,
validate : ?({| props : PropsInputType<P> |}) => void,
logger : Logger,
children : () => C,
exports : ExportsMapperDefinition<X>
|};
export type ZoidComponentInstance<P, X = void, C = void> = {|
...ParentHelpers<P>,
...X,
...C,
isEligible : () => boolean,
clone : () => ZoidComponentInstance<P, X, C>,
render : (container? : ContainerReferenceType, context? : $Values<typeof CONTEXT>) => ZalgoPromise<void>,
renderTo : (target : CrossDomainWindowType, container? : ContainerReferenceType, context? : $Values<typeof CONTEXT>) => ZalgoPromise<void>
|};
// eslint-disable-next-line flowtype/require-exact-type
export type ZoidComponent<P, X = void, C = void> = {
(props? : PropsInputType<P> | void) : ZoidComponentInstance<P, X, C>,
// eslint-disable-next-line no-undef
driver : <T>(string, mixed) => T,
isChild : () => boolean,
xprops? : PropsType<P>,
canRenderTo : (CrossDomainWindowType) => ZalgoPromise<boolean>,
instances : $ReadOnlyArray<ZoidComponentInstance<P, X, C>>
};
const getDefaultAttributes = () : AttributesType => {
// $FlowFixMe
return {};
};
const getDefaultAutoResize = () : AutoResizeType => {
// $FlowFixMe
return {};
};
const getDefaultExports = <X>() : () => X => {
// $FlowFixMe
return noop;
};
const getDefaultDimensions = () : CssDimensionsType => {
// $FlowFixMe
return {};
};
function normalizeOptions<P, X, C>(options : ComponentOptionsType<P, X, C>) : NormalizedComponentOptionsType<P, X, C> {
const {
tag,
url,
domain,
bridgeUrl,
props = {},
dimensions = getDefaultDimensions(),
autoResize = getDefaultAutoResize(),
allowedParentDomains = WILDCARD,
attributes = getDefaultAttributes(),
defaultContext = CONTEXT.IFRAME,
containerTemplate = (__ZOID__.__DEFAULT_CONTAINER__ ? defaultContainerTemplate : null),
prerenderTemplate = (__ZOID__.__DEFAULT_PRERENDER__ ? defaultPrerenderTemplate : null),
validate,
eligible = () => ({ eligible: true }),
logger = { info: noop },
exports: xportsDefinition = getDefaultExports(),
method,
children = () : C => {
// $FlowFixMe
return {};
}
} = options;
const name = tag.replace(/-/g, '_');
// $FlowFixMe[incompatible-type]
// $FlowFixMe[cannot-spread-inexact]
const propsDef : PropsDefinitionType<P, X> = {
...getBuiltInProps(),
...props
};
if (!containerTemplate) {
throw new Error(`Container template required`);
}
const xports = typeof xportsDefinition === 'function'
? xportsDefinition
: ({ getExports }) : X => {
const result = {};
for (const key of Object.keys(xportsDefinition)) {
const { type } = xportsDefinition[key];
const valuePromise = getExports().then(res => {
// $FlowFixMe
return res[key];
});
if (type === PROP_TYPE.FUNCTION) {
result[key] = (...args) => valuePromise.then(value => value(...args));
} else {
result[key] = valuePromise;
}
}
// $FlowFixMe
return result;
};
return {
name,
tag,
url,
domain,
bridgeUrl,
method,
propsDef,
dimensions,
autoResize,
allowedParentDomains,
attributes,
defaultContext,
containerTemplate,
prerenderTemplate,
validate,
logger,
eligible,
children,
exports: xports
};
}
let cleanInstances = cleanup();
const cleanZoid = cleanup();
export type Component<P, X, C> = {|
init : (props? : PropsInputType<P> | void) => ZoidComponentInstance<P, X, C>,
instances : $ReadOnlyArray<ZoidComponentInstance<P, X, C>>,
driver : (string, mixed) => mixed,
isChild : () => boolean,
canRenderTo : (CrossDomainWindowType) => ZalgoPromise<boolean>,
registerChild : () => ?ChildComponent<P, X>
|};
export function component<P, X, C>(opts : ComponentOptionsType<P, X, C>) : Component<P, X, C> {
if (__DEBUG__) {
validateOptions(opts);
}
const options = normalizeOptions(opts);
const {
name,
tag,
defaultContext,
propsDef,
eligible,
children
} = options;
const global = getGlobal(window);
const driverCache = {};
const instances = [];
const isChild = () : boolean => {
if (isChildComponentWindow(name)) {
const { payload } = getInitialParentPayload();
if (payload.tag === tag && matchDomain(payload.childDomainMatch, getDomain())) {
return true;
}
}
return false;
};
const registerChild = memoize(() : ?ChildComponent<P, X> => {
if (isChild()) {
if (window.xprops) {
delete global.components[tag];
throw new Error(`Can not register ${ name } as child - child already registered`);
}
const child = childComponent(options);
child.init();
return child;
}
});
const listenForDelegate = () => {
const allowDelegateListener = on(`${ POST_MESSAGE.ALLOW_DELEGATE }_${ name }`, () => {
return true;
});
const delegateListener = on(`${ POST_MESSAGE.DELEGATE }_${ name }`, ({ source, data: { uid, overrides } }) => {
return {
parent: parentComponent({
uid, options, overrides, parentWin: source
})
};
});
cleanZoid.register(allowDelegateListener.cancel);
cleanZoid.register(delegateListener.cancel);
};
const canRenderTo = (win : CrossDomainWindowType) : ZalgoPromise<boolean> => {
return send(win, `${ POST_MESSAGE.ALLOW_DELEGATE }_${ name }`).then(({ data }) => {
return data;
}).catch(() => {
return false;
});
};
const getDefaultContainer = (context : $Values<typeof CONTEXT>, container? : ContainerReferenceType) : ContainerReferenceType => {
if (container) {
if (typeof container !== 'string' && !isElement(container)) {
throw new TypeError(`Expected string or element selector to be passed`);
}
return container;
}
if (context === CONTEXT.POPUP) {
return 'body';
}
throw new Error(`Expected element to be passed to render iframe`);
};
const getDefaultContext = (props : PropsInputType<P>, context : ?$Values<typeof CONTEXT>) : ZalgoPromise<$Values<typeof CONTEXT>> => {
return ZalgoPromise.try(() => {
if (props.window) {
return toProxyWindow(props.window).getType();
}
if (context) {
if (context !== CONTEXT.IFRAME && context !== CONTEXT.POPUP) {
throw new Error(`Unrecognized context: ${ context }`);
}
return context;
}
return defaultContext;
});
};
const getDefaultInputProps = () : PropsInputType<P> => {
// $FlowFixMe
return {};
};
const init = (inputProps? : PropsInputType<P> | void) : ZoidComponentInstance<P, X, C> => {
// eslint-disable-next-line prefer-const
let instance;
const uid = `${ ZOID }-${ tag }-${ uniqueID() }`;
const props = inputProps || getDefaultInputProps();
const { eligible: eligibility, reason } = eligible({ props });
const isEligible = () => eligibility;
const onDestroy = props.onDestroy;
props.onDestroy = (...args) => {
if (instance && eligibility) {
instances.splice(instances.indexOf(instance), 1);
}
if (onDestroy) {
return onDestroy(...args);
}
};
const parent = parentComponent({
uid, options
});
parent.init();
if (eligibility) {
parent.setProps(props);
} else {
if (props.onDestroy) {
props.onDestroy();
}
}
cleanInstances.register(err => {
return parent.destroy(err || new Error(`zoid destroyed all components`));
});
const clone = ({ decorate = identity } = {}) => {
return init(decorate(props));
};
const getChildren = () : C => {
// $FlowFixMe
const childComponents : {| [string] : ZoidComponent<mixed> |} = children();
const result = {};
for (const childName of Object.keys(childComponents)) {
const Child : ZoidComponent<mixed> = childComponents[childName];
result[childName] = (childInputProps) => {
const parentProps : PropsType<P> = parent.getProps();
const parentExport : exportPropType<X> = parent.export;
const childParent : ParentPropType<P, X> = {
uid,
props: parentProps,
export: parentExport
};
const childProps : PropsInputType<mixed> = {
...childInputProps,
parent: childParent
};
return Child(childProps);
};
}
// $FlowFixMe
return result;
};
const render = (target, container, context) => {
return ZalgoPromise.try(() => {
if (!eligibility) {
const err = new Error(reason || `${ name } component is not eligible`);
return parent.destroy(err).then(() => {
throw err;
});
}
if (!isWindow(target)) {
throw new Error(`Must pass window to renderTo`);
}
return getDefaultContext(props, context);
}).then(finalContext => {
container = getDefaultContainer(finalContext, container);
if (target !== window && typeof container !== 'string') {
throw new Error(`Must pass string element when rendering to another window`);
}
return parent.render({
target,
container,
context: finalContext,
rerender: () => {
const newInstance = clone();
extend(instance, newInstance);
return newInstance.renderTo(target, container, context);
}
});
}).catch(err => {
return parent.destroy(err).then(() => {
throw err;
});
});
};
instance = {
...parent.getExports(),
...parent.getHelpers(),
...getChildren(),
isEligible,
clone,
render: (container, context) => render(window, container, context),
renderTo: (target, container, context) => render(target, container, context)
};
if (eligibility) {
instances.push(instance);
}
return instance;
};
const driver = (driverName : string, dep : mixed) : mixed => {
if (__ZOID__.__FRAMEWORK_SUPPORT__) {
const drivers = { react, angular, vue, vue3, angular2 };
if (!drivers[driverName]) {
throw new Error(`Could not find driver for framework: ${ driverName }`);
}
if (!driverCache[driverName]) {
driverCache[driverName] = drivers[driverName].register(tag, propsDef, init, dep);
}
return driverCache[driverName];
} else {
throw new Error(`Driver support not enabled`);
}
};
registerChild();
listenForDelegate();
global.components = global.components || {};
if (global.components[tag]) {
throw new Error(`Can not register multiple components with the same tag: ${ tag }`);
}
global.components[tag] = true;
return {
init,
instances,
driver,
isChild,
canRenderTo,
registerChild
};
}
export type ComponentDriverType<P, L, D, X, C> = {|
register : (string, PropsDefinitionType<P, X>, (PropsInputType<P>) => ZoidComponentInstance<P, X, C>, L) => D
|};
export type ZoidProps<P> = PropsType<P>;
// eslint-disable-next-line no-undef
export type CreateZoidComponent = <P, X, C>(options : ComponentOptionsType<P, X, C>) => ZoidComponent<P, X, C>;
export const create : CreateZoidComponent = <P, X, C>(options : ComponentOptionsType<P, X, C>) : ZoidComponent<P, X, C> => {
setupPostRobot();
const comp = component(options);
const init = (props? : PropsInputType<P> | void) => comp.init(props);
init.driver = (name, dep) => comp.driver(name, dep);
init.isChild = () => comp.isChild();
init.canRenderTo = (win) => comp.canRenderTo(win);
init.instances = comp.instances;
const child = comp.registerChild();
if (child) {
window.xprops = init.xprops = child.getProps();
}
return init;
};
export function destroyComponents(err? : mixed) : ZalgoPromise<void> {
if (bridge) {
bridge.destroyBridges();
}
const destroyPromise = cleanInstances.all(err);
cleanInstances = cleanup();
return destroyPromise;
}
export const destroyAll = destroyComponents;
export function destroy(err? : mixed) : ZalgoPromise<void> {
destroyAll();
destroyGlobal();
destroyPostRobot();
return cleanZoid.all(err);
}