UNPKG

infusion

Version:

Infusion is an application framework for developing flexible stuff with JavaScript

1,127 lines (1,004 loc) 595 kB
/*! infusion - v3.0.0-dev.20181204T213346Z.2ca90f6e6 Friday, December 7th, 2018, 7:29:03 AM branch: master revision: 2ca90f6e6 */ /*! * 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(); if (rendered.length > 0) { fluid.log("Current activity: "); fluid.each(rendered, function (args) { fluid.log.apply(null, 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.log.apply(null, 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. * * All arguments after the first are passed on to (and should be suitable to pass on 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 - legacy method * @return {Boolean} `true` if the current logging level exceeds `fluid.logLevel.IMPORTANT` */ fluid.isLogging = function () { return logLevelStack[0].priority > fluid.logLevel.IMPORTANT.priority; }; /** Determines whether the supplied argument is a valid logLevel marker * @param {Any} arg - The value to be tested * @return {Boolean} `true` if the supplied argument is a logLevel marker */ fluid.isLogLevel = function (arg) { return fluid.isMarker(arg) && arg.priority !== undefined; }; /** Check whether the current framework logging level would cause a message logged with the specified level to be * logged. Clients who issue particularly expensive log payload arguments are recommended to guard their logging * statements with this function * @param {LogLevel} testLogLevel - The logLevel value which the current logging level will be tested against. * Accepts one of the members of the <code>fluid.logLevel</code> structure. * @return {Boolean} Returns <code>true</code> if a message supplied at that log priority would be accepted at the current logging level. */ fluid.passLogLevel = function (testLogLevel) { return testLogLevel.priority <= logLevelStack[0].priority; }; /** Method to allow user to control the current framework logging level. The supplied level will be pushed onto a stack * of logging levels which may be popped via `fluid.popLogging`. * @param {Boolean|LogLevel} enabled - 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 by `fluid.log` */ 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 * @return {LogLevel} The logLevel that was just popped */ 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. * @param {Array} args - The complete array of arguments to be logged */ fluid.doBrowserLog = 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)) { fluid.loggingEvent.fire(directArgs); } }; // Functional programming utilities. // Type checking functions /** Check whether the argument is a value other than null or undefined * @param {Any} value - The value to be tested * @return {Boolean} `true` if the supplied value is other than null or undefined */ fluid.isValue = function (value) { return value !== undefined && value !== null; }; /** Check whether the argument is a primitive type * @param {Any} value - The value to be tested * @return {Boolean} `true` if the supplied value is a JavaScript (ES5) primitive */ 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 jQuery object. The strategy uses optimised inspection of the * constructor prototype since jQuery may not actually be loaded * @param {Any} totest - The value to be tested * @return {Boolean} `true` if the supplied value is a jQuery object */ fluid.isJQuery = function (totest) { return Boolean(totest && totest.jquery && totest.constructor && totest.constructor.prototype && totest.constructor.prototype.jquery); }; /** 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"). * @param {Any} totest - The value to be tested * @return {Boolean} `true` if the supplied value is an array */ // Note: The primary place jQuery->Array conversion is used in the framework is in dynamic components with a jQuery source. fluid.isArrayable = function (totest) { return Boolean(totest) && (Object.prototype.toString.call(totest) === "[object Array]" || fluid.isJQuery(totest)); }; /** 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 {Any} totest - The object to be tested * @param {Boolean} [strict] - (optional) If `true`, plain Arrays will fail the test rather than passing. * @return {Boolean} - `true` if `totest` is a plain object, `false` otherwise. */ 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 a string typeCode representing the type of the supplied value at a coarse level. * 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 * @param {Any} totest - The value to be tested * @return {String} Either `primitive`, `array` or `object` depending on the type of the supplied value */ 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 {Any} a - The first argument to be tested for being `undefined` * @param {Any} b - 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 {Array|Object} holder - The holding object whose member is to receive the pushed element(s). * @param {String} member - The member of the <code>holder</code> onto which the element(s) are to be pushed * @param {Array|Object} topush - 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 {Array|Object} source - The initial container of objects to be transformed. If the source is * neither an array nor an object, it will be returned untransformed * @param {...Function} fn1, fn2, etc. - 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 {Array|Object} - 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 {Arrayable|Object} source - The container to be iterated over * @param {Function} func - 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 {Arrayable|Object} source - The array or hash of objects to be searched. * @param {Function} func - 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 {Object} deflt - 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 {Array} list - The list of objects to be accumulated over. * @param {Function} fn - 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 {Object} arg - 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 {Number|Boolean} a - The first operand to be added * @param {Number|Boolean} b - 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 {Array|Object} source - 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 {Function} fn - 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 {Array|Object} [target] - (optional) A target object of the same type as <code>source</code>, which will * receive any objects removed from it. * @return {Array|Object} - <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 {Number} n - The size of the array to be filled * @param {Object|Function} generator - Either a value to be replicated or function to be called * @param {Boolean} applyFunc - 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 {Number} count - Size of the filled array to be returned * @param {Number} [first] - (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 {Array|Object} holder - The container to be filtered * @param {String|String[]} name - An EL path to be fetched from each top-level member * @return {Object} - The desired member component. */ 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 {Array|Object} toFilter - The object to be filtered - this will be NOT modified by the operation (current implementation * passes through $.extend shallow algorithm) * @param {String[]} keys - The array of keys to operate with * @param {Boolean} exclude - If <code>true</code>, the keys listed are removed rather than included * @return {Object} 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 {Object} obj - the Object to be searched through * @param {Object} value - 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 {String[]} array - 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 {Function} func - 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. * @return {Function} - A comparison function. */ 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} string - A string to be returned in integer form. * @return {Number|NaN} - The numeric value if the string can be converted, otherwise, returns NaN. */ 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 amount 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. * @return {Function} - A function that can be called as though it were the original function. */ 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 * @param {Any} tofreeze - The material to freeze. * @return {Any} - 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 {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) { // TODO: This branch incurs a huge cost that we incur across the whole framework, just to support the DOM binder // usage. We need to either do something "schematic" or move to proxies if (!origEnv && root.resolvePathSegment) { var togo = root.resolvePathSegment(segment); if (togo !== undefined) { // To resolve FLUID-6132 return togo; } } 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 = enviro