UNPKG

infusion

Version:

Infusion is an application framework for developing flexible stuff with JavaScript

1,173 lines (1,021 loc) 501 kB
/*! infusion - v2.0.0 Thursday, December 8th, 2016, 3:58:15 PM branch: HEAD revision: 85a1ffe */ /*! * Fluid Infusion v2.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 */ /* global console */ var fluid_2_0_0 = fluid_2_0_0 || {}; var fluid = fluid || fluid_2_0_0; (function ($, fluid) { "use strict"; fluid.version = "Infusion 2.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 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) || 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); }; // TODO: This is not as clever an idea as we think it is - this typically inner-loop function will optimise badly due to closure fluid.makeFlatten = function (index) { return function (obj) { var togo = []; fluid.each(obj, function (/* value, key */) { togo.push(arguments[index]); }); return togo; }; }; /** 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 = fluid.makeFlatten(1); /** Return the values in the supplied object as an array **/ fluid.values = fluid.makeFlatten(0); /** * 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; }; /** 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("."); }; /** Returns the index of the last occurrence of the period character . in the supplied string */ fluid.lastDotIndex = function (path) { return path.lastIndexOf("."); }; /** Returns all of an EL path minus its final segment - if the path consists of just one segment, returns "" - * WARNING - this method does not follow escaping rules */ fluid.model.getToTailPath = function (path) { var lastdot = fluid.lastDotIndex(path); return lastdot === -1 ? "" : path.substring(0, lastdot); }; /** Returns the very last path component of an EL path * WARNING - this method does not follow escaping rules */ fluid.model.getTailPath = function (path) { var lastdot = fluid.lastDotIndex(path); return path.substring(lastdot + 1); }; /** Helpful alias for old-style API **/ fluid.path = fluid.model.composeSegments; fluid.composePath = fluid.model.composePath; // unsupported, NON-API function fluid.requireDataBinding = function () { fluid.fail("Please include DataBinding.js in order to operate complex model accessor configuration"); }; fluid.model.setWithStrategy = fluid.model.getWithStrategy = fluid.requireDataBinding; // unsupported, NON-API function fluid.model.resolvePathSegment = function (root, segment, create, origEnv) { if (!origEnv && root.resolvePathSegment) { return root.resolvePathSegment(segment); } if (create && root[segment] === undefined) { // This optimisation in this heavily used function has a fair effect return root[segment] = {}; } return root[segment]; }; // unsupported, NON-API function fluid.model.parseToSegments = function (EL, parseEL, copy) { return typeof(EL) === "number" || typeof(EL) === "string" ? parseEL(EL) : (copy ? fluid.makeArray(EL) : EL); }; // unsupported, NON-API function fluid.model.pathToSegments = function (EL, config) { var parser = config && config.parser ? config.parser.parse : fluid.model.parseEL; return fluid.model.parseToSegments(EL, parser); }; // Overall strategy skeleton for all implementations of fluid.get/set fluid.model.accessImpl = function (root, EL, newValue, config, initSegs, returnSegs, traverser) { var segs = fluid.model.pathToSegments(EL, config); var initPos = 0; if (initSegs) { initPos = initSegs.length; segs = initSegs.concat(segs); } var uncess = newValue === fluid.NO_VALUE ? 0 : 1; root = traverser(root, segs, initPos, config, uncess); if (newValue === fluid.NO_VALUE || newValue === fluid.VALUE) { // get or custom return returnSegs ? {root: root, segs: segs} : root; } else { // set root[segs[segs.length - 1]] = newValue; } }; // unsupported, NON-API function fluid.model.accessSimple = function (root, EL, newValue, environment, initSegs, returnSegs) { return fluid.model.accessImpl(root, EL, newValue, environment, initSegs, returnSegs, fluid.model.traverseSimple); }; // unsupported, NON-API function fluid.model.traverseSimple = function (root, segs, initPos, environment, uncess) { var origEnv = environment; var limit = segs.length - uncess; for (var i = 0; i < limit; ++i) { if (!root) { return root; } var segment = segs[i]; if (environment && environment[segment]) { root = environment[segment]; } else { root = fluid.model.resolvePathSegment(root, segment, uncess === 1, origEnv); } environment = null; } return root; }; fluid.model.setSimple = function (root, EL, newValue, environment, initSegs) { fluid.model.accessSimple(root, EL, newValue, environment, initSegs, false); }; /** Optimised version of fluid.get for uncustomised configurations **/ fluid.model.getSimple = function (root, EL, environment, initSegs) { if (EL === null || EL === undefined || EL.length === 0) { return root; } return fluid.model.accessSimple(root, EL, fluid.NO_VALUE, environment, initSegs, false); }; /** Even more optimised version which assumes segs are parsed and no configuration **/ fluid.getImmediate = function (root, segs, i) { var limit = (i === undefined ? segs.length : i + 1); for (var j = 0; j < limit; ++j) { root = root ? root[segs[j]] : undefined; } return root; }; // unsupported, NON-API function // Returns undefined to signal complex configuration which needs to be farmed out to DataBinding.js // any other return represents an environment value AND a simple configuration we can handle here fluid.decodeAccessorArg = function (arg3) { return (!arg3 || arg3 === fluid.model.defaultGetConfig || arg3 === fluid.model.defaultSetConfig) ? null : (arg3.type === "environment" ? arg3.value : undefined); }; fluid.set = function (root, EL, newValue, config, initSegs) { var env = fluid.decodeAccessorArg(config); if (env === undefined) { fluid.model.setWithStrategy(root, EL, newValue, config, initSegs); } else { fluid.model.setSimple(root, EL, newValue, env, initSegs); } }; /** Evaluates an EL expression by fetching a dot-separated list of members * recursively from a provided root. * @param root The root data structure in which the EL expression is to be evaluated * @param {string/array} EL The EL expression to be evaluated, or an array of path segments * @param config An optional configuration or environment structure which can customise the fetch operation * @return The fetched data value. */ fluid.get = function (root, EL, config, initSegs) { var env = fluid.decodeAccessorArg(config); return env === undefined ? fluid.model.getWithStrategy(root, EL, config, initSegs) : fluid.model.accessImpl(root, EL, fluid.NO_VALUE, env, null, false, fluid.model.traverseSimple); }; fluid.getGlobalValue = function (path, env) { if (path) { env = env || fluid.environment; return fluid.get(fluid.global, path, {type: "environment", value: env}); } }; /** * Allows for the binding to a "this-ist" function * @param {Object} obj, "this-ist" object to bind to * @param {Object} fnName, the name of the function to call * @param {Object} args, arguments to call the function with */ fluid.bind = function (obj, fnName, args) { return obj[fnName].apply(obj, fluid.makeArray(args)); }; /** * Allows for the calling of a function from an EL expression "functionPath", with the arguments "args", scoped to an framework version "environment". * @param {Object} functionPath - An EL expression * @param {Object} args - An array of arguments to be applied to the function, specified in functionPath * @param {Object} environment - (optional) The object to scope the functionPath to (typically the framework root for version control) */ fluid.invokeGlobalFunction = function (functionPath, args, environment) { var func = fluid.getGlobalValue(functionPath, environment); if (!func) { fluid.fail("Error invoking global function: " + functionPath + " could not be located"); } else { return func.apply(null, fluid.isArrayable(args) ? args : fluid.makeArray(args)); } }; /** Registers a new global function at a given path */ fluid.registerGlobalFunction = function (functionPath, func, env) { env = env || fluid.environment; fluid.set(fluid.global, functionPath, func, {type: "environment", value: env}); }; fluid.setGlobalValue = fluid.registerGlobalFunction; /** Ensures that an entry in the global namespace exists. If it does not, a new entry is created as {} and returned. If an existing * value is found, it is returned instead **/ fluid.registerNamespace = function (naimspace, env) { env = env || fluid.environment; var existing = fluid.getGlobalValue(naimspace, env); if (!existing) { existing = {}; fluid.setGlobalValue(naimspace, existing, env); } return existing; }; // stubs for two functions in FluidDebugging.js fluid.dumpEl = fluid.identity; fluid.renderTimestamp = fluid.identity; /*** The Fluid instance id ***/ // unsupported, NON-API function fluid.generateUniquePrefix = function () { return (Math.floor(Math.random() * 1e12)).toString(36) + "-"; }; var fluid_prefix = fluid.generateUniquePrefix(); fluid.fluidInstance = fluid_prefix; var fluid_guid = 1; /** Allocate a string value that will be unique within this Infusion instance (frame or process), and * globally unique with high probability (50% chance of collision after a million trials) **/ fluid.allocateGuid = function () { return fluid_prefix + (fluid_guid++); }; /*** The Fluid Event system. ***/ fluid.registerNamespace("fluid.event"); // Fluid priority system for enc