/
FluidIoC.js
1947 lines (1794 loc) · 89.4 KB
/
FluidIoC.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
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright 2011-2013 OCAD University
Copyright 2010-2011 Lucendo Development Ltd.
Licensed under the Educational Community License (ECL), Version 2.0 or the New
BSD license. You may not use this file except in compliance with one these
Licenses.
You may obtain a copy of the ECL 2.0 License and BSD License at
https://github.com/fluid-project/infusion/raw/master/Infusion-LICENSE.txt
*/
// Declare dependencies
/*global fluid_1_5:true, jQuery*/
// JSLint options
/*jslint white: true, funcinvoke: true, continue: true, elsecatch: true, operator: true, jslintok:true, undef: true, newcap: true, regexp: true, bitwise: true, browser: true, forin: true, maxerr: 1000, indent: 4 */
var fluid_1_5 = fluid_1_5 || {};
(function ($, fluid) {
/** The Fluid "IoC System proper" - resolution of references and
* completely automated instantiation of declaratively defined
* component trees */
// unsupported, non-API function
// Currently still uses manual traversal - once we ban manually instantiated components,
// it will use the instantiator's records instead.
fluid.visitComponentChildren = function (that, visitor, options, path, i) {
var instantiator = fluid.getInstantiator(that);
for (var name in that) {
var newPath = instantiator.composePath(path, name);
var component = that[name];
// Every component *should* have an id, but some clients (e.g. DOM binder) may not yet be compliant
// This entire algorithm is primitive and expensive and will be removed once we can abolish manual init components
if (!component || !component.typeName || (component.id && options.visited && options.visited[component.id])) {continue; }
if (options.visited) {
options.visited[component.id] = true;
}
if (visitor(component, name, newPath, path, i)) {
return true;
}
if (!options.flat) {
fluid.visitComponentChildren(component, visitor, options, newPath);
}
}
};
// unsupported, non-API function
fluid.getMemberNames = function (instantiator, thatStack) {
var path = instantiator.idToPath(thatStack[thatStack.length - 1].id);
var segs = fluid.model.parseEL(path);
segs.unshift.apply(segs, fluid.generate(thatStack.length - segs.length, ""));
return segs;
};
// thatStack contains an increasing list of MORE SPECIFIC thats.
// this visits all components starting from the current location (end of stack)
// in visibility order up the tree.
var visitComponents = function (instantiator, thatStack, visitor, options) {
options = options || {
visited: {},
flat: true,
instantiator: instantiator
};
var memberNames = fluid.getMemberNames(instantiator, thatStack);
for (var i = thatStack.length - 1; i >= 0; --i) {
var that = thatStack[i], path;
if (that.typeName) {
options.visited[that.id] = true;
path = instantiator.idToPath[that.id];
if (visitor(that, memberNames[i], path, path, i)) {
return;
}
}
if (fluid.visitComponentChildren(that, visitor, options, path, i)) {
return;
}
}
};
fluid.mountStrategy = function (prefix, root, toMount, targetPrefix) {
var offset = prefix.length;
return function (target, name, i, segs) {
if (i <= prefix.length) { // Avoid OOB to not trigger deoptimisation!
return;
}
for (var j = 0; j < prefix.length; ++ j) {
if (segs[j] !== prefix[j]) {
return;
}
}
return toMount(target, name, i - prefix.length, segs.slice(offset));
}
};
// unsupported, NON-API function
fluid.invokerFromRecord = function (invokerec, name, that) {
fluid.pushActivity("makeInvoker", "beginning instantiation of invoker with name %name and record %record as child of %that",
{name: name, record: invokerec, that: that});
var invoker = fluid.makeInvoker(that, invokerec, name);
fluid.popActivity();
return invoker;
};
// unsupported, NON-API function
fluid.memberFromRecord = function (memberrec, name, that) {
var value = fluid.expandOptions(memberrec, that);
return value;
};
// unsupported, NON-API function
fluid.recordStrategy = function (that, options, optionsStrategy, recordPath, recordMaker, prefix) {
prefix = prefix || [];
return {
strategy: function (target, name, i, segs) {
if (i !== 1) {
return;
}
var record = fluid.driveStrategy(options, [recordPath, name], optionsStrategy);
if (record === undefined) {
return;
}
fluid.set(target, [name], fluid.inEvaluationMarker);
var member = recordMaker(record, name, that);
fluid.set(target, [name], member);
return member;
},
initter: function () {
var records = fluid.driveStrategy(options, recordPath, optionsStrategy) || {};
for (var name in records) {
fluid.getForComponent(that, prefix.concat([name]));
}
}
};
};
// patch Fluid.js version for timing
// unsupported, NON-API function
fluid.instantiateFirers = function (that, options) {
var shadow = fluid.shadowForComponent(that);
var initter = fluid.get(shadow, ["eventStrategyBlock", "initter"]) || fluid.identity;
initter();
};
// unsupported, NON-API function
fluid.makeDistributionRecord = function (contextThat, sourceRecord, sourcePath, targetSegs, exclusions, offset, sourceType) {
offset = offset || 0;
sourceType = sourceType || "distribution";
var source = fluid.copy(fluid.get(sourceRecord, sourcePath));
fluid.each(exclusions, function (exclusion) {
fluid.model.applyChangeRequest(source, {path: exclusion, type: "DELETE"});
});
var record = {options: {}};
var primitiveSource = fluid.isPrimitive(source);
fluid.model.applyChangeRequest(record, {path: targetSegs, type: primitiveSource? "ADD": "MERGE", value: source});
return $.extend(record, {contextThat: contextThat, recordType: sourceType, priority: fluid.mergeRecordTypes.distribution + offset});
};
// unsupported, NON-API function
fluid.filterBlocks = function (contextThat, sourceBlocks, sourcePath, targetSegs, exclusions, removeSource) {
var togo = [], offset = 0;
fluid.each(sourceBlocks, function (block) {
var source = fluid.get(block.source, sourcePath);
if (source) {
togo.push(fluid.makeDistributionRecord(contextThat, block.source, sourcePath, targetSegs, exclusions, offset++, block.recordType));
var rescued = $.extend({}, source);
if (removeSource) {
fluid.model.applyChangeRequest(block.source, {path: sourcePath, type: "DELETE"});
}
fluid.each(exclusions, function (exclusion) {
var orig = fluid.get(rescued, exclusion);
fluid.set(block.source, sourcePath.concat(exclusion), orig);
});
}
});
return togo;
};
// unsupported, NON-API function
// TODO: This implementation is obviously poor and has numerous flaws
fluid.matchIoCSelector = function (selector, thatStack, contextHashes, memberNames, i) {
var thatpos = thatStack.length - 1;
var selpos = selector.length - 1;
while (true) {
var mustMatchHere = thatpos === thatStack.length - 1 || selector[selpos].child;
var that = thatStack[thatpos];
var selel = selector[selpos];
var match = true;
for (var j = 0; j < selel.predList.length; ++j) {
var pred = selel.predList[j];
if (pred.context && !(contextHashes[thatpos][pred.context] || memberNames[thatpos] === pred.context)) {
match = false;
break;
}
if (pred.id && that.id !== pred.id) {
match = false;
break;
}
}
if (selpos === 0 && thatpos > i && mustMatchHere) {
match = false; // child selector must exhaust stack completely - FLUID-5029
}
if (match) {
if (selpos === 0) {
return true;
}
--thatpos;
--selpos;
}
else {
if (mustMatchHere) {
return false;
}
else {
--thatpos;
}
}
if (thatpos < i) {
return false;
}
}
};
// unsupported, NON-API function
fluid.collectDistributions = function (distributedBlocks, distribution, thatStack, contextHashes, memberNames, i) {
if (fluid.matchIoCSelector(distribution.selector, thatStack, contextHashes, memberNames, i)) {
distributedBlocks.push.apply(distributedBlocks, distribution.blocks);
}
};
fluid.getMembers = function (holder, name) {
return fluid.transform(holder, function(member) {
return fluid.get(member, name);
});
};
// unsupported, NON-API function
fluid.receiveDistributions = function (parentThat, gradeNames, memberName) {
var instantiator = fluid.getInstantiator(parentThat);
var thatStack = instantiator.getThatStack(parentThat); // most specific is at end
var memberNames = fluid.getMemberNames(instantiator, thatStack);
memberNames.push(memberName);
var distributedBlocks = [];
var shadows = fluid.transform(thatStack, function (thisThat) {
return instantiator.idToShadow[thisThat.id];
});
var contextHashes = fluid.getMembers(shadows, "contextHash");
contextHashes.push(fluid.gradeNamesToHash(gradeNames));
thatStack.push({}); // fake "that" since we try to match selectors before creation for FLUID-5013
for (var i = 0; i < thatStack.length - 1; ++ i) {
fluid.each(shadows[i].distributions, function (distribution) {
fluid.collectDistributions(distributedBlocks, distribution, thatStack, contextHashes, memberNames, i);
});
}
return distributedBlocks;
};
// unsupported, NON-API function
fluid.applyDistributions = function (that, preBlocks, targetShadow) {
var distributedBlocks = fluid.transform(preBlocks, function (preBlock) {
return fluid.generateExpandBlock(preBlock, that, targetShadow.mergePolicy);
});
var mergeOptions = targetShadow.mergeOptions;
mergeOptions.mergeBlocks.push.apply(mergeOptions.mergeBlocks, distributedBlocks);
mergeOptions.updateBlocks();
};
// unsupported, NON-API function
fluid.parseExpectedOptionsPath = function (path, role) {
var segs = fluid.model.parseEL(path);
if (segs.length > 1 && segs[0] !== "options") {
fluid.fail("Error in options distribution record ", record, " - only " + role + " paths beginning with \"options\" are supported");
}
return segs.slice(1);
};
// unsupported, NON-API function
fluid.isIoCSSSelector = function (context) {
return context.indexOf(" ") !== -1; // simple-minded check for an IoCSS reference
};
// unsupported, NON-API function
fluid.pushDistributions = function (targetHead, selector, blocks) {
var targetShadow = fluid.shadowForComponent(targetHead);
var id = fluid.allocateGuid();
var distributions = (targetShadow.distributions = targetShadow.distributions || []);
distributions.push({
id: id,
selector: selector,
blocks: blocks
});
return id;
};
// unsupported, NON-API function
fluid.clearDistributions = function (targetHead, id) {
var targetShadow = fluid.shadowForComponent(targetHead);
fluid.remove_if(targetShadow.distributions, function (distribution) {
return distribution.id === id;
});
};
// unsupported, NON-API function
// Modifies a parsed selector to extra its head context which will be matched upwards
fluid.extractSelectorHead = function (parsedSelector) {
var predList = parsedSelector[0].predList;
var context = predList[0].context;
predList.length = 0;
return context;
};
fluid.undistributableOptions = ["gradeNames", "distributeOptions", "returnedPath", "argumentMap", "initFunction", "mergePolicy", "progressiveCheckerOptions"]; // automatically added to "exclusions" of every distribution
// unsupported, NON-API function
fluid.distributeOptions = function (that, optionsStrategy) {
var records = fluid.makeArray(fluid.driveStrategy(that.options, "distributeOptions", optionsStrategy));
fluid.each(records, function (record) {
var targetRef = fluid.parseContextReference(record.target);
var targetComp, selector;
if (fluid.isIoCSSSelector(targetRef.context)) {
selector = fluid.parseSelector(targetRef.context, fluid.IoCSSMatcher);
var headContext = fluid.extractSelectorHead(selector);
if (headContext !== "that") {
fluid.fail("Downwards options distribution not supported from component other than \"that\"");
}
targetComp = that;
}
else {
targetComp = fluid.resolveContext(targetRef.context, that);
if (!targetComp) {
fluid.fail("Error in options distribution record ", record, " - could not resolve context selector {"+targetRef.context+"} to a root component");
}
}
var targetSegs = fluid.model.parseEL(targetRef.path);
var preBlocks;
if (record.record) {
preBlocks = [(fluid.makeDistributionRecord(that, record.record, [], targetSegs, [], 0))];
}
else {
var thatShadow = fluid.shadowForComponent(that);
var source = fluid.parseContextReference(record.source || "{that}.options");
if (source.context !== "that") {
fluid.fail("Error in options distribution record ", record, " only a context of {that} is supported");
}
var sourcePath = fluid.parseExpectedOptionsPath(source.path, "source");
var fullExclusions = fluid.makeArray(record.exclusions).concat(sourcePath.length === 0 ? fluid.undistributableOptions : []);
var exclusions = fluid.transform(fullExclusions, function (exclusion) {
return fluid.model.parseEL(exclusion);
});
preBlocks = fluid.filterBlocks(that, thatShadow.mergeOptions.mergeBlocks, sourcePath, targetSegs, exclusions, record.removeSource);
thatShadow.mergeOptions.updateBlocks(); // perhaps unnecessary
}
// TODO: inline material has to be expanded in its original context!
if (selector) {
fluid.pushDistributions(targetComp, selector, preBlocks);
}
else { // The component exists now, we must rebalance it
var targetShadow = fluid.shadowForComponent(targetComp);
fluid.applyDistributions(that, preBlocks, targetShadow);
}
});
};
// unsupported, NON-API function
fluid.gradeNamesToHash = function (gradeNames) {
var contextHash = {};
fluid.each(gradeNames, function (gradeName) {
contextHash[gradeName] = true;
contextHash[fluid.computeNickName(gradeName)] = true;
});
return contextHash;
};
// unsupported, NON-API function
fluid.cacheShadowGrades = function (that, shadow) {
var contextHash = fluid.gradeNamesToHash(that.options.gradeNames);
contextHash[that.nickName] = true;
shadow.contextHash = contextHash;
};
// First sequence point where the mergeOptions strategy is delivered from Fluid.js - here we take care
// of both receiving and transmitting options distributions
// unsupported, NON-API function
fluid.deliverOptionsStrategy = function (that, target, mergeOptions) {
var shadow = fluid.shadowForComponent(that, shadow);
fluid.cacheShadowGrades(that, shadow);
shadow.mergeOptions = mergeOptions;
};
// unsupported, NON-API function
fluid.resolveReturnedPath = function (returnedPath, that) {
var shadow = fluid.shadowForComponent(that);
// This prevents corruption of instantiator records by defeating effect of "returnedPath" for non-roots
return shadow && shadow.path !== "" ? null : returnedPath;
};
// unsupported, NON-API function
fluid.computeDynamicGrades = function (that, shadow, strategy) {
delete that.options.gradeNames; // Recompute gradeNames for FLUID-5012 and others
var gradeNames = fluid.driveStrategy(that.options, "gradeNames", strategy);
// TODO: In complex distribution cases, a component might end up with multiple default blocks
var defaultsBlock = fluid.findMergeBlocks(shadow.mergeOptions.mergeBlocks, "defaults")[0];
var dynamicGrades = fluid.remove_if(gradeNames, function (gradeName) {
return gradeName.charAt(0) === "{" || !fluid.hasGrade(defaultsBlock.target, gradeName);
}, []);
var resolved = [];
fluid.each(dynamicGrades, function (dynamicGrade) {
var func = fluid.expandOptions(dynamicGrade, that);
resolved = resolved.concat(typeof(func) === "function" ? func() : func);
});
if (resolved.length !== 0) {
gradeNames.push.apply(gradeNames, resolved);
fluid.unique(gradeNames.sort());
fluid.cacheShadowGrades(that, shadow);
var newDefaults = fluid.copy(fluid.getGradedDefaults(that.typeName, resolved));
var defaultsBlock = fluid.findMergeBlocks(shadow.mergeOptions.mergeBlocks, "defaults")[0];
defaultsBlock.source = newDefaults;
shadow.mergeOptions.updateBlocks();
}
};
fluid.computeDynamicComponentKey = function (recordKey, sourceKey) {
return recordKey + (sourceKey === 0 ? "" : "-" + sourceKey); // TODO: configurable name strategies
};
// unsupported, NON-API function
fluid.registerDynamicRecord = function (that, recordKey, sourceKey, record, toCensor) {
var key = fluid.computeDynamicComponentKey(recordKey, sourceKey);
var cRecord = fluid.copy(record);
delete cRecord[toCensor];
fluid.set(that.options, ["components", key], cRecord);
return key;
};
// unsupported, NON-API function
fluid.computeDynamicComponents = function (that, mergeOptions) {
var shadow = fluid.shadowForComponent(that);
var localSub = shadow.subcomponentLocal = {};
var records = fluid.driveStrategy(that.options, "dynamicComponents", mergeOptions.strategy);
fluid.each(records, function (record, recordKey) {
if (!record.sources && !record.createOnEvent) {
fluid.fail("Cannot process dynamicComponents record ", record, " without a \"sources\" or \"createOnEvent\" entry");
}
if (record.sources) {
var sources = fluid.expandOptions(record.sources, that);
fluid.each(sources, function (source, sourceKey) {
var key = fluid.registerDynamicRecord(that, recordKey, sourceKey, record, "sources");
localSub[key] = {"source": source, "sourcePath": sourceKey};
});
}
else if (record.createOnEvent) {
var event = fluid.event.expandOneEvent(that, record.createOnEvent);
fluid.set(shadow, ["dynamicComponentCount", recordKey], 0);
var listener = function () {
var key = fluid.registerDynamicRecord(that, recordKey, shadow.dynamicComponentCount[recordKey]++, record, "createOnEvent");
localSub[key] = {"arguments": fluid.makeArray(arguments)};
fluid.initDependent(that, key);
};
event.addListener(listener);
fluid.recordListener(event, listener, shadow);
}
});
};
// Second sequence point for mergeOptions from Fluid.js - here we construct all further
// strategies required on the IoC side and mount them into the shadow's getConfig for universal use
// unsupported, NON-API function
fluid.computeComponentAccessor = function (that) {
var shadow = fluid.shadowForComponent(that);
var options = that.options;
var strategy = shadow.mergeOptions.strategy;
var optionsStrategy = fluid.mountStrategy(["options"], options, strategy);
shadow.invokerStrategy = fluid.recordStrategy(that, options, strategy, "invokers", fluid.invokerFromRecord);
shadow.eventStrategyBlock = fluid.recordStrategy(that, options, strategy, "events", fluid.eventFromRecord, ["events"]);
var eventStrategy = fluid.mountStrategy(["events"], that, shadow.eventStrategyBlock.strategy, ["events"]);
shadow.memberStrategy = fluid.recordStrategy(that, options, strategy, "members", fluid.memberFromRecord);
// NB - ginger strategy handles concrete, rationalise
shadow.getConfig = {strategies: [fluid.model.funcResolverStrategy, fluid.makeGingerStrategy(that),
optionsStrategy, shadow.invokerStrategy.strategy, shadow.memberStrategy.strategy, eventStrategy]};
fluid.computeDynamicGrades(that, shadow, strategy, shadow.mergeOptions.mergeBlocks);
fluid.distributeOptions(that, strategy);
return shadow.getConfig;
};
fluid.shadowForComponent = function (component) {
var instantiator = fluid.getInstantiator(component);
return shadow = instantiator && component ? instantiator.idToShadow[component.id] : null;
};
fluid.getForComponent = function (component, path) {
var shadow = fluid.shadowForComponent(component);
var getConfig = shadow ? shadow.getConfig : undefined;
return fluid.get(component, path, getConfig);
};
// An EL segment resolver strategy that will attempt to trigger creation of
// components that it discovers along the EL path, if they have been defined but not yet
// constructed.
// unsupported, NON-API function
fluid.makeGingerStrategy = function (that) {
var instantiator = fluid.getInstantiator(that);
return function (component, thisSeg, index, segs) {
var atval = component[thisSeg];
if (atval === fluid.inEvaluationMarker && index === segs.length) {
fluid.fail("Error in component configuration - a circular reference was found during evaluation of path segment \"" + thisSeg
+ "\": for more details, see the activity records following this message in the console, or issue fluid.setLogging(fluid.logLevel.TRACE) when running your application");
}
if (index > 1) {
return atval;
}
if (atval === undefined) { // pick up components in instantiation here - we can cut this branch by attaching early
var parentPath = instantiator.idToShadow[component.id].path;
var childPath = fluid.composePath(parentPath, thisSeg);
atval = instantiator.pathToComponent[childPath];
}
if (atval === undefined) {
// TODO: This check is very expensive - once gingerness is stable, we ought to be able to
// eagerly compute and cache the value of options.components - check is also incorrect and will miss injections
if (fluid.getForComponent(component, ["options", "components", thisSeg])) {
fluid.initDependent(component, thisSeg);
atval = component[thisSeg];
}
}
return atval;
};
};
fluid.filterBuiltinGrades = function (gradeNames) {
return fluid.remove_if(fluid.makeArray(gradeNames), function (gradeName) {
return /autoInit|fluid.littleComponent|fluid.modelComponent|fluid.eventedComponent|fluid.viewComponent|fluid.typeFount/.test(gradeName);
});
};
fluid.dumpGradeNames = function (that) {
return that.options && that.options.gradeNames ?
" gradeNames: " + JSON.stringify(fluid.filterBuiltinGrades(that.options.gradeNames)) : "";
};
// unsupported, non-API function
fluid.dumpThat = function (that) {
return "{ typeName: \"" + that.typeName + "\"" +
fluid.dumpGradeNames(that) + " id: " + that.id + "}";
};
// unsupported, non-API function
fluid.dumpThatStack = function (thatStack, instantiator) {
var togo = fluid.transform(thatStack, function(that) {
var path = instantiator.idToPath(that.id);
return fluid.dumpThat(that) + (path? (" - path: " + path) : "");
});
return togo.join("\n");
};
var localRecordExpected = /arguments|options|container|source|sourcePath/;
// unsupported, NON-API function
fluid.resolveContext = function (context, that) {
var instantiator = fluid.getInstantiator(that);
if (context === "instantiator") {
return instantiator;
}
else if (context === "that") {
return that;
}
var foundComponent;
var thatStack = instantiator.getFullStack(that);
visitComponents(instantiator, thatStack, function (component, name) {
var shadow = fluid.shadowForComponent(component);
// TODO: Some components, e.g. the static environment and typeTags do not have a shadow, which slows us down here
if (context === name || shadow && shadow.contextHash && shadow.contextHash[context] || context === component.typeName || context === component.nickName) {
foundComponent = component;
return true; // YOUR VISIT IS AT AN END!!
}
if (fluid.getForComponent(component, ["options", "components", context, "type"]) && !component[context]) {
// This is an expensive guess since we make it for every component up the stack - must apply the WAVE OF EXPLOSION (FLUID-4925) to discover all components first
// This line attempts a hopeful construction of components that could be guessed by nickname through finding them unconstructed
// in options. In the near future we should eagerly BEGIN the process of constructing components, discovering their
// types and then attaching them to the tree VERY EARLY so that we get consistent results from different strategies.
foundComponent = fluid.getForComponent(component, context);
return true;
}
});
return foundComponent;
};
// unsupported, NON-API function
fluid.makeStackFetcher = function (parentThat, localRecord) {
var fetcher = function (parsed) {
var context = parsed.context;
if (localRecord && localRecordExpected.test(context)) {
var fetched = fluid.get(localRecord[context], parsed.path);
return context === "arguments" || context === "source" || context === "sourcePath" ? fetched : {
marker: context === "options" ? fluid.EXPAND : fluid.EXPAND_NOW,
value: fetched
};
}
var foundComponent = fluid.resolveContext(context, parentThat);
if (!foundComponent && parsed.path !== "") {
var ref = fluid.renderContextReference(parsed);
fluid.fail("Failed to resolve reference " + ref + " - could not match context with name "
+ context + " from component leaf ", parentThat);
}
return fluid.getForComponent(foundComponent, parsed.path);
};
return fetcher;
};
// unsupported, NON-API function
fluid.makeStackResolverOptions = function (parentThat, localRecord) {
return $.extend(fluid.copy(fluid.rawDefaults("fluid.makeExpandOptions")), {
fetcher: fluid.makeStackFetcher(parentThat, localRecord),
contextThat: parentThat
});
};
// unsupported, non-API function
fluid.clearListeners = function (shadow) {
fluid.each(shadow.listeners, function (rec) {
rec.event.removeListener(rec.listener);
});
delete shadow.listeners;
};
// unsupported, non-API function
fluid.recordListener = function (event, listener, shadow) {
var listeners = shadow.listeners;
if (!listeners) {
listeners = shadow.listeners = [];
}
listeners.push({event: event, listener: listener});
};
var idToInstantiator = {};
// unsupported, non-API function - however, this structure is of considerable interest to those debugging
// into IoC issues. The structures idToShadow and pathToComponent contain a complete map of the component tree
// forming the surrounding scope
fluid.instantiator = function (freeInstantiator) {
var that = {
id: fluid.allocateGuid(),
nickName: "instantiator",
pathToComponent: {},
idToShadow: {},
composePath: fluid.composePath // For speed, we declare that no component's name may contain a period
};
// We frequently get requests for components not in this instantiator - e.g. from the dynamicEnvironment or manually created ones
that.idToPath = function (id) {
var shadow = that.idToShadow[id];
return shadow ? shadow.path : "";
};
that.getThatStack = function (component) {
var shadow = that.idToShadow[component.id];
if (shadow) {
var path = shadow.path;
var parsed = fluid.model.parseEL(path);
var togo = fluid.transform(parsed, function (value, i) {
var parentPath = fluid.model.composeSegments.apply(null, parsed.slice(0, i + 1));
return that.pathToComponent[parentPath];
});
var root = that.pathToComponent[""];
if (root) {
togo.unshift(root);
}
return togo;
}
else { return [component];}
};
that.getEnvironmentalStack = function () {
var togo = [fluid.staticEnvironment];
if (!freeInstantiator) {
togo.push(fluid.globalThreadLocal());
}
return togo;
};
that.getFullStack = function (component) {
var thatStack = component? that.getThatStack(component) : [];
return that.getEnvironmentalStack().concat(thatStack);
};
function recordComponent(component, path, created) {
if (created) {
idToInstantiator[component.id] = that;
var shadow = that.idToShadow[component.id] = {};
shadow.path = path;
}
if (that.pathToComponent[path]) {
fluid.fail("Error during instantiation - path " + path + " which has just created component " + fluid.dumpThat(component)
+ " has already been used for component " + fluid.dumpThat(that.pathToComponent[path]) + " - this is a circular instantiation or other oversight."
+ " Please clear the component using instantiator.clearComponent() before reusing the path.");
}
that.pathToComponent[path] = component;
}
that.recordRoot = function (component) {
if (component && component.id && !that.pathToComponent[""]) {
recordComponent(component, "", true);
}
};
that.recordKnownComponent = function (parent, component, name, created) {
var parentPath = that.idToShadow[parent.id].path;
var path = that.composePath(parentPath, name);
recordComponent(component, path, created);
};
that.clearComponent = function (component, name, child, options, noModTree, path) {
var record = that.idToShadow[component.id].path;
// use flat recursion since we want to use our own recursion rather than rely on "visited" records
options = options || {flat: true, instantiator: that};
child = child || component[name];
path = path || record;
if (path === undefined) {
fluid.fail("Cannot clear component " + name + " from component ", component,
" which was not created by this instantiator");
}
fluid.fireEvent(child, "events.onClear", [child, name, component]);
var childPath = that.composePath(path, name);
var childRecord = that.idToShadow[child.id];
// only recurse on components which were created in place - if the id record disagrees with the
// recurse path, it must have been injected
if (childRecord && childRecord.path === childPath) {
fluid.fireEvent(child, "events.onDestroy", [child, name, component]);
fluid.clearListeners(childRecord);
fluid.visitComponentChildren(child, function(gchild, gchildname, newPath, parentPath) {
that.clearComponent(child, gchildname, null, options, true, parentPath);
}, options, childPath);
delete that.idToShadow[child.id];
delete idToInstantiator[child.id];
}
delete that.pathToComponent[childPath]; // there may be no entry - if created informally
if (!noModTree) {
delete component[name]; // there may be no entry - if creation is not concluded
}
};
return that;
};
// An instantiator to be used in the "free environment", unattached to any component tree
fluid.freeInstantiator = fluid.instantiator(true);
// Look up the globally registered instantiator for a particular component
fluid.getInstantiator = function (component) {
return component && idToInstantiator[component.id] || fluid.freeInstantiator;
};
/** Expand a set of component options either immediately, or with deferred effect.
* The current policy is to expand immediately function arguments within fluid.embodyDemands which are not the main options of a
* component. The component's own options take <code>{defer: true}</code> as part of
* <code>outerExpandOptions</code> which produces an "expandOptions" structure holding the "strategy" and "initter" pattern
* common to ginger participants.
* Probably not to be advertised as part of a public API, but is considerably more stable than most of the rest
* of the IoC API structure especially with respect to the first arguments.
*/
fluid.expandOptions = function (args, that, mergePolicy, localRecord, outerExpandOptions) {
if (!args) {
return args;
}
fluid.pushActivity("expandOptions", "expanding options %args for component %that ", {that: that, args: args});
var expandOptions = fluid.makeStackResolverOptions(that, localRecord);
expandOptions.mergePolicy = mergePolicy;
var expanded = outerExpandOptions && outerExpandOptions.defer ?
fluid.makeExpandOptions(args, expandOptions) : fluid.expand(args, expandOptions);
fluid.popActivity();
return expanded;
};
// unsupported, non-API function
fluid.localRecordExpected = ["type", "options", "args", "mergeOptions", "createOnEvent", "priority", "recordType"]; // last element unavoidably polluting
// unsupported, non-API function
fluid.checkComponentRecord = function (defaults, localRecord) {
var expected = fluid.arrayToHash(fluid.localRecordExpected);
fluid.each(defaults && defaults.argumentMap, function(value, key) {
expected[key] = true;
});
fluid.each(localRecord, function (value, key) {
if (!expected[key]) {
fluid.fail("Probable error in subcomponent record - key \"" + key +
"\" found, where the only legal options are " +
fluid.keys(expected).join(", "));
}
});
};
// unsupported, non-API function
fluid.pushDemands = function (list, demands) {
demands = fluid.makeArray(demands);
var thisp = fluid.mergeRecordTypes.demands;
function push(rec) {
rec.recordType = "demands";
rec.priority = thisp++;
list.push(rec);
}
// Assume these are sorted at source by intersect count (can't pre-merge if we want "mergeOptions")
for (var i = 0; i < demands.length; ++ i) {
var thisd = demands[i];
if (thisd.options) {
push(thisd);
}
else if (thisd.mergeOptions) {
var mergeOptions = fluid.makeArray(thisd.mergeOptions);
fluid.each(mergeOptions, function (record) { push ({options: record}); });
}
else {
fluid.fail("Uninterpretable demands record without options or mergeOptions ", thisd);
}
}
};
// unsupported, non-API function
fluid.mergeRecordsToList = function (mergeRecords) {
var list = [];
fluid.each(mergeRecords, function (value, key) {
value.recordType = key;
if (key === "distributions") {
list.push.apply(list, value);
}
else if (key !== "demands") {
if (!value.options) { return; }
value.priority = fluid.mergeRecordTypes[key];
if (value.priority === undefined) {
fluid.fail("Merge record with unrecognised type " + key + ": ", value);
}
list.push(value);
}
else {
fluid.pushDemands(list, value);
}
});
return list;
};
// TODO: overall efficiency could huge be improved by resorting to the hated PROTOTYPALISM as an optimisation
// for this mergePolicy which occurs in every component. Although it is a deep structure, the root keys are all we need
var addPolicyBuiltins = function (policy) {
fluid.each(["gradeNames", "mergePolicy", "argumentMap", "components", "dynamicComponents", "members", "invokers", "events", "listeners", "distributeOptions", "transformOptions"], function (key) {
fluid.set(policy, [key, "*", "noexpand"], true);
});
return policy;
};
// unsupported, NON-API function - used from Fluid.js
fluid.generateExpandBlock = function (record, that, mergePolicy, localRecord) {
var expanded = fluid.expandOptions(record.options, record.contextThat || that, mergePolicy, localRecord, {defer: true});
expanded.priority = record.priority;
expanded.recordType = record.recordType;
return expanded;
};
var expandComponentOptionsImpl = function (mergePolicy, defaults, userOptions, that) {
var defaultCopy = fluid.copy(defaults);
addPolicyBuiltins(mergePolicy);
var shadow = fluid.shadowForComponent(that);
shadow.mergePolicy = mergePolicy;
var mergeRecords = {
defaults: {options: defaultCopy}
};
if (userOptions) {
if (userOptions.marker === fluid.EXPAND) {
$.extend(mergeRecords, userOptions.mergeRecords);
// Do this here for gradeless components that were corrected by "localOptions"
if (mergeRecords.subcomponentRecord) {
fluid.checkComponentRecord(defaults, mergeRecords.subcomponentRecord);
}
}
else {
mergeRecords.user = {options: userOptions};
}
}
var expandList = fluid.mergeRecordsToList(mergeRecords);
var togo = fluid.transform(expandList, function (value) {
return fluid.generateExpandBlock(value, that, mergePolicy, userOptions && userOptions.localRecord);
});
return togo;
};
// unsupported, non-API function
fluid.expandComponentOptions = function (mergePolicy, defaults, userOptions, that) {
var instantiator = userOptions && userOptions.marker === fluid.EXPAND && userOptions.memberName !== undefined ?
userOptions.instantiator : null;
var fresh;
if (!instantiator) {
instantiator = fluid.instantiator();
fresh = true;
fluid.log("Created new instantiator with id " + instantiator.id + " in order to operate on component " + (that? that.typeName : "[none]"));
}
fluid.pushActivity("expandComponentOptions", "expanding component options %options with record %record for component %that",
{options: userOptions && userOptions.mergeRecords, record: userOptions, that: that});
if (fresh) {
instantiator.recordRoot(that);
}
else {
instantiator.recordKnownComponent(userOptions.parentThat, that, userOptions.memberName, true);
}
var togo = expandComponentOptionsImpl(mergePolicy, defaults, userOptions, that);
fluid.popActivity();
return togo;
};
// unsupported, non-API function
fluid.argMapToDemands = function (argMap) {
var togo = [];
fluid.each(argMap, function (value, key) {
togo[value] = "{" + key + "}";
});
return togo;
};
// unsupported, non-API function
fluid.makePassArgsSpec = function (initArgs) {
return fluid.transform(initArgs, function(arg, index) {
return "{arguments}." + index;
});
};
// unsupported, NON-API function
fluid.pushDemandSpec = function (record, options, mergeOptions) {
if (options && options !== "{options}") {
record.push({options: options});
}
if (mergeOptions) {
record.push({mergeOptions: mergeOptions});
}
};
/** Given a concrete argument list and/or options, determine the final concrete
* "invocation specification" which is coded by the supplied demandspec in the
* environment "thatStack" - the return is a package of concrete global function name
* and argument list which is suitable to be executed directly by fluid.invokeGlobalFunction.
*/
// unsupported, non-API function
// options is just a disposition record containing memberName, componentRecord + passArgs
// various built-in effects of this method
// i) note that it makes no effort to actually propagate direct
// options from "initArgs", assuming that they will be seen again in expandComponentOptions
fluid.embodyDemands = function (parentThat, demandspec, initArgs, options) {
options = options || {};
if (demandspec.mergeOptions && demandspec.options) {
fluid.fail("demandspec ", demandspec,
" is invalid - cannot specify literal options together with mergeOptions");
}
if (demandspec.transformOptions) { // Support for "transformOptions" at top level in a demands record
demandspec.options = $.extend(true, {}, demandspec.options, {
transformOptions: demandspec.transformOptions
});
}
var demands = fluid.makeArray(demandspec.args);
var upDefaults = fluid.defaults(demandspec.funcName);
var distributions = upDefaults && parentThat ? fluid.receiveDistributions(parentThat, upDefaults.gradeNames, options.memberName) : [];
var argMap = upDefaults? upDefaults.argumentMap : null;
var inferMap = false;
if (!argMap && (upDefaults || (options && options.componentRecord)) && !options.passArgs) {
inferMap = true;
// infer that it must be a little component if we have any reason to believe it is a component
if (demands.length < 2) {
argMap = fluid.rawDefaults("fluid.littleComponent").argumentMap;
}
else {
var optionpos = $.inArray("{options}", demands);
if (optionpos === -1) {
optionpos = demands.length - 1; // wild guess in the old style
}
argMap = {options: optionpos};
}
}
options = options || {};
if (demands.length === 0) {
if (argMap) {
demands = fluid.argMapToDemands(argMap);
}
else if (options.passArgs) {
demands = fluid.makePassArgsSpec(initArgs);
}
}
// confusion remains with "localRecord" - it is a random mishmash of user arguments and the component record
// this should itself be absorbed into "mergeRecords" and let stackFetcher sort it out
var localRecord = $.extend({"arguments": initArgs}, fluid.censorKeys(options.componentRecord, ["type"]));
var shadow = fluid.shadowForComponent(parentThat);
var localDynamic = shadow && options.memberName ? shadow.subcomponentLocal[options.memberName] : null;
fluid.each(argMap, function (index, name) {
// this is incorrect anyway! What if the supplied arguments were not in the same order as the target argmap,
// which was obtained from the target defaults
if (initArgs.length > 0) {
localRecord[name] = localRecord["arguments"][index];