/
Fluid.js
2884 lines (2588 loc) · 128 KB
/
Fluid.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
/*!
* Fluid Infusion v3.0.0
*
* Infusion is distributed under the Educational Community License 2.0 and new BSD licenses:
* http://wiki.fluidproject.org/display/fluid/Fluid+Licensing
*
* For information on copyright, see the individual Infusion source code files:
* https://github.com/fluid-project/infusion/
*/
/*
Copyright 2007-2010 University of Cambridge
Copyright 2007-2009 University of Toronto
Copyright 2007-2009 University of California, Berkeley
Copyright 2010-2011 Lucendo Development Ltd.
Copyright 2010-2015 OCAD University
Copyright 2011 Charly Molter
Copyright 2012-2014 Raising the Floor - US
Copyright 2014-2016 Raising the Floor - International
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
Includes code from Underscore.js 1.4.3
http://underscorejs.org
(c) 2009-2012 Jeremy Ashkenas, DocumentCloud Inc.
Underscore may be freely distributed under the MIT license.
*/
/* global console */
var fluid_3_0_0 = fluid_3_0_0 || {};
var fluid = fluid || fluid_3_0_0;
(function ($, fluid) {
"use strict";
fluid.version = "Infusion 3.0.0";
// Export this for use in environments like node.js, where it is useful for
// configuring stack trace behaviour
fluid.Error = Error;
fluid.environment = {
fluid: fluid
};
fluid.global = fluid.global || typeof window !== "undefined" ?
window : typeof self !== "undefined" ? self : {};
// A standard utility to schedule the invocation of a function after the current
// stack returns. On browsers this defaults to setTimeout(func, 1) but in
// other environments can be customised - e.g. to process.nextTick in node.js
// In future, this could be optimised in the browser to not dispatch into the event queue
fluid.invokeLater = function (func) {
return setTimeout(func, 1);
};
// The following flag defeats all logging/tracing activities in the most performance-critical parts of the framework.
// This should really be performed by a build-time step which eliminates calls to pushActivity/popActivity and fluid.log.
fluid.defeatLogging = true;
// This flag enables the accumulating of all "activity" records generated by pushActivity into a running trace, rather
// than removing them from the stack record permanently when receiving popActivity. This trace will be consumed by
// visual debugging tools.
fluid.activityTracing = false;
fluid.activityTrace = [];
var activityParser = /(%\w+)/g;
// Renders a single activity element in a form suitable to be sent to a modern browser's console
// unsupported, non-API function
fluid.renderOneActivity = function (activity, nowhile) {
var togo = nowhile === true ? [] : [" while "];
var message = activity.message;
var index = activityParser.lastIndex = 0;
while (true) {
var match = activityParser.exec(message);
if (match) {
var key = match[1].substring(1);
togo.push(message.substring(index, match.index));
togo.push(activity.args[key]);
index = activityParser.lastIndex;
}
else {
break;
}
}
if (index < message.length) {
togo.push(message.substring(index));
}
return togo;
};
// Renders an activity stack in a form suitable to be sent to a modern browser's console
// unsupported, non-API function
fluid.renderActivity = function (activityStack, renderer) {
renderer = renderer || fluid.renderOneActivity;
return fluid.transform(activityStack, renderer);
};
// Definitions for ThreadLocals - lifted here from
// FluidIoC.js so that we can issue calls to fluid.describeActivity for debugging purposes
// in the core framework
// unsupported, non-API function
fluid.singleThreadLocal = function (initFunc) {
var value = initFunc();
return function (newValue) {
return newValue === undefined ? value : value = newValue;
};
};
// Currently we only support single-threaded environments - ensure that this function
// is not used on startup so it can be successfully monkey-patched
// only remaining uses of threadLocals are for activity reporting and in the renderer utilities
// unsupported, non-API function
fluid.threadLocal = fluid.singleThreadLocal;
// unsupported, non-API function
fluid.globalThreadLocal = fluid.threadLocal(function () {
return {};
});
// Return an array of objects describing the current activity
// unsupported, non-API function
fluid.getActivityStack = function () {
var root = fluid.globalThreadLocal();
if (!root.activityStack) {
root.activityStack = [];
}
return root.activityStack;
};
// Return an array of objects describing the current activity
// unsupported, non-API function
fluid.describeActivity = fluid.getActivityStack;
// Renders either the current activity or the supplied activity to the console
fluid.logActivity = function (activity) {
activity = activity || fluid.describeActivity();
var rendered = fluid.renderActivity(activity).reverse();
fluid.log("Current activity: ");
fluid.each(rendered, function (args) {
fluid.doLog(args);
});
};
// Execute the supplied function with the specified activity description pushed onto the stack
// unsupported, non-API function
fluid.pushActivity = function (type, message, args) {
var record = {type: type, message: message, args: args, time: new Date().getTime()};
if (fluid.activityTracing) {
fluid.activityTrace.push(record);
}
if (fluid.passLogLevel(fluid.logLevel.TRACE)) {
fluid.doLog(fluid.renderOneActivity(record, true));
}
var activityStack = fluid.getActivityStack();
activityStack.push(record);
};
// Undo the effect of the most recent pushActivity, or multiple frames if an argument is supplied
fluid.popActivity = function (popframes) {
popframes = popframes || 1;
if (fluid.activityTracing) {
fluid.activityTrace.push({pop: popframes});
}
var activityStack = fluid.getActivityStack();
var popped = activityStack.length - popframes;
activityStack.length = popped < 0 ? 0 : popped;
};
// "this-ist" style Error so that we can distinguish framework errors whilst still retaining access to platform Error features
// Solution taken from http://stackoverflow.com/questions/8802845/inheriting-from-the-error-object-where-is-the-message-property#answer-17936621
fluid.FluidError = function (/*message*/) {
var togo = Error.apply(this, arguments);
this.message = togo.message;
try { // This technique is necessary on IE11 since otherwise the stack entry is not filled in
throw togo;
} catch (togo) {
this.stack = togo.stack;
}
return this;
};
fluid.FluidError.prototype = Object.create(Error.prototype);
// The framework's built-in "log" failure handler - this logs the supplied message as well as any framework activity in progress via fluid.log
fluid.logFailure = function (args, activity) {
fluid.log.apply(null, [fluid.logLevel.FAIL, "ASSERTION FAILED: "].concat(args));
fluid.logActivity(activity);
};
fluid.renderLoggingArg = function (arg) {
return arg === undefined ? "undefined" : fluid.isPrimitive(arg) || !fluid.isPlainObject(arg) ? arg : JSON.stringify(arg);
};
// The framework's built-in "fail" failure handler - this throws an exception of type <code>fluid.FluidError</code>
fluid.builtinFail = function (args /*, activity*/) {
var message = fluid.transform(args, fluid.renderLoggingArg).join("");
throw new fluid.FluidError("Assertion failure - check console for more details: " + message);
};
/**
* Signals an error to the framework. The default behaviour is to log a structured error message and throw an exception. This strategy may be configured using the legacy
* API <code>fluid.pushSoftFailure</code> or else by adding and removing suitably namespaced listeners to the special event <code>fluid.failureEvent</code>
*
* @param {String} message the error message to log
* @param ... Additional arguments, suitable for being sent to the native console.log function
*/
fluid.fail = function (/* message, ... */) {
var args = fluid.makeArray(arguments);
var activity = fluid.makeArray(fluid.describeActivity()); // Take copy since we will destructively modify
fluid.popActivity(activity.length); // clear any current activity - TODO: the framework currently has no exception handlers, although it will in time
if (fluid.failureEvent) { // notify any framework failure prior to successfully setting up the failure event below
fluid.failureEvent.fire(args, activity);
} else {
fluid.logFailure(args, activity);
fluid.builtinFail(args, activity);
}
};
// TODO: rescued from kettleCouchDB.js - clean up in time
fluid.expect = function (name, target, members) {
fluid.transform(fluid.makeArray(members), function (key) {
if (typeof target[key] === "undefined") {
fluid.fail(name + " missing required parameter " + key);
}
});
};
// Logging
/** Returns whether logging is enabled **/
fluid.isLogging = function () {
return logLevelStack[0].priority > fluid.logLevel.IMPORTANT.priority;
};
/** Determines whether the supplied argument is a valid logLevel marker **/
fluid.isLogLevel = function (arg) {
return fluid.isMarker(arg) && arg.priority !== undefined;
};
/** Accepts one of the members of the <code>fluid.logLevel</code> structure. Returns <code>true</code> if
* a message supplied at that log priority would be accepted at the current logging level. Clients who
* issue particularly expensive log payload arguments are recommended to guard their logging statements with this
* function */
fluid.passLogLevel = function (testLogLevel) {
return testLogLevel.priority <= logLevelStack[0].priority;
};
/** Method to allow user to control the logging level. Accepts either a boolean, for which <code>true</code>
* represents <code>fluid.logLevel.INFO</code> and <code>false</code> represents <code>fluid.logLevel.IMPORTANT</code> (the default),
* or else any other member of the structure <code>fluid.logLevel</code>
* Messages whose priority is strictly less than the current logging level will not be shown*/
fluid.setLogging = function (enabled) {
var logLevel;
if (typeof enabled === "boolean") {
logLevel = fluid.logLevel[enabled ? "INFO" : "IMPORTANT"];
} else if (fluid.isLogLevel(enabled)) {
logLevel = enabled;
} else {
fluid.fail("Unrecognised fluid logging level ", enabled);
}
logLevelStack.unshift(logLevel);
fluid.defeatLogging = !fluid.isLogging();
};
fluid.setLogLevel = fluid.setLogging;
/** Undo the effect of the most recent "setLogging", returning the logging system to its previous state **/
fluid.popLogging = function () {
var togo = logLevelStack.length === 1 ? logLevelStack[0] : logLevelStack.shift();
fluid.defeatLogging = !fluid.isLogging();
return togo;
};
/** Actually do the work of logging <code>args</code> to the environment's console. If the standard "console"
* stream is available, the message will be sent there.
*/
fluid.doLog = function (args) {
if (typeof (console) !== "undefined") {
if (console.debug) {
console.debug.apply(console, args);
} else if (typeof (console.log) === "function") {
console.log.apply(console, args);
}
}
};
/** Log a message to a suitable environmental console. If the first argument to fluid.log is
* one of the members of the <code>fluid.logLevel</code> structure, this will be taken as the priority
* of the logged message - else if will default to <code>fluid.logLevel.INFO</code>. If the logged message
* priority does not exceed that set by the most recent call to the <code>fluid.setLogging</code> function,
* the message will not appear.
*/
fluid.log = function (/* message /*, ... */) {
var directArgs = fluid.makeArray(arguments);
var userLogLevel = fluid.logLevel.INFO;
if (fluid.isLogLevel(directArgs[0])) {
userLogLevel = directArgs.shift();
}
if (fluid.passLogLevel(userLogLevel)) {
var arg0 = fluid.renderTimestamp(new Date()) + ": ";
var args = [arg0].concat(directArgs);
fluid.doLog(args);
}
};
// Functional programming utilities.
// Type checking functions
/** Returns true if the argument is a value other than null or undefined **/
fluid.isValue = function (value) {
return value !== undefined && value !== null;
};
/** Returns true if the argument is a primitive type **/
fluid.isPrimitive = function (value) {
var valueType = typeof (value);
return !value || valueType === "string" || valueType === "boolean" || valueType === "number" || valueType === "function";
};
/** Determines whether the supplied object is an array. The strategy used is an optimised
* approach taken from an earlier version of jQuery - detecting whether the toString() version
* of the object agrees with the textual form [object Array], or else whether the object is a
* jQuery object (the most common source of "fake arrays").
*/
fluid.isArrayable = function (totest) {
return totest && (totest.jquery || Object.prototype.toString.call(totest) === "[object Array]");
};
/** Determines whether the supplied object is a plain JSON-forming container - that is, it is either a plain Object
* or a plain Array. Note that this differs from jQuery's isPlainObject which does not pass Arrays.
* @param totest {Any} The object to be tested
* @param strict {Boolean} (optional) If `true`, plain Arrays will fail the test rather than passing.
*/
fluid.isPlainObject = function (totest, strict) {
var string = Object.prototype.toString.call(totest);
if (string === "[object Array]") {
return !strict;
} else if (string !== "[object Object]") {
return false;
} // FLUID-5226: This inventive strategy taken from jQuery detects whether the object's prototype is directly Object.prototype by virtue of having an "isPrototypeOf" direct member
return !totest.constructor || !totest.constructor.prototype || Object.prototype.hasOwnProperty.call(totest.constructor.prototype, "isPrototypeOf");
};
/** Returns <code>primitive</code>, <code>array</code> or <code>object</code> depending on whether the supplied object has
* one of those types, by use of the <code>fluid.isPrimitive</code>, <code>fluid.isPlainObject</code> and <code>fluid.isArrayable</code> utilities
*/
fluid.typeCode = function (totest) {
return fluid.isPrimitive(totest) || !fluid.isPlainObject(totest) ? "primitive" :
fluid.isArrayable(totest) ? "array" : "object";
};
fluid.isIoCReference = function (ref) {
return typeof(ref) === "string" && ref.charAt(0) === "{" && ref.indexOf("}") > 0;
};
fluid.isDOMNode = function (obj) {
// This could be more sound, but messy:
// http://stackoverflow.com/questions/384286/javascript-isdom-how-do-you-check-if-a-javascript-object-is-a-dom-object
// The real problem is browsers like IE6, 7 and 8 which still do not feature a "constructor" property on DOM nodes
return obj && typeof (obj.nodeType) === "number";
};
fluid.isComponent = function (obj) {
return obj && obj.constructor === fluid.componentConstructor;
};
fluid.isUncopyable = function (totest) {
return fluid.isPrimitive(totest) || !fluid.isPlainObject(totest);
};
fluid.isApplicable = function (totest) {
return totest.apply && typeof(totest.apply) === "function";
};
/** A basic utility that returns its argument unchanged */
fluid.identity = function (arg) {
return arg;
};
/** A function which raises a failure if executed */
fluid.notImplemented = function () {
fluid.fail("This operation is not implemented");
};
/** Returns the first of its arguments if it is not `undefined`, otherwise returns the second.
* @param a {Any} The first argument to be tested for being `undefined`
* @param b {Any} The fallback argument, to be returned if `a` is `undefined`
* @return {Any} `a` if it is not `undefined`, else `b`.
*/
fluid.firstDefined = function (a, b) {
return a === undefined ? b : a;
};
/** Return an empty container as the same type as the argument (either an
* array or hash */
fluid.freshContainer = function (tocopy) {
return fluid.isArrayable(tocopy) ? [] : {};
};
fluid.copyRecurse = function (tocopy, segs) {
if (segs.length > fluid.strategyRecursionBailout) {
fluid.fail("Runaway recursion encountered in fluid.copy - reached path depth of " + fluid.strategyRecursionBailout + " via path of " + segs.join(".") +
"this object is probably circularly connected. Either adjust your object structure to remove the circularity or increase fluid.strategyRecursionBailout");
}
if (fluid.isUncopyable(tocopy)) {
return tocopy;
} else {
return fluid.transform(tocopy, function (value, key) {
segs.push(key);
var togo = fluid.copyRecurse(value, segs);
segs.pop();
return togo;
});
}
};
/** Performs a deep copy (clone) of its argument. This will guard against cloning a circular object by terminating if it reaches a path depth
* greater than <code>fluid.strategyRecursionBailout</code>
**/
fluid.copy = function (tocopy) {
return fluid.copyRecurse(tocopy, []);
};
// TODO: Coming soon - reimplementation of $.extend using strategyRecursionBailout
fluid.extend = $.extend;
/** Corrected version of jQuery makeArray that returns an empty array on undefined rather than crashing.
* We don't deal with as many pathological cases as jQuery **/
fluid.makeArray = function (arg) {
var togo = [];
if (arg !== null && arg !== undefined) {
if (fluid.isPrimitive(arg) || fluid.isPlainObject(arg, true) || typeof(arg.length) !== "number") {
togo.push(arg);
}
else {
for (var i = 0; i < arg.length; ++i) {
togo[i] = arg[i];
}
}
}
return togo;
};
/** Pushes an element or elements onto an array, initialising the array as a member of a holding object if it is
* not already allocated.
* @param holder {Array or Object} The holding object whose member is to receive the pushed element(s).
* @param member {String} The member of the <code>holder</code> onto which the element(s) are to be pushed
* @param topush {Array or Object} If an array, these elements will be added to the end of the array using Array.push.apply. If an object, it will be pushed to the end of the array using Array.push.
*/
fluid.pushArray = function (holder, member, topush) {
var array = holder[member] ? holder[member] : (holder[member] = []);
if (fluid.isArrayable(topush)) {
array.push.apply(array, topush);
} else {
array.push(topush);
}
};
function transformInternal(source, togo, key, args) {
var transit = source[key];
for (var j = 0; j < args.length - 1; ++j) {
transit = args[j + 1](transit, key);
}
togo[key] = transit;
}
/** Return an array or hash of objects, transformed by one or more functions. Similar to
* jQuery.map, only will accept an arbitrary list of transformation functions and also
* works on non-arrays.
* @param source {Array or Object} The initial container of objects to be transformed. If the source is
* neither an array nor an object, it will be returned untransformed
* @param fn1, fn2, etc. {Function} An arbitrary number of optional further arguments,
* all of type Function, accepting the signature (object, index), where object is the
* structure member to be transformed, and index is its key or index. Each function will be
* applied in turn to each structure member, which will be replaced by the return value
* from the function.
* @return The finally transformed list, where each member has been replaced by the
* original member acted on by the function or functions.
*/
fluid.transform = function (source) {
if (fluid.isPrimitive(source)) {
return source;
}
var togo = fluid.freshContainer(source);
if (fluid.isArrayable(source)) {
for (var i = 0; i < source.length; ++i) {
transformInternal(source, togo, i, arguments);
}
} else {
for (var key in source) {
transformInternal(source, togo, key, arguments);
}
}
return togo;
};
/** Better jQuery.each which works on hashes as well as having the arguments
* the right way round.
* @param source {Arrayable or Object} The container to be iterated over
* @param func {Function} A function accepting (value, key) for each iterated
* object.
*/
fluid.each = function (source, func) {
if (fluid.isArrayable(source)) {
for (var i = 0; i < source.length; ++i) {
func(source[i], i);
}
} else {
for (var key in source) {
func(source[key], key);
}
}
};
fluid.make_find = function (find_if) {
var target = find_if ? false : undefined;
return function (source, func, deffolt) {
var disp;
if (fluid.isArrayable(source)) {
for (var i = 0; i < source.length; ++i) {
disp = func(source[i], i);
if (disp !== target) {
return find_if ? source[i] : disp;
}
}
} else {
for (var key in source) {
disp = func(source[key], key);
if (disp !== target) {
return find_if ? source[key] : disp;
}
}
}
return deffolt;
};
};
/** Scan through an array or hash of objects, terminating on the first member which
* matches a predicate function.
* @param source {Arrayable or Object} The array or hash of objects to be searched.
* @param func {Function} A predicate function, acting on a member. A predicate which
* returns any value which is not <code>undefined</code> will terminate
* the search. The function accepts (object, index).
* @param deflt {Object} A value to be returned in the case no predicate function matches
* a structure member. The default will be the natural value of <code>undefined</code>
* @return The first return value from the predicate function which is not <code>undefined</code>
*/
fluid.find = fluid.make_find(false);
/** The same signature as fluid.find, only the return value is the actual element for which the
* predicate returns a value different from <code>false</code>
*/
fluid.find_if = fluid.make_find(true);
/** Scan through an array of objects, "accumulating" a value over them
* (may be a straightforward "sum" or some other chained computation). "accumulate" is the name derived
* from the C++ STL, other names for this algorithm are "reduce" or "fold".
* @param list {Array} The list of objects to be accumulated over.
* @param fn {Function} An "accumulation function" accepting the signature (object, total, index) where
* object is the list member, total is the "running total" object (which is the return value from the previous function),
* and index is the index number.
* @param arg {Object} The initial value for the "running total" object.
* @return {Object} the final running total object as returned from the final invocation of the function on the last list member.
*/
fluid.accumulate = function (list, fn, arg) {
for (var i = 0; i < list.length; ++i) {
arg = fn(list[i], arg, i);
}
return arg;
};
/** Returns the sum of its two arguments. A useful utility to combine with fluid.accumulate to compute totals
* @param a {Number|Boolean} The first operand to be added
* @param b {Number|Boolean} The second operand to be added
* @return {Number} The sum of the two operands
**/
fluid.add = function (a, b) {
return a + b;
};
/** Scan through an array or hash of objects, removing those which match a predicate. Similar to
* jQuery.grep, only acts on the list in-place by removal, rather than by creating
* a new list by inclusion.
* @param source {Array|Object} The array or hash of objects to be scanned over. Note that in the case this is an array,
* the iteration will proceed from the end of the array towards the front.
* @param fn {Function} A predicate function determining whether an element should be
* removed. This accepts the standard signature (object, index) and returns a "truthy"
* result in order to determine that the supplied object should be removed from the structure.
* @param target {Array|Object} (optional) A target object of the same type as <code>source</code>, which will
* receive any objects removed from it.
* @return <code>target</code>, containing the removed elements, if it was supplied, or else <code>source</code>
* modified by the operation of removing the matched elements.
*/
fluid.remove_if = function (source, fn, target) {
if (fluid.isArrayable(source)) {
for (var i = source.length - 1; i >= 0; --i) {
if (fn(source[i], i)) {
if (target) {
target.unshift(source[i]);
}
source.splice(i, 1);
}
}
} else {
for (var key in source) {
if (fn(source[key], key)) {
if (target) {
target[key] = source[key];
}
delete source[key];
}
}
}
return target || source;
};
/** Fills an array of given size with copies of a value or result of a function invocation
* @param n {Number} The size of the array to be filled
* @param generator {Object|Function} Either a value to be replicated or function to be called
* @param applyFunc {Boolean} If true, treat the generator value as a function to be invoked with
* argument equal to the index position
*/
fluid.generate = function (n, generator, applyFunc) {
var togo = [];
for (var i = 0; i < n; ++i) {
togo[i] = applyFunc ? generator(i) : generator;
}
return togo;
};
/** Returns an array of size count, filled with increasing integers, starting at 0 or at the index specified by first.
* @param count {Number} Size of the filled array to be returned
* @param first {Number} (optional, defaults to 0) First element to appear in the array
*/
fluid.iota = function (count, first) {
first = first || 0;
var togo = [];
for (var i = 0; i < count; ++i) {
togo[togo.length] = first++;
}
return togo;
};
/** Extracts a particular member from each top-level member of a container, returning a new container of the same type
* @param holder {Array|Object} The container to be filtered
* @param name {String|Array of String} An EL path to be fetched from each top-level member
*/
fluid.getMembers = function (holder, name) {
return fluid.transform(holder, function (member) {
return fluid.get(member, name);
});
};
/** Accepts an object to be filtered, and an array of keys. Either all keys not present in
* the array are removed, or only keys present in the array are returned.
* @param toFilter {Array|Object} The object to be filtered - this will be NOT modified by the operation (current implementation
* passes through $.extend shallow algorithm)
* @param keys {Array of String} The array of keys to operate with
* @param exclude {boolean} If <code>true</code>, the keys listed are removed rather than included
* @return the filtered object (the same object that was supplied as <code>toFilter</code>
*/
fluid.filterKeys = function (toFilter, keys, exclude) {
return fluid.remove_if($.extend({}, toFilter), function (value, key) {
return exclude ^ (keys.indexOf(key) === -1);
});
};
/** A convenience wrapper for <code>fluid.filterKeys</code> with the parameter <code>exclude</code> set to <code>true</code>
* Returns the supplied object with listed keys removed */
fluid.censorKeys = function (toCensor, keys) {
return fluid.filterKeys(toCensor, keys, true);
};
/** Return the keys in the supplied object as an array. Note that this will return keys found in the prototype chain as well as "own properties", unlike Object.keys() **/
fluid.keys = function (obj) {
var togo = [];
for (var key in obj) {
togo.push(key);
}
return togo;
};
/** Return the values in the supplied object as an array **/
fluid.values = function (obj) {
var togo = [];
for (var key in obj) {
togo.push(obj[key]);
}
return togo;
};
/**
* Searches through the supplied object, and returns <code>true</code> if the supplied value
* can be found
*/
fluid.contains = function (obj, value) {
return obj ? (fluid.isArrayable(obj) ? obj.indexOf(value) !== -1 : fluid.find(obj, function (thisValue) {
if (value === thisValue) {
return true;
}
})) : undefined;
};
/**
* Searches through the supplied object for the first value which matches the one supplied.
* @param obj {Object} the Object to be searched through
* @param value {Object} the value to be found. This will be compared against the object's
* member using === equality.
* @return {String} The first key whose value matches the one supplied
*/
fluid.keyForValue = function (obj, value) {
return fluid.find(obj, function (thisValue, key) {
if (value === thisValue) {
return key;
}
});
};
/** Converts an array into an object whose keys are the elements of the array, each with the value "true"
* @param array {Array of String} The array to be converted to a hash
* @return hash {Object} An object with value <code>true</code> for each key taken from a member of <code>array</code>
*/
fluid.arrayToHash = function (array) {
var togo = {};
fluid.each(array, function (el) {
togo[el] = true;
});
return togo;
};
/** Applies a stable sorting algorithm to the supplied array and comparator (note that Array.sort in JavaScript is not specified
* to be stable). The algorithm used will be an insertion sort, which whilst quadratic in time, will perform well
* on small array sizes.
* @param array {Array} The array to be sorted. This input array will be modified in place.
* @param func {Function} A comparator returning >0, 0, or <0 on pairs of elements representing their sort order (same contract as Array.sort comparator)
*/
fluid.stableSort = function (array, func) {
for (var i = 0; i < array.length; i++) {
var j, k = array[i];
for (j = i; j > 0 && func(k, array[j - 1]) < 0; j--) {
array[j] = array[j - 1];
}
array[j] = k;
}
};
/** Converts a hash into an object by hoisting out the object's keys into an array element via the supplied String "key", and then transforming via an optional further function, which receives the signature
* (newElement, oldElement, key) where newElement is the freshly cloned element, oldElement is the original hash's element, and key is the key of the element.
* If the function is not supplied, the old element is simply deep-cloned onto the new element (same effect as transform fluid.transforms.deindexIntoArrayByKey).
* The supplied hash will not be modified, unless the supplied function explicitly does so by modifying its 2nd argument.
*/
fluid.hashToArray = function (hash, keyName, func) {
var togo = [];
fluid.each(hash, function (el, key) {
var newEl = {};
newEl[keyName] = key;
if (func) {
newEl = func(newEl, el, key) || newEl;
} else {
$.extend(true, newEl, el);
}
togo.push(newEl);
});
return togo;
};
/** Converts an array consisting of a mixture of arrays and non-arrays into the concatenation of any inner arrays
* with the non-array elements
*/
fluid.flatten = function (array) {
var togo = [];
fluid.each(array, function (element) {
if (fluid.isArrayable(element)) {
togo = togo.concat(element);
} else {
togo.push(element);
}
});
return togo;
};
/**
* Clears an object or array of its contents. For objects, each property is deleted.
*
* @param {Object|Array} target the target to be cleared
*/
fluid.clear = function (target) {
if (fluid.isArrayable(target)) {
target.length = 0;
} else {
for (var i in target) {
delete target[i];
}
}
};
/**
* @param boolean ascending <code>true</code> if a comparator is to be returned which
* sorts strings in descending order of length
*/
fluid.compareStringLength = function (ascending) {
return ascending ? function (a, b) {
return a.length - b.length;
} : function (a, b) {
return b.length - a.length;
};
};
/**
* Returns the converted integer if the input string can be converted to an integer. Otherwise, return NaN.
* @param {String} a string to be returned in integer
*/
fluid.parseInteger = function (string) {
return isFinite(string) && ((string % 1) === 0) ? Number(string) : NaN;
};
/**
* Derived from Sindre Sorhus's round-to node module ( https://github.com/sindresorhus/round-to ).
* License: MIT
*
* Rounds the supplied number to at most the number of decimal places indicated by the scale, omitting any trailing 0s.
* There are three possible rounding methods described below: "round", "ceil", "floor"
* Round: Numbers are rounded away from 0 (i.e 0.5 -> 1, -0.5 -> -1).
* Ceil: Numbers are rounded up
* Floor: Numbers are rounded down
* If the scale is invalid (i.e falsey, not a number, negative value), it is treated as 0.
* If the scale is a floating point number, it is rounded to an integer.
*
* @param {Number} num - the number to be rounded
* @param {Number} scale - the maximum number of decimal places to round to.
* @param {String} method - (optional) Request a rounding method to use ("round", "ceil", "floor").
* If nothing or an invalid method is provided, it will default to "round".
* @return {Number} The num value rounded to the specified number of decimal places.
*/
fluid.roundToDecimal = function (num, scale, method) {
// treat invalid scales as 0
scale = scale && scale >= 0 ? Math.round(scale) : 0;
if (method === "ceil" || method === "floor") {
// The following is derived from https://github.com/sindresorhus/round-to/blob/v2.0.0/index.js#L20
return Number(Math[method](num + "e" + scale) + "e-" + scale);
} else {
// The following is derived from https://github.com/sindresorhus/round-to/blob/v2.0.0/index.js#L17
var sign = num >= 0 ? 1 : -1; // manually calculating the sign because Math.sign is not supported in IE
return Number(sign * (Math.round(Math.abs(num) + "e" + scale) + "e-" + scale));
}
};
/**
* Copied from Underscore.js 1.4.3 - see licence at head of this file
*
* Will execute the passed in function after the specified about of time since it was last executed.
* @param {Function} func - the function to execute
* @param {Number} wait - the number of milliseconds to wait before executing the function
* @param {Boolean} immediate - Whether to trigger the function at the start (true) or end (false) of
* the wait interval.
*/
fluid.debounce = function (func, wait, immediate) {
var timeout, result;
return function () {
var context = this, args = arguments;
var later = function () {
timeout = null;
if (!immediate) {
result = func.apply(context, args);
}
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) {
result = func.apply(context, args);
}
return result;
};
};
/** Calls Object.freeze at each level of containment of the supplied object
* @return The supplied argument, recursively frozen
*/
fluid.freezeRecursive = function (tofreeze) {
if (fluid.isPlainObject(tofreeze)) {
fluid.each(tofreeze, function (value) {
fluid.freezeRecursive(value);
});
return Object.freeze(tofreeze);
} else {
return tofreeze;
}
};
/** A set of special "marker values" used in signalling in function arguments and return values,
* to partially compensate for JavaScript's lack of distinguished types. These should never appear
* in JSON structures or other kinds of static configuration. An API specifically documents if it
* accepts or returns any of these values, and if so, what its semantic is - most are of private
* use internal to the framework **/
fluid.marker = function () {};
fluid.makeMarker = function (value, extra) {
var togo = Object.create(fluid.marker.prototype);
togo.value = value;
$.extend(togo, extra);
return Object.freeze(togo);
};
/** A special "marker object" representing that a distinguished
* (probably context-dependent) value should be substituted.
*/
fluid.VALUE = fluid.makeMarker("VALUE");
/** A special "marker object" representing that no value is present (where
* signalling using the value "undefined" is not possible - e.g. the return value from a "strategy") */
fluid.NO_VALUE = fluid.makeMarker("NO_VALUE");
/** A marker indicating that a value requires to be expanded after component construction begins **/
fluid.EXPAND = fluid.makeMarker("EXPAND");
/** Determine whether an object is any marker, or a particular marker - omit the
* 2nd argument to detect any marker
*/
fluid.isMarker = function (totest, type) {
if (!(totest instanceof fluid.marker)) {
return false;
}
if (!type) {
return true;
}
return totest.value === type.value;
};
fluid.logLevelsSpec = {
"FATAL": 0,
"FAIL": 5,
"WARN": 10,
"IMPORTANT": 12, // The default logging "off" level - corresponds to the old "false"
"INFO": 15, // The default logging "on" level - corresponds to the old "true"
"TRACE": 20
};
/** A structure holding all supported log levels as supplied as a possible first argument to fluid.log
* Members with a higher value of the "priority" field represent lower priority logging levels */
// Moved down here since it uses fluid.transform and fluid.makeMarker on startup
fluid.logLevel = fluid.transform(fluid.logLevelsSpec, function (value, key) {
return fluid.makeMarker(key, {priority: value});
});
var logLevelStack = [fluid.logLevel.IMPORTANT]; // The stack of active logging levels, with the current level at index 0
// Model functions
fluid.model = {}; // cannot call registerNamespace yet since it depends on fluid.model
/** Copy a source "model" onto a target **/
fluid.model.copyModel = function (target, source) {
fluid.clear(target);
$.extend(true, target, source);
};
/** Parse an EL expression separated by periods (.) into its component segments.
* @param {String} EL The EL expression to be split
* @return {Array of String} the component path expressions.
* TODO: This needs to be upgraded to handle (the same) escaping rules (as RSF), so that
* path segments containing periods and backslashes etc. can be processed, and be harmonised
* with the more complex implementations in fluid.pathUtil(data binding).
*/
fluid.model.parseEL = function (EL) {
return EL === "" ? [] : String(EL).split(".");
};
/** Compose an EL expression from two separate EL expressions. The returned
* expression will be the one that will navigate the first expression, and then
* the second, from the value reached by the first. Either prefix or suffix may be
* the empty string **/
fluid.model.composePath = function (prefix, suffix) {
return prefix === "" ? suffix : (suffix === "" ? prefix : prefix + "." + suffix);
};
/** Compose any number of path segments, none of which may be empty **/
fluid.model.composeSegments = function () {
return fluid.makeArray(arguments).join(".");
};