infusion
Version:
Infusion is an application framework for developing flexible stuff with JavaScript
49,077 lines • 1.84 MB
JavaScript
/*!
infusion - v3.0.0-dev.20200326T173810Z.24ddb2718
Friday, March 27th, 2020, 9:20:32 PM
branch: FLUID-6482
revision: 24ddb2718
*/
/*!
* jQuery JavaScript Library v3.3.1
* https://jquery.com/
*
* Includes Sizzle.js
* https://sizzlejs.com/
*
* Copyright JS Foundation and other contributors
* Released under the MIT license
* https://jquery.org/license
*
* Date: 2018-01-20T17:24Z
*/
( function( global, factory ) {
"use strict";
if ( typeof module === "object" && typeof module.exports === "object" ) {
// For CommonJS and CommonJS-like environments where a proper `window`
// is present, execute the factory and get jQuery.
// For environments that do not have a `window` with a `document`
// (such as Node.js), expose a factory as module.exports.
// This accentuates the need for the creation of a real `window`.
// e.g. var jQuery = require("jquery")(window);
// See ticket #14549 for more info.
module.exports = global.document ?
factory( global, true ) :
function( w ) {
if ( !w.document ) {
throw new Error( "jQuery requires a window with a document" );
}
return factory( w );
};
} else {
factory( global );
}
// Pass this if window is not defined yet
} )( typeof window !== "undefined" ? window : this, function( window, noGlobal ) {
// Edge <= 12 - 13+, Firefox <=18 - 45+, IE 10 - 11, Safari 5.1 - 9+, iOS 6 - 9.1
// throw exceptions when non-strict code (e.g., ASP.NET 4.5) accesses strict mode
// arguments.callee.caller (trac-13335). But as of jQuery 3.0 (2016), strict mode should be common
// enough that all such attempts are guarded in a try block.
"use strict";
var arr = [];
var document = window.document;
var getProto = Object.getPrototypeOf;
var slice = arr.slice;
var concat = arr.concat;
var push = arr.push;
var indexOf = arr.indexOf;
var class2type = {};
var toString = class2type.toString;
var hasOwn = class2type.hasOwnProperty;
var fnToString = hasOwn.toString;
var ObjectFunctionString = fnToString.call( Object );
var support = {};
var isFunction = function isFunction( obj ) {
// Support: Chrome <=57, Firefox <=52
// In some browsers, typeof returns "function" for HTML <object> elements
// (i.e., `typeof document.createElement( "object" ) === "function"`).
// We don't want to classify *any* DOM node as a function.
return typeof obj === "function" && typeof obj.nodeType !== "number";
};
var isWindow = function isWindow( obj ) {
return obj != null && obj === obj.window;
};
var preservedScriptAttributes = {
type: true,
src: true,
noModule: true
};
function DOMEval( code, doc, node ) {
doc = doc || document;
var i,
script = doc.createElement( "script" );
script.text = code;
if ( node ) {
for ( i in preservedScriptAttributes ) {
if ( node[ i ] ) {
script[ i ] = node[ i ];
}
}
}
doc.head.appendChild( script ).parentNode.removeChild( script );
}
function toType( obj ) {
if ( obj == null ) {
return obj + "";
}
// Support: Android <=2.3 only (functionish RegExp)
return typeof obj === "object" || typeof obj === "function" ?
class2type[ toString.call( obj ) ] || "object" :
typeof obj;
}
/* global Symbol */
// Defining this global in .eslintrc.json would create a danger of using the global
// unguarded in another place, it seems safer to define global only for this module
var
version = "3.3.1",
// Define a local copy of jQuery
jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
// Need init if jQuery is called (just allow error to be thrown if not included)
return new jQuery.fn.init( selector, context );
},
// Support: Android <=4.0 only
// Make sure we trim BOM and NBSP
rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;
jQuery.fn = jQuery.prototype = {
// The current version of jQuery being used
jquery: version,
constructor: jQuery,
// The default length of a jQuery object is 0
length: 0,
toArray: function() {
return slice.call( this );
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
// Return all the elements in a clean array
if ( num == null ) {
return slice.call( this );
}
// Return just the one element from the set
return num < 0 ? this[ num + this.length ] : this[ num ];
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems ) {
// Build a new jQuery matched element set
var ret = jQuery.merge( this.constructor(), elems );
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
each: function( callback ) {
return jQuery.each( this, callback );
},
map: function( callback ) {
return this.pushStack( jQuery.map( this, function( elem, i ) {
return callback.call( elem, i, elem );
} ) );
},
slice: function() {
return this.pushStack( slice.apply( this, arguments ) );
},
first: function() {
return this.eq( 0 );
},
last: function() {
return this.eq( -1 );
},
eq: function( i ) {
var len = this.length,
j = +i + ( i < 0 ? len : 0 );
return this.pushStack( j >= 0 && j < len ? [ this[ j ] ] : [] );
},
end: function() {
return this.prevObject || this.constructor();
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: push,
sort: arr.sort,
splice: arr.splice
};
jQuery.extend = jQuery.fn.extend = function() {
var options, name, src, copy, copyIsArray, clone,
target = arguments[ 0 ] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
// Skip the boolean and the target
target = arguments[ i ] || {};
i++;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !isFunction( target ) ) {
target = {};
}
// Extend jQuery itself if only one argument is passed
if ( i === length ) {
target = this;
i--;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( ( options = arguments[ i ] ) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject( copy ) ||
( copyIsArray = Array.isArray( copy ) ) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && Array.isArray( src ) ? src : [];
} else {
clone = src && jQuery.isPlainObject( src ) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend( {
// Unique for each copy of jQuery on the page
expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ),
// Assume jQuery is ready without the ready module
isReady: true,
error: function( msg ) {
throw new Error( msg );
},
noop: function() {},
isPlainObject: function( obj ) {
var proto, Ctor;
// Detect obvious negatives
// Use toString instead of jQuery.type to catch host objects
if ( !obj || toString.call( obj ) !== "[object Object]" ) {
return false;
}
proto = getProto( obj );
// Objects with no prototype (e.g., `Object.create( null )`) are plain
if ( !proto ) {
return true;
}
// Objects with prototype are plain iff they were constructed by a global Object function
Ctor = hasOwn.call( proto, "constructor" ) && proto.constructor;
return typeof Ctor === "function" && fnToString.call( Ctor ) === ObjectFunctionString;
},
isEmptyObject: function( obj ) {
/* eslint-disable no-unused-vars */
// See https://github.com/eslint/eslint/issues/6125
var name;
for ( name in obj ) {
return false;
}
return true;
},
// Evaluates a script in a global context
globalEval: function( code ) {
DOMEval( code );
},
each: function( obj, callback ) {
var length, i = 0;
if ( isArrayLike( obj ) ) {
length = obj.length;
for ( ; i < length; i++ ) {
if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) {
break;
}
}
} else {
for ( i in obj ) {
if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) {
break;
}
}
}
return obj;
},
// Support: Android <=4.0 only
trim: function( text ) {
return text == null ?
"" :
( text + "" ).replace( rtrim, "" );
},
// results is for internal usage only
makeArray: function( arr, results ) {
var ret = results || [];
if ( arr != null ) {
if ( isArrayLike( Object( arr ) ) ) {
jQuery.merge( ret,
typeof arr === "string" ?
[ arr ] : arr
);
} else {
push.call( ret, arr );
}
}
return ret;
},
inArray: function( elem, arr, i ) {
return arr == null ? -1 : indexOf.call( arr, elem, i );
},
// Support: Android <=4.0 only, PhantomJS 1 only
// push.apply(_, arraylike) throws on ancient WebKit
merge: function( first, second ) {
var len = +second.length,
j = 0,
i = first.length;
for ( ; j < len; j++ ) {
first[ i++ ] = second[ j ];
}
first.length = i;
return first;
},
grep: function( elems, callback, invert ) {
var callbackInverse,
matches = [],
i = 0,
length = elems.length,
callbackExpect = !invert;
// Go through the array, only saving the items
// that pass the validator function
for ( ; i < length; i++ ) {
callbackInverse = !callback( elems[ i ], i );
if ( callbackInverse !== callbackExpect ) {
matches.push( elems[ i ] );
}
}
return matches;
},
// arg is for internal usage only
map: function( elems, callback, arg ) {
var length, value,
i = 0,
ret = [];
// Go through the array, translating each of the items to their new values
if ( isArrayLike( elems ) ) {
length = elems.length;
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret.push( value );
}
}
// Go through every key on the object,
} else {
for ( i in elems ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret.push( value );
}
}
}
// Flatten any nested arrays
return concat.apply( [], ret );
},
// A global GUID counter for objects
guid: 1,
// jQuery.support is not used in Core but other projects attach their
// properties to it so it needs to exist.
support: support
} );
if ( typeof Symbol === "function" ) {
jQuery.fn[ Symbol.iterator ] = arr[ Symbol.iterator ];
}
// Populate the class2type map
jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ),
function( i, name ) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
} );
function isArrayLike( obj ) {
// Support: real iOS 8.2 only (not reproducible in simulator)
// `in` check used to prevent JIT error (gh-2145)
// hasOwn isn't used here due to false negatives
// regarding Nodelist length in IE
var length = !!obj && "length" in obj && obj.length,
type = toType( obj );
if ( isFunction( obj ) || isWindow( obj ) ) {
return false;
}
return type === "array" || length === 0 ||
typeof length === "number" && length > 0 && ( length - 1 ) in obj;
}
var Sizzle =
/*!
* Sizzle CSS Selector Engine v2.3.3
* https://sizzlejs.com/
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2016-08-08
*/
(function( window ) {
var i,
support,
Expr,
getText,
isXML,
tokenize,
compile,
select,
outermostContext,
sortInput,
hasDuplicate,
// Local document vars
setDocument,
document,
docElem,
documentIsHTML,
rbuggyQSA,
rbuggyMatches,
matches,
contains,
// Instance-specific data
expando = "sizzle" + 1 * new Date(),
preferredDoc = window.document,
dirruns = 0,
done = 0,
classCache = createCache(),
tokenCache = createCache(),
compilerCache = createCache(),
sortOrder = function( a, b ) {
if ( a === b ) {
hasDuplicate = true;
}
return 0;
},
// Instance methods
hasOwn = ({}).hasOwnProperty,
arr = [],
pop = arr.pop,
push_native = arr.push,
push = arr.push,
slice = arr.slice,
// Use a stripped-down indexOf as it's faster than native
// https://jsperf.com/thor-indexof-vs-for/5
indexOf = function( list, elem ) {
var i = 0,
len = list.length;
for ( ; i < len; i++ ) {
if ( list[i] === elem ) {
return i;
}
}
return -1;
},
booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",
// Regular expressions
// http://www.w3.org/TR/css3-selectors/#whitespace
whitespace = "[\\x20\\t\\r\\n\\f]",
// http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
identifier = "(?:\\\\.|[\\w-]|[^\0-\\xa0])+",
// Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors
attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace +
// Operator (capture 2)
"*([*^$|!~]?=)" + whitespace +
// "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]"
"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace +
"*\\]",
pseudos = ":(" + identifier + ")(?:\\((" +
// To reduce the number of selectors needing tokenize in the preFilter, prefer arguments:
// 1. quoted (capture 3; capture 4 or capture 5)
"('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" +
// 2. simple (capture 6)
"((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" +
// 3. anything else (capture 2)
".*" +
")\\)|)",
// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
rwhitespace = new RegExp( whitespace + "+", "g" ),
rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),
rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ),
rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ),
rpseudo = new RegExp( pseudos ),
ridentifier = new RegExp( "^" + identifier + "$" ),
matchExpr = {
"ID": new RegExp( "^#(" + identifier + ")" ),
"CLASS": new RegExp( "^\\.(" + identifier + ")" ),
"TAG": new RegExp( "^(" + identifier + "|[*])" ),
"ATTR": new RegExp( "^" + attributes ),
"PSEUDO": new RegExp( "^" + pseudos ),
"CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace +
"*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
"*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
"bool": new RegExp( "^(?:" + booleans + ")$", "i" ),
// For use in libraries implementing .is()
// We use this for POS matching in `select`
"needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" +
whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" )
},
rinputs = /^(?:input|select|textarea|button)$/i,
rheader = /^h\d$/i,
rnative = /^[^{]+\{\s*\[native \w/,
// Easily-parseable/retrievable ID or TAG or CLASS selectors
rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
rsibling = /[+~]/,
// CSS escapes
// http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ),
funescape = function( _, escaped, escapedWhitespace ) {
var high = "0x" + escaped - 0x10000;
// NaN means non-codepoint
// Support: Firefox<24
// Workaround erroneous numeric interpretation of +"0x"
return high !== high || escapedWhitespace ?
escaped :
high < 0 ?
// BMP codepoint
String.fromCharCode( high + 0x10000 ) :
// Supplemental Plane codepoint (surrogate pair)
String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );
},
// CSS string/identifier serialization
// https://drafts.csswg.org/cssom/#common-serializing-idioms
rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,
fcssescape = function( ch, asCodePoint ) {
if ( asCodePoint ) {
// U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER
if ( ch === "\0" ) {
return "\uFFFD";
}
// Control characters and (dependent upon position) numbers get escaped as code points
return ch.slice( 0, -1 ) + "\\" + ch.charCodeAt( ch.length - 1 ).toString( 16 ) + " ";
}
// Other potentially-special ASCII characters get backslash-escaped
return "\\" + ch;
},
// Used for iframes
// See setDocument()
// Removing the function wrapper causes a "Permission Denied"
// error in IE
unloadHandler = function() {
setDocument();
},
disabledAncestor = addCombinator(
function( elem ) {
return elem.disabled === true && ("form" in elem || "label" in elem);
},
{ dir: "parentNode", next: "legend" }
);
// Optimize for push.apply( _, NodeList )
try {
push.apply(
(arr = slice.call( preferredDoc.childNodes )),
preferredDoc.childNodes
);
// Support: Android<4.0
// Detect silently failing push.apply
arr[ preferredDoc.childNodes.length ].nodeType;
} catch ( e ) {
push = { apply: arr.length ?
// Leverage slice if possible
function( target, els ) {
push_native.apply( target, slice.call(els) );
} :
// Support: IE<9
// Otherwise append directly
function( target, els ) {
var j = target.length,
i = 0;
// Can't trust NodeList.length
while ( (target[j++] = els[i++]) ) {}
target.length = j - 1;
}
};
}
function Sizzle( selector, context, results, seed ) {
var m, i, elem, nid, match, groups, newSelector,
newContext = context && context.ownerDocument,
// nodeType defaults to 9, since context defaults to document
nodeType = context ? context.nodeType : 9;
results = results || [];
// Return early from calls with invalid selector or context
if ( typeof selector !== "string" || !selector ||
nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) {
return results;
}
// Try to shortcut find operations (as opposed to filters) in HTML documents
if ( !seed ) {
if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) {
setDocument( context );
}
context = context || document;
if ( documentIsHTML ) {
// If the selector is sufficiently simple, try using a "get*By*" DOM method
// (excepting DocumentFragment context, where the methods don't exist)
if ( nodeType !== 11 && (match = rquickExpr.exec( selector )) ) {
// ID selector
if ( (m = match[1]) ) {
// Document context
if ( nodeType === 9 ) {
if ( (elem = context.getElementById( m )) ) {
// Support: IE, Opera, Webkit
// TODO: identify versions
// getElementById can match elements by name instead of ID
if ( elem.id === m ) {
results.push( elem );
return results;
}
} else {
return results;
}
// Element context
} else {
// Support: IE, Opera, Webkit
// TODO: identify versions
// getElementById can match elements by name instead of ID
if ( newContext && (elem = newContext.getElementById( m )) &&
contains( context, elem ) &&
elem.id === m ) {
results.push( elem );
return results;
}
}
// Type selector
} else if ( match[2] ) {
push.apply( results, context.getElementsByTagName( selector ) );
return results;
// Class selector
} else if ( (m = match[3]) && support.getElementsByClassName &&
context.getElementsByClassName ) {
push.apply( results, context.getElementsByClassName( m ) );
return results;
}
}
// Take advantage of querySelectorAll
if ( support.qsa &&
!compilerCache[ selector + " " ] &&
(!rbuggyQSA || !rbuggyQSA.test( selector )) ) {
if ( nodeType !== 1 ) {
newContext = context;
newSelector = selector;
// qSA looks outside Element context, which is not what we want
// Thanks to Andrew Dupont for this workaround technique
// Support: IE <=8
// Exclude object elements
} else if ( context.nodeName.toLowerCase() !== "object" ) {
// Capture the context ID, setting it first if necessary
if ( (nid = context.getAttribute( "id" )) ) {
nid = nid.replace( rcssescape, fcssescape );
} else {
context.setAttribute( "id", (nid = expando) );
}
// Prefix every selector in the list
groups = tokenize( selector );
i = groups.length;
while ( i-- ) {
groups[i] = "#" + nid + " " + toSelector( groups[i] );
}
newSelector = groups.join( "," );
// Expand context for sibling selectors
newContext = rsibling.test( selector ) && testContext( context.parentNode ) ||
context;
}
if ( newSelector ) {
try {
push.apply( results,
newContext.querySelectorAll( newSelector )
);
return results;
} catch ( qsaError ) {
} finally {
if ( nid === expando ) {
context.removeAttribute( "id" );
}
}
}
}
}
}
// All others
return select( selector.replace( rtrim, "$1" ), context, results, seed );
}
/**
* Create key-value caches of limited size
* @returns {function(string, object)} Returns the Object data after storing it on itself with
* property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
* deleting the oldest entry
*/
function createCache() {
var keys = [];
function cache( key, value ) {
// Use (key + " ") to avoid collision with native prototype properties (see Issue #157)
if ( keys.push( key + " " ) > Expr.cacheLength ) {
// Only keep the most recent entries
delete cache[ keys.shift() ];
}
return (cache[ key + " " ] = value);
}
return cache;
}
/**
* Mark a function for special use by Sizzle
* @param {Function} fn The function to mark
*/
function markFunction( fn ) {
fn[ expando ] = true;
return fn;
}
/**
* Support testing using an element
* @param {Function} fn Passed the created element and returns a boolean result
*/
function assert( fn ) {
var el = document.createElement("fieldset");
try {
return !!fn( el );
} catch (e) {
return false;
} finally {
// Remove from its parent by default
if ( el.parentNode ) {
el.parentNode.removeChild( el );
}
// release memory in IE
el = null;
}
}
/**
* Adds the same handler for all of the specified attrs
* @param {String} attrs Pipe-separated list of attributes
* @param {Function} handler The method that will be applied
*/
function addHandle( attrs, handler ) {
var arr = attrs.split("|"),
i = arr.length;
while ( i-- ) {
Expr.attrHandle[ arr[i] ] = handler;
}
}
/**
* Checks document order of two siblings
* @param {Element} a
* @param {Element} b
* @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b
*/
function siblingCheck( a, b ) {
var cur = b && a,
diff = cur && a.nodeType === 1 && b.nodeType === 1 &&
a.sourceIndex - b.sourceIndex;
// Use IE sourceIndex if available on both nodes
if ( diff ) {
return diff;
}
// Check if b follows a
if ( cur ) {
while ( (cur = cur.nextSibling) ) {
if ( cur === b ) {
return -1;
}
}
}
return a ? 1 : -1;
}
/**
* Returns a function to use in pseudos for input types
* @param {String} type
*/
function createInputPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === type;
};
}
/**
* Returns a function to use in pseudos for buttons
* @param {String} type
*/
function createButtonPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && elem.type === type;
};
}
/**
* Returns a function to use in pseudos for :enabled/:disabled
* @param {Boolean} disabled true for :disabled; false for :enabled
*/
function createDisabledPseudo( disabled ) {
// Known :disabled false positives: fieldset[disabled] > legend:nth-of-type(n+2) :can-disable
return function( elem ) {
// Only certain elements can match :enabled or :disabled
// https://html.spec.whatwg.org/multipage/scripting.html#selector-enabled
// https://html.spec.whatwg.org/multipage/scripting.html#selector-disabled
if ( "form" in elem ) {
// Check for inherited disabledness on relevant non-disabled elements:
// * listed form-associated elements in a disabled fieldset
// https://html.spec.whatwg.org/multipage/forms.html#category-listed
// https://html.spec.whatwg.org/multipage/forms.html#concept-fe-disabled
// * option elements in a disabled optgroup
// https://html.spec.whatwg.org/multipage/forms.html#concept-option-disabled
// All such elements have a "form" property.
if ( elem.parentNode && elem.disabled === false ) {
// Option elements defer to a parent optgroup if present
if ( "label" in elem ) {
if ( "label" in elem.parentNode ) {
return elem.parentNode.disabled === disabled;
} else {
return elem.disabled === disabled;
}
}
// Support: IE 6 - 11
// Use the isDisabled shortcut property to check for disabled fieldset ancestors
return elem.isDisabled === disabled ||
// Where there is no isDisabled, check manually
/* jshint -W018 */
elem.isDisabled !== !disabled &&
disabledAncestor( elem ) === disabled;
}
return elem.disabled === disabled;
// Try to winnow out elements that can't be disabled before trusting the disabled property.
// Some victims get caught in our net (label, legend, menu, track), but it shouldn't
// even exist on them, let alone have a boolean value.
} else if ( "label" in elem ) {
return elem.disabled === disabled;
}
// Remaining elements are neither :enabled nor :disabled
return false;
};
}
/**
* Returns a function to use in pseudos for positionals
* @param {Function} fn
*/
function createPositionalPseudo( fn ) {
return markFunction(function( argument ) {
argument = +argument;
return markFunction(function( seed, matches ) {
var j,
matchIndexes = fn( [], seed.length, argument ),
i = matchIndexes.length;
// Match elements found at the specified indexes
while ( i-- ) {
if ( seed[ (j = matchIndexes[i]) ] ) {
seed[j] = !(matches[j] = seed[j]);
}
}
});
});
}
/**
* Checks a node for validity as a Sizzle context
* @param {Element|Object=} context
* @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value
*/
function testContext( context ) {
return context && typeof context.getElementsByTagName !== "undefined" && context;
}
// Expose support vars for convenience
support = Sizzle.support = {};
/**
* Detects XML nodes
* @param {Element|Object} elem An element or a document
* @returns {Boolean} True iff elem is a non-HTML XML node
*/
isXML = Sizzle.isXML = function( elem ) {
// documentElement is verified for cases where it doesn't yet exist
// (such as loading iframes in IE - #4833)
var documentElement = elem && (elem.ownerDocument || elem).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
/**
* Sets document-related variables once based on the current document
* @param {Element|Object} [doc] An element or document object to use to set the document
* @returns {Object} Returns the current document
*/
setDocument = Sizzle.setDocument = function( node ) {
var hasCompare, subWindow,
doc = node ? node.ownerDocument || node : preferredDoc;
// Return early if doc is invalid or already selected
if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) {
return document;
}
// Update global variables
document = doc;
docElem = document.documentElement;
documentIsHTML = !isXML( document );
// Support: IE 9-11, Edge
// Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936)
if ( preferredDoc !== document &&
(subWindow = document.defaultView) && subWindow.top !== subWindow ) {
// Support: IE 11, Edge
if ( subWindow.addEventListener ) {
subWindow.addEventListener( "unload", unloadHandler, false );
// Support: IE 9 - 10 only
} else if ( subWindow.attachEvent ) {
subWindow.attachEvent( "onunload", unloadHandler );
}
}
/* Attributes
---------------------------------------------------------------------- */
// Support: IE<8
// Verify that getAttribute really returns attributes and not properties
// (excepting IE8 booleans)
support.attributes = assert(function( el ) {
el.className = "i";
return !el.getAttribute("className");
});
/* getElement(s)By*
---------------------------------------------------------------------- */
// Check if getElementsByTagName("*") returns only elements
support.getElementsByTagName = assert(function( el ) {
el.appendChild( document.createComment("") );
return !el.getElementsByTagName("*").length;
});
// Support: IE<9
support.getElementsByClassName = rnative.test( document.getElementsByClassName );
// Support: IE<10
// Check if getElementById returns elements by name
// The broken getElementById methods don't pick up programmatically-set names,
// so use a roundabout getElementsByName test
support.getById = assert(function( el ) {
docElem.appendChild( el ).id = expando;
return !document.getElementsByName || !document.getElementsByName( expando ).length;
});
// ID filter and find
if ( support.getById ) {
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
return elem.getAttribute("id") === attrId;
};
};
Expr.find["ID"] = function( id, context ) {
if ( typeof context.getElementById !== "undefined" && documentIsHTML ) {
var elem = context.getElementById( id );
return elem ? [ elem ] : [];
}
};
} else {
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
var node = typeof elem.getAttributeNode !== "undefined" &&
elem.getAttributeNode("id");
return node && node.value === attrId;
};
};
// Support: IE 6 - 7 only
// getElementById is not reliable as a find shortcut
Expr.find["ID"] = function( id, context ) {
if ( typeof context.getElementById !== "undefined" && documentIsHTML ) {
var node, i, elems,
elem = context.getElementById( id );
if ( elem ) {
// Verify the id attribute
node = elem.getAttributeNode("id");
if ( node && node.value === id ) {
return [ elem ];
}
// Fall back on getElementsByName
elems = context.getElementsByName( id );
i = 0;
while ( (elem = elems[i++]) ) {
node = elem.getAttributeNode("id");
if ( node && node.value === id ) {
return [ elem ];
}
}
}
return [];
}
};
}
// Tag
Expr.find["TAG"] = support.getElementsByTagName ?
function( tag, context ) {
if ( typeof context.getElementsByTagName !== "undefined" ) {
return context.getElementsByTagName( tag );
// DocumentFragment nodes don't have gEBTN
} else if ( support.qsa ) {
return context.querySelectorAll( tag );
}
} :
function( tag, context ) {
var elem,
tmp = [],
i = 0,
// By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too
results = context.getElementsByTagName( tag );
// Filter out possible comments
if ( tag === "*" ) {
while ( (elem = results[i++]) ) {
if ( elem.nodeType === 1 ) {
tmp.push( elem );
}
}
return tmp;
}
return results;
};
// Class
Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) {
if ( typeof context.getElementsByClassName !== "undefined" && documentIsHTML ) {
return context.getElementsByClassName( className );
}
};
/* QSA/matchesSelector
---------------------------------------------------------------------- */
// QSA and matchesSelector support
// matchesSelector(:active) reports false when true (IE9/Opera 11.5)
rbuggyMatches = [];
// qSa(:focus) reports false when true (Chrome 21)
// We allow this because of a bug in IE8/9 that throws an error
// whenever `document.activeElement` is accessed on an iframe
// So, we allow :focus to pass through QSA all the time to avoid the IE error
// See https://bugs.jquery.com/ticket/13378
rbuggyQSA = [];
if ( (support.qsa = rnative.test( document.querySelectorAll )) ) {
// Build QSA regex
// Regex strategy adopted from Diego Perini
assert(function( el ) {
// Select is set to empty string on purpose
// This is to test IE's treatment of not explicitly
// setting a boolean content attribute,
// since its presence should be enough
// https://bugs.jquery.com/ticket/12359
docElem.appendChild( el ).innerHTML = "<a id='" + expando + "'></a>" +
"<select id='" + expando + "-\r\\' msallowcapture=''>" +
"<option selected=''></option></select>";
// Support: IE8, Opera 11-12.16
// Nothing should be selected when empty strings follow ^= or $= or *=
// The test attribute must be unknown in Opera but "safe" for WinRT
// https://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section
if ( el.querySelectorAll("[msallowcapture^='']").length ) {
rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" );
}
// Support: IE8
// Boolean attributes and "value" are not treated correctly
if ( !el.querySelectorAll("[selected]").length ) {
rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" );
}
// Support: Chrome<29, Android<4.4, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.8+
if ( !el.querySelectorAll( "[id~=" + expando + "-]" ).length ) {
rbuggyQSA.push("~=");
}
// Webkit/Opera - :checked should return selected option elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
// IE8 throws error here and will not see later tests
if ( !el.querySelectorAll(":checked").length ) {
rbuggyQSA.push(":checked");
}
// Support: Safari 8+, iOS 8+
// https://bugs.webkit.org/show_bug.cgi?id=136851
// In-page `selector#id sibling-combinator selector` fails
if ( !el.querySelectorAll( "a#" + expando + "+*" ).length ) {
rbuggyQSA.push(".#.+[+~]");
}
});
assert(function( el ) {
el.innerHTML = "<a href='' disabled='disabled'></a>" +
"<select disabled='disabled'><option/></select>";
// Support: Windows 8 Native Apps
// The type and name attributes are restricted during .innerHTML assignment
var input = document.createElement("input");
input.setAttribute( "type", "hidden" );
el.appendChild( input ).setAttribute( "name", "D" );
// Support: IE8
// Enforce case-sensitivity of name attribute
if ( el.querySelectorAll("[name=d]").length ) {
rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" );
}
// FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
// IE8 throws error here and will not see later tests
if ( el.querySelectorAll(":enabled").length !== 2 ) {
rbuggyQSA.push( ":enabled", ":disabled" );
}
// Support: IE9-11+
// IE's :disabled selector does not pick up the children of disabled fieldsets
docElem.appendChild( el ).disabled = true;
if ( el.querySelectorAll(":disabled").length !== 2 ) {
rbuggyQSA.push( ":enabled", ":disabled" );
}
// Opera 10-11 does not throw on post-comma invalid pseudos
el.querySelectorAll("*,:x");
rbuggyQSA.push(",.*:");
});
}
if ( (support.matchesSelector = rnative.test( (matches = docElem.matches ||
docElem.webkitMatchesSelector ||
docElem.mozMatchesSelector ||
docElem.oMatchesSelector ||
docElem.msMatchesSelector) )) ) {
assert(function( el ) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9)
support.disconnectedMatch = matches.call( el, "*" );
// This should fail with an exception
// Gecko does not error, returns false instead
matches.call( el, "[s!='']:x" );
rbuggyMatches.push( "!=", pseudos );
});
}
rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") );
rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") );
/* Contains
---------------------------------------------------------------------- */
hasCompare = rnative.test( docElem.compareDocumentPosition );
// Element contains another
// Purposefully self-exclusive
// As in, an element does not contain itself
contains = hasCompare || rnative.test( docElem.contains ) ?
function( a, b ) {
var adown = a.nodeType === 9 ? a.documentElement : a,
bup = b && b.parentNode;
return a === bup || !!( bup && bup.nodeType === 1 && (
adown.contains ?
adown.contains( bup ) :
a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
));
} :
function( a, b ) {
if ( b ) {
while ( (b = b.parentNode) ) {
if ( b === a ) {
return true;
}
}
}
return false;
};
/* Sorting
---------------------------------------------------------------------- */
// Document order sorting
sortOrder = hasCompare ?
function( a, b ) {
// Flag for duplicate removal
if ( a === b ) {
hasDuplicate = true;
return 0;
}
// Sort on method existence if only one input has compareDocumentPosition
var compare = !a.compareDocumentPosition - !b.compareDocumentPosition;
if ( compare ) {
return compare;
}
// Calculate position if both inputs belong to the same document
compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ?
a.compareDocumentPosition( b ) :
// Otherwise we know they are disconnected
1;
// Disconnected nodes
if ( compare & 1 ||
(!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) {
// Choose the first element that is related to our preferred document
if ( a === document || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) {
return -1;
}
if ( b === document || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) {
return 1;
}
// Maintain original order
return sortInput ?
( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) :
0;
}
return compare & 4 ? -1 : 1;
} :
function( a, b ) {
// Exit early if the nodes are identical
if ( a === b ) {
hasDuplicate = true;
return 0;
}
var cur,
i = 0,
aup = a.parentNode,
bup = b.parentNode,
ap = [ a ],
bp = [ b ];
// Parentless nodes are either documents or disconnected
if ( !aup || !bup ) {
return a === document ? -1 :
b === document ? 1 :
aup ? -1 :
bup ? 1 :
sortInput ?
( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) :
0;
// If the nodes are siblings, we can do a quick check
} else if ( aup === bup ) {
return siblingCheck( a, b );
}
// Otherwise we need full lists of their ancestors for comparison
cur = a;
while ( (cur = cur.parentNode) ) {
ap.unshift( cur );
}
cur = b;
while ( (cur = cur.parentNode) ) {
bp.unshift( cur );
}
// Walk down the tree looking for a discrepancy
while ( ap[i] === bp[i] ) {
i++;
}
return i ?
// Do a sibling check if the nodes have a common ancestor
siblingCheck( ap[i], bp[i] ) :
// Otherwise nodes in our document sort first
ap[i] === preferredDoc ? -1 :
bp[i] === preferredDoc ? 1 :
0;
};
return document;
};
Sizzle.matches = function( expr, elements ) {
return Sizzle( expr, null, null, elements );
};
Sizzle.matchesSelector = function( elem, expr ) {
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
// Make sure that attribute selectors are quoted
expr = expr.replace( rattributeQuotes, "='$1']" );
if ( support.matchesSelector && documentIsHTML &&
!compilerCache[ expr + " " ] &&
( !rbuggyMatches || !rbuggyMatches.test( expr ) ) &&
( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) {
try {
var ret = matches.call( elem, expr );
// IE 9's matchesSelector returns false on disconnected nodes
if ( ret || support.disconnectedMatch ||
// As well, disconnected nodes are said to be in a document
// fragment in IE 9
elem.document && elem.document.nodeType !== 11 ) {
return ret;
}
} catch (e) {}
}
return Sizzle( expr, document, null, [ elem ] ).length > 0;
};
Sizzle.contains = function( context, elem ) {
// Set document vars if needed
if ( ( context.ownerDocument || context ) !== document ) {
setDocument( context );
}
return contains( context, elem );
};
Sizzle.attr = function( elem, name ) {
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
var fn = Expr.attrHandle[ name.toLowerCase() ],
// Don't get fooled by Object.prototype properties (jQuery #13807)
val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ?
fn( elem, name, !documentIsHTML ) :
undefined;
return val !== undefined ?
val :
support.attributes || !documentIsHTML ?
elem.getAttribute( name ) :
(val = elem.getAttributeNode(name)) && val.specified ?
val.value :
null;
};
Sizzle.escape = function( sel ) {
return (sel + "").replace( rcssescape, fcssescape );
};
Sizzle.error = function( msg ) {
throw new Error( "Syntax error, unrecognized expression: " + msg );
};
/**
* Document sorting and removing duplicates
* @param {ArrayLike} results
*/
Sizzle.uniqueSort = function( results ) {
var elem,
duplicates = [],
j = 0,
i = 0;
// Unless we *know* we can detect duplicates, assume their presence
hasDuplicate = !support.detectDuplicates;
sortInput = !support.sortStable && results.slice( 0 );
results.sort( sortOrder );
if ( hasDuplicate ) {
while ( (elem = results[i++]) ) {
if ( elem === results[ i ] ) {
j = duplicates.push( i );
}
}
while ( j-- ) {
results.splice( duplicates[ j ], 1 );
}
}
// Clear input after sorting to release objects
// See https://github.com/jquery/sizzle/pull/225
sortInput = null;
return results;
};
/**
* Utility function for retrieving the text value of an array of DOM nodes
* @param {Array|Element} elem
*/
getText = Sizzle.getText = function( elem ) {
var node,
ret = "",
i = 0,
nodeType = elem.nodeType;
if ( !nodeType ) {
// If no nodeType, this is expected to be an array
while ( (node = elem[i++]) ) {
// Do not traverse comment nodes
ret += getText( node );
}
} else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
// Use textContent for elements
// innerText usage removed for consistency of new lines (jQuery #11153)
if ( typeof elem.textContent === "string" ) {
return elem.textContent;
} else {
// Traverse its children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
ret += getText( elem );
}
}
} else if ( nodeType === 3 || nodeType === 4 ) {
return elem.nodeValue;
}
// Do not include comment or processing instruction nodes
return ret;
};
Expr = Sizzle.selectors = {
// Can be adjusted by the user
cacheLength: 50,
createPseudo: markFunction,
match: matchExpr,
attrHandle: {},
find: {},
relative: {
">": { dir: "parentNode", first: true },
" ": { dir: "parentNode" },
"+": { dir: "previousSibling", first: true },
"~": { dir: "previousSibling" }
},
preFilter: {
"ATTR": function( match ) {
match[1] = match[1].replace( runescape, funescape );
// Move the given value to match[3] whether quoted or unquoted
match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape );
if ( match[2] === "~=" ) {
match[3] = " " + match[3] + " ";
}
return match.slice( 0, 4 );
},
"CHILD": function( match ) {
/* matches from matchExpr["CHILD"]
1 type (only|nth|...)
2 what (child|of-type)
3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
4 xn-component of xn+y argument ([+-]?\d*n|)
5 sign of xn-component
6 x of xn-component
7 sign of y-component
8 y of y-component
*/
match[1] = match[1].toLowerCase();
if ( match[1].slice( 0, 3 ) === "nth" ) {
// nth-* requires argument
if ( !match[3] ) {
Sizzle.error( match[0] );
}
// numeric x and y parameters for Expr.filter.CHILD
// remember that false/true cast respectively to 0/1
match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) );
match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" );
// other types prohibit arguments
} else if ( match[3] ) {
Sizzle.error( match[0] );
}
return match;
},
"PSEUDO": function( match ) {
var excess,
unquoted = !match[6] && match[2];
if ( matchExpr["CHILD"].test( match[0] ) ) {
return null;
}
// Accept quoted arguments as-is
if ( match[3] ) {
match[2] = match[4] || match[5] || "";
// Strip excess characters from unquoted arguments
} else if ( unquoted && rpseudo.test( unquoted ) &&
// Get excess from tokenize (recursively)
(excess = tokenize( unquoted, true )) &&
// advance to the next closing parenthesis
(excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) {
// excess is a negative index
match[0] = match[0].slice( 0, excess );
match[2] = unquoted.slice( 0, excess );
}
// Return only captures needed by the pseudo filter method (type and argument)
return match.slice( 0, 3 );
}
},
filter: {
"TAG": function( nodeNameSelector ) {
var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase();
return nodeNameSelector === "*" ?
function() { return true; } :
function( elem ) {
return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
};
},
"CLASS": function( className ) {
var pattern = classCache[ className + " " ];
return pattern ||
(pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) &&
classCache( className, function( elem ) {
return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== "undefined" && elem.getAttribute("class") || "" );
});
},
"ATTR": function( name, operator, check ) {
return function( elem ) {
var result = Sizzle.attr( elem, name );
if ( result == null ) {
return operator === "!=";
}
if ( !operator ) {
return true;
}
result += "";
return operator === "=" ? result === check :
operator === "!=" ? result !== check :
operator === "^=" ? check && result.indexOf( check ) === 0 :
operator === "*=" ? check && result.indexOf( check ) > -1 :
operator === "$=" ? check && result.slice( -check.length ) === check :
operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 :
operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" :
false;
};
},
"CHILD": function( type, what, argument, first, last ) {
var simple = type.slice( 0, 3 ) !== "nth",
forward = type.slice( -4 ) !== "last",
ofType = what === "of-type";
return first === 1 && last === 0 ?
// Shortcut for :nth-*(n)
function( elem ) {
return !!elem.parentNode;
} :
function( elem, context, xml ) {
var cache, uniqueCache, outerCache, node, nodeIndex, start,
dir = simple !== forward ? "nextSibling" : "previousSibling",
parent = elem.parentNode,
name = ofType && elem.nodeName.toLowerCase(),
useCache = !xml && !ofType,
diff = false;
if ( parent ) {
// :(first|last|only)-(child|of-type)
if ( simple ) {
while ( dir ) {
node = elem;
while ( (node = node[ dir ]) ) {
if ( ofType ?
node.nodeName.toLowerCase() === name :
node.nodeType === 1 ) {
return false;
}
}
// Reverse direction for :only-* (if we haven't yet done so)
start = dir = type === "only" && !start && "nextSibling";
}
return true;
}
start = [ forward ? parent.firstChild : parent.lastChild ];
// non-xml :nth-child(...) stores cache data on `parent`
if ( forward && useCache ) {
// Seek `elem` from a previously-cached index
// ...in a gzip-friendly way
node = parent;
outerCache = node[ expando ] || (node[ expando ] = {});
// Support: IE <9 only
// Defend against cloned attroperties (jQuery gh-1709)
uniqueCache = outerCache[ node.uniqueID ] ||
(outerCache[ node.uniqueID ] = {});
cache = uniqueCache[ type ] || [];
nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ];
diff = nodeIndex && cache[ 2 ];
node = nodeIndex && parent.childNodes[ nodeIndex ];
while ( (node = ++nodeIndex && node && node[ dir ] ||
// Fallback to seeking `elem` from the start
(diff = nodeIndex = 0) || start.pop()) ) {
// When found, cache indexes on `parent` and break
if ( node.nodeType === 1 && ++diff && node === elem ) {
uniqueCache[ type ] = [ dirruns, nodeIndex, diff ];
break;
}
}
} else {
// Use previously-cached element index if available
if ( useCache ) {
// ...in a gzip-friendly way
node = elem;
outerCache = node[ expando ] || (node[ expando ] = {});
// Support: IE <9 only
// Defend against cloned attroperties (jQuery gh-1709)
uniqueCache = outerCache[ node.uniqueID ] ||
(outerCache[ node.uniqueID ] = {});
cache = uniqueCache[ type ] || [];
nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ];
diff = nodeIndex;
}
// xml :nth-child(...)
// or :nth-last-child(...) or :nth(-last)?-of-type(...)
if ( diff === false ) {
// Use the same loop as above to seek `elem` from the start
while ( (node = ++nodeIndex && node && node[ dir ] ||
(diff = nodeIndex = 0) || start.pop()) ) {
if ( ( ofType ?
node.nodeName.toLowerCase() === name :
node.nodeType === 1 ) &&
++diff ) {
// Cache the index of each encountered element
if ( useCache ) {
outerCache = node[ expando ] || (node[ expando ] = {});
// Support: IE <9 only
// Defend against cloned attroperties (jQuery gh-1709)
uniqueCache = outerCache[ node.uniqueID ] ||
(outerCache[ node.uniqueID ] = {});
uniqueCache[ type ] = [ dirruns, diff ];
}
if ( node === elem ) {
break;
}
}
}
}
}
// Incorporate the offset, then check against cycle size
diff -= last;
return diff === first || ( diff % first === 0 && diff / first >= 0 );
}
};
},
"PSEUDO": function( pseudo, argument ) {
// pseudo-class names are case-insensitive
// http://www.w3.org/TR/selectors/#pseudo-classes
// Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
// Remember that setFilters inherits from pseudos
var args,
fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
Sizzle.error( "unsupported pseudo: " + pseudo );
// The user may use createPseudo to indicate that
// arguments are needed to create the filter function
// just as Sizzle does
if ( fn[ expando ] ) {
return fn( argument );
}
// But maintain support for old signatures
if ( fn.length > 1 ) {
args = [ pseudo, pseudo, "", argument ];
return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
markFunction(function( seed, matches ) {
var idx,
matched = fn( seed, argument ),
i = matched.length;
while ( i-- ) {
idx = indexOf( seed, matched[i] );
seed[ idx ] = !( matches[ idx ] = matched[i] );
}
}) :
function( elem ) {
return fn( elem, 0, args );
};
}
return fn;
}
},
pseudos: {
// Potentially complex pseudos
"not": markFunction(function( selector ) {
// Trim the selector passed to compile
// to avoid treating leading and trailing
// spaces as combinators
var input = [],
results = [],
matcher = compile( selector.replace( rtrim, "$1" ) );
return matcher[ expando ] ?
markFunction(function( seed, matches, context, xml ) {
var elem,
unmatched = matcher( seed, null, xml, [] ),
i = seed.length;
// Match elements unmatched by `matcher`
while ( i-- ) {
if ( (elem = unmatched[i]) ) {
seed[i] = !(matches[i] = elem);
}
}
}) :
function( elem, context, xml ) {
input[0] = elem;
matcher( input, null, xml, results );
// Don't keep the element (issue #299)
input[0] = null;
return !results.pop();
};
}),
"has": markFunction(function( selector ) {
return function( elem ) {
return Sizzle( selector, elem ).length > 0;
};
}),
"contains": markFunction(function( text ) {
text = text.replace( runescape, funescape );
return function( elem ) {
return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;
};
}),
// "Whether an element is represented by a :lang() selector
// is based solely on the element's language value
// being equal to the identifier C,
// or beginning with the identifier C immediately followed by "-".
// The matching of C against the element's language value is performed case-insensitively.
// The identifier C does not have to be a valid language name."
// http://www.w3.org/TR/selectors/#lang-pseudo
"lang": markFunction( function( lang ) {
// lang value must be a valid identifier
if ( !ridentifier.test(lang || "") ) {
Sizzle.error( "unsupported lang: " + lang );
}
lang = lang.replace( runescape, funescape ).toLowerCase();
return function( elem ) {
var elemLang;
do {
if ( (elemLang = documentIsHTML ?
elem.lang :
elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) {
elemLang = elemLang.toLowerCase();
return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0;
}
} while ( (elem = elem.parentNode) && elem.nodeType === 1 );
return false;
};
}),
// Miscellaneous
"target": function( elem ) {
var hash = window.location && window.location.hash;
return hash && hash.slice( 1 ) === elem.id;
},
"root": function( elem ) {
return elem === docElem;
},
"focus": function( elem ) {
return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
},
// Boolean properties
"enabled": createDisabledPseudo( false ),
"disabled": createDisabledPseudo( true ),
"checked": function( elem ) {
// In CSS3, :checked should return both checked and selected elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
var nodeName = elem.nodeName.toLowerCase();
return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
},
"selected": function( elem ) {
// Accessing this property makes selected-by-default
// options in Safari work properly
if ( elem.parentNode ) {
elem.parentNode.selectedIndex;
}
return elem.selected === true;
},
// Contents
"empty": function( elem ) {
// http://www.w3.org/TR/selectors/#empty-pseudo
// :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5),
// but not by others (comment: 8; processing instruction: 7; etc.)
// nodeType < 6 works because attributes (2) do not appear as children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
if ( elem.nodeType < 6 ) {
return false;
}
}
return true;
},
"parent": function( elem ) {
return !Expr.pseudos["empty"]( elem );
},
// Element/input types
"header": function( elem ) {
return rheader.test( elem.nodeName );
},
"input": function( elem ) {
return rinputs.test( elem.nodeName );
},
"button": function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === "button" || name === "button";
},
"text": function( elem ) {
var attr;
return elem.nodeName.toLowerCase() === "input" &&
elem.type === "text" &&
// Support: IE<8
// New HTML5 attribute values (e.g., "search") appear with elem.type === "text"
( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" );
},
// Position-in-collection
"first": createPositionalPseudo(function() {
return [ 0 ];
}),
"last": createPositionalPseudo(function( matchIndexes, length ) {
return [ length - 1 ];
}),
"eq": createPositionalPseudo(function( matchIndexes, length, argument ) {
return [ argument < 0 ? argument + length : argument ];
}),
"even": createPositionalPseudo(function( matchIndexes, length ) {
var i = 0;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"odd": createPositionalPseudo(function( matchIndexes, length ) {
var i = 1;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"lt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; --i >= 0; ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"gt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; ++i < length; ) {
matchIndexes.push( i );
}
return matchIndexes;
})
}
};
Expr.pseudos["nth"] = Expr.pseudos["eq"];
// Add button/input type pseudos
for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) {
Expr.pseudos[ i ] = createInputPseudo( i );
}
for ( i in { submit: true, reset: true } ) {
Expr.pseudos[ i ] = createButtonPseudo( i );
}
// Easy API for creating new setFilters
function setFilters() {}
setFilters.prototype = Expr.filters = Expr.pseudos;
Expr.setFilters = new setFilters();
tokenize = Sizzle.tokenize = function( selector, parseOnly ) {
var matched, match, tokens, type,
soFar, groups, preFilters,
cached = tokenCache[ selector + " " ];
if ( cached ) {
return parseOnly ? 0 : cached.slice( 0 );
}
soFar = selector;
groups = [];
preFilters = Expr.preFilter;
while ( soFar ) {
// Comma and first run
if ( !matched || (match = rcomma.exec( soFar )) ) {
if ( match ) {
// Don't consume trailing commas as valid
soFar = soFar.slice( match[0].length ) || soFar;
}
groups.push( (tokens = []) );
}
matched = false;
// Combinators
if ( (match = rcombinators.exec( soFar )) ) {
matched = match.shift();
tokens.push({
value: matched,
// Cast descendant combinators to space
type: match[0].replace( rtrim, " " )
});
soFar = soFar.slice( matched.length );
}
// Filters
for ( type in Expr.filter ) {
if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
(match = preFilters[ type ]( match ))) ) {
matched = match.shift();
tokens.push({
value: matched,
type: type,
matches: match
});
soFar = soFar.slice( matched.length );
}
}
if ( !matched ) {
break;
}
}
// Return the length of the invalid excess
// if we're just parsing
// Otherwise, throw an error or return tokens
return parseOnly ?
soFar.length :
soFar ?
Sizzle.error( selector ) :
// Cache the tokens
tokenCache( selector, groups ).slice( 0 );
};
function toSelector( tokens ) {
var i = 0,
len = tokens.length,
selector = "";
for ( ; i < len; i++ ) {
selector += tokens[i].value;
}
return selector;
}
function addCombinator( matcher, combinator, base ) {
var dir = combinator.dir,
skip = combinator.next,
key = skip || dir,
checkNonElements = base && key === "parentNode",
doneName = done++;
return combinator.first ?
// Check against closest ancestor/preceding element
function( elem, context, xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
return matcher( elem, context, xml );
}
}
return false;
} :
// Check against all ancestor/preceding elements
function( elem, context, xml ) {
var oldCache, uniqueCache, outerCache,
newCache = [ dirruns, doneName ];
// We can't set arbitrary data on XML nodes, so they don't benefit from combinator caching
if ( xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
if ( matcher( elem, context, xml ) ) {
return true;
}
}
}
} else {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
outerCache = elem[ expando ] || (elem[ expando ] = {});
// Support: IE <9 only
// Defend against cloned attroperties (jQuery gh-1709)
uniqueCache = outerCache[ elem.uniqueID ] || (outerCache[ elem.uniqueID ] = {});
if ( skip && skip === elem.nodeName.toLowerCase() ) {
elem = elem[ dir ] || elem;
} else if ( (oldCache = uniqueCache[ key ]) &&
oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) {
// Assign to newCache so results back-propagate to previous elements
return (newCache[ 2 ] = oldCache[ 2 ]);
} else {
// Reuse newcache so results back-propagate to previous elements
uniqueCache[ key ] = newCache;
// A match means we're done; a fail means we have to keep checking
if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) {
return true;
}
}
}
}
}
return false;
};
}
function elementMatcher( matchers ) {
return matchers.length > 1 ?
function( elem, context, xml ) {
var i = matchers.length;
while ( i-- ) {
if ( !matchers[i]( elem, context, xml ) ) {
return false;
}
}
return true;
} :
matchers[0];
}
function multipleContexts( selector, contexts, results ) {
var i = 0,
len = contexts.length;
for ( ; i < len; i++ ) {
Sizzle( selector, contexts[i], results );
}
return results;
}
function condense( unmatched, map, filter, context, xml ) {
var elem,
newUnmatched = [],
i = 0,
len = unmatched.length,
mapped = map != null;
for ( ; i < len; i++ ) {
if ( (elem = unmatched[i]) ) {
if ( !filter || filter( elem, context, xml ) ) {
newUnmatched.push( elem );
if ( mapped ) {
map.push( i );
}
}
}
}
return newUnmatched;
}
function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
if ( postFilter && !postFilter[ expando ] ) {
postFilter = setMatcher( postFilter );
}
if ( postFinder && !postFinder[ expando ] ) {
postFinder = setMatcher( postFinder, postSelector );
}
return markFunction(function( seed, results, context, xml ) {
var temp, i, elem,
preMap = [],
postMap = [],
preexisting = results.length,
// Get initial elements from seed or context
elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ),
// Prefilter to get matcher input, preserving a map for seed-results synchronization
matcherIn = preFilter && ( seed || !selector ) ?
condense( elems, preMap, preFilter, context, xml ) :
elems,
matcherOut = matcher ?
// If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
postFinder || ( seed ? preFilter : preexisting || postFilter ) ?
// ...intermediate processing is necessary
[] :
// ...otherwise use results directly
results :
matcherIn;
// Find primary matches
if ( matcher ) {
matcher( matcherIn, matcherOut, context, xml );
}
// Apply postFilter
if ( postFilter ) {
temp = condense( matcherOut, postMap );
postFilter( temp, [], context, xml );
// Un-match failing elements by moving them back to matcherIn
i = temp.length;
while ( i-- ) {
if ( (elem = temp[i]) ) {
matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);
}
}
}
if ( seed ) {
if ( postFinder || preFilter ) {
if ( postFinder ) {
// Get the final matcherOut by condensing this intermediate into postFinder contexts
temp = [];
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) ) {
// Restore matcherIn since elem is not yet a final match
temp.push( (matcherIn[i] = elem) );
}
}
postFinder( null, (matcherOut = []), temp, xml );
}
// Move matched elements from seed to results to keep them synchronized
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) &&
(temp = postFinder ? indexOf( seed, elem ) : preMap[i]) > -1 ) {
seed[temp] = !(results[temp] = elem);
}
}
}
// Add elements to results, through postFinder if defined
} else {
matcherOut = condense(
matcherOut === results ?
matcherOut.splice( preexisting, matcherOut.length ) :
matcherOut
);
if ( postFinder ) {
postFinder( null, results, matcherOut, xml );
} else {
push.apply( results, matcherOut );
}
}
});
}
function matcherFromTokens( tokens ) {
var checkContext, matcher, j,
len = tokens.length,
leadingRelative = Expr.relative[ tokens[0].type ],
implicitRelative = leadingRelative || Expr.relative[" "],
i = leadingRelative ? 1 : 0,
// The foundational matcher ensures that elements are reachable from top-level context(s)
matchContext = addCombinator( function( elem ) {
return elem === checkContext;
}, implicitRelative, true ),
matchAnyContext = addCombinator( function( elem ) {
return indexOf( checkContext, elem ) > -1;
}, implicitRelative, true ),
matchers = [ function( elem, context, xml ) {
var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
(checkContext = context).nodeType ?
matchContext( elem, context, xml ) :
matchAnyContext( elem, context, xml ) );
// Avoid hanging onto element (issue #299)
checkContext = null;
return ret;
} ];
for ( ; i < len; i++ ) {
if ( (matcher = Expr.relative[ tokens[i].type ]) ) {
matchers = [ addCombinator(elementMatcher( matchers ), matcher) ];
} else {
matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches );
// Return special upon seeing a positional matcher
if ( matcher[ expando ] ) {
// Find the next relative operator (if any) for proper handling
j = ++i;
for ( ; j < len; j++ ) {
if ( Expr.relative[ tokens[j].type ] ) {
break;
}
}
return setMatcher(
i > 1 && elementMatcher( matchers ),
i > 1 && toSelector(
// If the preceding token was a descendant combinator, insert an implicit any-element `*`
tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" })
).replace( rtrim, "$1" ),
matcher,
i < j && matcherFromTokens( tokens.slice( i, j ) ),
j < len && matcherFromTokens( (tokens = tokens.slice( j )) ),
j < len && toSelector( tokens )
);
}
matchers.push( matcher );
}
}
return elementMatcher( matchers );
}
function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
var bySet = setMatchers.length > 0,
byElement = elementMatchers.length > 0,
superMatcher = function( seed, context, xml, results, outermost ) {
var elem, j, matcher,
matchedCount = 0,
i = "0",
unmatched = seed && [],
setMatched = [],
contextBackup = outermostContext,
// We must always have either seed elements or outermost context
elems = seed || byElement && Expr.find["TAG"]( "*", outermost ),
// Use integer dirruns iff this is the outermost matcher
dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1),
len = elems.length;
if ( outermost ) {
outermostContext = context === document || context || outermost;
}
// Add elements passing elementMatchers directly to results
// Support: IE<9, Safari
// Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id
for ( ; i !== len && (elem = elems[i]) != null; i++ ) {
if ( byElement && elem ) {
j = 0;
if ( !context && elem.ownerDocument !== document ) {
setDocument( elem );
xml = !documentIsHTML;
}
while ( (matcher = elementMatchers[j++]) ) {
if ( matcher( elem, context || document, xml) ) {
results.push( elem );
break;
}
}
if ( outermost ) {
dirruns = dirrunsUnique;
}
}
// Track unmatched elements for set filters
if ( bySet ) {
// They will have gone through all possible matchers
if ( (elem = !matcher && elem) ) {
matchedCount--;
}
// Lengthen the array for every element, matched or not
if ( seed ) {
unmatched.push( elem );
}
}
}
// `i` is now the count of elements visited above, and adding it to `matchedCount`
// makes the latter nonnegative.
matchedCount += i;
// Apply set filters to unmatched elements
// NOTE: This can be skipped if there are no unmatched elements (i.e., `matchedCount`
// equals `i`), unless we didn't visit _any_ elements in the above loop because we have
// no element matchers and no seed.
// Incrementing an initially-string "0" `i` allows `i` to remain a string only in that
// case, which will result in a "00" `matchedCount` that differs from `i` but is also
// numerically zero.
if ( bySet && i !== matchedCount ) {
j = 0;
while ( (matcher = setMatchers[j++]) ) {
matcher( unmatched, setMatched, context, xml );
}
if ( seed ) {
// Reintegrate element matches to eliminate the need for sorting
if ( matchedCount > 0 ) {
while ( i-- ) {
if ( !(unmatched[i] || setMatched[i]) ) {
setMatched[i] = pop.call( results );
}
}
}
// Discard index placeholder values to get only actual matches
setMatched = condense( setMatched );
}
// Add matches to results
push.apply( results, setMatched );
// Seedless set matches succeeding multiple successful matchers stipulate sorting
if ( outermost && !seed && setMatched.length > 0 &&
( matchedCount + setMatchers.length ) > 1 ) {
Sizzle.uniqueSort( results );
}
}
// Override manipulation of globals by nested matchers
if ( outermost ) {
dirruns = dirrunsUnique;
outermostContext = contextBackup;
}
return unmatched;
};
return bySet ?
markFunction( superMatcher ) :
superMatcher;
}
compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) {
var i,
setMatchers = [],
elementMatchers = [],
cached = compilerCache[ selector + " " ];
if ( !cached ) {
// Generate a function of recursive functions that can be used to check each element
if ( !match ) {
match = tokenize( selector );
}
i = match.length;
while ( i-- ) {
cached = matcherFromTokens( match[i] );
if ( cached[ expando ] ) {
setMatchers.push( cached );
} else {
elementMatchers.push( cached );
}
}
// Cache the compiled function
cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );
// Save selector and tokenization
cached.selector = selector;
}
return cached;
};
/**
* A low-level selection function that works with Sizzle's compiled
* selector functions
* @param {String|Function} selector A selector or a pre-compiled
* selector function built with Sizzle.compile
* @param {Element} context
* @param {Array} [results]
* @param {Array} [seed] A set of elements to match against
*/
select = Sizzle.select = function( selector, context, results, seed ) {
var i, tokens, token, type, find,
compiled = typeof selector === "function" && selector,
match = !seed && tokenize( (selector = compiled.selector || selector) );
results = results || [];
// Try to minimize operations if there is only one selector in the list and no seed
// (the latter of which guarantees us context)
if ( match.length === 1 ) {
// Reduce context if the leading compound selector is an ID
tokens = match[0] = match[0].slice( 0 );
if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[1].type ] ) {
context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0];
if ( !context ) {
return results;
// Precompiled matchers will still verify ancestry, so step up a level
} else if ( compiled ) {
context = context.parentNode;
}
selector = selector.slice( tokens.shift().value.length );
}
// Fetch a seed set for right-to-left matching
i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length;
while ( i-- ) {
token = tokens[i];
// Abort if we hit a combinator
if ( Expr.relative[ (type = token.type) ] ) {
break;
}
if ( (find = Expr.find[ type ]) ) {
// Search, expanding context for leading sibling combinators
if ( (seed = find(
token.matches[0].replace( runescape, funescape ),
rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context
)) ) {
// If seed is empty or no tokens remain, we can return early
tokens.splice( i, 1 );
selector = seed.length && toSelector( tokens );
if ( !selector ) {
push.apply( results, seed );
return results;
}
break;
}
}
}
}
// Compile and execute a filtering function if one is not provided
// Provide `match` to avoid retokenization if we modified the selector above
( compiled || compile( selector, match ) )(
seed,
context,
!documentIsHTML,
results,
!context || rsibling.test( selector ) && testContext( context.parentNode ) || context
);
return results;
};
// One-time assignments
// Sort stability
support.sortStable = expando.split("").sort( sortOrder ).join("") === expando;
// Support: Chrome 14-35+
// Always assume duplicates if they aren't passed to the comparison function
support.detectDuplicates = !!hasDuplicate;
// Initialize against the default document
setDocument();
// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27)
// Detached nodes confoundingly follow *each other*
support.sortDetached = assert(function( el ) {
// Should return 1, but returns 4 (following)
return el.compareDocumentPosition( document.createElement("fieldset") ) & 1;
});
// Support: IE<8
// Prevent attribute/property "interpolation"
// https://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
if ( !assert(function( el ) {
el.innerHTML = "<a href='#'></a>";
return el.firstChild.getAttribute("href") === "#" ;
}) ) {
addHandle( "type|href|height|width", function( elem, name, isXML ) {
if ( !isXML ) {
return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 );
}
});
}
// Support: IE<9
// Use defaultValue in place of getAttribute("value")
if ( !support.attributes || !assert(function( el ) {
el.innerHTML = "<input/>";
el.firstChild.setAttribute( "value", "" );
return el.firstChild.getAttribute( "value" ) === "";
}) ) {
addHandle( "value", function( elem, name, isXML ) {
if ( !isXML && elem.nodeName.toLowerCase() === "input" ) {
return elem.defaultValue;
}
});
}
// Support: IE<9
// Use getAttributeNode to fetch booleans when getAttribute lies
if ( !assert(function( el ) {
return el.getAttribute("disabled") == null;
}) ) {
addHandle( booleans, function( elem, name, isXML ) {
var val;
if ( !isXML ) {
return elem[ name ] === true ? name.toLowerCase() :
(val = elem.getAttributeNode( name )) && val.specified ?
val.value :
null;
}
});
}
return Sizzle;
})( window );
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
// Deprecated
jQuery.expr[ ":" ] = jQuery.expr.pseudos;
jQuery.uniqueSort = jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
jQuery.escapeSelector = Sizzle.escape;
var dir = function( elem, dir, until ) {
var matched = [],
truncate = until !== undefined;
while ( ( elem = elem[ dir ] ) && elem.nodeType !== 9 ) {
if ( elem.nodeType === 1 ) {
if ( truncate && jQuery( elem ).is( until ) ) {
break;
}
matched.push( elem );
}
}
return matched;
};
var siblings = function( n, elem ) {
var matched = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
matched.push( n );
}
}
return matched;
};
var rneedsContext = jQuery.expr.match.needsContext;
function nodeName( elem, name ) {
return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
};
var rsingleTag = ( /^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i );
// Implement the identical functionality for filter and not
function winnow( elements, qualifier, not ) {
if ( isFunction( qualifier ) ) {
return jQuery.grep( elements, function( elem, i ) {
return !!qualifier.call( elem, i, elem ) !== not;
} );
}
// Single element
if ( qualifier.nodeType ) {
return jQuery.grep( elements, function( elem ) {
return ( elem === qualifier ) !== not;
} );
}
// Arraylike of elements (jQuery, arguments, Array)
if ( typeof qualifier !== "string" ) {
return jQuery.grep( elements, function( elem ) {
return ( indexOf.call( qualifier, elem ) > -1 ) !== not;
} );
}
// Filtered directly for both simple and complex selectors
return jQuery.filter( qualifier, elements, not );
}
jQuery.filter = function( expr, elems, not ) {
var elem = elems[ 0 ];
if ( not ) {
expr = ":not(" + expr + ")";
}
if ( elems.length === 1 && elem.nodeType === 1 ) {
return jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [];
}
return jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) {
return elem.nodeType === 1;
} ) );
};
jQuery.fn.extend( {
find: function( selector ) {
var i, ret,
len = this.length,
self = this;
if ( typeof selector !== "string" ) {
return this.pushStack( jQuery( selector ).filter( function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( self[ i ], this ) ) {
return true;
}
}
} ) );
}
ret = this.pushStack( [] );
for ( i = 0; i < len; i++ ) {
jQuery.find( selector, self[ i ], ret );
}
return len > 1 ? jQuery.uniqueSort( ret ) : ret;
},
filter: function( selector ) {
return this.pushStack( winnow( this, selector || [], false ) );
},
not: function( selector ) {
return this.pushStack( winnow( this, selector || [], true ) );
},
is: function( selector ) {
return !!winnow(
this,
// If this is a positional/relative selector, check membership in the returned set
// so $("p:first").is("p:last") won't return true for a doc with two "p".
typeof selector === "string" && rneedsContext.test( selector ) ?
jQuery( selector ) :
selector || [],
false
).length;
}
} );
// Initialize a jQuery object
// A central reference to the root jQuery(document)
var rootjQuery,
// A simple way to check for HTML strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
// Strict HTML recognition (#11290: must start with <)
// Shortcut simple #id case for speed
rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/,
init = jQuery.fn.init = function( selector, context, root ) {
var match, elem;
// HANDLE: $(""), $(null), $(undefined), $(false)
if ( !selector ) {
return this;
}
// Method init() accepts an alternate rootjQuery
// so migrate can support jQuery.sub (gh-2101)
root = root || rootjQuery;
// Handle HTML strings
if ( typeof selector === "string" ) {
if ( selector[ 0 ] === "<" &&
selector[ selector.length - 1 ] === ">" &&
selector.length >= 3 ) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [ null, selector, null ];
} else {
match = rquickExpr.exec( selector );
}
// Match html or make sure no context is specified for #id
if ( match && ( match[ 1 ] || !context ) ) {
// HANDLE: $(html) -> $(array)
if ( match[ 1 ] ) {
context = context instanceof jQuery ? context[ 0 ] : context;
// Option to run scripts is true for back-compat
// Intentionally let the error be thrown if parseHTML is not present
jQuery.merge( this, jQuery.parseHTML(
match[ 1 ],
context && context.nodeType ? context.ownerDocument || context : document,
true
) );
// HANDLE: $(html, props)
if ( rsingleTag.test( match[ 1 ] ) && jQuery.isPlainObject( context ) ) {
for ( match in context ) {
// Properties of context are called as methods if possible
if ( isFunction( this[ match ] ) ) {
this[ match ]( context[ match ] );
// ...and otherwise set as attributes
} else {
this.attr( match, context[ match ] );
}
}
}
return this;
// HANDLE: $(#id)
} else {
elem = document.getElementById( match[ 2 ] );
if ( elem ) {
// Inject the element directly into the jQuery object
this[ 0 ] = elem;
this.length = 1;
}
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return ( context || root ).find( selector );
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return this.constructor( context ).find( selector );
}
// HANDLE: $(DOMElement)
} else if ( selector.nodeType ) {
this[ 0 ] = selector;
this.length = 1;
return this;
// HANDLE: $(function)
// Shortcut for document ready
} else if ( isFunction( selector ) ) {
return root.ready !== undefined ?
root.ready( selector ) :
// Execute immediately if ready is not present
selector( jQuery );
}
return jQuery.makeArray( selector, this );
};
// Give the init function the jQuery prototype for later instantiation
init.prototype = jQuery.fn;
// Initialize central reference
rootjQuery = jQuery( document );
var rparentsprev = /^(?:parents|prev(?:Until|All))/,
// Methods guaranteed to produce a unique set when starting from a unique set
guaranteedUnique = {
children: true,
contents: true,
next: true,
prev: true
};
jQuery.fn.extend( {
has: function( target ) {
var targets = jQuery( target, this ),
l = targets.length;
return this.filter( function() {
var i = 0;
for ( ; i < l; i++ ) {
if ( jQuery.contains( this, targets[ i ] ) ) {
return true;
}
}
} );
},
closest: function( selectors, context ) {
var cur,
i = 0,
l = this.length,
matched = [],
targets = typeof selectors !== "string" && jQuery( selectors );
// Positional selectors never match, since there's no _selection_ context
if ( !rneedsContext.test( selectors ) ) {
for ( ; i < l; i++ ) {
for ( cur = this[ i ]; cur && cur !== context; cur = cur.parentNode ) {
// Always skip document fragments
if ( cur.nodeType < 11 && ( targets ?
targets.index( cur ) > -1 :
// Don't pass non-elements to Sizzle
cur.nodeType === 1 &&
jQuery.find.matchesSelector( cur, selectors ) ) ) {
matched.push( cur );
break;
}
}
}
}
return this.pushStack( matched.length > 1 ? jQuery.uniqueSort( matched ) : matched );
},
// Determine the position of an element within the set
index: function( elem ) {
// No argument, return index in parent
if ( !elem ) {
return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1;
}
// Index in selector
if ( typeof elem === "string" ) {
return indexOf.call( jQuery( elem ), this[ 0 ] );
}
// Locate the position of the desired element
return indexOf.call( this,
// If it receives a jQuery object, the first element is used
elem.jquery ? elem[ 0 ] : elem
);
},
add: function( selector, context ) {
return this.pushStack(
jQuery.uniqueSort(
jQuery.merge( this.get(), jQuery( selector, context ) )
)
);
},
addBack: function( selector ) {
return this.add( selector == null ?
this.prevObject : this.prevObject.filter( selector )
);
}
} );
function sibling( cur, dir ) {
while ( ( cur = cur[ dir ] ) && cur.nodeType !== 1 ) {}
return cur;
}
jQuery.each( {
parent: function( elem ) {
var parent = elem.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
parents: function( elem ) {
return dir( elem, "parentNode" );
},
parentsUntil: function( elem, i, until ) {
return dir( elem, "parentNode", until );
},
next: function( elem ) {
return sibling( elem, "nextSibling" );
},
prev: function( elem ) {
return sibling( elem, "previousSibling" );
},
nextAll: function( elem ) {
return dir( elem, "nextSibling" );
},
prevAll: function( elem ) {
return dir( elem, "previousSibling" );
},
nextUntil: function( elem, i, until ) {
return dir( elem, "nextSibling", until );
},
prevUntil: function( elem, i, until ) {
return dir( elem, "previousSibling", until );
},
siblings: function( elem ) {
return siblings( ( elem.parentNode || {} ).firstChild, elem );
},
children: function( elem ) {
return siblings( elem.firstChild );
},
contents: function( elem ) {
if ( nodeName( elem, "iframe" ) ) {
return elem.contentDocument;
}
// Support: IE 9 - 11 only, iOS 7 only, Android Browser <=4.3 only
// Treat the template element as a regular one in browsers that
// don't support it.
if ( nodeName( elem, "template" ) ) {
elem = elem.content || elem;
}
return jQuery.merge( [], elem.childNodes );
}
}, function( name, fn ) {
jQuery.fn[ name ] = function( until, selector ) {
var matched = jQuery.map( this, fn, until );
if ( name.slice( -5 ) !== "Until" ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
matched = jQuery.filter( selector, matched );
}
if ( this.length > 1 ) {
// Remove duplicates
if ( !guaranteedUnique[ name ] ) {
jQuery.uniqueSort( matched );
}
// Reverse order for parents* and prev-derivatives
if ( rparentsprev.test( name ) ) {
matched.reverse();
}
}
return this.pushStack( matched );
};
} );
var rnothtmlwhite = ( /[^\x20\t\r\n\f]+/g );
// Convert String-formatted options into Object-formatted ones
function createOptions( options ) {
var object = {};
jQuery.each( options.match( rnothtmlwhite ) || [], function( _, flag ) {
object[ flag ] = true;
} );
return object;
}
/*
* Create a callback list using the following parameters:
*
* options: an optional list of space-separated options that will change how
* the callback list behaves or a more traditional option object
*
* By default a callback list will act like an event callback list and can be
* "fired" multiple times.
*
* Possible options:
*
* once: will ensure the callback list can only be fired once (like a Deferred)
*
* memory: will keep track of previous values and will call any callback added
* after the list has been fired right away with the latest "memorized"
* values (like a Deferred)
*
* unique: will ensure a callback can only be added once (no duplicate in the list)
*
* stopOnFalse: interrupt callings when a callback returns false
*
*/
jQuery.Callbacks = function( options ) {
// Convert options from String-formatted to Object-formatted if needed
// (we check in cache first)
options = typeof options === "string" ?
createOptions( options ) :
jQuery.extend( {}, options );
var // Flag to know if list is currently firing
firing,
// Last fire value for non-forgettable lists
memory,
// Flag to know if list was already fired
fired,
// Flag to prevent firing
locked,
// Actual callback list
list = [],
// Queue of execution data for repeatable lists
queue = [],
// Index of currently firing callback (modified by add/remove as needed)
firingIndex = -1,
// Fire callbacks
fire = function() {
// Enforce single-firing
locked = locked || options.once;
// Execute callbacks for all pending executions,
// respecting firingIndex overrides and runtime changes
fired = firing = true;
for ( ; queue.length; firingIndex = -1 ) {
memory = queue.shift();
while ( ++firingIndex < list.length ) {
// Run callback and check for early termination
if ( list[ firingIndex ].apply( memory[ 0 ], memory[ 1 ] ) === false &&
options.stopOnFalse ) {
// Jump to end and forget the data so .add doesn't re-fire
firingIndex = list.length;
memory = false;
}
}
}
// Forget the data if we're done with it
if ( !options.memory ) {
memory = false;
}
firing = false;
// Clean up if we're done firing for good
if ( locked ) {
// Keep an empty list if we have data for future add calls
if ( memory ) {
list = [];
// Otherwise, this object is spent
} else {
list = "";
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function() {
if ( list ) {
// If we have memory from a past run, we should fire after adding
if ( memory && !firing ) {
firingIndex = list.length - 1;
queue.push( memory );
}
( function add( args ) {
jQuery.each( args, function( _, arg ) {
if ( isFunction( arg ) ) {
if ( !options.unique || !self.has( arg ) ) {
list.push( arg );
}
} else if ( arg && arg.length && toType( arg ) !== "string" ) {
// Inspect recursively
add( arg );
}
} );
} )( arguments );
if ( memory && !firing ) {
fire();
}
}
return this;
},
// Remove a callback from the list
remove: function() {
jQuery.each( arguments, function( _, arg ) {
var index;
while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
list.splice( index, 1 );
// Handle firing indexes
if ( index <= firingIndex ) {
firingIndex--;
}
}
} );
return this;
},
// Check if a given callback is in the list.
// If no argument is given, return whether or not list has callbacks attached.
has: function( fn ) {
return fn ?
jQuery.inArray( fn, list ) > -1 :
list.length > 0;
},
// Remove all callbacks from the list
empty: function() {
if ( list ) {
list = [];
}
return this;
},
// Disable .fire and .add
// Abort any current/pending executions
// Clear all callbacks and values
disable: function() {
locked = queue = [];
list = memory = "";
return this;
},
disabled: function() {
return !list;
},
// Disable .fire
// Also disable .add unless we have memory (since it would have no effect)
// Abort any pending executions
lock: function() {
locked = queue = [];
if ( !memory && !firing ) {
list = memory = "";
}
return this;
},
locked: function() {
return !!locked;
},
// Call all callbacks with the given context and arguments
fireWith: function( context, args ) {
if ( !locked ) {
args = args || [];
args = [ context, args.slice ? args.slice() : args ];
queue.push( args );
if ( !firing ) {
fire();
}
}
return this;
},
// Call all the callbacks with the given arguments
fire: function() {
self.fireWith( this, arguments );
return this;
},
// To know if the callbacks have already been called at least once
fired: function() {
return !!fired;
}
};
return self;
};
function Identity( v ) {
return v;
}
function Thrower( ex ) {
throw ex;
}
function adoptValue( value, resolve, reject, noValue ) {
var method;
try {
// Check for promise aspect first to privilege synchronous behavior
if ( value && isFunction( ( method = value.promise ) ) ) {
method.call( value ).done( resolve ).fail( reject );
// Other thenables
} else if ( value && isFunction( ( method = value.then ) ) ) {
method.call( value, resolve, reject );
// Other non-thenables
} else {
// Control `resolve` arguments by letting Array#slice cast boolean `noValue` to integer:
// * false: [ value ].slice( 0 ) => resolve( value )
// * true: [ value ].slice( 1 ) => resolve()
resolve.apply( undefined, [ value ].slice( noValue ) );
}
// For Promises/A+, convert exceptions into rejections
// Since jQuery.when doesn't unwrap thenables, we can skip the extra checks appearing in
// Deferred#then to conditionally suppress rejection.
} catch ( value ) {
// Support: Android 4.0 only
// Strict mode functions invoked without .call/.apply get global-object context
reject.apply( undefined, [ value ] );
}
}
jQuery.extend( {
Deferred: function( func ) {
var tuples = [
// action, add listener, callbacks,
// ... .then handlers, argument index, [final state]
[ "notify", "progress", jQuery.Callbacks( "memory" ),
jQuery.Callbacks( "memory" ), 2 ],
[ "resolve", "done", jQuery.Callbacks( "once memory" ),
jQuery.Callbacks( "once memory" ), 0, "resolved" ],
[ "reject", "fail", jQuery.Callbacks( "once memory" ),
jQuery.Callbacks( "once memory" ), 1, "rejected" ]
],
state = "pending",
promise = {
state: function() {
return state;
},
always: function() {
deferred.done( arguments ).fail( arguments );
return this;
},
"catch": function( fn ) {
return promise.then( null, fn );
},
// Keep pipe for back-compat
pipe: function( /* fnDone, fnFail, fnProgress */ ) {
var fns = arguments;
return jQuery.Deferred( function( newDefer ) {
jQuery.each( tuples, function( i, tuple ) {
// Map tuples (progress, done, fail) to arguments (done, fail, progress)
var fn = isFunction( fns[ tuple[ 4 ] ] ) && fns[ tuple[ 4 ] ];
// deferred.progress(function() { bind to newDefer or newDefer.notify })
// deferred.done(function() { bind to newDefer or newDefer.resolve })
// deferred.fail(function() { bind to newDefer or newDefer.reject })
deferred[ tuple[ 1 ] ]( function() {
var returned = fn && fn.apply( this, arguments );
if ( returned && isFunction( returned.promise ) ) {
returned.promise()
.progress( newDefer.notify )
.done( newDefer.resolve )
.fail( newDefer.reject );
} else {
newDefer[ tuple[ 0 ] + "With" ](
this,
fn ? [ returned ] : arguments
);
}
} );
} );
fns = null;
} ).promise();
},
then: function( onFulfilled, onRejected, onProgress ) {
var maxDepth = 0;
function resolve( depth, deferred, handler, special ) {
return function() {
var that = this,
args = arguments,
mightThrow = function() {
var returned, then;
// Support: Promises/A+ section 2.3.3.3.3
// https://promisesaplus.com/#point-59
// Ignore double-resolution attempts
if ( depth < maxDepth ) {
return;
}
returned = handler.apply( that, args );
// Support: Promises/A+ section 2.3.1
// https://promisesaplus.com/#point-48
if ( returned === deferred.promise() ) {
throw new TypeError( "Thenable self-resolution" );
}
// Support: Promises/A+ sections 2.3.3.1, 3.5
// https://promisesaplus.com/#point-54
// https://promisesaplus.com/#point-75
// Retrieve `then` only once
then = returned &&
// Support: Promises/A+ section 2.3.4
// https://promisesaplus.com/#point-64
// Only check objects and functions for thenability
( typeof returned === "object" ||
typeof returned === "function" ) &&
returned.then;
// Handle a returned thenable
if ( isFunction( then ) ) {
// Special processors (notify) just wait for resolution
if ( special ) {
then.call(
returned,
resolve( maxDepth, deferred, Identity, special ),
resolve( maxDepth, deferred, Thrower, special )
);
// Normal processors (resolve) also hook into progress
} else {
// ...and disregard older resolution values
maxDepth++;
then.call(
returned,
resolve( maxDepth, deferred, Identity, special ),
resolve( maxDepth, deferred, Thrower, special ),
resolve( maxDepth, deferred, Identity,
deferred.notifyWith )
);
}
// Handle all other returned values
} else {
// Only substitute handlers pass on context
// and multiple values (non-spec behavior)
if ( handler !== Identity ) {
that = undefined;
args = [ returned ];
}
// Process the value(s)
// Default process is resolve
( special || deferred.resolveWith )( that, args );
}
},
// Only normal processors (resolve) catch and reject exceptions
process = special ?
mightThrow :
function() {
try {
mightThrow();
} catch ( e ) {
if ( jQuery.Deferred.exceptionHook ) {
jQuery.Deferred.exceptionHook( e,
process.stackTrace );
}
// Support: Promises/A+ section 2.3.3.3.4.1
// https://promisesaplus.com/#point-61
// Ignore post-resolution exceptions
if ( depth + 1 >= maxDepth ) {
// Only substitute handlers pass on context
// and multiple values (non-spec behavior)
if ( handler !== Thrower ) {
that = undefined;
args = [ e ];
}
deferred.rejectWith( that, args );
}
}
};
// Support: Promises/A+ section 2.3.3.3.1
// https://promisesaplus.com/#point-57
// Re-resolve promises immediately to dodge false rejection from
// subsequent errors
if ( depth ) {
process();
} else {
// Call an optional hook to record the stack, in case of exception
// since it's otherwise lost when execution goes async
if ( jQuery.Deferred.getStackHook ) {
process.stackTrace = jQuery.Deferred.getStackHook();
}
window.setTimeout( process );
}
};
}
return jQuery.Deferred( function( newDefer ) {
// progress_handlers.add( ... )
tuples[ 0 ][ 3 ].add(
resolve(
0,
newDefer,
isFunction( onProgress ) ?
onProgress :
Identity,
newDefer.notifyWith
)
);
// fulfilled_handlers.add( ... )
tuples[ 1 ][ 3 ].add(
resolve(
0,
newDefer,
isFunction( onFulfilled ) ?
onFulfilled :
Identity
)
);
// rejected_handlers.add( ... )
tuples[ 2 ][ 3 ].add(
resolve(
0,
newDefer,
isFunction( onRejected ) ?
onRejected :
Thrower
)
);
} ).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj ) {
return obj != null ? jQuery.extend( obj, promise ) : promise;
}
},
deferred = {};
// Add list-specific methods
jQuery.each( tuples, function( i, tuple ) {
var list = tuple[ 2 ],
stateString = tuple[ 5 ];
// promise.progress = list.add
// promise.done = list.add
// promise.fail = list.add
promise[ tuple[ 1 ] ] = list.add;
// Handle state
if ( stateString ) {
list.add(
function() {
// state = "resolved" (i.e., fulfilled)
// state = "rejected"
state = stateString;
},
// rejected_callbacks.disable
// fulfilled_callbacks.disable
tuples[ 3 - i ][ 2 ].disable,
// rejected_handlers.disable
// fulfilled_handlers.disable
tuples[ 3 - i ][ 3 ].disable,
// progress_callbacks.lock
tuples[ 0 ][ 2 ].lock,
// progress_handlers.lock
tuples[ 0 ][ 3 ].lock
);
}
// progress_handlers.fire
// fulfilled_handlers.fire
// rejected_handlers.fire
list.add( tuple[ 3 ].fire );
// deferred.notify = function() { deferred.notifyWith(...) }
// deferred.resolve = function() { deferred.resolveWith(...) }
// deferred.reject = function() { deferred.rejectWith(...) }
deferred[ tuple[ 0 ] ] = function() {
deferred[ tuple[ 0 ] + "With" ]( this === deferred ? undefined : this, arguments );
return this;
};
// deferred.notifyWith = list.fireWith
// deferred.resolveWith = list.fireWith
// deferred.rejectWith = list.fireWith
deferred[ tuple[ 0 ] + "With" ] = list.fireWith;
} );
// Make the deferred a promise
promise.promise( deferred );
// Call given func if any
if ( func ) {
func.call( deferred, deferred );
}
// All done!
return deferred;
},
// Deferred helper
when: function( singleValue ) {
var
// count of uncompleted subordinates
remaining = arguments.length,
// count of unprocessed arguments
i = remaining,
// subordinate fulfillment data
resolveContexts = Array( i ),
resolveValues = slice.call( arguments ),
// the master Deferred
master = jQuery.Deferred(),
// subordinate callback factory
updateFunc = function( i ) {
return function( value ) {
resolveContexts[ i ] = this;
resolveValues[ i ] = arguments.length > 1 ? slice.call( arguments ) : value;
if ( !( --remaining ) ) {
master.resolveWith( resolveContexts, resolveValues );
}
};
};
// Single- and empty arguments are adopted like Promise.resolve
if ( remaining <= 1 ) {
adoptValue( singleValue, master.done( updateFunc( i ) ).resolve, master.reject,
!remaining );
// Use .then() to unwrap secondary thenables (cf. gh-3000)
if ( master.state() === "pending" ||
isFunction( resolveValues[ i ] && resolveValues[ i ].then ) ) {
return master.then();
}
}
// Multiple arguments are aggregated like Promise.all array elements
while ( i-- ) {
adoptValue( resolveValues[ i ], updateFunc( i ), master.reject );
}
return master.promise();
}
} );
// These usually indicate a programmer mistake during development,
// warn about them ASAP rather than swallowing them by default.
var rerrorNames = /^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/;
jQuery.Deferred.exceptionHook = function( error, stack ) {
// Support: IE 8 - 9 only
// Console exists when dev tools are open, which can happen at any time
if ( window.console && window.console.warn && error && rerrorNames.test( error.name ) ) {
window.console.warn( "jQuery.Deferred exception: " + error.message, error.stack, stack );
}
};
jQuery.readyException = function( error ) {
window.setTimeout( function() {
throw error;
} );
};
// The deferred used on DOM ready
var readyList = jQuery.Deferred();
jQuery.fn.ready = function( fn ) {
readyList
.then( fn )
// Wrap jQuery.readyException in a function so that the lookup
// happens at the time of error handling instead of callback
// registration.
.catch( function( error ) {
jQuery.readyException( error );
} );
return this;
};
jQuery.extend( {
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Handle when the DOM is ready
ready: function( wait ) {
// Abort if there are pending holds or we're already ready
if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
return;
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.resolveWith( document, [ jQuery ] );
}
} );
jQuery.ready.then = readyList.then;
// The ready event handler and self cleanup method
function completed() {
document.removeEventListener( "DOMContentLoaded", completed );
window.removeEventListener( "load", completed );
jQuery.ready();
}
// Catch cases where $(document).ready() is called
// after the browser event has already occurred.
// Support: IE <=9 - 10 only
// Older IE sometimes signals "interactive" too soon
if ( document.readyState === "complete" ||
( document.readyState !== "loading" && !document.documentElement.doScroll ) ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
window.setTimeout( jQuery.ready );
} else {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", completed );
// A fallback to window.onload, that will always work
window.addEventListener( "load", completed );
}
// Multifunctional method to get and set values of a collection
// The value/s can optionally be executed if it's a function
var access = function( elems, fn, key, value, chainable, emptyGet, raw ) {
var i = 0,
len = elems.length,
bulk = key == null;
// Sets many values
if ( toType( key ) === "object" ) {
chainable = true;
for ( i in key ) {
access( elems, fn, i, key[ i ], true, emptyGet, raw );
}
// Sets one value
} else if ( value !== undefined ) {
chainable = true;
if ( !isFunction( value ) ) {
raw = true;
}
if ( bulk ) {
// Bulk operations run against the entire set
if ( raw ) {
fn.call( elems, value );
fn = null;
// ...except when executing function values
} else {
bulk = fn;
fn = function( elem, key, value ) {
return bulk.call( jQuery( elem ), value );
};
}
}
if ( fn ) {
for ( ; i < len; i++ ) {
fn(
elems[ i ], key, raw ?
value :
value.call( elems[ i ], i, fn( elems[ i ], key ) )
);
}
}
}
if ( chainable ) {
return elems;
}
// Gets
if ( bulk ) {
return fn.call( elems );
}
return len ? fn( elems[ 0 ], key ) : emptyGet;
};
// Matches dashed string for camelizing
var rmsPrefix = /^-ms-/,
rdashAlpha = /-([a-z])/g;
// Used by camelCase as callback to replace()
function fcamelCase( all, letter ) {
return letter.toUpperCase();
}
// Convert dashed to camelCase; used by the css and data modules
// Support: IE <=9 - 11, Edge 12 - 15
// Microsoft forgot to hump their vendor prefix (#9572)
function camelCase( string ) {
return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
}
var acceptData = function( owner ) {
// Accepts only:
// - Node
// - Node.ELEMENT_NODE
// - Node.DOCUMENT_NODE
// - Object
// - Any
return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType );
};
function Data() {
this.expando = jQuery.expando + Data.uid++;
}
Data.uid = 1;
Data.prototype = {
cache: function( owner ) {
// Check if the owner object already has a cache
var value = owner[ this.expando ];
// If not, create one
if ( !value ) {
value = {};
// We can accept data for non-element nodes in modern browsers,
// but we should not, see #8335.
// Always return an empty object.
if ( acceptData( owner ) ) {
// If it is a node unlikely to be stringify-ed or looped over
// use plain assignment
if ( owner.nodeType ) {
owner[ this.expando ] = value;
// Otherwise secure it in a non-enumerable property
// configurable must be true to allow the property to be
// deleted when data is removed
} else {
Object.defineProperty( owner, this.expando, {
value: value,
configurable: true
} );
}
}
}
return value;
},
set: function( owner, data, value ) {
var prop,
cache = this.cache( owner );
// Handle: [ owner, key, value ] args
// Always use camelCase key (gh-2257)
if ( typeof data === "string" ) {
cache[ camelCase( data ) ] = value;
// Handle: [ owner, { properties } ] args
} else {
// Copy the properties one-by-one to the cache object
for ( prop in data ) {
cache[ camelCase( prop ) ] = data[ prop ];
}
}
return cache;
},
get: function( owner, key ) {
return key === undefined ?
this.cache( owner ) :
// Always use camelCase key (gh-2257)
owner[ this.expando ] && owner[ this.expando ][ camelCase( key ) ];
},
access: function( owner, key, value ) {
// In cases where either:
//
// 1. No key was specified
// 2. A string key was specified, but no value provided
//
// Take the "read" path and allow the get method to determine
// which value to return, respectively either:
//
// 1. The entire cache object
// 2. The data stored at the key
//
if ( key === undefined ||
( ( key && typeof key === "string" ) && value === undefined ) ) {
return this.get( owner, key );
}
// When the key is not a string, or both a key and value
// are specified, set or extend (existing objects) with either:
//
// 1. An object of properties
// 2. A key and value
//
this.set( owner, key, value );
// Since the "set" path can have two possible entry points
// return the expected data based on which path was taken[*]
return value !== undefined ? value : key;
},
remove: function( owner, key ) {
var i,
cache = owner[ this.expando ];
if ( cache === undefined ) {
return;
}
if ( key !== undefined ) {
// Support array or space separated string of keys
if ( Array.isArray( key ) ) {
// If key is an array of keys...
// We always set camelCase keys, so remove that.
key = key.map( camelCase );
} else {
key = camelCase( key );
// If a key with the spaces exists, use it.
// Otherwise, create an array by matching non-whitespace
key = key in cache ?
[ key ] :
( key.match( rnothtmlwhite ) || [] );
}
i = key.length;
while ( i-- ) {
delete cache[ key[ i ] ];
}
}
// Remove the expando if there's no more data
if ( key === undefined || jQuery.isEmptyObject( cache ) ) {
// Support: Chrome <=35 - 45
// Webkit & Blink performance suffers when deleting properties
// from DOM nodes, so set to undefined instead
// https://bugs.chromium.org/p/chromium/issues/detail?id=378607 (bug restricted)
if ( owner.nodeType ) {
owner[ this.expando ] = undefined;
} else {
delete owner[ this.expando ];
}
}
},
hasData: function( owner ) {
var cache = owner[ this.expando ];
return cache !== undefined && !jQuery.isEmptyObject( cache );
}
};
var dataPriv = new Data();
var dataUser = new Data();
// Implementation Summary
//
// 1. Enforce API surface and semantic compatibility with 1.9.x branch
// 2. Improve the module's maintainability by reducing the storage
// paths to a single mechanism.
// 3. Use the same single mechanism to support "private" and "user" data.
// 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData)
// 5. Avoid exposing implementation details on user objects (eg. expando properties)
// 6. Provide a clear path for implementation upgrade to WeakMap in 2014
var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,
rmultiDash = /[A-Z]/g;
function getData( data ) {
if ( data === "true" ) {
return true;
}
if ( data === "false" ) {
return false;
}
if ( data === "null" ) {
return null;
}
// Only convert to a number if it doesn't change the string
if ( data === +data + "" ) {
return +data;
}
if ( rbrace.test( data ) ) {
return JSON.parse( data );
}
return data;
}
function dataAttr( elem, key, data ) {
var name;
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
name = "data-" + key.replace( rmultiDash, "-$&" ).toLowerCase();
data = elem.getAttribute( name );
if ( typeof data === "string" ) {
try {
data = getData( data );
} catch ( e ) {}
// Make sure we set the data so it isn't changed later
dataUser.set( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
jQuery.extend( {
hasData: function( elem ) {
return dataUser.hasData( elem ) || dataPriv.hasData( elem );
},
data: function( elem, name, data ) {
return dataUser.access( elem, name, data );
},
removeData: function( elem, name ) {
dataUser.remove( elem, name );
},
// TODO: Now that all calls to _data and _removeData have been replaced
// with direct calls to dataPriv methods, these can be deprecated.
_data: function( elem, name, data ) {
return dataPriv.access( elem, name, data );
},
_removeData: function( elem, name ) {
dataPriv.remove( elem, name );
}
} );
jQuery.fn.extend( {
data: function( key, value ) {
var i, name, data,
elem = this[ 0 ],
attrs = elem && elem.attributes;
// Gets all values
if ( key === undefined ) {
if ( this.length ) {
data = dataUser.get( elem );
if ( elem.nodeType === 1 && !dataPriv.get( elem, "hasDataAttrs" ) ) {
i = attrs.length;
while ( i-- ) {
// Support: IE 11 only
// The attrs elements can be null (#14894)
if ( attrs[ i ] ) {
name = attrs[ i ].name;
if ( name.indexOf( "data-" ) === 0 ) {
name = camelCase( name.slice( 5 ) );
dataAttr( elem, name, data[ name ] );
}
}
}
dataPriv.set( elem, "hasDataAttrs", true );
}
}
return data;
}
// Sets multiple values
if ( typeof key === "object" ) {
return this.each( function() {
dataUser.set( this, key );
} );
}
return access( this, function( value ) {
var data;
// The calling jQuery object (element matches) is not empty
// (and therefore has an element appears at this[ 0 ]) and the
// `value` parameter was not undefined. An empty jQuery object
// will result in `undefined` for elem = this[ 0 ] which will
// throw an exception if an attempt to read a data cache is made.
if ( elem && value === undefined ) {
// Attempt to get data from the cache
// The key will always be camelCased in Data
data = dataUser.get( elem, key );
if ( data !== undefined ) {
return data;
}
// Attempt to "discover" the data in
// HTML5 custom data-* attrs
data = dataAttr( elem, key );
if ( data !== undefined ) {
return data;
}
// We tried really hard, but the data doesn't exist.
return;
}
// Set the data...
this.each( function() {
// We always store the camelCased key
dataUser.set( this, key, value );
} );
}, null, value, arguments.length > 1, null, true );
},
removeData: function( key ) {
return this.each( function() {
dataUser.remove( this, key );
} );
}
} );
jQuery.extend( {
queue: function( elem, type, data ) {
var queue;
if ( elem ) {
type = ( type || "fx" ) + "queue";
queue = dataPriv.get( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !queue || Array.isArray( data ) ) {
queue = dataPriv.access( elem, type, jQuery.makeArray( data ) );
} else {
queue.push( data );
}
}
return queue || [];
}
},
dequeue: function( elem, type ) {
type = type || "fx";
var queue = jQuery.queue( elem, type ),
startLength = queue.length,
fn = queue.shift(),
hooks = jQuery._queueHooks( elem, type ),
next = function() {
jQuery.dequeue( elem, type );
};
// If the fx queue is dequeued, always remove the progress sentinel
if ( fn === "inprogress" ) {
fn = queue.shift();
startLength--;
}
if ( fn ) {
// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if ( type === "fx" ) {
queue.unshift( "inprogress" );
}
// Clear up the last queue stop function
delete hooks.stop;
fn.call( elem, next, hooks );
}
if ( !startLength && hooks ) {
hooks.empty.fire();
}
},
// Not public - generate a queueHooks object, or return the current one
_queueHooks: function( elem, type ) {
var key = type + "queueHooks";
return dataPriv.get( elem, key ) || dataPriv.access( elem, key, {
empty: jQuery.Callbacks( "once memory" ).add( function() {
dataPriv.remove( elem, [ type + "queue", key ] );
} )
} );
}
} );
jQuery.fn.extend( {
queue: function( type, data ) {
var setter = 2;
if ( typeof type !== "string" ) {
data = type;
type = "fx";
setter--;
}
if ( arguments.length < setter ) {
return jQuery.queue( this[ 0 ], type );
}
return data === undefined ?
this :
this.each( function() {
var queue = jQuery.queue( this, type, data );
// Ensure a hooks for this queue
jQuery._queueHooks( this, type );
if ( type === "fx" && queue[ 0 ] !== "inprogress" ) {
jQuery.dequeue( this, type );
}
} );
},
dequeue: function( type ) {
return this.each( function() {
jQuery.dequeue( this, type );
} );
},
clearQueue: function( type ) {
return this.queue( type || "fx", [] );
},
// Get a promise resolved when queues of a certain type
// are emptied (fx is the type by default)
promise: function( type, obj ) {
var tmp,
count = 1,
defer = jQuery.Deferred(),
elements = this,
i = this.length,
resolve = function() {
if ( !( --count ) ) {
defer.resolveWith( elements, [ elements ] );
}
};
if ( typeof type !== "string" ) {
obj = type;
type = undefined;
}
type = type || "fx";
while ( i-- ) {
tmp = dataPriv.get( elements[ i ], type + "queueHooks" );
if ( tmp && tmp.empty ) {
count++;
tmp.empty.add( resolve );
}
}
resolve();
return defer.promise( obj );
}
} );
var pnum = ( /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/ ).source;
var rcssNum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" );
var cssExpand = [ "Top", "Right", "Bottom", "Left" ];
var isHiddenWithinTree = function( elem, el ) {
// isHiddenWithinTree might be called from jQuery#filter function;
// in that case, element will be second argument
elem = el || elem;
// Inline style trumps all
return elem.style.display === "none" ||
elem.style.display === "" &&
// Otherwise, check computed style
// Support: Firefox <=43 - 45
// Disconnected elements can have computed display: none, so first confirm that elem is
// in the document.
jQuery.contains( elem.ownerDocument, elem ) &&
jQuery.css( elem, "display" ) === "none";
};
var swap = function( elem, options, callback, args ) {
var ret, name,
old = {};
// Remember the old values, and insert the new ones
for ( name in options ) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
}
ret = callback.apply( elem, args || [] );
// Revert the old values
for ( name in options ) {
elem.style[ name ] = old[ name ];
}
return ret;
};
function adjustCSS( elem, prop, valueParts, tween ) {
var adjusted, scale,
maxIterations = 20,
currentValue = tween ?
function() {
return tween.cur();
} :
function() {
return jQuery.css( elem, prop, "" );
},
initial = currentValue(),
unit = valueParts && valueParts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ),
// Starting value computation is required for potential unit mismatches
initialInUnit = ( jQuery.cssNumber[ prop ] || unit !== "px" && +initial ) &&
rcssNum.exec( jQuery.css( elem, prop ) );
if ( initialInUnit && initialInUnit[ 3 ] !== unit ) {
// Support: Firefox <=54
// Halve the iteration target value to prevent interference from CSS upper bounds (gh-2144)
initial = initial / 2;
// Trust units reported by jQuery.css
unit = unit || initialInUnit[ 3 ];
// Iteratively approximate from a nonzero starting point
initialInUnit = +initial || 1;
while ( maxIterations-- ) {
// Evaluate and update our best guess (doubling guesses that zero out).
// Finish if the scale equals or crosses 1 (making the old*new product non-positive).
jQuery.style( elem, prop, initialInUnit + unit );
if ( ( 1 - scale ) * ( 1 - ( scale = currentValue() / initial || 0.5 ) ) <= 0 ) {
maxIterations = 0;
}
initialInUnit = initialInUnit / scale;
}
initialInUnit = initialInUnit * 2;
jQuery.style( elem, prop, initialInUnit + unit );
// Make sure we update the tween properties later on
valueParts = valueParts || [];
}
if ( valueParts ) {
initialInUnit = +initialInUnit || +initial || 0;
// Apply relative offset (+=/-=) if specified
adjusted = valueParts[ 1 ] ?
initialInUnit + ( valueParts[ 1 ] + 1 ) * valueParts[ 2 ] :
+valueParts[ 2 ];
if ( tween ) {
tween.unit = unit;
tween.start = initialInUnit;
tween.end = adjusted;
}
}
return adjusted;
}
var defaultDisplayMap = {};
function getDefaultDisplay( elem ) {
var temp,
doc = elem.ownerDocument,
nodeName = elem.nodeName,
display = defaultDisplayMap[ nodeName ];
if ( display ) {
return display;
}
temp = doc.body.appendChild( doc.createElement( nodeName ) );
display = jQuery.css( temp, "display" );
temp.parentNode.removeChild( temp );
if ( display === "none" ) {
display = "block";
}
defaultDisplayMap[ nodeName ] = display;
return display;
}
function showHide( elements, show ) {
var display, elem,
values = [],
index = 0,
length = elements.length;
// Determine new display value for elements that need to change
for ( ; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
display = elem.style.display;
if ( show ) {
// Since we force visibility upon cascade-hidden elements, an immediate (and slow)
// check is required in this first loop unless we have a nonempty display value (either
// inline or about-to-be-restored)
if ( display === "none" ) {
values[ index ] = dataPriv.get( elem, "display" ) || null;
if ( !values[ index ] ) {
elem.style.display = "";
}
}
if ( elem.style.display === "" && isHiddenWithinTree( elem ) ) {
values[ index ] = getDefaultDisplay( elem );
}
} else {
if ( display !== "none" ) {
values[ index ] = "none";
// Remember what we're overwriting
dataPriv.set( elem, "display", display );
}
}
}
// Set the display of the elements in a second loop to avoid constant reflow
for ( index = 0; index < length; index++ ) {
if ( values[ index ] != null ) {
elements[ index ].style.display = values[ index ];
}
}
return elements;
}
jQuery.fn.extend( {
show: function() {
return showHide( this, true );
},
hide: function() {
return showHide( this );
},
toggle: function( state ) {
if ( typeof state === "boolean" ) {
return state ? this.show() : this.hide();
}
return this.each( function() {
if ( isHiddenWithinTree( this ) ) {
jQuery( this ).show();
} else {
jQuery( this ).hide();
}
} );
}
} );
var rcheckableType = ( /^(?:checkbox|radio)$/i );
var rtagName = ( /<([a-z][^\/\0>\x20\t\r\n\f]+)/i );
var rscriptType = ( /^$|^module$|\/(?:java|ecma)script/i );
// We have to close these tags to support XHTML (#13200)
var wrapMap = {
// Support: IE <=9 only
option: [ 1, "<select multiple='multiple'>", "</select>" ],
// XHTML parsers do not magically insert elements in the
// same way that tag soup parsers do. So we cannot shorten
// this by omitting <tbody> or other required elements.
thead: [ 1, "<table>", "</table>" ],
col: [ 2, "<table><colgroup>", "</colgroup></table>" ],
tr: [ 2, "<table><tbody>", "</tbody></table>" ],
td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
_default: [ 0, "", "" ]
};
// Support: IE <=9 only
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
function getAll( context, tag ) {
// Support: IE <=9 - 11 only
// Use typeof to avoid zero-argument method invocation on host objects (#15151)
var ret;
if ( typeof context.getElementsByTagName !== "undefined" ) {
ret = context.getElementsByTagName( tag || "*" );
} else if ( typeof context.querySelectorAll !== "undefined" ) {
ret = context.querySelectorAll( tag || "*" );
} else {
ret = [];
}
if ( tag === undefined || tag && nodeName( context, tag ) ) {
return jQuery.merge( [ context ], ret );
}
return ret;
}
// Mark scripts as having already been evaluated
function setGlobalEval( elems, refElements ) {
var i = 0,
l = elems.length;
for ( ; i < l; i++ ) {
dataPriv.set(
elems[ i ],
"globalEval",
!refElements || dataPriv.get( refElements[ i ], "globalEval" )
);
}
}
var rhtml = /<|&#?\w+;/;
function buildFragment( elems, context, scripts, selection, ignored ) {
var elem, tmp, tag, wrap, contains, j,
fragment = context.createDocumentFragment(),
nodes = [],
i = 0,
l = elems.length;
for ( ; i < l; i++ ) {
elem = elems[ i ];
if ( elem || elem === 0 ) {
// Add nodes directly
if ( toType( elem ) === "object" ) {
// Support: Android <=4.0 only, PhantomJS 1 only
// push.apply(_, arraylike) throws on ancient WebKit
jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem );
// Convert non-html into a text node
} else if ( !rhtml.test( elem ) ) {
nodes.push( context.createTextNode( elem ) );
// Convert html into DOM nodes
} else {
tmp = tmp || fragment.appendChild( context.createElement( "div" ) );
// Deserialize a standard representation
tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase();
wrap = wrapMap[ tag ] || wrapMap._default;
tmp.innerHTML = wrap[ 1 ] + jQuery.htmlPrefilter( elem ) + wrap[ 2 ];
// Descend through wrappers to the right content
j = wrap[ 0 ];
while ( j-- ) {
tmp = tmp.lastChild;
}
// Support: Android <=4.0 only, PhantomJS 1 only
// push.apply(_, arraylike) throws on ancient WebKit
jQuery.merge( nodes, tmp.childNodes );
// Remember the top-level container
tmp = fragment.firstChild;
// Ensure the created nodes are orphaned (#12392)
tmp.textContent = "";
}
}
}
// Remove wrapper from fragment
fragment.textContent = "";
i = 0;
while ( ( elem = nodes[ i++ ] ) ) {
// Skip elements already in the context collection (trac-4087)
if ( selection && jQuery.inArray( elem, selection ) > -1 ) {
if ( ignored ) {
ignored.push( elem );
}
continue;
}
contains = jQuery.contains( elem.ownerDocument, elem );
// Append to fragment
tmp = getAll( fragment.appendChild( elem ), "script" );
// Preserve script evaluation history
if ( contains ) {
setGlobalEval( tmp );
}
// Capture executables
if ( scripts ) {
j = 0;
while ( ( elem = tmp[ j++ ] ) ) {
if ( rscriptType.test( elem.type || "" ) ) {
scripts.push( elem );
}
}
}
}
return fragment;
}
( function() {
var fragment = document.createDocumentFragment(),
div = fragment.appendChild( document.createElement( "div" ) ),
input = document.createElement( "input" );
// Support: Android 4.0 - 4.3 only
// Check state lost if the name is set (#11217)
// Support: Windows Web Apps (WWA)
// `name` and `type` must use .setAttribute for WWA (#14901)
input.setAttribute( "type", "radio" );
input.setAttribute( "checked", "checked" );
input.setAttribute( "name", "t" );
div.appendChild( input );
// Support: Android <=4.1 only
// Older WebKit doesn't clone checked state correctly in fragments
support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked;
// Support: IE <=11 only
// Make sure textarea (and checkbox) defaultValue is properly cloned
div.innerHTML = "<textarea>x</textarea>";
support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue;
} )();
var documentElement = document.documentElement;
var
rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|pointer|contextmenu|drag|drop)|click/,
rtypenamespace = /^([^.]*)(?:\.(.+)|)/;
function returnTrue() {
return true;
}
function returnFalse() {
return false;
}
// Support: IE <=9 only
// See #13393 for more info
function safeActiveElement() {
try {
return document.activeElement;
} catch ( err ) { }
}
function on( elem, types, selector, data, fn, one ) {
var origFn, type;
// Types can be a map of types/handlers
if ( typeof types === "object" ) {
// ( types-Object, selector, data )
if ( typeof selector !== "string" ) {
// ( types-Object, data )
data = data || selector;
selector = undefined;
}
for ( type in types ) {
on( elem, type, selector, data, types[ type ], one );
}
return elem;
}
if ( data == null && fn == null ) {
// ( types, fn )
fn = selector;
data = selector = undefined;
} else if ( fn == null ) {
if ( typeof selector === "string" ) {
// ( types, selector, fn )
fn = data;
data = undefined;
} else {
// ( types, data, fn )
fn = data;
data = selector;
selector = undefined;
}
}
if ( fn === false ) {
fn = returnFalse;
} else if ( !fn ) {
return elem;
}
if ( one === 1 ) {
origFn = fn;
fn = function( event ) {
// Can use an empty set, since event contains the info
jQuery().off( event );
return origFn.apply( this, arguments );
};
// Use same guid so caller can remove using origFn
fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
}
return elem.each( function() {
jQuery.event.add( this, types, fn, data, selector );
} );
}
/*
* Helper functions for managing events -- not part of the public interface.
* Props to Dean Edwards' addEvent library for many of the ideas.
*/
jQuery.event = {
global: {},
add: function( elem, types, handler, data, selector ) {
var handleObjIn, eventHandle, tmp,
events, t, handleObj,
special, handlers, type, namespaces, origType,
elemData = dataPriv.get( elem );
// Don't attach events to noData or text/comment nodes (but allow plain objects)
if ( !elemData ) {
return;
}
// Caller can pass in an object of custom data in lieu of the handler
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
selector = handleObjIn.selector;
}
// Ensure that invalid selectors throw exceptions at attach time
// Evaluate against documentElement in case elem is a non-element node (e.g., document)
if ( selector ) {
jQuery.find.matchesSelector( documentElement, selector );
}
// Make sure that the handler has a unique ID, used to find/remove it later
if ( !handler.guid ) {
handler.guid = jQuery.guid++;
}
// Init the element's event structure and main handler, if this is the first
if ( !( events = elemData.events ) ) {
events = elemData.events = {};
}
if ( !( eventHandle = elemData.handle ) ) {
eventHandle = elemData.handle = function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== "undefined" && jQuery.event.triggered !== e.type ?
jQuery.event.dispatch.apply( elem, arguments ) : undefined;
};
}
// Handle multiple events separated by a space
types = ( types || "" ).match( rnothtmlwhite ) || [ "" ];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[ t ] ) || [];
type = origType = tmp[ 1 ];
namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort();
// There *must* be a type, no attaching namespace-only handlers
if ( !type ) {
continue;
}
// If event changes its type, use the special event handlers for the changed type
special = jQuery.event.special[ type ] || {};
// If selector defined, determine special event api type, otherwise given type
type = ( selector ? special.delegateType : special.bindType ) || type;
// Update special based on newly reset type
special = jQuery.event.special[ type ] || {};
// handleObj is passed to all event handlers
handleObj = jQuery.extend( {
type: type,
origType: origType,
data: data,
handler: handler,
guid: handler.guid,
selector: selector,
needsContext: selector && jQuery.expr.match.needsContext.test( selector ),
namespace: namespaces.join( "." )
}, handleObjIn );
// Init the event handler queue if we're the first
if ( !( handlers = events[ type ] ) ) {
handlers = events[ type ] = [];
handlers.delegateCount = 0;
// Only use addEventListener if the special events handler returns false
if ( !special.setup ||
special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle );
}
}
}
if ( special.add ) {
special.add.call( elem, handleObj );
if ( !handleObj.handler.guid ) {
handleObj.handler.guid = handler.guid;
}
}
// Add to the element's handler list, delegates in front
if ( selector ) {
handlers.splice( handlers.delegateCount++, 0, handleObj );
} else {
handlers.push( handleObj );
}
// Keep track of which events have ever been used, for event optimization
jQuery.event.global[ type ] = true;
}
},
// Detach an event or set of events from an element
remove: function( elem, types, handler, selector, mappedTypes ) {
var j, origCount, tmp,
events, t, handleObj,
special, handlers, type, namespaces, origType,
elemData = dataPriv.hasData( elem ) && dataPriv.get( elem );
if ( !elemData || !( events = elemData.events ) ) {
return;
}
// Once for each type.namespace in types; type may be omitted
types = ( types || "" ).match( rnothtmlwhite ) || [ "" ];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[ t ] ) || [];
type = origType = tmp[ 1 ];
namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort();
// Unbind all events (on this namespace, if provided) for the element
if ( !type ) {
for ( type in events ) {
jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
}
continue;
}
special = jQuery.event.special[ type ] || {};
type = ( selector ? special.delegateType : special.bindType ) || type;
handlers = events[ type ] || [];
tmp = tmp[ 2 ] &&
new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" );
// Remove matching events
origCount = j = handlers.length;
while ( j-- ) {
handleObj = handlers[ j ];
if ( ( mappedTypes || origType === handleObj.origType ) &&
( !handler || handler.guid === handleObj.guid ) &&
( !tmp || tmp.test( handleObj.namespace ) ) &&
( !selector || selector === handleObj.selector ||
selector === "**" && handleObj.selector ) ) {
handlers.splice( j, 1 );
if ( handleObj.selector ) {
handlers.delegateCount--;
}
if ( special.remove ) {
special.remove.call( elem, handleObj );
}
}
}
// Remove generic event handler if we removed something and no more handlers exist
// (avoids potential for endless recursion during removal of special event handlers)
if ( origCount && !handlers.length ) {
if ( !special.teardown ||
special.teardown.call( elem, namespaces, elemData.handle ) === false ) {
jQuery.removeEvent( elem, type, elemData.handle );
}
delete events[ type ];
}
}
// Remove data and the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
dataPriv.remove( elem, "handle events" );
}
},
dispatch: function( nativeEvent ) {
// Make a writable jQuery.Event from the native event object
var event = jQuery.event.fix( nativeEvent );
var i, j, ret, matched, handleObj, handlerQueue,
args = new Array( arguments.length ),
handlers = ( dataPriv.get( this, "events" ) || {} )[ event.type ] || [],
special = jQuery.event.special[ event.type ] || {};
// Use the fix-ed jQuery.Event rather than the (read-only) native event
args[ 0 ] = event;
for ( i = 1; i < arguments.length; i++ ) {
args[ i ] = arguments[ i ];
}
event.delegateTarget = this;
// Call the preDispatch hook for the mapped type, and let it bail if desired
if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
return;
}
// Determine handlers
handlerQueue = jQuery.event.handlers.call( this, event, handlers );
// Run delegates first; they may want to stop propagation beneath us
i = 0;
while ( ( matched = handlerQueue[ i++ ] ) && !event.isPropagationStopped() ) {
event.currentTarget = matched.elem;
j = 0;
while ( ( handleObj = matched.handlers[ j++ ] ) &&
!event.isImmediatePropagationStopped() ) {
// Triggered event must either 1) have no namespace, or 2) have namespace(s)
// a subset or equal to those in the bound event (both can have no namespace).
if ( !event.rnamespace || event.rnamespace.test( handleObj.namespace ) ) {
event.handleObj = handleObj;
event.data = handleObj.data;
ret = ( ( jQuery.event.special[ handleObj.origType ] || {} ).handle ||
handleObj.handler ).apply( matched.elem, args );
if ( ret !== undefined ) {
if ( ( event.result = ret ) === false ) {
event.preventDefault();
event.stopPropagation();
}
}
}
}
}
// Call the postDispatch hook for the mapped type
if ( special.postDispatch ) {
special.postDispatch.call( this, event );
}
return event.result;
},
handlers: function( event, handlers ) {
var i, handleObj, sel, matchedHandlers, matchedSelectors,
handlerQueue = [],
delegateCount = handlers.delegateCount,
cur = event.target;
// Find delegate handlers
if ( delegateCount &&
// Support: IE <=9
// Black-hole SVG <use> instance trees (trac-13180)
cur.nodeType &&
// Support: Firefox <=42
// Suppress spec-violating clicks indicating a non-primary pointer button (trac-3861)
// https://www.w3.org/TR/DOM-Level-3-Events/#event-type-click
// Support: IE 11 only
// ...but not arrow key "clicks" of radio inputs, which can have `button` -1 (gh-2343)
!( event.type === "click" && event.button >= 1 ) ) {
for ( ; cur !== this; cur = cur.parentNode || this ) {
// Don't check non-elements (#13208)
// Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
if ( cur.nodeType === 1 && !( event.type === "click" && cur.disabled === true ) ) {
matchedHandlers = [];
matchedSelectors = {};
for ( i = 0; i < delegateCount; i++ ) {
handleObj = handlers[ i ];
// Don't conflict with Object.prototype properties (#13203)
sel = handleObj.selector + " ";
if ( matchedSelectors[ sel ] === undefined ) {
matchedSelectors[ sel ] = handleObj.needsContext ?
jQuery( sel, this ).index( cur ) > -1 :
jQuery.find( sel, this, null, [ cur ] ).length;
}
if ( matchedSelectors[ sel ] ) {
matchedHandlers.push( handleObj );
}
}
if ( matchedHandlers.length ) {
handlerQueue.push( { elem: cur, handlers: matchedHandlers } );
}
}
}
}
// Add the remaining (directly-bound) handlers
cur = this;
if ( delegateCount < handlers.length ) {
handlerQueue.push( { elem: cur, handlers: handlers.slice( delegateCount ) } );
}
return handlerQueue;
},
addProp: function( name, hook ) {
Object.defineProperty( jQuery.Event.prototype, name, {
enumerable: true,
configurable: true,
get: isFunction( hook ) ?
function() {
if ( this.originalEvent ) {
return hook( this.originalEvent );
}
} :
function() {
if ( this.originalEvent ) {
return this.originalEvent[ name ];
}
},
set: function( value ) {
Object.defineProperty( this, name, {
enumerable: true,
configurable: true,
writable: true,
value: value
} );
}
} );
},
fix: function( originalEvent ) {
return originalEvent[ jQuery.expando ] ?
originalEvent :
new jQuery.Event( originalEvent );
},
special: {
load: {
// Prevent triggered image.load events from bubbling to window.load
noBubble: true
},
focus: {
// Fire native event if possible so blur/focus sequence is correct
trigger: function() {
if ( this !== safeActiveElement() && this.focus ) {
this.focus();
return false;
}
},
delegateType: "focusin"
},
blur: {
trigger: function() {
if ( this === safeActiveElement() && this.blur ) {
this.blur();
return false;
}
},
delegateType: "focusout"
},
click: {
// For checkbox, fire native event so checked state will be right
trigger: function() {
if ( this.type === "checkbox" && this.click && nodeName( this, "input" ) ) {
this.click();
return false;
}
},
// For cross-browser consistency, don't fire native .click() on links
_default: function( event ) {
return nodeName( event.target, "a" );
}
},
beforeunload: {
postDispatch: function( event ) {
// Support: Firefox 20+
// Firefox doesn't alert if the returnValue field is not set.
if ( event.result !== undefined && event.originalEvent ) {
event.originalEvent.returnValue = event.result;
}
}
}
}
};
jQuery.removeEvent = function( elem, type, handle ) {
// This "if" is needed for plain objects
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle );
}
};
jQuery.Event = function( src, props ) {
// Allow instantiation without the 'new' keyword
if ( !( this instanceof jQuery.Event ) ) {
return new jQuery.Event( src, props );
}
// Event object
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
// Events bubbling up the document may have been marked as prevented
// by a handler lower down the tree; reflect the correct value.
this.isDefaultPrevented = src.defaultPrevented ||
src.defaultPrevented === undefined &&
// Support: Android <=2.3 only
src.returnValue === false ?
returnTrue :
returnFalse;
// Create target properties
// Support: Safari <=6 - 7 only
// Target should not be a text node (#504, #13143)
this.target = ( src.target && src.target.nodeType === 3 ) ?
src.target.parentNode :
src.target;
this.currentTarget = src.currentTarget;
this.relatedTarget = src.relatedTarget;
// Event type
} else {
this.type = src;
}
// Put explicitly provided properties onto the event object
if ( props ) {
jQuery.extend( this, props );
}
// Create a timestamp if incoming event doesn't have one
this.timeStamp = src && src.timeStamp || Date.now();
// Mark it as fixed
this[ jQuery.expando ] = true;
};
// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// https://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
constructor: jQuery.Event,
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse,
isSimulated: false,
preventDefault: function() {
var e = this.originalEvent;
this.isDefaultPrevented = returnTrue;
if ( e && !this.isSimulated ) {
e.preventDefault();
}
},
stopPropagation: function() {
var e = this.originalEvent;
this.isPropagationStopped = returnTrue;
if ( e && !this.isSimulated ) {
e.stopPropagation();
}
},
stopImmediatePropagation: function() {
var e = this.originalEvent;
this.isImmediatePropagationStopped = returnTrue;
if ( e && !this.isSimulated ) {
e.stopImmediatePropagation();
}
this.stopPropagation();
}
};
// Includes all common event props including KeyEvent and MouseEvent specific props
jQuery.each( {
altKey: true,
bubbles: true,
cancelable: true,
changedTouches: true,
ctrlKey: true,
detail: true,
eventPhase: true,
metaKey: true,
pageX: true,
pageY: true,
shiftKey: true,
view: true,
"char": true,
charCode: true,
key: true,
keyCode: true,
button: true,
buttons: true,
clientX: true,
clientY: true,
offsetX: true,
offsetY: true,
pointerId: true,
pointerType: true,
screenX: true,
screenY: true,
targetTouches: true,
toElement: true,
touches: true,
which: function( event ) {
var button = event.button;
// Add which for key events
if ( event.which == null && rkeyEvent.test( event.type ) ) {
return event.charCode != null ? event.charCode : event.keyCode;
}
// Add which for click: 1 === left; 2 === middle; 3 === right
if ( !event.which && button !== undefined && rmouseEvent.test( event.type ) ) {
if ( button & 1 ) {
return 1;
}
if ( button & 2 ) {
return 3;
}
if ( button & 4 ) {
return 2;
}
return 0;
}
return event.which;
}
}, jQuery.event.addProp );
// Create mouseenter/leave events using mouseover/out and event-time checks
// so that event delegation works in jQuery.
// Do the same for pointerenter/pointerleave and pointerover/pointerout
//
// Support: Safari 7 only
// Safari sends mouseenter too often; see:
// https://bugs.chromium.org/p/chromium/issues/detail?id=470258
// for the description of the bug (it existed in older Chrome versions as well).
jQuery.each( {
mouseenter: "mouseover",
mouseleave: "mouseout",
pointerenter: "pointerover",
pointerleave: "pointerout"
}, function( orig, fix ) {
jQuery.event.special[ orig ] = {
delegateType: fix,
bindType: fix,
handle: function( event ) {
var ret,
target = this,
related = event.relatedTarget,
handleObj = event.handleObj;
// For mouseenter/leave call the handler if related is outside the target.
// NB: No relatedTarget if the mouse left/entered the browser window
if ( !related || ( related !== target && !jQuery.contains( target, related ) ) ) {
event.type = handleObj.origType;
ret = handleObj.handler.apply( this, arguments );
event.type = fix;
}
return ret;
}
};
} );
jQuery.fn.extend( {
on: function( types, selector, data, fn ) {
return on( this, types, selector, data, fn );
},
one: function( types, selector, data, fn ) {
return on( this, types, selector, data, fn, 1 );
},
off: function( types, selector, fn ) {
var handleObj, type;
if ( types && types.preventDefault && types.handleObj ) {
// ( event ) dispatched jQuery.Event
handleObj = types.handleObj;
jQuery( types.delegateTarget ).off(
handleObj.namespace ?
handleObj.origType + "." + handleObj.namespace :
handleObj.origType,
handleObj.selector,
handleObj.handler
);
return this;
}
if ( typeof types === "object" ) {
// ( types-object [, selector] )
for ( type in types ) {
this.off( type, selector, types[ type ] );
}
return this;
}
if ( selector === false || typeof selector === "function" ) {
// ( types [, fn] )
fn = selector;
selector = undefined;
}
if ( fn === false ) {
fn = returnFalse;
}
return this.each( function() {
jQuery.event.remove( this, types, fn, selector );
} );
}
} );
var
/* eslint-disable max-len */
// See https://github.com/eslint/eslint/issues/3229
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([a-z][^\/\0>\x20\t\r\n\f]*)[^>]*)\/>/gi,
/* eslint-enable */
// Support: IE <=10 - 11, Edge 12 - 13 only
// In IE/Edge using regex groups here causes severe slowdowns.
// See https://connect.microsoft.com/IE/feedback/details/1736512/
rnoInnerhtml = /<script|<style|<link/i,
// checked="checked" or checked
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g;
// Prefer a tbody over its parent table for containing new rows
function manipulationTarget( elem, content ) {
if ( nodeName( elem, "table" ) &&
nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ) {
return jQuery( elem ).children( "tbody" )[ 0 ] || elem;
}
return elem;
}
// Replace/restore the type attribute of script elements for safe DOM manipulation
function disableScript( elem ) {
elem.type = ( elem.getAttribute( "type" ) !== null ) + "/" + elem.type;
return elem;
}
function restoreScript( elem ) {
if ( ( elem.type || "" ).slice( 0, 5 ) === "true/" ) {
elem.type = elem.type.slice( 5 );
} else {
elem.removeAttribute( "type" );
}
return elem;
}
function cloneCopyEvent( src, dest ) {
var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events;
if ( dest.nodeType !== 1 ) {
return;
}
// 1. Copy private data: events, handlers, etc.
if ( dataPriv.hasData( src ) ) {
pdataOld = dataPriv.access( src );
pdataCur = dataPriv.set( dest, pdataOld );
events = pdataOld.events;
if ( events ) {
delete pdataCur.handle;
pdataCur.events = {};
for ( type in events ) {
for ( i = 0, l = events[ type ].length; i < l; i++ ) {
jQuery.event.add( dest, type, events[ type ][ i ] );
}
}
}
}
// 2. Copy user data
if ( dataUser.hasData( src ) ) {
udataOld = dataUser.access( src );
udataCur = jQuery.extend( {}, udataOld );
dataUser.set( dest, udataCur );
}
}
// Fix IE bugs, see support tests
function fixInput( src, dest ) {
var nodeName = dest.nodeName.toLowerCase();
// Fails to persist the checked state of a cloned checkbox or radio button.
if ( nodeName === "input" && rcheckableType.test( src.type ) ) {
dest.checked = src.checked;
// Fails to return the selected option to the default selected state when cloning options
} else if ( nodeName === "input" || nodeName === "textarea" ) {
dest.defaultValue = src.defaultValue;
}
}
function domManip( collection, args, callback, ignored ) {
// Flatten any nested arrays
args = concat.apply( [], args );
var fragment, first, scripts, hasScripts, node, doc,
i = 0,
l = collection.length,
iNoClone = l - 1,
value = args[ 0 ],
valueIsFunction = isFunction( value );
// We can't cloneNode fragments that contain checked, in WebKit
if ( valueIsFunction ||
( l > 1 && typeof value === "string" &&
!support.checkClone && rchecked.test( value ) ) ) {
return collection.each( function( index ) {
var self = collection.eq( index );
if ( valueIsFunction ) {
args[ 0 ] = value.call( this, index, self.html() );
}
domManip( self, args, callback, ignored );
} );
}
if ( l ) {
fragment = buildFragment( args, collection[ 0 ].ownerDocument, false, collection, ignored );
first = fragment.firstChild;
if ( fragment.childNodes.length === 1 ) {
fragment = first;
}
// Require either new content or an interest in ignored elements to invoke the callback
if ( first || ignored ) {
scripts = jQuery.map( getAll( fragment, "script" ), disableScript );
hasScripts = scripts.length;
// Use the original fragment for the last item
// instead of the first because it can end up
// being emptied incorrectly in certain situations (#8070).
for ( ; i < l; i++ ) {
node = fragment;
if ( i !== iNoClone ) {
node = jQuery.clone( node, true, true );
// Keep references to cloned scripts for later restoration
if ( hasScripts ) {
// Support: Android <=4.0 only, PhantomJS 1 only
// push.apply(_, arraylike) throws on ancient WebKit
jQuery.merge( scripts, getAll( node, "script" ) );
}
}
callback.call( collection[ i ], node, i );
}
if ( hasScripts ) {
doc = scripts[ scripts.length - 1 ].ownerDocument;
// Reenable scripts
jQuery.map( scripts, restoreScript );
// Evaluate executable scripts on first document insertion
for ( i = 0; i < hasScripts; i++ ) {
node = scripts[ i ];
if ( rscriptType.test( node.type || "" ) &&
!dataPriv.access( node, "globalEval" ) &&
jQuery.contains( doc, node ) ) {
if ( node.src && ( node.type || "" ).toLowerCase() !== "module" ) {
// Optional AJAX dependency, but won't run scripts if not present
if ( jQuery._evalUrl ) {
jQuery._evalUrl( node.src );
}
} else {
DOMEval( node.textContent.replace( rcleanScript, "" ), doc, node );
}
}
}
}
}
}
return collection;
}
function remove( elem, selector, keepData ) {
var node,
nodes = selector ? jQuery.filter( selector, elem ) : elem,
i = 0;
for ( ; ( node = nodes[ i ] ) != null; i++ ) {
if ( !keepData && node.nodeType === 1 ) {
jQuery.cleanData( getAll( node ) );
}
if ( node.parentNode ) {
if ( keepData && jQuery.contains( node.ownerDocument, node ) ) {
setGlobalEval( getAll( node, "script" ) );
}
node.parentNode.removeChild( node );
}
}
return elem;
}
jQuery.extend( {
htmlPrefilter: function( html ) {
return html.replace( rxhtmlTag, "<$1></$2>" );
},
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var i, l, srcElements, destElements,
clone = elem.cloneNode( true ),
inPage = jQuery.contains( elem.ownerDocument, elem );
// Fix IE cloning issues
if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) &&
!jQuery.isXMLDoc( elem ) ) {
// We eschew Sizzle here for performance reasons: https://jsperf.com/getall-vs-sizzle/2
destElements = getAll( clone );
srcElements = getAll( elem );
for ( i = 0, l = srcElements.length; i < l; i++ ) {
fixInput( srcElements[ i ], destElements[ i ] );
}
}
// Copy the events from the original to the clone
if ( dataAndEvents ) {
if ( deepDataAndEvents ) {
srcElements = srcElements || getAll( elem );
destElements = destElements || getAll( clone );
for ( i = 0, l = srcElements.length; i < l; i++ ) {
cloneCopyEvent( srcElements[ i ], destElements[ i ] );
}
} else {
cloneCopyEvent( elem, clone );
}
}
// Preserve script evaluation history
destElements = getAll( clone, "script" );
if ( destElements.length > 0 ) {
setGlobalEval( destElements, !inPage && getAll( elem, "script" ) );
}
// Return the cloned set
return clone;
},
cleanData: function( elems ) {
var data, elem, type,
special = jQuery.event.special,
i = 0;
for ( ; ( elem = elems[ i ] ) !== undefined; i++ ) {
if ( acceptData( elem ) ) {
if ( ( data = elem[ dataPriv.expando ] ) ) {
if ( data.events ) {
for ( type in data.events ) {
if ( special[ type ] ) {
jQuery.event.remove( elem, type );
// This is a shortcut to avoid jQuery.event.remove's overhead
} else {
jQuery.removeEvent( elem, type, data.handle );
}
}
}
// Support: Chrome <=35 - 45+
// Assign undefined instead of using delete, see Data#remove
elem[ dataPriv.expando ] = undefined;
}
if ( elem[ dataUser.expando ] ) {
// Support: Chrome <=35 - 45+
// Assign undefined instead of using delete, see Data#remove
elem[ dataUser.expando ] = undefined;
}
}
}
}
} );
jQuery.fn.extend( {
detach: function( selector ) {
return remove( this, selector, true );
},
remove: function( selector ) {
return remove( this, selector );
},
text: function( value ) {
return access( this, function( value ) {
return value === undefined ?
jQuery.text( this ) :
this.empty().each( function() {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
this.textContent = value;
}
} );
}, null, value, arguments.length );
},
append: function() {
return domManip( this, arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.appendChild( elem );
}
} );
},
prepend: function() {
return domManip( this, arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.insertBefore( elem, target.firstChild );
}
} );
},
before: function() {
return domManip( this, arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this );
}
} );
},
after: function() {
return domManip( this, arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this.nextSibling );
}
} );
},
empty: function() {
var elem,
i = 0;
for ( ; ( elem = this[ i ] ) != null; i++ ) {
if ( elem.nodeType === 1 ) {
// Prevent memory leaks
jQuery.cleanData( getAll( elem, false ) );
// Remove any remaining nodes
elem.textContent = "";
}
}
return this;
},
clone: function( dataAndEvents, deepDataAndEvents ) {
dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
return this.map( function() {
return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
} );
},
html: function( value ) {
return access( this, function( value ) {
var elem = this[ 0 ] || {},
i = 0,
l = this.length;
if ( value === undefined && elem.nodeType === 1 ) {
return elem.innerHTML;
}
// See if we can take a shortcut and just use innerHTML
if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
!wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) {
value = jQuery.htmlPrefilter( value );
try {
for ( ; i < l; i++ ) {
elem = this[ i ] || {};
// Remove element nodes and prevent memory leaks
if ( elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem, false ) );
elem.innerHTML = value;
}
}
elem = 0;
// If using innerHTML throws an exception, use the fallback method
} catch ( e ) {}
}
if ( elem ) {
this.empty().append( value );
}
}, null, value, arguments.length );
},
replaceWith: function() {
var ignored = [];
// Make the changes, replacing each non-ignored context element with the new content
return domManip( this, arguments, function( elem ) {
var parent = this.parentNode;
if ( jQuery.inArray( this, ignored ) < 0 ) {
jQuery.cleanData( getAll( this ) );
if ( parent ) {
parent.replaceChild( elem, this );
}
}
// Force callback invocation
}, ignored );
}
} );
jQuery.each( {
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) {
jQuery.fn[ name ] = function( selector ) {
var elems,
ret = [],
insert = jQuery( selector ),
last = insert.length - 1,
i = 0;
for ( ; i <= last; i++ ) {
elems = i === last ? this : this.clone( true );
jQuery( insert[ i ] )[ original ]( elems );
// Support: Android <=4.0 only, PhantomJS 1 only
// .get() because push.apply(_, arraylike) throws on ancient WebKit
push.apply( ret, elems.get() );
}
return this.pushStack( ret );
};
} );
var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" );
var getStyles = function( elem ) {
// Support: IE <=11 only, Firefox <=30 (#15098, #14150)
// IE throws on elements created in popups
// FF meanwhile throws on frame elements through "defaultView.getComputedStyle"
var view = elem.ownerDocument.defaultView;
if ( !view || !view.opener ) {
view = window;
}
return view.getComputedStyle( elem );
};
var rboxStyle = new RegExp( cssExpand.join( "|" ), "i" );
( function() {
// Executing both pixelPosition & boxSizingReliable tests require only one layout
// so they're executed at the same time to save the second computation.
function computeStyleTests() {
// This is a singleton, we need to execute it only once
if ( !div ) {
return;
}
container.style.cssText = "position:absolute;left:-11111px;width:60px;" +
"margin-top:1px;padding:0;border:0";
div.style.cssText =
"position:relative;display:block;box-sizing:border-box;overflow:scroll;" +
"margin:auto;border:1px;padding:1px;" +
"width:60%;top:1%";
documentElement.appendChild( container ).appendChild( div );
var divStyle = window.getComputedStyle( div );
pixelPositionVal = divStyle.top !== "1%";
// Support: Android 4.0 - 4.3 only, Firefox <=3 - 44
reliableMarginLeftVal = roundPixelMeasures( divStyle.marginLeft ) === 12;
// Support: Android 4.0 - 4.3 only, Safari <=9.1 - 10.1, iOS <=7.0 - 9.3
// Some styles come back with percentage values, even though they shouldn't
div.style.right = "60%";
pixelBoxStylesVal = roundPixelMeasures( divStyle.right ) === 36;
// Support: IE 9 - 11 only
// Detect misreporting of content dimensions for box-sizing:border-box elements
boxSizingReliableVal = roundPixelMeasures( divStyle.width ) === 36;
// Support: IE 9 only
// Detect overflow:scroll screwiness (gh-3699)
div.style.position = "absolute";
scrollboxSizeVal = div.offsetWidth === 36 || "absolute";
documentElement.removeChild( container );
// Nullify the div so it wouldn't be stored in the memory and
// it will also be a sign that checks already performed
div = null;
}
function roundPixelMeasures( measure ) {
return Math.round( parseFloat( measure ) );
}
var pixelPositionVal, boxSizingReliableVal, scrollboxSizeVal, pixelBoxStylesVal,
reliableMarginLeftVal,
container = document.createElement( "div" ),
div = document.createElement( "div" );
// Finish early in limited (non-browser) environments
if ( !div.style ) {
return;
}
// Support: IE <=9 - 11 only
// Style of cloned element affects source element cloned (#8908)
div.style.backgroundClip = "content-box";
div.cloneNode( true ).style.backgroundClip = "";
support.clearCloneStyle = div.style.backgroundClip === "content-box";
jQuery.extend( support, {
boxSizingReliable: function() {
computeStyleTests();
return boxSizingReliableVal;
},
pixelBoxStyles: function() {
computeStyleTests();
return pixelBoxStylesVal;
},
pixelPosition: function() {
computeStyleTests();
return pixelPositionVal;
},
reliableMarginLeft: function() {
computeStyleTests();
return reliableMarginLeftVal;
},
scrollboxSize: function() {
computeStyleTests();
return scrollboxSizeVal;
}
} );
} )();
function curCSS( elem, name, computed ) {
var width, minWidth, maxWidth, ret,
// Support: Firefox 51+
// Retrieving style before computed somehow
// fixes an issue with getting wrong values
// on detached elements
style = elem.style;
computed = computed || getStyles( elem );
// getPropertyValue is needed for:
// .css('filter') (IE 9 only, #12537)
// .css('--customProperty) (#3144)
if ( computed ) {
ret = computed.getPropertyValue( name ) || computed[ name ];
if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) {
ret = jQuery.style( elem, name );
}
// A tribute to the "awesome hack by Dean Edwards"
// Android Browser returns percentage for some values,
// but width seems to be reliably pixels.
// This is against the CSSOM draft spec:
// https://drafts.csswg.org/cssom/#resolved-values
if ( !support.pixelBoxStyles() && rnumnonpx.test( ret ) && rboxStyle.test( name ) ) {
// Remember the original values
width = style.width;
minWidth = style.minWidth;
maxWidth = style.maxWidth;
// Put in the new values to get a computed value out
style.minWidth = style.maxWidth = style.width = ret;
ret = computed.width;
// Revert the changed values
style.width = width;
style.minWidth = minWidth;
style.maxWidth = maxWidth;
}
}
return ret !== undefined ?
// Support: IE <=9 - 11 only
// IE returns zIndex value as an integer.
ret + "" :
ret;
}
function addGetHookIf( conditionFn, hookFn ) {
// Define the hook, we'll check on the first run if it's really needed.
return {
get: function() {
if ( conditionFn() ) {
// Hook not needed (or it's not possible to use it due
// to missing dependency), remove it.
delete this.get;
return;
}
// Hook needed; redefine it so that the support test is not executed again.
return ( this.get = hookFn ).apply( this, arguments );
}
};
}
var
// Swappable if display is none or starts with table
// except "table", "table-cell", or "table-caption"
// See here for display values: https://developer.mozilla.org/en-US/docs/CSS/display
rdisplayswap = /^(none|table(?!-c[ea]).+)/,
rcustomProp = /^--/,
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
cssNormalTransform = {
letterSpacing: "0",
fontWeight: "400"
},
cssPrefixes = [ "Webkit", "Moz", "ms" ],
emptyStyle = document.createElement( "div" ).style;
// Return a css property mapped to a potentially vendor prefixed property
function vendorPropName( name ) {
// Shortcut for names that are not vendor prefixed
if ( name in emptyStyle ) {
return name;
}
// Check for vendor prefixed names
var capName = name[ 0 ].toUpperCase() + name.slice( 1 ),
i = cssPrefixes.length;
while ( i-- ) {
name = cssPrefixes[ i ] + capName;
if ( name in emptyStyle ) {
return name;
}
}
}
// Return a property mapped along what jQuery.cssProps suggests or to
// a vendor prefixed property.
function finalPropName( name ) {
var ret = jQuery.cssProps[ name ];
if ( !ret ) {
ret = jQuery.cssProps[ name ] = vendorPropName( name ) || name;
}
return ret;
}
function setPositiveNumber( elem, value, subtract ) {
// Any relative (+/-) values have already been
// normalized at this point
var matches = rcssNum.exec( value );
return matches ?
// Guard against undefined "subtract", e.g., when used as in cssHooks
Math.max( 0, matches[ 2 ] - ( subtract || 0 ) ) + ( matches[ 3 ] || "px" ) :
value;
}
function boxModelAdjustment( elem, dimension, box, isBorderBox, styles, computedVal ) {
var i = dimension === "width" ? 1 : 0,
extra = 0,
delta = 0;
// Adjustment may not be necessary
if ( box === ( isBorderBox ? "border" : "content" ) ) {
return 0;
}
for ( ; i < 4; i += 2 ) {
// Both box models exclude margin
if ( box === "margin" ) {
delta += jQuery.css( elem, box + cssExpand[ i ], true, styles );
}
// If we get here with a content-box, we're seeking "padding" or "border" or "margin"
if ( !isBorderBox ) {
// Add padding
delta += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
// For "border" or "margin", add border
if ( box !== "padding" ) {
delta += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
// But still keep track of it otherwise
} else {
extra += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
}
// If we get here with a border-box (content + padding + border), we're seeking "content" or
// "padding" or "margin"
} else {
// For "content", subtract padding
if ( box === "content" ) {
delta -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
}
// For "content" or "padding", subtract border
if ( box !== "margin" ) {
delta -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
}
}
}
// Account for positive content-box scroll gutter when requested by providing computedVal
if ( !isBorderBox && computedVal >= 0 ) {
// offsetWidth/offsetHeight is a rounded sum of content, padding, scroll gutter, and border
// Assuming integer scroll gutter, subtract the rest and round down
delta += Math.max( 0, Math.ceil(
elem[ "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ) ] -
computedVal -
delta -
extra -
0.5
) );
}
return delta;
}
function getWidthOrHeight( elem, dimension, extra ) {
// Start with computed style
var styles = getStyles( elem ),
val = curCSS( elem, dimension, styles ),
isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
valueIsBorderBox = isBorderBox;
// Support: Firefox <=54
// Return a confounding non-pixel value or feign ignorance, as appropriate.
if ( rnumnonpx.test( val ) ) {
if ( !extra ) {
return val;
}
val = "auto";
}
// Check for style in case a browser which returns unreliable values
// for getComputedStyle silently falls back to the reliable elem.style
valueIsBorderBox = valueIsBorderBox &&
( support.boxSizingReliable() || val === elem.style[ dimension ] );
// Fall back to offsetWidth/offsetHeight when value is "auto"
// This happens for inline elements with no explicit setting (gh-3571)
// Support: Android <=4.1 - 4.3 only
// Also use offsetWidth/offsetHeight for misreported inline dimensions (gh-3602)
if ( val === "auto" ||
!parseFloat( val ) && jQuery.css( elem, "display", false, styles ) === "inline" ) {
val = elem[ "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ) ];
// offsetWidth/offsetHeight provide border-box values
valueIsBorderBox = true;
}
// Normalize "" and auto
val = parseFloat( val ) || 0;
// Adjust for the element's box model
return ( val +
boxModelAdjustment(
elem,
dimension,
extra || ( isBorderBox ? "border" : "content" ),
valueIsBorderBox,
styles,
// Provide the current computed size to request scroll gutter calculation (gh-3589)
val
)
) + "px";
}
jQuery.extend( {
// Add in style property hooks for overriding the default
// behavior of getting and setting a style property
cssHooks: {
opacity: {
get: function( elem, computed ) {
if ( computed ) {
// We should always get a number back from opacity
var ret = curCSS( elem, "opacity" );
return ret === "" ? "1" : ret;
}
}
}
},
// Don't automatically add "px" to these possibly-unitless properties
cssNumber: {
"animationIterationCount": true,
"columnCount": true,
"fillOpacity": true,
"flexGrow": true,
"flexShrink": true,
"fontWeight": true,
"lineHeight": true,
"opacity": true,
"order": true,
"orphans": true,
"widows": true,
"zIndex": true,
"zoom": true
},
// Add in properties whose names you wish to fix before
// setting or getting the value
cssProps: {},
// Get and set the style property on a DOM Node
style: function( elem, name, value, extra ) {
// Don't set styles on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
return;
}
// Make sure that we're working with the right name
var ret, type, hooks,
origName = camelCase( name ),
isCustomProp = rcustomProp.test( name ),
style = elem.style;
// Make sure that we're working with the right name. We don't
// want to query the value if it is a CSS custom property
// since they are user-defined.
if ( !isCustomProp ) {
name = finalPropName( origName );
}
// Gets hook for the prefixed version, then unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// Check if we're setting a value
if ( value !== undefined ) {
type = typeof value;
// Convert "+=" or "-=" to relative numbers (#7345)
if ( type === "string" && ( ret = rcssNum.exec( value ) ) && ret[ 1 ] ) {
value = adjustCSS( elem, name, ret );
// Fixes bug #9237
type = "number";
}
// Make sure that null and NaN values aren't set (#7116)
if ( value == null || value !== value ) {
return;
}
// If a number was passed in, add the unit (except for certain CSS properties)
if ( type === "number" ) {
value += ret && ret[ 3 ] || ( jQuery.cssNumber[ origName ] ? "" : "px" );
}
// background-* props affect original clone's values
if ( !support.clearCloneStyle && value === "" && name.indexOf( "background" ) === 0 ) {
style[ name ] = "inherit";
}
// If a hook was provided, use that value, otherwise just set the specified value
if ( !hooks || !( "set" in hooks ) ||
( value = hooks.set( elem, value, extra ) ) !== undefined ) {
if ( isCustomProp ) {
style.setProperty( name, value );
} else {
style[ name ] = value;
}
}
} else {
// If a hook was provided get the non-computed value from there
if ( hooks && "get" in hooks &&
( ret = hooks.get( elem, false, extra ) ) !== undefined ) {
return ret;
}
// Otherwise just get the value from the style object
return style[ name ];
}
},
css: function( elem, name, extra, styles ) {
var val, num, hooks,
origName = camelCase( name ),
isCustomProp = rcustomProp.test( name );
// Make sure that we're working with the right name. We don't
// want to modify the value if it is a CSS custom property
// since they are user-defined.
if ( !isCustomProp ) {
name = finalPropName( origName );
}
// Try prefixed name followed by the unprefixed name
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// If a hook was provided get the computed value from there
if ( hooks && "get" in hooks ) {
val = hooks.get( elem, true, extra );
}
// Otherwise, if a way to get the computed value exists, use that
if ( val === undefined ) {
val = curCSS( elem, name, styles );
}
// Convert "normal" to computed value
if ( val === "normal" && name in cssNormalTransform ) {
val = cssNormalTransform[ name ];
}
// Make numeric if forced or a qualifier was provided and val looks numeric
if ( extra === "" || extra ) {
num = parseFloat( val );
return extra === true || isFinite( num ) ? num || 0 : val;
}
return val;
}
} );
jQuery.each( [ "height", "width" ], function( i, dimension ) {
jQuery.cssHooks[ dimension ] = {
get: function( elem, computed, extra ) {
if ( computed ) {
// Certain elements can have dimension info if we invisibly show them
// but it must have a current display style that would benefit
return rdisplayswap.test( jQuery.css( elem, "display" ) ) &&
// Support: Safari 8+
// Table columns in Safari have non-zero offsetWidth & zero
// getBoundingClientRect().width unless display is changed.
// Support: IE <=11 only
// Running getBoundingClientRect on a disconnected node
// in IE throws an error.
( !elem.getClientRects().length || !elem.getBoundingClientRect().width ) ?
swap( elem, cssShow, function() {
return getWidthOrHeight( elem, dimension, extra );
} ) :
getWidthOrHeight( elem, dimension, extra );
}
},
set: function( elem, value, extra ) {
var matches,
styles = getStyles( elem ),
isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
subtract = extra && boxModelAdjustment(
elem,
dimension,
extra,
isBorderBox,
styles
);
// Account for unreliable border-box dimensions by comparing offset* to computed and
// faking a content-box to get border and padding (gh-3699)
if ( isBorderBox && support.scrollboxSize() === styles.position ) {
subtract -= Math.ceil(
elem[ "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ) ] -
parseFloat( styles[ dimension ] ) -
boxModelAdjustment( elem, dimension, "border", false, styles ) -
0.5
);
}
// Convert to pixels if value adjustment is needed
if ( subtract && ( matches = rcssNum.exec( value ) ) &&
( matches[ 3 ] || "px" ) !== "px" ) {
elem.style[ dimension ] = value;
value = jQuery.css( elem, dimension );
}
return setPositiveNumber( elem, value, subtract );
}
};
} );
jQuery.cssHooks.marginLeft = addGetHookIf( support.reliableMarginLeft,
function( elem, computed ) {
if ( computed ) {
return ( parseFloat( curCSS( elem, "marginLeft" ) ) ||
elem.getBoundingClientRect().left -
swap( elem, { marginLeft: 0 }, function() {
return elem.getBoundingClientRect().left;
} )
) + "px";
}
}
);
// These hooks are used by animate to expand properties
jQuery.each( {
margin: "",
padding: "",
border: "Width"
}, function( prefix, suffix ) {
jQuery.cssHooks[ prefix + suffix ] = {
expand: function( value ) {
var i = 0,
expanded = {},
// Assumes a single number if not a string
parts = typeof value === "string" ? value.split( " " ) : [ value ];
for ( ; i < 4; i++ ) {
expanded[ prefix + cssExpand[ i ] + suffix ] =
parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
}
return expanded;
}
};
if ( prefix !== "margin" ) {
jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber;
}
} );
jQuery.fn.extend( {
css: function( name, value ) {
return access( this, function( elem, name, value ) {
var styles, len,
map = {},
i = 0;
if ( Array.isArray( name ) ) {
styles = getStyles( elem );
len = name.length;
for ( ; i < len; i++ ) {
map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles );
}
return map;
}
return value !== undefined ?
jQuery.style( elem, name, value ) :
jQuery.css( elem, name );
}, name, value, arguments.length > 1 );
}
} );
function Tween( elem, options, prop, end, easing ) {
return new Tween.prototype.init( elem, options, prop, end, easing );
}
jQuery.Tween = Tween;
Tween.prototype = {
constructor: Tween,
init: function( elem, options, prop, end, easing, unit ) {
this.elem = elem;
this.prop = prop;
this.easing = easing || jQuery.easing._default;
this.options = options;
this.start = this.now = this.cur();
this.end = end;
this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" );
},
cur: function() {
var hooks = Tween.propHooks[ this.prop ];
return hooks && hooks.get ?
hooks.get( this ) :
Tween.propHooks._default.get( this );
},
run: function( percent ) {
var eased,
hooks = Tween.propHooks[ this.prop ];
if ( this.options.duration ) {
this.pos = eased = jQuery.easing[ this.easing ](
percent, this.options.duration * percent, 0, 1, this.options.duration
);
} else {
this.pos = eased = percent;
}
this.now = ( this.end - this.start ) * eased + this.start;
if ( this.options.step ) {
this.options.step.call( this.elem, this.now, this );
}
if ( hooks && hooks.set ) {
hooks.set( this );
} else {
Tween.propHooks._default.set( this );
}
return this;
}
};
Tween.prototype.init.prototype = Tween.prototype;
Tween.propHooks = {
_default: {
get: function( tween ) {
var result;
// Use a property on the element directly when it is not a DOM element,
// or when there is no matching style property that exists.
if ( tween.elem.nodeType !== 1 ||
tween.elem[ tween.prop ] != null && tween.elem.style[ tween.prop ] == null ) {
return tween.elem[ tween.prop ];
}
// Passing an empty string as a 3rd parameter to .css will automatically
// attempt a parseFloat and fallback to a string if the parse fails.
// Simple values such as "10px" are parsed to Float;
// complex values such as "rotate(1rad)" are returned as-is.
result = jQuery.css( tween.elem, tween.prop, "" );
// Empty strings, null, undefined and "auto" are converted to 0.
return !result || result === "auto" ? 0 : result;
},
set: function( tween ) {
// Use step hook for back compat.
// Use cssHook if its there.
// Use .style if available and use plain properties where available.
if ( jQuery.fx.step[ tween.prop ] ) {
jQuery.fx.step[ tween.prop ]( tween );
} else if ( tween.elem.nodeType === 1 &&
( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null ||
jQuery.cssHooks[ tween.prop ] ) ) {
jQuery.style( tween.elem, tween.prop, tween.now + tween.unit );
} else {
tween.elem[ tween.prop ] = tween.now;
}
}
}
};
// Support: IE <=9 only
// Panic based approach to setting things on disconnected nodes
Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {
set: function( tween ) {
if ( tween.elem.nodeType && tween.elem.parentNode ) {
tween.elem[ tween.prop ] = tween.now;
}
}
};
jQuery.easing = {
linear: function( p ) {
return p;
},
swing: function( p ) {
return 0.5 - Math.cos( p * Math.PI ) / 2;
},
_default: "swing"
};
jQuery.fx = Tween.prototype.init;
// Back compat <1.8 extension point
jQuery.fx.step = {};
var
fxNow, inProgress,
rfxtypes = /^(?:toggle|show|hide)$/,
rrun = /queueHooks$/;
function schedule() {
if ( inProgress ) {
if ( document.hidden === false && window.requestAnimationFrame ) {
window.requestAnimationFrame( schedule );
} else {
window.setTimeout( schedule, jQuery.fx.interval );
}
jQuery.fx.tick();
}
}
// Animations created synchronously will run synchronously
function createFxNow() {
window.setTimeout( function() {
fxNow = undefined;
} );
return ( fxNow = Date.now() );
}
// Generate parameters to create a standard animation
function genFx( type, includeWidth ) {
var which,
i = 0,
attrs = { height: type };
// If we include width, step value is 1 to do all cssExpand values,
// otherwise step value is 2 to skip over Left and Right
includeWidth = includeWidth ? 1 : 0;
for ( ; i < 4; i += 2 - includeWidth ) {
which = cssExpand[ i ];
attrs[ "margin" + which ] = attrs[ "padding" + which ] = type;
}
if ( includeWidth ) {
attrs.opacity = attrs.width = type;
}
return attrs;
}
function createTween( value, prop, animation ) {
var tween,
collection = ( Animation.tweeners[ prop ] || [] ).concat( Animation.tweeners[ "*" ] ),
index = 0,
length = collection.length;
for ( ; index < length; index++ ) {
if ( ( tween = collection[ index ].call( animation, prop, value ) ) ) {
// We're done with this property
return tween;
}
}
}
function defaultPrefilter( elem, props, opts ) {
var prop, value, toggle, hooks, oldfire, propTween, restoreDisplay, display,
isBox = "width" in props || "height" in props,
anim = this,
orig = {},
style = elem.style,
hidden = elem.nodeType && isHiddenWithinTree( elem ),
dataShow = dataPriv.get( elem, "fxshow" );
// Queue-skipping animations hijack the fx hooks
if ( !opts.queue ) {
hooks = jQuery._queueHooks( elem, "fx" );
if ( hooks.unqueued == null ) {
hooks.unqueued = 0;
oldfire = hooks.empty.fire;
hooks.empty.fire = function() {
if ( !hooks.unqueued ) {
oldfire();
}
};
}
hooks.unqueued++;
anim.always( function() {
// Ensure the complete handler is called before this completes
anim.always( function() {
hooks.unqueued--;
if ( !jQuery.queue( elem, "fx" ).length ) {
hooks.empty.fire();
}
} );
} );
}
// Detect show/hide animations
for ( prop in props ) {
value = props[ prop ];
if ( rfxtypes.test( value ) ) {
delete props[ prop ];
toggle = toggle || value === "toggle";
if ( value === ( hidden ? "hide" : "show" ) ) {
// Pretend to be hidden if this is a "show" and
// there is still data from a stopped show/hide
if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) {
hidden = true;
// Ignore all other no-op show/hide data
} else {
continue;
}
}
orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop );
}
}
// Bail out if this is a no-op like .hide().hide()
propTween = !jQuery.isEmptyObject( props );
if ( !propTween && jQuery.isEmptyObject( orig ) ) {
return;
}
// Restrict "overflow" and "display" styles during box animations
if ( isBox && elem.nodeType === 1 ) {
// Support: IE <=9 - 11, Edge 12 - 15
// Record all 3 overflow attributes because IE does not infer the shorthand
// from identically-valued overflowX and overflowY and Edge just mirrors
// the overflowX value there.
opts.overflow = [ style.overflow, style.overflowX, style.overflowY ];
// Identify a display type, preferring old show/hide data over the CSS cascade
restoreDisplay = dataShow && dataShow.display;
if ( restoreDisplay == null ) {
restoreDisplay = dataPriv.get( elem, "display" );
}
display = jQuery.css( elem, "display" );
if ( display === "none" ) {
if ( restoreDisplay ) {
display = restoreDisplay;
} else {
// Get nonempty value(s) by temporarily forcing visibility
showHide( [ elem ], true );
restoreDisplay = elem.style.display || restoreDisplay;
display = jQuery.css( elem, "display" );
showHide( [ elem ] );
}
}
// Animate inline elements as inline-block
if ( display === "inline" || display === "inline-block" && restoreDisplay != null ) {
if ( jQuery.css( elem, "float" ) === "none" ) {
// Restore the original display value at the end of pure show/hide animations
if ( !propTween ) {
anim.done( function() {
style.display = restoreDisplay;
} );
if ( restoreDisplay == null ) {
display = style.display;
restoreDisplay = display === "none" ? "" : display;
}
}
style.display = "inline-block";
}
}
}
if ( opts.overflow ) {
style.overflow = "hidden";
anim.always( function() {
style.overflow = opts.overflow[ 0 ];
style.overflowX = opts.overflow[ 1 ];
style.overflowY = opts.overflow[ 2 ];
} );
}
// Implement show/hide animations
propTween = false;
for ( prop in orig ) {
// General show/hide setup for this element animation
if ( !propTween ) {
if ( dataShow ) {
if ( "hidden" in dataShow ) {
hidden = dataShow.hidden;
}
} else {
dataShow = dataPriv.access( elem, "fxshow", { display: restoreDisplay } );
}
// Store hidden/visible for toggle so `.stop().toggle()` "reverses"
if ( toggle ) {
dataShow.hidden = !hidden;
}
// Show elements before animating them
if ( hidden ) {
showHide( [ elem ], true );
}
/* eslint-disable no-loop-func */
anim.done( function() {
/* eslint-enable no-loop-func */
// The final step of a "hide" animation is actually hiding the element
if ( !hidden ) {
showHide( [ elem ] );
}
dataPriv.remove( elem, "fxshow" );
for ( prop in orig ) {
jQuery.style( elem, prop, orig[ prop ] );
}
} );
}
// Per-property setup
propTween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim );
if ( !( prop in dataShow ) ) {
dataShow[ prop ] = propTween.start;
if ( hidden ) {
propTween.end = propTween.start;
propTween.start = 0;
}
}
}
}
function propFilter( props, specialEasing ) {
var index, name, easing, value, hooks;
// camelCase, specialEasing and expand cssHook pass
for ( index in props ) {
name = camelCase( index );
easing = specialEasing[ name ];
value = props[ index ];
if ( Array.isArray( value ) ) {
easing = value[ 1 ];
value = props[ index ] = value[ 0 ];
}
if ( index !== name ) {
props[ name ] = value;
delete props[ index ];
}
hooks = jQuery.cssHooks[ name ];
if ( hooks && "expand" in hooks ) {
value = hooks.expand( value );
delete props[ name ];
// Not quite $.extend, this won't overwrite existing keys.
// Reusing 'index' because we have the correct "name"
for ( index in value ) {
if ( !( index in props ) ) {
props[ index ] = value[ index ];
specialEasing[ index ] = easing;
}
}
} else {
specialEasing[ name ] = easing;
}
}
}
function Animation( elem, properties, options ) {
var result,
stopped,
index = 0,
length = Animation.prefilters.length,
deferred = jQuery.Deferred().always( function() {
// Don't match elem in the :animated selector
delete tick.elem;
} ),
tick = function() {
if ( stopped ) {
return false;
}
var currentTime = fxNow || createFxNow(),
remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ),
// Support: Android 2.3 only
// Archaic crash bug won't allow us to use `1 - ( 0.5 || 0 )` (#12497)
temp = remaining / animation.duration || 0,
percent = 1 - temp,
index = 0,
length = animation.tweens.length;
for ( ; index < length; index++ ) {
animation.tweens[ index ].run( percent );
}
deferred.notifyWith( elem, [ animation, percent, remaining ] );
// If there's more to do, yield
if ( percent < 1 && length ) {
return remaining;
}
// If this was an empty animation, synthesize a final progress notification
if ( !length ) {
deferred.notifyWith( elem, [ animation, 1, 0 ] );
}
// Resolve the animation and report its conclusion
deferred.resolveWith( elem, [ animation ] );
return false;
},
animation = deferred.promise( {
elem: elem,
props: jQuery.extend( {}, properties ),
opts: jQuery.extend( true, {
specialEasing: {},
easing: jQuery.easing._default
}, options ),
originalProperties: properties,
originalOptions: options,
startTime: fxNow || createFxNow(),
duration: options.duration,
tweens: [],
createTween: function( prop, end ) {
var tween = jQuery.Tween( elem, animation.opts, prop, end,
animation.opts.specialEasing[ prop ] || animation.opts.easing );
animation.tweens.push( tween );
return tween;
},
stop: function( gotoEnd ) {
var index = 0,
// If we are going to the end, we want to run all the tweens
// otherwise we skip this part
length = gotoEnd ? animation.tweens.length : 0;
if ( stopped ) {
return this;
}
stopped = true;
for ( ; index < length; index++ ) {
animation.tweens[ index ].run( 1 );
}
// Resolve when we played the last frame; otherwise, reject
if ( gotoEnd ) {
deferred.notifyWith( elem, [ animation, 1, 0 ] );
deferred.resolveWith( elem, [ animation, gotoEnd ] );
} else {
deferred.rejectWith( elem, [ animation, gotoEnd ] );
}
return this;
}
} ),
props = animation.props;
propFilter( props, animation.opts.specialEasing );
for ( ; index < length; index++ ) {
result = Animation.prefilters[ index ].call( animation, elem, props, animation.opts );
if ( result ) {
if ( isFunction( result.stop ) ) {
jQuery._queueHooks( animation.elem, animation.opts.queue ).stop =
result.stop.bind( result );
}
return result;
}
}
jQuery.map( props, createTween, animation );
if ( isFunction( animation.opts.start ) ) {
animation.opts.start.call( elem, animation );
}
// Attach callbacks from options
animation
.progress( animation.opts.progress )
.done( animation.opts.done, animation.opts.complete )
.fail( animation.opts.fail )
.always( animation.opts.always );
jQuery.fx.timer(
jQuery.extend( tick, {
elem: elem,
anim: animation,
queue: animation.opts.queue
} )
);
return animation;
}
jQuery.Animation = jQuery.extend( Animation, {
tweeners: {
"*": [ function( prop, value ) {
var tween = this.createTween( prop, value );
adjustCSS( tween.elem, prop, rcssNum.exec( value ), tween );
return tween;
} ]
},
tweener: function( props, callback ) {
if ( isFunction( props ) ) {
callback = props;
props = [ "*" ];
} else {
props = props.match( rnothtmlwhite );
}
var prop,
index = 0,
length = props.length;
for ( ; index < length; index++ ) {
prop = props[ index ];
Animation.tweeners[ prop ] = Animation.tweeners[ prop ] || [];
Animation.tweeners[ prop ].unshift( callback );
}
},
prefilters: [ defaultPrefilter ],
prefilter: function( callback, prepend ) {
if ( prepend ) {
Animation.prefilters.unshift( callback );
} else {
Animation.prefilters.push( callback );
}
}
} );
jQuery.speed = function( speed, easing, fn ) {
var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : {
complete: fn || !fn && easing ||
isFunction( speed ) && speed,
duration: speed,
easing: fn && easing || easing && !isFunction( easing ) && easing
};
// Go to the end state if fx are off
if ( jQuery.fx.off ) {
opt.duration = 0;
} else {
if ( typeof opt.duration !== "number" ) {
if ( opt.duration in jQuery.fx.speeds ) {
opt.duration = jQuery.fx.speeds[ opt.duration ];
} else {
opt.duration = jQuery.fx.speeds._default;
}
}
}
// Normalize opt.queue - true/undefined/null -> "fx"
if ( opt.queue == null || opt.queue === true ) {
opt.queue = "fx";
}
// Queueing
opt.old = opt.complete;
opt.complete = function() {
if ( isFunction( opt.old ) ) {
opt.old.call( this );
}
if ( opt.queue ) {
jQuery.dequeue( this, opt.queue );
}
};
return opt;
};
jQuery.fn.extend( {
fadeTo: function( speed, to, easing, callback ) {
// Show any hidden elements after setting opacity to 0
return this.filter( isHiddenWithinTree ).css( "opacity", 0 ).show()
// Animate to the value specified
.end().animate( { opacity: to }, speed, easing, callback );
},
animate: function( prop, speed, easing, callback ) {
var empty = jQuery.isEmptyObject( prop ),
optall = jQuery.speed( speed, easing, callback ),
doAnimation = function() {
// Operate on a copy of prop so per-property easing won't be lost
var anim = Animation( this, jQuery.extend( {}, prop ), optall );
// Empty animations, or finishing resolves immediately
if ( empty || dataPriv.get( this, "finish" ) ) {
anim.stop( true );
}
};
doAnimation.finish = doAnimation;
return empty || optall.queue === false ?
this.each( doAnimation ) :
this.queue( optall.queue, doAnimation );
},
stop: function( type, clearQueue, gotoEnd ) {
var stopQueue = function( hooks ) {
var stop = hooks.stop;
delete hooks.stop;
stop( gotoEnd );
};
if ( typeof type !== "string" ) {
gotoEnd = clearQueue;
clearQueue = type;
type = undefined;
}
if ( clearQueue && type !== false ) {
this.queue( type || "fx", [] );
}
return this.each( function() {
var dequeue = true,
index = type != null && type + "queueHooks",
timers = jQuery.timers,
data = dataPriv.get( this );
if ( index ) {
if ( data[ index ] && data[ index ].stop ) {
stopQueue( data[ index ] );
}
} else {
for ( index in data ) {
if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) {
stopQueue( data[ index ] );
}
}
}
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this &&
( type == null || timers[ index ].queue === type ) ) {
timers[ index ].anim.stop( gotoEnd );
dequeue = false;
timers.splice( index, 1 );
}
}
// Start the next in the queue if the last step wasn't forced.
// Timers currently will call their complete callbacks, which
// will dequeue but only if they were gotoEnd.
if ( dequeue || !gotoEnd ) {
jQuery.dequeue( this, type );
}
} );
},
finish: function( type ) {
if ( type !== false ) {
type = type || "fx";
}
return this.each( function() {
var index,
data = dataPriv.get( this ),
queue = data[ type + "queue" ],
hooks = data[ type + "queueHooks" ],
timers = jQuery.timers,
length = queue ? queue.length : 0;
// Enable finishing flag on private data
data.finish = true;
// Empty the queue first
jQuery.queue( this, type, [] );
if ( hooks && hooks.stop ) {
hooks.stop.call( this, true );
}
// Look for any active animations, and finish them
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this && timers[ index ].queue === type ) {
timers[ index ].anim.stop( true );
timers.splice( index, 1 );
}
}
// Look for any animations in the old queue and finish them
for ( index = 0; index < length; index++ ) {
if ( queue[ index ] && queue[ index ].finish ) {
queue[ index ].finish.call( this );
}
}
// Turn off finishing flag
delete data.finish;
} );
}
} );
jQuery.each( [ "toggle", "show", "hide" ], function( i, name ) {
var cssFn = jQuery.fn[ name ];
jQuery.fn[ name ] = function( speed, easing, callback ) {
return speed == null || typeof speed === "boolean" ?
cssFn.apply( this, arguments ) :
this.animate( genFx( name, true ), speed, easing, callback );
};
} );
// Generate shortcuts for custom animations
jQuery.each( {
slideDown: genFx( "show" ),
slideUp: genFx( "hide" ),
slideToggle: genFx( "toggle" ),
fadeIn: { opacity: "show" },
fadeOut: { opacity: "hide" },
fadeToggle: { opacity: "toggle" }
}, function( name, props ) {
jQuery.fn[ name ] = function( speed, easing, callback ) {
return this.animate( props, speed, easing, callback );
};
} );
jQuery.timers = [];
jQuery.fx.tick = function() {
var timer,
i = 0,
timers = jQuery.timers;
fxNow = Date.now();
for ( ; i < timers.length; i++ ) {
timer = timers[ i ];
// Run the timer and safely remove it when done (allowing for external removal)
if ( !timer() && timers[ i ] === timer ) {
timers.splice( i--, 1 );
}
}
if ( !timers.length ) {
jQuery.fx.stop();
}
fxNow = undefined;
};
jQuery.fx.timer = function( timer ) {
jQuery.timers.push( timer );
jQuery.fx.start();
};
jQuery.fx.interval = 13;
jQuery.fx.start = function() {
if ( inProgress ) {
return;
}
inProgress = true;
schedule();
};
jQuery.fx.stop = function() {
inProgress = null;
};
jQuery.fx.speeds = {
slow: 600,
fast: 200,
// Default speed
_default: 400
};
// Based off of the plugin by Clint Helfers, with permission.
// https://web.archive.org/web/20100324014747/http://blindsignals.com/index.php/2009/07/jquery-delay/
jQuery.fn.delay = function( time, type ) {
time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
type = type || "fx";
return this.queue( type, function( next, hooks ) {
var timeout = window.setTimeout( next, time );
hooks.stop = function() {
window.clearTimeout( timeout );
};
} );
};
( function() {
var input = document.createElement( "input" ),
select = document.createElement( "select" ),
opt = select.appendChild( document.createElement( "option" ) );
input.type = "checkbox";
// Support: Android <=4.3 only
// Default value for a checkbox should be "on"
support.checkOn = input.value !== "";
// Support: IE <=11 only
// Must access selectedIndex to make default options select
support.optSelected = opt.selected;
// Support: IE <=11 only
// An input loses its value after becoming a radio
input = document.createElement( "input" );
input.value = "t";
input.type = "radio";
support.radioValue = input.value === "t";
} )();
var boolHook,
attrHandle = jQuery.expr.attrHandle;
jQuery.fn.extend( {
attr: function( name, value ) {
return access( this, jQuery.attr, name, value, arguments.length > 1 );
},
removeAttr: function( name ) {
return this.each( function() {
jQuery.removeAttr( this, name );
} );
}
} );
jQuery.extend( {
attr: function( elem, name, value ) {
var ret, hooks,
nType = elem.nodeType;
// Don't get/set attributes on text, comment and attribute nodes
if ( nType === 3 || nType === 8 || nType === 2 ) {
return;
}
// Fallback to prop when attributes are not supported
if ( typeof elem.getAttribute === "undefined" ) {
return jQuery.prop( elem, name, value );
}
// Attribute hooks are determined by the lowercase version
// Grab necessary hook if one is defined
if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
hooks = jQuery.attrHooks[ name.toLowerCase() ] ||
( jQuery.expr.match.bool.test( name ) ? boolHook : undefined );
}
if ( value !== undefined ) {
if ( value === null ) {
jQuery.removeAttr( elem, name );
return;
}
if ( hooks && "set" in hooks &&
( ret = hooks.set( elem, value, name ) ) !== undefined ) {
return ret;
}
elem.setAttribute( name, value + "" );
return value;
}
if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) {
return ret;
}
ret = jQuery.find.attr( elem, name );
// Non-existent attributes return null, we normalize to undefined
return ret == null ? undefined : ret;
},
attrHooks: {
type: {
set: function( elem, value ) {
if ( !support.radioValue && value === "radio" &&
nodeName( elem, "input" ) ) {
var val = elem.value;
elem.setAttribute( "type", value );
if ( val ) {
elem.value = val;
}
return value;
}
}
}
},
removeAttr: function( elem, value ) {
var name,
i = 0,
// Attribute names can contain non-HTML whitespace characters
// https://html.spec.whatwg.org/multipage/syntax.html#attributes-2
attrNames = value && value.match( rnothtmlwhite );
if ( attrNames && elem.nodeType === 1 ) {
while ( ( name = attrNames[ i++ ] ) ) {
elem.removeAttribute( name );
}
}
}
} );
// Hooks for boolean attributes
boolHook = {
set: function( elem, value, name ) {
if ( value === false ) {
// Remove boolean attributes when set to false
jQuery.removeAttr( elem, name );
} else {
elem.setAttribute( name, name );
}
return name;
}
};
jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) {
var getter = attrHandle[ name ] || jQuery.find.attr;
attrHandle[ name ] = function( elem, name, isXML ) {
var ret, handle,
lowercaseName = name.toLowerCase();
if ( !isXML ) {
// Avoid an infinite loop by temporarily removing this function from the getter
handle = attrHandle[ lowercaseName ];
attrHandle[ lowercaseName ] = ret;
ret = getter( elem, name, isXML ) != null ?
lowercaseName :
null;
attrHandle[ lowercaseName ] = handle;
}
return ret;
};
} );
var rfocusable = /^(?:input|select|textarea|button)$/i,
rclickable = /^(?:a|area)$/i;
jQuery.fn.extend( {
prop: function( name, value ) {
return access( this, jQuery.prop, name, value, arguments.length > 1 );
},
removeProp: function( name ) {
return this.each( function() {
delete this[ jQuery.propFix[ name ] || name ];
} );
}
} );
jQuery.extend( {
prop: function( elem, name, value ) {
var ret, hooks,
nType = elem.nodeType;
// Don't get/set properties on text, comment and attribute nodes
if ( nType === 3 || nType === 8 || nType === 2 ) {
return;
}
if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
// Fix name and attach hooks
name = jQuery.propFix[ name ] || name;
hooks = jQuery.propHooks[ name ];
}
if ( value !== undefined ) {
if ( hooks && "set" in hooks &&
( ret = hooks.set( elem, value, name ) ) !== undefined ) {
return ret;
}
return ( elem[ name ] = value );
}
if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) {
return ret;
}
return elem[ name ];
},
propHooks: {
tabIndex: {
get: function( elem ) {
// Support: IE <=9 - 11 only
// elem.tabIndex doesn't always return the
// correct value when it hasn't been explicitly set
// https://web.archive.org/web/20141116233347/http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
// Use proper attribute retrieval(#12072)
var tabindex = jQuery.find.attr( elem, "tabindex" );
if ( tabindex ) {
return parseInt( tabindex, 10 );
}
if (
rfocusable.test( elem.nodeName ) ||
rclickable.test( elem.nodeName ) &&
elem.href
) {
return 0;
}
return -1;
}
}
},
propFix: {
"for": "htmlFor",
"class": "className"
}
} );
// Support: IE <=11 only
// Accessing the selectedIndex property
// forces the browser to respect setting selected
// on the option
// The getter ensures a default option is selected
// when in an optgroup
// eslint rule "no-unused-expressions" is disabled for this code
// since it considers such accessions noop
if ( !support.optSelected ) {
jQuery.propHooks.selected = {
get: function( elem ) {
/* eslint no-unused-expressions: "off" */
var parent = elem.parentNode;
if ( parent && parent.parentNode ) {
parent.parentNode.selectedIndex;
}
return null;
},
set: function( elem ) {
/* eslint no-unused-expressions: "off" */
var parent = elem.parentNode;
if ( parent ) {
parent.selectedIndex;
if ( parent.parentNode ) {
parent.parentNode.selectedIndex;
}
}
}
};
}
jQuery.each( [
"tabIndex",
"readOnly",
"maxLength",
"cellSpacing",
"cellPadding",
"rowSpan",
"colSpan",
"useMap",
"frameBorder",
"contentEditable"
], function() {
jQuery.propFix[ this.toLowerCase() ] = this;
} );
// Strip and collapse whitespace according to HTML spec
// https://infra.spec.whatwg.org/#strip-and-collapse-ascii-whitespace
function stripAndCollapse( value ) {
var tokens = value.match( rnothtmlwhite ) || [];
return tokens.join( " " );
}
function getClass( elem ) {
return elem.getAttribute && elem.getAttribute( "class" ) || "";
}
function classesToArray( value ) {
if ( Array.isArray( value ) ) {
return value;
}
if ( typeof value === "string" ) {
return value.match( rnothtmlwhite ) || [];
}
return [];
}
jQuery.fn.extend( {
addClass: function( value ) {
var classes, elem, cur, curValue, clazz, j, finalValue,
i = 0;
if ( isFunction( value ) ) {
return this.each( function( j ) {
jQuery( this ).addClass( value.call( this, j, getClass( this ) ) );
} );
}
classes = classesToArray( value );
if ( classes.length ) {
while ( ( elem = this[ i++ ] ) ) {
curValue = getClass( elem );
cur = elem.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " );
if ( cur ) {
j = 0;
while ( ( clazz = classes[ j++ ] ) ) {
if ( cur.indexOf( " " + clazz + " " ) < 0 ) {
cur += clazz + " ";
}
}
// Only assign if different to avoid unneeded rendering.
finalValue = stripAndCollapse( cur );
if ( curValue !== finalValue ) {
elem.setAttribute( "class", finalValue );
}
}
}
}
return this;
},
removeClass: function( value ) {
var classes, elem, cur, curValue, clazz, j, finalValue,
i = 0;
if ( isFunction( value ) ) {
return this.each( function( j ) {
jQuery( this ).removeClass( value.call( this, j, getClass( this ) ) );
} );
}
if ( !arguments.length ) {
return this.attr( "class", "" );
}
classes = classesToArray( value );
if ( classes.length ) {
while ( ( elem = this[ i++ ] ) ) {
curValue = getClass( elem );
// This expression is here for better compressibility (see addClass)
cur = elem.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " );
if ( cur ) {
j = 0;
while ( ( clazz = classes[ j++ ] ) ) {
// Remove *all* instances
while ( cur.indexOf( " " + clazz + " " ) > -1 ) {
cur = cur.replace( " " + clazz + " ", " " );
}
}
// Only assign if different to avoid unneeded rendering.
finalValue = stripAndCollapse( cur );
if ( curValue !== finalValue ) {
elem.setAttribute( "class", finalValue );
}
}
}
}
return this;
},
toggleClass: function( value, stateVal ) {
var type = typeof value,
isValidValue = type === "string" || Array.isArray( value );
if ( typeof stateVal === "boolean" && isValidValue ) {
return stateVal ? this.addClass( value ) : this.removeClass( value );
}
if ( isFunction( value ) ) {
return this.each( function( i ) {
jQuery( this ).toggleClass(
value.call( this, i, getClass( this ), stateVal ),
stateVal
);
} );
}
return this.each( function() {
var className, i, self, classNames;
if ( isValidValue ) {
// Toggle individual class names
i = 0;
self = jQuery( this );
classNames = classesToArray( value );
while ( ( className = classNames[ i++ ] ) ) {
// Check each className given, space separated list
if ( self.hasClass( className ) ) {
self.removeClass( className );
} else {
self.addClass( className );
}
}
// Toggle whole class name
} else if ( value === undefined || type === "boolean" ) {
className = getClass( this );
if ( className ) {
// Store className if set
dataPriv.set( this, "__className__", className );
}
// If the element has a class name or if we're passed `false`,
// then remove the whole classname (if there was one, the above saved it).
// Otherwise bring back whatever was previously saved (if anything),
// falling back to the empty string if nothing was stored.
if ( this.setAttribute ) {
this.setAttribute( "class",
className || value === false ?
"" :
dataPriv.get( this, "__className__" ) || ""
);
}
}
} );
},
hasClass: function( selector ) {
var className, elem,
i = 0;
className = " " + selector + " ";
while ( ( elem = this[ i++ ] ) ) {
if ( elem.nodeType === 1 &&
( " " + stripAndCollapse( getClass( elem ) ) + " " ).indexOf( className ) > -1 ) {
return true;
}
}
return false;
}
} );
var rreturn = /\r/g;
jQuery.fn.extend( {
val: function( value ) {
var hooks, ret, valueIsFunction,
elem = this[ 0 ];
if ( !arguments.length ) {
if ( elem ) {
hooks = jQuery.valHooks[ elem.type ] ||
jQuery.valHooks[ elem.nodeName.toLowerCase() ];
if ( hooks &&
"get" in hooks &&
( ret = hooks.get( elem, "value" ) ) !== undefined
) {
return ret;
}
ret = elem.value;
// Handle most common string cases
if ( typeof ret === "string" ) {
return ret.replace( rreturn, "" );
}
// Handle cases where value is null/undef or number
return ret == null ? "" : ret;
}
return;
}
valueIsFunction = isFunction( value );
return this.each( function( i ) {
var val;
if ( this.nodeType !== 1 ) {
return;
}
if ( valueIsFunction ) {
val = value.call( this, i, jQuery( this ).val() );
} else {
val = value;
}
// Treat null/undefined as ""; convert numbers to string
if ( val == null ) {
val = "";
} else if ( typeof val === "number" ) {
val += "";
} else if ( Array.isArray( val ) ) {
val = jQuery.map( val, function( value ) {
return value == null ? "" : value + "";
} );
}
hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];
// If set returns undefined, fall back to normal setting
if ( !hooks || !( "set" in hooks ) || hooks.set( this, val, "value" ) === undefined ) {
this.value = val;
}
} );
}
} );
jQuery.extend( {
valHooks: {
option: {
get: function( elem ) {
var val = jQuery.find.attr( elem, "value" );
return val != null ?
val :
// Support: IE <=10 - 11 only
// option.text throws exceptions (#14686, #14858)
// Strip and collapse whitespace
// https://html.spec.whatwg.org/#strip-and-collapse-whitespace
stripAndCollapse( jQuery.text( elem ) );
}
},
select: {
get: function( elem ) {
var value, option, i,
options = elem.options,
index = elem.selectedIndex,
one = elem.type === "select-one",
values = one ? null : [],
max = one ? index + 1 : options.length;
if ( index < 0 ) {
i = max;
} else {
i = one ? index : 0;
}
// Loop through all the selected options
for ( ; i < max; i++ ) {
option = options[ i ];
// Support: IE <=9 only
// IE8-9 doesn't update selected after form reset (#2551)
if ( ( option.selected || i === index ) &&
// Don't return options that are disabled or in a disabled optgroup
!option.disabled &&
( !option.parentNode.disabled ||
!nodeName( option.parentNode, "optgroup" ) ) ) {
// Get the specific value for the option
value = jQuery( option ).val();
// We don't need an array for one selects
if ( one ) {
return value;
}
// Multi-Selects return an array
values.push( value );
}
}
return values;
},
set: function( elem, value ) {
var optionSet, option,
options = elem.options,
values = jQuery.makeArray( value ),
i = options.length;
while ( i-- ) {
option = options[ i ];
/* eslint-disable no-cond-assign */
if ( option.selected =
jQuery.inArray( jQuery.valHooks.option.get( option ), values ) > -1
) {
optionSet = true;
}
/* eslint-enable no-cond-assign */
}
// Force browsers to behave consistently when non-matching value is set
if ( !optionSet ) {
elem.selectedIndex = -1;
}
return values;
}
}
}
} );
// Radios and checkboxes getter/setter
jQuery.each( [ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = {
set: function( elem, value ) {
if ( Array.isArray( value ) ) {
return ( elem.checked = jQuery.inArray( jQuery( elem ).val(), value ) > -1 );
}
}
};
if ( !support.checkOn ) {
jQuery.valHooks[ this ].get = function( elem ) {
return elem.getAttribute( "value" ) === null ? "on" : elem.value;
};
}
} );
// Return jQuery for attributes-only inclusion
support.focusin = "onfocusin" in window;
var rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
stopPropagationCallback = function( e ) {
e.stopPropagation();
};
jQuery.extend( jQuery.event, {
trigger: function( event, data, elem, onlyHandlers ) {
var i, cur, tmp, bubbleType, ontype, handle, special, lastElement,
eventPath = [ elem || document ],
type = hasOwn.call( event, "type" ) ? event.type : event,
namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split( "." ) : [];
cur = lastElement = tmp = elem = elem || document;
// Don't do events on text and comment nodes
if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
return;
}
// focus/blur morphs to focusin/out; ensure we're not firing them right now
if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
return;
}
if ( type.indexOf( "." ) > -1 ) {
// Namespaced trigger; create a regexp to match event type in handle()
namespaces = type.split( "." );
type = namespaces.shift();
namespaces.sort();
}
ontype = type.indexOf( ":" ) < 0 && "on" + type;
// Caller can pass in a jQuery.Event object, Object, or just an event type string
event = event[ jQuery.expando ] ?
event :
new jQuery.Event( type, typeof event === "object" && event );
// Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true)
event.isTrigger = onlyHandlers ? 2 : 3;
event.namespace = namespaces.join( "." );
event.rnamespace = event.namespace ?
new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ) :
null;
// Clean up the event in case it is being reused
event.result = undefined;
if ( !event.target ) {
event.target = elem;
}
// Clone any incoming data and prepend the event, creating the handler arg list
data = data == null ?
[ event ] :
jQuery.makeArray( data, [ event ] );
// Allow special events to draw outside the lines
special = jQuery.event.special[ type ] || {};
if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) {
return;
}
// Determine event propagation path in advance, per W3C events spec (#9951)
// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
if ( !onlyHandlers && !special.noBubble && !isWindow( elem ) ) {
bubbleType = special.delegateType || type;
if ( !rfocusMorph.test( bubbleType + type ) ) {
cur = cur.parentNode;
}
for ( ; cur; cur = cur.parentNode ) {
eventPath.push( cur );
tmp = cur;
}
// Only add window if we got to document (e.g., not plain obj or detached DOM)
if ( tmp === ( elem.ownerDocument || document ) ) {
eventPath.push( tmp.defaultView || tmp.parentWindow || window );
}
}
// Fire handlers on the event path
i = 0;
while ( ( cur = eventPath[ i++ ] ) && !event.isPropagationStopped() ) {
lastElement = cur;
event.type = i > 1 ?
bubbleType :
special.bindType || type;
// jQuery handler
handle = ( dataPriv.get( cur, "events" ) || {} )[ event.type ] &&
dataPriv.get( cur, "handle" );
if ( handle ) {
handle.apply( cur, data );
}
// Native handler
handle = ontype && cur[ ontype ];
if ( handle && handle.apply && acceptData( cur ) ) {
event.result = handle.apply( cur, data );
if ( event.result === false ) {
event.preventDefault();
}
}
}
event.type = type;
// If nobody prevented the default action, do it now
if ( !onlyHandlers && !event.isDefaultPrevented() ) {
if ( ( !special._default ||
special._default.apply( eventPath.pop(), data ) === false ) &&
acceptData( elem ) ) {
// Call a native DOM method on the target with the same name as the event.
// Don't do default actions on window, that's where global variables be (#6170)
if ( ontype && isFunction( elem[ type ] ) && !isWindow( elem ) ) {
// Don't re-trigger an onFOO event when we call its FOO() method
tmp = elem[ ontype ];
if ( tmp ) {
elem[ ontype ] = null;
}
// Prevent re-triggering of the same event, since we already bubbled it above
jQuery.event.triggered = type;
if ( event.isPropagationStopped() ) {
lastElement.addEventListener( type, stopPropagationCallback );
}
elem[ type ]();
if ( event.isPropagationStopped() ) {
lastElement.removeEventListener( type, stopPropagationCallback );
}
jQuery.event.triggered = undefined;
if ( tmp ) {
elem[ ontype ] = tmp;
}
}
}
}
return event.result;
},
// Piggyback on a donor event to simulate a different one
// Used only for `focus(in | out)` events
simulate: function( type, elem, event ) {
var e = jQuery.extend(
new jQuery.Event(),
event,
{
type: type,
isSimulated: true
}
);
jQuery.event.trigger( e, null, elem );
}
} );
jQuery.fn.extend( {
trigger: function( type, data ) {
return this.each( function() {
jQuery.event.trigger( type, data, this );
} );
},
triggerHandler: function( type, data ) {
var elem = this[ 0 ];
if ( elem ) {
return jQuery.event.trigger( type, data, elem, true );
}
}
} );
// Support: Firefox <=44
// Firefox doesn't have focus(in | out) events
// Related ticket - https://bugzilla.mozilla.org/show_bug.cgi?id=687787
//
// Support: Chrome <=48 - 49, Safari <=9.0 - 9.1
// focus(in | out) events fire after focus & blur events,
// which is spec violation - http://www.w3.org/TR/DOM-Level-3-Events/#events-focusevent-event-order
// Related ticket - https://bugs.chromium.org/p/chromium/issues/detail?id=449857
if ( !support.focusin ) {
jQuery.each( { focus: "focusin", blur: "focusout" }, function( orig, fix ) {
// Attach a single capturing handler on the document while someone wants focusin/focusout
var handler = function( event ) {
jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ) );
};
jQuery.event.special[ fix ] = {
setup: function() {
var doc = this.ownerDocument || this,
attaches = dataPriv.access( doc, fix );
if ( !attaches ) {
doc.addEventListener( orig, handler, true );
}
dataPriv.access( doc, fix, ( attaches || 0 ) + 1 );
},
teardown: function() {
var doc = this.ownerDocument || this,
attaches = dataPriv.access( doc, fix ) - 1;
if ( !attaches ) {
doc.removeEventListener( orig, handler, true );
dataPriv.remove( doc, fix );
} else {
dataPriv.access( doc, fix, attaches );
}
}
};
} );
}
var location = window.location;
var nonce = Date.now();
var rquery = ( /\?/ );
// Cross-browser xml parsing
jQuery.parseXML = function( data ) {
var xml;
if ( !data || typeof data !== "string" ) {
return null;
}
// Support: IE 9 - 11 only
// IE throws on parseFromString with invalid input.
try {
xml = ( new window.DOMParser() ).parseFromString( data, "text/xml" );
} catch ( e ) {
xml = undefined;
}
if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
};
var
rbracket = /\[\]$/,
rCRLF = /\r?\n/g,
rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
rsubmittable = /^(?:input|select|textarea|keygen)/i;
function buildParams( prefix, obj, traditional, add ) {
var name;
if ( Array.isArray( obj ) ) {
// Serialize array item.
jQuery.each( obj, function( i, v ) {
if ( traditional || rbracket.test( prefix ) ) {
// Treat each array item as a scalar.
add( prefix, v );
} else {
// Item is non-scalar (array or object), encode its numeric index.
buildParams(
prefix + "[" + ( typeof v === "object" && v != null ? i : "" ) + "]",
v,
traditional,
add
);
}
} );
} else if ( !traditional && toType( obj ) === "object" ) {
// Serialize object item.
for ( name in obj ) {
buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
}
} else {
// Serialize scalar item.
add( prefix, obj );
}
}
// Serialize an array of form elements or a set of
// key/values into a query string
jQuery.param = function( a, traditional ) {
var prefix,
s = [],
add = function( key, valueOrFunction ) {
// If value is a function, invoke it and use its return value
var value = isFunction( valueOrFunction ) ?
valueOrFunction() :
valueOrFunction;
s[ s.length ] = encodeURIComponent( key ) + "=" +
encodeURIComponent( value == null ? "" : value );
};
// If an array was passed in, assume that it is an array of form elements.
if ( Array.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
// Serialize the form elements
jQuery.each( a, function() {
add( this.name, this.value );
} );
} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for ( prefix in a ) {
buildParams( prefix, a[ prefix ], traditional, add );
}
}
// Return the resulting serialization
return s.join( "&" );
};
jQuery.fn.extend( {
serialize: function() {
return jQuery.param( this.serializeArray() );
},
serializeArray: function() {
return this.map( function() {
// Can add propHook for "elements" to filter or add form elements
var elements = jQuery.prop( this, "elements" );
return elements ? jQuery.makeArray( elements ) : this;
} )
.filter( function() {
var type = this.type;
// Use .is( ":disabled" ) so that fieldset[disabled] works
return this.name && !jQuery( this ).is( ":disabled" ) &&
rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) &&
( this.checked || !rcheckableType.test( type ) );
} )
.map( function( i, elem ) {
var val = jQuery( this ).val();
if ( val == null ) {
return null;
}
if ( Array.isArray( val ) ) {
return jQuery.map( val, function( val ) {
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
} );
}
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
} ).get();
}
} );
var
r20 = /%20/g,
rhash = /#.*$/,
rantiCache = /([?&])_=[^&]*/,
rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg,
// #7653, #8125, #8152: local protocol detection
rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/,
rnoContent = /^(?:GET|HEAD)$/,
rprotocol = /^\/\//,
/* Prefilters
* 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
* 2) These are called:
* - BEFORE asking for a transport
* - AFTER param serialization (s.data is a string if s.processData is true)
* 3) key is the dataType
* 4) the catchall symbol "*" can be used
* 5) execution will start with transport dataType and THEN continue down to "*" if needed
*/
prefilters = {},
/* Transports bindings
* 1) key is the dataType
* 2) the catchall symbol "*" can be used
* 3) selection will start with transport dataType and THEN go to "*" if needed
*/
transports = {},
// Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
allTypes = "*/".concat( "*" ),
// Anchor tag for parsing the document origin
originAnchor = document.createElement( "a" );
originAnchor.href = location.href;
// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
function addToPrefiltersOrTransports( structure ) {
// dataTypeExpression is optional and defaults to "*"
return function( dataTypeExpression, func ) {
if ( typeof dataTypeExpression !== "string" ) {
func = dataTypeExpression;
dataTypeExpression = "*";
}
var dataType,
i = 0,
dataTypes = dataTypeExpression.toLowerCase().match( rnothtmlwhite ) || [];
if ( isFunction( func ) ) {
// For each dataType in the dataTypeExpression
while ( ( dataType = dataTypes[ i++ ] ) ) {
// Prepend if requested
if ( dataType[ 0 ] === "+" ) {
dataType = dataType.slice( 1 ) || "*";
( structure[ dataType ] = structure[ dataType ] || [] ).unshift( func );
// Otherwise append
} else {
( structure[ dataType ] = structure[ dataType ] || [] ).push( func );
}
}
}
};
}
// Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) {
var inspected = {},
seekingTransport = ( structure === transports );
function inspect( dataType ) {
var selected;
inspected[ dataType ] = true;
jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) {
var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR );
if ( typeof dataTypeOrTransport === "string" &&
!seekingTransport && !inspected[ dataTypeOrTransport ] ) {
options.dataTypes.unshift( dataTypeOrTransport );
inspect( dataTypeOrTransport );
return false;
} else if ( seekingTransport ) {
return !( selected = dataTypeOrTransport );
}
} );
return selected;
}
return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" );
}
// A special extend for ajax options
// that takes "flat" options (not to be deep extended)
// Fixes #9887
function ajaxExtend( target, src ) {
var key, deep,
flatOptions = jQuery.ajaxSettings.flatOptions || {};
for ( key in src ) {
if ( src[ key ] !== undefined ) {
( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ];
}
}
if ( deep ) {
jQuery.extend( true, target, deep );
}
return target;
}
/* Handles responses to an ajax request:
* - finds the right dataType (mediates between content-type and expected dataType)
* - returns the corresponding response
*/
function ajaxHandleResponses( s, jqXHR, responses ) {
var ct, type, finalDataType, firstDataType,
contents = s.contents,
dataTypes = s.dataTypes;
// Remove auto dataType and get content-type in the process
while ( dataTypes[ 0 ] === "*" ) {
dataTypes.shift();
if ( ct === undefined ) {
ct = s.mimeType || jqXHR.getResponseHeader( "Content-Type" );
}
}
// Check if we're dealing with a known content-type
if ( ct ) {
for ( type in contents ) {
if ( contents[ type ] && contents[ type ].test( ct ) ) {
dataTypes.unshift( type );
break;
}
}
}
// Check to see if we have a response for the expected dataType
if ( dataTypes[ 0 ] in responses ) {
finalDataType = dataTypes[ 0 ];
} else {
// Try convertible dataTypes
for ( type in responses ) {
if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[ 0 ] ] ) {
finalDataType = type;
break;
}
if ( !firstDataType ) {
firstDataType = type;
}
}
// Or just use first one
finalDataType = finalDataType || firstDataType;
}
// If we found a dataType
// We add the dataType to the list if needed
// and return the corresponding response
if ( finalDataType ) {
if ( finalDataType !== dataTypes[ 0 ] ) {
dataTypes.unshift( finalDataType );
}
return responses[ finalDataType ];
}
}
/* Chain conversions given the request and the original response
* Also sets the responseXXX fields on the jqXHR instance
*/
function ajaxConvert( s, response, jqXHR, isSuccess ) {
var conv2, current, conv, tmp, prev,
converters = {},
// Work with a copy of dataTypes in case we need to modify it for conversion
dataTypes = s.dataTypes.slice();
// Create converters map with lowercased keys
if ( dataTypes[ 1 ] ) {
for ( conv in s.converters ) {
converters[ conv.toLowerCase() ] = s.converters[ conv ];
}
}
current = dataTypes.shift();
// Convert to each sequential dataType
while ( current ) {
if ( s.responseFields[ current ] ) {
jqXHR[ s.responseFields[ current ] ] = response;
}
// Apply the dataFilter if provided
if ( !prev && isSuccess && s.dataFilter ) {
response = s.dataFilter( response, s.dataType );
}
prev = current;
current = dataTypes.shift();
if ( current ) {
// There's only work to do if current dataType is non-auto
if ( current === "*" ) {
current = prev;
// Convert response if prev dataType is non-auto and differs from current
} else if ( prev !== "*" && prev !== current ) {
// Seek a direct converter
conv = converters[ prev + " " + current ] || converters[ "* " + current ];
// If none found, seek a pair
if ( !conv ) {
for ( conv2 in converters ) {
// If conv2 outputs current
tmp = conv2.split( " " );
if ( tmp[ 1 ] === current ) {
// If prev can be converted to accepted input
conv = converters[ prev + " " + tmp[ 0 ] ] ||
converters[ "* " + tmp[ 0 ] ];
if ( conv ) {
// Condense equivalence converters
if ( conv === true ) {
conv = converters[ conv2 ];
// Otherwise, insert the intermediate dataType
} else if ( converters[ conv2 ] !== true ) {
current = tmp[ 0 ];
dataTypes.unshift( tmp[ 1 ] );
}
break;
}
}
}
}
// Apply converter (if not an equivalence)
if ( conv !== true ) {
// Unless errors are allowed to bubble, catch and return them
if ( conv && s.throws ) {
response = conv( response );
} else {
try {
response = conv( response );
} catch ( e ) {
return {
state: "parsererror",
error: conv ? e : "No conversion from " + prev + " to " + current
};
}
}
}
}
}
}
return { state: "success", data: response };
}
jQuery.extend( {
// Counter for holding the number of active queries
active: 0,
// Last-Modified header cache for next request
lastModified: {},
etag: {},
ajaxSettings: {
url: location.href,
type: "GET",
isLocal: rlocalProtocol.test( location.protocol ),
global: true,
processData: true,
async: true,
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
/*
timeout: 0,
data: null,
dataType: null,
username: null,
password: null,
cache: null,
throws: false,
traditional: false,
headers: {},
*/
accepts: {
"*": allTypes,
text: "text/plain",
html: "text/html",
xml: "application/xml, text/xml",
json: "application/json, text/javascript"
},
contents: {
xml: /\bxml\b/,
html: /\bhtml/,
json: /\bjson\b/
},
responseFields: {
xml: "responseXML",
text: "responseText",
json: "responseJSON"
},
// Data converters
// Keys separate source (or catchall "*") and destination types with a single space
converters: {
// Convert anything to text
"* text": String,
// Text to html (true = no transformation)
"text html": true,
// Evaluate text as a json expression
"text json": JSON.parse,
// Parse text as xml
"text xml": jQuery.parseXML
},
// For options that shouldn't be deep extended:
// you can add your own custom options here if
// and when you create one that shouldn't be
// deep extended (see ajaxExtend)
flatOptions: {
url: true,
context: true
}
},
// Creates a full fledged settings object into target
// with both ajaxSettings and settings fields.
// If target is omitted, writes into ajaxSettings.
ajaxSetup: function( target, settings ) {
return settings ?
// Building a settings object
ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) :
// Extending ajaxSettings
ajaxExtend( jQuery.ajaxSettings, target );
},
ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
ajaxTransport: addToPrefiltersOrTransports( transports ),
// Main method
ajax: function( url, options ) {
// If url is an object, simulate pre-1.5 signature
if ( typeof url === "object" ) {
options = url;
url = undefined;
}
// Force options to be an object
options = options || {};
var transport,
// URL without anti-cache param
cacheURL,
// Response headers
responseHeadersString,
responseHeaders,
// timeout handle
timeoutTimer,
// Url cleanup var
urlAnchor,
// Request state (becomes false upon send and true upon completion)
completed,
// To know if global events are to be dispatched
fireGlobals,
// Loop variable
i,
// uncached part of the url
uncached,
// Create the final options object
s = jQuery.ajaxSetup( {}, options ),
// Callbacks context
callbackContext = s.context || s,
// Context for global events is callbackContext if it is a DOM node or jQuery collection
globalEventContext = s.context &&
( callbackContext.nodeType || callbackContext.jquery ) ?
jQuery( callbackContext ) :
jQuery.event,
// Deferreds
deferred = jQuery.Deferred(),
completeDeferred = jQuery.Callbacks( "once memory" ),
// Status-dependent callbacks
statusCode = s.statusCode || {},
// Headers (they are sent all at once)
requestHeaders = {},
requestHeadersNames = {},
// Default abort message
strAbort = "canceled",
// Fake xhr
jqXHR = {
readyState: 0,
// Builds headers hashtable if needed
getResponseHeader: function( key ) {
var match;
if ( completed ) {
if ( !responseHeaders ) {
responseHeaders = {};
while ( ( match = rheaders.exec( responseHeadersString ) ) ) {
responseHeaders[ match[ 1 ].toLowerCase() ] = match[ 2 ];
}
}
match = responseHeaders[ key.toLowerCase() ];
}
return match == null ? null : match;
},
// Raw string
getAllResponseHeaders: function() {
return completed ? responseHeadersString : null;
},
// Caches the header
setRequestHeader: function( name, value ) {
if ( completed == null ) {
name = requestHeadersNames[ name.toLowerCase() ] =
requestHeadersNames[ name.toLowerCase() ] || name;
requestHeaders[ name ] = value;
}
return this;
},
// Overrides response content-type header
overrideMimeType: function( type ) {
if ( completed == null ) {
s.mimeType = type;
}
return this;
},
// Status-dependent callbacks
statusCode: function( map ) {
var code;
if ( map ) {
if ( completed ) {
// Execute the appropriate callbacks
jqXHR.always( map[ jqXHR.status ] );
} else {
// Lazy-add the new callbacks in a way that preserves old ones
for ( code in map ) {
statusCode[ code ] = [ statusCode[ code ], map[ code ] ];
}
}
}
return this;
},
// Cancel the request
abort: function( statusText ) {
var finalText = statusText || strAbort;
if ( transport ) {
transport.abort( finalText );
}
done( 0, finalText );
return this;
}
};
// Attach deferreds
deferred.promise( jqXHR );
// Add protocol if not provided (prefilters might expect it)
// Handle falsy url in the settings object (#10093: consistency with old signature)
// We also use the url parameter if available
s.url = ( ( url || s.url || location.href ) + "" )
.replace( rprotocol, location.protocol + "//" );
// Alias method option to type as per ticket #12004
s.type = options.method || options.type || s.method || s.type;
// Extract dataTypes list
s.dataTypes = ( s.dataType || "*" ).toLowerCase().match( rnothtmlwhite ) || [ "" ];
// A cross-domain request is in order when the origin doesn't match the current origin.
if ( s.crossDomain == null ) {
urlAnchor = document.createElement( "a" );
// Support: IE <=8 - 11, Edge 12 - 15
// IE throws exception on accessing the href property if url is malformed,
// e.g. http://example.com:80x/
try {
urlAnchor.href = s.url;
// Support: IE <=8 - 11 only
// Anchor's host property isn't correctly set when s.url is relative
urlAnchor.href = urlAnchor.href;
s.crossDomain = originAnchor.protocol + "//" + originAnchor.host !==
urlAnchor.protocol + "//" + urlAnchor.host;
} catch ( e ) {
// If there is an error parsing the URL, assume it is crossDomain,
// it can be rejected by the transport if it is invalid
s.crossDomain = true;
}
}
// Convert data if not already a string
if ( s.data && s.processData && typeof s.data !== "string" ) {
s.data = jQuery.param( s.data, s.traditional );
}
// Apply prefilters
inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
// If request was aborted inside a prefilter, stop there
if ( completed ) {
return jqXHR;
}
// We can fire global events as of now if asked to
// Don't fire events if jQuery.event is undefined in an AMD-usage scenario (#15118)
fireGlobals = jQuery.event && s.global;
// Watch for a new set of requests
if ( fireGlobals && jQuery.active++ === 0 ) {
jQuery.event.trigger( "ajaxStart" );
}
// Uppercase the type
s.type = s.type.toUpperCase();
// Determine if request has content
s.hasContent = !rnoContent.test( s.type );
// Save the URL in case we're toying with the If-Modified-Since
// and/or If-None-Match header later on
// Remove hash to simplify url manipulation
cacheURL = s.url.replace( rhash, "" );
// More options handling for requests with no content
if ( !s.hasContent ) {
// Remember the hash so we can put it back
uncached = s.url.slice( cacheURL.length );
// If data is available and should be processed, append data to url
if ( s.data && ( s.processData || typeof s.data === "string" ) ) {
cacheURL += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data;
// #9682: remove data so that it's not used in an eventual retry
delete s.data;
}
// Add or update anti-cache param if needed
if ( s.cache === false ) {
cacheURL = cacheURL.replace( rantiCache, "$1" );
uncached = ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ( nonce++ ) + uncached;
}
// Put hash and anti-cache on the URL that will be requested (gh-1732)
s.url = cacheURL + uncached;
// Change '%20' to '+' if this is encoded form body content (gh-2658)
} else if ( s.data && s.processData &&
( s.contentType || "" ).indexOf( "application/x-www-form-urlencoded" ) === 0 ) {
s.data = s.data.replace( r20, "+" );
}
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
if ( jQuery.lastModified[ cacheURL ] ) {
jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] );
}
if ( jQuery.etag[ cacheURL ] ) {
jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] );
}
}
// Set the correct header, if data is being sent
if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
jqXHR.setRequestHeader( "Content-Type", s.contentType );
}
// Set the Accepts header for the server, depending on the dataType
jqXHR.setRequestHeader(
"Accept",
s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[ 0 ] ] ?
s.accepts[ s.dataTypes[ 0 ] ] +
( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
s.accepts[ "*" ]
);
// Check for headers option
for ( i in s.headers ) {
jqXHR.setRequestHeader( i, s.headers[ i ] );
}
// Allow custom headers/mimetypes and early abort
if ( s.beforeSend &&
( s.beforeSend.call( callbackContext, jqXHR, s ) === false || completed ) ) {
// Abort if not done already and return
return jqXHR.abort();
}
// Aborting is no longer a cancellation
strAbort = "abort";
// Install callbacks on deferreds
completeDeferred.add( s.complete );
jqXHR.done( s.success );
jqXHR.fail( s.error );
// Get transport
transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
// If no transport, we auto-abort
if ( !transport ) {
done( -1, "No Transport" );
} else {
jqXHR.readyState = 1;
// Send global event
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
}
// If request was aborted inside ajaxSend, stop there
if ( completed ) {
return jqXHR;
}
// Timeout
if ( s.async && s.timeout > 0 ) {
timeoutTimer = window.setTimeout( function() {
jqXHR.abort( "timeout" );
}, s.timeout );
}
try {
completed = false;
transport.send( requestHeaders, done );
} catch ( e ) {
// Rethrow post-completion exceptions
if ( completed ) {
throw e;
}
// Propagate others as results
done( -1, e );
}
}
// Callback for when everything is done
function done( status, nativeStatusText, responses, headers ) {
var isSuccess, success, error, response, modified,
statusText = nativeStatusText;
// Ignore repeat invocations
if ( completed ) {
return;
}
completed = true;
// Clear timeout if it exists
if ( timeoutTimer ) {
window.clearTimeout( timeoutTimer );
}
// Dereference transport for early garbage collection
// (no matter how long the jqXHR object will be used)
transport = undefined;
// Cache response headers
responseHeadersString = headers || "";
// Set readyState
jqXHR.readyState = status > 0 ? 4 : 0;
// Determine if successful
isSuccess = status >= 200 && status < 300 || status === 304;
// Get response data
if ( responses ) {
response = ajaxHandleResponses( s, jqXHR, responses );
}
// Convert no matter what (that way responseXXX fields are always set)
response = ajaxConvert( s, response, jqXHR, isSuccess );
// If successful, handle type chaining
if ( isSuccess ) {
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
modified = jqXHR.getResponseHeader( "Last-Modified" );
if ( modified ) {
jQuery.lastModified[ cacheURL ] = modified;
}
modified = jqXHR.getResponseHeader( "etag" );
if ( modified ) {
jQuery.etag[ cacheURL ] = modified;
}
}
// if no content
if ( status === 204 || s.type === "HEAD" ) {
statusText = "nocontent";
// if not modified
} else if ( status === 304 ) {
statusText = "notmodified";
// If we have data, let's convert it
} else {
statusText = response.state;
success = response.data;
error = response.error;
isSuccess = !error;
}
} else {
// Extract error from statusText and normalize for non-aborts
error = statusText;
if ( status || !statusText ) {
statusText = "error";
if ( status < 0 ) {
status = 0;
}
}
}
// Set data for the fake xhr object
jqXHR.status = status;
jqXHR.statusText = ( nativeStatusText || statusText ) + "";
// Success/Error
if ( isSuccess ) {
deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
} else {
deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
}
// Status-dependent callbacks
jqXHR.statusCode( statusCode );
statusCode = undefined;
if ( fireGlobals ) {
globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError",
[ jqXHR, s, isSuccess ? success : error ] );
}
// Complete
completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
// Handle the global AJAX counter
if ( !( --jQuery.active ) ) {
jQuery.event.trigger( "ajaxStop" );
}
}
}
return jqXHR;
},
getJSON: function( url, data, callback ) {
return jQuery.get( url, data, callback, "json" );
},
getScript: function( url, callback ) {
return jQuery.get( url, undefined, callback, "script" );
}
} );
jQuery.each( [ "get", "post" ], function( i, method ) {
jQuery[ method ] = function( url, data, callback, type ) {
// Shift arguments if data argument was omitted
if ( isFunction( data ) ) {
type = type || callback;
callback = data;
data = undefined;
}
// The url can be an options object (which then must have .url)
return jQuery.ajax( jQuery.extend( {
url: url,
type: method,
dataType: type,
data: data,
success: callback
}, jQuery.isPlainObject( url ) && url ) );
};
} );
jQuery._evalUrl = function( url ) {
return jQuery.ajax( {
url: url,
// Make this explicit, since user can override this through ajaxSetup (#11264)
type: "GET",
dataType: "script",
cache: true,
async: false,
global: false,
"throws": true
} );
};
jQuery.fn.extend( {
wrapAll: function( html ) {
var wrap;
if ( this[ 0 ] ) {
if ( isFunction( html ) ) {
html = html.call( this[ 0 ] );
}
// The elements to wrap the target around
wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true );
if ( this[ 0 ].parentNode ) {
wrap.insertBefore( this[ 0 ] );
}
wrap.map( function() {
var elem = this;
while ( elem.firstElementChild ) {
elem = elem.firstElementChild;
}
return elem;
} ).append( this );
}
return this;
},
wrapInner: function( html ) {
if ( isFunction( html ) ) {
return this.each( function( i ) {
jQuery( this ).wrapInner( html.call( this, i ) );
} );
}
return this.each( function() {
var self = jQuery( this ),
contents = self.contents();
if ( contents.length ) {
contents.wrapAll( html );
} else {
self.append( html );
}
} );
},
wrap: function( html ) {
var htmlIsFunction = isFunction( html );
return this.each( function( i ) {
jQuery( this ).wrapAll( htmlIsFunction ? html.call( this, i ) : html );
} );
},
unwrap: function( selector ) {
this.parent( selector ).not( "body" ).each( function() {
jQuery( this ).replaceWith( this.childNodes );
} );
return this;
}
} );
jQuery.expr.pseudos.hidden = function( elem ) {
return !jQuery.expr.pseudos.visible( elem );
};
jQuery.expr.pseudos.visible = function( elem ) {
return !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length );
};
jQuery.ajaxSettings.xhr = function() {
try {
return new window.XMLHttpRequest();
} catch ( e ) {}
};
var xhrSuccessStatus = {
// File protocol always yields status code 0, assume 200
0: 200,
// Support: IE <=9 only
// #1450: sometimes IE returns 1223 when it should be 204
1223: 204
},
xhrSupported = jQuery.ajaxSettings.xhr();
support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
support.ajax = xhrSupported = !!xhrSupported;
jQuery.ajaxTransport( function( options ) {
var callback, errorCallback;
// Cross domain only allowed if supported through XMLHttpRequest
if ( support.cors || xhrSupported && !options.crossDomain ) {
return {
send: function( headers, complete ) {
var i,
xhr = options.xhr();
xhr.open(
options.type,
options.url,
options.async,
options.username,
options.password
);
// Apply custom fields if provided
if ( options.xhrFields ) {
for ( i in options.xhrFields ) {
xhr[ i ] = options.xhrFields[ i ];
}
}
// Override mime type if needed
if ( options.mimeType && xhr.overrideMimeType ) {
xhr.overrideMimeType( options.mimeType );
}
// X-Requested-With header
// For cross-domain requests, seeing as conditions for a preflight are
// akin to a jigsaw puzzle, we simply never set it to be sure.
// (it can always be set on a per-request basis or even using ajaxSetup)
// For same-domain requests, won't change header if already provided.
if ( !options.crossDomain && !headers[ "X-Requested-With" ] ) {
headers[ "X-Requested-With" ] = "XMLHttpRequest";
}
// Set headers
for ( i in headers ) {
xhr.setRequestHeader( i, headers[ i ] );
}
// Callback
callback = function( type ) {
return function() {
if ( callback ) {
callback = errorCallback = xhr.onload =
xhr.onerror = xhr.onabort = xhr.ontimeout =
xhr.onreadystatechange = null;
if ( type === "abort" ) {
xhr.abort();
} else if ( type === "error" ) {
// Support: IE <=9 only
// On a manual native abort, IE9 throws
// errors on any property access that is not readyState
if ( typeof xhr.status !== "number" ) {
complete( 0, "error" );
} else {
complete(
// File: protocol always yields status 0; see #8605, #14207
xhr.status,
xhr.statusText
);
}
} else {
complete(
xhrSuccessStatus[ xhr.status ] || xhr.status,
xhr.statusText,
// Support: IE <=9 only
// IE9 has no XHR2 but throws on binary (trac-11426)
// For XHR2 non-text, let the caller handle it (gh-2498)
( xhr.responseType || "text" ) !== "text" ||
typeof xhr.responseText !== "string" ?
{ binary: xhr.response } :
{ text: xhr.responseText },
xhr.getAllResponseHeaders()
);
}
}
};
};
// Listen to events
xhr.onload = callback();
errorCallback = xhr.onerror = xhr.ontimeout = callback( "error" );
// Support: IE 9 only
// Use onreadystatechange to replace onabort
// to handle uncaught aborts
if ( xhr.onabort !== undefined ) {
xhr.onabort = errorCallback;
} else {
xhr.onreadystatechange = function() {
// Check readyState before timeout as it changes
if ( xhr.readyState === 4 ) {
// Allow onerror to be called first,
// but that will not handle a native abort
// Also, save errorCallback to a variable
// as xhr.onerror cannot be accessed
window.setTimeout( function() {
if ( callback ) {
errorCallback();
}
} );
}
};
}
// Create the abort callback
callback = callback( "abort" );
try {
// Do send the request (this may raise an exception)
xhr.send( options.hasContent && options.data || null );
} catch ( e ) {
// #14683: Only rethrow if this hasn't been notified as an error yet
if ( callback ) {
throw e;
}
}
},
abort: function() {
if ( callback ) {
callback();
}
}
};
}
} );
// Prevent auto-execution of scripts when no explicit dataType was provided (See gh-2432)
jQuery.ajaxPrefilter( function( s ) {
if ( s.crossDomain ) {
s.contents.script = false;
}
} );
// Install script dataType
jQuery.ajaxSetup( {
accepts: {
script: "text/javascript, application/javascript, " +
"application/ecmascript, application/x-ecmascript"
},
contents: {
script: /\b(?:java|ecma)script\b/
},
converters: {
"text script": function( text ) {
jQuery.globalEval( text );
return text;
}
}
} );
// Handle cache's special case and crossDomain
jQuery.ajaxPrefilter( "script", function( s ) {
if ( s.cache === undefined ) {
s.cache = false;
}
if ( s.crossDomain ) {
s.type = "GET";
}
} );
// Bind script tag hack transport
jQuery.ajaxTransport( "script", function( s ) {
// This transport only deals with cross domain requests
if ( s.crossDomain ) {
var script, callback;
return {
send: function( _, complete ) {
script = jQuery( "<script>" ).prop( {
charset: s.scriptCharset,
src: s.url
} ).on(
"load error",
callback = function( evt ) {
script.remove();
callback = null;
if ( evt ) {
complete( evt.type === "error" ? 404 : 200, evt.type );
}
}
);
// Use native DOM manipulation to avoid our domManip AJAX trickery
document.head.appendChild( script[ 0 ] );
},
abort: function() {
if ( callback ) {
callback();
}
}
};
}
} );
var oldCallbacks = [],
rjsonp = /(=)\?(?=&|$)|\?\?/;
// Default jsonp settings
jQuery.ajaxSetup( {
jsonp: "callback",
jsonpCallback: function() {
var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) );
this[ callback ] = true;
return callback;
}
} );
// Detect, normalize options and install callbacks for jsonp requests
jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
var callbackName, overwritten, responseContainer,
jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ?
"url" :
typeof s.data === "string" &&
( s.contentType || "" )
.indexOf( "application/x-www-form-urlencoded" ) === 0 &&
rjsonp.test( s.data ) && "data"
);
// Handle iff the expected data type is "jsonp" or we have a parameter to set
if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) {
// Get callback name, remembering preexisting value associated with it
callbackName = s.jsonpCallback = isFunction( s.jsonpCallback ) ?
s.jsonpCallback() :
s.jsonpCallback;
// Insert callback into url or form data
if ( jsonProp ) {
s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName );
} else if ( s.jsonp !== false ) {
s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName;
}
// Use data converter to retrieve json after script execution
s.converters[ "script json" ] = function() {
if ( !responseContainer ) {
jQuery.error( callbackName + " was not called" );
}
return responseContainer[ 0 ];
};
// Force json dataType
s.dataTypes[ 0 ] = "json";
// Install callback
overwritten = window[ callbackName ];
window[ callbackName ] = function() {
responseContainer = arguments;
};
// Clean-up function (fires after converters)
jqXHR.always( function() {
// If previous value didn't exist - remove it
if ( overwritten === undefined ) {
jQuery( window ).removeProp( callbackName );
// Otherwise restore preexisting value
} else {
window[ callbackName ] = overwritten;
}
// Save back as free
if ( s[ callbackName ] ) {
// Make sure that re-using the options doesn't screw things around
s.jsonpCallback = originalSettings.jsonpCallback;
// Save the callback name for future use
oldCallbacks.push( callbackName );
}
// Call if it was a function and we have a response
if ( responseContainer && isFunction( overwritten ) ) {
overwritten( responseContainer[ 0 ] );
}
responseContainer = overwritten = undefined;
} );
// Delegate to script
return "script";
}
} );
// Support: Safari 8 only
// In Safari 8 documents created via document.implementation.createHTMLDocument
// collapse sibling forms: the second one becomes a child of the first one.
// Because of that, this security measure has to be disabled in Safari 8.
// https://bugs.webkit.org/show_bug.cgi?id=137337
support.createHTMLDocument = ( function() {
var body = document.implementation.createHTMLDocument( "" ).body;
body.innerHTML = "<form></form><form></form>";
return body.childNodes.length === 2;
} )();
// Argument "data" should be string of html
// context (optional): If specified, the fragment will be created in this context,
// defaults to document
// keepScripts (optional): If true, will include scripts passed in the html string
jQuery.parseHTML = function( data, context, keepScripts ) {
if ( typeof data !== "string" ) {
return [];
}
if ( typeof context === "boolean" ) {
keepScripts = context;
context = false;
}
var base, parsed, scripts;
if ( !context ) {
// Stop scripts or inline event handlers from being executed immediately
// by using document.implementation
if ( support.createHTMLDocument ) {
context = document.implementation.createHTMLDocument( "" );
// Set the base href for the created document
// so any parsed elements with URLs
// are based on the document's URL (gh-2965)
base = context.createElement( "base" );
base.href = document.location.href;
context.head.appendChild( base );
} else {
context = document;
}
}
parsed = rsingleTag.exec( data );
scripts = !keepScripts && [];
// Single tag
if ( parsed ) {
return [ context.createElement( parsed[ 1 ] ) ];
}
parsed = buildFragment( [ data ], context, scripts );
if ( scripts && scripts.length ) {
jQuery( scripts ).remove();
}
return jQuery.merge( [], parsed.childNodes );
};
/**
* Load a url into a page
*/
jQuery.fn.load = function( url, params, callback ) {
var selector, type, response,
self = this,
off = url.indexOf( " " );
if ( off > -1 ) {
selector = stripAndCollapse( url.slice( off ) );
url = url.slice( 0, off );
}
// If it's a function
if ( isFunction( params ) ) {
// We assume that it's the callback
callback = params;
params = undefined;
// Otherwise, build a param string
} else if ( params && typeof params === "object" ) {
type = "POST";
}
// If we have elements to modify, make the request
if ( self.length > 0 ) {
jQuery.ajax( {
url: url,
// If "type" variable is undefined, then "GET" method will be used.
// Make value of this field explicit since
// user can override it through ajaxSetup method
type: type || "GET",
dataType: "html",
data: params
} ).done( function( responseText ) {
// Save response for use in complete callback
response = arguments;
self.html( selector ?
// If a selector was specified, locate the right elements in a dummy div
// Exclude scripts to avoid IE 'Permission Denied' errors
jQuery( "<div>" ).append( jQuery.parseHTML( responseText ) ).find( selector ) :
// Otherwise use the full result
responseText );
// If the request succeeds, this function gets "data", "status", "jqXHR"
// but they are ignored because response was set above.
// If it fails, this function gets "jqXHR", "status", "error"
} ).always( callback && function( jqXHR, status ) {
self.each( function() {
callback.apply( this, response || [ jqXHR.responseText, status, jqXHR ] );
} );
} );
}
return this;
};
// Attach a bunch of functions for handling common AJAX events
jQuery.each( [
"ajaxStart",
"ajaxStop",
"ajaxComplete",
"ajaxError",
"ajaxSuccess",
"ajaxSend"
], function( i, type ) {
jQuery.fn[ type ] = function( fn ) {
return this.on( type, fn );
};
} );
jQuery.expr.pseudos.animated = function( elem ) {
return jQuery.grep( jQuery.timers, function( fn ) {
return elem === fn.elem;
} ).length;
};
jQuery.offset = {
setOffset: function( elem, options, i ) {
var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition,
position = jQuery.css( elem, "position" ),
curElem = jQuery( elem ),
props = {};
// Set position first, in-case top/left are set even on static elem
if ( position === "static" ) {
elem.style.position = "relative";
}
curOffset = curElem.offset();
curCSSTop = jQuery.css( elem, "top" );
curCSSLeft = jQuery.css( elem, "left" );
calculatePosition = ( position === "absolute" || position === "fixed" ) &&
( curCSSTop + curCSSLeft ).indexOf( "auto" ) > -1;
// Need to be able to calculate position if either
// top or left is auto and position is either absolute or fixed
if ( calculatePosition ) {
curPosition = curElem.position();
curTop = curPosition.top;
curLeft = curPosition.left;
} else {
curTop = parseFloat( curCSSTop ) || 0;
curLeft = parseFloat( curCSSLeft ) || 0;
}
if ( isFunction( options ) ) {
// Use jQuery.extend here to allow modification of coordinates argument (gh-1848)
options = options.call( elem, i, jQuery.extend( {}, curOffset ) );
}
if ( options.top != null ) {
props.top = ( options.top - curOffset.top ) + curTop;
}
if ( options.left != null ) {
props.left = ( options.left - curOffset.left ) + curLeft;
}
if ( "using" in options ) {
options.using.call( elem, props );
} else {
curElem.css( props );
}
}
};
jQuery.fn.extend( {
// offset() relates an element's border box to the document origin
offset: function( options ) {
// Preserve chaining for setter
if ( arguments.length ) {
return options === undefined ?
this :
this.each( function( i ) {
jQuery.offset.setOffset( this, options, i );
} );
}
var rect, win,
elem = this[ 0 ];
if ( !elem ) {
return;
}
// Return zeros for disconnected and hidden (display: none) elements (gh-2310)
// Support: IE <=11 only
// Running getBoundingClientRect on a
// disconnected node in IE throws an error
if ( !elem.getClientRects().length ) {
return { top: 0, left: 0 };
}
// Get document-relative position by adding viewport scroll to viewport-relative gBCR
rect = elem.getBoundingClientRect();
win = elem.ownerDocument.defaultView;
return {
top: rect.top + win.pageYOffset,
left: rect.left + win.pageXOffset
};
},
// position() relates an element's margin box to its offset parent's padding box
// This corresponds to the behavior of CSS absolute positioning
position: function() {
if ( !this[ 0 ] ) {
return;
}
var offsetParent, offset, doc,
elem = this[ 0 ],
parentOffset = { top: 0, left: 0 };
// position:fixed elements are offset from the viewport, which itself always has zero offset
if ( jQuery.css( elem, "position" ) === "fixed" ) {
// Assume position:fixed implies availability of getBoundingClientRect
offset = elem.getBoundingClientRect();
} else {
offset = this.offset();
// Account for the *real* offset parent, which can be the document or its root element
// when a statically positioned element is identified
doc = elem.ownerDocument;
offsetParent = elem.offsetParent || doc.documentElement;
while ( offsetParent &&
( offsetParent === doc.body || offsetParent === doc.documentElement ) &&
jQuery.css( offsetParent, "position" ) === "static" ) {
offsetParent = offsetParent.parentNode;
}
if ( offsetParent && offsetParent !== elem && offsetParent.nodeType === 1 ) {
// Incorporate borders into its offset, since they are outside its content origin
parentOffset = jQuery( offsetParent ).offset();
parentOffset.top += jQuery.css( offsetParent, "borderTopWidth", true );
parentOffset.left += jQuery.css( offsetParent, "borderLeftWidth", true );
}
}
// Subtract parent offsets and element margins
return {
top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ),
left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true )
};
},
// This method will return documentElement in the following cases:
// 1) For the element inside the iframe without offsetParent, this method will return
// documentElement of the parent window
// 2) For the hidden or detached element
// 3) For body or html element, i.e. in case of the html node - it will return itself
//
// but those exceptions were never presented as a real life use-cases
// and might be considered as more preferable results.
//
// This logic, however, is not guaranteed and can change at any point in the future
offsetParent: function() {
return this.map( function() {
var offsetParent = this.offsetParent;
while ( offsetParent && jQuery.css( offsetParent, "position" ) === "static" ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || documentElement;
} );
}
} );
// Create scrollLeft and scrollTop methods
jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) {
var top = "pageYOffset" === prop;
jQuery.fn[ method ] = function( val ) {
return access( this, function( elem, method, val ) {
// Coalesce documents and windows
var win;
if ( isWindow( elem ) ) {
win = elem;
} else if ( elem.nodeType === 9 ) {
win = elem.defaultView;
}
if ( val === undefined ) {
return win ? win[ prop ] : elem[ method ];
}
if ( win ) {
win.scrollTo(
!top ? val : win.pageXOffset,
top ? val : win.pageYOffset
);
} else {
elem[ method ] = val;
}
}, method, val, arguments.length );
};
} );
// Support: Safari <=7 - 9.1, Chrome <=37 - 49
// Add the top/left cssHooks using jQuery.fn.position
// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
// Blink bug: https://bugs.chromium.org/p/chromium/issues/detail?id=589347
// getComputedStyle returns percent when specified for top/left/bottom/right;
// rather than make the css module depend on the offset module, just check for it here
jQuery.each( [ "top", "left" ], function( i, prop ) {
jQuery.cssHooks[ prop ] = addGetHookIf( support.pixelPosition,
function( elem, computed ) {
if ( computed ) {
computed = curCSS( elem, prop );
// If curCSS returns percentage, fallback to offset
return rnumnonpx.test( computed ) ?
jQuery( elem ).position()[ prop ] + "px" :
computed;
}
}
);
} );
// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods
jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name },
function( defaultExtra, funcName ) {
// Margin is only for outerHeight, outerWidth
jQuery.fn[ funcName ] = function( margin, value ) {
var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ),
extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" );
return access( this, function( elem, type, value ) {
var doc;
if ( isWindow( elem ) ) {
// $( window ).outerWidth/Height return w/h including scrollbars (gh-1729)
return funcName.indexOf( "outer" ) === 0 ?
elem[ "inner" + name ] :
elem.document.documentElement[ "client" + name ];
}
// Get document width or height
if ( elem.nodeType === 9 ) {
doc = elem.documentElement;
// Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height],
// whichever is greatest
return Math.max(
elem.body[ "scroll" + name ], doc[ "scroll" + name ],
elem.body[ "offset" + name ], doc[ "offset" + name ],
doc[ "client" + name ]
);
}
return value === undefined ?
// Get width or height on the element, requesting but not forcing parseFloat
jQuery.css( elem, type, extra ) :
// Set width or height on the element
jQuery.style( elem, type, value, extra );
}, type, chainable ? margin : undefined, chainable );
};
} );
} );
jQuery.each( ( "blur focus focusin focusout resize scroll click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
"change select submit keydown keypress keyup contextmenu" ).split( " " ),
function( i, name ) {
// Handle event binding
jQuery.fn[ name ] = function( data, fn ) {
return arguments.length > 0 ?
this.on( name, null, data, fn ) :
this.trigger( name );
};
} );
jQuery.fn.extend( {
hover: function( fnOver, fnOut ) {
return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
}
} );
jQuery.fn.extend( {
bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
},
unbind: function( types, fn ) {
return this.off( types, null, fn );
},
delegate: function( selector, types, data, fn ) {
return this.on( types, selector, data, fn );
},
undelegate: function( selector, types, fn ) {
// ( namespace ) or ( selector, types [, fn] )
return arguments.length === 1 ?
this.off( selector, "**" ) :
this.off( types, selector || "**", fn );
}
} );
// Bind a function to a context, optionally partially applying any
// arguments.
// jQuery.proxy is deprecated to promote standards (specifically Function#bind)
// However, it is not slated for removal any time soon
jQuery.proxy = function( fn, context ) {
var tmp, args, proxy;
if ( typeof context === "string" ) {
tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ( !isFunction( fn ) ) {
return undefined;
}
// Simulated bind
args = slice.call( arguments, 2 );
proxy = function() {
return fn.apply( context || this, args.concat( slice.call( arguments ) ) );
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || jQuery.guid++;
return proxy;
};
jQuery.holdReady = function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
};
jQuery.isArray = Array.isArray;
jQuery.parseJSON = JSON.parse;
jQuery.nodeName = nodeName;
jQuery.isFunction = isFunction;
jQuery.isWindow = isWindow;
jQuery.camelCase = camelCase;
jQuery.type = toType;
jQuery.now = Date.now;
jQuery.isNumeric = function( obj ) {
// As of jQuery 3.0, isNumeric is limited to
// strings and numbers (primitives or objects)
// that can be coerced to finite numbers (gh-2662)
var type = jQuery.type( obj );
return ( type === "number" || type === "string" ) &&
// parseFloat NaNs numeric-cast false positives ("")
// ...but misinterprets leading-number strings, particularly hex literals ("0x...")
// subtraction forces infinities to NaN
!isNaN( obj - parseFloat( obj ) );
};
// Register as a named AMD module, since jQuery can be concatenated with other
// files that may use define, but not via a proper concatenation script that
// understands anonymous AMD modules. A named AMD is safest and most robust
// way to register. Lowercase jquery is used because AMD module names are
// derived from file names, and jQuery is normally delivered in a lowercase
// file name. Do this after creating the global so that if an AMD module wants
// to call noConflict to hide this version of jQuery, it will work.
// Note that for maximum portability, libraries that are not jQuery should
// declare themselves as anonymous modules, and avoid setting a global if an
// AMD loader is present. jQuery is a special case. For more information, see
// https://github.com/jrburke/requirejs/wiki/Updating-existing-libraries#wiki-anon
if ( typeof define === "function" && define.amd ) {
define( "jquery", [], function() {
return jQuery;
} );
}
var
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$;
jQuery.noConflict = function( deep ) {
if ( window.$ === jQuery ) {
window.$ = _$;
}
if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}
return jQuery;
};
// Expose jQuery and $ identifiers, even in AMD
// (#7102#comment:10, https://github.com/jquery/jquery/pull/557)
// and CommonJS for browser emulators (#13566)
if ( !noGlobal ) {
window.jQuery = window.$ = jQuery;
}
return jQuery;
} );
;
( function( factory ) {
if ( typeof define === "function" && define.amd ) {
// AMD. Register as an anonymous module.
define( [ "jquery" ], factory );
} else {
// Browser globals
factory( jQuery );
}
} ( function( $ ) {
$.ui = $.ui || {};
return $.ui.version = "1.12.1";
} ) );
;
/*!
* jQuery UI Widget 1.12.1
* http://jqueryui.com
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*/
//>>label: Widget
//>>group: Core
//>>description: Provides a factory for creating stateful widgets with a common API.
//>>docs: http://api.jqueryui.com/jQuery.widget/
//>>demos: http://jqueryui.com/widget/
( function( factory ) {
if ( typeof define === "function" && define.amd ) {
// AMD. Register as an anonymous module.
define( [ "jquery", "./version" ], factory );
} else {
// Browser globals
factory( jQuery );
}
}( function( $ ) {
var widgetUuid = 0;
var widgetSlice = Array.prototype.slice;
$.cleanData = ( function( orig ) {
return function( elems ) {
var events, elem, i;
for ( i = 0; ( elem = elems[ i ] ) != null; i++ ) {
try {
// Only trigger remove when necessary to save time
events = $._data( elem, "events" );
if ( events && events.remove ) {
$( elem ).triggerHandler( "remove" );
}
// Http://bugs.jquery.com/ticket/8235
} catch ( e ) {}
}
orig( elems );
};
} )( $.cleanData );
$.widget = function( name, base, prototype ) {
var existingConstructor, constructor, basePrototype;
// ProxiedPrototype allows the provided prototype to remain unmodified
// so that it can be used as a mixin for multiple widgets (#8876)
var proxiedPrototype = {};
var namespace = name.split( "." )[ 0 ];
name = name.split( "." )[ 1 ];
var fullName = namespace + "-" + name;
if ( !prototype ) {
prototype = base;
base = $.Widget;
}
if ( $.isArray( prototype ) ) {
prototype = $.extend.apply( null, [ {} ].concat( prototype ) );
}
// Create selector for plugin
$.expr[ ":" ][ fullName.toLowerCase() ] = function( elem ) {
return !!$.data( elem, fullName );
};
$[ namespace ] = $[ namespace ] || {};
existingConstructor = $[ namespace ][ name ];
constructor = $[ namespace ][ name ] = function( options, element ) {
// Allow instantiation without "new" keyword
if ( !this._createWidget ) {
return new constructor( options, element );
}
// Allow instantiation without initializing for simple inheritance
// must use "new" keyword (the code above always passes args)
if ( arguments.length ) {
this._createWidget( options, element );
}
};
// Extend with the existing constructor to carry over any static properties
$.extend( constructor, existingConstructor, {
version: prototype.version,
// Copy the object used to create the prototype in case we need to
// redefine the widget later
_proto: $.extend( {}, prototype ),
// Track widgets that inherit from this widget in case this widget is
// redefined after a widget inherits from it
_childConstructors: []
} );
basePrototype = new base();
// We need to make the options hash a property directly on the new instance
// otherwise we'll modify the options hash on the prototype that we're
// inheriting from
basePrototype.options = $.widget.extend( {}, basePrototype.options );
$.each( prototype, function( prop, value ) {
if ( !$.isFunction( value ) ) {
proxiedPrototype[ prop ] = value;
return;
}
proxiedPrototype[ prop ] = ( function() {
function _super() {
return base.prototype[ prop ].apply( this, arguments );
}
function _superApply( args ) {
return base.prototype[ prop ].apply( this, args );
}
return function() {
var __super = this._super;
var __superApply = this._superApply;
var returnValue;
this._super = _super;
this._superApply = _superApply;
returnValue = value.apply( this, arguments );
this._super = __super;
this._superApply = __superApply;
return returnValue;
};
} )();
} );
constructor.prototype = $.widget.extend( basePrototype, {
// TODO: remove support for widgetEventPrefix
// always use the name + a colon as the prefix, e.g., draggable:start
// don't prefix for widgets that aren't DOM-based
widgetEventPrefix: existingConstructor ? ( basePrototype.widgetEventPrefix || name ) : name
}, proxiedPrototype, {
constructor: constructor,
namespace: namespace,
widgetName: name,
widgetFullName: fullName
} );
// If this widget is being redefined then we need to find all widgets that
// are inheriting from it and redefine all of them so that they inherit from
// the new version of this widget. We're essentially trying to replace one
// level in the prototype chain.
if ( existingConstructor ) {
$.each( existingConstructor._childConstructors, function( i, child ) {
var childPrototype = child.prototype;
// Redefine the child widget using the same prototype that was
// originally used, but inherit from the new version of the base
$.widget( childPrototype.namespace + "." + childPrototype.widgetName, constructor,
child._proto );
} );
// Remove the list of existing child constructors from the old constructor
// so the old child constructors can be garbage collected
delete existingConstructor._childConstructors;
} else {
base._childConstructors.push( constructor );
}
$.widget.bridge( name, constructor );
return constructor;
};
$.widget.extend = function( target ) {
var input = widgetSlice.call( arguments, 1 );
var inputIndex = 0;
var inputLength = input.length;
var key;
var value;
for ( ; inputIndex < inputLength; inputIndex++ ) {
for ( key in input[ inputIndex ] ) {
value = input[ inputIndex ][ key ];
if ( input[ inputIndex ].hasOwnProperty( key ) && value !== undefined ) {
// Clone objects
if ( $.isPlainObject( value ) ) {
target[ key ] = $.isPlainObject( target[ key ] ) ?
$.widget.extend( {}, target[ key ], value ) :
// Don't extend strings, arrays, etc. with objects
$.widget.extend( {}, value );
// Copy everything else by reference
} else {
target[ key ] = value;
}
}
}
}
return target;
};
$.widget.bridge = function( name, object ) {
var fullName = object.prototype.widgetFullName || name;
$.fn[ name ] = function( options ) {
var isMethodCall = typeof options === "string";
var args = widgetSlice.call( arguments, 1 );
var returnValue = this;
if ( isMethodCall ) {
// If this is an empty collection, we need to have the instance method
// return undefined instead of the jQuery instance
if ( !this.length && options === "instance" ) {
returnValue = undefined;
} else {
this.each( function() {
var methodValue;
var instance = $.data( this, fullName );
if ( options === "instance" ) {
returnValue = instance;
return false;
}
if ( !instance ) {
return $.error( "cannot call methods on " + name +
" prior to initialization; " +
"attempted to call method '" + options + "'" );
}
if ( !$.isFunction( instance[ options ] ) || options.charAt( 0 ) === "_" ) {
return $.error( "no such method '" + options + "' for " + name +
" widget instance" );
}
methodValue = instance[ options ].apply( instance, args );
if ( methodValue !== instance && methodValue !== undefined ) {
returnValue = methodValue && methodValue.jquery ?
returnValue.pushStack( methodValue.get() ) :
methodValue;
return false;
}
} );
}
} else {
// Allow multiple hashes to be passed on init
if ( args.length ) {
options = $.widget.extend.apply( null, [ options ].concat( args ) );
}
this.each( function() {
var instance = $.data( this, fullName );
if ( instance ) {
instance.option( options || {} );
if ( instance._init ) {
instance._init();
}
} else {
$.data( this, fullName, new object( options, this ) );
}
} );
}
return returnValue;
};
};
$.Widget = function( /* options, element */ ) {};
$.Widget._childConstructors = [];
$.Widget.prototype = {
widgetName: "widget",
widgetEventPrefix: "",
defaultElement: "<div>",
options: {
classes: {},
disabled: false,
// Callbacks
create: null
},
_createWidget: function( options, element ) {
element = $( element || this.defaultElement || this )[ 0 ];
this.element = $( element );
this.uuid = widgetUuid++;
this.eventNamespace = "." + this.widgetName + this.uuid;
this.bindings = $();
this.hoverable = $();
this.focusable = $();
this.classesElementLookup = {};
if ( element !== this ) {
$.data( element, this.widgetFullName, this );
this._on( true, this.element, {
remove: function( event ) {
if ( event.target === element ) {
this.destroy();
}
}
} );
this.document = $( element.style ?
// Element within the document
element.ownerDocument :
// Element is window or document
element.document || element );
this.window = $( this.document[ 0 ].defaultView || this.document[ 0 ].parentWindow );
}
this.options = $.widget.extend( {},
this.options,
this._getCreateOptions(),
options );
this._create();
if ( this.options.disabled ) {
this._setOptionDisabled( this.options.disabled );
}
this._trigger( "create", null, this._getCreateEventData() );
this._init();
},
_getCreateOptions: function() {
return {};
},
_getCreateEventData: $.noop,
_create: $.noop,
_init: $.noop,
destroy: function() {
var that = this;
this._destroy();
$.each( this.classesElementLookup, function( key, value ) {
that._removeClass( value, key );
} );
// We can probably remove the unbind calls in 2.0
// all event bindings should go through this._on()
this.element
.off( this.eventNamespace )
.removeData( this.widgetFullName );
this.widget()
.off( this.eventNamespace )
.removeAttr( "aria-disabled" );
// Clean up events and states
this.bindings.off( this.eventNamespace );
},
_destroy: $.noop,
widget: function() {
return this.element;
},
option: function( key, value ) {
var options = key;
var parts;
var curOption;
var i;
if ( arguments.length === 0 ) {
// Don't return a reference to the internal hash
return $.widget.extend( {}, this.options );
}
if ( typeof key === "string" ) {
// Handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } }
options = {};
parts = key.split( "." );
key = parts.shift();
if ( parts.length ) {
curOption = options[ key ] = $.widget.extend( {}, this.options[ key ] );
for ( i = 0; i < parts.length - 1; i++ ) {
curOption[ parts[ i ] ] = curOption[ parts[ i ] ] || {};
curOption = curOption[ parts[ i ] ];
}
key = parts.pop();
if ( arguments.length === 1 ) {
return curOption[ key ] === undefined ? null : curOption[ key ];
}
curOption[ key ] = value;
} else {
if ( arguments.length === 1 ) {
return this.options[ key ] === undefined ? null : this.options[ key ];
}
options[ key ] = value;
}
}
this._setOptions( options );
return this;
},
_setOptions: function( options ) {
var key;
for ( key in options ) {
this._setOption( key, options[ key ] );
}
return this;
},
_setOption: function( key, value ) {
if ( key === "classes" ) {
this._setOptionClasses( value );
}
this.options[ key ] = value;
if ( key === "disabled" ) {
this._setOptionDisabled( value );
}
return this;
},
_setOptionClasses: function( value ) {
var classKey, elements, currentElements;
for ( classKey in value ) {
currentElements = this.classesElementLookup[ classKey ];
if ( value[ classKey ] === this.options.classes[ classKey ] ||
!currentElements ||
!currentElements.length ) {
continue;
}
// We are doing this to create a new jQuery object because the _removeClass() call
// on the next line is going to destroy the reference to the current elements being
// tracked. We need to save a copy of this collection so that we can add the new classes
// below.
elements = $( currentElements.get() );
this._removeClass( currentElements, classKey );
// We don't use _addClass() here, because that uses this.options.classes
// for generating the string of classes. We want to use the value passed in from
// _setOption(), this is the new value of the classes option which was passed to
// _setOption(). We pass this value directly to _classes().
elements.addClass( this._classes( {
element: elements,
keys: classKey,
classes: value,
add: true
} ) );
}
},
_setOptionDisabled: function( value ) {
this._toggleClass( this.widget(), this.widgetFullName + "-disabled", null, !!value );
// If the widget is becoming disabled, then nothing is interactive
if ( value ) {
this._removeClass( this.hoverable, null, "ui-state-hover" );
this._removeClass( this.focusable, null, "ui-state-focus" );
}
},
enable: function() {
return this._setOptions( { disabled: false } );
},
disable: function() {
return this._setOptions( { disabled: true } );
},
_classes: function( options ) {
var full = [];
var that = this;
options = $.extend( {
element: this.element,
classes: this.options.classes || {}
}, options );
function processClassString( classes, checkOption ) {
var current, i;
for ( i = 0; i < classes.length; i++ ) {
current = that.classesElementLookup[ classes[ i ] ] || $();
if ( options.add ) {
current = $( $.unique( current.get().concat( options.element.get() ) ) );
} else {
current = $( current.not( options.element ).get() );
}
that.classesElementLookup[ classes[ i ] ] = current;
full.push( classes[ i ] );
if ( checkOption && options.classes[ classes[ i ] ] ) {
full.push( options.classes[ classes[ i ] ] );
}
}
}
this._on( options.element, {
"remove": "_untrackClassesElement"
} );
if ( options.keys ) {
processClassString( options.keys.match( /\S+/g ) || [], true );
}
if ( options.extra ) {
processClassString( options.extra.match( /\S+/g ) || [] );
}
return full.join( " " );
},
_untrackClassesElement: function( event ) {
var that = this;
$.each( that.classesElementLookup, function( key, value ) {
if ( $.inArray( event.target, value ) !== -1 ) {
that.classesElementLookup[ key ] = $( value.not( event.target ).get() );
}
} );
},
_removeClass: function( element, keys, extra ) {
return this._toggleClass( element, keys, extra, false );
},
_addClass: function( element, keys, extra ) {
return this._toggleClass( element, keys, extra, true );
},
_toggleClass: function( element, keys, extra, add ) {
add = ( typeof add === "boolean" ) ? add : extra;
var shift = ( typeof element === "string" || element === null ),
options = {
extra: shift ? keys : extra,
keys: shift ? element : keys,
element: shift ? this.element : element,
add: add
};
options.element.toggleClass( this._classes( options ), add );
return this;
},
_on: function( suppressDisabledCheck, element, handlers ) {
var delegateElement;
var instance = this;
// No suppressDisabledCheck flag, shuffle arguments
if ( typeof suppressDisabledCheck !== "boolean" ) {
handlers = element;
element = suppressDisabledCheck;
suppressDisabledCheck = false;
}
// No element argument, shuffle and use this.element
if ( !handlers ) {
handlers = element;
element = this.element;
delegateElement = this.widget();
} else {
element = delegateElement = $( element );
this.bindings = this.bindings.add( element );
}
$.each( handlers, function( event, handler ) {
function handlerProxy() {
// Allow widgets to customize the disabled handling
// - disabled as an array instead of boolean
// - disabled class as method for disabling individual parts
if ( !suppressDisabledCheck &&
( instance.options.disabled === true ||
$( this ).hasClass( "ui-state-disabled" ) ) ) {
return;
}
return ( typeof handler === "string" ? instance[ handler ] : handler )
.apply( instance, arguments );
}
// Copy the guid so direct unbinding works
if ( typeof handler !== "string" ) {
handlerProxy.guid = handler.guid =
handler.guid || handlerProxy.guid || $.guid++;
}
var match = event.match( /^([\w:-]*)\s*(.*)$/ );
var eventName = match[ 1 ] + instance.eventNamespace;
var selector = match[ 2 ];
if ( selector ) {
delegateElement.on( eventName, selector, handlerProxy );
} else {
element.on( eventName, handlerProxy );
}
} );
},
_off: function( element, eventName ) {
eventName = ( eventName || "" ).split( " " ).join( this.eventNamespace + " " ) +
this.eventNamespace;
element.off( eventName ).off( eventName );
// Clear the stack to avoid memory leaks (#10056)
this.bindings = $( this.bindings.not( element ).get() );
this.focusable = $( this.focusable.not( element ).get() );
this.hoverable = $( this.hoverable.not( element ).get() );
},
_delay: function( handler, delay ) {
function handlerProxy() {
return ( typeof handler === "string" ? instance[ handler ] : handler )
.apply( instance, arguments );
}
var instance = this;
return setTimeout( handlerProxy, delay || 0 );
},
_hoverable: function( element ) {
this.hoverable = this.hoverable.add( element );
this._on( element, {
mouseenter: function( event ) {
this._addClass( $( event.currentTarget ), null, "ui-state-hover" );
},
mouseleave: function( event ) {
this._removeClass( $( event.currentTarget ), null, "ui-state-hover" );
}
} );
},
_focusable: function( element ) {
this.focusable = this.focusable.add( element );
this._on( element, {
focusin: function( event ) {
this._addClass( $( event.currentTarget ), null, "ui-state-focus" );
},
focusout: function( event ) {
this._removeClass( $( event.currentTarget ), null, "ui-state-focus" );
}
} );
},
_trigger: function( type, event, data ) {
var prop, orig;
var callback = this.options[ type ];
data = data || {};
event = $.Event( event );
event.type = ( type === this.widgetEventPrefix ?
type :
this.widgetEventPrefix + type ).toLowerCase();
// The original event may come from any element
// so we need to reset the target on the new event
event.target = this.element[ 0 ];
// Copy original event properties over to the new event
orig = event.originalEvent;
if ( orig ) {
for ( prop in orig ) {
if ( !( prop in event ) ) {
event[ prop ] = orig[ prop ];
}
}
}
this.element.trigger( event, data );
return !( $.isFunction( callback ) &&
callback.apply( this.element[ 0 ], [ event ].concat( data ) ) === false ||
event.isDefaultPrevented() );
}
};
$.each( { show: "fadeIn", hide: "fadeOut" }, function( method, defaultEffect ) {
$.Widget.prototype[ "_" + method ] = function( element, options, callback ) {
if ( typeof options === "string" ) {
options = { effect: options };
}
var hasOptions;
var effectName = !options ?
method :
options === true || typeof options === "number" ?
defaultEffect :
options.effect || defaultEffect;
options = options || {};
if ( typeof options === "number" ) {
options = { duration: options };
}
hasOptions = !$.isEmptyObject( options );
options.complete = callback;
if ( options.delay ) {
element.delay( options.delay );
}
if ( hasOptions && $.effects && $.effects.effect[ effectName ] ) {
element[ method ]( options );
} else if ( effectName !== method && element[ effectName ] ) {
element[ effectName ]( options.duration, options.easing, callback );
} else {
element.queue( function( next ) {
$( this )[ method ]();
if ( callback ) {
callback.call( element[ 0 ] );
}
next();
} );
}
};
} );
return $.widget;
} ) );
;
( function( factory ) {
if ( typeof define === "function" && define.amd ) {
// AMD. Register as an anonymous module.
define( [ "jquery", "./version" ], factory );
} else {
// Browser globals
factory( jQuery );
}
} ( function( $ ) {
// $.ui.plugin is deprecated. Use $.widget() extensions instead.
return $.ui.plugin = {
add: function( module, option, set ) {
var i,
proto = $.ui[ module ].prototype;
for ( i in set ) {
proto.plugins[ i ] = proto.plugins[ i ] || [];
proto.plugins[ i ].push( [ option, set[ i ] ] );
}
},
call: function( instance, name, args, allowDisconnected ) {
var i,
set = instance.plugins[ name ];
if ( !set ) {
return;
}
if ( !allowDisconnected && ( !instance.element[ 0 ].parentNode ||
instance.element[ 0 ].parentNode.nodeType === 11 ) ) {
return;
}
for ( i = 0; i < set.length; i++ ) {
if ( instance.options[ set[ i ][ 0 ] ] ) {
set[ i ][ 1 ].apply( instance.element, args );
}
}
}
};
} ) );
;
( function( factory ) {
if ( typeof define === "function" && define.amd ) {
// AMD. Register as an anonymous module.
define( [ "jquery", "./version" ], factory );
} else {
// Browser globals
factory( jQuery );
}
} ( function( $ ) {
return $.ui.safeActiveElement = function( document ) {
var activeElement;
// Support: IE 9 only
// IE9 throws an "Unspecified error" accessing document.activeElement from an <iframe>
try {
activeElement = document.activeElement;
} catch ( error ) {
activeElement = document.body;
}
// Support: IE 9 - 11 only
// IE may return null instead of an element
// Interestingly, this only seems to occur when NOT in an iframe
if ( !activeElement ) {
activeElement = document.body;
}
// Support: IE 11 only
// IE11 returns a seemingly empty object in some cases when accessing
// document.activeElement from an <iframe>
if ( !activeElement.nodeName ) {
activeElement = document.body;
}
return activeElement;
};
} ) );
;
( function( factory ) {
if ( typeof define === "function" && define.amd ) {
// AMD. Register as an anonymous module.
define( [ "jquery", "./version" ], factory );
} else {
// Browser globals
factory( jQuery );
}
} ( function( $ ) {
return $.ui.safeBlur = function( element ) {
// Support: IE9 - 10 only
// If the <body> is blurred, IE will switch windows, see #9420
if ( element && element.nodeName.toLowerCase() !== "body" ) {
$( element ).trigger( "blur" );
}
};
} ) );
;
/*!
* jQuery UI Scroll Parent 1.12.1
* http://jqueryui.com
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*/
//>>label: scrollParent
//>>group: Core
//>>description: Get the closest ancestor element that is scrollable.
//>>docs: http://api.jqueryui.com/scrollParent/
( function( factory ) {
if ( typeof define === "function" && define.amd ) {
// AMD. Register as an anonymous module.
define( [ "jquery", "./version" ], factory );
} else {
// Browser globals
factory( jQuery );
}
} ( function( $ ) {
return $.fn.scrollParent = function( includeHidden ) {
var position = this.css( "position" ),
excludeStaticParent = position === "absolute",
overflowRegex = includeHidden ? /(auto|scroll|hidden)/ : /(auto|scroll)/,
scrollParent = this.parents().filter( function() {
var parent = $( this );
if ( excludeStaticParent && parent.css( "position" ) === "static" ) {
return false;
}
return overflowRegex.test( parent.css( "overflow" ) + parent.css( "overflow-y" ) +
parent.css( "overflow-x" ) );
} ).eq( 0 );
return position === "fixed" || !scrollParent.length ?
$( this[ 0 ].ownerDocument || document ) :
scrollParent;
};
} ) );
;
/*!
* jQuery UI Position 1.12.1
* http://jqueryui.com
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*
* http://api.jqueryui.com/position/
*/
//>>label: Position
//>>group: Core
//>>description: Positions elements relative to other elements.
//>>docs: http://api.jqueryui.com/position/
//>>demos: http://jqueryui.com/position/
( function( factory ) {
if ( typeof define === "function" && define.amd ) {
// AMD. Register as an anonymous module.
define( [ "jquery", "./version" ], factory );
} else {
// Browser globals
factory( jQuery );
}
}( function( $ ) {
( function() {
var cachedScrollbarWidth,
max = Math.max,
abs = Math.abs,
rhorizontal = /left|center|right/,
rvertical = /top|center|bottom/,
roffset = /[\+\-]\d+(\.[\d]+)?%?/,
rposition = /^\w+/,
rpercent = /%$/,
_position = $.fn.position;
function getOffsets( offsets, width, height ) {
return [
parseFloat( offsets[ 0 ] ) * ( rpercent.test( offsets[ 0 ] ) ? width / 100 : 1 ),
parseFloat( offsets[ 1 ] ) * ( rpercent.test( offsets[ 1 ] ) ? height / 100 : 1 )
];
}
function parseCss( element, property ) {
return parseInt( $.css( element, property ), 10 ) || 0;
}
function getDimensions( elem ) {
var raw = elem[ 0 ];
if ( raw.nodeType === 9 ) {
return {
width: elem.width(),
height: elem.height(),
offset: { top: 0, left: 0 }
};
}
if ( $.isWindow( raw ) ) {
return {
width: elem.width(),
height: elem.height(),
offset: { top: elem.scrollTop(), left: elem.scrollLeft() }
};
}
if ( raw.preventDefault ) {
return {
width: 0,
height: 0,
offset: { top: raw.pageY, left: raw.pageX }
};
}
return {
width: elem.outerWidth(),
height: elem.outerHeight(),
offset: elem.offset()
};
}
$.position = {
scrollbarWidth: function() {
if ( cachedScrollbarWidth !== undefined ) {
return cachedScrollbarWidth;
}
var w1, w2,
div = $( "<div " +
"style='display:block;position:absolute;width:50px;height:50px;overflow:hidden;'>" +
"<div style='height:100px;width:auto;'></div></div>" ),
innerDiv = div.children()[ 0 ];
$( "body" ).append( div );
w1 = innerDiv.offsetWidth;
div.css( "overflow", "scroll" );
w2 = innerDiv.offsetWidth;
if ( w1 === w2 ) {
w2 = div[ 0 ].clientWidth;
}
div.remove();
return ( cachedScrollbarWidth = w1 - w2 );
},
getScrollInfo: function( within ) {
var overflowX = within.isWindow || within.isDocument ? "" :
within.element.css( "overflow-x" ),
overflowY = within.isWindow || within.isDocument ? "" :
within.element.css( "overflow-y" ),
hasOverflowX = overflowX === "scroll" ||
( overflowX === "auto" && within.width < within.element[ 0 ].scrollWidth ),
hasOverflowY = overflowY === "scroll" ||
( overflowY === "auto" && within.height < within.element[ 0 ].scrollHeight );
return {
width: hasOverflowY ? $.position.scrollbarWidth() : 0,
height: hasOverflowX ? $.position.scrollbarWidth() : 0
};
},
getWithinInfo: function( element ) {
var withinElement = $( element || window ),
isWindow = $.isWindow( withinElement[ 0 ] ),
isDocument = !!withinElement[ 0 ] && withinElement[ 0 ].nodeType === 9,
hasOffset = !isWindow && !isDocument;
return {
element: withinElement,
isWindow: isWindow,
isDocument: isDocument,
offset: hasOffset ? $( element ).offset() : { left: 0, top: 0 },
scrollLeft: withinElement.scrollLeft(),
scrollTop: withinElement.scrollTop(),
width: withinElement.outerWidth(),
height: withinElement.outerHeight()
};
}
};
$.fn.position = function( options ) {
if ( !options || !options.of ) {
return _position.apply( this, arguments );
}
// Make a copy, we don't want to modify arguments
options = $.extend( {}, options );
var atOffset, targetWidth, targetHeight, targetOffset, basePosition, dimensions,
target = $( options.of ),
within = $.position.getWithinInfo( options.within ),
scrollInfo = $.position.getScrollInfo( within ),
collision = ( options.collision || "flip" ).split( " " ),
offsets = {};
dimensions = getDimensions( target );
if ( target[ 0 ].preventDefault ) {
// Force left top to allow flipping
options.at = "left top";
}
targetWidth = dimensions.width;
targetHeight = dimensions.height;
targetOffset = dimensions.offset;
// Clone to reuse original targetOffset later
basePosition = $.extend( {}, targetOffset );
// Force my and at to have valid horizontal and vertical positions
// if a value is missing or invalid, it will be converted to center
$.each( [ "my", "at" ], function() {
var pos = ( options[ this ] || "" ).split( " " ),
horizontalOffset,
verticalOffset;
if ( pos.length === 1 ) {
pos = rhorizontal.test( pos[ 0 ] ) ?
pos.concat( [ "center" ] ) :
rvertical.test( pos[ 0 ] ) ?
[ "center" ].concat( pos ) :
[ "center", "center" ];
}
pos[ 0 ] = rhorizontal.test( pos[ 0 ] ) ? pos[ 0 ] : "center";
pos[ 1 ] = rvertical.test( pos[ 1 ] ) ? pos[ 1 ] : "center";
// Calculate offsets
horizontalOffset = roffset.exec( pos[ 0 ] );
verticalOffset = roffset.exec( pos[ 1 ] );
offsets[ this ] = [
horizontalOffset ? horizontalOffset[ 0 ] : 0,
verticalOffset ? verticalOffset[ 0 ] : 0
];
// Reduce to just the positions without the offsets
options[ this ] = [
rposition.exec( pos[ 0 ] )[ 0 ],
rposition.exec( pos[ 1 ] )[ 0 ]
];
} );
// Normalize collision option
if ( collision.length === 1 ) {
collision[ 1 ] = collision[ 0 ];
}
if ( options.at[ 0 ] === "right" ) {
basePosition.left += targetWidth;
} else if ( options.at[ 0 ] === "center" ) {
basePosition.left += targetWidth / 2;
}
if ( options.at[ 1 ] === "bottom" ) {
basePosition.top += targetHeight;
} else if ( options.at[ 1 ] === "center" ) {
basePosition.top += targetHeight / 2;
}
atOffset = getOffsets( offsets.at, targetWidth, targetHeight );
basePosition.left += atOffset[ 0 ];
basePosition.top += atOffset[ 1 ];
return this.each( function() {
var collisionPosition, using,
elem = $( this ),
elemWidth = elem.outerWidth(),
elemHeight = elem.outerHeight(),
marginLeft = parseCss( this, "marginLeft" ),
marginTop = parseCss( this, "marginTop" ),
collisionWidth = elemWidth + marginLeft + parseCss( this, "marginRight" ) +
scrollInfo.width,
collisionHeight = elemHeight + marginTop + parseCss( this, "marginBottom" ) +
scrollInfo.height,
position = $.extend( {}, basePosition ),
myOffset = getOffsets( offsets.my, elem.outerWidth(), elem.outerHeight() );
if ( options.my[ 0 ] === "right" ) {
position.left -= elemWidth;
} else if ( options.my[ 0 ] === "center" ) {
position.left -= elemWidth / 2;
}
if ( options.my[ 1 ] === "bottom" ) {
position.top -= elemHeight;
} else if ( options.my[ 1 ] === "center" ) {
position.top -= elemHeight / 2;
}
position.left += myOffset[ 0 ];
position.top += myOffset[ 1 ];
collisionPosition = {
marginLeft: marginLeft,
marginTop: marginTop
};
$.each( [ "left", "top" ], function( i, dir ) {
if ( $.ui.position[ collision[ i ] ] ) {
$.ui.position[ collision[ i ] ][ dir ]( position, {
targetWidth: targetWidth,
targetHeight: targetHeight,
elemWidth: elemWidth,
elemHeight: elemHeight,
collisionPosition: collisionPosition,
collisionWidth: collisionWidth,
collisionHeight: collisionHeight,
offset: [ atOffset[ 0 ] + myOffset[ 0 ], atOffset [ 1 ] + myOffset[ 1 ] ],
my: options.my,
at: options.at,
within: within,
elem: elem
} );
}
} );
if ( options.using ) {
// Adds feedback as second argument to using callback, if present
using = function( props ) {
var left = targetOffset.left - position.left,
right = left + targetWidth - elemWidth,
top = targetOffset.top - position.top,
bottom = top + targetHeight - elemHeight,
feedback = {
target: {
element: target,
left: targetOffset.left,
top: targetOffset.top,
width: targetWidth,
height: targetHeight
},
element: {
element: elem,
left: position.left,
top: position.top,
width: elemWidth,
height: elemHeight
},
horizontal: right < 0 ? "left" : left > 0 ? "right" : "center",
vertical: bottom < 0 ? "top" : top > 0 ? "bottom" : "middle"
};
if ( targetWidth < elemWidth && abs( left + right ) < targetWidth ) {
feedback.horizontal = "center";
}
if ( targetHeight < elemHeight && abs( top + bottom ) < targetHeight ) {
feedback.vertical = "middle";
}
if ( max( abs( left ), abs( right ) ) > max( abs( top ), abs( bottom ) ) ) {
feedback.important = "horizontal";
} else {
feedback.important = "vertical";
}
options.using.call( this, props, feedback );
};
}
elem.offset( $.extend( position, { using: using } ) );
} );
};
$.ui.position = {
fit: {
left: function( position, data ) {
var within = data.within,
withinOffset = within.isWindow ? within.scrollLeft : within.offset.left,
outerWidth = within.width,
collisionPosLeft = position.left - data.collisionPosition.marginLeft,
overLeft = withinOffset - collisionPosLeft,
overRight = collisionPosLeft + data.collisionWidth - outerWidth - withinOffset,
newOverRight;
// Element is wider than within
if ( data.collisionWidth > outerWidth ) {
// Element is initially over the left side of within
if ( overLeft > 0 && overRight <= 0 ) {
newOverRight = position.left + overLeft + data.collisionWidth - outerWidth -
withinOffset;
position.left += overLeft - newOverRight;
// Element is initially over right side of within
} else if ( overRight > 0 && overLeft <= 0 ) {
position.left = withinOffset;
// Element is initially over both left and right sides of within
} else {
if ( overLeft > overRight ) {
position.left = withinOffset + outerWidth - data.collisionWidth;
} else {
position.left = withinOffset;
}
}
// Too far left -> align with left edge
} else if ( overLeft > 0 ) {
position.left += overLeft;
// Too far right -> align with right edge
} else if ( overRight > 0 ) {
position.left -= overRight;
// Adjust based on position and margin
} else {
position.left = max( position.left - collisionPosLeft, position.left );
}
},
top: function( position, data ) {
var within = data.within,
withinOffset = within.isWindow ? within.scrollTop : within.offset.top,
outerHeight = data.within.height,
collisionPosTop = position.top - data.collisionPosition.marginTop,
overTop = withinOffset - collisionPosTop,
overBottom = collisionPosTop + data.collisionHeight - outerHeight - withinOffset,
newOverBottom;
// Element is taller than within
if ( data.collisionHeight > outerHeight ) {
// Element is initially over the top of within
if ( overTop > 0 && overBottom <= 0 ) {
newOverBottom = position.top + overTop + data.collisionHeight - outerHeight -
withinOffset;
position.top += overTop - newOverBottom;
// Element is initially over bottom of within
} else if ( overBottom > 0 && overTop <= 0 ) {
position.top = withinOffset;
// Element is initially over both top and bottom of within
} else {
if ( overTop > overBottom ) {
position.top = withinOffset + outerHeight - data.collisionHeight;
} else {
position.top = withinOffset;
}
}
// Too far up -> align with top
} else if ( overTop > 0 ) {
position.top += overTop;
// Too far down -> align with bottom edge
} else if ( overBottom > 0 ) {
position.top -= overBottom;
// Adjust based on position and margin
} else {
position.top = max( position.top - collisionPosTop, position.top );
}
}
},
flip: {
left: function( position, data ) {
var within = data.within,
withinOffset = within.offset.left + within.scrollLeft,
outerWidth = within.width,
offsetLeft = within.isWindow ? within.scrollLeft : within.offset.left,
collisionPosLeft = position.left - data.collisionPosition.marginLeft,
overLeft = collisionPosLeft - offsetLeft,
overRight = collisionPosLeft + data.collisionWidth - outerWidth - offsetLeft,
myOffset = data.my[ 0 ] === "left" ?
-data.elemWidth :
data.my[ 0 ] === "right" ?
data.elemWidth :
0,
atOffset = data.at[ 0 ] === "left" ?
data.targetWidth :
data.at[ 0 ] === "right" ?
-data.targetWidth :
0,
offset = -2 * data.offset[ 0 ],
newOverRight,
newOverLeft;
if ( overLeft < 0 ) {
newOverRight = position.left + myOffset + atOffset + offset + data.collisionWidth -
outerWidth - withinOffset;
if ( newOverRight < 0 || newOverRight < abs( overLeft ) ) {
position.left += myOffset + atOffset + offset;
}
} else if ( overRight > 0 ) {
newOverLeft = position.left - data.collisionPosition.marginLeft + myOffset +
atOffset + offset - offsetLeft;
if ( newOverLeft > 0 || abs( newOverLeft ) < overRight ) {
position.left += myOffset + atOffset + offset;
}
}
},
top: function( position, data ) {
var within = data.within,
withinOffset = within.offset.top + within.scrollTop,
outerHeight = within.height,
offsetTop = within.isWindow ? within.scrollTop : within.offset.top,
collisionPosTop = position.top - data.collisionPosition.marginTop,
overTop = collisionPosTop - offsetTop,
overBottom = collisionPosTop + data.collisionHeight - outerHeight - offsetTop,
top = data.my[ 1 ] === "top",
myOffset = top ?
-data.elemHeight :
data.my[ 1 ] === "bottom" ?
data.elemHeight :
0,
atOffset = data.at[ 1 ] === "top" ?
data.targetHeight :
data.at[ 1 ] === "bottom" ?
-data.targetHeight :
0,
offset = -2 * data.offset[ 1 ],
newOverTop,
newOverBottom;
if ( overTop < 0 ) {
newOverBottom = position.top + myOffset + atOffset + offset + data.collisionHeight -
outerHeight - withinOffset;
if ( newOverBottom < 0 || newOverBottom < abs( overTop ) ) {
position.top += myOffset + atOffset + offset;
}
} else if ( overBottom > 0 ) {
newOverTop = position.top - data.collisionPosition.marginTop + myOffset + atOffset +
offset - offsetTop;
if ( newOverTop > 0 || abs( newOverTop ) < overBottom ) {
position.top += myOffset + atOffset + offset;
}
}
}
},
flipfit: {
left: function() {
$.ui.position.flip.left.apply( this, arguments );
$.ui.position.fit.left.apply( this, arguments );
},
top: function() {
$.ui.position.flip.top.apply( this, arguments );
$.ui.position.fit.top.apply( this, arguments );
}
}
};
} )();
return $.ui.position;
} ) );
;
/*!
* jQuery UI :data 1.12.1
* http://jqueryui.com
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*/
//>>label: :data Selector
//>>group: Core
//>>description: Selects elements which have data stored under the specified key.
//>>docs: http://api.jqueryui.com/data-selector/
( function( factory ) {
if ( typeof define === "function" && define.amd ) {
// AMD. Register as an anonymous module.
define( [ "jquery", "./version" ], factory );
} else {
// Browser globals
factory( jQuery );
}
} ( function( $ ) {
return $.extend( $.expr[ ":" ], {
data: $.expr.createPseudo ?
$.expr.createPseudo( function( dataName ) {
return function( elem ) {
return !!$.data( elem, dataName );
};
} ) :
// Support: jQuery <1.8
function( elem, i, match ) {
return !!$.data( elem, match[ 3 ] );
}
} );
} ) );
;
/*!
* jQuery UI Keycode 1.12.1
* http://jqueryui.com
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*/
//>>label: Keycode
//>>group: Core
//>>description: Provide keycodes as keynames
//>>docs: http://api.jqueryui.com/jQuery.ui.keyCode/
( function( factory ) {
if ( typeof define === "function" && define.amd ) {
// AMD. Register as an anonymous module.
define( [ "jquery", "./version" ], factory );
} else {
// Browser globals
factory( jQuery );
}
} ( function( $ ) {
return $.ui.keyCode = {
BACKSPACE: 8,
COMMA: 188,
DELETE: 46,
DOWN: 40,
END: 35,
ENTER: 13,
ESCAPE: 27,
HOME: 36,
LEFT: 37,
PAGE_DOWN: 34,
PAGE_UP: 33,
PERIOD: 190,
RIGHT: 39,
SPACE: 32,
TAB: 9,
UP: 38
};
} ) );
;
/*!
* jQuery UI Unique ID 1.12.1
* http://jqueryui.com
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*/
//>>label: uniqueId
//>>group: Core
//>>description: Functions to generate and remove uniqueId's
//>>docs: http://api.jqueryui.com/uniqueId/
( function( factory ) {
if ( typeof define === "function" && define.amd ) {
// AMD. Register as an anonymous module.
define( [ "jquery", "./version" ], factory );
} else {
// Browser globals
factory( jQuery );
}
} ( function( $ ) {
return $.fn.extend( {
uniqueId: ( function() {
var uuid = 0;
return function() {
return this.each( function() {
if ( !this.id ) {
this.id = "ui-id-" + ( ++uuid );
}
} );
};
} )(),
removeUniqueId: function() {
return this.each( function() {
if ( /^ui-id-\d+$/.test( this.id ) ) {
$( this ).removeAttr( "id" );
}
} );
}
} );
} ) );
;
/*!
* jQuery UI Mouse 1.12.1
* http://jqueryui.com
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*/
//>>label: Mouse
//>>group: Widgets
//>>description: Abstracts mouse-based interactions to assist in creating certain widgets.
//>>docs: http://api.jqueryui.com/mouse/
( function( factory ) {
if ( typeof define === "function" && define.amd ) {
// AMD. Register as an anonymous module.
define( [
"jquery",
"../ie",
"../version",
"../widget"
], factory );
} else {
// Browser globals
factory( jQuery );
}
}( function( $ ) {
var mouseHandled = false;
$( document ).on( "mouseup", function() {
mouseHandled = false;
} );
return $.widget( "ui.mouse", {
version: "1.12.1",
options: {
cancel: "input, textarea, button, select, option",
distance: 1,
delay: 0
},
_mouseInit: function() {
var that = this;
this.element
.on( "mousedown." + this.widgetName, function( event ) {
return that._mouseDown( event );
} )
.on( "click." + this.widgetName, function( event ) {
if ( true === $.data( event.target, that.widgetName + ".preventClickEvent" ) ) {
$.removeData( event.target, that.widgetName + ".preventClickEvent" );
event.stopImmediatePropagation();
return false;
}
} );
this.started = false;
},
// TODO: make sure destroying one instance of mouse doesn't mess with
// other instances of mouse
_mouseDestroy: function() {
this.element.off( "." + this.widgetName );
if ( this._mouseMoveDelegate ) {
this.document
.off( "mousemove." + this.widgetName, this._mouseMoveDelegate )
.off( "mouseup." + this.widgetName, this._mouseUpDelegate );
}
},
_mouseDown: function( event ) {
// don't let more than one widget handle mouseStart
if ( mouseHandled ) {
return;
}
this._mouseMoved = false;
// We may have missed mouseup (out of window)
( this._mouseStarted && this._mouseUp( event ) );
this._mouseDownEvent = event;
var that = this,
btnIsLeft = ( event.which === 1 ),
// event.target.nodeName works around a bug in IE 8 with
// disabled inputs (#7620)
elIsCancel = ( typeof this.options.cancel === "string" && event.target.nodeName ?
$( event.target ).closest( this.options.cancel ).length : false );
if ( !btnIsLeft || elIsCancel || !this._mouseCapture( event ) ) {
return true;
}
this.mouseDelayMet = !this.options.delay;
if ( !this.mouseDelayMet ) {
this._mouseDelayTimer = setTimeout( function() {
that.mouseDelayMet = true;
}, this.options.delay );
}
if ( this._mouseDistanceMet( event ) && this._mouseDelayMet( event ) ) {
this._mouseStarted = ( this._mouseStart( event ) !== false );
if ( !this._mouseStarted ) {
event.preventDefault();
return true;
}
}
// Click event may never have fired (Gecko & Opera)
if ( true === $.data( event.target, this.widgetName + ".preventClickEvent" ) ) {
$.removeData( event.target, this.widgetName + ".preventClickEvent" );
}
// These delegates are required to keep context
this._mouseMoveDelegate = function( event ) {
return that._mouseMove( event );
};
this._mouseUpDelegate = function( event ) {
return that._mouseUp( event );
};
this.document
.on( "mousemove." + this.widgetName, this._mouseMoveDelegate )
.on( "mouseup." + this.widgetName, this._mouseUpDelegate );
event.preventDefault();
mouseHandled = true;
return true;
},
_mouseMove: function( event ) {
// Only check for mouseups outside the document if you've moved inside the document
// at least once. This prevents the firing of mouseup in the case of IE<9, which will
// fire a mousemove event if content is placed under the cursor. See #7778
// Support: IE <9
if ( this._mouseMoved ) {
// IE mouseup check - mouseup happened when mouse was out of window
if ( $.ui.ie && ( !document.documentMode || document.documentMode < 9 ) &&
!event.button ) {
return this._mouseUp( event );
// Iframe mouseup check - mouseup occurred in another document
} else if ( !event.which ) {
// Support: Safari <=8 - 9
// Safari sets which to 0 if you press any of the following keys
// during a drag (#14461)
if ( event.originalEvent.altKey || event.originalEvent.ctrlKey ||
event.originalEvent.metaKey || event.originalEvent.shiftKey ) {
this.ignoreMissingWhich = true;
} else if ( !this.ignoreMissingWhich ) {
return this._mouseUp( event );
}
}
}
if ( event.which || event.button ) {
this._mouseMoved = true;
}
if ( this._mouseStarted ) {
this._mouseDrag( event );
return event.preventDefault();
}
if ( this._mouseDistanceMet( event ) && this._mouseDelayMet( event ) ) {
this._mouseStarted =
( this._mouseStart( this._mouseDownEvent, event ) !== false );
( this._mouseStarted ? this._mouseDrag( event ) : this._mouseUp( event ) );
}
return !this._mouseStarted;
},
_mouseUp: function( event ) {
this.document
.off( "mousemove." + this.widgetName, this._mouseMoveDelegate )
.off( "mouseup." + this.widgetName, this._mouseUpDelegate );
if ( this._mouseStarted ) {
this._mouseStarted = false;
if ( event.target === this._mouseDownEvent.target ) {
$.data( event.target, this.widgetName + ".preventClickEvent", true );
}
this._mouseStop( event );
}
if ( this._mouseDelayTimer ) {
clearTimeout( this._mouseDelayTimer );
delete this._mouseDelayTimer;
}
this.ignoreMissingWhich = false;
mouseHandled = false;
event.preventDefault();
},
_mouseDistanceMet: function( event ) {
return ( Math.max(
Math.abs( this._mouseDownEvent.pageX - event.pageX ),
Math.abs( this._mouseDownEvent.pageY - event.pageY )
) >= this.options.distance
);
},
_mouseDelayMet: function( /* event */ ) {
return this.mouseDelayMet;
},
// These are placeholder methods, to be overriden by extending plugin
_mouseStart: function( /* event */ ) {},
_mouseDrag: function( /* event */ ) {},
_mouseStop: function( /* event */ ) {},
_mouseCapture: function( /* event */ ) { return true; }
} );
} ) );
;
/*!
* jQuery UI Draggable 1.12.1
* http://jqueryui.com
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*/
//>>label: Draggable
//>>group: Interactions
//>>description: Enables dragging functionality for any element.
//>>docs: http://api.jqueryui.com/draggable/
//>>demos: http://jqueryui.com/draggable/
//>>css.structure: ../../themes/base/draggable.css
( function( factory ) {
if ( typeof define === "function" && define.amd ) {
// AMD. Register as an anonymous module.
define( [
"jquery",
"./mouse",
"../data",
"../plugin",
"../safe-active-element",
"../safe-blur",
"../scroll-parent",
"../version",
"../widget"
], factory );
} else {
// Browser globals
factory( jQuery );
}
}( function( $ ) {
$.widget( "ui.draggable", $.ui.mouse, {
version: "1.12.1",
widgetEventPrefix: "drag",
options: {
addClasses: true,
appendTo: "parent",
axis: false,
connectToSortable: false,
containment: false,
cursor: "auto",
cursorAt: false,
grid: false,
handle: false,
helper: "original",
iframeFix: false,
opacity: false,
refreshPositions: false,
revert: false,
revertDuration: 500,
scope: "default",
scroll: true,
scrollSensitivity: 20,
scrollSpeed: 20,
snap: false,
snapMode: "both",
snapTolerance: 20,
stack: false,
zIndex: false,
// Callbacks
drag: null,
start: null,
stop: null
},
_create: function() {
if ( this.options.helper === "original" ) {
this._setPositionRelative();
}
if ( this.options.addClasses ) {
this._addClass( "ui-draggable" );
}
this._setHandleClassName();
this._mouseInit();
},
_setOption: function( key, value ) {
this._super( key, value );
if ( key === "handle" ) {
this._removeHandleClassName();
this._setHandleClassName();
}
},
_destroy: function() {
if ( ( this.helper || this.element ).is( ".ui-draggable-dragging" ) ) {
this.destroyOnClear = true;
return;
}
this._removeHandleClassName();
this._mouseDestroy();
},
_mouseCapture: function( event ) {
var o = this.options;
// Among others, prevent a drag on a resizable-handle
if ( this.helper || o.disabled ||
$( event.target ).closest( ".ui-resizable-handle" ).length > 0 ) {
return false;
}
//Quit if we're not on a valid handle
this.handle = this._getHandle( event );
if ( !this.handle ) {
return false;
}
this._blurActiveElement( event );
this._blockFrames( o.iframeFix === true ? "iframe" : o.iframeFix );
return true;
},
_blockFrames: function( selector ) {
this.iframeBlocks = this.document.find( selector ).map( function() {
var iframe = $( this );
return $( "<div>" )
.css( "position", "absolute" )
.appendTo( iframe.parent() )
.outerWidth( iframe.outerWidth() )
.outerHeight( iframe.outerHeight() )
.offset( iframe.offset() )[ 0 ];
} );
},
_unblockFrames: function() {
if ( this.iframeBlocks ) {
this.iframeBlocks.remove();
delete this.iframeBlocks;
}
},
_blurActiveElement: function( event ) {
var activeElement = $.ui.safeActiveElement( this.document[ 0 ] ),
target = $( event.target );
// Don't blur if the event occurred on an element that is within
// the currently focused element
// See #10527, #12472
if ( target.closest( activeElement ).length ) {
return;
}
// Blur any element that currently has focus, see #4261
$.ui.safeBlur( activeElement );
},
_mouseStart: function( event ) {
var o = this.options;
//Create and append the visible helper
this.helper = this._createHelper( event );
this._addClass( this.helper, "ui-draggable-dragging" );
//Cache the helper size
this._cacheHelperProportions();
//If ddmanager is used for droppables, set the global draggable
if ( $.ui.ddmanager ) {
$.ui.ddmanager.current = this;
}
/*
* - Position generation -
* This block generates everything position related - it's the core of draggables.
*/
//Cache the margins of the original element
this._cacheMargins();
//Store the helper's css position
this.cssPosition = this.helper.css( "position" );
this.scrollParent = this.helper.scrollParent( true );
this.offsetParent = this.helper.offsetParent();
this.hasFixedAncestor = this.helper.parents().filter( function() {
return $( this ).css( "position" ) === "fixed";
} ).length > 0;
//The element's absolute position on the page minus margins
this.positionAbs = this.element.offset();
this._refreshOffsets( event );
//Generate the original position
this.originalPosition = this.position = this._generatePosition( event, false );
this.originalPageX = event.pageX;
this.originalPageY = event.pageY;
//Adjust the mouse offset relative to the helper if "cursorAt" is supplied
( o.cursorAt && this._adjustOffsetFromHelper( o.cursorAt ) );
//Set a containment if given in the options
this._setContainment();
//Trigger event + callbacks
if ( this._trigger( "start", event ) === false ) {
this._clear();
return false;
}
//Recache the helper size
this._cacheHelperProportions();
//Prepare the droppable offsets
if ( $.ui.ddmanager && !o.dropBehaviour ) {
$.ui.ddmanager.prepareOffsets( this, event );
}
// Execute the drag once - this causes the helper not to be visible before getting its
// correct position
this._mouseDrag( event, true );
// If the ddmanager is used for droppables, inform the manager that dragging has started
// (see #5003)
if ( $.ui.ddmanager ) {
$.ui.ddmanager.dragStart( this, event );
}
return true;
},
_refreshOffsets: function( event ) {
this.offset = {
top: this.positionAbs.top - this.margins.top,
left: this.positionAbs.left - this.margins.left,
scroll: false,
parent: this._getParentOffset(),
relative: this._getRelativeOffset()
};
this.offset.click = {
left: event.pageX - this.offset.left,
top: event.pageY - this.offset.top
};
},
_mouseDrag: function( event, noPropagation ) {
// reset any necessary cached properties (see #5009)
if ( this.hasFixedAncestor ) {
this.offset.parent = this._getParentOffset();
}
//Compute the helpers position
this.position = this._generatePosition( event, true );
this.positionAbs = this._convertPositionTo( "absolute" );
//Call plugins and callbacks and use the resulting position if something is returned
if ( !noPropagation ) {
var ui = this._uiHash();
if ( this._trigger( "drag", event, ui ) === false ) {
this._mouseUp( new $.Event( "mouseup", event ) );
return false;
}
this.position = ui.position;
}
this.helper[ 0 ].style.left = this.position.left + "px";
this.helper[ 0 ].style.top = this.position.top + "px";
if ( $.ui.ddmanager ) {
$.ui.ddmanager.drag( this, event );
}
return false;
},
_mouseStop: function( event ) {
//If we are using droppables, inform the manager about the drop
var that = this,
dropped = false;
if ( $.ui.ddmanager && !this.options.dropBehaviour ) {
dropped = $.ui.ddmanager.drop( this, event );
}
//if a drop comes from outside (a sortable)
if ( this.dropped ) {
dropped = this.dropped;
this.dropped = false;
}
if ( ( this.options.revert === "invalid" && !dropped ) ||
( this.options.revert === "valid" && dropped ) ||
this.options.revert === true || ( $.isFunction( this.options.revert ) &&
this.options.revert.call( this.element, dropped ) )
) {
$( this.helper ).animate(
this.originalPosition,
parseInt( this.options.revertDuration, 10 ),
function() {
if ( that._trigger( "stop", event ) !== false ) {
that._clear();
}
}
);
} else {
if ( this._trigger( "stop", event ) !== false ) {
this._clear();
}
}
return false;
},
_mouseUp: function( event ) {
this._unblockFrames();
// If the ddmanager is used for droppables, inform the manager that dragging has stopped
// (see #5003)
if ( $.ui.ddmanager ) {
$.ui.ddmanager.dragStop( this, event );
}
// Only need to focus if the event occurred on the draggable itself, see #10527
if ( this.handleElement.is( event.target ) ) {
// The interaction is over; whether or not the click resulted in a drag,
// focus the element
this.element.trigger( "focus" );
}
return $.ui.mouse.prototype._mouseUp.call( this, event );
},
cancel: function() {
if ( this.helper.is( ".ui-draggable-dragging" ) ) {
this._mouseUp( new $.Event( "mouseup", { target: this.element[ 0 ] } ) );
} else {
this._clear();
}
return this;
},
_getHandle: function( event ) {
return this.options.handle ?
!!$( event.target ).closest( this.element.find( this.options.handle ) ).length :
true;
},
_setHandleClassName: function() {
this.handleElement = this.options.handle ?
this.element.find( this.options.handle ) : this.element;
this._addClass( this.handleElement, "ui-draggable-handle" );
},
_removeHandleClassName: function() {
this._removeClass( this.handleElement, "ui-draggable-handle" );
},
_createHelper: function( event ) {
var o = this.options,
helperIsFunction = $.isFunction( o.helper ),
helper = helperIsFunction ?
$( o.helper.apply( this.element[ 0 ], [ event ] ) ) :
( o.helper === "clone" ?
this.element.clone().removeAttr( "id" ) :
this.element );
if ( !helper.parents( "body" ).length ) {
helper.appendTo( ( o.appendTo === "parent" ?
this.element[ 0 ].parentNode :
o.appendTo ) );
}
// Http://bugs.jqueryui.com/ticket/9446
// a helper function can return the original element
// which wouldn't have been set to relative in _create
if ( helperIsFunction && helper[ 0 ] === this.element[ 0 ] ) {
this._setPositionRelative();
}
if ( helper[ 0 ] !== this.element[ 0 ] &&
!( /(fixed|absolute)/ ).test( helper.css( "position" ) ) ) {
helper.css( "position", "absolute" );
}
return helper;
},
_setPositionRelative: function() {
if ( !( /^(?:r|a|f)/ ).test( this.element.css( "position" ) ) ) {
this.element[ 0 ].style.position = "relative";
}
},
_adjustOffsetFromHelper: function( obj ) {
if ( typeof obj === "string" ) {
obj = obj.split( " " );
}
if ( $.isArray( obj ) ) {
obj = { left: +obj[ 0 ], top: +obj[ 1 ] || 0 };
}
if ( "left" in obj ) {
this.offset.click.left = obj.left + this.margins.left;
}
if ( "right" in obj ) {
this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left;
}
if ( "top" in obj ) {
this.offset.click.top = obj.top + this.margins.top;
}
if ( "bottom" in obj ) {
this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top;
}
},
_isRootNode: function( element ) {
return ( /(html|body)/i ).test( element.tagName ) || element === this.document[ 0 ];
},
_getParentOffset: function() {
//Get the offsetParent and cache its position
var po = this.offsetParent.offset(),
document = this.document[ 0 ];
// This is a special case where we need to modify a offset calculated on start, since the
// following happened:
// 1. The position of the helper is absolute, so it's position is calculated based on the
// next positioned parent
// 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't
// the document, which means that the scroll is included in the initial calculation of the
// offset of the parent, and never recalculated upon drag
if ( this.cssPosition === "absolute" && this.scrollParent[ 0 ] !== document &&
$.contains( this.scrollParent[ 0 ], this.offsetParent[ 0 ] ) ) {
po.left += this.scrollParent.scrollLeft();
po.top += this.scrollParent.scrollTop();
}
if ( this._isRootNode( this.offsetParent[ 0 ] ) ) {
po = { top: 0, left: 0 };
}
return {
top: po.top + ( parseInt( this.offsetParent.css( "borderTopWidth" ), 10 ) || 0 ),
left: po.left + ( parseInt( this.offsetParent.css( "borderLeftWidth" ), 10 ) || 0 )
};
},
_getRelativeOffset: function() {
if ( this.cssPosition !== "relative" ) {
return { top: 0, left: 0 };
}
var p = this.element.position(),
scrollIsRootNode = this._isRootNode( this.scrollParent[ 0 ] );
return {
top: p.top - ( parseInt( this.helper.css( "top" ), 10 ) || 0 ) +
( !scrollIsRootNode ? this.scrollParent.scrollTop() : 0 ),
left: p.left - ( parseInt( this.helper.css( "left" ), 10 ) || 0 ) +
( !scrollIsRootNode ? this.scrollParent.scrollLeft() : 0 )
};
},
_cacheMargins: function() {
this.margins = {
left: ( parseInt( this.element.css( "marginLeft" ), 10 ) || 0 ),
top: ( parseInt( this.element.css( "marginTop" ), 10 ) || 0 ),
right: ( parseInt( this.element.css( "marginRight" ), 10 ) || 0 ),
bottom: ( parseInt( this.element.css( "marginBottom" ), 10 ) || 0 )
};
},
_cacheHelperProportions: function() {
this.helperProportions = {
width: this.helper.outerWidth(),
height: this.helper.outerHeight()
};
},
_setContainment: function() {
var isUserScrollable, c, ce,
o = this.options,
document = this.document[ 0 ];
this.relativeContainer = null;
if ( !o.containment ) {
this.containment = null;
return;
}
if ( o.containment === "window" ) {
this.containment = [
$( window ).scrollLeft() - this.offset.relative.left - this.offset.parent.left,
$( window ).scrollTop() - this.offset.relative.top - this.offset.parent.top,
$( window ).scrollLeft() + $( window ).width() -
this.helperProportions.width - this.margins.left,
$( window ).scrollTop() +
( $( window ).height() || document.body.parentNode.scrollHeight ) -
this.helperProportions.height - this.margins.top
];
return;
}
if ( o.containment === "document" ) {
this.containment = [
0,
0,
$( document ).width() - this.helperProportions.width - this.margins.left,
( $( document ).height() || document.body.parentNode.scrollHeight ) -
this.helperProportions.height - this.margins.top
];
return;
}
if ( o.containment.constructor === Array ) {
this.containment = o.containment;
return;
}
if ( o.containment === "parent" ) {
o.containment = this.helper[ 0 ].parentNode;
}
c = $( o.containment );
ce = c[ 0 ];
if ( !ce ) {
return;
}
isUserScrollable = /(scroll|auto)/.test( c.css( "overflow" ) );
this.containment = [
( parseInt( c.css( "borderLeftWidth" ), 10 ) || 0 ) +
( parseInt( c.css( "paddingLeft" ), 10 ) || 0 ),
( parseInt( c.css( "borderTopWidth" ), 10 ) || 0 ) +
( parseInt( c.css( "paddingTop" ), 10 ) || 0 ),
( isUserScrollable ? Math.max( ce.scrollWidth, ce.offsetWidth ) : ce.offsetWidth ) -
( parseInt( c.css( "borderRightWidth" ), 10 ) || 0 ) -
( parseInt( c.css( "paddingRight" ), 10 ) || 0 ) -
this.helperProportions.width -
this.margins.left -
this.margins.right,
( isUserScrollable ? Math.max( ce.scrollHeight, ce.offsetHeight ) : ce.offsetHeight ) -
( parseInt( c.css( "borderBottomWidth" ), 10 ) || 0 ) -
( parseInt( c.css( "paddingBottom" ), 10 ) || 0 ) -
this.helperProportions.height -
this.margins.top -
this.margins.bottom
];
this.relativeContainer = c;
},
_convertPositionTo: function( d, pos ) {
if ( !pos ) {
pos = this.position;
}
var mod = d === "absolute" ? 1 : -1,
scrollIsRootNode = this._isRootNode( this.scrollParent[ 0 ] );
return {
top: (
// The absolute mouse position
pos.top +
// Only for relative positioned nodes: Relative offset from element to offset parent
this.offset.relative.top * mod +
// The offsetParent's offset without borders (offset + border)
this.offset.parent.top * mod -
( ( this.cssPosition === "fixed" ?
-this.offset.scroll.top :
( scrollIsRootNode ? 0 : this.offset.scroll.top ) ) * mod )
),
left: (
// The absolute mouse position
pos.left +
// Only for relative positioned nodes: Relative offset from element to offset parent
this.offset.relative.left * mod +
// The offsetParent's offset without borders (offset + border)
this.offset.parent.left * mod -
( ( this.cssPosition === "fixed" ?
-this.offset.scroll.left :
( scrollIsRootNode ? 0 : this.offset.scroll.left ) ) * mod )
)
};
},
_generatePosition: function( event, constrainPosition ) {
var containment, co, top, left,
o = this.options,
scrollIsRootNode = this._isRootNode( this.scrollParent[ 0 ] ),
pageX = event.pageX,
pageY = event.pageY;
// Cache the scroll
if ( !scrollIsRootNode || !this.offset.scroll ) {
this.offset.scroll = {
top: this.scrollParent.scrollTop(),
left: this.scrollParent.scrollLeft()
};
}
/*
* - Position constraining -
* Constrain the position to a mix of grid, containment.
*/
// If we are not dragging yet, we won't check for options
if ( constrainPosition ) {
if ( this.containment ) {
if ( this.relativeContainer ) {
co = this.relativeContainer.offset();
containment = [
this.containment[ 0 ] + co.left,
this.containment[ 1 ] + co.top,
this.containment[ 2 ] + co.left,
this.containment[ 3 ] + co.top
];
} else {
containment = this.containment;
}
if ( event.pageX - this.offset.click.left < containment[ 0 ] ) {
pageX = containment[ 0 ] + this.offset.click.left;
}
if ( event.pageY - this.offset.click.top < containment[ 1 ] ) {
pageY = containment[ 1 ] + this.offset.click.top;
}
if ( event.pageX - this.offset.click.left > containment[ 2 ] ) {
pageX = containment[ 2 ] + this.offset.click.left;
}
if ( event.pageY - this.offset.click.top > containment[ 3 ] ) {
pageY = containment[ 3 ] + this.offset.click.top;
}
}
if ( o.grid ) {
//Check for grid elements set to 0 to prevent divide by 0 error causing invalid
// argument errors in IE (see ticket #6950)
top = o.grid[ 1 ] ? this.originalPageY + Math.round( ( pageY -
this.originalPageY ) / o.grid[ 1 ] ) * o.grid[ 1 ] : this.originalPageY;
pageY = containment ? ( ( top - this.offset.click.top >= containment[ 1 ] ||
top - this.offset.click.top > containment[ 3 ] ) ?
top :
( ( top - this.offset.click.top >= containment[ 1 ] ) ?
top - o.grid[ 1 ] : top + o.grid[ 1 ] ) ) : top;
left = o.grid[ 0 ] ? this.originalPageX +
Math.round( ( pageX - this.originalPageX ) / o.grid[ 0 ] ) * o.grid[ 0 ] :
this.originalPageX;
pageX = containment ? ( ( left - this.offset.click.left >= containment[ 0 ] ||
left - this.offset.click.left > containment[ 2 ] ) ?
left :
( ( left - this.offset.click.left >= containment[ 0 ] ) ?
left - o.grid[ 0 ] : left + o.grid[ 0 ] ) ) : left;
}
if ( o.axis === "y" ) {
pageX = this.originalPageX;
}
if ( o.axis === "x" ) {
pageY = this.originalPageY;
}
}
return {
top: (
// The absolute mouse position
pageY -
// Click offset (relative to the element)
this.offset.click.top -
// Only for relative positioned nodes: Relative offset from element to offset parent
this.offset.relative.top -
// The offsetParent's offset without borders (offset + border)
this.offset.parent.top +
( this.cssPosition === "fixed" ?
-this.offset.scroll.top :
( scrollIsRootNode ? 0 : this.offset.scroll.top ) )
),
left: (
// The absolute mouse position
pageX -
// Click offset (relative to the element)
this.offset.click.left -
// Only for relative positioned nodes: Relative offset from element to offset parent
this.offset.relative.left -
// The offsetParent's offset without borders (offset + border)
this.offset.parent.left +
( this.cssPosition === "fixed" ?
-this.offset.scroll.left :
( scrollIsRootNode ? 0 : this.offset.scroll.left ) )
)
};
},
_clear: function() {
this._removeClass( this.helper, "ui-draggable-dragging" );
if ( this.helper[ 0 ] !== this.element[ 0 ] && !this.cancelHelperRemoval ) {
this.helper.remove();
}
this.helper = null;
this.cancelHelperRemoval = false;
if ( this.destroyOnClear ) {
this.destroy();
}
},
// From now on bulk stuff - mainly helpers
_trigger: function( type, event, ui ) {
ui = ui || this._uiHash();
$.ui.plugin.call( this, type, [ event, ui, this ], true );
// Absolute position and offset (see #6884 ) have to be recalculated after plugins
if ( /^(drag|start|stop)/.test( type ) ) {
this.positionAbs = this._convertPositionTo( "absolute" );
ui.offset = this.positionAbs;
}
return $.Widget.prototype._trigger.call( this, type, event, ui );
},
plugins: {},
_uiHash: function() {
return {
helper: this.helper,
position: this.position,
originalPosition: this.originalPosition,
offset: this.positionAbs
};
}
} );
$.ui.plugin.add( "draggable", "connectToSortable", {
start: function( event, ui, draggable ) {
var uiSortable = $.extend( {}, ui, {
item: draggable.element
} );
draggable.sortables = [];
$( draggable.options.connectToSortable ).each( function() {
var sortable = $( this ).sortable( "instance" );
if ( sortable && !sortable.options.disabled ) {
draggable.sortables.push( sortable );
// RefreshPositions is called at drag start to refresh the containerCache
// which is used in drag. This ensures it's initialized and synchronized
// with any changes that might have happened on the page since initialization.
sortable.refreshPositions();
sortable._trigger( "activate", event, uiSortable );
}
} );
},
stop: function( event, ui, draggable ) {
var uiSortable = $.extend( {}, ui, {
item: draggable.element
} );
draggable.cancelHelperRemoval = false;
$.each( draggable.sortables, function() {
var sortable = this;
if ( sortable.isOver ) {
sortable.isOver = 0;
// Allow this sortable to handle removing the helper
draggable.cancelHelperRemoval = true;
sortable.cancelHelperRemoval = false;
// Use _storedCSS To restore properties in the sortable,
// as this also handles revert (#9675) since the draggable
// may have modified them in unexpected ways (#8809)
sortable._storedCSS = {
position: sortable.placeholder.css( "position" ),
top: sortable.placeholder.css( "top" ),
left: sortable.placeholder.css( "left" )
};
sortable._mouseStop( event );
// Once drag has ended, the sortable should return to using
// its original helper, not the shared helper from draggable
sortable.options.helper = sortable.options._helper;
} else {
// Prevent this Sortable from removing the helper.
// However, don't set the draggable to remove the helper
// either as another connected Sortable may yet handle the removal.
sortable.cancelHelperRemoval = true;
sortable._trigger( "deactivate", event, uiSortable );
}
} );
},
drag: function( event, ui, draggable ) {
$.each( draggable.sortables, function() {
var innermostIntersecting = false,
sortable = this;
// Copy over variables that sortable's _intersectsWith uses
sortable.positionAbs = draggable.positionAbs;
sortable.helperProportions = draggable.helperProportions;
sortable.offset.click = draggable.offset.click;
if ( sortable._intersectsWith( sortable.containerCache ) ) {
innermostIntersecting = true;
$.each( draggable.sortables, function() {
// Copy over variables that sortable's _intersectsWith uses
this.positionAbs = draggable.positionAbs;
this.helperProportions = draggable.helperProportions;
this.offset.click = draggable.offset.click;
if ( this !== sortable &&
this._intersectsWith( this.containerCache ) &&
$.contains( sortable.element[ 0 ], this.element[ 0 ] ) ) {
innermostIntersecting = false;
}
return innermostIntersecting;
} );
}
if ( innermostIntersecting ) {
// If it intersects, we use a little isOver variable and set it once,
// so that the move-in stuff gets fired only once.
if ( !sortable.isOver ) {
sortable.isOver = 1;
// Store draggable's parent in case we need to reappend to it later.
draggable._parent = ui.helper.parent();
sortable.currentItem = ui.helper
.appendTo( sortable.element )
.data( "ui-sortable-item", true );
// Store helper option to later restore it
sortable.options._helper = sortable.options.helper;
sortable.options.helper = function() {
return ui.helper[ 0 ];
};
// Fire the start events of the sortable with our passed browser event,
// and our own helper (so it doesn't create a new one)
event.target = sortable.currentItem[ 0 ];
sortable._mouseCapture( event, true );
sortable._mouseStart( event, true, true );
// Because the browser event is way off the new appended portlet,
// modify necessary variables to reflect the changes
sortable.offset.click.top = draggable.offset.click.top;
sortable.offset.click.left = draggable.offset.click.left;
sortable.offset.parent.left -= draggable.offset.parent.left -
sortable.offset.parent.left;
sortable.offset.parent.top -= draggable.offset.parent.top -
sortable.offset.parent.top;
draggable._trigger( "toSortable", event );
// Inform draggable that the helper is in a valid drop zone,
// used solely in the revert option to handle "valid/invalid".
draggable.dropped = sortable.element;
// Need to refreshPositions of all sortables in the case that
// adding to one sortable changes the location of the other sortables (#9675)
$.each( draggable.sortables, function() {
this.refreshPositions();
} );
// Hack so receive/update callbacks work (mostly)
draggable.currentItem = draggable.element;
sortable.fromOutside = draggable;
}
if ( sortable.currentItem ) {
sortable._mouseDrag( event );
// Copy the sortable's position because the draggable's can potentially reflect
// a relative position, while sortable is always absolute, which the dragged
// element has now become. (#8809)
ui.position = sortable.position;
}
} else {
// If it doesn't intersect with the sortable, and it intersected before,
// we fake the drag stop of the sortable, but make sure it doesn't remove
// the helper by using cancelHelperRemoval.
if ( sortable.isOver ) {
sortable.isOver = 0;
sortable.cancelHelperRemoval = true;
// Calling sortable's mouseStop would trigger a revert,
// so revert must be temporarily false until after mouseStop is called.
sortable.options._revert = sortable.options.revert;
sortable.options.revert = false;
sortable._trigger( "out", event, sortable._uiHash( sortable ) );
sortable._mouseStop( event, true );
// Restore sortable behaviors that were modfied
// when the draggable entered the sortable area (#9481)
sortable.options.revert = sortable.options._revert;
sortable.options.helper = sortable.options._helper;
if ( sortable.placeholder ) {
sortable.placeholder.remove();
}
// Restore and recalculate the draggable's offset considering the sortable
// may have modified them in unexpected ways. (#8809, #10669)
ui.helper.appendTo( draggable._parent );
draggable._refreshOffsets( event );
ui.position = draggable._generatePosition( event, true );
draggable._trigger( "fromSortable", event );
// Inform draggable that the helper is no longer in a valid drop zone
draggable.dropped = false;
// Need to refreshPositions of all sortables just in case removing
// from one sortable changes the location of other sortables (#9675)
$.each( draggable.sortables, function() {
this.refreshPositions();
} );
}
}
} );
}
} );
$.ui.plugin.add( "draggable", "cursor", {
start: function( event, ui, instance ) {
var t = $( "body" ),
o = instance.options;
if ( t.css( "cursor" ) ) {
o._cursor = t.css( "cursor" );
}
t.css( "cursor", o.cursor );
},
stop: function( event, ui, instance ) {
var o = instance.options;
if ( o._cursor ) {
$( "body" ).css( "cursor", o._cursor );
}
}
} );
$.ui.plugin.add( "draggable", "opacity", {
start: function( event, ui, instance ) {
var t = $( ui.helper ),
o = instance.options;
if ( t.css( "opacity" ) ) {
o._opacity = t.css( "opacity" );
}
t.css( "opacity", o.opacity );
},
stop: function( event, ui, instance ) {
var o = instance.options;
if ( o._opacity ) {
$( ui.helper ).css( "opacity", o._opacity );
}
}
} );
$.ui.plugin.add( "draggable", "scroll", {
start: function( event, ui, i ) {
if ( !i.scrollParentNotHidden ) {
i.scrollParentNotHidden = i.helper.scrollParent( false );
}
if ( i.scrollParentNotHidden[ 0 ] !== i.document[ 0 ] &&
i.scrollParentNotHidden[ 0 ].tagName !== "HTML" ) {
i.overflowOffset = i.scrollParentNotHidden.offset();
}
},
drag: function( event, ui, i ) {
var o = i.options,
scrolled = false,
scrollParent = i.scrollParentNotHidden[ 0 ],
document = i.document[ 0 ];
if ( scrollParent !== document && scrollParent.tagName !== "HTML" ) {
if ( !o.axis || o.axis !== "x" ) {
if ( ( i.overflowOffset.top + scrollParent.offsetHeight ) - event.pageY <
o.scrollSensitivity ) {
scrollParent.scrollTop = scrolled = scrollParent.scrollTop + o.scrollSpeed;
} else if ( event.pageY - i.overflowOffset.top < o.scrollSensitivity ) {
scrollParent.scrollTop = scrolled = scrollParent.scrollTop - o.scrollSpeed;
}
}
if ( !o.axis || o.axis !== "y" ) {
if ( ( i.overflowOffset.left + scrollParent.offsetWidth ) - event.pageX <
o.scrollSensitivity ) {
scrollParent.scrollLeft = scrolled = scrollParent.scrollLeft + o.scrollSpeed;
} else if ( event.pageX - i.overflowOffset.left < o.scrollSensitivity ) {
scrollParent.scrollLeft = scrolled = scrollParent.scrollLeft - o.scrollSpeed;
}
}
} else {
if ( !o.axis || o.axis !== "x" ) {
if ( event.pageY - $( document ).scrollTop() < o.scrollSensitivity ) {
scrolled = $( document ).scrollTop( $( document ).scrollTop() - o.scrollSpeed );
} else if ( $( window ).height() - ( event.pageY - $( document ).scrollTop() ) <
o.scrollSensitivity ) {
scrolled = $( document ).scrollTop( $( document ).scrollTop() + o.scrollSpeed );
}
}
if ( !o.axis || o.axis !== "y" ) {
if ( event.pageX - $( document ).scrollLeft() < o.scrollSensitivity ) {
scrolled = $( document ).scrollLeft(
$( document ).scrollLeft() - o.scrollSpeed
);
} else if ( $( window ).width() - ( event.pageX - $( document ).scrollLeft() ) <
o.scrollSensitivity ) {
scrolled = $( document ).scrollLeft(
$( document ).scrollLeft() + o.scrollSpeed
);
}
}
}
if ( scrolled !== false && $.ui.ddmanager && !o.dropBehaviour ) {
$.ui.ddmanager.prepareOffsets( i, event );
}
}
} );
$.ui.plugin.add( "draggable", "snap", {
start: function( event, ui, i ) {
var o = i.options;
i.snapElements = [];
$( o.snap.constructor !== String ? ( o.snap.items || ":data(ui-draggable)" ) : o.snap )
.each( function() {
var $t = $( this ),
$o = $t.offset();
if ( this !== i.element[ 0 ] ) {
i.snapElements.push( {
item: this,
width: $t.outerWidth(), height: $t.outerHeight(),
top: $o.top, left: $o.left
} );
}
} );
},
drag: function( event, ui, inst ) {
var ts, bs, ls, rs, l, r, t, b, i, first,
o = inst.options,
d = o.snapTolerance,
x1 = ui.offset.left, x2 = x1 + inst.helperProportions.width,
y1 = ui.offset.top, y2 = y1 + inst.helperProportions.height;
for ( i = inst.snapElements.length - 1; i >= 0; i-- ) {
l = inst.snapElements[ i ].left - inst.margins.left;
r = l + inst.snapElements[ i ].width;
t = inst.snapElements[ i ].top - inst.margins.top;
b = t + inst.snapElements[ i ].height;
if ( x2 < l - d || x1 > r + d || y2 < t - d || y1 > b + d ||
!$.contains( inst.snapElements[ i ].item.ownerDocument,
inst.snapElements[ i ].item ) ) {
if ( inst.snapElements[ i ].snapping ) {
( inst.options.snap.release &&
inst.options.snap.release.call(
inst.element,
event,
$.extend( inst._uiHash(), { snapItem: inst.snapElements[ i ].item } )
) );
}
inst.snapElements[ i ].snapping = false;
continue;
}
if ( o.snapMode !== "inner" ) {
ts = Math.abs( t - y2 ) <= d;
bs = Math.abs( b - y1 ) <= d;
ls = Math.abs( l - x2 ) <= d;
rs = Math.abs( r - x1 ) <= d;
if ( ts ) {
ui.position.top = inst._convertPositionTo( "relative", {
top: t - inst.helperProportions.height,
left: 0
} ).top;
}
if ( bs ) {
ui.position.top = inst._convertPositionTo( "relative", {
top: b,
left: 0
} ).top;
}
if ( ls ) {
ui.position.left = inst._convertPositionTo( "relative", {
top: 0,
left: l - inst.helperProportions.width
} ).left;
}
if ( rs ) {
ui.position.left = inst._convertPositionTo( "relative", {
top: 0,
left: r
} ).left;
}
}
first = ( ts || bs || ls || rs );
if ( o.snapMode !== "outer" ) {
ts = Math.abs( t - y1 ) <= d;
bs = Math.abs( b - y2 ) <= d;
ls = Math.abs( l - x1 ) <= d;
rs = Math.abs( r - x2 ) <= d;
if ( ts ) {
ui.position.top = inst._convertPositionTo( "relative", {
top: t,
left: 0
} ).top;
}
if ( bs ) {
ui.position.top = inst._convertPositionTo( "relative", {
top: b - inst.helperProportions.height,
left: 0
} ).top;
}
if ( ls ) {
ui.position.left = inst._convertPositionTo( "relative", {
top: 0,
left: l
} ).left;
}
if ( rs ) {
ui.position.left = inst._convertPositionTo( "relative", {
top: 0,
left: r - inst.helperProportions.width
} ).left;
}
}
if ( !inst.snapElements[ i ].snapping && ( ts || bs || ls || rs || first ) ) {
( inst.options.snap.snap &&
inst.options.snap.snap.call(
inst.element,
event,
$.extend( inst._uiHash(), {
snapItem: inst.snapElements[ i ].item
} ) ) );
}
inst.snapElements[ i ].snapping = ( ts || bs || ls || rs || first );
}
}
} );
$.ui.plugin.add( "draggable", "stack", {
start: function( event, ui, instance ) {
var min,
o = instance.options,
group = $.makeArray( $( o.stack ) ).sort( function( a, b ) {
return ( parseInt( $( a ).css( "zIndex" ), 10 ) || 0 ) -
( parseInt( $( b ).css( "zIndex" ), 10 ) || 0 );
} );
if ( !group.length ) { return; }
min = parseInt( $( group[ 0 ] ).css( "zIndex" ), 10 ) || 0;
$( group ).each( function( i ) {
$( this ).css( "zIndex", min + i );
} );
this.css( "zIndex", ( min + group.length ) );
}
} );
$.ui.plugin.add( "draggable", "zIndex", {
start: function( event, ui, instance ) {
var t = $( ui.helper ),
o = instance.options;
if ( t.css( "zIndex" ) ) {
o._zIndex = t.css( "zIndex" );
}
t.css( "zIndex", o.zIndex );
},
stop: function( event, ui, instance ) {
var o = instance.options;
if ( o._zIndex ) {
$( ui.helper ).css( "zIndex", o._zIndex );
}
}
} );
return $.ui.draggable;
} ) );
;
/*!
* jQuery UI Tooltip 1.12.1
* http://jqueryui.com
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*/
//>>label: Tooltip
//>>group: Widgets
//>>description: Shows additional information for any element on hover or focus.
//>>docs: http://api.jqueryui.com/tooltip/
//>>demos: http://jqueryui.com/tooltip/
//>>css.structure: ../../themes/base/core.css
//>>css.structure: ../../themes/base/tooltip.css
//>>css.theme: ../../themes/base/theme.css
( function( factory ) {
if ( typeof define === "function" && define.amd ) {
// AMD. Register as an anonymous module.
define( [
"jquery",
"../keycode",
"../position",
"../unique-id",
"../version",
"../widget"
], factory );
} else {
// Browser globals
factory( jQuery );
}
}( function( $ ) {
$.widget( "ui.tooltip", {
version: "1.12.1",
options: {
classes: {
"ui-tooltip": "ui-corner-all ui-widget-shadow"
},
content: function() {
// support: IE<9, Opera in jQuery <1.7
// .text() can't accept undefined, so coerce to a string
var title = $( this ).attr( "title" ) || "";
// Escape title, since we're going from an attribute to raw HTML
return $( "<a>" ).text( title ).html();
},
hide: true,
// Disabled elements have inconsistent behavior across browsers (#8661)
items: "[title]:not([disabled])",
position: {
my: "left top+15",
at: "left bottom",
collision: "flipfit flip"
},
show: true,
track: false,
// Callbacks
close: null,
open: null
},
_addDescribedBy: function( elem, id ) {
var describedby = ( elem.attr( "aria-describedby" ) || "" ).split( /\s+/ );
describedby.push( id );
elem
.data( "ui-tooltip-id", id )
.attr( "aria-describedby", $.trim( describedby.join( " " ) ) );
},
_removeDescribedBy: function( elem ) {
var id = elem.data( "ui-tooltip-id" ),
describedby = ( elem.attr( "aria-describedby" ) || "" ).split( /\s+/ ),
index = $.inArray( id, describedby );
if ( index !== -1 ) {
describedby.splice( index, 1 );
}
elem.removeData( "ui-tooltip-id" );
describedby = $.trim( describedby.join( " " ) );
if ( describedby ) {
elem.attr( "aria-describedby", describedby );
} else {
elem.removeAttr( "aria-describedby" );
}
},
_create: function() {
this._on( {
mouseover: "open",
focusin: "open"
} );
// IDs of generated tooltips, needed for destroy
this.tooltips = {};
// IDs of parent tooltips where we removed the title attribute
this.parents = {};
// Append the aria-live region so tooltips announce correctly
this.liveRegion = $( "<div>" )
.attr( {
role: "log",
"aria-live": "assertive",
"aria-relevant": "additions"
} )
.appendTo( this.document[ 0 ].body );
this._addClass( this.liveRegion, null, "ui-helper-hidden-accessible" );
this.disabledTitles = $( [] );
},
_setOption: function( key, value ) {
var that = this;
this._super( key, value );
if ( key === "content" ) {
$.each( this.tooltips, function( id, tooltipData ) {
that._updateContent( tooltipData.element );
} );
}
},
_setOptionDisabled: function( value ) {
this[ value ? "_disable" : "_enable" ]();
},
_disable: function() {
var that = this;
// Close open tooltips
$.each( this.tooltips, function( id, tooltipData ) {
var event = $.Event( "blur" );
event.target = event.currentTarget = tooltipData.element[ 0 ];
that.close( event, true );
} );
// Remove title attributes to prevent native tooltips
this.disabledTitles = this.disabledTitles.add(
this.element.find( this.options.items ).addBack()
.filter( function() {
var element = $( this );
if ( element.is( "[title]" ) ) {
return element
.data( "ui-tooltip-title", element.attr( "title" ) )
.removeAttr( "title" );
}
} )
);
},
_enable: function() {
// restore title attributes
this.disabledTitles.each( function() {
var element = $( this );
if ( element.data( "ui-tooltip-title" ) ) {
element.attr( "title", element.data( "ui-tooltip-title" ) );
}
} );
this.disabledTitles = $( [] );
},
open: function( event ) {
var that = this,
target = $( event ? event.target : this.element )
// we need closest here due to mouseover bubbling,
// but always pointing at the same event target
.closest( this.options.items );
// No element to show a tooltip for or the tooltip is already open
if ( !target.length || target.data( "ui-tooltip-id" ) ) {
return;
}
if ( target.attr( "title" ) ) {
target.data( "ui-tooltip-title", target.attr( "title" ) );
}
target.data( "ui-tooltip-open", true );
// Kill parent tooltips, custom or native, for hover
if ( event && event.type === "mouseover" ) {
target.parents().each( function() {
var parent = $( this ),
blurEvent;
if ( parent.data( "ui-tooltip-open" ) ) {
blurEvent = $.Event( "blur" );
blurEvent.target = blurEvent.currentTarget = this;
that.close( blurEvent, true );
}
if ( parent.attr( "title" ) ) {
parent.uniqueId();
that.parents[ this.id ] = {
element: this,
title: parent.attr( "title" )
};
parent.attr( "title", "" );
}
} );
}
this._registerCloseHandlers( event, target );
this._updateContent( target, event );
},
_updateContent: function( target, event ) {
var content,
contentOption = this.options.content,
that = this,
eventType = event ? event.type : null;
if ( typeof contentOption === "string" || contentOption.nodeType ||
contentOption.jquery ) {
return this._open( event, target, contentOption );
}
content = contentOption.call( target[ 0 ], function( response ) {
// IE may instantly serve a cached response for ajax requests
// delay this call to _open so the other call to _open runs first
that._delay( function() {
// Ignore async response if tooltip was closed already
if ( !target.data( "ui-tooltip-open" ) ) {
return;
}
// JQuery creates a special event for focusin when it doesn't
// exist natively. To improve performance, the native event
// object is reused and the type is changed. Therefore, we can't
// rely on the type being correct after the event finished
// bubbling, so we set it back to the previous value. (#8740)
if ( event ) {
event.type = eventType;
}
this._open( event, target, response );
} );
} );
if ( content ) {
this._open( event, target, content );
}
},
_open: function( event, target, content ) {
var tooltipData, tooltip, delayedShow, a11yContent,
positionOption = $.extend( {}, this.options.position );
if ( !content ) {
return;
}
// Content can be updated multiple times. If the tooltip already
// exists, then just update the content and bail.
tooltipData = this._find( target );
if ( tooltipData ) {
tooltipData.tooltip.find( ".ui-tooltip-content" ).html( content );
return;
}
// If we have a title, clear it to prevent the native tooltip
// we have to check first to avoid defining a title if none exists
// (we don't want to cause an element to start matching [title])
//
// We use removeAttr only for key events, to allow IE to export the correct
// accessible attributes. For mouse events, set to empty string to avoid
// native tooltip showing up (happens only when removing inside mouseover).
if ( target.is( "[title]" ) ) {
if ( event && event.type === "mouseover" ) {
target.attr( "title", "" );
} else {
target.removeAttr( "title" );
}
}
tooltipData = this._tooltip( target );
tooltip = tooltipData.tooltip;
this._addDescribedBy( target, tooltip.attr( "id" ) );
tooltip.find( ".ui-tooltip-content" ).html( content );
// Support: Voiceover on OS X, JAWS on IE <= 9
// JAWS announces deletions even when aria-relevant="additions"
// Voiceover will sometimes re-read the entire log region's contents from the beginning
this.liveRegion.children().hide();
a11yContent = $( "<div>" ).html( tooltip.find( ".ui-tooltip-content" ).html() );
a11yContent.removeAttr( "name" ).find( "[name]" ).removeAttr( "name" );
a11yContent.removeAttr( "id" ).find( "[id]" ).removeAttr( "id" );
a11yContent.appendTo( this.liveRegion );
function position( event ) {
positionOption.of = event;
if ( tooltip.is( ":hidden" ) ) {
return;
}
tooltip.position( positionOption );
}
if ( this.options.track && event && /^mouse/.test( event.type ) ) {
this._on( this.document, {
mousemove: position
} );
// trigger once to override element-relative positioning
position( event );
} else {
tooltip.position( $.extend( {
of: target
}, this.options.position ) );
}
tooltip.hide();
this._show( tooltip, this.options.show );
// Handle tracking tooltips that are shown with a delay (#8644). As soon
// as the tooltip is visible, position the tooltip using the most recent
// event.
// Adds the check to add the timers only when both delay and track options are set (#14682)
if ( this.options.track && this.options.show && this.options.show.delay ) {
delayedShow = this.delayedShow = setInterval( function() {
if ( tooltip.is( ":visible" ) ) {
position( positionOption.of );
clearInterval( delayedShow );
}
}, $.fx.interval );
}
this._trigger( "open", event, { tooltip: tooltip } );
},
_registerCloseHandlers: function( event, target ) {
var events = {
keyup: function( event ) {
if ( event.keyCode === $.ui.keyCode.ESCAPE ) {
var fakeEvent = $.Event( event );
fakeEvent.currentTarget = target[ 0 ];
this.close( fakeEvent, true );
}
}
};
// Only bind remove handler for delegated targets. Non-delegated
// tooltips will handle this in destroy.
if ( target[ 0 ] !== this.element[ 0 ] ) {
events.remove = function() {
this._removeTooltip( this._find( target ).tooltip );
};
}
if ( !event || event.type === "mouseover" ) {
events.mouseleave = "close";
}
if ( !event || event.type === "focusin" ) {
events.focusout = "close";
}
this._on( true, target, events );
},
close: function( event ) {
var tooltip,
that = this,
target = $( event ? event.currentTarget : this.element ),
tooltipData = this._find( target );
// The tooltip may already be closed
if ( !tooltipData ) {
// We set ui-tooltip-open immediately upon open (in open()), but only set the
// additional data once there's actually content to show (in _open()). So even if the
// tooltip doesn't have full data, we always remove ui-tooltip-open in case we're in
// the period between open() and _open().
target.removeData( "ui-tooltip-open" );
return;
}
tooltip = tooltipData.tooltip;
// Disabling closes the tooltip, so we need to track when we're closing
// to avoid an infinite loop in case the tooltip becomes disabled on close
if ( tooltipData.closing ) {
return;
}
// Clear the interval for delayed tracking tooltips
clearInterval( this.delayedShow );
// Only set title if we had one before (see comment in _open())
// If the title attribute has changed since open(), don't restore
if ( target.data( "ui-tooltip-title" ) && !target.attr( "title" ) ) {
target.attr( "title", target.data( "ui-tooltip-title" ) );
}
this._removeDescribedBy( target );
tooltipData.hiding = true;
tooltip.stop( true );
this._hide( tooltip, this.options.hide, function() {
that._removeTooltip( $( this ) );
} );
target.removeData( "ui-tooltip-open" );
this._off( target, "mouseleave focusout keyup" );
// Remove 'remove' binding only on delegated targets
if ( target[ 0 ] !== this.element[ 0 ] ) {
this._off( target, "remove" );
}
this._off( this.document, "mousemove" );
if ( event && event.type === "mouseleave" ) {
$.each( this.parents, function( id, parent ) {
$( parent.element ).attr( "title", parent.title );
delete that.parents[ id ];
} );
}
tooltipData.closing = true;
this._trigger( "close", event, { tooltip: tooltip } );
if ( !tooltipData.hiding ) {
tooltipData.closing = false;
}
},
_tooltip: function( element ) {
var tooltip = $( "<div>" ).attr( "role", "tooltip" ),
content = $( "<div>" ).appendTo( tooltip ),
id = tooltip.uniqueId().attr( "id" );
this._addClass( content, "ui-tooltip-content" );
this._addClass( tooltip, "ui-tooltip", "ui-widget ui-widget-content" );
tooltip.appendTo( this._appendTo( element ) );
return this.tooltips[ id ] = {
element: element,
tooltip: tooltip
};
},
_find: function( target ) {
var id = target.data( "ui-tooltip-id" );
return id ? this.tooltips[ id ] : null;
},
_removeTooltip: function( tooltip ) {
tooltip.remove();
delete this.tooltips[ tooltip.attr( "id" ) ];
},
_appendTo: function( target ) {
var element = target.closest( ".ui-front, dialog" );
if ( !element.length ) {
element = this.document[ 0 ].body;
}
return element;
},
_destroy: function() {
var that = this;
// Close open tooltips
$.each( this.tooltips, function( id, tooltipData ) {
// Delegate to close method to handle common cleanup
var event = $.Event( "blur" ),
element = tooltipData.element;
event.target = event.currentTarget = element[ 0 ];
that.close( event, true );
// Remove immediately; destroying an open tooltip doesn't use the
// hide animation
$( "#" + id ).remove();
// Restore the title
if ( element.data( "ui-tooltip-title" ) ) {
// If the title attribute has changed since open(), don't restore
if ( !element.attr( "title" ) ) {
element.attr( "title", element.data( "ui-tooltip-title" ) );
}
element.removeData( "ui-tooltip-title" );
}
} );
this.liveRegion.remove();
}
} );
// DEPRECATED
// TODO: Switch return back to widget declaration at top of file when this is removed
if ( $.uiBackCompat !== false ) {
// Backcompat for tooltipClass option
$.widget( "ui.tooltip", $.ui.tooltip, {
options: {
tooltipClass: null
},
_tooltip: function() {
var tooltipData = this._superApply( arguments );
if ( this.options.tooltipClass ) {
tooltipData.tooltip.addClass( this.options.tooltipClass );
}
return tooltipData;
}
} );
}
return $.ui.tooltip;
} ) );
;
/*!
* 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
*
* Copyright The Infusion copyright holders
* See the AUTHORS.md file at the top-level directory of this distribution and at
* https://github.com/fluid-project/infusion/raw/master/AUTHORS.md
*/
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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) ? [] : {};
};
/** Determine whether the supplied object path exceeds the maximum strategy recursion depth of fluid.strategyRecursionBailout -
* if it does, fluid.fail will be issued with a diagnostic
* @param {String} funcName - The name of the function to appear in the diagnostic if issued
* @param {String[]} segs - The segments of the path that the strategy has reached
*/
fluid.testStrategyRecursion = function (funcName, segs) {
if (segs.length > fluid.strategyRecursionBailout) {
fluid.fail("Runaway recursion encountered in " + funcName + " - 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");
}
};
fluid.copyRecurse = function (tocopy, segs) {
fluid.testStrategyRecursion("fluid.copy", segs);
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 {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.
* @param {String[]} [segs] - Implementation-internal - path segments that recursion has reached.
* @return {Any} - The supplied argument, recursively frozen.
*/
fluid.freezeRecursive = function (tofreeze, segs) {
segs = segs || [];
fluid.testStrategyRecursion("fluid.freezeRecursive", segs);
if (fluid.isPlainObject(tofreeze)) {
fluid.each(tofreeze, function (value, key) {
segs.push(key);
fluid.freezeRecursive(value, segs);
segs.pop();
});
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 = environment;
var limit = segs.length - uncess;
for (var i = 0; i < limit; ++i) {
if (!root) {
return undefined;
}
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 {Object} 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 {Object} [config] - An optional configuration or environment structure which can customise the fetch operation
* @return {Any} 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.
* @return {Any} - The return value (if any) of the underlying function.
*/
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)
* @return {Any} - The return value from the invoked function.
*/
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 encoding relative positions of, e.g. listeners, transforms, options, in lists
fluid.extremePriority = 4e9; // around 2^32 - allows headroom of 21 fractional bits for sub-priorities
fluid.priorityTypes = {
first: -1,
last: 1,
before: 0,
after: 0
};
// TODO: This should be properly done with defaults blocks and a much more performant fluid.indexDefaults
fluid.extremalPriorities = {
// a built-in definition to allow test infrastructure "last" listeners to sort after all impl listeners, and authoring/debugging listeners to sort after those
// these are "priority intensities", and will be flipped for "first" listeners
none: 0,
testing: 10,
authoring: 20
};
// unsupported, NON-API function
// TODO: Note - no "fixedOnly = true" sites remain in the framework
fluid.parsePriorityConstraint = function (constraint, fixedOnly, site) {
var segs = constraint.split(":");
var type = segs[0];
var lookup = fluid.priorityTypes[type];
if (lookup === undefined) {
fluid.fail("Invalid constraint type in priority field " + constraint + ": the only supported values are " + fluid.keys(fluid.priorityTypes).join(", ") + " or numeric");
}
if (fixedOnly && lookup === 0) {
fluid.fail("Constraint type in priority field " + constraint + " is not supported in a " + site + " record - you must use either a numeric value or first, last");
}
return {
type: segs[0],
target: segs[1]
};
};
// unsupported, NON-API function
fluid.parsePriority = function (priority, count, fixedOnly, site) {
priority = priority || 0;
var togo = {
count: count || 0,
fixed: null,
constraint: null,
site: site
};
if (typeof(priority) === "number") {
togo.fixed = -priority;
} else {
togo.constraint = fluid.parsePriorityConstraint(priority, fixedOnly, site);
}
var multiplier = togo.constraint ? fluid.priorityTypes[togo.constraint.type] : 0;
if (multiplier !== 0) {
var target = togo.constraint.target || "none";
var extremal = fluid.extremalPriorities[target];
if (extremal === undefined) {
fluid.fail("Unrecognised extremal priority target " + target + ": the currently supported values are " + fluid.keys(fluid.extremalPriorities).join(", ") + ": register your value in fluid.extremalPriorities");
}
togo.fixed = multiplier * (fluid.extremePriority + extremal);
}
if (togo.fixed !== null) {
togo.fixed += togo.count / 1024; // use some fractional bits to encode count bias
}
return togo;
};
fluid.renderPriority = function (parsed) {
return parsed.constraint ? (parsed.constraint.target ? parsed.constraint.type + ":" + parsed.constraint.target : parsed.constraint.type ) : Math.floor(parsed.fixed);
};
// unsupported, NON-API function
fluid.compareByPriority = function (recA, recB) {
if (recA.priority.fixed !== null && recB.priority.fixed !== null) {
return recA.priority.fixed - recB.priority.fixed;
} else { // sort constraint records to the end
// relies on JavaScript boolean coercion rules (ECMA 9.3 toNumber)
return (recA.priority.fixed === null) - (recB.priority.fixed === null);
}
};
fluid.honourConstraint = function (array, firstConstraint, c) {
var constraint = array[c].priority.constraint;
var matchIndex = fluid.find(array, function (element, index) {
return element.namespace === constraint.target ? index : undefined;
}, -1);
if (matchIndex === -1) { // TODO: We should report an error during firing if this condition persists until then
return true;
} else if (matchIndex >= firstConstraint) {
return false;
} else {
var offset = constraint.type === "after" ? 1 : 0;
var target = matchIndex + offset;
var temp = array[c];
for (var shift = c; shift >= target; --shift) {
array[shift] = array[shift - 1];
}
array[target] = temp;
return true;
}
};
// unsupported, NON-API function
// Priorities accepted from users have higher numbers representing high priority (sort first) -
fluid.sortByPriority = function (array) {
fluid.stableSort(array, fluid.compareByPriority);
var firstConstraint = fluid.find(array, function (element, index) {
return element.priority.constraint && fluid.priorityTypes[element.priority.constraint.type] === 0 ? index : undefined;
}, array.length);
while (true) {
if (firstConstraint === array.length) {
return array;
}
var oldFirstConstraint = firstConstraint;
for (var c = firstConstraint; c < array.length; ++c) {
var applied = fluid.honourConstraint(array, firstConstraint, c);
if (applied) {
++firstConstraint;
}
}
if (firstConstraint === oldFirstConstraint) {
var holders = array.slice(firstConstraint);
fluid.fail("Could not find targets for any constraints in " + holders[0].priority.site + " ", holders, ": none of the targets (" + fluid.getMembers(holders, "priority.constraint.target").join(", ") +
") matched any namespaces of the elements in (", array.slice(0, firstConstraint), ") - this is caused by either an invalid or circular reference");
}
}
};
/** Parse a hash containing prioritised records (for example, as found in a ContextAwareness record) and return a sorted array of these records in priority order.
* @param {Object} records - A hash of key names to prioritised records. Each record may contain an member `namespace` - if it does not, the namespace will be taken from the
* record's key. It may also contain a `String` member `priority` encoding a priority with respect to these namespaces as document at http://docs.fluidproject.org/infusion/development/Priorities.html .
* @param {String} name - A human-readable name describing the supplied records, which will be incorporated into the message of any error encountered when resolving the priorities
* @return {Array} An array of the same elements supplied to `records`, sorted into priority order. The supplied argument `records` will not be modified.
*/
fluid.parsePriorityRecords = function (records, name) {
var array = fluid.hashToArray(records, "namespace", function (newElement, oldElement) {
$.extend(newElement, oldElement);
newElement.priority = fluid.parsePriority(oldElement.priority, 0, false, name);
});
fluid.sortByPriority(array);
return array;
};
fluid.event.identifyListener = function (listener, soft) {
if (typeof(listener) !== "string" && !listener.$$fluid_guid && !soft) {
listener.$$fluid_guid = fluid.allocateGuid();
}
return listener.$$fluid_guid;
};
// unsupported, NON-API function
fluid.event.impersonateListener = function (origListener, newListener) {
fluid.event.identifyListener(origListener);
newListener.$$fluid_guid = origListener.$$fluid_guid;
};
// unsupported, NON-API function
fluid.event.sortListeners = function (listeners) {
var togo = [];
fluid.each(listeners, function (oneNamespace) {
var headHard; // notify only the first listener with hard namespace - or else all if all are soft
for (var i = 0; i < oneNamespace.length; ++i) {
var thisListener = oneNamespace[i];
if (!thisListener.softNamespace && !headHard) {
headHard = thisListener;
}
}
if (headHard) {
togo.push(headHard);
} else {
togo = togo.concat(oneNamespace);
}
});
return fluid.sortByPriority(togo);
};
// unsupported, NON-API function
fluid.event.resolveListener = function (listener) {
var listenerName = listener.globalName || (typeof(listener) === "string" ? listener : null);
if (listenerName) {
var listenerFunc = fluid.getGlobalValue(listenerName);
if (!listenerFunc) {
fluid.fail("Unable to look up name " + listenerName + " as a global function");
} else {
listener = listenerFunc;
}
}
return listener;
};
/* Generate a name for a component for debugging purposes */
fluid.nameComponent = function (that) {
return that ? "component with typename " + that.typeName + " and id " + that.id : "[unknown component]";
};
fluid.event.nameEvent = function (that, eventName) {
return eventName + " of " + fluid.nameComponent(that);
};
/** Construct an "event firer" object which can be used to register and deregister
* listeners, to which "events" can be fired. These events consist of an arbitrary
* function signature. General documentation on the Fluid events system is at
* http://docs.fluidproject.org/infusion/development/InfusionEventSystem.html .
* @param {Object} options - A structure to configure this event firer. Supported fields:
* {String} name - a readable name for this firer to be used in diagnostics and debugging
* {Boolean} preventable - If <code>true</code> the return value of each handler will
* be checked for <code>false</code> in which case further listeners will be shortcircuited, and this
* will be the return value of fire()
* @return {Object} - The newly-created event firer.
*/
fluid.makeEventFirer = function (options) {
options = options || {};
var name = options.name || "<anonymous>";
var that;
var lazyInit = function () { // Lazy init function to economise on object references for events which are never listened to
// The authoritative list of all listeners, a hash indexed by namespace, looking up to a stack (array) of
// listener records in "burial order"
that.listeners = {};
// An index of all listeners by "id" - we should consider removing this since it is only used during removal
// and because that.listeners is a hash of stacks we can't really accelerate removal by much
that.byId = {};
// The "live" list of listeners which will be notified in order on any firing. Recomputed on any use of
// addListener/removeListener
that.sortedListeners = [];
// arguments after 3rd are not part of public API
// listener as Object is used only by ChangeApplier to tunnel path, segs, etc as part of its "spec"
/** Adds a listener to this event.
* @param {Function|String} listener - The listener function to be added, or a global name resolving to a function. The signature of the function is arbitrary and matches that sent to event.fire()
* @param {String} namespace - (Optional) A namespace for this listener. At most one listener with a particular namespace can be active on an event at one time. Removing successively added listeners with a particular
* namespace will expose previously added ones in a stack idiom
* @param {String|Number} priority - A priority for the listener relative to others, perhaps expressed with a constraint relative to the namespace of another - see
* http://docs.fluidproject.org/infusion/development/Priorities.html
* @param {String} softNamespace - An unsupported internal option that is not part of the public API.
* @param {String} listenerId - An unsupported internal option that is not part of the public API.
*/
that.addListener = function (listener, namespace, priority, softNamespace, listenerId) {
var record;
if (that.destroyed) {
fluid.fail("Cannot add listener to destroyed event firer " + that.name);
}
if (!listener) {
return;
}
if (fluid.isPlainObject(listener, true) && !fluid.isApplicable(listener)) {
record = listener;
listener = record.listener;
namespace = record.namespace;
priority = record.priority;
softNamespace = record.softNamespace;
listenerId = record.listenerId;
}
if (typeof(listener) === "string") {
listener = {globalName: listener};
}
var id = listenerId || fluid.event.identifyListener(listener);
namespace = namespace || id;
record = $.extend(record || {}, {
namespace: namespace,
listener: listener,
softNamespace: softNamespace,
listenerId: listenerId,
priority: fluid.parsePriority(priority, that.sortedListeners.length, false, "listeners")
});
that.byId[id] = record;
var thisListeners = (that.listeners[namespace] = fluid.makeArray(that.listeners[namespace]));
thisListeners[softNamespace ? "push" : "unshift"] (record);
that.sortedListeners = fluid.event.sortListeners(that.listeners);
};
that.addListener.apply(null, arguments);
};
that = {
eventId: fluid.allocateGuid(),
name: name,
ownerId: options.ownerId,
typeName: "fluid.event.firer",
destroy: function () {
that.destroyed = true;
},
addListener: function () {
lazyInit.apply(null, arguments);
},
/** Removes a listener previously registered with this event.
* @param {Function|String} toremove - Either the listener function, the namespace of a listener (in which case a previous listener with that namespace may be uncovered) or an id sent to the undocumented
* `listenerId` argument of `addListener
*/
// Can be supplied either listener, namespace, or id (which may match either listener function's guid or original listenerId argument)
removeListener: function (listener) {
if (!that.listeners) { return; }
var namespace, id, record;
if (typeof (listener) === "string") {
namespace = listener;
record = that.listeners[namespace];
if (!record) { // it was an id and not a namespace - take the namespace from its record later
id = namespace;
namespace = null;
}
}
else if (typeof(listener) === "function") {
id = fluid.event.identifyListener(listener, true);
if (!id) {
fluid.fail("Cannot remove unregistered listener function ", listener, " from event " + that.name);
}
}
var rec = that.byId[id];
var softNamespace = rec && rec.softNamespace;
namespace = namespace || (rec && rec.namespace) || id;
delete that.byId[id];
record = that.listeners[namespace];
if (record) {
if (softNamespace) {
fluid.remove_if(record, function (thisLis) {
return thisLis.listener.$$fluid_guid === id || thisLis.listenerId === id;
});
} else {
record.shift();
}
if (record.length === 0) {
delete that.listeners[namespace];
}
}
that.sortedListeners = fluid.event.sortListeners(that.listeners);
},
/* Fires this event to all listeners which are active. They will be notified in order of priority. The signature of this method is free. */
fire: function () {
var listeners = that.sortedListeners;
if (!listeners || that.destroyed) { return; }
for (var i = 0; i < listeners.length; ++i) {
var lisrec = listeners[i];
if (typeof(lisrec.listener) !== "function") {
lisrec.listener = fluid.event.resolveListener(lisrec.listener);
}
var listener = lisrec.listener;
var ret = listener.apply(null, arguments);
var value;
if (options.preventable && ret === false || that.destroyed) {
value = false;
}
if (value !== undefined) {
return value;
}
}
}
};
return that;
};
// unsupported, NON-API function
// Fires to an event which may not be instantiated (in which case no-op) - primary modern usage is to resolve FLUID-5904
fluid.fireEvent = function (component, eventName, args) {
var firer = component.events[eventName];
if (firer) {
firer.fire.apply(null, fluid.makeArray(args));
}
};
// unsupported, NON-API function
fluid.event.addListenerToFirer = function (firer, value, namespace, wrapper) {
wrapper = wrapper || fluid.identity;
if (fluid.isArrayable(value)) {
for (var i = 0; i < value.length; ++i) {
fluid.event.addListenerToFirer(firer, value[i], namespace, wrapper);
}
} else if (typeof (value) === "function" || typeof (value) === "string") {
wrapper(firer).addListener(value, namespace);
} else if (value && typeof (value) === "object") {
wrapper(firer).addListener(value.listener, namespace || value.namespace, value.priority, value.softNamespace, value.listenerId);
}
};
// unsupported, NON-API function - non-IOC passthrough
fluid.event.resolveListenerRecord = function (records) {
return { records: records };
};
fluid.expandImmediate = function (material) {
fluid.fail("fluid.expandImmediate could not be loaded - please include FluidIoC.js in order to operate IoC-driven event with descriptor " + material);
};
// unsupported, NON-API function
fluid.mergeListeners = function (that, events, listeners) {
fluid.each(listeners, function (value, key) {
var firer, namespace;
if (fluid.isIoCReference(key)) {
firer = fluid.expandImmediate(key, that);
if (!firer) {
fluid.fail("Error in listener record: key " + key + " could not be looked up to an event firer - did you miss out \"events.\" when referring to an event firer?");
}
} else {
var keydot = key.indexOf(".");
if (keydot !== -1) {
namespace = key.substring(keydot + 1);
key = key.substring(0, keydot);
}
if (!events[key]) {
fluid.fail("Listener registered for event " + key + " which is not defined for this component");
}
firer = events[key];
}
var record = fluid.event.resolveListenerRecord(value, that, key, namespace, true);
fluid.event.addListenerToFirer(firer, record.records, namespace, record.adderWrapper);
});
};
// unsupported, NON-API function
fluid.eventFromRecord = function (eventSpec, eventKey, that) {
var isIoCEvent = eventSpec && (typeof (eventSpec) !== "string" || fluid.isIoCReference(eventSpec));
var event;
if (isIoCEvent) {
if (!fluid.event.resolveEvent) {
fluid.fail("fluid.event.resolveEvent could not be loaded - please include FluidIoC.js in order to operate IoC-driven event with descriptor ",
eventSpec);
} else {
event = fluid.event.resolveEvent(that, eventKey, eventSpec);
}
} else {
event = fluid.makeEventFirer({
name: fluid.event.nameEvent(that, eventKey),
preventable: eventSpec === "preventable",
ownerId: that.id
});
}
return event;
};
// unsupported, NON-API function - this is patched from FluidIoC.js
fluid.instantiateFirers = function (that, options) {
fluid.each(options.events, function (eventSpec, eventKey) {
that.events[eventKey] = fluid.eventFromRecord(eventSpec, eventKey, that);
});
};
// unsupported, NON-API function
fluid.mergeListenerPolicy = function (target, source, key) {
if (typeof (key) !== "string") {
fluid.fail("Error in listeners declaration - the keys in this structure must resolve to event names - got " + key + " from ", source);
}
// cf. triage in mergeListeners
var hasNamespace = !fluid.isIoCReference(key) && key.indexOf(".") !== -1;
return hasNamespace ? (source || target) : fluid.arrayConcatPolicy(target, source);
};
// unsupported, NON-API function
fluid.makeMergeListenersPolicy = function (merger, modelRelay) {
return function (target, source) {
target = target || {};
if (modelRelay && (fluid.isArrayable(source) || typeof(source.target) === "string")) { // This form allowed for modelRelay
target[""] = merger(target[""], source, "");
} else {
fluid.each(source, function (listeners, key) {
target[key] = merger(target[key], listeners, key);
});
}
return target;
};
};
fluid.validateListenersImplemented = function (that) {
var errors = [];
fluid.each(that.events, function (event, name) {
fluid.each(event.sortedListeners, function (lisrec) {
if (lisrec.listener === fluid.notImplemented || lisrec.listener.globalName === "fluid.notImplemented") {
errors.push({name: name, namespace: lisrec.namespace, componentSource: fluid.model.getSimple(that.options.listeners, [name + "." + lisrec.namespace, 0, "componentSource"])});
}
});
});
return errors;
};
/* Removes duplicated and empty elements from an already sorted array. */
fluid.unique = function (array) {
return fluid.remove_if(array, function (element, i) {
return !element || i > 0 && element === array[i - 1];
});
};
fluid.arrayConcatPolicy = function (target, source) {
return fluid.makeArray(target).concat(fluid.makeArray(source));
};
/*** FLUID LOGGING SYSTEM ***/
// This event represents the process of resolving the action of a request to fluid.log. Each listener shares
// access to an array, shallow-copied from the original arguments list to fluid.log, which is assumed writeable
// and which they may splice, transform, etc. before it is dispatched to the listener with namespace "log" which
// actually performs the logging action
fluid.loggingEvent = fluid.makeEventFirer({name: "logging event"});
fluid.addTimestampArg = function (args) {
var arg0 = fluid.renderTimestamp(new Date()) + ": ";
args.unshift(arg0);
};
fluid.loggingEvent.addListener(fluid.doBrowserLog, "log");
// Not intended to be overridden - just a positional placeholder so that the priority of
// actions filtering the log arguments before dispatching may be referred to it
fluid.loggingEvent.addListener(fluid.identity, "filterArgs", "before:log");
fluid.loggingEvent.addListener(fluid.addTimestampArg, "addTimestampArg", "after:filterArgs");
/*** FLUID ERROR SYSTEM ***/
fluid.failureEvent = fluid.makeEventFirer({name: "failure event"});
fluid.failureEvent.addListener(fluid.builtinFail, "fail");
fluid.failureEvent.addListener(fluid.logFailure, "log", "before:fail");
/**
* Configure the behaviour of fluid.fail by pushing or popping a disposition record onto a stack.
* @param {Number|Function} condition - Supply either a function, which will be called with two arguments, args (the complete arguments to
* fluid.fail) and activity, an array of strings describing the current framework invocation state.
* Or, the argument may be the number <code>-1</code> indicating that the previously supplied disposition should
* be popped off the stack
*/
fluid.pushSoftFailure = function (condition) {
if (typeof (condition) === "function") {
fluid.failureEvent.addListener(condition, "fail");
} else if (condition === -1) {
fluid.failureEvent.removeListener("fail");
} else if (typeof(condition) === "boolean") {
fluid.fail("pushSoftFailure with boolean value is no longer supported");
}
};
/*** DEFAULTS AND OPTIONS MERGING SYSTEM ***/
// A function to tag the types of all Fluid components
fluid.componentConstructor = function () {};
/** Create a "type tag" component with no state but simply a type name and id. The most
* minimal form of Fluid component */
// No longer a publically supported function - we don't abolish this because it is too annoying to prevent
// circularity during the bootup of the IoC system if we try to construct full components before it is complete
// unsupported, non-API function
fluid.typeTag = function (name) {
var that = Object.create(fluid.componentConstructor.prototype);
that.typeName = name;
that.id = fluid.allocateGuid();
return that;
};
var gradeTick = 1; // tick counter for managing grade cache invalidation
var gradeTickStore = {};
fluid.defaultsStore = {};
// unsupported, NON-API function
// Recursively builds up "gradeStructure" in first argument. 2nd arg receives gradeNames to be resolved, with stronger grades at right (defaults order)
// builds up gradeStructure.gradeChain pushed from strongest to weakest (reverse defaults order)
fluid.resolveGradesImpl = function (gs, gradeNames) {
gradeNames = fluid.makeArray(gradeNames);
for (var i = gradeNames.length - 1; i >= 0; --i) { // from stronger to weaker
var gradeName = gradeNames[i];
if (gradeName && !gs.gradeHash[gradeName]) {
var isDynamic = fluid.isIoCReference(gradeName);
var options = (isDynamic ? null : fluid.rawDefaults(gradeName)) || {};
var thisTick = gradeTickStore[gradeName] || (gradeTick - 1); // a nonexistent grade is recorded as just previous to current
gs.lastTick = Math.max(gs.lastTick, thisTick);
gs.gradeHash[gradeName] = true;
gs.gradeChain.push(gradeName);
var oGradeNames = fluid.makeArray(options.gradeNames);
for (var j = oGradeNames.length - 1; j >= 0; --j) { // from stronger to weaker grades
// TODO: in future, perhaps restore mergedDefaultsCache function of storing resolved gradeNames for bare grades
fluid.resolveGradesImpl(gs, oGradeNames[j]);
}
}
}
return gs;
};
// unsupported, NON-API function
fluid.resolveGradeStructure = function (defaultName, gradeNames) {
var gradeStruct = {
lastTick: 0,
gradeChain: [],
gradeHash: {}
};
// stronger grades appear to the right in defaults - dynamic grades are stronger still - FLUID-5085
// we supply these to resolveGradesImpl with strong grades at the right
fluid.resolveGradesImpl(gradeStruct, [defaultName].concat(fluid.makeArray(gradeNames)));
gradeStruct.gradeChain.reverse(); // reverse into defaults order
return gradeStruct;
};
fluid.hasGrade = function (options, gradeName) {
return !options || !options.gradeNames ? false : fluid.contains(options.gradeNames, gradeName);
};
// unsupported, NON-API function
fluid.resolveGrade = function (defaults, defaultName, gradeNames) {
var gradeStruct = fluid.resolveGradeStructure(defaultName, gradeNames);
// TODO: Fault in the merging algorithm does not actually treat arguments as immutable - failure in FLUID-5082 tests
// due to listeners mergePolicy
var mergeArgs = fluid.transform(gradeStruct.gradeChain, fluid.rawDefaults, fluid.copy);
fluid.remove_if(mergeArgs, function (options) {
return !options;
});
var mergePolicy = {};
for (var i = 0; i < mergeArgs.length; ++i) {
if (mergeArgs[i] && mergeArgs[i].mergePolicy) {
mergePolicy = $.extend(true, mergePolicy, mergeArgs[i].mergePolicy);
}
}
mergeArgs = [mergePolicy, {}].concat(mergeArgs);
var mergedDefaults = fluid.merge.apply(null, mergeArgs);
mergedDefaults.gradeNames = gradeStruct.gradeChain; // replace these since mergePolicy version is inadequate
fluid.freezeRecursive(mergedDefaults);
return {defaults: mergedDefaults, lastTick: gradeStruct.lastTick};
};
fluid.mergedDefaultsCache = {};
// unsupported, NON-API function
fluid.gradeNamesToKey = function (defaultName, gradeNames) {
return defaultName + "|" + gradeNames.join("|");
};
// unsupported, NON-API function
// The main entry point to acquire the fully merged defaults for a combination of defaults plus mixin grades - from FluidIoC.js as well as recursively within itself
fluid.getMergedDefaults = function (defaultName, gradeNames) {
gradeNames = fluid.makeArray(gradeNames);
var key = fluid.gradeNamesToKey(defaultName, gradeNames);
var mergedDefaults = fluid.mergedDefaultsCache[key];
if (mergedDefaults) {
var lastTick = 0; // check if cache should be invalidated through real latest tick being later than the one stored
var searchGrades = mergedDefaults.defaults.gradeNames || [];
for (var i = 0; i < searchGrades.length; ++i) {
lastTick = Math.max(lastTick, gradeTickStore[searchGrades[i]] || 0);
}
if (lastTick > mergedDefaults.lastTick) {
if (fluid.passLogLevel(fluid.logLevel.TRACE)) {
fluid.log(fluid.logLevel.TRACE, "Clearing cache for component " + defaultName + " with gradeNames ", searchGrades);
}
mergedDefaults = null;
}
}
if (!mergedDefaults) {
var defaults = fluid.rawDefaults(defaultName);
if (!defaults) {
return defaults;
}
mergedDefaults = fluid.mergedDefaultsCache[key] = fluid.resolveGrade(defaults, defaultName, gradeNames);
}
return mergedDefaults.defaults;
};
// unsupported, NON-API function
/** Upgrades an element of an IoC record which designates a function to prepare for a {func, args} representation.
* @param {Any} rec - If the record is of a primitive type,
* @param {String} key - The key in the returned record to hold the function, this will default to `funcName` if `rec` is a `string` *not*
* holding an IoC reference, or `func` otherwise
* @return {Object} The original `rec` if it was not of primitive type, else a record holding { key : rec } if it was of primitive type.
*/
fluid.upgradePrimitiveFunc = function (rec, key) {
if (rec && fluid.isPrimitive(rec)) {
var togo = {};
togo[key || (typeof(rec) === "string" && rec.charAt(0) !== "{" ? "funcName" : "func")] = rec;
togo.args = fluid.NO_VALUE;
return togo;
} else {
return rec;
}
};
// unsupported, NON-API function
// Modify supplied options record to include "componentSource" annotation required by FLUID-5082
// TODO: This function really needs to act recursively in order to catch listeners registered for subcomponents - fix with FLUID-5614
fluid.annotateListeners = function (componentName, options) {
options.listeners = fluid.transform(options.listeners, function (record) {
var togo = fluid.makeArray(record);
return fluid.transform(togo, function (onerec) {
onerec = fluid.upgradePrimitiveFunc(onerec, "listener");
onerec.componentSource = componentName;
return onerec;
});
});
options.invokers = fluid.transform(options.invokers, function (record) {
record = fluid.upgradePrimitiveFunc(record);
if (record) {
record.componentSource = componentName;
}
return record;
});
};
// unsupported, NON-API function
fluid.rawDefaults = function (componentName) {
var entry = fluid.defaultsStore[componentName];
return entry && entry.options;
};
// unsupported, NON-API function
fluid.registerRawDefaults = function (componentName, options) {
fluid.pushActivity("registerRawDefaults", "registering defaults for grade %componentName with options %options",
{componentName: componentName, options: options});
var optionsCopy = fluid.expandCompact ? fluid.expandCompact(options) : fluid.copy(options);
fluid.annotateListeners(componentName, optionsCopy);
var callerInfo = fluid.getCallerInfo && fluid.getCallerInfo(6);
fluid.defaultsStore[componentName] = {
options: optionsCopy,
callerInfo: callerInfo
};
gradeTickStore[componentName] = gradeTick++;
fluid.popActivity();
};
// unsupported, NON-API function
fluid.doIndexDefaults = function (defaultName, defaults, index, indexSpec) {
var requiredGrades = fluid.makeArray(indexSpec.gradeNames);
for (var i = 0; i < requiredGrades.length; ++i) {
if (!fluid.hasGrade(defaults, requiredGrades[i])) { return; }
}
var indexFunc = typeof(indexSpec.indexFunc) === "function" ? indexSpec.indexFunc : fluid.getGlobalValue(indexSpec.indexFunc);
var keys = indexFunc(defaults) || [];
for (var j = 0; j < keys.length; ++j) {
fluid.pushArray(index, keys[j], defaultName);
}
};
/** Evaluates an index specification over all the defaults records registered into the system.
* @param {String} indexName - The name of this index record (currently ignored)
* @param {Object} indexSpec - Specification of the index to be performed - fields:
* gradeNames: {String|String[]} List of grades that must be matched by this indexer
* indexFunc: {String|Function} An index function which accepts a defaults record and returns an array of keys
* @return A structure indexing keys to arrays of matched gradenames
*/
// The expectation is that this function is extremely rarely used with respect to registration of defaults
// in the system, so currently we do not make any attempts to cache the results. The field "indexName" is
// supplied in case a future implementation chooses to implement caching
fluid.indexDefaults = function (indexName, indexSpec) {
var index = {};
for (var defaultName in fluid.defaultsStore) {
var defaults = fluid.getMergedDefaults(defaultName);
fluid.doIndexDefaults(defaultName, defaults, index, indexSpec);
}
return index;
};
/**
* Retrieves and stores a grade's configuration centrally.
* @param {String} componentName - The name of the grade whose options are to be read or written
* @param {Object} [options] - An (optional) object containing the options to be set
* @return {Object|undefined} - If `options` is omitted, returns the defaults for `componentName`. Otherwise,
* creates an instance of the named component with the supplied options.
*/
fluid.defaults = function (componentName, options) {
if (options === undefined) {
return fluid.getMergedDefaults(componentName);
}
else {
if (options && options.options) {
fluid.fail("Probable error in options structure for " + componentName +
" with option named \"options\" - perhaps you meant to write these options at top level in fluid.defaults? - ", options);
}
fluid.registerRawDefaults(componentName, options);
var gradedDefaults = fluid.getMergedDefaults(componentName);
if (!fluid.hasGrade(gradedDefaults, "fluid.function")) {
fluid.makeComponentCreator(componentName);
}
}
};
fluid.makeComponentCreator = function (componentName) {
var creator = function () {
var defaults = fluid.getMergedDefaults(componentName);
if (!defaults.gradeNames || defaults.gradeNames.length === 0) {
fluid.fail("Cannot make component creator for type " + componentName + " which does not have any gradeNames defined");
} else if (!defaults.initFunction) {
var blankGrades = [];
for (var i = 0; i < defaults.gradeNames.length; ++i) {
var gradeName = defaults.gradeNames[i];
var rawDefaults = fluid.rawDefaults(gradeName);
if (!rawDefaults) {
blankGrades.push(gradeName);
}
}
if (blankGrades.length === 0) {
fluid.fail("Cannot make component creator for type " + componentName + " which does not have an initFunction defined");
} else {
fluid.fail("The grade hierarchy of component with type " + componentName + " is incomplete - it inherits from the following grade(s): " +
blankGrades.join(", ") + " for which the grade definitions are corrupt or missing. Please check the files which might include these " +
"grades and ensure they are readable and have been loaded by this instance of Infusion");
}
} else {
return fluid.initComponent(componentName, arguments);
}
};
var existing = fluid.getGlobalValue(componentName);
if (existing) {
$.extend(creator, existing);
}
fluid.setGlobalValue(componentName, creator);
};
fluid.emptyPolicy = fluid.freezeRecursive({});
// unsupported, NON-API function
fluid.derefMergePolicy = function (policy) {
return (policy ? policy["*"] : fluid.emptyPolicy) || fluid.emptyPolicy;
};
// unsupported, NON-API function
fluid.compileMergePolicy = function (mergePolicy) {
var builtins = {}, defaultValues = {};
var togo = {builtins: builtins, defaultValues: defaultValues};
if (!mergePolicy) {
return togo;
}
fluid.each(mergePolicy, function (value, key) {
var parsed = {}, builtin = true;
if (typeof(value) === "function") {
parsed.func = value;
}
else if (typeof(value) === "object") {
parsed = value;
}
else if (!fluid.isDefaultValueMergePolicy(value)) {
var split = value.split(/\s*,\s*/);
for (var i = 0; i < split.length; ++i) {
parsed[split[i]] = true;
}
}
else {
// Convert to ginger self-reference - NB, this can only be parsed by IoC
fluid.set(defaultValues, key, "{that}.options." + value);
togo.hasDefaults = true;
builtin = false;
}
if (builtin) {
fluid.set(builtins, fluid.composePath(key, "*"), parsed);
}
});
return togo;
};
// TODO: deprecate this method of detecting default value merge policies before 1.6 in favour of
// explicit typed records a la ModelTransformations
// unsupported, NON-API function
fluid.isDefaultValueMergePolicy = function (policy) {
return typeof(policy) === "string" &&
(policy.indexOf(",") === -1 && !/replace|nomerge|noexpand/.test(policy));
};
// unsupported, NON-API function
fluid.mergeOneImpl = function (thisTarget, thisSource, j, sources, newPolicy, i, segs) {
var togo = thisTarget;
var primitiveTarget = fluid.isPrimitive(thisTarget);
if (thisSource !== undefined) {
if (!newPolicy.func && thisSource !== null && fluid.isPlainObject(thisSource) && !newPolicy.nomerge) {
if (primitiveTarget) {
togo = thisTarget = fluid.freshContainer(thisSource);
}
// recursion is now external? We can't do it from here since sources are not all known
// options.recurse(thisTarget, i + 1, segs, sources, newPolicyHolder, options);
} else {
sources[j] = undefined;
if (newPolicy.func) {
togo = newPolicy.func.call(null, thisTarget, thisSource, segs[i - 1], segs, i); // NB - change in this mostly unused argument
} else {
togo = thisSource;
}
}
}
return togo;
};
// NB - same quadratic worry about these as in FluidIoC in the case the RHS trundler is live -
// since at each regeneration step driving the RHS we are discarding the "cursor arguments" these
// would have to be regenerated at each step - although in practice this can only happen once for
// each object for all time, since after first resolution it will be concrete.
function regenerateCursor(source, segs, limit, sourceStrategy) {
for (var i = 0; i < limit; ++i) {
source = sourceStrategy(source, segs[i], i, fluid.makeArray(segs)); // copy for FLUID-5243
}
return source;
}
function regenerateSources(sources, segs, limit, sourceStrategies) {
var togo = [];
for (var i = 0; i < sources.length; ++i) {
var thisSource = regenerateCursor(sources[i], segs, limit, sourceStrategies[i]);
if (thisSource !== undefined) {
togo.push(thisSource);
}
}
return togo;
}
// unsupported, NON-API function
fluid.fetchMergeChildren = function (target, i, segs, sources, mergePolicy, options) {
var thisPolicy = fluid.derefMergePolicy(mergePolicy);
for (var j = sources.length - 1; j >= 0; --j) { // this direction now irrelevant - control is in the strategy
var source = sources[j];
// NB - this detection relies on strategy return being complete objects - which they are
// although we need to set up the roots separately. We need to START the process of evaluating each
// object root (sources) COMPLETELY, before we even begin! Even if the effect of this is to cause a
// dispatch into ourselves almost immediately. We can do this because we can take control over our
// TARGET objects and construct them early. Even if there is a self-dispatch, it will be fine since it is
// DIRECTED and so will not trouble our "slow" detection of properties. After all self-dispatches end, control
// will THEN return to "evaluation of arguments" (expander blocks) and only then FINALLY to this "slow"
// traversal of concrete properties to do the final merge.
if (source !== undefined) {
fluid.each(source, function (newSource, name) {
var childPolicy = fluid.concreteTrundler(mergePolicy, name);
// 2nd arm of condition is an Outrageous bodge to fix FLUID-4930 further. See fluid.tests.retrunking in FluidIoCTests.js
// We make extra use of the old "evaluateFully" flag and ensure to flood any trunk objects again during final "initter" phase of merging.
// The problem is that a custom mergePolicy may have replaced the system generated trunk with a differently structured object which we must not
// corrupt. This work should properly be done with a set of dedicated provenance/progress records in a separate structure
if (!(name in target) || (options.evaluateFully && childPolicy === undefined && !fluid.isPrimitive(target[name]))) { // only request each new target key once -- all sources will be queried per strategy
segs[i] = name;
options.strategy(target, name, i + 1, segs, sources, mergePolicy);
}
});
if (thisPolicy.replace) { // this branch primarily deals with a policy of replace at the root
break;
}
}
}
return target;
};
// A special marker object which will be placed at a current evaluation point in the tree in order
// to protect against circular evaluation
fluid.inEvaluationMarker = Object.freeze({"__CURRENTLY_IN_EVALUATION__": true});
// A path depth above which the core "process strategies" will bail out, assuming that the
// structure has become circularly linked. Helpful in environments such as Firebug which will
// kill the browser process if they happen to be open when a stack overflow occurs. Also provides
// a more helpful diagnostic.
fluid.strategyRecursionBailout = 50;
// unsupported, NON-API function
fluid.makeMergeStrategy = function (options) {
var strategy = function (target, name, i, segs, sources, policy) {
if (i > fluid.strategyRecursionBailout) {
fluid.fail("Overflow/circularity in options merging, current path is ", segs, " at depth " , i, " - please protect components from merging using the \"nomerge\" merge policy");
}
if (fluid.isPrimitive(target)) { // For "use strict"
return undefined; // Review this after FLUID-4925 since the only trigger is in slow component lookahead
}
if (fluid.isTracing) {
fluid.tracing.pathCount.push(fluid.path(segs.slice(0, i)));
}
var oldTarget;
if (name in target) { // bail out if our work has already been done
oldTarget = target[name];
if (!options.evaluateFully) { // see notes on this hack in "initter" - early attempt to deal with FLUID-4930
return oldTarget;
}
}
else {
if (target !== fluid.inEvaluationMarker) { // TODO: blatant "coding to the test" - this enables the simplest "re-trunking" in
// FluidIoCTests to function. In practice, we need to throw away this implementation entirely in favour of the
// "iterative deepening" model coming with FLUID-4925
target[name] = fluid.inEvaluationMarker;
}
}
if (sources === undefined) { // recover our state in case this is an external entry point
segs = fluid.makeArray(segs); // avoid trashing caller's segs
sources = regenerateSources(options.sources, segs, i - 1, options.sourceStrategies);
policy = regenerateCursor(options.mergePolicy, segs, i - 1, fluid.concreteTrundler);
}
var newPolicyHolder = fluid.concreteTrundler(policy, name);
var newPolicy = fluid.derefMergePolicy(newPolicyHolder);
var start, limit, mul;
if (newPolicy.replace) {
start = 1 - sources.length; limit = 0; mul = -1;
}
else {
start = 0; limit = sources.length - 1; mul = +1;
}
var newSources = [];
var thisTarget;
for (var j = start; j <= limit; ++j) { // TODO: try to economise on this array and on gaps
var k = mul * j;
var thisSource = options.sourceStrategies[k](sources[k], name, i, segs); // Run the RH algorithm in "driving" mode
if (thisSource !== undefined) {
if (!fluid.isPrimitive(thisSource)) {
newSources[k] = thisSource;
}
if (oldTarget === undefined) {
if (mul === -1) { // if we are going backwards, it is "replace"
thisTarget = target[name] = thisSource;
break;
}
else {
// write this in early, since early expansions may generate a trunk object which is written in to by later ones
thisTarget = fluid.mergeOneImpl(thisTarget, thisSource, j, newSources, newPolicy, i, segs, options);
if (target !== fluid.inEvaluationMarker) {
target[name] = thisTarget;
}
}
}
}
}
if (oldTarget !== undefined) {
thisTarget = oldTarget;
}
if (newSources.length > 0) {
if (fluid.isPlainObject(thisTarget)) {
fluid.fetchMergeChildren(thisTarget, i, segs, newSources, newPolicyHolder, options);
}
}
if (oldTarget === undefined && newSources.length === 0) {
delete target[name]; // remove the evaluation marker - nothing to evaluate
}
return thisTarget;
};
options.strategy = strategy;
return strategy;
};
// A simple stand-in for "fluid.get" where the material is covered by a single strategy
fluid.driveStrategy = function (root, pathSegs, strategy) {
pathSegs = fluid.makeArray(pathSegs);
for (var i = 0; i < pathSegs.length; ++i) {
if (!root) {
return undefined;
}
root = strategy(root, pathSegs[i], i + 1, pathSegs);
}
return root;
};
// A very simple "new inner trundler" that just performs concrete property access
// Note that every "strategy" is also a "trundler" of this type, considering just the first two arguments
fluid.concreteTrundler = function (source, seg) {
return !source ? undefined : source[seg];
};
/** Merge a collection of options structures onto a target, following an optional policy.
* This method is now used only for the purpose of merging "dead" option documents in order to
* cache graded component defaults. Component option merging is now performed by the
* fluid.makeMergeOptions pathway which sets up a deferred merging process. This function
* will not be removed in the Fluid 2.0 release but it is recommended that users not call it
* directly.
* The behaviour of this function is explained more fully on
* the page http://wiki.fluidproject.org/display/fluid/Options+Merging+for+Fluid+Components .
* @param {Object|String} policy - A "policy object" specifiying the type of merge to be performed.
* If policy is of type {String} it should take on the value "replace" representing
* a static policy. If it is an
* Object, it should contain a mapping of EL paths onto these String values, representing a
* fine-grained policy. If it is an Object, the values may also themselves be EL paths
* representing that a default value is to be taken from that path.
* @param {...Object} options1, options2, .... - an arbitrary list of options structure which are to
* be merged together. These will not be modified.
*/
fluid.merge = function (policy /*, ... sources */) {
var sources = Array.prototype.slice.call(arguments, 1);
var compiled = fluid.compileMergePolicy(policy).builtins;
var options = fluid.makeMergeOptions(compiled, sources, {});
options.initter();
return options.target;
};
// unsupported, NON-API function
fluid.simpleGingerBlock = function (source, recordType) {
var block = {
target: source,
simple: true,
strategy: fluid.concreteTrundler,
initter: fluid.identity,
recordType: recordType,
priority: fluid.mergeRecordTypes[recordType]
};
return block;
};
// unsupported, NON-API function
fluid.makeMergeOptions = function (policy, sources, userOptions) {
// note - we close over the supplied policy as a shared object reference - it will be updated during discovery
var options = {
mergePolicy: policy,
sources: sources
};
options = $.extend(options, userOptions);
options.target = options.target || fluid.freshContainer(options.sources[0]);
options.sourceStrategies = options.sourceStrategies || fluid.generate(options.sources.length, fluid.concreteTrundler);
options.initter = function () {
// This hack is necessary to ensure that the FINAL evaluation doesn't balk when discovering a trunk path which was already
// visited during self-driving via the expander. This bi-modality is sort of rubbish, but we currently don't have "room"
// in the strategy API to express when full evaluation is required - and the "flooding API" is not standardised. See FLUID-4930
options.evaluateFully = true;
fluid.fetchMergeChildren(options.target, 0, [], options.sources, options.mergePolicy, options);
};
fluid.makeMergeStrategy(options);
return options;
};
// unsupported, NON-API function
fluid.transformOptions = function (options, transRec) {
fluid.expect("Options transformation record", transRec, ["transformer", "config"]);
var transFunc = fluid.getGlobalValue(transRec.transformer);
return transFunc.call(null, options, transRec.config);
};
// unsupported, NON-API function
fluid.findMergeBlocks = function (mergeBlocks, recordType) {
return fluid.remove_if(fluid.makeArray(mergeBlocks), function (block) { return block.recordType !== recordType; });
};
// unsupported, NON-API function
fluid.transformOptionsBlocks = function (mergeBlocks, transformOptions, recordTypes) {
fluid.each(recordTypes, function (recordType) {
var blocks = fluid.findMergeBlocks(mergeBlocks, recordType);
fluid.each(blocks, function (block) {
var source = block.source ? "source" : "target"; // TODO: Problem here with irregular presentation of options which consist of a reference in their entirety
block[block.simple || source === "target" ? "target" : "source"] = fluid.transformOptions(block[source], transformOptions);
});
});
};
// unsupported, NON-API function
fluid.dedupeDistributionNamespaces = function (mergeBlocks) { // to implement FLUID-5824
var byNamespace = {};
fluid.remove_if(mergeBlocks, function (mergeBlock) {
var ns = mergeBlock.namespace;
if (ns) {
if (byNamespace[ns] && byNamespace[ns] !== mergeBlock.contextThat.id) { // source check for FLUID-5835
return true;
} else {
byNamespace[ns] = mergeBlock.contextThat.id;
}
}
});
};
// unsupported, NON-API function
fluid.deliverOptionsStrategy = fluid.identity;
fluid.computeComponentAccessor = fluid.identity;
fluid.computeDynamicComponents = fluid.identity;
// The types of merge record the system supports, with the weakest records first
fluid.mergeRecordTypes = {
defaults: 1000,
defaultValueMerge: 900,
subcomponentRecord: 800,
user: 700,
distribution: 100 // and above
};
// Utility used in the framework (primarily with distribution assembly), unconnected with new ChangeApplier
// unsupported, NON-API function
fluid.model.applyChangeRequest = function (model, request) {
var segs = request.segs;
if (segs.length === 0) {
if (request.type === "ADD") {
$.extend(true, model, request.value);
} else {
fluid.clear(model);
}
} else if (request.type === "ADD") {
fluid.model.setSimple(model, request.segs, request.value);
} else {
for (var i = 0; i < segs.length - 1; ++i) {
model = model[segs[i]];
if (!model) {
return;
}
}
var last = segs[segs.length - 1];
delete model[last];
}
};
/** Delete the value in the supplied object held at the specified path
* @param {Object} target - The object holding the value to be deleted (possibly empty)
* @param {String[]} segs - the path of the value to be deleted
*/
// unsupported, NON-API function
fluid.destroyValue = function (target, segs) {
if (target) {
fluid.model.applyChangeRequest(target, {type: "DELETE", segs: segs});
}
};
/**
* Merges the component's declared defaults, as obtained from fluid.defaults(),
* with the user's specified overrides.
*
* @param {Object} that - the instance to attach the options to
* @param {String} componentName - the unique "name" of the component, which will be used
* to fetch the default options from store. By recommendation, this should be the global
* name of the component's creator function.
* @param {Object} userOptions - the user-specified configuration options for this component
*/
// unsupported, NON-API function
fluid.mergeComponentOptions = function (that, componentName, userOptions, localOptions) {
var rawDefaults = fluid.rawDefaults(componentName);
var defaults = fluid.getMergedDefaults(componentName, rawDefaults && rawDefaults.gradeNames ? null : localOptions.gradeNames);
var sharedMergePolicy = {};
var mergeBlocks = [];
if (fluid.expandComponentOptions) {
mergeBlocks = mergeBlocks.concat(fluid.expandComponentOptions(sharedMergePolicy, defaults, userOptions, that));
}
else {
mergeBlocks = mergeBlocks.concat([fluid.simpleGingerBlock(defaults, "defaults"),
fluid.simpleGingerBlock(userOptions, "user")]);
}
var options = {}; // ultimate target
var sourceStrategies = [], sources = [];
var baseMergeOptions = {
target: options,
sourceStrategies: sourceStrategies
};
// Called both from here and from IoC whenever there is a change of block content or arguments which
// requires them to be resorted and rebound
var updateBlocks = function () {
fluid.each(mergeBlocks, function (block) {
if (fluid.isPrimitive(block.priority)) {
block.priority = fluid.parsePriority(block.priority, 0, false, "options distribution");
}
});
fluid.sortByPriority(mergeBlocks);
fluid.dedupeDistributionNamespaces(mergeBlocks);
sourceStrategies.length = 0;
sources.length = 0;
fluid.each(mergeBlocks, function (block) {
sourceStrategies.push(block.strategy);
sources.push(block.target);
});
};
updateBlocks();
var mergeOptions = fluid.makeMergeOptions(sharedMergePolicy, sources, baseMergeOptions);
mergeOptions.mergeBlocks = mergeBlocks;
mergeOptions.updateBlocks = updateBlocks;
mergeOptions.destroyValue = function (segs) { // This method is a temporary hack to assist FLUID-5091
for (var i = 0; i < mergeBlocks.length; ++i) {
if (!mergeBlocks[i].immutableTarget) {
fluid.destroyValue(mergeBlocks[i].target, segs);
}
}
fluid.destroyValue(baseMergeOptions.target, segs);
};
var compiledPolicy;
var mergePolicy;
function computeMergePolicy() {
// Decode the now available mergePolicy
mergePolicy = fluid.driveStrategy(options, "mergePolicy", mergeOptions.strategy);
mergePolicy = $.extend({}, fluid.rootMergePolicy, mergePolicy);
compiledPolicy = fluid.compileMergePolicy(mergePolicy);
// TODO: expandComponentOptions has already put some builtins here - performance implications of the now huge
// default mergePolicy material need to be investigated as well as this deep merge
$.extend(true, sharedMergePolicy, compiledPolicy.builtins); // ensure it gets broadcast to all sharers
}
computeMergePolicy();
mergeOptions.computeMergePolicy = computeMergePolicy;
if (compiledPolicy.hasDefaults) {
if (fluid.generateExpandBlock) {
mergeBlocks.push(fluid.generateExpandBlock({
options: compiledPolicy.defaultValues,
recordType: "defaultValueMerge",
priority: fluid.mergeRecordTypes.defaultValueMerge
}, that, {}));
updateBlocks();
}
else {
fluid.fail("Cannot operate mergePolicy ", mergePolicy, " for component ", that, " without including FluidIoC.js");
}
}
that.options = options;
fluid.driveStrategy(options, "gradeNames", mergeOptions.strategy);
fluid.deliverOptionsStrategy(that, options, mergeOptions); // do this early to broadcast and receive "distributeOptions"
fluid.computeComponentAccessor(that, userOptions && userOptions.localRecord);
var transformOptions = fluid.driveStrategy(options, "transformOptions", mergeOptions.strategy);
if (transformOptions) {
fluid.transformOptionsBlocks(mergeBlocks, transformOptions, ["user", "subcomponentRecord"]);
updateBlocks(); // because the possibly simple blocks may have changed target
}
if (!baseMergeOptions.target.mergePolicy) {
computeMergePolicy();
}
return mergeOptions;
};
// The Fluid Component System proper
// The base system grade definitions
fluid.defaults("fluid.function", {});
/** Invoke a global function by name and named arguments. A courtesy to allow declaratively encoded function calls
* to use named arguments rather than bare arrays.
* @param {String} name - A global name which can be resolved to a Function. The defaults for this name must
* resolve onto a grade including "fluid.function". The defaults record should also contain an entry
* <code>argumentMap</code>, a hash of argument names onto indexes.
* @param {Object} spec - A named hash holding the argument values to be sent to the function. These will be looked
* up in the <code>argumentMap</code> and resolved into a flat list of arguments.
* @return {Any} The return value from the function
*/
fluid.invokeGradedFunction = function (name, spec) {
var defaults = fluid.defaults(name);
if (!defaults || !defaults.argumentMap || !fluid.hasGrade(defaults, "fluid.function")) {
fluid.fail("Cannot look up name " + name +
" to a function with registered argumentMap - got defaults ", defaults);
}
var args = [];
fluid.each(defaults.argumentMap, function (value, key) {
args[value] = spec[key];
});
return fluid.invokeGlobalFunction(name, args);
};
fluid.noNamespaceDistributionPrefix = "no-namespace-distribution-";
fluid.mergeOneDistribution = function (target, source, key) {
var namespace = source.namespace || key || fluid.noNamespaceDistributionPrefix + fluid.allocateGuid();
source.namespace = namespace;
target[namespace] = $.extend(true, {}, target[namespace], source);
};
fluid.distributeOptionsPolicy = function (target, source) {
target = target || {};
if (fluid.isArrayable(source)) {
for (var i = 0; i < source.length; ++i) {
fluid.mergeOneDistribution(target, source[i]);
}
} else if (typeof(source.target) === "string") {
fluid.mergeOneDistribution(target, source);
} else {
fluid.each(source, function (oneSource, key) {
fluid.mergeOneDistribution(target, oneSource, key);
});
}
return target;
};
fluid.mergingArray = function () {};
fluid.mergingArray.prototype = [];
// Defer all evaluation of all nested members to resolve FLUID-5668
fluid.membersMergePolicy = function (target, source) {
target = target || {};
fluid.each(source, function (oneSource, key) {
if (!target[key]) {
target[key] = new fluid.mergingArray();
}
if (oneSource instanceof fluid.mergingArray) {
target[key].push.apply(target[key], oneSource);
} else if (oneSource !== undefined) {
target[key].push(oneSource);
}
});
return target;
};
fluid.invokerStrategies = fluid.arrayToHash(["func", "funcName", "listener", "this", "method", "changePath", "value"]);
// Resolve FLUID-5741, FLUID-5184 by ensuring that we avoid mixing incompatible invoker strategies
fluid.invokersMergePolicy = function (target, source) {
target = target || {};
fluid.each(source, function (oneInvoker, name) {
if (!oneInvoker) {
target[name] = oneInvoker;
return;
} else {
oneInvoker = fluid.upgradePrimitiveFunc(oneInvoker);
}
var oneT = target[name];
if (!oneT) {
oneT = target[name] = {};
}
for (var key in fluid.invokerStrategies) {
if (key in oneInvoker) {
for (var key2 in fluid.invokerStrategies) {
oneT[key2] = undefined; // can't delete since stupid driveStrategy bug from recordStrategy reinstates them
}
}
}
$.extend(oneT, oneInvoker);
});
return target;
};
fluid.rootMergePolicy = {
gradeNames: fluid.arrayConcatPolicy,
distributeOptions: fluid.distributeOptionsPolicy,
members: {
noexpand: true,
func: fluid.membersMergePolicy
},
invokers: {
noexpand: true,
func: fluid.invokersMergePolicy
},
transformOptions: "replace",
listeners: fluid.makeMergeListenersPolicy(fluid.mergeListenerPolicy)
};
fluid.defaults("fluid.component", {
initFunction: "fluid.initLittleComponent",
mergePolicy: fluid.rootMergePolicy,
argumentMap: {
options: 0
},
events: { // Three standard lifecycle points common to all components
onCreate: null,
onDestroy: null,
afterDestroy: null
}
});
fluid.defaults("fluid.emptySubcomponent", {
gradeNames: ["fluid.component"]
});
/* Compute a "nickname" given a fully qualified typename, by returning the last path
* segment.
*/
fluid.computeNickName = function (typeName) {
var segs = fluid.model.parseEL(typeName);
return segs[segs.length - 1];
};
/** A specially recognised grade tag which directs the IoC framework to instantiate this component first amongst
* its set of siblings, since it is likely to bear a context-forming type name. This will be removed from the framework
* once we have implemented FLUID-4925 "wave of explosions" */
fluid.defaults("fluid.typeFount", {
gradeNames: ["fluid.component"]
});
/**
* Creates a new "little component": a that-ist object with options merged into it by the framework.
* This method is a convenience for creating small objects that have options but don't require full
* View-like features such as the DOM Binder or events
*
* @param {Object} name - The name of the little component to create
* @param {Object} options - User-supplied options to merge with the defaults
*/
// NOTE: the 3rd argument localOptions is NOT to be advertised as part of the stable API, it is present
// just to allow backward compatibility whilst grade specifications are not mandatory - similarly for 4th arg "receiver"
// NOTE historical name to avoid confusion with fluid.initComponent below - this will all be refactored with FLUID-4925
fluid.initLittleComponent = function (name, userOptions, localOptions, receiver) {
var that = fluid.typeTag(name);
that.lifecycleStatus = "constructing";
localOptions = localOptions || {gradeNames: "fluid.component"};
that.destroy = fluid.makeRootDestroy(that); // overwritten by FluidIoC for constructed subcomponents
var mergeOptions = fluid.mergeComponentOptions(that, name, userOptions, localOptions);
mergeOptions.exceptions = {members: {model: true, modelRelay: true}}; // don't evaluate these in "early flooding" - they must be fetched explicitly
var options = that.options;
that.events = {};
// deliver to a non-IoC side early receiver of the component (currently only initView)
(receiver || fluid.identity)(that, options, mergeOptions.strategy);
fluid.computeDynamicComponents(that, mergeOptions);
// TODO: ****THIS**** is the point we must deliver and suspend!! Construct the "component skeleton" first, and then continue
// for as long as we can continue to find components.
for (var i = 0; i < mergeOptions.mergeBlocks.length; ++i) {
mergeOptions.mergeBlocks[i].initter();
}
mergeOptions.initter();
delete options.mergePolicy;
fluid.instantiateFirers(that, options);
fluid.mergeListeners(that, that.events, options.listeners);
return that;
};
fluid.diagnoseFailedView = fluid.identity;
// unsupported, NON-API function
fluid.makeRootDestroy = function (that) {
return function () {
fluid.doDestroy(that);
fluid.fireEvent(that, "afterDestroy", [that, "", null]);
};
};
/* Returns <code>true</code> if the supplied reference holds a component which has been destroyed */
fluid.isDestroyed = function (that) {
return that.lifecycleStatus === "destroyed";
};
// unsupported, NON-API function
fluid.doDestroy = function (that, name, parent) {
fluid.fireEvent(that, "onDestroy", [that, name || "", parent]);
that.lifecycleStatus = "destroyed";
for (var key in that.events) {
if (key !== "afterDestroy" && typeof(that.events[key].destroy) === "function") {
that.events[key].destroy();
}
}
if (that.applier) { // TODO: Break this out into the grade's destroyer
that.applier.destroy();
}
};
// unsupported, NON-API function
fluid.initComponent = function (componentName, initArgs) {
var options = fluid.defaults(componentName);
if (!options.gradeNames) {
fluid.fail("Cannot initialise component " + componentName + " which has no gradeName registered");
}
var args = [componentName].concat(fluid.makeArray(initArgs));
var that;
fluid.pushActivity("initComponent", "constructing component of type %componentName with arguments %initArgs",
{componentName: componentName, initArgs: initArgs});
that = fluid.invokeGlobalFunction(options.initFunction, args);
fluid.diagnoseFailedView(componentName, that, options, args);
if (fluid.initDependents) {
fluid.initDependents(that);
}
var errors = fluid.validateListenersImplemented(that);
if (errors.length > 0) {
fluid.fail(fluid.transform(errors, function (error) {
return ["Error constructing component ", that, " - the listener for event " + error.name + " with namespace " + error.namespace + (
(error.componentSource ? " which was defined in grade " + error.componentSource : "") + " needs to be overridden with a concrete implementation")];
})).join("\n");
}
if (that.lifecycleStatus === "constructing") {
that.lifecycleStatus = "constructed";
}
that.events.onCreate.fire(that);
fluid.popActivity();
return that;
};
// unsupported, NON-API function
fluid.initSubcomponentImpl = function (that, entry, args) {
var togo;
if (typeof (entry) !== "function") {
var entryType = typeof (entry) === "string" ? entry : entry.type;
togo = entryType === "fluid.emptySubcomponent" ?
null : fluid.invokeGlobalFunction(entryType, args);
} else {
togo = entry.apply(null, args);
}
return togo;
};
// ******* SELECTOR ENGINE *********
// selector regexps copied from jQuery - recent versions correct the range to start C0
// The initial portion of the main character selector: "just add water" to add on extra
// accepted characters, as well as the "\\\\." -> "\." portion necessary for matching
// period characters escaped in selectors
var charStart = "(?:[\\w\\u00c0-\\uFFFF*_-";
fluid.simpleCSSMatcher = {
regexp: new RegExp("([#.]?)(" + charStart + "]|\\\\.)+)", "g"),
charToTag: {
"": "tag",
"#": "id",
".": "clazz"
}
};
fluid.IoCSSMatcher = {
regexp: new RegExp("([&#]?)(" + charStart + "]|\\.|\\/)+)", "g"),
charToTag: {
"": "context",
"&": "context",
"#": "id"
}
};
var childSeg = new RegExp("\\s*(>)?\\s*", "g");
// var whiteSpace = new RegExp("^\\w*$");
// Parses a selector expression into a data structure holding a list of predicates
// 2nd argument is a "strategy" structure, e.g. fluid.simpleCSSMatcher or fluid.IoCSSMatcher
// unsupported, non-API function
fluid.parseSelector = function (selstring, strategy) {
var togo = [];
selstring = selstring.trim();
//ws-(ss*)[ws/>]
var regexp = strategy.regexp;
regexp.lastIndex = 0;
var lastIndex = 0;
while (true) {
var atNode = []; // a list of predicates at a particular node
var first = true;
while (true) {
var segMatch = regexp.exec(selstring);
if (!segMatch) {
break;
}
if (segMatch.index !== lastIndex) {
if (first) {
fluid.fail("Error in selector string - cannot match child selector expression starting at " + selstring.substring(lastIndex));
}
else {
break;
}
}
var thisNode = {};
var text = segMatch[2];
var targetTag = strategy.charToTag[segMatch[1]];
if (targetTag) {
thisNode[targetTag] = text;
}
atNode[atNode.length] = thisNode;
lastIndex = regexp.lastIndex;
first = false;
}
childSeg.lastIndex = lastIndex;
var fullAtNode = {predList: atNode};
var childMatch = childSeg.exec(selstring);
if (!childMatch || childMatch.index !== lastIndex) {
fluid.fail("Error in selector string - can not match child selector expression at " + selstring.substring(lastIndex));
}
if (childMatch[1] === ">") {
fullAtNode.child = true;
}
togo[togo.length] = fullAtNode;
// >= test here to compensate for IE bug http://blog.stevenlevithan.com/archives/exec-bugs
if (childSeg.lastIndex >= selstring.length) {
break;
}
lastIndex = childSeg.lastIndex;
regexp.lastIndex = childSeg.lastIndex;
}
return togo;
};
// Message resolution and templating
/**
*
* Take an original object and represent it using top-level sub-elements whose keys are EL Paths. For example,
* `originalObject` might look like:
*
* ```
* {
* deep: {
* path: {
* value: "foo",
* emptyObject: {},
* array: [ "peas", "porridge", "hot"]
* }
* }
* }
* ```
*
* Calling `fluid.flattenObjectKeys` on this would result in a new object that looks like:
*
* ```
* {
* "deep": "[object Object]",
* "deep.path": "[object Object]",
* "deep.path.value": "foo",
* "deep.path.array": "peas,porridge,hot",
* "deep.path.array.0": "peas",
* "deep.path.array.1": "porridge",
* "deep.path.array.2": "hot"
* }
* ```
*
* This function preserves the previous functionality of displaying an entire object using its `toString` function,
* which is why many of the paths above resolve to "[object Object]".
*
* This function is an unsupported non-API function that is used in by `fluid.stringTemplate` (see below).
*
* @param {Object} originalObject - An object.
* @return {Object} A representation of the original object that only contains top-level sub-elements whose keys are EL Paths.
*
*/
// unsupported, non-API function
fluid.flattenObjectPaths = function (originalObject) {
var flattenedObject = {};
fluid.each(originalObject, function (value, key) {
if (value !== null && typeof value === "object") {
var flattenedSubObject = fluid.flattenObjectPaths(value);
fluid.each(flattenedSubObject, function (subValue, subKey) {
flattenedObject[key + "." + subKey] = subValue;
});
if (typeof fluid.get(value, "toString") === "function") {
flattenedObject[key] = value.toString();
}
}
else {
flattenedObject[key] = value;
}
});
return flattenedObject;
};
/**
*
* Simple string template system. Takes a template string containing tokens in the form of "%value" or
* "%deep.path.to.value". Returns a new string with the tokens replaced by the specified values. Keys and values
* can be of any data type that can be coerced into a string.
*
* @param {String} template - A string (can be HTML) that contains tokens embedded into it.
* @param {Object} values - A collection of token keys and values.
* @return {String} A string whose tokens have been replaced with values.
*
*/
fluid.stringTemplate = function (template, values) {
var flattenedValues = fluid.flattenObjectPaths(values);
var keys = fluid.keys(flattenedValues);
keys = keys.sort(fluid.compareStringLength());
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
var templatePlaceholder = "%" + key;
var replacementValue = flattenedValues[key];
var indexOfPlaceHolder = -1;
while ((indexOfPlaceHolder = template.indexOf(templatePlaceholder)) !== -1) {
template = template.slice(0, indexOfPlaceHolder) + replacementValue + template.slice(indexOfPlaceHolder + templatePlaceholder.length);
}
}
return template;
};
})(jQuery, fluid_3_0_0);
;
/*!
Copyright 2011 unscriptable.com / John Hann
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
License MIT
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
// Light fluidification of minimal promises library. See original gist at
// https://gist.github.com/unscriptable/814052 for limitations and commentary
// This implementation provides what could be described as "flat promises" with
// no support for structured programming idioms involving promise composition.
// It provides what a proponent of mainstream promises would describe as
// a "glorified callback aggregator"
fluid.promise = function () {
var that = {
onResolve: [],
onReject: []
// disposition
// value
};
that.then = function (onResolve, onReject) {
if (onResolve) {
if (that.disposition === "resolve") {
onResolve(that.value);
} else {
that.onResolve.push(onResolve);
}
}
if (onReject) {
if (that.disposition === "reject") {
onReject(that.value);
} else {
that.onReject.push(onReject);
}
}
return that;
};
that.resolve = function (value) {
if (that.disposition) {
fluid.fail("Error: resolving promise ", that,
" which has already received \"" + that.disposition + "\"");
} else {
that.complete("resolve", that.onResolve, value);
}
return that;
};
that.reject = function (reason) {
if (that.disposition) {
fluid.fail("Error: rejecting promise ", that,
"which has already received \"" + that.disposition + "\"");
} else {
that.complete("reject", that.onReject, reason);
}
return that;
};
// PRIVATE, NON-API METHOD
that.complete = function (which, queue, arg) {
that.disposition = which;
that.value = arg;
for (var i = 0; i < queue.length; ++i) {
queue[i](arg);
}
};
return that;
};
/* Any object with a member <code>then</code> of type <code>function</code> passes this test.
* This includes essentially every known variety, including jQuery promises.
*/
fluid.isPromise = function (totest) {
return totest && typeof(totest.then) === "function";
};
/** Coerces any value to a promise
* @param {Any} promiseOrValue - The value to be coerced
* @return {Promise} - If the supplied value is already a promise, it is returned unchanged. Otherwise a fresh promise is created with the value as resolution and returned
*/
fluid.toPromise = function (promiseOrValue) {
if (fluid.isPromise(promiseOrValue)) {
return promiseOrValue;
} else {
var togo = fluid.promise();
togo.resolve(promiseOrValue);
return togo;
}
};
/* Chains the resolution methods of one promise (target) so that they follow those of another (source).
* That is, whenever source resolves, target will resolve, or when source rejects, target will reject, with the
* same payloads in each case.
*/
fluid.promise.follow = function (source, target) {
source.then(target.resolve, target.reject);
};
/** Returns a promise whose resolved value is mapped from the source promise or value by the supplied function.
* @param {Object|Promise} source - An object or promise whose value is to be mapped
* @param {Function} func - A function which will map the resolved promise value
* @return {Promise} - A promise for the resolved mapped value.
*/
fluid.promise.map = function (source, func) {
var promise = fluid.toPromise(source);
var togo = fluid.promise();
promise.then(function (value) {
var mapped = func(value);
if (fluid.isPromise(mapped)) {
fluid.promise.follow(mapped, togo);
} else {
togo.resolve(mapped);
}
}, function (error) {
togo.reject(error);
});
return togo;
};
/* General skeleton for all sequential promise algorithms, e.g. transform, reduce, sequence, etc.
* These accept a variable "strategy" pair to customise the interchange of values and final return
*/
fluid.promise.makeSequencer = function (sources, options, strategy) {
if (!fluid.isArrayable(sources)) {
fluid.fail("fluid.promise sequence algorithms must be supplied an array as source");
}
return {
sources: sources,
resolvedSources: [], // the values of "sources" only with functions invoked (an array of promises or values)
index: 0,
strategy: strategy,
options: options, // available to be supplied to each listener
returns: [],
promise: fluid.promise() // the final return value
};
};
fluid.promise.progressSequence = function (that, retValue) {
that.returns.push(retValue);
that.index++;
// No we dun't have no tail recursion elimination
fluid.promise.resumeSequence(that);
};
fluid.promise.processSequenceReject = function (that, error) { // Allow earlier promises in the sequence to wrap the rejection supplied by later ones (FLUID-5584)
for (var i = that.index - 1; i >= 0; --i) {
var resolved = that.resolvedSources[i];
var accumulator = fluid.isPromise(resolved) && typeof(resolved.accumulateRejectionReason) === "function" ? resolved.accumulateRejectionReason : fluid.identity;
error = accumulator(error);
}
that.promise.reject(error);
};
fluid.promise.resumeSequence = function (that) {
if (that.index === that.sources.length) {
that.promise.resolve(that.strategy.resolveResult(that));
} else {
var value = that.strategy.invokeNext(that);
that.resolvedSources[that.index] = value;
if (fluid.isPromise(value)) {
value.then(function (retValue) {
fluid.promise.progressSequence(that, retValue);
}, function (error) {
fluid.promise.processSequenceReject(that, error);
});
} else {
fluid.promise.progressSequence(that, value);
}
}
};
// SEQUENCE ALGORITHM APPLYING PROMISES
fluid.promise.makeSequenceStrategy = function () {
return {
invokeNext: function (that) {
var source = that.sources[that.index];
return typeof(source) === "function" ? source(that.options) : source;
},
resolveResult: function (that) {
return that.returns;
}
};
};
// accepts an array of values, promises or functions returning promises - in the case of functions returning promises,
// will assure that at most one of these is "in flight" at a time - that is, the succeeding function will not be invoked
// until the promise at the preceding position has resolved
fluid.promise.sequence = function (sources, options) {
var sequencer = fluid.promise.makeSequencer(sources, options, fluid.promise.makeSequenceStrategy());
fluid.promise.resumeSequence(sequencer);
return sequencer.promise;
};
// TRANSFORM ALGORITHM APPLYING PROMISES
fluid.promise.makeTransformerStrategy = function () {
return {
invokeNext: function (that) {
var lisrec = that.sources[that.index];
lisrec.listener = fluid.event.resolveListener(lisrec.listener);
var value = lisrec.listener.apply(null, [that.returns[that.index], that.options]);
return value;
},
resolveResult: function (that) {
return that.returns[that.index];
}
};
};
// Construct a "mini-object" managing the process of a sequence of transforms,
// each of which may be synchronous or return a promise
fluid.promise.makeTransformer = function (listeners, payload, options) {
listeners.unshift({listener:
function () {
return payload;
}
});
var sequencer = fluid.promise.makeSequencer(listeners, options, fluid.promise.makeTransformerStrategy());
sequencer.returns.push(null); // first dummy return from initial entry
fluid.promise.resumeSequence(sequencer);
return sequencer;
};
fluid.promise.filterNamespaces = function (listeners, namespaces) {
if (!namespaces) {
return listeners;
}
return fluid.remove_if(fluid.makeArray(listeners), function (element) {
return element.namespace && !element.softNamespace && !fluid.contains(namespaces, element.namespace);
});
};
/** Top-level API to operate a Fluid event which manages a sequence of
* chained transforms. Rather than being a standard listener accepting the
* same payload, each listener to the event accepts the payload returned by the
* previous listener, and returns either a transformed payload or else a promise
* yielding such a payload.
* @param {fluid.eventFirer} event - A Fluid event to which the listeners are to be interpreted as
* elements cooperating in a chained transform. Each listener will receive arguments <code>(payload, options)</code> where <code>payload</code>
* is the (successful, resolved) return value of the previous listener, and <code>options</code> is the final argument to this function
* @param {Object|Promise} payload - The initial payload input to the transform chain
* @param {Object} options - A free object containing options governing the transform. Fields interpreted at this top level are:
* reverse {Boolean}: <code>true</code> if the listeners are to be called in reverse order of priority (typically the case for an inverse transform)
* filterTransforms {Array}: An array of listener namespaces. If this field is set, only the transform elements whose listener namespaces listed in this array will be applied.
* @return {fluid.promise} A promise which will yield either the final transformed value, or the response of the first transform which fails.
*/
fluid.promise.fireTransformEvent = function (event, payload, options) {
options = options || {};
var listeners = options.reverse ? fluid.makeArray(event.sortedListeners).reverse() :
fluid.makeArray(event.sortedListeners);
listeners = fluid.promise.filterNamespaces(listeners, options.filterNamespaces);
var transformer = fluid.promise.makeTransformer(listeners, payload, options);
return transformer.promise;
};
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
/** NOTE: Much of this work originated from https://github.com/fluid-project/kettle/blob/master/lib/dataSource-core.js **/
/** Some common content encodings - suitable to appear as the "encoding" subcomponent of a dataSource **/
fluid.defaults("fluid.dataSource.encoding.JSON", {
gradeNames: "fluid.component",
invokers: {
parse: "fluid.dataSource.parseJSON",
render: "fluid.dataSource.stringifyJSON"
},
contentType: "application/json"
});
fluid.defaults("fluid.dataSource.encoding.none", {
gradeNames: "fluid.component",
invokers: {
parse: "fluid.identity",
render: "fluid.identity"
},
contentType: "text/plain"
});
fluid.dataSource.parseJSON = function (string) {
var togo = fluid.promise();
if (!string) {
togo.resolve(undefined);
} else {
try {
togo.resolve(JSON.parse(string));
} catch (err) {
togo.reject({
message: err
});
}
}
return togo;
};
fluid.dataSource.stringifyJSON = function (obj) {
return obj === undefined ? "" : JSON.stringify(obj, null, 4);
};
/**
* The head of the hierarchy of dataSource components. These abstract
* over the process of read and write access to data, following a simple CRUD-type semantic, indexed by
* a coordinate model (directModel) and which may be asynchronous.
* Top-level methods are:
* get(directModel[, callback|options] - to get the data from data resource
* set(directModel, model[, callback|options] - to set the data
*
*
* directModel: An object expressing an "index" into some set of
* state which can be read or written.
*
* model: The payload sent to the storage.
*
* options: An object expressing implementation specific details
* regarding the handling of a request. Note: this does not
* include details for identifying the resource. Those should be
* placed in the directModel.
*/
fluid.defaults("fluid.dataSource", {
gradeNames: ["fluid.component"],
events: {
// The "onRead" event is operated in a custom workflow by fluid.fireTransformEvent to
// process dataSource payloads during the get process. Each listener
// receives the data returned by the last.
onRead: null,
onError: null
},
components: {
encoding: {
type: "fluid.dataSource.encoding.JSON"
}
},
listeners: {
// handler for "onRead.impl" must be implemented by a concrete subgrade
// Note: The intial payload (first argument) will be undefined
"onRead.impl": {
func: "fluid.notImplemented",
priority: "first"
},
"onRead.encoding": {
func: "{encoding}.parse",
priority: "after:impl"
}
},
invokers: {
get: {
funcName: "fluid.dataSource.get",
args: ["{that}", "{arguments}.0", "{arguments}.1"] // directModel, options/callback
}
}
});
/**
* Base grade for adding write configuration to a dataSource.
*
* Grade linkage should be used to apply the concrete writable grade to the datasource configuration.
* For example fluid.makeGradeLinkage("kettle.dataSource.CouchDB.linkage", ["fluid.dataSource.writable", "kettle.dataSource.CouchDB"], "kettle.dataSource.CouchDB.writable");
*/
fluid.defaults("fluid.dataSource.writable", {
gradeNames: ["fluid.component"],
events: {
// events "onWrite" and "onWriteResponse" are operated in a custom workflow by fluid.fireTransformEvent to
// process dataSource payloads during the set process. Each listener
// receives the data returned by the last.
onWrite: null,
onWriteResponse: null
},
listeners: {
"onWrite.encoding": {
func: "{encoding}.render"
},
// handler for "onWrite.impl" must be implemented by a concrete subgrade
"onWrite.impl": {
func: "fluid.notImplemented",
priority: "after:encoding"
},
"onWriteResponse.encoding": {
func: "{encoding}.parse"
}
},
invokers: {
set: {
funcName: "fluid.dataSource.set",
args: ["{that}", "{arguments}.0", "{arguments}.1", "{arguments}.2"] // directModel, model, options/callback
}
}
});
// Registers the default promise handlers for a dataSource operation -
// i) If the user has supplied a function in place of method `options`, register this function as a success handler
// ii) if the user has supplied an onError handler in method `options`, this is registered - otherwise
// we register the firer of the dataSource's own onError method.
fluid.dataSource.registerStandardPromiseHandlers = function (that, promise, options) {
promise.then(typeof(options) === "function" ? options : null,
options.onError ? options.onError : that.events.onError.fire);
};
fluid.dataSource.defaultiseOptions = function (componentOptions, options, directModel, isSet) {
options = options || {};
options.directModel = directModel;
options.operation = isSet ? "set" : "get";
options.notFoundIsEmpty = options.notFoundIsEmpty || componentOptions.notFoundIsEmpty;
return options;
};
/** Operate the core "transforming promise workflow" of a dataSource's `get` method. The initial listener provides the initial payload;
* which then proceeds through the transform chain to arrive at the final payload.
* @param that {Component} The dataSource itself
* @param directModel {Object} The direct model expressing the "coordinates" of the model to be fetched
* @param options {Object} A structure of options configuring the action of this get request - many of these will be specific to the particular concrete DataSource
* @return {Promise} A promise for the final resolved payload
*/
fluid.dataSource.get = function (that, directModel, options) {
options = fluid.dataSource.defaultiseOptions(that.options, options, directModel);
var promise = fluid.promise.fireTransformEvent(that.events.onRead, undefined, options);
fluid.dataSource.registerStandardPromiseHandlers(that, promise, options);
return promise;
};
/** Operate the core "transforming promise workflow" of a dataSource's `set` method.
* Any return from this is then pushed forwards through a range of the transforms (typically, e.g. just decoding it as JSON)
* on its way back to the user via the onWriteResponse event.
* @param that {Component} The dataSource itself
* @param directModel {Object} The direct model expressing the "coordinates" of the model to be written
* @param model {Object} The payload to be written to the dataSource
* @param options {Object} A structure of options configuring the action of this set request - many of these will be specific to the particular concrete DataSource
* @return {Promise} A promise for the final resolved payload (not all DataSources will provide any for a `set` method)
*/
fluid.dataSource.set = function (that, directModel, model, options) {
options = fluid.dataSource.defaultiseOptions(that.options, options, directModel, true); // shared and writeable between all participants
var transformPromise = fluid.promise.fireTransformEvent(that.events.onWrite, model, options);
var togo = fluid.promise();
transformPromise.then(function (setResponse) {
var options2 = fluid.dataSource.defaultiseOptions(that.options, fluid.copy(options), directModel);
var retransformed = fluid.promise.fireTransformEvent(that.events.onWriteResponse, setResponse, options2);
fluid.promise.follow(retransformed, togo);
}, function (error) {
togo.reject(error);
});
fluid.dataSource.registerStandardPromiseHandlers(that, togo, options);
return togo;
};
})(jQuery, fluid_3_0_0);
;
/*
Copyright 2005-2013 jQuery Foundation, Inc. and other contributors
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
/** This file contains functions which depend on the presence of a DOM document
* but which do not depend on the contents of Fluid.js **/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
// polyfill for $.browser which was removed in jQuery 1.9 and later
// Taken from jquery-migrate-1.2.1.js,
// jQuery Migrate - v1.2.1 - 2013-05-08
// https://github.com/jquery/jquery-migrate
// Copyright 2005, 2013 jQuery Foundation, Inc. and other contributors; Licensed MIT
fluid.uaMatch = function (ua) {
ua = ua.toLowerCase();
var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) ||
/(webkit)[ \/]([\w.]+)/.exec( ua ) ||
/(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) ||
/(msie) ([\w.]+)/.exec( ua ) ||
ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) || [];
return {
browser: match[ 1 ] || "",
version: match[ 2 ] || "0"
};
};
var matched, browser;
// Don't clobber any existing jQuery.browser in case it's different
if (!$.browser) {
if (!!navigator.userAgent.match(/Trident\/7\./)) {
browser = { // From http://stackoverflow.com/questions/18684099/jquery-fail-to-detect-ie-11
msie: true,
version: 11
};
} else {
matched = fluid.uaMatch(navigator.userAgent);
browser = {};
if (matched.browser) {
browser[matched.browser] = true;
browser.version = matched.version;
}
// Chrome is Webkit, but Webkit is also Safari.
if (browser.chrome) {
browser.webkit = true;
} else if (browser.webkit) {
browser.safari = true;
}
}
$.browser = browser;
}
// Private constants.
var NAMESPACE_KEY = "fluid-scoped-data";
/*
* Gets stored state from the jQuery instance's data map.
* This function is unsupported: It is not really intended for use by implementors.
*/
fluid.getScopedData = function (target, key) {
var data = $(target).data(NAMESPACE_KEY);
return data ? data[key] : undefined;
};
/*
* Stores state in the jQuery instance's data map. Unlike jQuery's version,
* accepts multiple-element jQueries.
* This function is unsupported: It is not really intended for use by implementors.
*/
fluid.setScopedData = function (target, key, value) {
$(target).each(function () {
var data = $.data(this, NAMESPACE_KEY) || {};
data[key] = value;
$.data(this, NAMESPACE_KEY, data);
});
};
/** Global focus manager - makes use of "focusin" event supported in jquery 1.4.2 or later.
*/
var lastFocusedElement = null;
$(document).on("focusin", function (event) {
lastFocusedElement = event.target;
});
fluid.getLastFocusedElement = function () {
return lastFocusedElement;
};
var ENABLEMENT_KEY = "enablement";
/** Queries or sets the enabled status of a control. An activatable node
* may be "disabled" in which case its keyboard bindings will be inoperable
* (but still stored) until it is reenabled again.
* This function is unsupported: It is not really intended for use by implementors.
*/
fluid.enabled = function (target, state) {
target = $(target);
if (state === undefined) {
return fluid.getScopedData(target, ENABLEMENT_KEY) !== false;
}
else {
$("*", target).add(target).each(function () {
if (fluid.getScopedData(this, ENABLEMENT_KEY) !== undefined) {
fluid.setScopedData(this, ENABLEMENT_KEY, state);
}
else if (/select|textarea|input/i.test(this.nodeName)) {
$(this).prop("disabled", !state);
}
});
fluid.setScopedData(target, ENABLEMENT_KEY, state);
}
};
fluid.initEnablement = function (target) {
fluid.setScopedData(target, ENABLEMENT_KEY, true);
};
// This utility is required through the use of newer versions of jQuery which will obscure the original
// event responsible for interaction with a target. This is currently use in Tooltip.js and FluidView.js
// "dead man's blur" but would be of general utility
fluid.resolveEventTarget = function (event) {
while (event.originalEvent && event.originalEvent.target) {
event = event.originalEvent;
}
return event.target;
};
// These function (fluid.focus() and fluid.blur()) serve several functions. They should be used by
// all implementation both in test cases and component implementation which require to trigger a focus
// event. Firstly, they restore the old behaviour in jQuery versions prior to 1.10 in which a focus
// trigger synchronously relays to a focus handler. In newer jQueries this defers to the real browser
// relay with numerous platform and timing-dependent effects.
// Secondly, they are necessary since simulation of focus events by jQuery under IE
// is not sufficiently good to intercept the "focusin" binding. Any code which triggers
// focus or blur synthetically throughout the framework and client code must use this function,
// especially if correct cross-platform interaction is required with the "deadMansBlur" function.
function applyOp(node, func) {
node = $(node);
node.trigger("fluid-" + func);
node.triggerHandler(func);
node[func]();
return node;
}
$.each(["focus", "blur"], function (i, name) {
fluid[name] = function (elem) {
return applyOp(elem, name);
};
});
/* Sets the value to the DOM element and triggers the change event on the element.
* Note: when using jQuery val() function to change the node value, the change event would
* not be fired automatically, it requires to be initiated by the user.
*
* @param {A jQueryable DOM element} node - A selector, a DOM node, or a jQuery instance
* @param {String|Number|Array} value - A string of text, a number, or an array of strings
* corresponding to the value of each matched element to set in the node
*/
fluid.changeElementValue = function (node, value) {
node = $(node);
node.val(value).change();
};
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
fluid.dom = fluid.dom || {};
// Node walker function for iterateDom.
var getNextNode = function (iterator) {
if (iterator.node.firstChild) {
iterator.node = iterator.node.firstChild;
iterator.depth += 1;
return iterator;
}
while (iterator.node) {
if (iterator.node.nextSibling) {
iterator.node = iterator.node.nextSibling;
return iterator;
}
iterator.node = iterator.node.parentNode;
iterator.depth -= 1;
}
return iterator;
};
/**
* Walks the DOM, applying the specified acceptor function to each element.
* There is a special case for the acceptor, allowing for quick deletion of elements and their children.
* Return "delete" from your acceptor function if you want to delete the element in question.
* Return "stop" to terminate iteration.
* Implementation note - this utility exists mainly for performance reasons. It was last tested
* carefully some time ago (around jQuery 1.2) but at that time was around 3-4x faster at raw DOM
* filtration tasks than the jQuery equivalents, which was an important source of performance loss in the
* Reorderer component. General clients of the framework should use this method with caution if at all, and
* the performance issues should be reassessed when we have time.
*
* @param {Element} node - The node to start walking from.
* @param {Function} acceptor - The function to invoke with each DOM element.
* @param {Boolean} allNodes - Use <code>true</code> to call acceptor on all nodes, rather than just element nodes
* (type 1).
* @return {Object|undefined} - Returns `undefined` if the run completed successfully. If a node stopped the run,
* that node is returned.
*/
fluid.dom.iterateDom = function (node, acceptor, allNodes) {
var currentNode = {node: node, depth: 0};
var prevNode = node;
var condition;
while (currentNode.node !== null && currentNode.depth >= 0 && currentNode.depth < fluid.dom.iterateDom.DOM_BAIL_DEPTH) {
condition = null;
if (currentNode.node.nodeType === 1 || allNodes) {
condition = acceptor(currentNode.node, currentNode.depth);
}
if (condition) {
if (condition === "delete") {
currentNode.node.parentNode.removeChild(currentNode.node);
currentNode.node = prevNode;
}
else if (condition === "stop") {
return currentNode.node;
}
}
prevNode = currentNode.node;
currentNode = getNextNode(currentNode);
}
};
// Work around IE circular DOM issue. This is the default max DOM depth on IE.
// http://msdn2.microsoft.com/en-us/library/ms761392(VS.85).aspx
fluid.dom.iterateDom.DOM_BAIL_DEPTH = 256;
/**
* Checks if the specified container is actually the parent of containee.
*
* @param {Element} container - the potential parent
* @param {Element} containee - the child in question
* @return {Boolean} - `true` if `container` contains `containee`, `false` otherwise.
*/
fluid.dom.isContainer = function (container, containee) {
for (; containee; containee = containee.parentNode) {
if (container === containee) {
return true;
}
}
return false;
};
/* Return the element text from the supplied DOM node as a single String.
* Implementation note - this is a special-purpose utility used in the framework in just one
* position in the Reorderer. It only performs a "shallow" traversal of the text and was intended
* as a quick and dirty means of extracting element labels where the user had not explicitly provided one.
* It should not be used by general users of the framework and its presence here needs to be
* reassessed.
*/
fluid.dom.getElementText = function (element) {
var nodes = element.childNodes;
var text = "";
for (var i = 0; i < nodes.length; ++i) {
var child = nodes[i];
if (child.nodeType === 3) {
text = text + child.nodeValue;
}
}
return text;
};
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
var unUnicode = /(\\u[\dabcdef]{4}|\\x[\dabcdef]{2})/g;
fluid.unescapeProperties = function (string) {
string = string.replace(unUnicode, function (match) {
var code = match.substring(2);
var parsed = parseInt(code, 16);
return String.fromCharCode(parsed);
});
var pos = 0;
while (true) {
var backpos = string.indexOf("\\", pos);
if (backpos === -1) {
break;
}
if (backpos === string.length - 1) {
return [string.substring(0, string.length - 1), true];
}
var replace = string.charAt(backpos + 1);
if (replace === "n") { replace = "\n"; }
if (replace === "r") { replace = "\r"; }
if (replace === "t") { replace = "\t"; }
string = string.substring(0, backpos) + replace + string.substring(backpos + 2);
pos = backpos + 1;
}
return [string, false];
};
var breakPos = /[^\\][\s:=]/;
fluid.parseJavaProperties = function (text) {
// File format described at http://java.sun.com/javase/6/docs/api/java/util/Properties.html#load(java.io.Reader)
var togo = {};
text = text.replace(/\r\n/g, "\n");
text = text.replace(/\r/g, "\n");
var lines = text.split("\n");
var contin, key, valueComp, valueRaw, valueEsc;
for (var i = 0; i < lines.length; ++i) {
var line = $.trim(lines[i]);
if (!line || line.charAt(0) === "#" || line.charAt(0) === "!") {
continue;
}
if (!contin) {
valueComp = "";
var breakpos = line.search(breakPos);
if (breakpos === -1) {
key = line;
valueRaw = "";
}
else {
key = $.trim(line.substring(0, breakpos + 1)); // +1 since first char is escape exclusion
valueRaw = $.trim(line.substring(breakpos + 2));
if (valueRaw.charAt(0) === ":" || valueRaw.charAt(0) === "=") {
valueRaw = $.trim(valueRaw.substring(1));
}
}
key = fluid.unescapeProperties(key)[0];
valueEsc = fluid.unescapeProperties(valueRaw);
}
else {
valueEsc = fluid.unescapeProperties(line);
}
contin = valueEsc[1];
if (!valueEsc[1]) { // this line was not a continuation line - store the value
togo[key] = valueComp + valueEsc[0];
}
else {
valueComp += valueEsc[0];
}
}
return togo;
};
/**
*
* Expand a message string with respect to a set of arguments, following a basic subset of the Java MessageFormat
* rules.
* http://java.sun.com/j2se/1.4.2/docs/api/java/text/MessageFormat.html
*
* The message string is expected to contain replacement specifications such as {0}, {1}, {2}, etc.
*
* @param {String} messageString - The message key to be expanded
* @param {String|String[]} args - A single string or array of strings to be substituted into the message.
* @return {String} - The expanded message string.
*/
fluid.formatMessage = function (messageString, args) {
if (!args) {
return messageString;
}
if (typeof(args) === "string") {
args = [args];
}
for (var i = 0; i < args.length; ++i) {
messageString = messageString.replace("{" + i + "}", args[i]);
}
return messageString;
};
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
/** Render a timestamp from a Date object into a helpful fixed format for debug logs to millisecond accuracy
* @param {Date} date - The date to be rendered
* @return {String} - A string format consisting of hours:minutes:seconds.millis for the datestamp padded to fixed with
*/
fluid.renderTimestamp = function (date) {
var zeropad = function (num, width) {
if (!width) { width = 2; }
var numstr = (num === undefined ? "" : num.toString());
return "00000".substring(5 - width + numstr.length) + numstr;
};
return zeropad(date.getHours()) + ":" + zeropad(date.getMinutes()) + ":" + zeropad(date.getSeconds()) + "." + zeropad(date.getMilliseconds(), 3);
};
fluid.isTracing = false;
fluid.registerNamespace("fluid.tracing");
fluid.tracing.pathCount = [];
fluid.tracing.summarisePathCount = function (pathCount) {
pathCount = pathCount || fluid.tracing.pathCount;
var togo = {};
for (var i = 0; i < pathCount.length; ++i) {
var path = pathCount[i];
if (!togo[path]) {
togo[path] = 1;
}
else {
++togo[path];
}
}
var toReallyGo = [];
fluid.each(togo, function (el, path) {
toReallyGo.push({path: path, count: el});
});
toReallyGo.sort(function (a, b) {return b.count - a.count;});
return toReallyGo;
};
fluid.tracing.condensePathCount = function (prefixes, pathCount) {
prefixes = fluid.makeArray(prefixes);
var prefixCount = {};
fluid.each(prefixes, function (prefix) {
prefixCount[prefix] = 0;
});
var togo = [];
fluid.each(pathCount, function (el) {
var path = el.path;
if (!fluid.find(prefixes, function (prefix) {
if (path.indexOf(prefix) === 0) {
prefixCount[prefix] += el.count;
return true;
}
})) {
togo.push(el);
}
});
fluid.each(prefixCount, function (count, path) {
togo.unshift({path: path, count: count});
});
return togo;
};
// Exception stripping code taken from https://github.com/emwendelin/javascript-stacktrace/blob/master/stacktrace.js
// BSD licence, see header
fluid.detectStackStyle = function (e) {
var style = "other";
var stackStyle = {
offset: 0
};
if (e.arguments) {
style = "chrome";
} else if (typeof window !== "undefined" && window.opera && e.stacktrace) {
style = "opera10";
} else if (e.stack) {
style = "firefox";
// Detect FireFox 4-style stacks which are 1 level less deep
stackStyle.offset = e.stack.indexOf("Trace exception") === -1 ? 1 : 0;
} else if (typeof window !== "undefined" && window.opera && !("stacktrace" in e)) { //Opera 9-
style = "opera";
}
stackStyle.style = style;
return stackStyle;
};
fluid.obtainException = function () {
try {
throw new Error("Trace exception");
}
catch (e) {
return e;
}
};
var stackStyle = fluid.detectStackStyle(fluid.obtainException());
fluid.registerNamespace("fluid.exceptionDecoders");
fluid.decodeStack = function () {
if (stackStyle.style !== "firefox") {
return null;
}
var e = fluid.obtainException();
return fluid.exceptionDecoders[stackStyle.style](e);
};
fluid.exceptionDecoders.firefox = function (e) {
var delimiter = "at ";
var lines = e.stack.replace(/(?:\n@:0)?\s+$/m, "").replace(/^\(/gm, "{anonymous}(").split("\n");
return fluid.transform(lines, function (line) {
line = line.replace(/\)/g, "");
var atind = line.indexOf(delimiter);
return atind === -1 ? [line] : [line.substring(atind + delimiter.length), line.substring(0, atind)];
});
};
// Main entry point for callers.
fluid.getCallerInfo = function (atDepth) {
atDepth = (atDepth || 3) - stackStyle.offset;
var stack = fluid.decodeStack();
var element = stack && stack[atDepth] && stack[atDepth][0];
if (element) {
var lastslash = element.lastIndexOf("/");
if (lastslash === -1) {
lastslash = 0;
}
var nextColon = element.indexOf(":", lastslash);
return {
path: element.substring(0, lastslash),
filename: element.substring(lastslash + 1, nextColon),
index: element.substring(nextColon + 1)
};
} else {
return null;
}
};
/** Generates a string for padding purposes by replicating a character a given number of times
* @param {Character} c - A character to be used for padding
* @param {Integer} count - The number of times to repeat the character
* @return A string of length <code>count</code> consisting of repetitions of the supplied character
*/
// UNOPTIMISED
fluid.generatePadding = function (c, count) {
var togo = "";
for (var i = 0; i < count; ++i) {
togo += c;
}
return togo;
};
// Marker so that we can render a custom string for properties which are not direct and concrete
fluid.SYNTHETIC_PROPERTY = Object.freeze({});
// utility to avoid triggering custom getter code which could throw an exception - e.g. express 3.x's request object
fluid.getSafeProperty = function (obj, key) {
var desc = Object.getOwnPropertyDescriptor(obj, key); // supported on all of our environments - is broken on IE8
return desc && !desc.get ? obj[key] : fluid.SYNTHETIC_PROPERTY;
};
function printImpl(obj, small, options) {
function out(str) {
options.output += str;
}
var big = small + options.indentChars, isFunction = typeof(obj) === "function";
if (options.maxRenderChars !== undefined && options.output.length > options.maxRenderChars) {
return true;
}
if (obj === null) {
out("null");
} else if (obj === undefined) {
out("undefined"); // NB - object invalid for JSON interchange
} else if (obj === fluid.SYNTHETIC_PROPERTY) {
out("[Synthetic property]");
} else if (fluid.isPrimitive(obj) && !isFunction) {
out(JSON.stringify(obj));
}
else {
if (options.stack.indexOf(obj) !== -1) {
out("(CIRCULAR)"); // NB - object invalid for JSON interchange
return;
}
options.stack.push(obj);
var i;
if (fluid.isArrayable(obj)) {
if (obj.length === 0) {
out("[]");
} else {
out("[\n" + big);
for (i = 0; i < obj.length; ++i) {
if (printImpl(obj[i], big, options)) {
return true;
}
if (i !== obj.length - 1) {
out(",\n" + big);
}
}
out("\n" + small + "]");
}
}
else {
out("{" + (isFunction ? " Function" : "") + "\n" + big); // NB - Function object invalid for JSON interchange
var keys = fluid.keys(obj);
for (i = 0; i < keys.length; ++i) {
var key = keys[i];
var value = fluid.getSafeProperty(obj, key);
out(JSON.stringify(key) + ": ");
if (printImpl(value, big, options)) {
return true;
}
if (i !== keys.length - 1) {
out(",\n" + big);
}
}
out("\n" + small + "}");
}
options.stack.pop();
}
return;
}
/** Render a complex JSON object into a nicely indented format suitable for human readability.
* @param {Object} obj - The object to be rendered
* @param {Object} options - An options structure governing the rendering process. This supports the following options:
* <code>indent</code> {Integer} the number of space characters to be used to indent each level of containment (default value: 4)
* <code>maxRenderChars</code> {Integer} rendering the object will cease once this number of characters has been generated
* @return {String} - The generated output.
*/
fluid.prettyPrintJSON = function (obj, options) {
options = $.extend({indent: 4, stack: [], output: ""}, options);
options.indentChars = fluid.generatePadding(" ", options.indent);
printImpl(obj, "", options);
return options.output;
};
/**
* Dumps a DOM element into a readily recognisable form for debugging - produces a
* "semi-selector" summarising its tag name, class and id, whichever are set.
*
* @param {jQueryable} element - The element to be dumped
* @return {String} - A string representing the element.
*/
fluid.dumpEl = function (element) {
var togo;
if (!element) {
return "null";
}
if (element.nodeType === 3 || element.nodeType === 8) {
return "[data: " + element.data + "]";
}
if (element.nodeType === 9) {
return "[document: location " + element.location + "]";
}
if (!element.nodeType && fluid.isArrayable(element)) {
togo = "[";
for (var i = 0; i < element.length; ++i) {
togo += fluid.dumpEl(element[i]);
if (i < element.length - 1) {
togo += ", ";
}
}
return togo + "]";
}
element = $(element);
togo = element.get(0).tagName;
if (element.id) {
togo += "#" + element.id;
}
if (element.attr("class")) {
togo += "." + element.attr("class");
}
return togo;
};
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
/** NOTE: The contents of this file are by default NOT PART OF THE PUBLIC FLUID API unless explicitly annotated before the function **/
/* The Fluid "IoC System proper" - resolution of references and
* completely automated instantiation of declaratively defined
* component trees */
// Currently still uses manual traversal - once we ban manually instantiated components,
// it will use the instantiator's records instead.
fluid.visitComponentChildren = function (that, visitor, options, segs) {
segs = segs || [];
for (var name in that) {
var component = that[name];
// This entire algorithm is primitive and expensive and will be removed once we can abolish manual init components
if (!fluid.isComponent(component) || (options.visited && options.visited[component.id])) {
continue;
}
segs.push(name);
if (options.visited) { // recall that this is here because we may run into a component that has been cross-injected which might otherwise cause cyclicity
options.visited[component.id] = true;
}
if (visitor(component, name, segs, segs.length - 1)) {
return true;
}
if (!options.flat) {
fluid.visitComponentChildren(component, visitor, options, segs);
}
segs.pop();
}
};
fluid.getContextHash = function (instantiator, that) {
var shadow = instantiator.idToShadow[that.id];
return shadow && shadow.contextHash;
};
fluid.componentHasGrade = function (that, gradeName) {
var contextHash = fluid.getContextHash(fluid.globalInstantiator, that);
return !!(contextHash && contextHash[gradeName]);
};
// A variant of fluid.visitComponentChildren that supplies the signature expected for fluid.matchIoCSelector
// this is: thatStack, contextHashes, memberNames, i - note, the supplied arrays are NOT writeable and shared through the iteration
fluid.visitComponentsForMatching = function (that, options, visitor) {
var instantiator = fluid.getInstantiator(that);
options = $.extend({
visited: {},
instantiator: instantiator
}, options);
var thatStack = [that];
var contextHashes = [fluid.getContextHash(instantiator, that)];
var visitorWrapper = function (component, name, segs) {
thatStack.length = 1;
contextHashes.length = 1;
for (var i = 0; i < segs.length; ++i) {
var child = thatStack[i][segs[i]];
thatStack[i + 1] = child;
contextHashes[i + 1] = fluid.getContextHash(instantiator, child) || {};
}
return visitor(component, thatStack, contextHashes, segs, segs.length);
};
fluid.visitComponentChildren(that, visitorWrapper, options, []);
};
fluid.getMemberNames = function (instantiator, thatStack) {
if (thatStack.length === 0) { // Odd edge case for FLUID-6126 from fluid.computeDistributionPriority
return [];
} else {
var path = instantiator.idToPath(thatStack[thatStack.length - 1].id);
var segs = instantiator.parseEL(path);
// TODO: we should now have no longer shortness in the stack
segs.unshift.apply(segs, fluid.generate(thatStack.length - segs.length, ""));
return segs;
}
};
// thatStack contains an increasing list of MORE SPECIFIC thats.
// this visits all components starting from the current location (end of stack)
// in visibility order UP the tree.
fluid.visitComponentsForVisibility = function (instantiator, thatStack, visitor, options) {
options = options || {
visited: {},
flat: true,
instantiator: instantiator
};
var memberNames = fluid.getMemberNames(instantiator, thatStack);
for (var i = thatStack.length - 1; i >= 0; --i) {
var that = thatStack[i];
// explicitly visit the direct parent first
options.visited[that.id] = true;
if (visitor(that, memberNames[i], memberNames, i)) {
return;
}
if (fluid.visitComponentChildren(that, visitor, options, memberNames)) {
return;
}
memberNames.pop();
}
};
fluid.mountStrategy = function (prefix, root, toMount) {
var offset = prefix.length;
return function (target, name, i, segs) {
if (i <= prefix.length) { // Avoid OOB to not trigger deoptimisation!
return;
}
for (var j = 0; j < prefix.length; ++j) {
if (segs[j] !== prefix[j]) {
return;
}
}
return toMount(target, name, i - prefix.length, segs.slice(offset));
};
};
fluid.invokerFromRecord = function (invokerec, name, that) {
fluid.pushActivity("makeInvoker", "beginning instantiation of invoker with name %name and record %record as child of %that",
{name: name, record: invokerec, that: that});
var invoker = invokerec ? fluid.makeInvoker(that, invokerec, name) : undefined;
fluid.popActivity();
return invoker;
};
fluid.memberFromRecord = function (memberrecs, name, that) {
var togo;
for (var i = 0; i < memberrecs.length; ++i) { // memberrecs is the special "fluid.mergingArray" type which is not Arrayable
var expanded = fluid.expandImmediate(memberrecs[i], that);
if (!fluid.isPlainObject(togo)) { // poor man's "merge" algorithm to hack FLUID-5668 for now
togo = expanded;
} else {
togo = $.extend(true, togo, expanded);
}
}
return togo;
};
fluid.recordStrategy = function (that, options, optionsStrategy, recordPath, recordMaker, prefix, exceptions) {
prefix = prefix || [];
return {
strategy: function (target, name, i) {
if (i !== 1) {
return;
}
var record = fluid.driveStrategy(options, [recordPath, name], optionsStrategy);
if (record === undefined) {
return;
}
fluid.set(target, [name], fluid.inEvaluationMarker);
var member = recordMaker(record, name, that);
fluid.set(target, [name], member);
return member;
},
initter: function () {
var records = fluid.driveStrategy(options, recordPath, optionsStrategy) || {};
for (var name in records) {
if (!exceptions || !exceptions[name]) {
fluid.getForComponent(that, prefix.concat([name]));
}
}
}
};
};
// patch Fluid.js version for timing
fluid.instantiateFirers = function (that) {
var shadow = fluid.shadowForComponent(that);
var initter = fluid.get(shadow, ["eventStrategyBlock", "initter"]) || fluid.identity;
initter();
};
fluid.makeDistributionRecord = function (contextThat, sourceRecord, sourcePath, targetSegs, exclusions, sourceType) {
sourceType = sourceType || "distribution";
fluid.pushActivity("makeDistributionRecord", "Making distribution record from source record %sourceRecord path %sourcePath to target path %targetSegs", {sourceRecord: sourceRecord, sourcePath: sourcePath, targetSegs: targetSegs});
var source = fluid.copy(fluid.get(sourceRecord, sourcePath));
fluid.each(exclusions, function (exclusion) {
fluid.model.applyChangeRequest(source, {segs: exclusion, type: "DELETE"});
});
var record = {options: {}};
fluid.model.applyChangeRequest(record, {segs: targetSegs, type: "ADD", value: source});
fluid.checkComponentRecord(record);
fluid.popActivity();
return $.extend(record, {contextThat: contextThat, recordType: sourceType});
};
// Part of the early "distributeOptions" workflow. Given the description of the blocks to be distributed, assembles "canned" records
// suitable to be either registered into the shadow record for later or directly pushed to an existing component, as well as honouring
// any "removeSource" annotations by removing these options from the source block.
fluid.filterBlocks = function (contextThat, sourceBlocks, sourceSegs, targetSegs, exclusions, removeSource) {
var togo = [];
fluid.each(sourceBlocks, function (block) {
var source = fluid.get(block.source, sourceSegs);
if (source !== undefined) {
togo.push(fluid.makeDistributionRecord(contextThat, block.source, sourceSegs, targetSegs, exclusions, block.recordType));
var rescued = $.extend({}, source);
if (removeSource) {
fluid.model.applyChangeRequest(block.source, {segs: sourceSegs, type: "DELETE"});
}
fluid.each(exclusions, function (exclusion) {
var orig = fluid.get(rescued, exclusion);
fluid.set(block.source, sourceSegs.concat(exclusion), orig);
});
}
});
return togo;
};
// Use this peculiar signature since the actual component and shadow itself may not exist yet. Perhaps clean up with FLUID-4925
fluid.noteCollectedDistribution = function (parentShadow, memberName, distribution) {
fluid.model.setSimple(parentShadow, ["collectedDistributions", memberName, distribution.id], true);
};
fluid.isCollectedDistribution = function (parentShadow, memberName, distribution) {
return fluid.model.getSimple(parentShadow, ["collectedDistributions", memberName, distribution.id]);
};
fluid.clearCollectedDistributions = function (parentShadow, memberName) {
fluid.model.applyChangeRequest(parentShadow, {segs: ["collectedDistributions", memberName], type: "DELETE"});
};
fluid.collectDistributions = function (distributedBlocks, parentShadow, distribution, thatStack, contextHashes, memberNames, i) {
var lastMember = memberNames[memberNames.length - 1];
if (!fluid.isCollectedDistribution(parentShadow, lastMember, distribution) &&
fluid.matchIoCSelector(distribution.selector, thatStack, contextHashes, memberNames, i)) {
distributedBlocks.push.apply(distributedBlocks, distribution.blocks);
fluid.noteCollectedDistribution(parentShadow, lastMember, distribution);
}
};
// Slightly silly function to clean up the "appliedDistributions" records. In general we need to be much more aggressive both
// about clearing instantiation garbage (e.g. onCreate and most of the shadow)
// as well as caching frequently-used records such as the "thatStack" which
// would mean this function could be written in a sensible way
fluid.registerCollectedClearer = function (shadow, parentShadow, memberName) {
if (!shadow.collectedClearer && parentShadow) {
shadow.collectedClearer = function () {
fluid.clearCollectedDistributions(parentShadow, memberName);
};
}
};
fluid.receiveDistributions = function (parentThat, gradeNames, memberName, that) {
var instantiator = fluid.getInstantiator(parentThat || that);
var thatStack = instantiator.getThatStack(parentThat || that); // most specific is at end
thatStack.unshift(fluid.rootComponent);
var memberNames = fluid.getMemberNames(instantiator, thatStack);
var shadows = fluid.transform(thatStack, function (thisThat) {
return instantiator.idToShadow[thisThat.id];
});
var parentShadow = shadows[shadows.length - (parentThat ? 1 : 2)];
var contextHashes = fluid.getMembers(shadows, "contextHash");
if (parentThat) { // if called before construction of component from assembleCreatorArguments - NB this path will be abolished/amalgamated
memberNames.push(memberName);
contextHashes.push(fluid.gradeNamesToHash(gradeNames));
thatStack.push(that);
} else {
fluid.registerCollectedClearer(shadows[shadows.length - 1], parentShadow, memberNames[memberNames.length - 1]);
}
var distributedBlocks = [];
for (var i = 0; i < thatStack.length - 1; ++i) {
fluid.each(shadows[i].distributions, function (distribution) { // eslint-disable-line no-loop-func
fluid.collectDistributions(distributedBlocks, parentShadow, distribution, thatStack, contextHashes, memberNames, i);
});
}
return distributedBlocks;
};
fluid.computeTreeDistance = function (path1, path2) {
var i = 0;
while (i < path1.length && i < path2.length && path1[i] === path2[i]) {
++i;
}
return path1.length + path2.length - 2*i; // eslint-disable-line space-infix-ops
};
// Called from applyDistributions (immediate application route) as well as mergeRecordsToList (pre-instantiation route) AS WELL AS assembleCreatorArguments (pre-pre-instantiation route)
fluid.computeDistributionPriority = function (targetThat, distributedBlock) {
if (!distributedBlock.priority) {
var instantiator = fluid.getInstantiator(targetThat);
var targetStack = instantiator.getThatStack(targetThat);
var targetPath = fluid.getMemberNames(instantiator, targetStack);
var sourceStack = instantiator.getThatStack(distributedBlock.contextThat);
var sourcePath = fluid.getMemberNames(instantiator, sourceStack);
var distance = fluid.computeTreeDistance(targetPath, sourcePath);
distributedBlock.priority = fluid.mergeRecordTypes.distribution - distance;
}
return distributedBlock;
};
// convert "preBlocks" as produced from fluid.filterBlocks into "real blocks" suitable to be used by the expansion machinery.
fluid.applyDistributions = function (that, preBlocks, targetShadow) {
var distributedBlocks = fluid.transform(preBlocks, function (preBlock) {
return fluid.generateExpandBlock(preBlock, that, targetShadow.mergePolicy);
}, function (distributedBlock) {
return fluid.computeDistributionPriority(that, distributedBlock);
});
var mergeOptions = targetShadow.mergeOptions;
mergeOptions.mergeBlocks.push.apply(mergeOptions.mergeBlocks, distributedBlocks);
mergeOptions.updateBlocks();
return distributedBlocks;
};
// TODO: This implementation is obviously poor and has numerous flaws - in particular it does no backtracking as well as matching backwards through the selector
/** Match a parsed IoC selector against a selection of data structures representing a component's tree context.
* @param {ParsedSelector} selector - A parsed selector structure as returned from `fluid.parseSelector`.
* @param {Component[]} thatStack - An array of components ascending up the tree from the component being matched,
* which will be held in the last position.
* @param {Object[]} contextHashes - An array of context hashes as cached in the component's shadows - a hash to
* `true`/"memberName" depending on the reason the context matches
* @param {String[]} [memberNames] - An array of member names of components in their parents. This is only used in the distributeOptions route.
* @param {Number} i - One plus the index of the IoCSS head component within `thatStack` - all components before this
* index will be ignored for matching. Will have value `1` in the queryIoCSelector route.
* @return {Boolean} `true` if the selector matches the leaf component at the end of `thatStack`
*/
fluid.matchIoCSelector = function (selector, thatStack, contextHashes, memberNames, i) {
var thatpos = thatStack.length - 1;
var selpos = selector.length - 1;
while (true) {
var isChild = selector[selpos].child;
var mustMatchHere = thatpos === thatStack.length - 1 || isChild;
var that = thatStack[thatpos];
var selel = selector[selpos];
var match = true;
for (var j = 0; j < selel.predList.length; ++j) {
var pred = selel.predList[j];
var context = pred.context;
if (context && context !== "*" && !(contextHashes[thatpos][context] || memberNames[thatpos] === context)) {
match = false;
break;
}
if (pred.id && that.id !== pred.id) {
match = false;
break;
}
}
if (selpos === 0 && thatpos > i && mustMatchHere && isChild) {
match = false; // child selector must exhaust stack completely - FLUID-5029
}
if (match) {
if (selpos === 0) {
return true;
}
--thatpos;
--selpos;
}
else {
if (mustMatchHere) {
return false;
}
else {
--thatpos;
}
}
if (thatpos < i) {
return false;
}
}
};
/** Query for all components matching a selector in a particular tree
* @param {Component} root - The root component at which to start the search
* @param {String} selector - An IoCSS selector, in form of a string. Note that since selectors supplied to this function implicitly
* match downwards, they need not contain the "head context" followed by whitespace required in the distributeOptions form. E.g.
* simply <code>"fluid.viewComponent"</code> will match all viewComponents below the root.
* @param {Boolean} flat - [Optional] <code>true</code> if the search should just be performed at top level of the component tree
* Note that with <code>flat=true</code> this search will scan every component in the tree and may well be very slow.
* @return {Component[]} The list of all components matching the selector
*/
// supported, PUBLIC API function
fluid.queryIoCSelector = function (root, selector, flat) {
var parsed = fluid.parseSelector(selector, fluid.IoCSSMatcher);
var togo = [];
fluid.visitComponentsForMatching(root, {flat: flat}, function (that, thatStack, contextHashes) {
if (fluid.matchIoCSelector(parsed, thatStack, contextHashes, [], 1)) {
togo.push(that);
}
});
return togo;
};
fluid.isIoCSSSelector = function (context) {
return context.indexOf(" ") !== -1; // simple-minded check for an IoCSS reference
};
fluid.pushDistributions = function (targetHead, selector, target, blocks) {
var targetShadow = fluid.shadowForComponent(targetHead);
var id = fluid.allocateGuid();
var distribution = {
id: id, // This id is used in clearDistributions
target: target, // Here for improved debuggability - info is duplicated in "selector"
selector: selector,
blocks: blocks
};
Object.freeze(distribution);
Object.freeze(distribution.blocks);
fluid.pushArray(targetShadow, "distributions", distribution);
return id;
};
fluid.clearDistribution = function (targetHeadId, id) {
var targetHeadShadow = fluid.globalInstantiator.idToShadow[targetHeadId];
// By FLUID-6193, the head component may already have been destroyed, in which case the distributions are gone,
// and we have leaked only its id. In theory we may want to re-establish the distribution if the head is
// re-created, but that is a far wider issue.
if (targetHeadShadow) {
fluid.remove_if(targetHeadShadow.distributions, function (distribution) {
return distribution.id === id;
});
}
};
fluid.clearDistributions = function (shadow) {
fluid.each(shadow.outDistributions, function (outDist) {
fluid.clearDistribution(outDist.targetHeadId, outDist.distributionId);
});
};
// Modifies a parsed selector to extract and remove its head context which will be matched upwards
fluid.extractSelectorHead = function (parsedSelector) {
var predList = parsedSelector[0].predList;
var context = predList[0].context;
predList.length = 0;
return context;
};
fluid.parseExpectedOptionsPath = function (path, role) {
var segs = fluid.model.parseEL(path);
if (segs[0] !== "options") {
fluid.fail("Error in options distribution path ", path, " - only " + role + " paths beginning with \"options\" are supported");
}
return segs.slice(1);
};
fluid.replicateProperty = function (source, property, targets) {
if (source[property] !== undefined) {
fluid.each(targets, function (target) {
target[property] = source[property];
});
}
};
fluid.undistributableOptions = ["gradeNames", "distributeOptions", "argumentMap", "initFunction", "mergePolicy", "progressiveCheckerOptions"]; // automatically added to "exclusions" of every distribution
fluid.distributeOptions = function (that, optionsStrategy) {
var thatShadow = fluid.shadowForComponent(that);
var records = fluid.driveStrategy(that.options, "distributeOptions", optionsStrategy);
fluid.each(records, function distributeOptionsOne(record) {
fluid.pushActivity("distributeOptions", "parsing distributeOptions block %record %that ", {that: that, record: record});
if (typeof(record.target) !== "string") {
fluid.fail("Error in options distribution record ", record, " a member named \"target\" must be supplied holding an IoC reference");
}
if (typeof(record.source) === "string" ^ record.record === undefined) {
fluid.fail("Error in options distribution record ", record, ": must supply either a member \"source\" holding an IoC reference or a member \"record\" holding a literal record");
}
var targetRef = fluid.parseContextReference(record.target);
var targetHead, selector, context;
if (fluid.isIoCSSSelector(targetRef.context)) {
selector = fluid.parseSelector(targetRef.context, fluid.IoCSSMatcher);
var headContext = fluid.extractSelectorHead(selector);
if (headContext === "/") {
targetHead = fluid.rootComponent;
} else {
context = headContext;
}
}
else {
context = targetRef.context;
}
targetHead = targetHead || fluid.resolveContext(context, that);
if (!targetHead) {
fluid.fail("Error in options distribution record ", record, " - could not resolve context {" + context + "} to a head component");
}
var targetSegs = fluid.model.parseEL(targetRef.path);
var preBlocks;
if (record.record !== undefined) {
preBlocks = [(fluid.makeDistributionRecord(that, record.record, [], targetSegs, []))];
}
else {
var source = fluid.parseContextReference(record.source);
if (source.context !== "that") {
fluid.fail("Error in options distribution record ", record, " only a context of {that} is supported");
}
var sourceSegs = fluid.parseExpectedOptionsPath(source.path, "source");
var fullExclusions = fluid.makeArray(record.exclusions).concat(sourceSegs.length === 0 ? fluid.undistributableOptions : []);
var exclusions = fluid.transform(fullExclusions, function (exclusion) {
return fluid.model.parseEL(exclusion);
});
preBlocks = fluid.filterBlocks(that, thatShadow.mergeOptions.mergeBlocks, sourceSegs, targetSegs, exclusions, record.removeSource);
thatShadow.mergeOptions.updateBlocks(); // perhaps unnecessary
}
fluid.replicateProperty(record, "priority", preBlocks);
fluid.replicateProperty(record, "namespace", preBlocks);
// TODO: inline material has to be expanded in its original context!
if (selector) {
var distributionId = fluid.pushDistributions(targetHead, selector, record.target, preBlocks);
thatShadow.outDistributions = thatShadow.outDistributions || [];
thatShadow.outDistributions.push({
targetHeadId: targetHead.id,
distributionId: distributionId
});
}
else { // The component exists now, we must rebalance it
var targetShadow = fluid.shadowForComponent(targetHead);
fluid.applyDistributions(that, preBlocks, targetShadow);
}
fluid.popActivity();
});
};
fluid.gradeNamesToHash = function (gradeNames) {
var contextHash = {};
fluid.each(gradeNames, function (gradeName) {
contextHash[gradeName] = true;
contextHash[fluid.computeNickName(gradeName)] = true;
});
return contextHash;
};
fluid.cacheShadowGrades = function (that, shadow) {
var contextHash = fluid.gradeNamesToHash(that.options.gradeNames);
if (!contextHash[shadow.memberName]) {
contextHash[shadow.memberName] = "memberName"; // This is filtered out again in recordComponent - TODO: Ensure that ALL resolution uses the scope chain eventually
}
shadow.contextHash = contextHash;
fluid.each(contextHash, function (troo, context) {
shadow.ownScope[context] = that;
if (shadow.parentShadow && shadow.parentShadow.that.type !== "fluid.rootComponent") {
shadow.parentShadow.childrenScope[context] = that;
}
});
};
// First sequence point where the mergeOptions strategy is delivered from Fluid.js - here we take care
// of both receiving and transmitting options distributions
fluid.deliverOptionsStrategy = function (that, target, mergeOptions) {
var shadow = fluid.shadowForComponent(that, shadow);
fluid.cacheShadowGrades(that, shadow);
shadow.mergeOptions = mergeOptions;
};
/** Dynamic grade closure algorithm - the following 4 functions share access to a small record structure "rec" which is
* constructed at the start of fluid.computeDynamicGrades
*/
fluid.collectDistributedGrades = function (rec) {
// Receive distributions first since these may cause arrival of more contextAwareness blocks.
var distributedBlocks = fluid.receiveDistributions(null, null, null, rec.that);
if (distributedBlocks.length > 0) {
var readyBlocks = fluid.applyDistributions(rec.that, distributedBlocks, rec.shadow);
var gradeNamesList = fluid.transform(fluid.getMembers(readyBlocks, ["source", "gradeNames"]), fluid.makeArray);
fluid.accumulateDynamicGrades(rec, fluid.flatten(gradeNamesList));
}
};
// Apply a batch of freshly acquired plain dynamic grades to the target component and recompute its options
fluid.applyDynamicGrades = function (rec) {
rec.oldGradeNames = fluid.makeArray(rec.gradeNames);
// Note that this crude algorithm doesn't allow us to determine which grades are "new" and which not // TODO: can no longer interpret comment
var newDefaults = fluid.copy(fluid.getMergedDefaults(rec.that.typeName, rec.gradeNames));
rec.gradeNames.length = 0; // acquire derivatives of dynamic grades (FLUID-5054)
rec.gradeNames.push.apply(rec.gradeNames, newDefaults.gradeNames);
fluid.each(rec.gradeNames, function (gradeName) {
if (!fluid.isIoCReference(gradeName)) {
rec.seenGrades[gradeName] = true;
}
});
var shadow = rec.shadow;
fluid.cacheShadowGrades(rec.that, shadow);
// This cheap strategy patches FLUID-5091 for now - some more sophisticated activity will take place
// at this site when we have a full fix for FLUID-5028
shadow.mergeOptions.destroyValue(["mergePolicy"]);
shadow.mergeOptions.destroyValue(["components"]);
shadow.mergeOptions.destroyValue(["invokers"]);
rec.defaultsBlock.source = newDefaults;
shadow.mergeOptions.updateBlocks();
shadow.mergeOptions.computeMergePolicy(); // TODO: we should really only do this if its content changed - this implies moving all options evaluation over to some (cheap) variety of the ChangeApplier
fluid.accumulateDynamicGrades(rec, newDefaults.gradeNames);
};
// Filter some newly discovered grades into their plain and dynamic queues
fluid.accumulateDynamicGrades = function (rec, newGradeNames) {
fluid.each(newGradeNames, function (gradeName) {
if (!rec.seenGrades[gradeName]) {
if (fluid.isIoCReference(gradeName)) {
rec.rawDynamic.push(gradeName);
rec.seenGrades[gradeName] = true;
} else if (!fluid.contains(rec.oldGradeNames, gradeName)) {
rec.plainDynamic.push(gradeName);
}
}
});
};
fluid.computeDynamicGrades = function (that, shadow, strategy) {
delete that.options.gradeNames; // Recompute gradeNames for FLUID-5012 and others
var gradeNames = fluid.driveStrategy(that.options, "gradeNames", strategy); // Just acquire the reference and force eval of mergeBlocks "target", contents are wrong
gradeNames.length = 0;
// TODO: In complex distribution cases, a component might end up with multiple default blocks
var defaultsBlock = fluid.findMergeBlocks(shadow.mergeOptions.mergeBlocks, "defaults")[0];
var rec = {
that: that,
shadow: shadow,
defaultsBlock: defaultsBlock,
gradeNames: gradeNames, // remember that this array is globally shared
seenGrades: {},
plainDynamic: [],
rawDynamic: []
};
fluid.each(shadow.mergeOptions.mergeBlocks, function (block) { // acquire parents of earlier blocks before applying later ones
gradeNames.push.apply(gradeNames, fluid.makeArray(block.target && block.target.gradeNames));
fluid.applyDynamicGrades(rec);
});
fluid.collectDistributedGrades(rec);
while (true) {
while (rec.plainDynamic.length > 0) {
gradeNames.push.apply(gradeNames, rec.plainDynamic);
rec.plainDynamic.length = 0;
fluid.applyDynamicGrades(rec);
fluid.collectDistributedGrades(rec);
}
if (rec.rawDynamic.length > 0) {
var expanded = fluid.expandImmediate(rec.rawDynamic.shift(), that, shadow.localDynamic);
if (typeof(expanded) === "function") {
expanded = expanded();
}
if (expanded) {
rec.plainDynamic = rec.plainDynamic.concat(expanded);
}
} else {
break;
}
}
if (shadow.collectedClearer) {
shadow.collectedClearer();
delete shadow.collectedClearer;
}
};
fluid.computeDynamicComponentKey = function (recordKey, sourceKey) {
return recordKey + (sourceKey === 0 ? "" : "-" + sourceKey); // TODO: configurable name strategies
};
// Hacked resolution of FLUID-6371 - we can't add a listener because this version of the framework doesn't
// support multiple records as subcomponents, and there may have been a total options injection
fluid.hasDynamicComponentCount = function (shadow, key) {
var hypos = key.indexOf("-");
if (hypos !== -1) {
var recordKey = key.substring(0, hypos);
return shadow.dynamicComponentCount !== undefined && shadow.dynamicComponentCount[recordKey] !== undefined;
}
};
fluid.clearDynamicParentRecord = function (shadow, key) {
if (fluid.hasDynamicComponentCount(shadow, key)) {
var holder = fluid.get(shadow.that, ["options", "components"]);
if (holder) {
delete holder[key];
}
}
};
fluid.registerDynamicRecord = function (that, recordKey, sourceKey, record, toCensor) {
var key = fluid.computeDynamicComponentKey(recordKey, sourceKey);
var recordCopy = fluid.copy(record);
delete recordCopy[toCensor];
fluid.set(that.options, ["components", key], recordCopy);
return key;
};
fluid.computeDynamicComponents = function (that, mergeOptions) {
var shadow = fluid.shadowForComponent(that);
var localSub = shadow.subcomponentLocal = {};
var records = fluid.driveStrategy(that.options, "dynamicComponents", mergeOptions.strategy);
fluid.each(records, function (record, recordKey) {
if (!record.sources && !record.createOnEvent) {
fluid.fail("Cannot process dynamicComponents record ", record, " without a \"sources\" or \"createOnEvent\" entry");
}
if (record.sources) {
var sources = fluid.expandOptions(record.sources, that);
fluid.each(sources, function (source, sourceKey) {
var key = fluid.registerDynamicRecord(that, recordKey, sourceKey, record, "sources");
localSub[key] = {"source": source, "sourcePath": sourceKey};
});
}
else if (record.createOnEvent) {
var event = fluid.event.expandOneEvent(that, record.createOnEvent);
fluid.set(shadow, ["dynamicComponentCount", recordKey], 0);
var listener = function () {
var key = fluid.registerDynamicRecord(that, recordKey, shadow.dynamicComponentCount[recordKey]++, record, "createOnEvent");
var localRecord = {"arguments": fluid.makeArray(arguments)};
fluid.initDependent(that, key, localRecord);
};
event.addListener(listener);
fluid.recordListener(event, listener, shadow);
}
});
};
// Second sequence point for mergeOptions from Fluid.js - here we construct all further
// strategies required on the IoC side and mount them into the shadow's getConfig for universal use
fluid.computeComponentAccessor = function (that, localRecord) {
var instantiator = fluid.globalInstantiator;
var shadow = fluid.shadowForComponent(that);
shadow.localDynamic = localRecord; // for signalling to dynamic grades from dynamic components
var options = that.options;
var strategy = shadow.mergeOptions.strategy;
var optionsStrategy = fluid.mountStrategy(["options"], options, strategy);
shadow.invokerStrategy = fluid.recordStrategy(that, options, strategy, "invokers", fluid.invokerFromRecord);
shadow.eventStrategyBlock = fluid.recordStrategy(that, options, strategy, "events", fluid.eventFromRecord, ["events"]);
var eventStrategy = fluid.mountStrategy(["events"], that, shadow.eventStrategyBlock.strategy, ["events"]);
shadow.memberStrategy = fluid.recordStrategy(that, options, strategy, "members", fluid.memberFromRecord, null, {model: true, modelRelay: true});
// NB - ginger strategy handles concrete, rationalise
shadow.getConfig = {strategies: [fluid.model.funcResolverStrategy, fluid.makeGingerStrategy(that),
optionsStrategy, shadow.invokerStrategy.strategy, shadow.memberStrategy.strategy, eventStrategy]};
fluid.computeDynamicGrades(that, shadow, strategy, shadow.mergeOptions.mergeBlocks);
fluid.distributeOptions(that, strategy);
if (shadow.contextHash["fluid.resolveRoot"]) {
var memberName;
if (shadow.contextHash["fluid.resolveRootSingle"]) {
var singleRootType = fluid.getForComponent(that, ["options", "singleRootType"]);
if (!singleRootType) {
fluid.fail("Cannot register object with grades " + Object.keys(shadow.contextHash).join(", ") + " as fluid.resolveRootSingle since it has not defined option singleRootType");
}
memberName = fluid.typeNameToMemberName(singleRootType);
} else {
memberName = fluid.computeGlobalMemberName(that);
}
var parent = fluid.resolveRootComponent;
if (parent[memberName]) {
instantiator.clearComponent(parent, memberName);
}
instantiator.recordKnownComponent(parent, that, memberName, false);
}
return shadow.getConfig;
};
// About the SHADOW:
// Allocated at: instantiator's "recordComponent"
// Contents:
// path {String} Principal allocated path (point of construction) in tree
// that {Component} The component itself
// contextHash {String to Boolean} Map of context names which this component matches
// mergePolicy, mergeOptions: Machinery for last phase of options merging
// invokerStrategy, eventStrategyBlock, memberStrategy, getConfig: Junk required to operate the accessor
// listeners: Listeners registered during this component's construction, to be cleared during clearListeners
// distributions, collectedClearer: Managing options distributions
// outDistributions: A list of distributions registered from this component, signalling from distributeOptions to clearDistributions
// subcomponentLocal: Signalling local record from computeDynamicComponents to assembleCreatorArguments
// dynamicLocal: Local signalling for dynamic grades
// ownScope: A hash of names to components which are in scope from this component - populated in cacheShadowGrades
// childrenScope: A hash of names to components which are in scope because they are children of this component (BELOW own ownScope in resolution order)
fluid.shadowForComponent = function (component) {
var instantiator = fluid.getInstantiator(component);
return instantiator && component ? instantiator.idToShadow[component.id] : null;
};
// Access the member at a particular path in a component, forcing it to be constructed gingerly if necessary
// supported, PUBLIC API function
fluid.getForComponent = function (component, path) {
var shadow = fluid.shadowForComponent(component);
var getConfig = shadow ? shadow.getConfig : undefined;
return fluid.get(component, path, getConfig);
};
// An EL segment resolver strategy that will attempt to trigger creation of
// components that it discovers along the EL path, if they have been defined but not yet
// constructed.
fluid.makeGingerStrategy = function (that) {
var instantiator = fluid.getInstantiator(that);
return function (component, thisSeg, index, segs) {
var atval = component[thisSeg];
if (atval === fluid.inEvaluationMarker && index === segs.length) {
fluid.fail("Error in component configuration - a circular reference was found during evaluation of path segment \"" + thisSeg +
"\": for more details, see the activity records following this message in the console, or issue fluid.setLogging(fluid.logLevel.TRACE) when running your application");
}
if (index > 1) {
return atval;
}
if (atval === undefined && component.hasOwnProperty(thisSeg)) { // avoid recomputing properties that have been explicitly evaluated to undefined
return fluid.NO_VALUE;
}
if (atval === undefined) { // pick up components in instantiation here - we can cut this branch by attaching early
var parentPath = instantiator.idToShadow[component.id].path;
var childPath = instantiator.composePath(parentPath, thisSeg);
atval = instantiator.pathToComponent[childPath];
}
if (atval === undefined) {
// TODO: This check is very expensive - once gingerness is stable, we ought to be able to
// eagerly compute and cache the value of options.components - check is also incorrect and will miss injections
var subRecord = fluid.getForComponent(component, ["options", "components", thisSeg]);
if (subRecord) {
if (subRecord.createOnEvent) {
fluid.fail("Error resolving path segment \"" + thisSeg + "\" of path " + segs.join(".") + " since component with record ", subRecord,
" has annotation \"createOnEvent\" - this very likely represents an implementation error. Either alter the reference so it does not " +
" match this component, or alter your workflow to ensure that the component is instantiated by the time this reference resolves");
}
fluid.initDependent(component, thisSeg);
atval = component[thisSeg];
}
}
return atval;
};
};
// Listed in dependence order
fluid.frameworkGrades = ["fluid.component", "fluid.modelComponent", "fluid.viewComponent", "fluid.rendererComponent"];
fluid.filterBuiltinGrades = function (gradeNames) {
return fluid.remove_if(fluid.makeArray(gradeNames), function (gradeName) {
return fluid.frameworkGrades.indexOf(gradeName) !== -1;
});
};
fluid.dumpGradeNames = function (that) {
return that.options && that.options.gradeNames ?
" gradeNames: " + JSON.stringify(fluid.filterBuiltinGrades(that.options.gradeNames)) : "";
};
fluid.dumpThat = function (that) {
return "{ typeName: \"" + that.typeName + "\"" + fluid.dumpGradeNames(that) + " id: " + that.id + "}";
};
fluid.dumpThatStack = function (thatStack, instantiator) {
var togo = fluid.transform(thatStack, function (that) {
var path = instantiator.idToPath(that.id);
return fluid.dumpThat(that) + (path ? (" - path: " + path) : "");
});
return togo.join("\n");
};
fluid.dumpComponentPath = function (that) {
var path = fluid.pathForComponent(that);
return path ? fluid.pathUtil.composeSegments(path) : "** no path registered for component **";
};
fluid.resolveContext = function (context, that, fast) {
if (context === "that") {
return that;
}
// TODO: Check performance impact of this type check introduced for FLUID-5903 in a very sensitive corner
if (typeof(context) === "object") {
var innerContext = fluid.resolveContext(context.context, that, fast);
if (!fluid.isComponent(innerContext)) {
fluid.triggerMismatchedPathError(context.context, that);
}
var rawValue = fluid.getForComponent(innerContext, context.path);
// TODO: Terrible, slow dispatch for this route
var expanded = fluid.expandOptions(rawValue, that);
if (!fluid.isComponent(expanded)) {
fluid.fail("Unable to resolve recursive context expression " + fluid.renderContextReference(context) + ": the directly resolved value of " + rawValue +
" did not resolve to a component in the scope of component ", that, ": got ", expanded);
}
return expanded;
} else {
var foundComponent;
var instantiator = fluid.globalInstantiator; // fluid.getInstantiator(that); // this hash lookup takes over 1us!
if (fast) {
var shadow = instantiator.idToShadow[that.id];
return shadow.ownScope[context];
} else {
var thatStack = instantiator.getFullStack(that);
fluid.visitComponentsForVisibility(instantiator, thatStack, function (component, name) {
var shadow = fluid.shadowForComponent(component);
// TODO: Some components, e.g. the static environment and typeTags do not have a shadow, which slows us down here
if (context === name || shadow && shadow.contextHash && shadow.contextHash[context] || context === component.typeName) {
foundComponent = component;
return true; // YOUR VISIT IS AT AN END!!
}
if (fluid.getForComponent(component, ["options", "components", context]) && !component[context]) {
// This is an expensive guess since we make it for every component up the stack - must apply the WAVE OF EXPLOSIONS (FLUID-4925) to discover all components first
// This line attempts a hopeful construction of components that could be guessed by nickname through finding them unconstructed
// in options. In the near future we should eagerly BEGIN the process of constructing components, discovering their
// types and then attaching them to the tree VERY EARLY so that we get consistent results from different strategies.
foundComponent = fluid.getForComponent(component, context);
return true;
}
});
return foundComponent;
}
}
};
fluid.triggerMismatchedPathError = function (parsed, parentThat) {
var ref = fluid.renderContextReference(parsed);
fluid.fail("Failed to resolve reference " + ref + " - could not match context with name " +
parsed.context + " from component " + fluid.dumpThat(parentThat) + " at path " + fluid.dumpComponentPath(parentThat) + " component: " , parentThat);
};
fluid.makeStackFetcher = function (parentThat, localRecord, fast) {
var fetcher = function (parsed) {
if (parentThat && parentThat.lifecycleStatus === "destroyed") {
fluid.fail("Cannot resolve reference " + fluid.renderContextReference(parsed) + " from component " + fluid.dumpThat(parentThat) + " which has been destroyed");
}
var context = parsed.context;
if (localRecord && context in localRecord) {
return fluid.get(localRecord[context], parsed.path);
}
var foundComponent = fluid.resolveContext(context, parentThat, fast);
if (!foundComponent && parsed.path !== "") {
fluid.triggerMismatchedPathError(parsed, parentThat);
}
return fluid.getForComponent(foundComponent, parsed.path);
};
return fetcher;
};
fluid.makeStackResolverOptions = function (parentThat, localRecord, fast) {
return $.extend(fluid.copy(fluid.rawDefaults("fluid.makeExpandOptions")), {
ELstyle: "{}",
localRecord: localRecord || {},
fetcher: fluid.makeStackFetcher(parentThat, localRecord, fast),
contextThat: parentThat,
exceptions: {members: {model: true, modelRelay: true}}
});
};
fluid.clearListeners = function (shadow) {
// TODO: bug here - "afterDestroy" listeners will be unregistered already unless they come from this component
fluid.each(shadow.listeners, function (rec) {
rec.event.removeListener(rec.listenerId || rec.listener);
});
delete shadow.listeners;
};
fluid.recordListener = function (event, listener, shadow, listenerId) {
if (event.ownerId !== shadow.that.id) { // don't bother recording listeners registered from this component itself
fluid.pushArray(shadow, "listeners", {event: event, listener: listener, listenerId: listenerId});
}
};
fluid.constructScopeObjects = function (instantiator, parent, child, childShadow) {
var parentShadow = parent ? instantiator.idToShadow[parent.id] : null;
childShadow.childrenScope = parentShadow ? Object.create(parentShadow.ownScope) : {};
childShadow.ownScope = Object.create(childShadow.childrenScope);
childShadow.parentShadow = parentShadow;
};
fluid.clearChildrenScope = function (instantiator, parentShadow, child, childShadow) {
fluid.each(childShadow.contextHash, function (troo, context) {
if (parentShadow.childrenScope[context] === child) {
delete parentShadow.childrenScope[context]; // TODO: ambiguous resolution
}
});
};
// unsupported, non-API function - however, this structure is of considerable interest to those debugging
// into IoC issues. The structures idToShadow and pathToComponent contain a complete map of the component tree
// forming the surrounding scope
fluid.instantiator = function () {
var that = fluid.typeTag("instantiator");
$.extend(that, {
lifecycleStatus: "constructed",
pathToComponent: {},
idToShadow: {},
modelTransactions: {init: {}}, // a map of transaction id to map of component id to records of components enlisted in a current model initialisation transaction
composePath: fluid.model.composePath, // For speed, we declare that no component's name may contain a period
composeSegments: fluid.model.composeSegments,
parseEL: fluid.model.parseEL,
events: {
onComponentAttach: fluid.makeEventFirer({name: "instantiator's onComponentAttach event"}),
onComponentClear: fluid.makeEventFirer({name: "instantiator's onComponentClear event"})
}
});
// TODO: this API can shortly be removed
that.idToPath = function (id) {
var shadow = that.idToShadow[id];
return shadow ? shadow.path : "";
};
// Note - the returned stack is assumed writeable and does not include the root
that.getThatStack = function (component) {
var shadow = that.idToShadow[component.id];
if (shadow) {
var path = shadow.path;
var parsed = that.parseEL(path);
var root = that.pathToComponent[""], togo = [];
for (var i = 0; i < parsed.length; ++i) {
root = root[parsed[i]];
togo.push(root);
}
return togo;
}
else { return [];}
};
that.getFullStack = function (component) {
var thatStack = component ? that.getThatStack(component) : [];
thatStack.unshift(fluid.resolveRootComponent);
return thatStack;
};
function recordComponent(parent, component, path, name, created) {
var shadow;
if (created) {
shadow = that.idToShadow[component.id] = {};
shadow.that = component;
shadow.path = path;
shadow.memberName = name;
fluid.constructScopeObjects(that, parent, component, shadow);
} else {
shadow = that.idToShadow[component.id];
shadow.injectedPaths = shadow.injectedPaths || {}; // a hash since we will modify whilst iterating
shadow.injectedPaths[path] = true;
var parentShadow = that.idToShadow[parent.id]; // structural parent shadow - e.g. resolveRootComponent
var keys = fluid.keys(shadow.contextHash);
fluid.remove_if(keys, function (key) {
return shadow.contextHash && shadow.contextHash[key] === "memberName";
});
keys.push(name); // add local name - FLUID-5696 and FLUID-5820
fluid.each(keys, function (context) {
if (!parentShadow.childrenScope[context]) {
parentShadow.childrenScope[context] = component;
}
});
}
if (that.pathToComponent[path]) {
fluid.fail("Error during instantiation - path " + path + " which has just created component " + fluid.dumpThat(component) +
" has already been used for component " + fluid.dumpThat(that.pathToComponent[path]) + " - this is a circular instantiation or other oversight." +
" Please clear the component using instantiator.clearComponent() before reusing the path.");
}
that.pathToComponent[path] = component;
}
that.recordRoot = function (component) {
recordComponent(null, component, "", "", true);
};
that.recordKnownComponent = function (parent, component, name, created) {
parent[name] = component;
if (fluid.isComponent(component) || component.type === "instantiator") {
var parentPath = that.idToShadow[parent.id].path;
var path = that.composePath(parentPath, name);
recordComponent(parent, component, path, name, created);
that.events.onComponentAttach.fire(component, path, that, created);
} else {
fluid.fail("Cannot record non-component with value ", component, " at path \"" + name + "\" of parent ", parent);
}
};
that.clearConcreteComponent = function (destroyRec) {
// Clear injected instance of this component from all other paths - historically we didn't bother
// to do this since injecting into a shorter scope is an error - but now we have resolveRoot area
fluid.each(destroyRec.childShadow.injectedPaths, function (troo, injectedPath) {
var parentPath = fluid.model.getToTailPath(injectedPath);
var otherParent = that.pathToComponent[parentPath];
that.clearComponent(otherParent, fluid.model.getTailPath(injectedPath), destroyRec.child);
});
fluid.clearDistributions(destroyRec.childShadow);
fluid.clearListeners(destroyRec.childShadow);
fluid.clearDynamicParentRecord(destroyRec.shadow, destroyRec.name);
fluid.fireEvent(destroyRec.child, "afterDestroy", [destroyRec.child, destroyRec.name, destroyRec.component]);
delete that.idToShadow[destroyRec.child.id];
};
that.clearComponent = function (component, name, child, options, nested, path) {
// options are visitor options for recursive driving
var shadow = that.idToShadow[component.id];
// use flat recursion since we want to use our own recursion rather than rely on "visited" records
options = options || {flat: true, instantiator: that, destroyRecs: []};
child = child || component[name];
path = path || shadow.path;
if (path === undefined) {
fluid.fail("Cannot clear component " + name + " from component ", component,
" which was not created by this instantiator");
}
var childPath = that.composePath(path, name);
var childShadow = that.idToShadow[child.id];
if (!childShadow) { // Explicit FLUID-5812 check - this can be eliminated once we move visitComponentChildren to instantiator's records
return;
}
var created = childShadow.path === childPath;
that.events.onComponentClear.fire(child, childPath, component, created);
// only recurse on components which were created in place - if the id record disagrees with the
// recurse path, it must have been injected
if (created) {
fluid.visitComponentChildren(child, function (gchild, gchildname, segs, i) {
var parentPath = that.composeSegments.apply(null, segs.slice(0, i));
that.clearComponent(child, gchildname, null, options, true, parentPath);
}, options, that.parseEL(childPath));
fluid.doDestroy(child, name, component); // call "onDestroy", null out events and invokers, setting lifecycleStatus to "destroyed"
options.destroyRecs.push({child: child, childShadow: childShadow, name: name, component: component, shadow: shadow});
} else {
fluid.remove_if(childShadow.injectedPaths, function (troo, path) {
return path === childPath;
});
}
fluid.clearChildrenScope(that, shadow, child, childShadow);
// Note that "pathToComponent" will not be available during afterDestroy. This is so that we can synchronously recreate the component
// in an afterDestroy listener (FLUID-5931). We don't clear up the shadow itself until after afterDestroy.
delete that.pathToComponent[childPath];
if (!nested) {
delete component[name]; // there may be no entry - if creation is not concluded
// Do actual destruction for the whole tree here, including "afterDestroy" and deleting shadows
fluid.each(options.destroyRecs, that.clearConcreteComponent);
}
};
return that;
};
// The global instantiator, holding all components instantiated in this context (instance of Infusion)
fluid.globalInstantiator = fluid.instantiator();
// Look up the globally registered instantiator for a particular component - we now only really support a
// single, global instantiator, but this method is left as a notation point in case this ever reverts
// Returns null if argument is a noncomponent or has no shadow
fluid.getInstantiator = function (component) {
var instantiator = fluid.globalInstantiator;
return component && instantiator.idToShadow[component.id] ? instantiator : null;
};
// The grade supplied to components which will be resolvable from all parts of the component tree
fluid.defaults("fluid.resolveRoot");
// In addition to being resolvable at the root, "resolveRootSingle" component will have just a single instance available. Fresh
// instances will displace older ones.
fluid.defaults("fluid.resolveRootSingle", {
gradeNames: "fluid.resolveRoot"
});
fluid.constructRootComponents = function (instantiator) {
// Instantiate the primordial components at the root of each context tree
fluid.rootComponent = instantiator.rootComponent = fluid.typeTag("fluid.rootComponent");
instantiator.recordRoot(fluid.rootComponent);
// The component which for convenience holds injected instances of all components with fluid.resolveRoot grade
fluid.resolveRootComponent = instantiator.resolveRootComponent = fluid.typeTag("fluid.resolveRootComponent");
instantiator.recordKnownComponent(fluid.rootComponent, fluid.resolveRootComponent, "resolveRootComponent", true);
// obliterate resolveRoot's scope objects and replace by the real root scope - which is unused by its own children
var rootShadow = instantiator.idToShadow[fluid.rootComponent.id];
rootShadow.contextHash = {}; // Fix for FLUID-6128
var resolveRootShadow = instantiator.idToShadow[fluid.resolveRootComponent.id];
resolveRootShadow.ownScope = rootShadow.ownScope;
resolveRootShadow.childrenScope = rootShadow.childrenScope;
instantiator.recordKnownComponent(fluid.resolveRootComponent, instantiator, "instantiator", true); // needs to have a shadow so it can be injected
resolveRootShadow.childrenScope.instantiator = instantiator; // needs to be mounted since it never passes through cacheShadowGrades
};
fluid.constructRootComponents(fluid.globalInstantiator); // currently a singleton - in future, alternative instantiators might come back
/** Expand a set of component options either immediately, or with deferred effect.
* The current policy is to expand immediately function arguments within fluid.assembleCreatorArguments which are not the main options of a
* component. The component's own options take <code>{defer: true}</code> as part of
* <code>outerExpandOptions</code> which produces an "expandOptions" structure holding the "strategy" and "initter" pattern
* common to ginger participants.
* Probably not to be advertised as part of a public API, but is considerably more stable than most of the rest
* of the IoC API structure especially with respect to the first arguments.
*/
// TODO: Can we move outerExpandOptions to 2nd place? only user of 3 and 4 is fluid.makeExpandBlock
// TODO: Actually we want localRecord in 2nd place since outerExpandOptions is now almost disused
fluid.expandOptions = function (args, that, mergePolicy, localRecord, outerExpandOptions) {
if (!args) {
return args;
}
fluid.pushActivity("expandOptions", "expanding options %args for component %that ", {that: that, args: args});
var expandOptions = fluid.makeStackResolverOptions(that, localRecord);
expandOptions.mergePolicy = mergePolicy;
expandOptions.defer = outerExpandOptions && outerExpandOptions.defer;
var expanded = expandOptions.defer ?
fluid.makeExpandOptions(args, expandOptions) : fluid.expand(args, expandOptions);
fluid.popActivity();
return expanded;
};
fluid.localRecordExpected = fluid.arrayToHash(["type", "options", "container", "createOnEvent", "priority", "recordType"]); // last element unavoidably polluting
fluid.checkComponentRecord = function (localRecord) {
fluid.each(localRecord, function (value, key) {
if (!fluid.localRecordExpected[key]) {
fluid.fail("Probable error in subcomponent record ", localRecord, " - key \"" + key +
"\" found, where the only legal options are " +
fluid.keys(fluid.localRecordExpected).join(", "));
}
});
};
fluid.mergeRecordsToList = function (that, mergeRecords) {
var list = [];
fluid.each(mergeRecords, function (value, key) {
value.recordType = key;
if (key === "distributions") {
list.push.apply(list, fluid.transform(value, function (distributedBlock) {
return fluid.computeDistributionPriority(that, distributedBlock);
}));
}
else {
if (!value.options) { return; }
value.priority = fluid.mergeRecordTypes[key];
if (value.priority === undefined) {
fluid.fail("Merge record with unrecognised type " + key + ": ", value);
}
list.push(value);
}
});
return list;
};
// TODO: overall efficiency could huge be improved by resorting to the hated PROTOTYPALISM as an optimisation
// for this mergePolicy which occurs in every component. Although it is a deep structure, the root keys are all we need
var addPolicyBuiltins = function (policy) {
fluid.each(["gradeNames", "mergePolicy", "argumentMap", "components", "dynamicComponents", "events", "listeners", "modelListeners", "modelRelay", "distributeOptions", "transformOptions"], function (key) {
fluid.set(policy, [key, "*", "noexpand"], true);
});
return policy;
};
// used from Fluid.js
fluid.generateExpandBlock = function (record, that, mergePolicy, localRecord) {
var expanded = fluid.expandOptions(record.options, record.contextThat || that, mergePolicy, localRecord, {defer: true});
expanded.priority = record.priority;
expanded.namespace = record.namespace;
expanded.recordType = record.recordType;
return expanded;
};
var expandComponentOptionsImpl = function (mergePolicy, defaults, initRecord, that) {
var defaultCopy = fluid.copy(defaults);
addPolicyBuiltins(mergePolicy);
var shadow = fluid.shadowForComponent(that);
shadow.mergePolicy = mergePolicy;
var mergeRecords = {
defaults: {options: defaultCopy}
};
$.extend(mergeRecords, initRecord.mergeRecords);
// Do this here for gradeless components that were corrected by "localOptions"
if (mergeRecords.subcomponentRecord) {
fluid.checkComponentRecord(mergeRecords.subcomponentRecord);
}
var expandList = fluid.mergeRecordsToList(that, mergeRecords);
var togo = fluid.transform(expandList, function (value) {
return fluid.generateExpandBlock(value, that, mergePolicy, initRecord.localRecord);
});
return togo;
};
fluid.fabricateDestroyMethod = function (that, name, instantiator, child) {
return function () {
instantiator.clearComponent(that, name, child);
};
};
// Computes a name for a component appearing at the global root which is globally unique, from its nickName and id
fluid.computeGlobalMemberName = function (that) {
var nickName = fluid.computeNickName(that.typeName);
return nickName + "-" + that.id;
};
// Maps a type name to the member name to be used for it at a particular path level where it is intended to be unique
// Note that "." is still not supported within a member name
// supported, PUBLIC API function
fluid.typeNameToMemberName = function (typeName) {
return typeName.replace(/\./g, "_");
};
// This is the initial entry point from the non-IoC side reporting the first presence of a new component - called from fluid.mergeComponentOptions
fluid.expandComponentOptions = function (mergePolicy, defaults, userOptions, that) {
var initRecord = userOptions; // might have been tunnelled through "userOptions" from "assembleCreatorArguments"
var instantiator = userOptions && userOptions.marker === fluid.EXPAND ? userOptions.instantiator : null;
fluid.pushActivity("expandComponentOptions", "expanding component options %options with record %record for component %that",
{options: instantiator ? userOptions.mergeRecords.user : userOptions, record: initRecord, that: that});
if (!instantiator) { // it is a top-level component which needs to be attached to the global root
instantiator = fluid.globalInstantiator;
initRecord = { // upgrade "userOptions" to the same format produced by fluid.assembleCreatorArguments via the subcomponent route
mergeRecords: {user: {options: fluid.expandCompact(userOptions, true)}},
memberName: fluid.computeGlobalMemberName(that),
instantiator: instantiator,
parentThat: fluid.rootComponent
};
}
that.destroy = fluid.fabricateDestroyMethod(initRecord.parentThat, initRecord.memberName, instantiator, that);
instantiator.recordKnownComponent(initRecord.parentThat, that, initRecord.memberName, true);
var togo = expandComponentOptionsImpl(mergePolicy, defaults, initRecord, that);
fluid.popActivity();
return togo;
};
/** Given a typeName, determine the final concrete
* "invocation specification" consisting of a concrete global function name
* and argument list which is suitable to be executed directly by fluid.invokeGlobalFunction.
*/
// options is just a disposition record containing memberName, componentRecord
fluid.assembleCreatorArguments = function (parentThat, typeName, options) {
var upDefaults = fluid.defaults(typeName); // we're not responsive to dynamic changes in argMap, but we don't believe in these anyway
if (!upDefaults || !upDefaults.argumentMap) {
fluid.fail("Error in assembleCreatorArguments: cannot look up component type name " + typeName + " to a component creator grade with an argumentMap");
}
var fakeThat = {}; // fake "that" for receiveDistributions since we try to match selectors before creation for FLUID-5013
var distributions = parentThat ? fluid.receiveDistributions(parentThat, upDefaults.gradeNames, options.memberName, fakeThat) : [];
fluid.each(distributions, function (distribution) { // TODO: The duplicated route for this is in fluid.mergeComponentOptions
fluid.computeDistributionPriority(parentThat, distribution);
if (fluid.isPrimitive(distribution.priority)) { // TODO: These should be immutable and parsed just once on registration - but we can't because of crazy target-dependent distance system
distribution.priority = fluid.parsePriority(distribution.priority, 0, false, "options distribution");
}
});
fluid.sortByPriority(distributions);
var localDynamic = options.localDynamic;
var localRecord = $.extend({}, fluid.censorKeys(options.componentRecord, ["type"]), localDynamic);
var argMap = upDefaults.argumentMap;
var findKeys = Object.keys(argMap).concat(["type"]);
fluid.each(findKeys, function (name) {
for (var i = 0; i < distributions.length; ++i) { // Apply non-options material from distributions (FLUID-5013)
if (distributions[i][name] !== undefined) {
localRecord[name] = distributions[i][name];
}
}
});
typeName = localRecord.type || typeName;
delete localRecord.type;
delete localRecord.options;
var mergeRecords = {distributions: distributions};
if (options.componentRecord !== undefined) {
// Deliberately put too many things here so they can be checked in expandComponentOptions (FLUID-4285)
mergeRecords.subcomponentRecord = $.extend({}, options.componentRecord);
}
var args = [];
fluid.each(argMap, function (index, name) {
var arg;
if (name === "options") {
arg = {marker: fluid.EXPAND,
localRecord: localDynamic,
mergeRecords: mergeRecords,
instantiator: fluid.getInstantiator(parentThat),
parentThat: parentThat,
memberName: options.memberName};
} else {
var value = localRecord[name];
arg = fluid.expandImmediate(value, parentThat, localRecord);
}
args[index] = arg;
});
var togo = {
args: args,
funcName: typeName
};
return togo;
};
/** Instantiate the subcomponent with the supplied name of the supplied top-level component. Although this method
* is published as part of the Fluid API, it should not be called by general users and may not remain stable. It is
* currently the only mechanism provided for instantiating components whose definitions are dynamic, and will be
* replaced in time by dedicated declarative framework described by FLUID-5022.
* @param {Component} that - The parent component for which the subcomponent is to be instantiated
* @param {String} name - The name of the component - the index of the options block which configures it as part of the
* <code>components</code> section of its parent's options
* @param {Object} [localRecord] - A local scope record keyed by context names which should specially be in scope for this
* construction, e.g. `arguments`. Primarily for internal framework use.
* @return {Component} The constructed subcomponent
*/
fluid.initDependent = function (that, name, localRecord) {
if (that[name]) { return; } // TODO: move this into strategy
var component = that.options.components[name];
var instance;
var instantiator = fluid.globalInstantiator;
var shadow = instantiator.idToShadow[that.id];
var localDynamic = localRecord || shadow.subcomponentLocal && shadow.subcomponentLocal[name];
fluid.pushActivity("initDependent", "instantiating dependent component at path \"%path\" with record %record as child of %parent",
{path: shadow.path + "." + name, record: component, parent: that});
if (typeof(component) === "string" || component.expander) {
that[name] = fluid.inEvaluationMarker;
instance = fluid.expandImmediate(component, that);
if (instance) {
instantiator.recordKnownComponent(that, instance, name, false);
} else {
delete that[name];
}
}
else if (component.type) {
var type = fluid.expandImmediate(component.type, that, localDynamic);
if (!type) {
fluid.fail("Error in subcomponent record: ", component.type, " could not be resolved to a type for component ", name,
" of parent ", that);
}
var invokeSpec = fluid.assembleCreatorArguments(that, type, {componentRecord: component, memberName: name, localDynamic: localDynamic});
instance = fluid.initSubcomponentImpl(that, {type: invokeSpec.funcName}, invokeSpec.args);
}
else {
fluid.fail("Unrecognised material in place of subcomponent " + name + " - no \"type\" field found");
}
fluid.popActivity();
return instance;
};
fluid.bindDeferredComponent = function (that, componentName, component) {
var events = fluid.makeArray(component.createOnEvent);
fluid.each(events, function (eventName) {
var event = fluid.isIoCReference(eventName) ? fluid.expandOptions(eventName, that) : that.events[eventName];
if (!event || !event.addListener) {
fluid.fail("Error instantiating createOnEvent component with name " + componentName + " of parent ", that, " since event specification " +
eventName + " could not be expanded to an event - got ", event);
}
event.addListener(function () {
fluid.pushActivity("initDeferred", "instantiating deferred component %componentName of parent %that due to event %eventName",
{componentName: componentName, that: that, eventName: eventName});
if (that[componentName]) {
fluid.globalInstantiator.clearComponent(that, componentName);
}
var localRecord = {"arguments": fluid.makeArray(arguments)};
fluid.initDependent(that, componentName, localRecord);
fluid.popActivity();
}, null, component.priority);
});
};
fluid.priorityForComponent = function (component) {
return component.priority ? component.priority :
(component.type === "fluid.typeFount" || fluid.hasGrade(fluid.defaults(component.type), "fluid.typeFount")) ?
"first" : undefined;
};
fluid.initDependents = function (that) {
fluid.pushActivity("initDependents", "instantiating dependent components for component %that", {that: that});
var shadow = fluid.shadowForComponent(that);
shadow.memberStrategy.initter();
shadow.invokerStrategy.initter();
fluid.getForComponent(that, "modelRelay");
fluid.getForComponent(that, "model"); // trigger this as late as possible - but must be before components so that child component has model on its onCreate
if (fluid.isDestroyed(that)) {
return; // Further fix for FLUID-5869 - if we managed to destroy ourselves through some bizarre model self-reaction, bail out here
}
var options = that.options;
var components = options.components || {};
var componentSort = [];
fluid.each(components, function (component, name) {
if (!component.createOnEvent) {
var priority = fluid.priorityForComponent(component);
componentSort.push({namespace: name, priority: fluid.parsePriority(priority)});
}
else {
fluid.bindDeferredComponent(that, name, component);
}
});
fluid.sortByPriority(componentSort);
fluid.each(componentSort, function (entry) {
fluid.initDependent(that, entry.namespace);
});
if (shadow.subcomponentLocal) {
fluid.clear(shadow.subcomponentLocal); // still need repo for event-driven dynamic components - abolish these in time
}
that.lifecycleStatus = "constructed";
fluid.assessTreeConstruction(that, shadow);
fluid.popActivity();
};
fluid.assessTreeConstruction = function (that, shadow) {
var instantiator = fluid.globalInstantiator;
var thatStack = instantiator.getThatStack(that);
var unstableUp = fluid.find_if(thatStack, function (that) {
return that.lifecycleStatus === "constructing";
});
if (unstableUp) {
that.lifecycleStatus = "constructed";
} else {
fluid.markSubtree(instantiator, that, shadow.path, "treeConstructed");
}
};
fluid.markSubtree = function (instantiator, that, path, state) {
that.lifecycleStatus = state;
fluid.visitComponentChildren(that, function (child, name) {
var childPath = instantiator.composePath(path, name);
var childShadow = instantiator.idToShadow[child.id];
var created = childShadow && childShadow.path === childPath;
if (created) {
fluid.markSubtree(instantiator, child, childPath, state);
}
}, {flat: true});
};
/* == BEGIN NEXUS METHODS == */
/**
* Given a component reference, returns the path of that component within its component tree.
*
* @param {Component} component - A reference to a component.
* @param {Instantiator} [instantiator] - (optional) An instantiator to use for the lookup.
* @return {String[]} An array of {String} path segments of the component within its tree, or `null` if the reference does not hold a live component.
*/
fluid.pathForComponent = function (component, instantiator) {
instantiator = instantiator || fluid.getInstantiator(component) || fluid.globalInstantiator;
var shadow = instantiator.idToShadow[component.id];
if (!shadow) {
return null;
}
return instantiator.parseEL(shadow.path);
};
/** Construct a component with the supplied options at the specified path in the component tree. The parent path of the location must already be a component.
* @param {String|String[]} path - Path where the new component is to be constructed, represented as a string or array of string segments
* @param {Object} options - Top-level options supplied to the component - must at the very least include a field <code>type</code> holding the component's type
* @param {Instantiator} [instantiator] - [optional] The instantiator holding the component to be created - if blank, the global instantiator will be used
* @return {Object} The constructed component.
*/
fluid.construct = function (path, options, instantiator) {
var record = fluid.destroy(path, instantiator);
// TODO: We must construct a more principled scheme for designating child components than this - especially once options become immutable
fluid.set(record.parent, ["options", "components", record.memberName], {
type: options.type,
options: options
});
return fluid.initDependent(record.parent, record.memberName);
};
/** Destroys a component held at the specified path. The parent path must represent a component, although the component itself may be nonexistent
* @param {String|String[]} path - Path where the new component is to be destroyed, represented as a string or array of string segments
* @param {Instantiator} [instantiator] - [optional] The instantiator holding the component to be destroyed - if blank, the global instantiator will be used.
* @return {Object} - An object containing a reference to the parent of the destroyed element, and the member name of the destroyed component.
*/
fluid.destroy = function (path, instantiator) {
instantiator = instantiator || fluid.globalInstantiator;
var segs = fluid.model.parseToSegments(path, instantiator.parseEL, true);
if (segs.length === 0) {
fluid.fail("Cannot destroy the root component");
}
var memberName = segs.pop(), parentPath = instantiator.composeSegments.apply(null, segs);
var parent = instantiator.pathToComponent[parentPath];
if (!parent) {
fluid.fail("Cannot modify component with nonexistent parent at path ", path);
}
if (parent[memberName]) {
parent[memberName].destroy();
}
return {
parent: parent,
memberName: memberName
};
};
/** Construct an instance of a component as a child of the specified parent, with a well-known, unique name derived from its typeName
* @param {String|String[]} parentPath - Parent of path where the new component is to be constructed, represented as a {String} or array of {String} segments
* @param {String|Object} options - Options encoding the component to be constructed. If this is of type String, it is assumed to represent the component's typeName with no options
* @param {Instantiator} [instantiator] - [optional] The instantiator holding the component to be created - if blank, the global instantiator will be used
*/
fluid.constructSingle = function (parentPath, options, instantiator) {
instantiator = instantiator || fluid.globalInstantiator;
parentPath = parentPath || "";
var segs = fluid.model.parseToSegments(parentPath, instantiator.parseEL, true);
if (typeof(options) === "string") {
options = {type: options};
}
var type = options.type;
if (!type) {
fluid.fail("Cannot construct singleton object without a type entry");
}
options = $.extend({}, options);
var gradeNames = options.gradeNames = fluid.makeArray(options.gradeNames);
gradeNames.unshift(type); // principal type may be noninstantiable
options.type = "fluid.component";
var root = segs.length === 0;
if (root) {
gradeNames.push("fluid.resolveRoot");
}
var memberName = fluid.typeNameToMemberName(options.singleRootType || type);
segs.push(memberName);
fluid.construct(segs, options, instantiator);
};
/** Destroy an instance created by `fluid.constructSingle`
* @param {String|String[]} parentPath - Parent of path where the new component is to be constructed, represented as a {String} or array of {String} segments
* @param {String} typeName - The type name used to construct the component (either `type` or `singleRootType` of the `options` argument to `fluid.constructSingle`
* @param {Instantiator} [instantiator] - [optional] The instantiator holding the component to be created - if blank, the global instantiator will be used
*/
fluid.destroySingle = function (parentPath, typeName, instantiator) {
instantiator = instantiator || fluid.globalInstantiator;
var segs = fluid.model.parseToSegments(parentPath, instantiator.parseEL, true);
var memberName = fluid.typeNameToMemberName(typeName);
segs.push(memberName);
fluid.destroy(segs, instantiator);
};
/** Registers and constructs a "linkage distribution" which will ensure that wherever a set of "input grades" co-occur, they will
* always result in a supplied "output grades" in the component where they co-occur.
* @param {String} linkageName - The name of the grade which will broadcast the resulting linkage. If required, this linkage can be destroyed by supplying this name to `fluid.destroySingle`.
* @param {String[]} inputNames - An array of grade names which will be tested globally for co-occurrence
* @param {String|String[]} outputNames - A single grade name or array of grade names which will be output into the co-occuring component
*/
fluid.makeGradeLinkage = function (linkageName, inputNames, outputNames) {
fluid.defaults(linkageName, {
gradeNames: "fluid.component",
distributeOptions: {
record: outputNames,
target: "{/ " + inputNames.join("&") + "}.options.gradeNames"
}
});
fluid.constructSingle([], linkageName);
};
/** Retrieves a component by global path.
* @param {String|String[]} path - The global path of the component to look up, expressed as a string or as an array of segments.
* @return {Object} - The component at the specified path, or undefined if none is found.
*/
fluid.componentForPath = function (path) {
return fluid.globalInstantiator.pathToComponent[fluid.isArrayable(path) ? path.join(".") : path];
};
/** END NEXUS METHODS **/
/** BEGIN IOC DEBUGGING METHODS **/
fluid["debugger"] = function () {
debugger; // eslint-disable-line no-debugger
};
fluid.defaults("fluid.debuggingProbe", {
gradeNames: ["fluid.component"]
});
// probe looks like:
// target: {preview other}.listeners.eventName
// priority: first/last
// func: console.log/fluid.log/fluid.debugger
fluid.probeToDistribution = function (probe) {
var instantiator = fluid.globalInstantiator;
var parsed = fluid.parseContextReference(probe.target);
var segs = fluid.model.parseToSegments(parsed.path, instantiator.parseEL, true);
if (segs[0] !== "options") {
segs.unshift("options"); // compensate for this insanity until we have the great options flattening
}
var parsedPriority = fluid.parsePriority(probe.priority);
if (parsedPriority.constraint && !parsedPriority.constraint.target) {
parsedPriority.constraint.target = "authoring";
}
return {
target: "{/ " + parsed.context + "}." + instantiator.composeSegments.apply(null, segs),
record: {
func: probe.func,
funcName: probe.funcName,
args: probe.args,
priority: fluid.renderPriority(parsedPriority)
}
};
};
fluid.registerProbes = function (probes) {
var probeDistribution = fluid.transform(probes, fluid.probeToDistribution);
var memberName = "fluid_debuggingProbe_" + fluid.allocateGuid();
fluid.construct([memberName], {
type: "fluid.debuggingProbe",
distributeOptions: probeDistribution
});
return memberName;
};
fluid.deregisterProbes = function (probeName) {
fluid.destroy([probeName]);
};
/** END IOC DEBUGGING METHODS **/
fluid.thisistToApplicable = function (record, recthis, that) {
return {
apply: function (noThis, args) {
// Resolve this material late, to deal with cases where the target has only just been brought into existence
// (e.g. a jQuery target for rendered material) - TODO: Possibly implement cached versions of these as we might do for invokers
var resolvedThis = fluid.expandOptions(recthis, that);
if (typeof(resolvedThis) === "string") {
resolvedThis = fluid.getGlobalValue(resolvedThis);
}
if (!resolvedThis) {
fluid.fail("Could not resolve reference " + recthis + " to a value");
}
var resolvedFunc = resolvedThis[record.method];
if (typeof(resolvedFunc) !== "function") {
fluid.fail("Object ", resolvedThis, " at reference " + recthis + " has no member named " + record.method + " which is a function ");
}
if (fluid.passLogLevel(fluid.logLevel.TRACE)) {
fluid.log(fluid.logLevel.TRACE, "Applying arguments ", args, " to method " + record.method + " of instance ", resolvedThis);
}
return resolvedFunc.apply(resolvedThis, args);
}
};
};
fluid.changeToApplicable = function (record, that) {
return {
apply: function (noThis, args, localRecord, mergeRecord) {
var parsed = fluid.parseValidModelReference(that, "changePath listener record", record.changePath);
var value = fluid.expandOptions(record.value, that, {}, fluid.extend(localRecord, {"arguments": args}));
var sources = mergeRecord && mergeRecord.source && mergeRecord.source.length ? fluid.makeArray(record.source).concat(mergeRecord.source) : record.source;
parsed.applier.change(parsed.modelSegs, value, record.type, sources); // FLUID-5586 now resolved
}
};
};
// Convert "exotic records" into an applicable form ("this/method" for FLUID-4878 or "changePath" for FLUID-3674)
fluid.recordToApplicable = function (record, that, standard) {
if (record.changePath !== undefined) { // Allow falsy paths for FLUID-5586
return fluid.changeToApplicable(record, that, standard);
}
var recthis = record["this"];
if (record.method ^ recthis) {
fluid.fail("Record ", that, " must contain both entries \"method\" and \"this\" if it contains either");
}
return record.method ? fluid.thisistToApplicable(record, recthis, that) : null;
};
fluid.getGlobalValueNonComponent = function (funcName, context) { // TODO: Guard this in listeners as well
var defaults = fluid.defaults(funcName);
if (defaults && fluid.hasGrade(defaults, "fluid.component")) {
fluid.fail("Error in function specification - cannot invoke function " + funcName + " in the context of " + context + ": component creator functions can only be used as subcomponents");
}
return fluid.getGlobalValue(funcName);
};
fluid.makeInvoker = function (that, invokerec, name) {
invokerec = fluid.upgradePrimitiveFunc(invokerec); // shorthand case for direct function invokers (FLUID-4926)
if (invokerec.args !== undefined && invokerec.args !== fluid.NO_VALUE && !fluid.isArrayable(invokerec.args)) {
invokerec.args = fluid.makeArray(invokerec.args);
}
var func = fluid.recordToApplicable(invokerec, that);
var invokePre = fluid.preExpand(invokerec.args);
var localRecord = {};
var expandOptions = fluid.makeStackResolverOptions(that, localRecord, true);
func = func || (invokerec.funcName ? fluid.getGlobalValueNonComponent(invokerec.funcName, "an invoker") : fluid.expandImmediate(invokerec.func, that));
if (!func || !func.apply) {
fluid.fail("Error in invoker record: could not resolve members func, funcName or method to a function implementation - got " + func + " from ", invokerec);
} else if (func === fluid.notImplemented) {
fluid.fail("Error constructing component ", that, " - the invoker named " + name + " which was defined in grade " + invokerec.componentSource + " needs to be overridden with a concrete implementation");
}
return function invokeInvoker() {
if (fluid.defeatLogging === false) {
fluid.pushActivity("invokeInvoker", "invoking invoker with name %name and record %record from path %path holding component %that",
{name: name, record: invokerec, path: fluid.dumpComponentPath(that), that: that});
}
var togo, finalArgs;
if (that.lifecycleStatus === "destroyed") {
fluid.log(fluid.logLevel.WARN, "Ignoring call to invoker " + name + " of component ", that, " which has been destroyed");
} else {
localRecord.arguments = arguments;
if (invokerec.args === undefined || invokerec.args === fluid.NO_VALUE) {
finalArgs = arguments;
} else {
fluid.expandImmediateImpl(invokePre, expandOptions);
finalArgs = invokePre.source;
}
togo = func.apply(null, finalArgs);
}
if (fluid.defeatLogging === false) {
fluid.popActivity();
}
return togo;
};
};
// weird higher-order function so that we can staightforwardly dispatch original args back onto listener
fluid.event.makeTrackedListenerAdder = function (source) {
var shadow = fluid.shadowForComponent(source);
return function (event) {
return {addListener: function (listener, namespace, priority, softNamespace, listenerId) {
fluid.recordListener(event, listener, shadow, listenerId);
event.addListener.apply(null, arguments);
}};
};
};
fluid.event.listenerEngine = function (eventSpec, callback, adder) {
var argstruc = {};
function checkFire() {
var notall = fluid.find(eventSpec, function (value, key) {
if (argstruc[key] === undefined) {
return true;
}
});
if (!notall) {
var oldstruc = argstruc;
argstruc = {}; // guard against the case the callback perversely fires one of its prerequisites (FLUID-5112)
callback(oldstruc);
}
}
fluid.each(eventSpec, function (event, eventName) {
adder(event).addListener(function () {
argstruc[eventName] = fluid.makeArray(arguments);
checkFire();
});
});
};
fluid.event.dispatchListener = function (that, listener, eventName, eventSpec, wrappedArgs) {
if (eventSpec.args !== undefined && eventSpec.args !== fluid.NO_VALUE && !fluid.isArrayable(eventSpec.args)) {
eventSpec.args = fluid.makeArray(eventSpec.args);
}
listener = fluid.event.resolveListener(listener); // In theory this optimisation is too aggressive if global name is not defined yet
var dispatchPre = fluid.preExpand(eventSpec.args);
var localRecord = {};
var expandOptions = fluid.makeStackResolverOptions(that, localRecord, true);
var togo = function () {
if (fluid.defeatLogging === false) {
fluid.pushActivity("dispatchListener", "firing to listener to event named %eventName of component %that",
{eventName: eventName, that: that});
}
var args = wrappedArgs ? arguments[0] : arguments, finalArgs;
localRecord.arguments = args;
if (eventSpec.args !== undefined && eventSpec.args !== fluid.NO_VALUE) {
// In theory something more exotic happens here, and in makeInvoker - where "source" is an array we want to
// keep its base reference stable since Function.apply will fork it sufficiently, but we really need to
// clone each structured argument. Implies that expandImmediateImpl needs to be split in two, and operate
// reference by "segs" rather than by "holder"
fluid.expandImmediateImpl(dispatchPre, expandOptions);
finalArgs = dispatchPre.source;
} else {
finalArgs = args;
}
var togo = listener.apply(null, finalArgs);
if (fluid.defeatLogging === false) {
fluid.popActivity();
}
return togo;
};
fluid.event.impersonateListener(listener, togo); // still necessary for FLUID-5254 even though framework's listeners now get explicit guids
return togo;
};
fluid.event.resolveSoftNamespace = function (key) {
if (typeof(key) !== "string") {
return null;
} else {
var lastpos = Math.max(key.lastIndexOf("."), key.lastIndexOf("}"));
return key.substring(lastpos + 1);
}
};
fluid.event.resolveListenerRecord = function (lisrec, that, eventName, namespace, standard) {
var badRec = function (record, extra) {
fluid.fail("Error in listener record - could not resolve reference ", record, " to a listener or firer. " +
"Did you miss out \"events.\" when referring to an event firer?" + extra);
};
fluid.pushActivity("resolveListenerRecord", "resolving listener record for event named %eventName for component %that",
{eventName: eventName, that: that});
var records = fluid.makeArray(lisrec);
var transRecs = fluid.transform(records, function (record) {
// TODO: FLUID-5242 fix - we copy here since distributeOptions does not copy options blocks that it distributes and we can hence corrupt them.
// need to clarify policy on options sharing - for slightly better efficiency, copy should happen during distribution and not here
// Note that fluid.mergeModelListeners expects to write to these too
var expanded = fluid.isPrimitive(record) || record.expander ? {listener: record} : fluid.copy(record);
var methodist = fluid.recordToApplicable(record, that, standard);
if (methodist) {
expanded.listener = methodist;
}
else {
expanded.listener = expanded.listener || expanded.func || expanded.funcName;
}
if (!expanded.listener) {
badRec(record, " Listener record must contain a member named \"listener\", \"func\", \"funcName\" or \"method\"");
}
var softNamespace = record.method ?
fluid.event.resolveSoftNamespace(record["this"]) + "." + record.method :
fluid.event.resolveSoftNamespace(expanded.listener);
if (!expanded.namespace && !namespace && softNamespace) {
expanded.softNamespace = true;
expanded.namespace = (record.componentSource ? record.componentSource : that.typeName) + "." + softNamespace;
}
var listener = expanded.listener = fluid.expandOptions(expanded.listener, that);
if (!listener) {
badRec(record, "");
}
var firer = false;
if (listener.typeName === "fluid.event.firer") {
listener = listener.fire;
firer = true;
}
expanded.listener = (standard && (expanded.args && listener !== "fluid.notImplemented" || firer)) ? fluid.event.dispatchListener(that, listener, eventName, expanded) : listener;
expanded.listenerId = fluid.allocateGuid();
return expanded;
});
var togo = {
records: transRecs,
adderWrapper: standard ? fluid.event.makeTrackedListenerAdder(that) : null
};
fluid.popActivity();
return togo;
};
fluid.event.expandOneEvent = function (that, event) {
var origin;
if (typeof(event) === "string" && event.charAt(0) !== "{") {
// Shorthand for resolving onto our own events, but with GINGER WORLD!
origin = fluid.getForComponent(that, ["events", event]);
}
else {
origin = fluid.expandOptions(event, that);
}
if (!origin || origin.typeName !== "fluid.event.firer") {
fluid.fail("Error in event specification - could not resolve base event reference ", event, " to an event firer: got ", origin);
}
return origin;
};
fluid.event.expandEvents = function (that, event) {
return typeof(event) === "string" ?
fluid.event.expandOneEvent(that, event) :
fluid.transform(event, function (oneEvent) {
return fluid.event.expandOneEvent(that, oneEvent);
});
};
fluid.event.resolveEvent = function (that, eventName, eventSpec) {
fluid.pushActivity("resolveEvent", "resolving event with name %eventName attached to component %that",
{eventName: eventName, that: that});
var adder = fluid.event.makeTrackedListenerAdder(that);
if (typeof(eventSpec) === "string") {
eventSpec = {event: eventSpec};
}
var event = eventSpec.typeName === "fluid.event.firer" ? eventSpec : eventSpec.event || eventSpec.events;
if (!event) {
fluid.fail("Event specification for event with name " + eventName + " does not include a base event specification: ", eventSpec);
}
var origin = event.typeName === "fluid.event.firer" ? event : fluid.event.expandEvents(that, event);
var isMultiple = origin.typeName !== "fluid.event.firer";
var isComposite = eventSpec.args || isMultiple;
// If "event" is not composite, we want to share the listener list and FIRE method with the original
// If "event" is composite, we need to create a new firer. "composite" includes case where any boiling
// occurred - this was implemented wrongly in 1.4.
var firer;
if (isComposite) {
firer = fluid.makeEventFirer({name: " [composite] " + fluid.event.nameEvent(that, eventName)});
var dispatcher = fluid.event.dispatchListener(that, firer.fire, eventName, eventSpec, isMultiple);
if (isMultiple) {
fluid.event.listenerEngine(origin, dispatcher, adder);
}
else {
adder(origin).addListener(dispatcher);
}
}
else {
firer = {typeName: "fluid.event.firer"};
firer.fire = function () {
var outerArgs = fluid.makeArray(arguments);
fluid.pushActivity("fireSynthetic", "firing synthetic event %eventName ", {eventName: eventName});
var togo = origin.fire.apply(null, outerArgs);
fluid.popActivity();
return togo;
};
firer.addListener = function (listener, namespace, priority, softNamespace, listenerId) {
var dispatcher = fluid.event.dispatchListener(that, listener, eventName, eventSpec);
adder(origin).addListener(dispatcher, namespace, priority, softNamespace, listenerId);
};
firer.removeListener = function (listener) {
origin.removeListener(listener);
};
// To allow introspection on listeners in cases such as fluid.test.findListenerId
firer.originEvent = origin;
}
fluid.popActivity();
return firer;
};
/** BEGIN unofficial IoC material **/
// The following three functions are unsupported ane only used in the renderer expander.
// The material they produce is no longer recognised for component resolution.
fluid.withEnvironment = function (envAdd, func, root) {
var key;
root = root || fluid.globalThreadLocal();
try {
for (key in envAdd) {
root[key] = envAdd[key];
}
$.extend(root, envAdd);
return func();
} finally {
for (key in envAdd) {
delete root[key]; // TODO: users may want a recursive "scoping" model
}
}
};
fluid.fetchContextReference = function (parsed, directModel, env, elResolver, externalFetcher) {
// The "elResolver" is a hack to make certain common idioms in protoTrees work correctly, where a contextualised EL
// path actually resolves onto a further EL reference rather than directly onto a value target
if (elResolver) {
parsed = elResolver(parsed, env);
}
var base = parsed.context ? env[parsed.context] : directModel;
if (!base) {
var resolveExternal = externalFetcher && externalFetcher(parsed);
return resolveExternal || base;
}
return parsed.noDereference ? parsed.path : fluid.get(base, parsed.path);
};
fluid.makeEnvironmentFetcher = function (directModel, elResolver, envGetter, externalFetcher) {
envGetter = envGetter || fluid.globalThreadLocal;
return function (parsed) {
var env = envGetter();
return fluid.fetchContextReference(parsed, directModel, env, elResolver, externalFetcher);
};
};
/** END of unofficial IoC material **/
/* Compact expansion machinery - for short form invoker and expander references such as @expand:func(arg) and func(arg) */
fluid.coerceToPrimitive = function (string) {
return string === "false" ? false : (string === "true" ? true :
(isFinite(string) ? Number(string) : string));
};
fluid.compactStringToRec = function (string, type) {
var openPos = string.indexOf("(");
var closePos = string.indexOf(")");
if (openPos === -1 ^ closePos === -1 || openPos > closePos) {
fluid.fail("Badly-formed compact " + type + " record without matching parentheses: " + string);
}
if (openPos !== -1 && closePos !== -1) {
var trail = string.substring(closePos + 1);
if ($.trim(trail) !== "") {
fluid.fail("Badly-formed compact " + type + " record " + string + " - unexpected material following close parenthesis: " + trail);
}
var prefix = string.substring(0, openPos);
var body = $.trim(string.substring(openPos + 1, closePos));
var args = body === "" ? [] : fluid.transform(body.split(","), $.trim, fluid.coerceToPrimitive);
var togo = fluid.upgradePrimitiveFunc(prefix, null);
togo.args = args;
return togo;
}
else if (type === "expander") {
fluid.fail("Badly-formed compact expander record without parentheses: " + string);
}
return string;
};
fluid.expandPrefix = "@expand:";
fluid.expandCompactString = function (string, active) {
var rec = string;
if (string.indexOf(fluid.expandPrefix) === 0) {
var rem = string.substring(fluid.expandPrefix.length);
rec = {
expander: fluid.compactStringToRec(rem, "expander")
};
}
else if (active) {
rec = fluid.compactStringToRec(string, active);
}
return rec;
};
var singularPenRecord = {
listeners: "listener",
modelListeners: "modelListener"
};
var singularRecord = $.extend({
invokers: "invoker"
}, singularPenRecord);
fluid.expandCompactRec = function (segs, target, source) {
fluid.guardCircularExpansion(segs, segs.length);
var pen = segs.length > 0 ? segs[segs.length - 1] : "";
var active = singularRecord[pen];
if (!active && segs.length > 1) {
active = singularPenRecord[segs[segs.length - 2]]; // support array of listeners and modelListeners
}
fluid.each(source, function (value, key) {
if (fluid.isPlainObject(value)) {
target[key] = fluid.freshContainer(value);
segs.push(key);
fluid.expandCompactRec(segs, target[key], value);
segs.pop();
return;
}
else if (typeof(value) === "string") {
value = fluid.expandCompactString(value, active);
}
target[key] = value;
});
};
fluid.expandCompact = function (options) {
var togo = {};
fluid.expandCompactRec([], togo, options);
return togo;
};
/** End compact record expansion machinery **/
fluid.extractEL = function (string, options) {
if (options.ELstyle === "ALL" || options.ELstyle === "{}") {
return string;
}
else if (options.ELstyle.length === 1) {
if (string.charAt(0) === options.ELstyle) {
return string.substring(1);
}
}
else if (options.ELstyle === "${}") {
var i1 = string.indexOf("${");
var i2 = string.lastIndexOf("}");
if (i1 === 0 && i2 !== -1) {
return string.substring(2, i2);
}
}
};
fluid.extractELWithContext = function (string, options) {
var EL = fluid.extractEL(string, options);
if (fluid.isIoCReference(EL)) {
return fluid.parseContextReference(EL);
} else if (options.ELstyle === "{}") {
return null;
}
return EL ? {path: EL} : EL;
};
/** Parse the string form of a contextualised IoC reference into an object.
* @param {String} reference - The reference to be parsed. The character at position `index` is assumed to be `{`
* @param {String} [index] - [optional] The index into the string to start parsing at, if omitted, defaults to 0
* @param {Character} [delimiter] - [optional] A character which will delimit the end of the context expression. If omitted, the expression continues to the end of the string.
* @return {ParsedContext} A structure holding the parsed structure, with members
* context {String|ParsedContext} The context portion of the reference. This will be a `string` for a flat reference, or a further `ParsedContext` for a recursive reference
* path {String} The string portion of the reference
* endpos {Integer} The position in the string where parsing stopped [this member is not supported and will be removed in a future release]
*/
fluid.parseContextReference = function (reference, index, delimiter) {
index = index || 0;
var isNested = reference.charAt(index + 1) === "{", endcpos, context, nested;
if (isNested) {
nested = fluid.parseContextReference(reference, index + 1, "}");
endcpos = nested.endpos;
} else {
endcpos = reference.indexOf("}", index + 1);
}
if (endcpos === -1) {
fluid.fail("Cannot parse context reference \"" + reference + "\": Malformed context reference without }");
}
if (isNested) {
context = nested;
} else {
context = reference.substring(index + 1, endcpos);
}
var endpos = delimiter ? reference.indexOf(delimiter, endcpos + 1) : reference.length;
var path = reference.substring(endcpos + 1, endpos);
if (path.charAt(0) === ".") {
path = path.substring(1);
}
return {context: context, path: path, endpos: endpos};
};
fluid.renderContextReference = function (parsed) {
var context = parsed.context;
return "{" + (fluid.isPrimitive(context) ? context : fluid.renderContextReference(context)) + "}" + (parsed.path ? "." + parsed.path : "");
};
// TODO: Once we eliminate expandSource (in favour of fluid.expander.fetch), all of this tree of functions can be hived off to RendererUtilities
fluid.resolveContextValue = function (string, options) {
function fetch(parsed) {
fluid.pushActivity("resolveContextValue", "resolving context value %parsed", {parsed: parsed});
var togo = options.fetcher(parsed);
fluid.pushActivity("resolvedContextValue", "resolved value %parsed to value %value", {parsed: parsed, value: togo});
fluid.popActivity(2);
return togo;
}
var parsed;
if (options.bareContextRefs && fluid.isIoCReference(string)) {
parsed = fluid.parseContextReference(string);
return fetch(parsed);
}
else if (options.ELstyle && options.ELstyle !== "${}") {
parsed = fluid.extractELWithContext(string, options);
if (parsed) {
return fetch(parsed);
}
}
if (options.ELstyle === "${}") {
while (typeof(string) === "string") {
var i1 = string.indexOf("${");
var i2 = string.indexOf("}", i1 + 2);
if (i1 !== -1 && i2 !== -1) {
if (string.charAt(i1 + 2) === "{") {
parsed = fluid.parseContextReference(string, i1 + 2, "}");
i2 = parsed.endpos;
}
else {
parsed = {path: string.substring(i1 + 2, i2)};
}
var subs = fetch(parsed);
var all = (i1 === 0 && i2 === string.length - 1);
// TODO: test case for all undefined substitution
if (subs === undefined || subs === null) {
return subs;
}
string = all ? subs : string.substring(0, i1) + subs + string.substring(i2 + 1);
}
else {
break;
}
}
}
return string;
};
// This function appears somewhat reusable, but not entirely - it probably needs to be packaged
// along with the particular "strategy". Very similar to the old "filter"... the "outer driver" needs
// to execute it to get the first recursion going at top level. This was one of the most odd results
// of the reorganisation, since the "old work" seemed much more naturally expressed in terms of values
// and what happened to them. The "new work" is expressed in terms of paths and how to move amongst them.
fluid.fetchExpandChildren = function (target, i, segs, source, mergePolicy, options) {
if (source.expander) { // possible expander at top level
var expanded = fluid.expandExpander(target, source, options);
if (fluid.isPrimitive(expanded) || !fluid.isPlainObject(expanded) || (fluid.isArrayable(expanded) ^ fluid.isArrayable(target))) {
return expanded;
}
else { // make an attempt to preserve the root reference if possible
$.extend(true, target, expanded);
}
}
// NOTE! This expects that RHS is concrete! For material input to "expansion" this happens to be the case, but is not
// true for other algorithms. Inconsistently, this algorithm uses "sourceStrategy" below. In fact, this "fetchChildren"
// operation looks like it is a fundamental primitive of the system. We do call "deliverer" early which enables correct
// reference to parent nodes up the tree - however, anyone processing a tree IN THE CHAIN requires that it is produced
// concretely at the point STRATEGY returns. Which in fact it is...............
fluid.each(source, function (newSource, key) {
if (newSource === undefined) {
target[key] = undefined; // avoid ever dispatching to ourselves with undefined source
}
else if (key !== "expander") {
segs[i] = key;
if (fluid.getImmediate(options.exceptions, segs, i) !== true) {
options.strategy(target, key, i + 1, segs, source, mergePolicy);
}
}
});
return target;
};
// TODO: This method is unnecessary and will quadratic inefficiency if RHS block is not concrete.
// The driver should detect "homogeneous uni-strategy trundling" and agree to preserve the extra
// "cursor arguments" which should be advertised somehow (at least their number)
function regenerateCursor(source, segs, limit, sourceStrategy) {
for (var i = 0; i < limit; ++i) {
// copy segs to avoid aliasing with FLUID-5243
source = sourceStrategy(source, segs[i], i, fluid.makeArray(segs));
}
return source;
}
fluid.isUnexpandable = function (source) { // slightly more efficient compound of fluid.isCopyable and fluid.isComponent - review performance
return fluid.isPrimitive(source) || !fluid.isPlainObject(source);
};
fluid.expandSource = function (options, target, i, segs, deliverer, source, policy, recurse) {
var expanded, isTrunk;
var thisPolicy = fluid.derefMergePolicy(policy);
if (typeof (source) === "string" && !thisPolicy.noexpand) {
if (!options.defaultEL || source.charAt(0) === "{") { // hard-code this for performance
fluid.pushActivity("expandContextValue", "expanding context value %source held at path %path", {source: source, path: fluid.path.apply(null, segs.slice(0, i))});
expanded = fluid.resolveContextValue(source, options);
fluid.popActivity(1);
} else {
expanded = source;
}
}
else if (thisPolicy.noexpand || fluid.isUnexpandable(source)) {
expanded = source;
}
else if (source.expander) {
expanded = fluid.expandExpander(deliverer, source, options);
}
else {
expanded = fluid.freshContainer(source);
isTrunk = true;
}
if (expanded !== fluid.NO_VALUE) {
deliverer(expanded);
}
if (isTrunk) {
recurse(expanded, source, i, segs, policy);
}
return expanded;
};
fluid.guardCircularExpansion = function (segs, i) {
if (i > fluid.strategyRecursionBailout) {
fluid.fail("Overflow/circularity in options expansion, current path is ", segs, " at depth " , i, " - please ensure options are not circularly connected, or protect from expansion using the \"noexpand\" policy or expander");
}
};
fluid.makeExpandStrategy = function (options) {
var recurse = function (target, source, i, segs, policy) {
return fluid.fetchExpandChildren(target, i || 0, segs || [], source, policy, options);
};
var strategy = function (target, name, i, segs, source, policy) {
fluid.guardCircularExpansion(segs, i);
if (!target) {
return;
}
if (target.hasOwnProperty(name)) { // bail out if our work has already been done
return target[name];
}
if (source === undefined) { // recover our state in case this is an external entry point
source = regenerateCursor(options.source, segs, i - 1, options.sourceStrategy);
policy = regenerateCursor(options.mergePolicy, segs, i - 1, fluid.concreteTrundler);
}
var thisSource = options.sourceStrategy(source, name, i, segs);
var thisPolicy = fluid.concreteTrundler(policy, name);
function deliverer(value) {
target[name] = value;
}
return fluid.expandSource(options, target, i, segs, deliverer, thisSource, thisPolicy, recurse);
};
options.recurse = recurse;
options.strategy = strategy;
return strategy;
};
fluid.defaults("fluid.makeExpandOptions", {
ELstyle: "${}",
bareContextRefs: true,
target: fluid.inCreationMarker
});
fluid.makeExpandOptions = function (source, options) {
options = $.extend({}, fluid.rawDefaults("fluid.makeExpandOptions"), options);
options.defaultEL = options.ELStyle === "${}" && options.bareContextRefs; // optimisation to help expander
options.expandSource = function (source) {
return fluid.expandSource(options, null, 0, [], fluid.identity, source, options.mergePolicy, false);
};
if (!fluid.isUnexpandable(source)) {
options.source = source;
options.target = fluid.freshContainer(source);
options.sourceStrategy = options.sourceStrategy || fluid.concreteTrundler;
fluid.makeExpandStrategy(options);
options.initter = function () {
options.target = fluid.fetchExpandChildren(options.target, 0, [], options.source, options.mergePolicy, options);
};
}
else { // these init immediately since we must deliver a valid root target
options.strategy = fluid.concreteTrundler;
options.initter = fluid.identity;
if (typeof(source) === "string") {
// Copy is necessary to resolve FLUID-6213 since targets are regularly scrawled over with "undefined" by dim expansion pathway
// However, we can't screw up object identity for uncloneable things like events resolved via local expansion
options.target = (options.defer ? fluid.copy : fluid.identity)(options.expandSource(source));
}
else {
options.target = source;
}
options.immutableTarget = true;
}
return options;
};
// supported, PUBLIC API function
fluid.expand = function (source, options) {
var expandOptions = fluid.makeExpandOptions(source, options);
expandOptions.initter();
return expandOptions.target;
};
fluid.preExpandRecurse = function (root, source, holder, member, rootSegs) { // on entry, holder[member] = source
fluid.guardCircularExpansion(rootSegs, rootSegs.length);
function pushExpander(expander) {
root.expanders.push({expander: expander, holder: holder, member: member});
delete holder[member];
}
if (fluid.isIoCReference(source)) {
var parsed = fluid.parseContextReference(source);
var segs = fluid.model.parseEL(parsed.path);
pushExpander({
typeFunc: fluid.expander.fetch,
context: parsed.context,
segs: segs
});
} else if (fluid.isPlainObject(source)) {
if (source.expander) {
source.expander.typeFunc = fluid.getGlobalValue(source.expander.type || "fluid.invokeFunc");
pushExpander(source.expander);
} else {
fluid.each(source, function (value, key) {
rootSegs.push(key);
fluid.preExpandRecurse(root, value, source, key, rootSegs);
rootSegs.pop();
});
}
}
};
fluid.preExpand = function (source) {
var root = {
expanders: [],
source: fluid.isUnexpandable(source) ? source : fluid.copy(source)
};
fluid.preExpandRecurse(root, root.source, root, "source", []);
return root;
};
// Main pathway for freestanding material that is not part of a component's options
fluid.expandImmediate = function (source, that, localRecord) {
var options = fluid.makeStackResolverOptions(that, localRecord, true); // TODO: ELstyle and target are now ignored
var root = fluid.preExpand(source);
fluid.expandImmediateImpl(root, options);
return root.source;
};
// High performance expander for situations such as invokers, listeners, where raw materials can be cached - consumes "root" structure produced by preExpand
fluid.expandImmediateImpl = function (root, options) {
var expanders = root.expanders;
for (var i = 0; i < expanders.length; ++i) {
var expander = expanders[i];
expander.holder[expander.member] = expander.expander.typeFunc(null, expander, options);
}
};
fluid.expandExpander = function (deliverer, source, options) {
var expander = fluid.getGlobalValue(source.expander.type || "fluid.invokeFunc");
if (!expander) {
fluid.fail("Unknown expander with type " + source.expander.type);
}
return expander(deliverer, source, options);
};
fluid.registerNamespace("fluid.expander");
// "deliverer" is null in the new (fast) pathway, this is a relic of the old "source expander" signature. It appears we can already globally remove this
fluid.expander.fetch = function (deliverer, source, options) {
var localRecord = options.localRecord, context = source.expander.context, segs = source.expander.segs;
// TODO: Either type-check on context as string or else create fetchSlow
var inLocal = localRecord[context] !== undefined;
var contextStatus = options.contextThat.lifecycleStatus;
// somewhat hack to anticipate "fits" for FLUID-4925 - we assume that if THIS component is in construction, its reference target might be too
// if context is destroyed, we are most likely in an afterDestroy listener and so path records have been destroyed
var fast = contextStatus === "treeConstructed" || contextStatus === "destroyed";
var component = inLocal ? localRecord[context] : fluid.resolveContext(context, options.contextThat, fast);
if (component) {
var root = component;
if (inLocal || component.lifecycleStatus !== "constructing") {
for (var i = 0; i < segs.length; ++i) { // fast resolution of paths when no ginger process active
root = root ? root[segs[i]] : undefined;
}
} else {
root = fluid.getForComponent(component, segs);
}
if (root === undefined && !inLocal) { // last-ditch attempt to get exotic EL value from component
root = fluid.getForComponent(component, segs);
}
return root;
} else if (segs.length > 0) {
fluid.triggerMismatchedPathError(source.expander, options.contextThat);
}
};
/* "light" expanders, starting with the default expander invokeFunc,
which makes an arbitrary function call (after expanding arguments) and are then replaced in
the configuration with the call results. These will probably be abolished and replaced with
equivalent model transformation machinery */
// This one is now positioned as the "universal expander" - default if no type supplied
fluid.invokeFunc = function (deliverer, source, options) {
var expander = source.expander;
var args = fluid.makeArray(expander.args);
expander.args = args; // head off case where args is an EL reference which resolves to an array
if (options.recurse) { // only available in the path from fluid.expandOptions - this will be abolished in the end
args = options.recurse([], args);
} else {
expander = fluid.expandImmediate(expander, options.contextThat, options.localRecord);
args = expander.args;
}
var funcEntry = expander.func || expander.funcName;
var func = (options.expandSource ? options.expandSource(funcEntry) : funcEntry) || fluid.recordToApplicable(expander, options.contextThat);
if (typeof(func) === "string") {
func = fluid.getGlobalValue(func);
}
if (!func) {
fluid.fail("Error in expander record ", expander, ": " + funcEntry + " could not be resolved to a function for component ", options.contextThat);
}
return func.apply(null, args);
};
// The "noexpand" expander which simply unwraps one level of expansion and ceases.
fluid.noexpand = function (deliverer, source) {
return source.expander.value ? source.expander.value : source.expander.tree;
};
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
/** NOTE: The contents of this file are by default NOT PART OF THE PUBLIC FLUID API unless explicitly annotated before the function **/
/** MODEL ACCESSOR ENGINE **/
/** Standard strategies for resolving path segments **/
fluid.model.makeEnvironmentStrategy = function (environment) {
return function (root, segment, index) {
return index === 0 && environment[segment] ?
environment[segment] : undefined;
};
};
fluid.model.defaultCreatorStrategy = function (root, segment) {
if (root[segment] === undefined) {
root[segment] = {};
return root[segment];
}
};
fluid.model.defaultFetchStrategy = function (root, segment) {
return root[segment];
};
fluid.model.funcResolverStrategy = function (root, segment) {
if (root.resolvePathSegment) {
return root.resolvePathSegment(segment);
}
};
fluid.model.traverseWithStrategy = function (root, segs, initPos, config, uncess) {
var strategies = config.strategies;
var limit = segs.length - uncess;
for (var i = initPos; i < limit; ++i) {
if (!root) {
return root;
}
var accepted;
for (var j = 0; j < strategies.length; ++j) {
accepted = strategies[j](root, segs[i], i + 1, segs);
if (accepted !== undefined) {
break; // May now short-circuit with stateless strategies
}
}
if (accepted === fluid.NO_VALUE) {
accepted = undefined;
}
root = accepted;
}
return root;
};
/* Returns both the value and the path of the value held at the supplied EL path */
fluid.model.getValueAndSegments = function (root, EL, config, initSegs) {
return fluid.model.accessWithStrategy(root, EL, fluid.NO_VALUE, config, initSegs, true);
};
// Very lightweight remnant of trundler, only used in resolvers
fluid.model.makeTrundler = function (config) {
return function (valueSeg, EL) {
return fluid.model.getValueAndSegments(valueSeg.root, EL, config, valueSeg.segs);
};
};
fluid.model.getWithStrategy = function (root, EL, config, initSegs) {
return fluid.model.accessWithStrategy(root, EL, fluid.NO_VALUE, config, initSegs);
};
fluid.model.setWithStrategy = function (root, EL, newValue, config, initSegs) {
fluid.model.accessWithStrategy(root, EL, newValue, config, initSegs);
};
fluid.model.accessWithStrategy = function (root, EL, newValue, config, initSegs, returnSegs) {
// This function is written in this unfortunate style largely for efficiency reasons. In many cases
// it should be capable of running with 0 allocations (EL is preparsed, initSegs is empty)
if (!fluid.isPrimitive(EL) && !fluid.isArrayable(EL)) {
var key = EL.type || "default";
var resolver = config.resolvers[key];
if (!resolver) {
fluid.fail("Unable to find resolver of type " + key);
}
var trundler = fluid.model.makeTrundler(config); // very lightweight trundler for resolvers
var valueSeg = {root: root, segs: initSegs};
valueSeg = resolver(valueSeg, EL, trundler);
if (EL.path && valueSeg) { // every resolver supports this piece of output resolution
valueSeg = trundler(valueSeg, EL.path);
}
return returnSegs ? valueSeg : (valueSeg ? valueSeg.root : undefined);
}
else {
return fluid.model.accessImpl(root, EL, newValue, config, initSegs, returnSegs, fluid.model.traverseWithStrategy);
}
};
// Implementation notes: The EL path manipulation utilities here are equivalents of the simpler ones
// that are provided in Fluid.js and elsewhere - they apply escaping rules to parse characters .
// as \. and \ as \\ - allowing us to process member names containing periods. These versions are mostly
// in use within model machinery, whereas the cheaper versions based on String.split(".") are mostly used
// within the IoC machinery.
// Performance testing in early 2015 suggests that modern browsers now allow these to execute slightly faster
// than the equivalent machinery written using complex regexps - therefore they will continue to be maintained
// here. However, there is still a significant performance gap with respect to the performance of String.split(".")
// especially on Chrome, so we will continue to insist that component member names do not contain a "." character
// for the time being.
// See http://jsperf.com/parsing-escaped-el for some experiments
fluid.registerNamespace("fluid.pathUtil");
fluid.pathUtil.getPathSegmentImpl = function (accept, path, i) {
var segment = null;
if (accept) {
segment = "";
}
var escaped = false;
var limit = path.length;
for (; i < limit; ++i) {
var c = path.charAt(i);
if (!escaped) {
if (c === ".") {
break;
}
else if (c === "\\") {
escaped = true;
}
else if (segment !== null) {
segment += c;
}
}
else {
escaped = false;
if (segment !== null) {
segment += c;
}
}
}
if (segment !== null) {
accept[0] = segment;
}
return i;
};
var globalAccept = []; // TODO: reentrancy risk here. This holder is here to allow parseEL to make two returns without an allocation.
/* A version of fluid.model.parseEL that apples escaping rules - this allows path segments
* to contain period characters . - characters "\" and "}" will also be escaped. WARNING -
* this current implementation is EXTREMELY slow compared to fluid.model.parseEL and should
* not be used in performance-sensitive applications */
// supported, PUBLIC API function
fluid.pathUtil.parseEL = function (path) {
var togo = [];
var index = 0;
var limit = path.length;
while (index < limit) {
var firstdot = fluid.pathUtil.getPathSegmentImpl(globalAccept, path, index);
togo.push(globalAccept[0]);
index = firstdot + 1;
}
return togo;
};
// supported, PUBLIC API function
fluid.pathUtil.composeSegment = function (prefix, toappend) {
toappend = toappend.toString();
for (var i = 0; i < toappend.length; ++i) {
var c = toappend.charAt(i);
if (c === "." || c === "\\" || c === "}") {
prefix += "\\";
}
prefix += c;
}
return prefix;
};
/* Escapes a single path segment by replacing any character ".", "\" or "}" with itself prepended by \ */
// supported, PUBLIC API function
fluid.pathUtil.escapeSegment = function (segment) {
return fluid.pathUtil.composeSegment("", segment);
};
/*
* Compose a prefix and suffix EL path, where the prefix is already escaped.
* Prefix may be empty, but not null. The suffix will become escaped.
*/
// supported, PUBLIC API function
fluid.pathUtil.composePath = function (prefix, suffix) {
if (prefix.length !== 0) {
prefix += ".";
}
return fluid.pathUtil.composeSegment(prefix, suffix);
};
/*
* Compose a set of path segments supplied as arguments into an escaped EL expression. Escaped version
* of fluid.model.composeSegments
*/
// supported, PUBLIC API function
fluid.pathUtil.composeSegments = function () {
var path = "";
for (var i = 0; i < arguments.length; ++i) {
path = fluid.pathUtil.composePath(path, arguments[i]);
}
return path;
};
/* Helpful utility for use in resolvers - matches a path which has already been parsed into segments */
fluid.pathUtil.matchSegments = function (toMatch, segs, start, end) {
if (end - start !== toMatch.length) {
return false;
}
for (var i = start; i < end; ++i) {
if (segs[i] !== toMatch[i - start]) {
return false;
}
}
return true;
};
fluid.model.unescapedParser = {
parse: fluid.model.parseEL,
compose: fluid.model.composeSegments
};
// supported, PUBLIC API record
fluid.model.defaultGetConfig = {
parser: fluid.model.unescapedParser,
strategies: [fluid.model.funcResolverStrategy, fluid.model.defaultFetchStrategy]
};
// supported, PUBLIC API record
fluid.model.defaultSetConfig = {
parser: fluid.model.unescapedParser,
strategies: [fluid.model.funcResolverStrategy, fluid.model.defaultFetchStrategy, fluid.model.defaultCreatorStrategy]
};
fluid.model.escapedParser = {
parse: fluid.pathUtil.parseEL,
compose: fluid.pathUtil.composeSegments
};
// supported, PUBLIC API record
fluid.model.escapedGetConfig = {
parser: fluid.model.escapedParser,
strategies: [fluid.model.defaultFetchStrategy]
};
// supported, PUBLIC API record
fluid.model.escapedSetConfig = {
parser: fluid.model.escapedParser,
strategies: [fluid.model.defaultFetchStrategy, fluid.model.defaultCreatorStrategy]
};
/** CONNECTED COMPONENTS AND TOPOLOGICAL SORTING **/
// Following "tarjan" at https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm
/** Compute the strongly connected components of a graph, specified as a list of vertices and an accessor function.
* Returns an array of arrays of strongly connected vertices, with each component in topologically sorted order.
* @param {Vertex[]} vertices - An array of vertices of the graph to be processed. Each vertex object will be polluted
* with three extra fields: `tarjanIndex`, `lowIndex` and `onStack`.
* @param {Function} accessor - A function that returns the accessor vertex or vertices.
* @return {Array.<Vertex[]>} - An array of arrays of vertices.
*/
fluid.stronglyConnected = function (vertices, accessor) {
var that = {
stack: [],
accessor: accessor,
components: [],
index: 0
};
vertices.forEach(function (vertex) {
if (vertex.tarjanIndex === undefined) {
fluid.stronglyConnectedOne(vertex, that);
}
});
return that.components;
};
// Perform one round of the Tarjan search algorithm using the state structure generated in fluid.stronglyConnected
fluid.stronglyConnectedOne = function (vertex, that) {
vertex.tarjanIndex = that.index;
vertex.lowIndex = that.index;
++that.index;
that.stack.push(vertex);
vertex.onStack = true;
var outEdges = that.accessor(vertex);
outEdges.forEach(function (outVertex) {
if (outVertex.tarjanIndex === undefined) {
// Successor has not yet been visited; recurse on it
fluid.stronglyConnectedOne(outVertex, that);
vertex.lowIndex = Math.min(vertex.lowIndex, outVertex.lowIndex);
} else if (outVertex.onStack) {
// Successor is on the stack and hence in the current component
vertex.lowIndex = Math.min(vertex.lowIndex, outVertex.tarjanIndex);
}
});
// If vertex is a root node, pop the stack back as far as it and generate a component
if (vertex.lowIndex === vertex.tarjanIndex) {
var component = [], outVertex;
do {
outVertex = that.stack.pop();
outVertex.onStack = false;
component.push(outVertex);
} while (outVertex !== vertex);
that.components.push(component);
}
};
/** MODEL COMPONENT HIERARCHY AND RELAY SYSTEM **/
fluid.initRelayModel = function (that) {
fluid.deenlistModelComponent(that);
return that.model;
};
// TODO: This utility compensates for our lack of control over "wave of explosions" initialisation - we may
// catch a model when it is apparently "completely initialised" and that's the best we can do, since we have
// missed its own initial transaction
fluid.isModelComplete = function (that) {
return "model" in that && that.model !== fluid.inEvaluationMarker;
};
// Enlist this model component as part of the "initial transaction" wave - note that "special transaction" init
// is indexed by component, not by applier, and has special record type (complete + initModel), not transaction
fluid.enlistModelComponent = function (that) {
var instantiator = fluid.getInstantiator(that);
var enlist = instantiator.modelTransactions.init[that.id];
if (!enlist) {
enlist = {
that: that,
applier: fluid.getForComponent(that, "applier"), // required for FLUID-5504 even though currently unused
complete: fluid.isModelComplete(that)
};
instantiator.modelTransactions.init[that.id] = enlist;
}
return enlist;
};
fluid.clearTransactions = function () {
var instantiator = fluid.globalInstantiator;
fluid.clear(instantiator.modelTransactions);
instantiator.modelTransactions.init = {};
};
fluid.failureEvent.addListener(fluid.clearTransactions, "clearTransactions", "before:fail");
// Utility to coordinate with our crude "oscillation prevention system" which limits each link to 2 updates (presumably
// in opposite directions). In the case of the initial transaction, we need to reset the count given that genuine
// changes are arising in the system with each new enlisted model. TODO: if we ever get users operating their own
// transactions, think of a way to incorporate this into that workflow
fluid.clearLinkCounts = function (transRec, relaysAlso) {
// TODO: Separate this record out into different types of records (relays are already in their own area)
fluid.each(transRec, function (value, key) {
if (typeof(value) === "number") {
transRec[key] = 0;
} else if (relaysAlso && value.options && typeof(value.relayCount) === "number") {
value.relayCount = 0;
}
});
};
/** Compute relay dependency out arcs for a group of initialising components.
* @param {Object} transacs - Hash of component id to local ChangeApplier transaction.
* @param {Object} mrec - Hash of component id to enlisted component record.
* @return {Object} - Hash of component id to list of enlisted component record.
*/
fluid.computeInitialOutArcs = function (transacs, mrec) {
return fluid.transform(mrec, function (recel, id) {
var oneOutArcs = {};
var listeners = recel.that.applier.listeners.sortedListeners;
fluid.each(listeners, function (listener) {
if (listener.isRelay && !fluid.isExcludedChangeSource(transacs[id], listener.cond)) {
var targetId = listener.targetId;
if (targetId !== id) {
oneOutArcs[targetId] = true;
}
}
});
var oneOutArcList = Object.keys(oneOutArcs);
var togo = oneOutArcList.map(function (id) {
return mrec[id];
});
// No edge if the component is not enlisted - it will sort to the end via "completeOnInit"
fluid.remove_if(togo, function (rec) {
return rec === undefined;
});
return togo;
});
};
fluid.sortCompleteLast = function (reca, recb) {
return (reca.completeOnInit ? 1 : 0) - (recb.completeOnInit ? 1 : 0);
};
/** Operate all coordinated transactions by bringing models to their respective initial values, and then commit them all
* @param {Component} that - A representative component of the collection for which the initial transaction is to be operated
* @param {Object} mrec - The global model transaction record for the init transaction. This is a hash indexed by component id
* to a model transaction record, as registered in `fluid.enlistModelComponent`. This has members `that`, `applier`, `complete`.
*/
fluid.operateInitialTransaction = function (that, mrec) {
var transId = fluid.allocateGuid();
var transRec = fluid.getModelTransactionRec(that, transId);
var transac;
var transacs = fluid.transform(mrec, function (recel) {
transac = recel.that.applier.initiate(null, "init", transId);
transRec[recel.that.applier.applierId] = {transaction: transac};
return transac;
});
// TODO: This sort has very little effect in any current test (can be replaced by no-op - see FLUID-5339) - but
// at least can't be performed in reverse order ("FLUID-3674 event coordination test" will fail) - need more cases
// Compute the graph of init transaction relays for FLUID-6234 - one day we will have to do better than this, since there
// may be finer structure than per-component - it may be that each piece of model area participates in this relation
// differently. But this will require even more ambitious work such as fragmenting all the initial model values along
// these boundaries.
var outArcs = fluid.computeInitialOutArcs(transacs, mrec);
var arcAccessor = function (mrec) {
return outArcs[mrec.that.id];
};
var recs = fluid.values(mrec);
var components = fluid.stronglyConnected(recs, arcAccessor);
var priorityIndex = 0;
components.forEach(function (component) {
component.forEach(function (recel) {
recel.initPriority = recel.completeOnInit ? Math.Infinity : priorityIndex++;
});
});
recs.sort(function (reca, recb) {
return reca.initPriority - recb.initPriority;
});
recs.forEach(function (recel) {
var that = recel.that;
var transac = transacs[that.id];
if (recel.completeOnInit) {
fluid.initModelEvent(that, that.applier, transac, that.applier.listeners.sortedListeners);
} else {
fluid.each(recel.initModels, function (initModel) {
transac.fireChangeRequest({type: "ADD", segs: [], value: initModel});
fluid.clearLinkCounts(transRec, true);
});
}
var shadow = fluid.shadowForComponent(that);
if (shadow) { // Fix for FLUID-5869 - the component may have been destroyed during its own init transaction
shadow.modelComplete = true; // technically this is a little early, but this flag is only read in fluid.connectModelRelay
}
});
transac.commit(); // committing one representative transaction will commit them all
};
// This modelComponent has now concluded initialisation - commit its initialisation transaction if it is the last such in the wave
fluid.deenlistModelComponent = function (that) {
var instantiator = fluid.getInstantiator(that);
var mrec = instantiator.modelTransactions.init;
if (!mrec[that.id]) { // avoid double evaluation through currently hacked "members" implementation
return;
}
that.model = undefined; // Abuse of the ginger system - in fact it is "currently in evaluation" - we need to return a proper initial model value even if no init occurred yet
mrec[that.id].complete = true; // flag means - "complete as in ready to participate in this transaction"
var incomplete = fluid.find_if(mrec, function (recel) {
return recel.complete !== true;
});
if (!incomplete) {
try { // For FLUID-6195 ensure that exceptions during init relay don't leave the framework unusable
fluid.operateInitialTransaction(that, mrec);
} catch (e) {
fluid.clearTransactions();
throw e;
}
// NB: Don't call fluid.concludeTransaction since "init" is not a standard record - this occurs in commitRelays for the corresponding genuine record as usual
instantiator.modelTransactions.init = {};
}
};
fluid.parseModelReference = function (that, ref) {
var parsed = fluid.parseContextReference(ref);
parsed.segs = that.applier.parseEL(parsed.path);
return parsed;
};
/** Given a string which may represent a reference into a model, parses it into a structure holding the coordinates for resolving the reference. It specially
* detects "references into model material" by looking for the first path segment in the path reference which holds the value "model". Some of its workflow is bypassed
* in the special case of a reference representing an implicit model relay. In this case, ref will definitely be a String, and if it does not refer to model material, rather than
* raising an error, the return structure will include a field <code>nonModel: true</code>
* @param {Component} that - The component holding the reference
* @param {String} name - A human-readable string representing the type of block holding the reference - e.g. "modelListeners"
* @param {String|ModelReference} ref - The model reference to be parsed. This may have already been partially parsed at the original site - that is, a ModelReference is a
* structure containing
* segs: {String[]} An array of model path segments to be dereferenced in the target component (will become `modelSegs` in the final return)
* context: {String} An IoC reference to the component holding the model
* @param {Boolean} implicitRelay - <code>true</code> if the reference was being resolved for an implicit model relay - that is,
* whether it occured within the `model` block itself. In this case, references to non-model material are not a failure and will simply be resolved
* (by the caller) onto their targets (as constants). Otherwise, this function will issue a failure on discovering a reference to non-model material.
* @return {Object} - A structure holding:
* that {Component} The component whose model is the target of the reference. This may end up being constructed as part of the act of resolving the reference
* applier {Component} The changeApplier for the component <code>that</code>. This may end up being constructed as part of the act of resolving the reference
* modelSegs {String[]} An array of path segments into the model of the component
* path {String} the value of <code>modelSegs</code> encoded as an EL path (remove client uses of this in time)
* nonModel {Boolean} Set if <code>implicitRelay</code> was true and the reference was not into a model (modelSegs/path will not be set in this case)
* segs {String[]} Holds the full array of path segments found by parsing the original reference - only useful in <code>nonModel</code> case
*/
fluid.parseValidModelReference = function (that, name, ref, implicitRelay) {
var reject = function () {
var failArgs = ["Error in " + name + ": ", ref].concat(fluid.makeArray(arguments));
fluid.fail.apply(null, failArgs);
};
var rejectNonModel = function (value) {
reject(" must be a reference to a component with a ChangeApplier (descended from fluid.modelComponent), instead got ", value);
};
var parsed; // resolve ref into context and modelSegs
if (typeof(ref) === "string") {
if (fluid.isIoCReference(ref)) {
parsed = fluid.parseModelReference(that, ref);
var modelPoint = parsed.segs.indexOf("model");
if (modelPoint === -1) {
if (implicitRelay) {
parsed.nonModel = true;
} else {
reject(" must be a reference into a component model via a path including the segment \"model\"");
}
} else {
parsed.modelSegs = parsed.segs.slice(modelPoint + 1);
parsed.contextSegs = parsed.segs.slice(0, modelPoint);
delete parsed.path;
}
} else {
parsed = {
path: ref,
modelSegs: that.applier.parseEL(ref)
};
}
} else {
if (!fluid.isArrayable(ref.segs)) {
reject(" must contain an entry \"segs\" holding path segments referring a model path within a component");
}
parsed = {
context: ref.context,
modelSegs: fluid.expandOptions(ref.segs, that)
};
}
var contextTarget, target; // resolve target component, which defaults to "that"
if (parsed.context) {
contextTarget = fluid.resolveContext(parsed.context, that);
if (!contextTarget) {
reject(" context must be a reference to an existing component");
}
target = parsed.contextSegs ? fluid.getForComponent(contextTarget, parsed.contextSegs) : contextTarget;
} else {
target = that;
}
if (!parsed.nonModel) {
if (!fluid.isComponent(target)) {
rejectNonModel(target);
}
if (!target.applier) {
fluid.getForComponent(target, ["applier"]);
}
if (!target.applier) {
rejectNonModel(target);
}
}
parsed.that = target;
parsed.applier = target && target.applier;
if (!parsed.path) { // ChangeToApplicable amongst others rely on this
parsed.path = target && target.applier.composeSegments.apply(null, parsed.modelSegs);
}
return parsed;
};
// Gets global record for a particular transaction id, allocating if necessary - looks up applier id to transaction,
// as well as looking up source id (linkId in below) to count/true
// Through poor implementation quality, not every access passes through this function - some look up instantiator.modelTransactions directly
fluid.getModelTransactionRec = function (that, transId) {
var instantiator = fluid.getInstantiator(that);
if (!transId) {
fluid.fail("Cannot get transaction record without transaction id");
}
if (!instantiator) {
return null;
}
var transRec = instantiator.modelTransactions[transId];
if (!transRec) {
transRec = instantiator.modelTransactions[transId] = {
relays: [], // sorted array of relay elements (also appear at top level index by transaction id)
sources: {}, // hash of the global transaction sources (includes "init" but excludes "relay" and "local")
externalChanges: {} // index by applierId to changePath to listener record
};
}
return transRec;
};
fluid.recordChangeListener = function (component, applier, sourceListener, listenerId) {
var shadow = fluid.shadowForComponent(component);
fluid.recordListener(applier.modelChanged, sourceListener, shadow, listenerId);
};
/** Called when a relay listener registered using `fluid.registerDirectChangeRelay` enlists in a transaction. Opens a local
* representative of this transaction on `targetApplier`, creates and stores a "transaction element" within the global transaction
* record keyed by the target applier's id. The transaction element is also pushed onto the `relays` member of the global transaction record - they
* will be sorted by priority here when changes are fired.
* @param {TransactionRecord} transRec - The global record for the current ChangeApplier transaction as retrieved from `fluid.getModelTransactionRec`
* @param {ChangeApplier} targetApplier - The ChangeApplier to which outgoing changes will be applied. A local representative of the transaction will be opened on this applier and returned.
* @param {String} transId - The global id of this transaction
* @param {Object} options - The `options` argument supplied to `fluid.registerDirectChangeRelay`. This will be stored in the returned transaction element
* - note that only the member `update` is ever used in `fluid.model.updateRelays` - TODO: We should thin this out
* @param {Object} npOptions - Namespace and priority options
* namespace {String} [optional] The namespace attached to this relay definition
* priority {String} [optional] The (unparsed) priority attached to this relay definition
* @return {Object} A "transaction element" holding information relevant to this relay's enlistment in the current transaction. This includes fields:
* transaction {Transaction} The local representative of this transaction created on `targetApplier`
* relayCount {Integer} The number of times this relay has been activated in this transaction
* namespace {String} [optional] Namespace for this relay definition
* priority {Priority} The parsed priority definition for this relay
*/
fluid.registerRelayTransaction = function (transRec, targetApplier, transId, options, npOptions) {
var newTrans = targetApplier.initiate("relay", null, transId); // non-top-level transaction will defeat postCommit
var transEl = transRec[targetApplier.applierId] = {transaction: newTrans, relayCount: 0, namespace: npOptions.namespace, priority: npOptions.priority, options: options};
transEl.priority = fluid.parsePriority(transEl.priority, transRec.relays.length, false, "model relay");
transRec.relays.push(transEl);
return transEl;
};
// Configure this parameter to tweak the number of relays the model will attempt per transaction before bailing out with an error
fluid.relayRecursionBailout = 100;
// Used with various arg combinations from different sources. For standard "implicit relay" or fully lensed relay,
// the first 4 args will be set, and "options" will be empty
// For a model-dependent relay, this will be used in two halves - firstly, all of the model
// sources will bind to the relay transform document itself. In this case the argument "targetApplier" within "options" will be set.
// In this case, the component known as "target" is really the source - it is a component reference discovered by parsing the
// relay document.
// Secondly, the relay itself will schedule an invalidation (as if receiving change to "*" of its source - which may in most
// cases actually be empty) and play through its transducer. "Source" component itself is never empty, since it is used for listener
// degistration on destruction (check this is correct for external model relay). However, "sourceSegs" may be empty in the case
// there is no "source" component registered for the link. This change is played in a "half-transactional" way - that is, we wait
// for all other changes in the system to settle before playing the relay document, in order to minimise the chances of multiple
// firing and corruption. This is done via the "preCommit" hook registered at top level in establishModelRelay. This listener
// is transactional but it does not require the transaction to conclude in order to fire - it may be reused as many times as
// required within the "overall" transaction whilst genuine (external) changes continue to arrive.
// TODO: Vast overcomplication and generation of closure garbage. SURELY we should be able to convert this into an externalised, arg-ist form
/** Registers a listener operating one leg of a model relay relation, connecting the source and target. Called once or twice from `fluid.connectModelRelay` -
* see the comment there for the three cases involved. Note that in its case iii)B) the applier to bind to is not the one attached to `target` but is instead
* held in `options.targetApplier`.
* @param {Object} target - The target component at the end of the relay.
* @param {String[]} targetSegs - String segments representing the path in the target where outgoing changes are to be fired
* @param {Component|null} source - The source component from where changes will be listened to. May be null if the change source is a relay document.
* @param {String[]} sourceSegs - String segments representing the path in the source component's model at which changes will be listened to
* @param {String} linkId - The unique id of this relay arc. This will be used as a key within the active transaction record to look up dynamic information about
* activation of the link within that transaction (currently just an activation count)
* @param {Function|null} transducer - A function which will be invoked when a change is to be relayed. This is one of the adapters constructed in "makeTransformPackage"
* and is set in all cases other than iii)B) (collecting changes to contextualised relay). Note that this will have a member `cond` as returned from
* `fluid.model.parseRelayCondition` encoding the condition whereby changes should be excluded from the transaction. The rule encoded by the condition
* will be applied by the function within `transducer`.
* @param {Object} options -
* transactional {Boolean} `true` in case iii) - although this only represents `half-transactions`, `false` in others since these are resolved immediately with no granularity
* targetApplier {ChangeApplier} [optional] in case iii)B) holds the applier for the contextualised relay document which outgoing changes should be applied to
* sourceApplier {ChangeApplier} [optional] in case ii) holds the applier for the contextualised relay document on which we listen for outgoing changes
* @param {Object} npOptions - Namespace and priority options
* namespace {String} [optional] The namespace attached to this relay definition
* priority {String} [optional] The (unparsed) priority attached to this relay definition
*/
fluid.registerDirectChangeRelay = function (target, targetSegs, source, sourceSegs, linkId, transducer, options, npOptions) {
var targetApplier = options.targetApplier || target.applier; // first branch implies the target is a relay document
var sourceApplier = options.sourceApplier || source.applier; // first branch implies the source is a relay document - listener will be transactional
var applierId = targetApplier.applierId;
targetSegs = fluid.makeArray(targetSegs);
sourceSegs = fluid.makeArray(sourceSegs); // take copies since originals will be trashed
var sourceListener = function (newValue, oldValue, path, changeRequest, trans, applier) {
var transId = trans.id;
var transRec = fluid.getModelTransactionRec(target, transId);
if (applier && trans && !transRec[applier.applierId]) { // don't trash existing record which may contain "options" (FLUID-5397)
transRec[applier.applierId] = {transaction: trans}; // enlist the outer user's original transaction
}
var existing = transRec[applierId];
transRec[linkId] = transRec[linkId] || 0;
// Crude "oscillation prevention" system limits each link to maximum of 2 operations per cycle (presumably in opposite directions)
var relay = true; // TODO: See FLUID-5303 - we currently disable this check entirely to solve FLUID-5293 - perhaps we might remove link counts entirely
if (relay) {
++transRec[linkId];
if (transRec[linkId] > fluid.relayRecursionBailout) {
fluid.fail("Error in model relay specification at component ", target, " - operated more than " + fluid.relayRecursionBailout + " relays without model value settling - current model contents are ", trans.newHolder.model);
}
if (!existing) {
existing = fluid.registerRelayTransaction(transRec, targetApplier, transId, options, npOptions);
}
if (transducer && !options.targetApplier) {
// TODO: This is just for safety but is still unusual and now abused. The transducer doesn't need the "newValue" since all the transform information
// has been baked into the transform document itself. However, we now rely on this special signalling value to make sure we regenerate transforms in
// the "forwardAdapter"
transducer(existing.transaction, options.sourceApplier ? undefined : newValue, sourceSegs, targetSegs, changeRequest);
} else {
if (changeRequest && changeRequest.type === "DELETE") {
existing.transaction.fireChangeRequest({type: "DELETE", segs: targetSegs});
}
if (newValue !== undefined) {
existing.transaction.fireChangeRequest({type: "ADD", segs: targetSegs, value: newValue});
}
}
}
};
var spec = sourceApplier.modelChanged.addListener({
isRelay: true,
cond: transducer && transducer.cond,
targetId: target.id, // these two fields for debuggability
targetApplierId: targetApplier.id,
segs: sourceSegs,
transactional: options.transactional
}, sourceListener);
if (fluid.passLogLevel(fluid.logLevel.TRACE)) {
fluid.log(fluid.logLevel.TRACE, "Adding relay listener with listenerId " + spec.listenerId + " to source applier with id " +
sourceApplier.applierId + " from target applier with id " + applierId + " for target component with id " + target.id);
}
if (source) { // TODO - we actually may require to register on THREE sources in the case modelRelay is attached to a
// component which is neither source nor target. Note there will be problems if source, say, is destroyed and recreated,
// and holder is not - relay will in that case be lost. Need to integrate relay expressions with IoCSS.
fluid.recordChangeListener(source, sourceApplier, sourceListener, spec.listenerId);
if (target !== source) {
fluid.recordChangeListener(target, sourceApplier, sourceListener, spec.listenerId);
}
}
};
/** Connect a model relay relation between model material. This is called in three scenarios:
* i) from `fluid.parseModelRelay` when parsing an uncontextualised model relay (one with a static transform document), to
* directly connect the source and target of the relay
* ii) from `fluid.parseModelRelay` when parsing a contextualised model relay (one whose transform document depends on other model
* material), to connect updates emitted from the transform document's applier onto the relay ends (both source and target)
* iii) from `fluid.parseImplicitRelay` when parsing model references found within contextualised model relay to bind changes emitted
* from the target of the reference onto the transform document's applier. These may apply directly to another component's model (in its case
* A) or apply to a relay document (in its case B)
*
* This function will make one or two calls to `fluid.registerDirectChangeRelay` in order to set up each leg of any required relay.
* Note that in case iii)B) the component referred to as our argument `target` is actually the "source" of the changes (that is, the one encountered
* while traversing the transform document), and our argument `source` is the component holding the transform, and so
* the call to `fluid.registerDirectChangeRelay` will have `source` and `target` reversed (`fluid.registerDirectChangeRelay` will bind to the `targetApplier`
* in the options rather than source's applier).
* @param {Component} source - The component holding the material giving rise to the relay, or the one referred to by the `source` member
* of the configuration in case ii), if there is one
* @param {Array|null} sourceSegs - An array of parsed string segments of the `source` relay reference in case i), or the offset into the transform
* document of the reference component in case iii), otherwise `null` (case ii))
* @param {Component} target - The component holding the model relay `target` in cases i) and ii), or the component at the other end of
* the model reference in case iii) (in this case in fact a "source" for the changes.
* @param {Array} targetSegs - An array of parsed string segments of the `target` reference in cases i) and ii), or of the model reference in
* case iii)
* @param {Object} options - A structure describing the relay, allowing discrimination of the various cases above. This is derived from the return from
* `fluid.makeTransformPackage` but will have some members filtered in different cases. This contains members:
* update {Function} A function to be called at the end of a "half-transaction" when all pending updates have been applied to the document's applier.
* This discriminates case iii)
* targetApplier {ChangeApplier} The ChangeApplier for the relay document, in case iii)B)
* forwardApplier (ChangeApplier} The ChangeApplier for the relay document, in cases ii) and iii)B) (only used in latter case)
* forwardAdapter {Adapter} A function accepting (transaction, newValue) to pass through the forward leg of the relay. Contains a member `cond` holding the parsed relay condition.
* backwardAdapter {Adapter} A function accepting (transaction, newValue) to pass through the backward leg of the relay. Contains a member `cond` holding the parsed relay condition.
* namespace {String} Namespace for any relay definition
* priority {String} Priority for any relay definition or synthetic "first" for iii)A)
*/
fluid.connectModelRelay = function (source, sourceSegs, target, targetSegs, options) {
var linkId = fluid.allocateGuid();
function enlistComponent(component) {
var enlist = fluid.enlistModelComponent(component);
if (enlist.complete) {
var shadow = fluid.shadowForComponent(component);
if (shadow.modelComplete) {
enlist.completeOnInit = true;
}
}
}
enlistComponent(target);
enlistComponent(source); // role of "source" and "target" are swapped in case iii)B)
var npOptions = fluid.filterKeys(options, ["namespace", "priority"]);
if (options.update) { // it is a call for a relay document - ii) or iii)B)
if (options.targetApplier) { // case iii)B)
// We are in the middle of parsing a contextualised relay, and this call has arrived via its parseImplicitRelay.
// register changes from the target model onto changes to the model relay document
fluid.registerDirectChangeRelay(source, sourceSegs, target, targetSegs, linkId, null, {
transactional: false,
targetApplier: options.targetApplier,
update: options.update
}, npOptions);
} else { // case ii), contextualised relay overall output
// Rather than bind source-source, instead register the "half-transactional" listener which binds changes
// from the relay document itself onto the target
fluid.registerDirectChangeRelay(target, targetSegs, source, [], linkId + "-transform", options.forwardAdapter, {transactional: true, sourceApplier: options.forwardApplier}, npOptions);
}
} else { // case i) or iii)A): more efficient, old-fashioned branch where relay is uncontextualised
fluid.registerDirectChangeRelay(target, targetSegs, source, sourceSegs, linkId, options.forwardAdapter, {transactional: false}, npOptions);
fluid.registerDirectChangeRelay(source, sourceSegs, target, targetSegs, linkId, options.backwardAdapter, {transactional: false}, npOptions);
}
};
fluid.parseSourceExclusionSpec = function (targetSpec, sourceSpec) {
targetSpec.excludeSource = fluid.arrayToHash(fluid.makeArray(sourceSpec.excludeSource || (sourceSpec.includeSource ? "*" : undefined)));
targetSpec.includeSource = fluid.arrayToHash(fluid.makeArray(sourceSpec.includeSource));
return targetSpec;
};
/** Determines whether the supplied transaction should have changes not propagated into it as a result of being excluded by a
* condition specification.
* @param {Transaction} transaction - A local ChangeApplier transaction, with member `fullSources` holding all currently active sources
* @param {ConditionSpec} spec - A parsed relay condition specification, as returned from `fluid.model.parseRelayCondition`.
* @return {Boolean} `true` if changes should be excluded from the supplied transaction according to the supplied specification
*/
fluid.isExcludedChangeSource = function (transaction, spec) {
if (!spec || !spec.excludeSource) { // mergeModelListeners initModelEvent fabricates a fake spec that bypasses processing
return false;
}
var excluded = spec.excludeSource["*"];
for (var source in transaction.fullSources) {
if (spec.excludeSource[source]) {
excluded = true;
}
if (spec.includeSource[source]) {
excluded = false;
}
}
return excluded;
};
fluid.model.guardedAdapter = function (transaction, cond, func, args) {
if (!fluid.isExcludedChangeSource(transaction, cond) && func !== fluid.model.transform.uninvertibleTransform) {
func.apply(null, args);
}
};
// TODO: This rather crummy function is the only site with a hard use of "path" as String
fluid.transformToAdapter = function (transform, targetPath) {
var basedTransform = {};
basedTransform[targetPath] = transform; // TODO: Faulty with respect to escaping rules
return function (trans, newValue, sourceSegs, targetSegs, changeRequest) {
if (changeRequest && changeRequest.type === "DELETE") {
trans.fireChangeRequest({type: "DELETE", path: targetPath}); // avoid mouse droppings in target document for FLUID-5585
}
// TODO: More efficient model that can only run invalidated portion of transform (need to access changeMap of source transaction)
fluid.model.transformWithRules(newValue, basedTransform, {finalApplier: trans});
};
};
// TODO: sourcePath and targetPath should really be converted to segs to avoid excess work in parseValidModelReference
fluid.makeTransformPackage = function (componentThat, transform, sourcePath, targetPath, forwardCond, backwardCond, namespace, priority) {
var that = {
forwardHolder: {model: transform},
backwardHolder: {model: null}
};
that.generateAdapters = function (trans) {
// can't commit "half-transaction" or events will fire - violate encapsulation in this way
that.forwardAdapterImpl = fluid.transformToAdapter(trans ? trans.newHolder.model : that.forwardHolder.model, targetPath);
if (sourcePath !== null) {
var inverted = fluid.model.transform.invertConfiguration(transform);
if (inverted !== fluid.model.transform.uninvertibleTransform) {
that.backwardHolder.model = inverted;
that.backwardAdapterImpl = fluid.transformToAdapter(that.backwardHolder.model, sourcePath);
} else {
that.backwardAdapterImpl = inverted;
}
}
};
that.forwardAdapter = function (transaction, newValue) { // create a stable function reference for this possibly changing adapter
if (newValue === undefined) {
that.generateAdapters(); // TODO: Quick fix for incorrect scheduling of invalidation/transducing
// "it so happens" that fluid.registerDirectChangeRelay invokes us with empty newValue in the case of invalidation -> transduction
}
fluid.model.guardedAdapter(transaction, forwardCond, that.forwardAdapterImpl, arguments);
};
that.forwardAdapter.cond = forwardCond; // Used when parsing graph in init transaction
// fired from fluid.model.updateRelays via invalidator event
that.runTransform = function (trans) {
trans.commit(); // this will reach the special "half-transactional listener" registered in fluid.connectModelRelay,
// branch with options.targetApplier - by committing the transaction, we update the relay document in bulk and then cause
// it to execute (via "transducer")
trans.reset();
};
that.forwardApplier = fluid.makeHolderChangeApplier(that.forwardHolder);
that.forwardApplier.isRelayApplier = true; // special annotation so these can be discovered in the transaction record
that.invalidator = fluid.makeEventFirer({name: "Invalidator for model relay with applier " + that.forwardApplier.applierId});
if (sourcePath !== null) {
// TODO: backwardApplier is unused
that.backwardApplier = fluid.makeHolderChangeApplier(that.backwardHolder);
that.backwardAdapter = function (transaction) {
fluid.model.guardedAdapter(transaction, backwardCond, that.backwardAdapterImpl, arguments);
};
that.backwardAdapter.cond = backwardCond;
}
that.update = that.invalidator.fire; // necessary so that both routes to fluid.connectModelRelay from here hit the first branch
var implicitOptions = {
targetApplier: that.forwardApplier, // this special field identifies us to fluid.connectModelRelay
update: that.update,
namespace: namespace,
priority: priority,
refCount: 0
};
that.forwardHolder.model = fluid.parseImplicitRelay(componentThat, transform, [], implicitOptions);
that.refCount = implicitOptions.refCount;
that.namespace = namespace;
that.priority = priority;
that.generateAdapters();
that.invalidator.addListener(that.generateAdapters);
that.invalidator.addListener(that.runTransform);
return that;
};
fluid.singleTransformToFull = function (singleTransform) {
var withPath = $.extend(true, {inputPath: ""}, singleTransform);
return {
"": {
transform: withPath
}
};
};
// Convert old-style "relay conditions" to source includes/excludes as used in model listeners
fluid.model.relayConditions = {
initOnly: {includeSource: "init"},
liveOnly: {excludeSource: "init"},
never: {includeSource: []},
always: {}
};
/** Parse a relay condition specification, e.g. of the form `{includeSource: "init"}` or `never` into a hash representation
* suitable for rapid querying.
* @param {String|Object} condition - A relay condition specification, appearing in the section `forward` or `backward` of a
* relay definition
* @return {RelayCondition} The parsed condition, holding members `includeSource` and `excludeSource` each with a hash to `true`
* of referenced sources
*/
fluid.model.parseRelayCondition = function (condition) {
if (condition === "initOnly") {
fluid.log(fluid.logLevel.WARN, "The relay condition \"initOnly\" is deprecated: Please use the form 'includeSource: \"init\"' instead");
} else if (condition === "liveOnly") {
fluid.log(fluid.logLevel.WARN, "The relay condition \"liveOnly\" is deprecated: Please use the form 'excludeSource: \"init\"' instead");
}
var exclusionRec;
if (!condition) {
exclusionRec = {};
} else if (typeof(condition) === "string") {
exclusionRec = fluid.model.relayConditions[condition];
if (!exclusionRec) {
fluid.fail("Unrecognised model relay condition string \"" + condition + "\": the supported values are \"never\" or a record with members \"includeSource\" and/or \"excludeSource\"");
}
} else {
exclusionRec = condition;
}
return fluid.parseSourceExclusionSpec({}, exclusionRec);
};
/** Parse a single model relay record as appearing nested within the `modelRelay` block in a model component's
* options. By various calls to `fluid.connectModelRelay` this will set up the structure operating the live
* relay during the component#s lifetime.
* @param {Component} that - The component holding the record, currently instantiating
* @param {Object} mrrec - The model relay record. This must contain either a member `singleTransform` or `transform` and may also contain
* members `namespace`, `path`, `priority`, `forward` and `backward`
* @param {String} key -
*/
fluid.parseModelRelay = function (that, mrrec, key) {
var parsedSource = mrrec.source !== undefined ? fluid.parseValidModelReference(that, "modelRelay record member \"source\"", mrrec.source) :
{path: null, modelSegs: null};
var parsedTarget = fluid.parseValidModelReference(that, "modelRelay record member \"target\"", mrrec.target);
var namespace = mrrec.namespace || key;
var transform = mrrec.singleTransform ? fluid.singleTransformToFull(mrrec.singleTransform) : mrrec.transform;
if (!transform) {
fluid.fail("Cannot parse modelRelay record without element \"singleTransform\" or \"transform\":", mrrec);
}
var forwardCond = fluid.model.parseRelayCondition(mrrec.forward), backwardCond = fluid.model.parseRelayCondition(mrrec.backward);
var transformPackage = fluid.makeTransformPackage(that, transform, parsedSource.path, parsedTarget.path, forwardCond, backwardCond, namespace, mrrec.priority);
if (transformPackage.refCount === 0) { // There were no implicit relay elements found in the relay document - it can be relayed directly
// Case i): Bind changes emitted from the relay ends to each other, synchronously
fluid.connectModelRelay(parsedSource.that || that, parsedSource.modelSegs, parsedTarget.that, parsedTarget.modelSegs,
// Primarily, here, we want to get rid of "update" which is what signals to connectModelRelay that this is a invalidatable relay
fluid.filterKeys(transformPackage, ["forwardAdapter", "backwardAdapter", "namespace", "priority"]));
} else {
if (parsedSource.modelSegs) {
fluid.fail("Error in model relay definition: If a relay transform has a model dependency, you can not specify a \"source\" entry - please instead enter this as \"input\" in the transform specification. Definition was ", mrrec, " for component ", that);
}
// Case ii): Binds changes emitted from the relay document itself onto the relay ends (using the "half-transactional system")
fluid.connectModelRelay(that, null, parsedTarget.that, parsedTarget.modelSegs, transformPackage);
}
};
/** Traverses a model document written within a component's options, parsing any IoC references looking for
* i) references to general material, which will be fetched and interpolated now, and ii) "implicit relay" references to the
* model areas of other components, which will be used to set up live synchronisation between the area in this component where
* they appear and their target, as well as setting up initial synchronisation to compute the initial contents.
* This is called in two situations: A) parsing the `model` configuration option for a model component, and B) parsing the
* `transform` member (perhaps derived from `singleTransform`) of a `modelRelay` block for a model component. It calls itself
* recursively as it progresses through the model document material with updated `segs`
* @param {Component} that - The component holding the model document
* @param {Any} modelRec - The model document specification to be parsed
* @param {String[]} segs - The array of string path segments from the root of the entire model document to the point of current parsing
* @param {Object} options - Configuration options (mutable) governing this parse. This is primarily used to hand as the 5th argument to
* `fluid.connectModelRelay` for any model references found, and contains members
* refCount {Integer} An count incremented for every call to `fluid.connectModelRelay` setting up a synchronizing relay for every
* reference to model material encountered
* priority {String} The unparsed priority member attached to this record, or `first` for a parse of `model` (case A)
* namespace {String} [optional] A namespace attached to this transform, if we are parsing a transform
* targetApplier {ChangeApplier} [optional] The ChangeApplier for this transform document, if it is a transform, empty otherwise
* update {Function} [optional] A function to be called on conclusion of a "half-transaction" where all currently pending updates have been applied
* to this transform document. This function will update/regenerate the relay transform functions used to relay changes between the transform
* ends based on the updated document.
* @return {Any} - The resulting model value.
*/
fluid.parseImplicitRelay = function (that, modelRec, segs, options) {
var value;
if (fluid.isIoCReference(modelRec)) {
var parsed = fluid.parseValidModelReference(that, "model reference from model (implicit relay)", modelRec, true);
if (parsed.nonModel) {
value = fluid.getForComponent(parsed.that, parsed.segs);
} else {
++options.refCount; // This count is used from within fluid.makeTransformPackage
fluid.connectModelRelay(that, segs, parsed.that, parsed.modelSegs, options);
}
} else if (fluid.isPrimitive(modelRec) || !fluid.isPlainObject(modelRec)) {
value = modelRec;
} else if (modelRec.expander && fluid.isPlainObject(modelRec.expander)) {
value = fluid.expandOptions(modelRec, that);
} else {
value = fluid.freshContainer(modelRec);
fluid.each(modelRec, function (innerValue, key) {
segs.push(key);
var innerTrans = fluid.parseImplicitRelay(that, innerValue, segs, options);
if (innerTrans !== undefined) {
value[key] = innerTrans;
}
segs.pop();
});
}
return value;
};
// Conclude the transaction by firing to all external listeners in priority order
fluid.model.notifyExternal = function (transRec) {
var allChanges = transRec ? fluid.values(transRec.externalChanges) : [];
fluid.sortByPriority(allChanges);
for (var i = 0; i < allChanges.length; ++i) {
var change = allChanges[i];
var targetApplier = change.args[5]; // NOTE: This argument gets here via fluid.model.storeExternalChange from fluid.notifyModelChanges
if (!targetApplier.destroyed) { // 3rd point of guarding for FLUID-5592
change.listener.apply(null, change.args);
}
}
fluid.clearLinkCounts(transRec, true); // "options" structures for relayCount are aliased
};
fluid.model.commitRelays = function (instantiator, transactionId) {
var transRec = instantiator.modelTransactions[transactionId];
fluid.each(transRec, function (transEl) {
// EXPLAIN: This must commit ALL current transactions, not just those for relays - why?
if (transEl.transaction) { // some entries are links
transEl.transaction.commit("relay");
transEl.transaction.reset();
}
});
};
// Listens to all invalidation to relays, and reruns/applies them if they have been invalidated
fluid.model.updateRelays = function (instantiator, transactionId) {
var transRec = instantiator.modelTransactions[transactionId];
var updates = 0;
fluid.sortByPriority(transRec.relays);
fluid.each(transRec.relays, function (transEl) {
// TODO: We have a bit of a problem here in that we only process updatable relays by priority - plain relays get to act non-transactionally
if (transEl.transaction.changeRecord.changes > 0 && transEl.relayCount < 2 && transEl.options.update) {
transEl.relayCount++;
fluid.clearLinkCounts(transRec);
transEl.options.update(transEl.transaction, transRec);
++updates;
}
});
return updates;
};
fluid.establishModelRelay = function (that, optionsModel, optionsML, optionsMR, applier) {
var shadow = fluid.shadowForComponent(that);
if (!shadow.modelRelayEstablished) {
shadow.modelRelayEstablished = true;
} else {
fluid.fail("FLUID-5887 failure: Model relay initialised twice on component", that);
}
fluid.mergeModelListeners(that, optionsML);
var enlist = fluid.enlistModelComponent(that);
fluid.each(optionsMR, function (mrrec, key) {
for (var i = 0; i < mrrec.length; ++i) {
fluid.parseModelRelay(that, mrrec[i], key);
}
});
// Note: this particular instance of "refCount" is disused. We only use the count made within fluid.makeTransformPackge
var initModels = fluid.transform(optionsModel, function (modelRec) {
return fluid.parseImplicitRelay(that, modelRec, [], {refCount: 0, priority: "first"});
});
enlist.initModels = initModels;
var instantiator = fluid.getInstantiator(that);
function updateRelays(transaction) {
while (fluid.model.updateRelays(instantiator, transaction.id) > 0) {} // eslint-disable-line no-empty
}
function commitRelays(transaction, applier, code) {
if (code !== "relay") { // don't commit relays if this commit is already a relay commit
fluid.model.commitRelays(instantiator, transaction.id);
}
}
function concludeTransaction(transaction, applier, code) {
if (code !== "relay") {
fluid.model.notifyExternal(instantiator.modelTransactions[transaction.id]);
delete instantiator.modelTransactions[transaction.id];
}
}
applier.preCommit.addListener(updateRelays);
applier.preCommit.addListener(commitRelays);
applier.postCommit.addListener(concludeTransaction);
return null;
};
// supported, PUBLIC API grade
fluid.defaults("fluid.modelComponent", {
gradeNames: ["fluid.component"],
changeApplierOptions: {
relayStyle: true,
cullUnchanged: true
},
members: {
model: "@expand:fluid.initRelayModel({that}, {that}.modelRelay)",
applier: "@expand:fluid.makeHolderChangeApplier({that}, {that}.options.changeApplierOptions)",
modelRelay: "@expand:fluid.establishModelRelay({that}, {that}.options.model, {that}.options.modelListeners, {that}.options.modelRelay, {that}.applier)"
},
mergePolicy: {
model: {
noexpand: true,
func: fluid.arrayConcatPolicy // TODO: bug here in case a model consists of an array
},
modelListeners: fluid.makeMergeListenersPolicy(fluid.arrayConcatPolicy),
modelRelay: fluid.makeMergeListenersPolicy(fluid.arrayConcatPolicy, true)
}
});
fluid.modelChangedToChange = function (args) {
return {
value: args[0],
oldValue: args[1],
path: args[2],
transaction: args[4]
};
};
// Note - has only one call, from resolveModelListener
fluid.event.invokeListener = function (listener, args, localRecord, mergeRecord) {
if (typeof(listener) === "string") {
listener = fluid.event.resolveListener(listener); // just resolves globals
}
return listener.apply(null, args, localRecord, mergeRecord); // can be "false apply" that requires extra context for expansion
};
fluid.resolveModelListener = function (that, record) {
var togo = function () {
if (fluid.isDestroyed(that)) { // first guarding point to resolve FLUID-5592
return;
}
var change = fluid.modelChangedToChange(arguments);
var args = arguments;
var localRecord = {change: change, "arguments": args};
var mergeRecord = {source: Object.keys(change.transaction.sources)}; // cascade for FLUID-5490
if (record.args) {
args = fluid.expandOptions(record.args, that, {}, localRecord);
}
fluid.event.invokeListener(record.listener, fluid.makeArray(args), localRecord, mergeRecord);
};
fluid.event.impersonateListener(record.listener, togo);
return togo;
};
fluid.registerModelListeners = function (that, record, paths, namespace) {
var func = fluid.resolveModelListener(that, record);
fluid.each(record.byTarget, function (parsedArray) {
var parsed = parsedArray[0]; // that, applier are common across all these elements
var spec = {
listener: func, // for initModelEvent
listenerId: fluid.allocateGuid(), // external declarative listeners may often share listener handle, identify here
segsArray: fluid.getMembers(parsedArray, "modelSegs"),
pathArray: fluid.getMembers(parsedArray, "path"),
includeSource: record.includeSource,
excludeSource: record.excludeSource,
priority: fluid.expandOptions(record.priority, that),
transactional: true
};
// update "spec" so that we parse priority information just once
spec = parsed.applier.modelChanged.addListener(spec, func, namespace, record.softNamespace);
fluid.recordChangeListener(that, parsed.applier, func, spec.listenerId);
function initModelEvent() {
if (fluid.isModelComplete(parsed.that)) {
var trans = parsed.applier.initiate(null, "init");
fluid.initModelEvent(that, parsed.applier, trans, [spec]);
trans.commit();
}
}
if (that !== parsed.that && !fluid.isModelComplete(that)) { // TODO: Use FLUID-4883 "latched events" when available
// Don't confuse the end user by firing their listener before the component is constructed
// TODO: Better detection than this is requred - we assume that the target component will not be discovered as part
// of the initial transaction wave, but if it is, it will get a double notification - we really need "wave of explosions"
// since we are currently too early in initialisation of THIS component in order to tell if other will be found
// independently.
var onCreate = fluid.getForComponent(that, ["events", "onCreate"]);
onCreate.addListener(initModelEvent);
}
});
};
fluid.mergeModelListeners = function (that, listeners) {
fluid.each(listeners, function (value, key) {
if (typeof(value) === "string") {
value = {
funcName: value
};
}
// Bypass fluid.event.dispatchListener by means of "standard = false" and enter our custom workflow including expanding "change":
var records = fluid.event.resolveListenerRecord(value, that, "modelListeners", null, false).records;
fluid.each(records, function (record) {
// Aggregate model listeners into groups referring to the same component target.
// We do this so that a single entry will appear in its modelListeners so that they may
// be notified just once per transaction, and also displaced by namespace
record.byTarget = {};
var paths = fluid.makeArray(record.path === undefined ? key : record.path);
fluid.each(paths, function (path) {
var parsed = fluid.parseValidModelReference(that, "modelListeners entry", path);
fluid.pushArray(record.byTarget, parsed.that.id, parsed);
});
var namespace = (record.namespace && !record.softNamespace ? record.namespace : null) || (record.path !== undefined ? key : null);
fluid.registerModelListeners(that, record, paths, namespace);
});
});
};
/** CHANGE APPLIER **/
/* Dispatches a list of changes to the supplied applier */
fluid.fireChanges = function (applier, changes) {
for (var i = 0; i < changes.length; ++i) {
applier.fireChangeRequest(changes[i]);
}
};
fluid.model.isChangedPath = function (changeMap, segs) {
for (var i = 0; i <= segs.length; ++i) {
if (typeof(changeMap) === "string") {
return true;
}
if (i < segs.length && changeMap) {
changeMap = changeMap[segs[i]];
}
}
return false;
};
fluid.model.setChangedPath = function (options, segs, value) {
var notePath = function (record) {
segs.unshift(record);
fluid.model.setSimple(options, segs, value);
segs.shift();
};
if (!fluid.model.isChangedPath(options.changeMap, segs)) {
++options.changes;
notePath("changeMap");
}
if (!fluid.model.isChangedPath(options.deltaMap, segs)) {
++options.deltas;
notePath("deltaMap");
}
};
fluid.model.fetchChangeChildren = function (target, i, segs, source, options) {
fluid.each(source, function (value, key) {
segs[i] = key;
fluid.model.applyChangeStrategy(target, key, i, segs, value, options);
segs.length = i;
});
};
// Called with two primitives which are compared for equality. This takes account of "floating point slop" to avoid
// continuing to propagate inverted values as changes
// TODO: replace with a pluggable implementation
fluid.model.isSameValue = function (a, b) {
if (typeof(a) !== "number" || typeof(b) !== "number") {
return a === b;
} else {
// Don't use isNaN because of https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/isNaN#Confusing_special-case_behavior
if (a === b || a !== a && b !== b) { // Either the same concrete number or both NaN
return true;
} else {
var relError = Math.abs((a - b) / b);
return relError < 1e-12; // 64-bit floats have approx 16 digits accuracy, this should deal with most reasonable transforms
}
}
};
fluid.model.applyChangeStrategy = function (target, name, i, segs, source, options) {
var targetSlot = target[name];
var sourceCode = fluid.typeCode(source);
var targetCode = fluid.typeCode(targetSlot);
var changedValue = fluid.NO_VALUE;
if (sourceCode === "primitive") {
if (!fluid.model.isSameValue(targetSlot, source)) {
changedValue = source;
++options.unchanged;
}
} else if (targetCode !== sourceCode || sourceCode === "array" && source.length !== targetSlot.length) {
// RH is not primitive - array or object and mismatching or any array rewrite
changedValue = fluid.freshContainer(source);
}
if (changedValue !== fluid.NO_VALUE) {
target[name] = changedValue;
if (options.changeMap) {
fluid.model.setChangedPath(options, segs, options.inverse ? "DELETE" : "ADD");
}
}
if (sourceCode !== "primitive") {
fluid.model.fetchChangeChildren(target[name], i + 1, segs, source, options);
}
};
fluid.model.stepTargetAccess = function (target, type, segs, startpos, endpos, options) {
for (var i = startpos; i < endpos; ++i) {
if (!target) {
continue;
}
var oldTrunk = target[segs[i]];
target = fluid.model.traverseWithStrategy(target, segs, i, options[type === "ADD" ? "resolverSetConfig" : "resolverGetConfig"],
segs.length - i - 1);
if (oldTrunk !== target && options.changeMap) {
fluid.model.setChangedPath(options, segs.slice(0, i + 1), "ADD");
}
}
return {root: target, last: segs[endpos]};
};
fluid.model.defaultAccessorConfig = function (options) {
options = options || {};
options.resolverSetConfig = options.resolverSetConfig || fluid.model.escapedSetConfig;
options.resolverGetConfig = options.resolverGetConfig || fluid.model.escapedGetConfig;
return options;
};
// Changes: "MERGE" action abolished
// ADD/DELETE at root can be destructive
// changes tracked in optional final argument holding "changeMap: {}, changes: 0, unchanged: 0"
fluid.model.applyHolderChangeRequest = function (holder, request, options) {
options = fluid.model.defaultAccessorConfig(options);
options.deltaMap = options.changeMap ? {} : null;
options.deltas = 0;
var length = request.segs.length;
var pen, atRoot = length === 0;
if (atRoot) {
pen = {root: holder, last: "model"};
} else {
if (!holder.model) {
holder.model = {};
fluid.model.setChangedPath(options, [], options.inverse ? "DELETE" : "ADD");
}
pen = fluid.model.stepTargetAccess(holder.model, request.type, request.segs, 0, length - 1, options);
}
if (request.type === "ADD") {
var value = request.value;
var segs = fluid.makeArray(request.segs);
fluid.model.applyChangeStrategy(pen.root, pen.last, length - 1, segs, value, options, atRoot);
} else if (request.type === "DELETE") {
if (pen.root && pen.root[pen.last] !== undefined) {
delete pen.root[pen.last];
if (options.changeMap) {
fluid.model.setChangedPath(options, request.segs, "DELETE");
}
}
} else {
fluid.fail("Unrecognised change type of " + request.type);
}
return options.deltas ? options.deltaMap : null;
};
/** Compare two models for equality using a deep algorithm. It is assumed that both models are JSON-equivalent and do
* not contain circular links.
* @param modela The first model to be compared
* @param modelb The second model to be compared
* @param {Object} options - If supplied, will receive a map and summary of the change content between the objects. Structure is:
* changeMap: {Object/String} An isomorphic map of the object structures to values "ADD" or "DELETE" indicating
* that values have been added/removed at that location. Note that in the case the object structure differs at the root, <code>changeMap</code> will hold
* the plain String value "ADD" or "DELETE"
* changes: {Integer} Counts the number of changes between the objects - The two objects are identical iff <code>changes === 0</code>.
* unchanged: {Integer} Counts the number of leaf (primitive) values at which the two objects are identical. Note that the current implementation will
* double-count, this summary should be considered indicative rather than precise.
* @return <code>true</code> if the models are identical
*/
// TODO: This algorithm is quite inefficient in that both models will be copied once each
// supported, PUBLIC API function
fluid.model.diff = function (modela, modelb, options) {
options = options || {changes: 0, unchanged: 0, changeMap: {}}; // current algorithm can't avoid the expense of changeMap
var typea = fluid.typeCode(modela);
var typeb = fluid.typeCode(modelb);
var togo;
if (typea === "primitive" && typeb === "primitive") {
togo = fluid.model.isSameValue(modela, modelb);
} else if (typea === "primitive" ^ typeb === "primitive") {
togo = false;
} else {
// Apply both forward and reverse changes - if no changes either way, models are identical
// "ADD" reported in the reverse direction must be accounted as a "DELETE"
var holdera = {
model: fluid.copy(modela)
};
fluid.model.applyHolderChangeRequest(holdera, {value: modelb, segs: [], type: "ADD"}, options);
var holderb = {
model: fluid.copy(modelb)
};
options.inverse = true;
fluid.model.applyHolderChangeRequest(holderb, {value: modela, segs: [], type: "ADD"}, options);
togo = options.changes === 0;
}
if (togo === false && options.changes === 0) { // catch all primitive cases
options.changes = 1;
options.changeMap = modelb === undefined ? "DELETE" : "ADD";
} else if (togo === true && options.unchanged === 0) {
options.unchanged = 1;
}
return togo;
};
fluid.outputMatches = function (matches, outSegs, root) {
fluid.each(root, function (value, key) {
matches.push(outSegs.concat(key));
});
};
// Here we only support for now very simple expressions which have at most one
// wildcard which must appear in the final segment
fluid.matchChanges = function (changeMap, specSegs, newHolder, oldHolder) {
var newRoot = newHolder.model;
var oldRoot = oldHolder.model;
var map = changeMap;
var outSegs = ["model"];
var wildcard = false;
var togo = [];
for (var i = 0; i < specSegs.length; ++i) {
var seg = specSegs[i];
if (seg === "*") {
if (i === specSegs.length - 1) {
wildcard = true;
} else {
fluid.fail("Wildcard specification in modelChanged listener is only supported for the final path segment: " + specSegs.join("."));
}
} else {
outSegs.push(seg);
map = fluid.isPrimitive(map) ? map : map[seg];
newRoot = newRoot ? newRoot[seg] : undefined;
oldRoot = oldRoot ? oldRoot[seg] : undefined;
}
}
if (map) {
if (wildcard) {
if (map === "DELETE") {
fluid.outputMatches(togo, outSegs, oldRoot);
} else if (map === "ADD") {
fluid.outputMatches(togo, outSegs, newRoot);
} else {
fluid.outputMatches(togo, outSegs, map);
}
} else {
togo.push(outSegs);
}
}
return togo;
};
fluid.storeExternalChange = function (transRec, applier, invalidPath, spec, args) {
var pathString = applier.composeSegments.apply(null, invalidPath);
var keySegs = [applier.holder.id, spec.listenerId, (spec.wildcard ? pathString : "")];
var keyString = keySegs.join("|");
// TODO: We think we probably have a bug in that notifications destined for end of transaction are actually continuously emitted during the transaction
// These are unbottled in fluid.concludeTransaction
transRec.externalChanges[keyString] = {listener: spec.listener, namespace: spec.namespace, priority: spec.priority, args: args};
};
fluid.notifyModelChanges = function (listeners, changeMap, newHolder, oldHolder, changeRequest, transaction, applier, that) {
if (!listeners) {
return;
}
var transRec = transaction && fluid.getModelTransactionRec(that, transaction.id);
for (var i = 0; i < listeners.length; ++i) {
var spec = listeners[i];
var multiplePaths = spec.segsArray.length > 1; // does this spec listen on multiple paths? If so, don't rebase arguments and just report once per transaction
for (var j = 0; j < spec.segsArray.length; ++j) {
var invalidPaths = fluid.matchChanges(changeMap, spec.segsArray[j], newHolder, oldHolder);
// We only have multiple invalidPaths here if there is a wildcard
for (var k = 0; k < invalidPaths.length; ++k) {
if (applier.destroyed) { // 2nd guarding point for FLUID-5592
return;
}
var invalidPath = invalidPaths[k];
spec.listener = fluid.event.resolveListener(spec.listener);
var args = [multiplePaths ? newHolder.model : fluid.model.getSimple(newHolder, invalidPath),
multiplePaths ? oldHolder.model : fluid.model.getSimple(oldHolder, invalidPath),
multiplePaths ? [] : invalidPath.slice(1), changeRequest, transaction, applier];
// FLUID-5489: Do not notify of null changes which were reported as a result of invalidating a higher path
// TODO: We can improve greatly on efficiency by i) reporting a special code from fluid.matchChanges which signals the difference between invalidating a higher and lower path,
// ii) improving fluid.model.diff to create fewer intermediate structures and no copies
// TODO: The relay invalidation system is broken and must always be notified (branch 1) - since our old/new value detection is based on the wrong (global) timepoints in the transaction here,
// rather than the "last received model" by the holder of the transform document
if (!spec.isRelay) {
var isNull = fluid.model.diff(args[0], args[1]);
if (isNull) {
continue;
}
var sourceExcluded = fluid.isExcludedChangeSource(transaction, spec);
if (sourceExcluded) {
continue;
}
}
if (transRec && !spec.isRelay && spec.transactional) { // bottle up genuine external changes so we can sort and dedupe them later
fluid.storeExternalChange(transRec, applier, invalidPath, spec, args);
} else {
spec.listener.apply(null, args);
}
}
}
}
};
fluid.bindELMethods = function (applier) {
applier.parseEL = function (EL) {
return fluid.model.pathToSegments(EL, applier.options.resolverSetConfig);
};
applier.composeSegments = function () {
return applier.options.resolverSetConfig.parser.compose.apply(null, arguments);
};
};
fluid.initModelEvent = function (that, applier, trans, listeners) {
fluid.notifyModelChanges(listeners, "ADD", trans.oldHolder, fluid.emptyHolder, null, trans, applier, that);
};
// A standard "empty model" for the purposes of comparing initial state during the primordial transaction
fluid.emptyHolder = fluid.freezeRecursive({ model: undefined });
fluid.preFireChangeRequest = function (applier, changeRequest) {
if (!changeRequest.type) {
changeRequest.type = "ADD";
}
changeRequest.segs = changeRequest.segs || applier.parseEL(changeRequest.path);
};
// Automatically adapts change onto fireChangeRequest
fluid.bindRequestChange = function (that) {
that.change = function (path, value, type, source) {
var changeRequest = {
path: path,
value: value,
type: type,
source: source
};
that.fireChangeRequest(changeRequest);
};
};
// Quick n dirty test to cheaply detect Object versus other JSON types
fluid.isObjectSimple = function (totest) {
return Object.prototype.toString.call(totest) === "[object Object]";
};
fluid.mergeChangeSources = function (target, globalSources) {
if (fluid.isObjectSimple(globalSources)) { // TODO: No test for this branch!
fluid.extend(target, globalSources);
} else {
fluid.each(fluid.makeArray(globalSources), function (globalSource) {
target[globalSource] = true;
});
}
};
fluid.ChangeApplier = function () {};
fluid.makeHolderChangeApplier = function (holder, options) {
options = fluid.model.defaultAccessorConfig(options);
var applierId = fluid.allocateGuid();
var that = new fluid.ChangeApplier();
var name = fluid.isComponent(holder) ? "ChangeApplier for component " + fluid.dumpThat(holder) : "ChangeApplier with id " + applierId;
$.extend(that, {
applierId: applierId,
holder: holder,
listeners: fluid.makeEventFirer({name: "Internal change listeners for " + name}),
transListeners: fluid.makeEventFirer({name: "External change listeners for " + name}),
options: options,
modelChanged: {},
preCommit: fluid.makeEventFirer({name: "preCommit event for " + name}),
postCommit: fluid.makeEventFirer({name: "postCommit event for " + name})
});
that.destroy = function () {
that.preCommit.destroy();
that.postCommit.destroy();
that.destroyed = true;
};
that.modelChanged.addListener = function (spec, listener, namespace, softNamespace) {
if (typeof(spec) === "string") {
spec = {
path: spec
};
} else {
spec = fluid.copy(spec);
}
spec.listenerId = spec.listenerId || fluid.allocateGuid(); // FLUID-5151: don't use identifyListener since event.addListener will use this as a namespace
spec.namespace = namespace;
spec.softNamespace = softNamespace;
if (typeof(listener) === "string") { // The reason for "globalName" is so that listener names can be resolved on first use and not on registration
listener = {globalName: listener};
}
spec.listener = listener;
if (spec.transactional !== false) {
spec.transactional = true;
}
if (!spec.segsArray) { // It's a manual registration
if (spec.path !== undefined) {
spec.segs = spec.segs || that.parseEL(spec.path);
}
if (!spec.segsArray) {
spec.segsArray = [spec.segs];
}
}
if (!spec.isRelay) {
// This acts for listeners registered externally. For relays, the exclusion spec is stored in "cond"
fluid.parseSourceExclusionSpec(spec, spec);
spec.wildcard = fluid.accumulate(fluid.transform(spec.segsArray, function (segs) {
return fluid.contains(segs, "*");
}), fluid.add, 0);
if (spec.wildcard && spec.segsArray.length > 1) {
fluid.fail("Error in model listener specification ", spec, " - you may not supply a wildcard pattern as one of a set of multiple paths to be matched");
}
}
var firer = that[spec.transactional ? "transListeners" : "listeners"];
firer.addListener(spec);
return spec; // return is used in registerModelListeners
};
that.modelChanged.removeListener = function (listener) {
that.listeners.removeListener(listener);
that.transListeners.removeListener(listener);
};
that.fireChangeRequest = function (changeRequest) {
var ation = that.initiate("local", changeRequest.source);
ation.fireChangeRequest(changeRequest);
ation.commit();
};
/**
* Initiate a fresh transaction on this applier, perhaps coordinated with other transactions sharing the same id across the component tree
* Arguments all optional
* @param {String} localSource - "local", "relay" or null Local source identifiers only good for transaction's representative on this applier
* @param {String|Array|Object} globalSources - Global source identifiers common across this transaction, expressed as a single string, an array of strings, or an object with a "toString" method.
* @param {String} transactionId - Global transaction id to enlist with.
* @return {Object} - The component initiating the change.
*/
that.initiate = function (localSource, globalSources, transactionId) {
localSource = globalSources === "init" ? null : (localSource || "local"); // supported values for localSource are "local" and "relay" - globalSource of "init" defeats defaulting of localSource to "local"
var defeatPost = localSource === "relay"; // defeatPost is supplied for all non-top-level transactions
var trans = {
instanceId: fluid.allocateGuid(), // for debugging only - the representative of this transction on this applier
id: transactionId || fluid.allocateGuid(), // The global transaction id across all appliers - allocate here if this is the starting point
changeRecord: {
resolverSetConfig: options.resolverSetConfig, // here to act as "options" in applyHolderChangeRequest
resolverGetConfig: options.resolverGetConfig
},
reset: function () {
trans.oldHolder = holder;
trans.newHolder = { model: fluid.copy(holder.model) };
trans.changeRecord.changes = 0;
trans.changeRecord.unchanged = 0; // just for type consistency - we don't use these values in the ChangeApplier
trans.changeRecord.changeMap = {};
},
commit: function (code) {
that.preCommit.fire(trans, that, code);
if (trans.changeRecord.changes > 0) {
var oldHolder = {model: holder.model};
holder.model = trans.newHolder.model;
fluid.notifyModelChanges(that.transListeners.sortedListeners, trans.changeRecord.changeMap, holder, oldHolder, null, trans, that, holder);
}
if (!defeatPost) {
that.postCommit.fire(trans, that, code);
}
},
fireChangeRequest: function (changeRequest) {
fluid.preFireChangeRequest(that, changeRequest);
changeRequest.transactionId = trans.id;
var deltaMap = fluid.model.applyHolderChangeRequest(trans.newHolder, changeRequest, trans.changeRecord);
fluid.notifyModelChanges(that.listeners.sortedListeners, deltaMap, trans.newHolder, holder, changeRequest, trans, that, holder);
},
hasChangeSource: function (source) {
return trans.fullSources[source];
}
};
var transRec = fluid.getModelTransactionRec(holder, trans.id);
if (transRec) {
fluid.mergeChangeSources(transRec.sources, globalSources);
trans.sources = transRec.sources;
trans.fullSources = Object.create(transRec.sources);
trans.fullSources[localSource] = true;
}
trans.reset();
fluid.bindRequestChange(trans);
return trans;
};
fluid.bindRequestChange(that);
fluid.bindELMethods(that);
return that;
};
/**
* Calculates the changes between the model values 'value' and
* 'oldValue' and returns an array of change records. The optional
* argument 'changePathPrefix' is prepended to the change path of
* each record (this is useful for generating change records to be
* applied at a non-root path in a model). The returned array of
* change records may be used with fluid.fireChanges().
*
* @param {Any} value - Model value to compare.
* @param {Any} oldValue - Model value to compare.
* @param {String|Array} [changePathPrefix] - [optional] Path prefix to prepend to change record paths, expressed as a string or an array of string segments.
* @return {Array} - An array of change record objects.
*/
fluid.modelPairToChanges = function (value, oldValue, changePathPrefix) {
changePathPrefix = changePathPrefix || "";
// Calculate the diff between value and oldValue
var diffOptions = {changes: 0, unchanged: 0, changeMap: {}};
fluid.model.diff(oldValue, value, diffOptions);
var changes = [];
// Recursively process the diff to generate an array of change
// records, stored in 'changes'
fluid.modelPairToChangesImpl(value,
fluid.pathUtil.parseEL(changePathPrefix),
diffOptions.changeMap, [], changes);
return changes;
};
/**
* This function implements recursive processing for
* fluid.modelPairToChanges(). It builds an array of change
* records, accumulated in the 'changes' argument, by walking the
* 'changeMap' structure and 'value' model value. As we walk down
* the model, our path from the root of the model is recorded in
* the 'changeSegs' argument.
*
* @param {Any} value - Model value
* @param {String[]} changePathPrefixSegs - Path prefix to prepend to change record paths, expressed as an array of string segments.
* @param {String|Object} changeMap - The changeMap structure from fluid.model.diff().
* @param {String[]} changeSegs - Our path relative to the model value root, expressed as an array of string segments.
* @param {Object[]} changes - The accumulated change record objects.
*/
fluid.modelPairToChangesImpl = function (value, changePathPrefixSegs, changeMap, changeSegs, changes) {
if (changeMap === "ADD") {
// The whole model value is new
changes.push({
path: changePathPrefixSegs,
value: value,
type: "ADD"
});
} else if (changeMap === "DELETE") {
// The whole model value has been deleted
changes.push({
path: changePathPrefixSegs,
value: null,
type: "DELETE"
});
} else if (fluid.isPlainObject(changeMap, true)) {
// Something within the model value has changed
fluid.each(changeMap, function (change, seg) {
var currentChangeSegs = changeSegs.concat([seg]);
if (change === "ADD") {
changes.push({
path: changePathPrefixSegs.concat(currentChangeSegs),
value: fluid.get(value, currentChangeSegs),
type: "ADD"
});
} else if (change === "DELETE") {
changes.push({
path: changePathPrefixSegs.concat(currentChangeSegs),
value: null,
type: "DELETE"
});
} else if (fluid.isPlainObject(change, true)) {
// Recurse down the tree of changes
fluid.modelPairToChangesImpl(value, changePathPrefixSegs,
change, currentChangeSegs, changes);
}
});
}
};
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
/**
* fluid.remoteModelComponent builds on top of fluid.modelComponent with the purpose of providing a buffer between a
* local and remote model that are attempting to stay in sync. For example a local model is being updated by user
* interaction, this is sent back to a remote server, which in turn tries to update the local model. If additional
* user actions occur during the roundtrip, an infinite loop of updates may occur. fluid.remoteModelComponent solves
* this by restricting reading and writing to a single request at a time, waiting for one request to complete
* before operating the next.
*
* For more detailed documentation, including diagrams outlining the fetch and write workflows, see:
* https://docs.fluidproject.org/infusion/development/RemoteModelAPI.html
*/
fluid.defaults("fluid.remoteModelComponent", {
gradeNames: ["fluid.modelComponent"],
events: {
afterFetch: null,
onFetch: null,
onFetchError: null,
afterWrite: null,
onWrite: null,
onWriteError: null
},
members: {
pendingRequests: {
write: null,
fetch: null
}
},
model: {
// an implementor must setup a model relay between the buffered local value and the portions of the
// component's model state that should be updated with the remote source.
local: {},
remote: {},
requestInFlight: false
},
modelListeners: {
"requestInFlight": {
listener: "fluid.remoteModelComponent.launchPendingRequest",
args: ["{that}"]
}
},
listeners: {
"afterFetch.updateModel": {
listener: "fluid.remoteModelComponent.updateModelFromFetch",
args: ["{that}", "{arguments}.0"],
priority: "before:unblock"
},
"afterFetch.unblock": {
listener: "fluid.remoteModelComponent.unblockFetchReq",
args: ["{that}"]
},
"onFetchError.unblock": {
listener: "fluid.remoteModelComponent.unblockFetchReq",
args: ["{that}"]
},
"afterWrite.updateRemoteModel": {
listener: "fluid.remoteModelComponent.updateRemoteFromLocal",
args: ["{that}"]
},
"afterWrite.unblock": {
changePath: "requestInFlight",
value: false,
priority: "after:updateRemoteModel"
},
"onWriteError.unblock": {
changePath: "requestInFlight",
value: false
}
},
invokers: {
fetch: {
funcName: "fluid.remoteModelComponent.fetch",
args: ["{that}"]
},
fetchImpl: "fluid.notImplemented",
write: {
funcName: "fluid.remoteModelComponent.write",
args: ["{that}"]
},
writeImpl: "fluid.notImplemented"
}
});
fluid.remoteModelComponent.launchPendingRequest = function (that) {
if (!that.model.requestInFlight) {
if (that.pendingRequests.fetch) {
that.fetch();
} else if (that.pendingRequests.write) {
that.write();
}
}
};
fluid.remoteModelComponent.updateModelFromFetch = function (that, fetchedModel) {
var remoteChanges = fluid.modelPairToChanges(fetchedModel, that.model.remote, "local");
var localChanges = fluid.modelPairToChanges(that.model.local, that.model.remote, "local");
var changes = remoteChanges.concat(localChanges);
// perform model updates in a single transaction
var transaction = that.applier.initiate();
transaction.fireChangeRequest({path: "local", type: "DELETE"}); // clear old local model
transaction.change("local", that.model.remote); // reset local model to the base for applying changes.
transaction.fireChangeRequest({path: "remote", type: "DELETE"}); // clear old remote model
transaction.change("remote", fetchedModel); // update remote model to fetched changes.
fluid.fireChanges(transaction, changes); // apply changes from remote and local onto base model.
transaction.commit(); // submit transaction
};
fluid.remoteModelComponent.updateRemoteFromLocal = function (that) {
// perform model updates in a single transaction
var transaction = that.applier.initiate();
transaction.fireChangeRequest({path: "remote", type: "DELETE"}); // clear old remote model
transaction.change("remote", that.model.local); // update remote model to local changes.
transaction.commit(); // submit transaction
};
/*
* Similar to fluid.promise.makeSequenceStrategy from FluidPromises.js; however, rather than passing along the
* result from one listener in the sequence to the next, the original payload is always passed to each listener.
* In this way, the synthetic events are handled like typical events, but a promise can be resolved/rejected at the
* end of the sequence.
*/
fluid.remoteModelComponent.makeSequenceStrategy = function (payload) {
return {
invokeNext: function (that) {
var lisrec = that.sources[that.index];
lisrec.listener = fluid.event.resolveListener(lisrec.listener);
var value = lisrec.listener.apply(null, [payload, that.options]);
return value;
},
resolveResult: function () {
return payload;
}
};
};
fluid.remoteModelComponent.makeSequence = function (listeners, payload, options) {
var sequencer = fluid.promise.makeSequencer(listeners, options, fluid.remoteModelComponent.makeSequenceStrategy(payload));
fluid.promise.resumeSequence(sequencer);
return sequencer;
};
fluid.remoteModelComponent.fireEventSequence = function (event, payload, options) {
var listeners = fluid.makeArray(event.sortedListeners);
var sequence = fluid.remoteModelComponent.makeSequence(listeners, payload, options);
return sequence.promise;
};
/**
* Adds a fetch request and returns a promise.
*
* Only one request can be in flight (processing) at a time. If a write request is in flight, the fetch will be
* queued. If a fetch request is already in queue/flight, the result of that request will be passed along to the
* current fetch request. When a fetch request is in flight , it will trigger the fetchImpl invoker to perform the
* actual request.
*
* Two synthetic events, onFetch and afterFetch, are fired during the processing of a fetch. onFetch can be used to
* perform any necessary actions before running fetchImpl. afterFetch can be used to perform any necessary actions
* after running fetchImpl (e.g. updating the model, unblocking the queue). If promises returned from onFetch, afterFetch, or
* fetchImpl are rejected, the onFetchError event will be fired.
*
* @param {Object} that - The component itself.
* @return {Promise} - A promise that will be resolved with the fetched value or rejected if there is an error.
*/
fluid.remoteModelComponent.fetch = function (that) {
var promise = fluid.promise();
var activePromise;
if (that.pendingRequests.fetch) {
activePromise = that.pendingRequests.fetch;
fluid.promise.follow(activePromise, promise);
} else {
activePromise = promise;
that.pendingRequests.fetch = promise;
}
if (!that.model.requestInFlight) {
var onFetchSeqPromise = fluid.remoteModelComponent.fireEventSequence(that.events.onFetch);
onFetchSeqPromise.then(function () {
that.applier.change("requestInFlight", true);
var reqPromise = that.fetchImpl();
reqPromise.then(function (data) {
var afterFetchSeqPromise = fluid.remoteModelComponent.fireEventSequence(that.events.afterFetch, data);
fluid.promise.follow(afterFetchSeqPromise, activePromise);
}, that.events.onFetchError.fire);
}, that.events.onFetchError.fire);
}
return promise;
};
fluid.remoteModelComponent.unblockFetchReq = function (that) {
that.pendingRequests.fetch = null;
that.applier.change("requestInFlight", false);
};
/**
* Adds a write request and returns a promise.
*
* Only one request can be in flight (processing) at a time. If a fetch or write request is in flight, the write will
* be queued. If a write request is already in queue, the result of that request will be passed along to the current
* write request. When a write request is in flight , it will trigger the writeImpl invoker to perform the
* actual request.
*
* Two synthetic events, onWrite and afterWrite, are fired during the processing of a write. onWrite can be used to
* perform any necessary actions before running writeImpl (e.g. performing a fetch). afterWrite can be used to perform any necessary actions
* after running writeImpl (e.g. unblocking the queue, performing a fetch). If promises returned from onWrite, afterWrite, or
* writeImpl are rejected, the onWriteError event will be fired.
*
* @param {Object} that - The component itself.
* @return {Promise} - A promise that will be resolved when the value is written or rejected if there is an error.
*/
fluid.remoteModelComponent.write = function (that) {
var promise = fluid.promise();
var activePromise;
if (that.pendingRequests.write) {
activePromise = that.pendingRequests.write;
fluid.promise.follow(that.pendingRequests.write, promise);
} else {
activePromise = promise;
}
if (that.model.requestInFlight) {
that.pendingRequests.write = activePromise;
} else {
var onWriteSeqPromise = fluid.remoteModelComponent.fireEventSequence(that.events.onWrite);
onWriteSeqPromise.then(function () {
that.applier.change("requestInFlight", true);
that.pendingRequests.write = null;
if (fluid.model.diff(that.model.local, that.model.remote)) {
var afterWriteSeqPromise = fluid.remoteModelComponent.fireEventSequence(that.events.afterWrite, that.model.local);
fluid.promise.follow(afterWriteSeqPromise, activePromise);
} else {
var reqPromise = that.writeImpl(that.model.local);
reqPromise.then(function (data) {
var afterWriteSeqPromise = fluid.remoteModelComponent.fireEventSequence(that.events.afterWrite, data);
fluid.promise.follow(afterWriteSeqPromise, activePromise);
}, that.events.onWriteError.fire);;
}
}, that.events.onWriteError.fire);
}
return promise;
};
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
fluid.registerNamespace("fluid.model.transform");
/** Grade definitions for standard transformation function hierarchy **/
fluid.defaults("fluid.transformFunction", {
gradeNames: "fluid.function"
});
// uses standard layout and workflow involving inputPath - an undefined input value
// will short-circuit the evaluation
fluid.defaults("fluid.standardInputTransformFunction", {
gradeNames: "fluid.transformFunction"
});
fluid.defaults("fluid.standardOutputTransformFunction", {
gradeNames: "fluid.transformFunction"
});
// defines a set of options "inputVariables" referring to its inputs, which are converted
// to functions that the transform may explicitly use to demand the input value
fluid.defaults("fluid.multiInputTransformFunction", {
gradeNames: "fluid.transformFunction"
});
// uses the standard layout and workflow involving inputPath and outputPath
fluid.defaults("fluid.standardTransformFunction", {
gradeNames: ["fluid.standardInputTransformFunction", "fluid.standardOutputTransformFunction"]
});
fluid.defaults("fluid.lens", {
gradeNames: "fluid.transformFunction",
invertConfiguration: null
// this function method returns "inverted configuration" rather than actually performing inversion
// TODO: harmonise with strategy used in VideoPlayer_framework.js
});
/***********************************
* Base utilities for transformers *
***********************************/
// unsupported, NON-API function
fluid.model.transform.pathToRule = function (inputPath) {
return {
transform: {
type: "fluid.transforms.value",
inputPath: inputPath
}
};
};
// unsupported, NON-API function
fluid.model.transform.literalValueToRule = function (input) {
return {
transform: {
type: "fluid.transforms.literalValue",
input: input
}
};
};
/* Accepts two fully escaped paths, either of which may be empty or null */
fluid.model.composePaths = function (prefix, suffix) {
prefix = prefix === 0 ? "0" : prefix || "";
suffix = suffix === 0 ? "0" : suffix || "";
return !prefix ? suffix : (!suffix ? prefix : prefix + "." + suffix);
};
fluid.model.transform.accumulateInputPath = function (inputPath, transformer, paths) {
if (inputPath !== undefined) {
paths.push(fluid.model.composePaths(transformer.inputPrefix, inputPath));
}
};
fluid.model.transform.accumulateStandardInputPath = function (input, transformSpec, transformer, paths) {
fluid.model.transform.getValue(undefined, transformSpec[input], transformer);
fluid.model.transform.accumulateInputPath(transformSpec[input + "Path"], transformer, paths);
};
fluid.model.transform.accumulateMultiInputPaths = function (inputVariables, transformSpec, transformer, paths) {
fluid.each(inputVariables, function (v, k) {
fluid.model.transform.accumulateStandardInputPath(k, transformSpec, transformer, paths);
});
};
fluid.model.transform.getValue = function (inputPath, value, transformer) {
var togo;
if (inputPath !== undefined) { // NB: We may one day want to reverse the crazy jQuery-like convention that "no path means root path"
togo = fluid.get(transformer.source, fluid.model.composePaths(transformer.inputPrefix, inputPath), transformer.resolverGetConfig);
}
if (togo === undefined) {
// FLUID-5867 - actually helpful behaviour here rather than the insane original default of expecting a short-form value document
togo = fluid.isPrimitive(value) ? value :
("literalValue" in value ? value.literalValue :
(value.transform === undefined ? value : transformer.expand(value)));
}
return togo;
};
// distinguished value which indicates that a transformation rule supplied a
// non-default output path, and so the user should be prevented from making use of it
// in a compound transform definition
fluid.model.transform.NONDEFAULT_OUTPUT_PATH_RETURN = {};
fluid.model.transform.setValue = function (userOutputPath, value, transformer) {
// avoid crosslinking to input object - this might be controlled by a "nocopy" option in future
var toset = fluid.copy(value);
var outputPath = fluid.model.composePaths(transformer.outputPrefix, userOutputPath);
// TODO: custom resolver config here to create non-hash output model structure
if (toset !== undefined) {
transformer.applier.change(outputPath, toset);
}
return userOutputPath ? fluid.model.transform.NONDEFAULT_OUTPUT_PATH_RETURN : toset;
};
/* Resolves the <key> given as parameter by looking up the path <key>Path in the object
* to be transformed. If not present, it resolves the <key> by using the literal value if primitive,
* or expanding otherwise. <def> defines the default value if unableto resolve the key. If no
* default value is given undefined is returned
*/
fluid.model.transform.resolveParam = function (transformSpec, transformer, key, def) {
var val = fluid.model.transform.getValue(transformSpec[key + "Path"], transformSpec[key], transformer);
return (val !== undefined) ? val : def;
};
// Compute a "match score" between two pieces of model material, with 0 indicating a complete mismatch, and
// higher values indicating increasingly good matches
fluid.model.transform.matchValue = function (expected, actual, partialMatches) {
var stats = {changes: 0, unchanged: 0, changeMap: {}};
fluid.model.diff(expected, actual, stats);
// i) a pair with 0 matches counts for 0 in all cases
// ii) without "partial match mode" (the default), we simply count matches, with any mismatch giving 0
// iii) with "partial match mode", a "perfect score" in the top 24 bits is
// penalised for each mismatch, with a positive score of matches store in the bottom 24 bits
return stats.unchanged === 0 ? 0
: (partialMatches ? 0xffffff000000 - 0x1000000 * stats.changes + stats.unchanged :
(stats.changes ? 0 : 0xffffff000000 + stats.unchanged));
};
fluid.model.transform.invertPaths = function (transformSpec, transformer) {
// TODO: this will not behave correctly in the face of compound "input" which contains
// further transforms
var oldOutput = fluid.model.composePaths(transformer.outputPrefix, transformSpec.outputPath);
transformSpec.outputPath = fluid.model.composePaths(transformer.inputPrefix, transformSpec.inputPath);
transformSpec.inputPath = oldOutput;
return transformSpec;
};
// TODO: prefixApplier is a transform which is currently unused and untested
fluid.model.transform.prefixApplier = function (transformSpec, transformer) {
if (transformSpec.inputPrefix) {
transformer.inputPrefixOp.push(transformSpec.inputPrefix);
}
if (transformSpec.outputPrefix) {
transformer.outputPrefixOp.push(transformSpec.outputPrefix);
}
transformer.expand(transformSpec.input);
if (transformSpec.inputPrefix) {
transformer.inputPrefixOp.pop();
}
if (transformSpec.outputPrefix) {
transformer.outputPrefixOp.pop();
}
};
fluid.defaults("fluid.model.transform.prefixApplier", {
gradeNames: ["fluid.transformFunction"]
});
// unsupported, NON-API function
fluid.model.makePathStack = function (transform, prefixName) {
var stack = transform[prefixName + "Stack"] = [];
transform[prefixName] = "";
return {
push: function (prefix) {
var newPath = fluid.model.composePaths(transform[prefixName], prefix);
stack.push(transform[prefixName]);
transform[prefixName] = newPath;
},
pop: function () {
transform[prefixName] = stack.pop();
}
};
};
// unsupported, NON-API function
fluid.model.transform.doTransform = function (transformSpec, transformer, transformOpts) {
var expdef = transformOpts.defaults;
var transformFn = fluid.getGlobalValue(transformOpts.typeName);
if (typeof(transformFn) !== "function") {
fluid.fail("Transformation record specifies transformation function with name " +
transformSpec.type + " which is not a function - ", transformFn);
}
if (!fluid.hasGrade(expdef, "fluid.transformFunction")) {
// If no suitable grade is set up, assume that it is intended to be used as a standardTransformFunction
expdef = fluid.defaults("fluid.standardTransformFunction");
}
var transformArgs = [transformSpec, transformer];
if (fluid.hasGrade(expdef, "fluid.multiInputTransformFunction")) {
var inputs = {};
fluid.each(expdef.inputVariables, function (v, k) {
inputs[k] = function () {
var input = fluid.model.transform.getValue(transformSpec[k + "Path"], transformSpec[k], transformer);
// TODO: This is a mess, null might perfectly well be a possible default
// if no match, assign default if one exists (v != null)
input = (input === undefined && v !== null) ? v : input;
return input;
};
});
transformArgs.unshift(inputs);
}
if (fluid.hasGrade(expdef, "fluid.standardInputTransformFunction")) {
if (!("input" in transformSpec) && !("inputPath" in transformSpec)) {
fluid.fail("Error in transform specification. Either \"input\" or \"inputPath\" must be specified for a standardInputTransformFunction: received ", transformSpec);
}
var expanded = fluid.model.transform.getValue(transformSpec.inputPath, transformSpec.input, transformer);
transformArgs.unshift(expanded);
// if the function has no input, the result is considered undefined, and this is returned
if (expanded === undefined) {
return undefined;
}
}
var transformed = transformFn.apply(null, transformArgs);
if (fluid.hasGrade(expdef, "fluid.standardOutputTransformFunction")) {
// "doOutput" flag is currently set nowhere, but could be used in future
var outputPath = transformSpec.outputPath !== undefined ? transformSpec.outputPath : (transformOpts.doOutput ? "" : undefined);
if (outputPath !== undefined && transformed !== undefined) {
//If outputPath is given in the expander we want to:
// (1) output to the document
// (2) return undefined, to ensure that expanders higher up in the hierarchy doesn't attempt to output it again
fluid.model.transform.setValue(transformSpec.outputPath, transformed, transformer);
transformed = undefined;
}
}
return transformed;
};
// OLD PATHUTIL utilities: Rescued from old DataBinding implementation to support obsolete "schema" scheme for transforms - all of this needs to be rethought
var globalAccept = [];
fluid.registerNamespace("fluid.pathUtil");
/* Parses a path segment, following escaping rules, starting from character index i in the supplied path */
fluid.pathUtil.getPathSegment = function (path, i) {
fluid.pathUtil.getPathSegmentImpl(globalAccept, path, i);
return globalAccept[0];
};
/* Returns just the head segment of an EL path */
fluid.pathUtil.getHeadPath = function (path) {
return fluid.pathUtil.getPathSegment(path, 0);
};
/* Returns all of an EL path minus its first segment - if the path consists of just one segment, returns "" */
fluid.pathUtil.getFromHeadPath = function (path) {
var firstdot = fluid.pathUtil.getPathSegmentImpl(null, path, 0);
return firstdot === path.length ? "" : path.substring(firstdot + 1);
};
/** Determines whether a particular EL path matches a given path specification.
* The specification consists of a path with optional wildcard segments represented by "*".
* @param {String} spec - The specification to be matched
* @param {String} path - The path to be tested
* @param {Boolean} exact - Whether the path must exactly match the length of the specification in
* terms of path segments in order to count as match. If exact is falsy, short specifications will
* match all longer paths as if they were padded out with "*" segments
* @return {Array|null} - An array of {String} path segments which matched the specification, or <code>null</code> if there was no match.
*/
fluid.pathUtil.matchPath = function (spec, path, exact) {
var togo = [];
while (true) {
if (((path === "") ^ (spec === "")) && exact) {
return null;
}
// FLUID-4625 - symmetry on spec and path is actually undesirable, but this
// quickly avoids at least missed notifications - improved (but slower)
// implementation should explode composite changes
if (!spec || !path) {
break;
}
var spechead = fluid.pathUtil.getHeadPath(spec);
var pathhead = fluid.pathUtil.getHeadPath(path);
// if we fail to match on a specific component, fail.
if (spechead !== "*" && spechead !== pathhead) {
return null;
}
togo.push(pathhead);
spec = fluid.pathUtil.getFromHeadPath(spec);
path = fluid.pathUtil.getFromHeadPath(path);
}
return togo;
};
// unsupported, NON-API function
fluid.model.transform.expandWildcards = function (transformer, source) {
fluid.each(source, function (value, key) {
var q = transformer.queuedTransforms;
transformer.pathOp.push(fluid.pathUtil.escapeSegment(key.toString()));
for (var i = 0; i < q.length; ++i) {
if (fluid.pathUtil.matchPath(q[i].matchPath, transformer.path, true)) {
var esCopy = fluid.copy(q[i].transformSpec);
if (esCopy.inputPath === undefined || fluid.model.transform.hasWildcard(esCopy.inputPath)) {
esCopy.inputPath = "";
}
// TODO: allow some kind of interpolation for output path
// TODO: Also, we now require outputPath to be specified in these cases for output to be produced as well.. Is that something we want to continue with?
transformer.inputPrefixOp.push(transformer.path);
transformer.outputPrefixOp.push(transformer.path);
var transformOpts = fluid.model.transform.lookupType(esCopy.type);
var result = fluid.model.transform.doTransform(esCopy, transformer, transformOpts);
if (result !== undefined) {
fluid.model.transform.setValue(null, result, transformer);
}
transformer.outputPrefixOp.pop();
transformer.inputPrefixOp.pop();
}
}
if (!fluid.isPrimitive(value)) {
fluid.model.transform.expandWildcards(transformer, value);
}
transformer.pathOp.pop();
});
};
// unsupported, NON-API function
fluid.model.transform.hasWildcard = function (path) {
return typeof(path) === "string" && path.indexOf("*") !== -1;
};
// unsupported, NON-API function
fluid.model.transform.maybePushWildcard = function (transformSpec, transformer) {
var hw = fluid.model.transform.hasWildcard;
var matchPath;
if (hw(transformSpec.inputPath)) {
matchPath = fluid.model.composePaths(transformer.inputPrefix, transformSpec.inputPath);
}
else if (hw(transformer.outputPrefix) || hw(transformSpec.outputPath)) {
matchPath = fluid.model.composePaths(transformer.outputPrefix, transformSpec.outputPath);
}
if (matchPath) {
transformer.queuedTransforms.push({transformSpec: transformSpec, outputPrefix: transformer.outputPrefix, inputPrefix: transformer.inputPrefix, matchPath: matchPath});
return true;
}
return false;
};
fluid.model.sortByKeyLength = function (inObject) {
var keys = fluid.keys(inObject);
return keys.sort(fluid.compareStringLength(true));
};
// Three handler functions operating the (currently) three different processing modes
// unsupported, NON-API function
fluid.model.transform.handleTransformStrategy = function (transformSpec, transformer, transformOpts) {
if (fluid.model.transform.maybePushWildcard(transformSpec, transformer)) {
return;
}
else {
return fluid.model.transform.doTransform(transformSpec, transformer, transformOpts);
}
};
// unsupported, NON-API function
fluid.model.transform.handleInvertStrategy = function (transformSpec, transformer, transformOpts) {
transformSpec = fluid.copy(transformSpec);
// if we have a standardTransformFunction we can switch input and output arguments:
if (fluid.hasGrade(transformOpts.defaults, "fluid.standardTransformFunction")) {
transformSpec = fluid.model.transform.invertPaths(transformSpec, transformer);
}
var invertor = transformOpts.defaults && transformOpts.defaults.invertConfiguration;
if (invertor) {
var inverted = fluid.invokeGlobalFunction(invertor, [transformSpec, transformer]);
transformer.inverted.push(inverted);
} else {
transformer.inverted.push(fluid.model.transform.uninvertibleTransform);
}
};
// unsupported, NON-API function
fluid.model.transform.handleCollectStrategy = function (transformSpec, transformer, transformOpts) {
var defaults = transformOpts.defaults;
var standardInput = fluid.hasGrade(defaults, "fluid.standardInputTransformFunction");
var multiInput = fluid.hasGrade(defaults, "fluid.multiInputTransformFunction");
if (standardInput) {
fluid.model.transform.accumulateStandardInputPath("input", transformSpec, transformer, transformer.inputPaths);
}
if (multiInput) {
fluid.model.transform.accumulateMultiInputPaths(defaults.inputVariables, transformSpec, transformer, transformer.inputPaths);
}
var collector = defaults.collectInputPaths;
if (collector) {
var collected = fluid.makeArray(fluid.invokeGlobalFunction(collector, [transformSpec, transformer]));
Array.prototype.push.apply(transformer.inputPaths, collected); // push all elements of collected onto inputPaths
}
};
fluid.model.transform.lookupType = function (typeName, transformSpec) {
if (!typeName) {
fluid.fail("Transformation record is missing a type name: ", transformSpec);
}
if (typeName.indexOf(".") === -1) {
typeName = "fluid.transforms." + typeName;
}
var defaults = fluid.defaults(typeName);
return { defaults: defaults, typeName: typeName};
};
// unsupported, NON-API function
fluid.model.transform.processRule = function (rule, transformer) {
if (typeof(rule) === "string") {
rule = fluid.model.transform.pathToRule(rule);
}
// special dispensation to allow "literalValue" to escape any value
else if (rule.literalValue !== undefined) {
rule = fluid.model.transform.literalValueToRule(rule.literalValue);
}
var togo;
if (rule.transform) {
var transformSpec, transformOpts;
if (fluid.isArrayable(rule.transform)) {
// if the transform holds an array, each transformer within that is responsible for its own output
var transforms = rule.transform;
togo = undefined;
for (var i = 0; i < transforms.length; ++i) {
transformSpec = transforms[i];
transformOpts = fluid.model.transform.lookupType(transformSpec.type);
transformer.transformHandler(transformSpec, transformer, transformOpts);
}
} else {
// else we just have a normal single transform which will return 'undefined' as a flag to defeat cascading output
transformSpec = rule.transform;
transformOpts = fluid.model.transform.lookupType(transformSpec.type);
togo = transformer.transformHandler(transformSpec, transformer, transformOpts);
}
}
// if rule is an array, save path for later use in schema strategy on final applier (so output will be interpreted as array)
if (fluid.isArrayable(rule)) {
transformer.collectedFlatSchemaOpts = transformer.collectedFlatSchemaOpts || {};
transformer.collectedFlatSchemaOpts[transformer.outputPrefix] = "array";
}
fluid.each(rule, function (value, key) {
if (key !== "transform") {
transformer.outputPrefixOp.push(key);
var togo = transformer.expand(value, transformer);
// Value expanders and arrays as rules implicitly output, unless they have nothing (undefined) to output
if (togo !== undefined) {
fluid.model.transform.setValue(null, togo, transformer);
// ensure that expanders further up does not try to output this value as well.
togo = undefined;
}
transformer.outputPrefixOp.pop();
}
});
return togo;
};
// unsupported, NON-API function
// 3rd arg is disused by the framework and always defaults to fluid.model.transform.processRule
fluid.model.transform.makeStrategy = function (transformer, handleFn, transformFn) {
transformFn = transformFn || fluid.model.transform.processRule;
transformer.expand = function (rules) {
return transformFn(rules, transformer);
};
transformer.outputPrefixOp = fluid.model.makePathStack(transformer, "outputPrefix");
transformer.inputPrefixOp = fluid.model.makePathStack(transformer, "inputPrefix");
transformer.transformHandler = handleFn;
};
/* A special, empty, transform document representing the inversion of a transformation which does not not have an inverse
*/
fluid.model.transform.uninvertibleTransform = Object.freeze({});
/** Accepts a transformation document, and returns its inverse if all of its constituent transforms have inverses
* defined via their individual invertConfiguration functions, or else `fluid.model.transform.uninvertibleTransform`
* if any of them do not.
* Note that this algorithm will give faulty results in many cases of compound transformation documents.
* @param {Transform} rules - The model transformation document to be inverted
* @return {Transform} The inverse transformation document if it can be computed easily, or
* `fluid.model.transform.uninvertibleTransform` if it is clear that it cannot.
*/
fluid.model.transform.invertConfiguration = function (rules) {
var transformer = {
inverted: []
};
fluid.model.transform.makeStrategy(transformer, fluid.model.transform.handleInvertStrategy);
transformer.expand(rules);
var invertible = transformer.inverted.indexOf(fluid.model.transform.uninvertibleTransform) === -1;
return invertible ? {
transform: transformer.inverted
} : fluid.model.transform.uninvertibleTransform;
};
/** Compute the paths which will be read from the input document of the supplied transformation if it were operated.
*
* @param {Transform} rules - The transformation for which the input paths are to be computed.
* @return {Array} - An array of paths which will be read by the document.
*/
fluid.model.transform.collectInputPaths = function (rules) {
var transformer = {
inputPaths: []
};
fluid.model.transform.makeStrategy(transformer, fluid.model.transform.handleCollectStrategy);
transformer.expand(rules);
// Deduplicate input paths
var inputPathHash = fluid.arrayToHash(transformer.inputPaths);
return Object.keys(inputPathHash);
};
// unsupported, NON-API function
fluid.model.transform.flatSchemaStrategy = function (flatSchema, getConfig) {
var keys = fluid.model.sortByKeyLength(flatSchema);
return function (root, segment, index, segs) {
var path = getConfig.parser.compose.apply(null, segs.slice(0, index));
// TODO: clearly this implementation could be much more efficient
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
if (fluid.pathUtil.matchPath(key, path, true) !== null) {
return flatSchema[key];
}
}
};
};
// unsupported, NON-API function
fluid.model.transform.defaultSchemaValue = function (schemaValue) {
var type = fluid.isPrimitive(schemaValue) ? schemaValue : schemaValue.type;
return type === "array" ? [] : {};
};
// unsupported, NON-API function
fluid.model.transform.isomorphicSchemaStrategy = function (source, getConfig) {
return function (root, segment, index, segs) {
var existing = fluid.get(source, segs.slice(0, index), getConfig);
return fluid.isArrayable(existing) ? "array" : "object";
};
};
// unsupported, NON-API function
fluid.model.transform.decodeStrategy = function (source, options, getConfig) {
if (options.isomorphic) {
return fluid.model.transform.isomorphicSchemaStrategy(source, getConfig);
}
else if (options.flatSchema) {
return fluid.model.transform.flatSchemaStrategy(options.flatSchema, getConfig);
}
};
// unsupported, NON-API function
fluid.model.transform.schemaToCreatorStrategy = function (strategy) {
return function (root, segment, index, segs) {
if (root[segment] === undefined) {
var schemaValue = strategy(root, segment, index, segs);
root[segment] = fluid.model.transform.defaultSchemaValue(schemaValue);
return root[segment];
}
};
};
/* Transforms a model by a sequence of rules. Parameters as for fluid.model.transform,
* only with an array accepted for "rules"
*/
fluid.model.transform.sequence = function (source, rules, options) {
for (var i = 0; i < rules.length; ++i) {
source = fluid.model.transform(source, rules[i], options);
}
return source;
};
fluid.model.compareByPathLength = function (changea, changeb) {
var pdiff = changea.path.length - changeb.path.length;
return pdiff === 0 ? changea.sequence - changeb.sequence : pdiff;
};
/* Fires an accumulated set of change requests in increasing order of target pathlength */
fluid.model.fireSortedChanges = function (changes, applier) {
changes.sort(fluid.model.compareByPathLength);
fluid.fireChanges(applier, changes);
};
/**
* Transforms a model based on a specified expansion rules objects.
* Rules objects take the form of:
* {
* "target.path": "value.el.path" || {
* transform: {
* type: "transform.function.path",
* ...
* }
* }
* }
*
* @param {Object} source - the model to transform
* @param {Object} rules - a rules object containing instructions on how to transform the model
* @param {Object} options - a set of rules governing the transformations. At present this may contain
* the values <code>isomorphic: true</code> indicating that the output model is to be governed by the
* same schema found in the input model, or <code>flatSchema</code> holding a flat schema object which
* consists of a hash of EL path specifications with wildcards, to the values "array"/"object" defining
* the schema to be used to construct missing trunk values.
* @return {Any} The transformed model.
*/
fluid.model.transformWithRules = function (source, rules, options) {
options = options || {};
var getConfig = fluid.model.escapedGetConfig;
var setConfig = fluid.model.escapedSetConfig;
var schemaStrategy = fluid.model.transform.decodeStrategy(source, options, getConfig);
var transformer = {
source: source,
target: {
// TODO: This should default to undefined to allow return of primitives, etc.
model: schemaStrategy ? fluid.model.transform.defaultSchemaValue(schemaStrategy(null, "", 0, [""])) : {}
},
resolverGetConfig: getConfig,
resolverSetConfig: setConfig,
collectedFlatSchemaOpts: undefined, // to hold options for flat schema collected during transforms
queuedChanges: [],
queuedTransforms: [] // TODO: This is used only by wildcard applier - explain its operation
};
fluid.model.transform.makeStrategy(transformer, fluid.model.transform.handleTransformStrategy);
transformer.applier = {
fireChangeRequest: function (changeRequest) {
changeRequest.sequence = transformer.queuedChanges.length;
transformer.queuedChanges.push(changeRequest);
}
};
fluid.bindRequestChange(transformer.applier);
transformer.expand(rules);
var rootSetConfig = fluid.copy(setConfig);
// Modify schemaStrategy if we collected flat schema options for the setConfig of finalApplier
if (transformer.collectedFlatSchemaOpts !== undefined) {
$.extend(transformer.collectedFlatSchemaOpts, options.flatSchema);
schemaStrategy = fluid.model.transform.flatSchemaStrategy(transformer.collectedFlatSchemaOpts, getConfig);
}
rootSetConfig.strategies = [fluid.model.defaultFetchStrategy, schemaStrategy ? fluid.model.transform.schemaToCreatorStrategy(schemaStrategy)
: fluid.model.defaultCreatorStrategy];
transformer.finalApplier = options.finalApplier || fluid.makeHolderChangeApplier(transformer.target, {resolverSetConfig: rootSetConfig});
if (transformer.queuedTransforms.length > 0) {
transformer.typeStack = [];
transformer.pathOp = fluid.model.makePathStack(transformer, "path");
fluid.model.transform.expandWildcards(transformer, source);
}
fluid.model.fireSortedChanges(transformer.queuedChanges, transformer.finalApplier);
return transformer.target.model;
};
$.extend(fluid.model.transformWithRules, fluid.model.transform);
fluid.model.transform = fluid.model.transformWithRules;
/* Utility function to produce a standard options transformation record for a single set of rules */
fluid.transformOne = function (rules) {
return {
transformOptions: {
transformer: "fluid.model.transformWithRules",
config: rules
}
};
};
/* Utility function to produce a standard options transformation record for multiple rules to be applied in sequence */
fluid.transformMany = function (rules) {
return {
transformOptions: {
transformer: "fluid.model.transform.sequence",
config: rules
}
};
};
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
fluid.registerNamespace("fluid.model.transform");
fluid.registerNamespace("fluid.transforms");
/**********************************
* Standard transformer functions *
**********************************/
fluid.defaults("fluid.transforms.value", {
gradeNames: "fluid.standardTransformFunction",
invertConfiguration: "fluid.identity"
});
fluid.transforms.value = fluid.identity;
// Export the use of the "value" transform under the "identity" name for FLUID-5293
fluid.transforms.identity = fluid.transforms.value;
fluid.defaults("fluid.transforms.identity", {
gradeNames: "fluid.transforms.value"
});
// A helpful utility function to be used when a transform's inverse is the identity
fluid.transforms.invertToIdentity = function (transformSpec) {
transformSpec.type = "fluid.transforms.identity";
return transformSpec;
};
fluid.defaults("fluid.transforms.literalValue", {
gradeNames: "fluid.standardOutputTransformFunction"
});
fluid.transforms.literalValue = function (transformSpec) {
return transformSpec.input;
};
fluid.defaults("fluid.transforms.stringToNumber", {
gradeNames: ["fluid.standardTransformFunction", "fluid.lens"],
invertConfiguration: "fluid.transforms.stringToNumber.invert"
});
fluid.transforms.stringToNumber = function (value) {
var newValue = Number(value);
return isNaN(newValue) ? undefined : newValue;
};
fluid.transforms.stringToNumber.invert = function (transformSpec) {
transformSpec.type = "fluid.transforms.numberToString";
return transformSpec;
};
fluid.defaults("fluid.transforms.numberToString", {
gradeNames: ["fluid.standardTransformFunction", "fluid.lens"],
invertConfiguration: "fluid.transforms.numberToString.invert"
});
fluid.transforms.numberToString = function (value, transformSpec) {
if (typeof value === "number") {
if (typeof transformSpec.scale === "number" && !isNaN(transformSpec.scale)) {
var rounded = fluid.roundToDecimal(value, transformSpec.scale, transformSpec.method);
return rounded.toString();
} else {
return value.toString();
}
}
};
fluid.transforms.numberToString.invert = function (transformSpec) {
transformSpec.type = "fluid.transforms.stringToNumber";
return transformSpec;
};
fluid.defaults("fluid.transforms.count", {
gradeNames: "fluid.standardTransformFunction"
});
fluid.transforms.count = function (value) {
return fluid.makeArray(value).length;
};
fluid.defaults("fluid.transforms.round", {
gradeNames: ["fluid.standardTransformFunction", "fluid.lens"],
invertConfiguration: "fluid.transforms.invertToIdentity"
});
fluid.transforms.round = function (value, transformSpec) {
// validation of scale is handled by roundToDecimal
return fluid.roundToDecimal(value, transformSpec.scale, transformSpec.method);
};
fluid.defaults("fluid.transforms.delete", {
gradeNames: "fluid.transformFunction"
});
fluid.transforms["delete"] = function (transformSpec, transformer) {
var outputPath = fluid.model.composePaths(transformer.outputPrefix, transformSpec.outputPath);
transformer.applier.change(outputPath, null, "DELETE");
};
fluid.defaults("fluid.transforms.firstValue", {
gradeNames: "fluid.standardOutputTransformFunction"
});
fluid.transforms.firstValue = function (transformSpec, transformer) {
if (!transformSpec.values || !transformSpec.values.length) {
fluid.fail("firstValue transformer requires an array of values at path named \"values\", supplied", transformSpec);
}
for (var i = 0; i < transformSpec.values.length; i++) {
var value = transformSpec.values[i];
// TODO: problem here - all of these transforms will have their side-effects (setValue) even if only one is chosen
var expanded = transformer.expand(value);
if (expanded !== undefined) {
return expanded;
}
}
};
fluid.defaults("fluid.transforms.linearScale", {
gradeNames: ["fluid.multiInputTransformFunction",
"fluid.standardTransformFunction",
"fluid.lens" ],
invertConfiguration: "fluid.transforms.linearScale.invert",
inputVariables: {
factor: 1,
offset: 0
}
});
/* simple linear transformation */
fluid.transforms.linearScale = function (input, extraInputs) {
var factor = extraInputs.factor();
var offset = extraInputs.offset();
if (typeof(input) !== "number" || typeof(factor) !== "number" || typeof(offset) !== "number") {
return undefined;
}
return input * factor + offset;
};
/* TODO: This inversion doesn't work if the value and factors are given as paths in the source model */
fluid.transforms.linearScale.invert = function (transformSpec) {
// delete the factor and offset paths if present
delete transformSpec.factorPath;
delete transformSpec.offsetPath;
if (transformSpec.factor !== undefined) {
transformSpec.factor = (transformSpec.factor === 0) ? 0 : 1 / transformSpec.factor;
}
if (transformSpec.offset !== undefined) {
transformSpec.offset = -transformSpec.offset * (transformSpec.factor !== undefined ? transformSpec.factor : 1);
}
return transformSpec;
};
fluid.defaults("fluid.transforms.binaryOp", {
gradeNames: [ "fluid.multiInputTransformFunction", "fluid.standardOutputTransformFunction" ],
inputVariables: {
left: null,
right: null
}
});
fluid.transforms.binaryLookup = {
"===": function (a, b) { return fluid.model.isSameValue(a, b); },
"!==": function (a, b) { return !fluid.model.isSameValue(a, b); },
"<=": function (a, b) { return a <= b; },
"<": function (a, b) { return a < b; },
">=": function (a, b) { return a >= b; },
">": function (a, b) { return a > b; },
"+": function (a, b) { return a + b; },
"-": function (a, b) { return a - b; },
"*": function (a, b) { return a * b; },
"/": function (a, b) { return a / b; },
"%": function (a, b) { return a % b; },
"&&": function (a, b) { return a && b; },
"||": function (a, b) { return a || b; }
};
fluid.transforms.binaryOp = function (inputs, transformSpec, transformer) {
var left = inputs.left();
var right = inputs.right();
var operator = fluid.model.transform.getValue(undefined, transformSpec.operator, transformer);
var fun = fluid.transforms.binaryLookup[operator];
return (fun === undefined || left === undefined || right === undefined) ?
undefined : fun(left, right);
};
fluid.defaults("fluid.transforms.condition", {
gradeNames: [ "fluid.multiInputTransformFunction", "fluid.standardOutputTransformFunction" ],
inputVariables: {
"true": null,
"false": null,
"condition": null
}
});
fluid.transforms.condition = function (inputs) {
var condition = inputs.condition();
if (condition === null) {
return undefined;
}
return inputs[condition ? "true" : "false"]();
};
fluid.defaults("fluid.transforms.valueMapper", {
gradeNames: ["fluid.lens"],
invertConfiguration: "fluid.transforms.valueMapper.invert",
collectInputPaths: "fluid.transforms.valueMapper.collect"
});
/* unsupported, NON-API function
* sorts by the object's 'matchValue' property, where higher is better.
* Tiebreaking is done via the `index` property, where a lower index takes priority
*/
fluid.model.transform.compareMatches = function (speca, specb) {
var matchDiff = specb.matchValue - speca.matchValue;
return matchDiff === 0 ? speca.index - specb.index : matchDiff; // tiebreak using 'index'
};
fluid.transforms.valueMapper = function (transformSpec, transformer) {
if (!transformSpec.match) {
fluid.fail("valueMapper requires an array or hash of matches at path named \"match\", supplied ", transformSpec);
}
var value = fluid.model.transform.getValue(transformSpec.defaultInputPath, transformSpec.defaultInput, transformer);
var matchedEntry = (fluid.isArrayable(transformSpec.match)) ? // long form with array of records?
fluid.transforms.valueMapper.longFormMatch(value, transformSpec, transformer) :
transformSpec.match[value];
if (matchedEntry === undefined) { // if no matches found, default to noMatch
matchedEntry = transformSpec.noMatch;
}
if (matchedEntry === undefined) { // if there was no noMatch directive, return undefined
return;
}
var outputPath = matchedEntry.outputPath === undefined ? transformSpec.defaultOutputPath : matchedEntry.outputPath;
transformer.outputPrefixOp.push(outputPath);
var outputValue;
if (fluid.isPrimitive(matchedEntry)) {
outputValue = matchedEntry;
} else if (matchedEntry.outputUndefinedValue) { // if outputUndefinedValue is set, outputValue `undefined`
outputValue = undefined;
} else {
// get value from outputValue. If none is found set the outputValue to be that of defaultOutputValue (or undefined)
outputValue = fluid.model.transform.resolveParam(matchedEntry, transformer, "outputValue", undefined);
outputValue = (outputValue === undefined) ? transformSpec.defaultOutputValue : outputValue;
}
// output if we have a path and something to output
if (typeof(outputPath) === "string" && outputValue !== undefined) {
fluid.model.transform.setValue(undefined, outputValue, transformer, transformSpec.merge);
outputValue = undefined; // make sure we don't also return value
}
transformer.outputPrefixOp.pop();
return outputValue;
};
// unsupported, NON-API function
fluid.transforms.valueMapper.longFormMatch = function (valueFromDefaultPath, transformSpec, transformer) {
var o = transformSpec.match;
if (o.length === 0) {
fluid.fail("valueMapper supplied empty list of matches: ", transformSpec);
}
var matchPower = [];
for (var i = 0; i < o.length; ++i) {
var option = o[i];
var value = option.inputPath ?
fluid.model.transform.getValue(option.inputPath, undefined, transformer) : valueFromDefaultPath;
var matchValue = fluid.model.transform.matchValue(option.inputValue, value, option.partialMatches);
matchPower[i] = {index: i, matchValue: matchValue};
}
matchPower.sort(fluid.model.transform.compareMatches);
return matchPower[0].matchValue <= 0 ? undefined : o[matchPower[0].index];
};
fluid.transforms.valueMapper.invert = function (transformSpec, transformer) {
var match = [];
var togo = {
type: "fluid.transforms.valueMapper",
match: match
};
var isArray = fluid.isArrayable(transformSpec.match);
togo.defaultInputPath = fluid.model.composePaths(transformer.outputPrefix, transformSpec.defaultOutputPath);
togo.defaultOutputPath = fluid.model.composePaths(transformer.inputPrefix, transformSpec.defaultInputPath);
var def = fluid.firstDefined;
fluid.each(transformSpec.match, function (option, key) {
if (option.outputUndefinedValue === true) {
return; // don't attempt to invert undefined output value entries
}
var outOption = {};
var origInputValue = def(isArray ? option.inputValue : key, transformSpec.defaultInputValue);
if (origInputValue === undefined) {
fluid.fail("Failure inverting configuration for valueMapper - inputValue could not be resolved for record " + key + ": ", transformSpec);
}
outOption.outputValue = origInputValue;
outOption.inputValue = !isArray && fluid.isPrimitive(option) ?
option : def(option.outputValue, transformSpec.defaultOutputValue);
if (option.outputPath) {
outOption.inputPath = fluid.model.composePaths(transformer.outputPrefix, def(option.outputPath, transformSpec.outputPath));
}
if (option.inputPath) {
outOption.outputPath = fluid.model.composePaths(transformer.inputPrefix, def(option.inputPath, transformSpec.inputPath));
}
match.push(outOption);
});
return togo;
};
fluid.transforms.valueMapper.collect = function (transformSpec, transformer) {
var togo = [];
fluid.model.transform.accumulateStandardInputPath("defaultInput", transformSpec, transformer, togo);
fluid.each(transformSpec.match, function (option) {
fluid.model.transform.accumulateInputPath(option.inputPath, transformer, togo);
});
return togo;
};
/* -------- arrayToSetMembership and setMembershipToArray ---------------- */
fluid.defaults("fluid.transforms.arrayToSetMembership", {
gradeNames: ["fluid.standardTransformFunction", "fluid.lens"],
invertConfiguration: "fluid.transforms.arrayToSetMembership.invert"
});
fluid.transforms.arrayToSetMembership = function (value, transformSpec, transformer) {
var output = {};
var options = transformSpec.options;
if (!value || !fluid.isArrayable(value)) {
fluid.fail("arrayToSetMembership didn't find array at inputPath nor passed as value.", transformSpec);
}
if (!options) {
fluid.fail("arrayToSetMembership requires an options block set");
}
if (transformSpec.presentValue === undefined) {
transformSpec.presentValue = true;
}
if (transformSpec.missingValue === undefined) {
transformSpec.missingValue = false;
}
fluid.each(options, function (outPath, key) {
// write to output object the value <presentValue> or <missingValue> depending on whether key is found in user input
var outVal = (value.indexOf(key) !== -1) ? transformSpec.presentValue : transformSpec.missingValue;
fluid.set(output, outPath, outVal, transformer.resolverSetConfig);
});
return output;
};
/*
* NON-API function; Copies the entire transformSpec with the following modifications:
* * A new type is set (from argument)
* * each [key]=value entry in the options is swapped to be: [value]=key
*/
fluid.transforms.arrayToSetMembership.invertWithType = function (transformSpec, transformer, newType) {
transformSpec.type = newType;
var newOptions = {};
fluid.each(transformSpec.options, function (path, oldKey) {
newOptions[path] = oldKey;
});
transformSpec.options = newOptions;
return transformSpec;
};
fluid.transforms.arrayToSetMembership.invert = function (transformSpec, transformer) {
return fluid.transforms.arrayToSetMembership.invertWithType(transformSpec, transformer,
"fluid.transforms.setMembershipToArray");
};
fluid.defaults("fluid.transforms.setMembershipToArray", {
gradeNames: ["fluid.standardTransformFunction", "fluid.lens"],
invertConfiguration: "fluid.transforms.setMembershipToArray.invert"
});
fluid.transforms.setMembershipToArray = function (input, transformSpec, transformer) {
var options = transformSpec.options;
if (!options) {
fluid.fail("setMembershipToArray requires an options block specified");
}
if (transformSpec.presentValue === undefined) {
transformSpec.presentValue = true;
}
if (transformSpec.missingValue === undefined) {
transformSpec.missingValue = false;
}
var outputArr = [];
fluid.each(options, function (outputVal, key) {
var value = fluid.get(input, key, transformer.resolverGetConfig);
if (value === transformSpec.presentValue) {
outputArr.push(outputVal);
}
});
return outputArr;
};
fluid.transforms.setMembershipToArray.invert = function (transformSpec, transformer) {
return fluid.transforms.arrayToSetMembership.invertWithType(transformSpec, transformer,
"fluid.transforms.arrayToSetMembership");
};
/* -------- deindexIntoArrayByKey and indexArrayByKey -------------------- */
/*
* Transforms the given array to an object.
* Uses the transformSpec.options.key values from each object within the array as new keys.
*
* For example, with transformSpec.key = "name" and an input object like this:
*
* {
* b: [
* { name: b1, v: v1 },
* { name: b2, v: v2 }
* ]
* }
*
* The output will be:
* {
* b: {
* b1: {
* v: v1
* }
* },
* {
* b2: {
* v: v2
* }
* }
* }
*/
fluid.model.transform.applyPaths = function (operation, pathOp, paths) {
for (var i = 0; i < paths.length; ++i) {
if (operation === "push") {
pathOp.push(paths[i]);
} else {
pathOp.pop();
}
}
};
fluid.model.transform.expandInnerValues = function (inputPath, outputPath, transformer, innerValues) {
var inputPrefixOp = transformer.inputPrefixOp;
var outputPrefixOp = transformer.outputPrefixOp;
var apply = fluid.model.transform.applyPaths;
apply("push", inputPrefixOp, inputPath);
apply("push", outputPrefixOp, outputPath);
var expanded = {};
fluid.each(innerValues, function (innerValue) {
var expandedInner = transformer.expand(innerValue);
if (!fluid.isPrimitive(expandedInner)) {
$.extend(true, expanded, expandedInner);
} else {
expanded = expandedInner;
}
});
apply("pop", outputPrefixOp, outputPath);
apply("pop", inputPrefixOp, inputPath);
return expanded;
};
fluid.defaults("fluid.transforms.indexArrayByKey", {
gradeNames: ["fluid.standardTransformFunction", "fluid.lens" ],
invertConfiguration: "fluid.transforms.indexArrayByKey.invert"
});
/* Transforms an array of objects into an object of objects, by indexing using the option "key" which must be supplied within the transform specification.
* The key of each element will be taken from the value held in each each original object's member derived from the option value in "key" - this member should
* exist in each array element. The member with name agreeing with "key" and its value will be removed from each original object before inserting into the returned
* object.
* For example,
* <code>fluid.transforms.indexArrayByKey([{k: "e1", b: 1, c: 2}, {k: "e2", b: 2: c: 3}], {key: "k"})</code> will output the object
* <code>{e1: {b: 1, c: 2}, e2: {b: 2: c, 3}</code>
* Note: This transform frequently arises in the context of data which arose in XML form, which often represents "morally indexed" data in repeating array-like
* constructs where the indexing key is held, for example, in an attribute.
*/
fluid.transforms.indexArrayByKey = function (arr, transformSpec, transformer) {
if (transformSpec.key === undefined) {
fluid.fail("indexArrayByKey requires a 'key' option.", transformSpec);
}
if (!fluid.isArrayable(arr)) {
fluid.fail("indexArrayByKey didn't find array at inputPath.", transformSpec);
}
var newHash = {};
var pivot = transformSpec.key;
fluid.each(arr, function (v, k) {
// check that we have a pivot entry in the object and it's a valid type:
var newKey = v[pivot];
var keyType = typeof(newKey);
if (keyType !== "string" && keyType !== "boolean" && keyType !== "number") {
fluid.fail("indexArrayByKey encountered untransformable array due to missing or invalid key", v);
}
// use the value of the key element as key and use the remaining content as value
var content = fluid.copy(v);
delete content[pivot];
// fix sub Arrays if needed:
if (transformSpec.innerValue) {
content = fluid.model.transform.expandInnerValues([transformer.inputPrefix, transformSpec.inputPath, k.toString()],
[transformSpec.outputPath, newKey], transformer, transformSpec.innerValue);
}
newHash[newKey] = content;
});
return newHash;
};
fluid.transforms.indexArrayByKey.invert = function (transformSpec) {
transformSpec.type = "fluid.transforms.deindexIntoArrayByKey";
// invert transforms from innerValue as well:
// TODO: The Model Transformations framework should be capable of this, but right now the
// issue is that we use a "private contract" to operate the "innerValue" slot. We need to
// spend time thinking of how this should be formalised
if (transformSpec.innerValue) {
var innerValue = transformSpec.innerValue;
for (var i = 0; i < innerValue.length; ++i) {
var inverted = fluid.model.transform.invertConfiguration(innerValue[i]);
if (inverted === fluid.model.transform.uninvertibleTransform) {
return inverted;
} else {
innerValue[i] = inverted;
}
}
}
return transformSpec;
};
fluid.defaults("fluid.transforms.deindexIntoArrayByKey", {
gradeNames: [ "fluid.standardTransformFunction", "fluid.lens" ],
invertConfiguration: "fluid.transforms.deindexIntoArrayByKey.invert"
});
/*
* Transforms an object of objects into an array of objects, by deindexing by the option "key" which must be supplied within the transform specification.
* The key of each object will become split out into a fresh value in each array element which will be given the key held in the transformSpec option "key".
* For example:
* <code>fluid.transforms.deindexIntoArrayByKey({e1: {b: 1, c: 2}, e2: {b: 2: c, 3}, {key: "k"})</code> will output the array
* <code>[{k: "e1", b: 1, c: 2}, {k: "e2", b: 2: c: 3}]</code>
*
* This performs the inverse transform of fluid.transforms.indexArrayByKey.
*/
fluid.transforms.deindexIntoArrayByKey = function (hash, transformSpec, transformer) {
if (transformSpec.key === undefined) {
fluid.fail("deindexIntoArrayByKey requires a \"key\" option.", transformSpec);
}
var newArray = [];
var pivot = transformSpec.key;
fluid.each(hash, function (v, k) {
var content = {};
content[pivot] = k;
if (transformSpec.innerValue) {
v = fluid.model.transform.expandInnerValues([transformSpec.inputPath, k], [transformSpec.outputPath, newArray.length.toString()],
transformer, transformSpec.innerValue);
}
$.extend(true, content, v);
newArray.push(content);
});
return newArray;
};
fluid.transforms.deindexIntoArrayByKey.invert = function (transformSpec) {
transformSpec.type = "fluid.transforms.indexArrayByKey";
// invert transforms from innerValue as well:
// TODO: The Model Transformations framework should be capable of this, but right now the
// issue is that we use a "private contract" to operate the "innerValue" slot. We need to
// spend time thinking of how this should be formalised
if (transformSpec.innerValue) {
var innerValue = transformSpec.innerValue;
for (var i = 0; i < innerValue.length; ++i) {
innerValue[i] = fluid.model.transform.invertConfiguration(innerValue[i]);
}
}
return transformSpec;
};
fluid.defaults("fluid.transforms.limitRange", {
gradeNames: ["fluid.standardTransformFunction", "fluid.lens"],
invertConfiguration: "fluid.transforms.invertToIdentity"
});
fluid.transforms.limitRange = function (value, transformSpec) {
var min = transformSpec.min;
if (min !== undefined) {
var excludeMin = transformSpec.excludeMin || 0;
min += excludeMin;
if (value < min) {
value = min;
}
}
var max = transformSpec.max;
if (max !== undefined) {
var excludeMax = transformSpec.excludeMax || 0;
max -= excludeMax;
if (value > max) {
value = max;
}
}
return value;
};
fluid.defaults("fluid.transforms.indexOf", {
gradeNames: ["fluid.standardTransformFunction", "fluid.lens"],
invertConfiguration: "fluid.transforms.indexOf.invert"
});
fluid.transforms.indexOf = function (value, transformSpec) {
// We do not allow a positive number as 'notFound' value, as it threatens invertibility
if (typeof (transformSpec.notFound) === "number" && transformSpec.notFound >= 0) {
fluid.fail("A positive number is not allowed as 'notFound' value for indexOf");
}
var offset = fluid.transforms.parseIndexationOffset(transformSpec.offset, "indexOf");
var array = fluid.makeArray(transformSpec.array);
var originalIndex = array.indexOf(value);
return originalIndex === -1 && transformSpec.notFound ? transformSpec.notFound : originalIndex + offset;
};
fluid.transforms.indexOf.invert = function (transformSpec, transformer) {
var togo = fluid.transforms.invertArrayIndexation(transformSpec, transformer);
togo.type = "fluid.transforms.dereference";
return togo;
};
fluid.defaults("fluid.transforms.dereference", {
gradeNames: ["fluid.standardTransformFunction", "fluid.lens"],
invertConfiguration: "fluid.transforms.dereference.invert"
});
fluid.transforms.dereference = function (value, transformSpec) {
if (typeof (value) !== "number") {
return undefined;
}
var offset = fluid.transforms.parseIndexationOffset(transformSpec.offset, "dereference");
var array = fluid.makeArray(transformSpec.array);
var index = value + offset;
return array[index];
};
fluid.transforms.dereference.invert = function (transformSpec, transformer) {
var togo = fluid.transforms.invertArrayIndexation(transformSpec, transformer);
togo.type = "fluid.transforms.indexOf";
return togo;
};
fluid.transforms.parseIndexationOffset = function (offset, transformName) {
var parsedOffset = 0;
if (offset !== undefined) {
parsedOffset = fluid.parseInteger(offset);
if (isNaN(parsedOffset)) {
fluid.fail(transformName + " requires the value of \"offset\" to be an integer or a string that can be converted to an integer. " + offset + " is invalid.");
}
}
return parsedOffset;
};
fluid.transforms.invertArrayIndexation = function (transformSpec) {
if (!isNaN(Number(transformSpec.offset))) {
transformSpec.offset = Number(transformSpec.offset) * (-1);
}
return transformSpec;
};
fluid.defaults("fluid.transforms.stringTemplate", {
gradeNames: "fluid.standardOutputTransformFunction"
});
fluid.transforms.stringTemplate = function (transformSpec) {
return fluid.stringTemplate(transformSpec.template, transformSpec.terms);
};
fluid.defaults("fluid.transforms.free", {
gradeNames: "fluid.transformFunction"
});
fluid.transforms.free = function (transformSpec) {
var args = fluid.makeArray(transformSpec.args);
return fluid.invokeGlobalFunction(transformSpec.func, args);
};
fluid.defaults("fluid.transforms.quantize", {
gradeNames: "fluid.standardTransformFunction",
collectInputPaths: "fluid.transforms.quantize.collect"
});
/*
* Quantize function maps a continuous range into discrete values. Given an input, it will
* be matched into a discrete bucket and the corresponding output will be done.
*/
fluid.transforms.quantize = function (value, transformSpec, transformer) {
if (!transformSpec.ranges || !transformSpec.ranges.length) {
fluid.fail("fluid.transforms.quantize should have a key called ranges containing an array defining ranges to quantize");
}
// TODO: error checking that upper bounds are all numbers and increasing
for (var i = 0; i < transformSpec.ranges.length; i++) {
var rangeSpec = transformSpec.ranges[i];
if (value <= rangeSpec.upperBound || rangeSpec.upperBound === undefined && value >= Number.NEGATIVE_INFINITY) {
return fluid.isPrimitive(rangeSpec.output) ? rangeSpec.output : transformer.expand(rangeSpec.output);
}
}
};
fluid.transforms.quantize.collect = function (transformSpec, transformer) {
transformSpec.ranges.forEach(function (rangeSpec) {
if (!fluid.isPrimitive(rangeSpec.output)) {
transformer.expand(rangeSpec.output);
}
});
};
/**
* inRange transformer checks whether a value is within a given range and returns `true` if it is,
* and `false` if it's not.
*
* The range is defined by the two inputs: "min" and "max" (both inclusive). If one of these inputs
* is not present it is treated as -Infinity and +Infinity, respectively - In other words, if no
* `min` value is defined, any value below or equal to the given `max` value will result in `true`.
*/
fluid.defaults("fluid.transforms.inRange", {
gradeNames: "fluid.standardTransformFunction"
});
fluid.transforms.inRange = function (value, transformSpec) {
return (transformSpec.min === undefined || transformSpec.min <= value) &&
(transformSpec.max === undefined || transformSpec.max >= value) ? true : false;
};
/**
*
* Convert a string to a Boolean, for example, when working with HTML form element values.
*
* The following are all false: undefined, null, "", "0", "false", false, 0
*
* Everything else is true.
*
* @param {String} value - The value to be interpreted.
* @return {Boolean} The interpreted value.
*/
fluid.transforms.stringToBoolean = function (value) {
if (value) {
return !(value === "0" || value === "false");
}
else {
return false;
}
};
fluid.transforms.stringToBoolean.invert = function (transformSpec) {
transformSpec.type = "fluid.transforms.booleanToString";
return transformSpec;
};
fluid.defaults("fluid.transforms.stringToBoolean", {
gradeNames: ["fluid.standardTransformFunction", "fluid.lens"],
invertConfiguration: "fluid.transforms.stringToBoolean.invert"
});
/**
*
* Convert any value into a stringified boolean, i. e. either "true" or "false". Anything that evaluates to
* true (1, true, "non empty string", {}, et. cetera) returns "true". Anything else (0, false, null, et. cetera)
* returns "false".
*
* @param {Any} value - The value to be converted to a stringified Boolean.
* @return {String} - A stringified boolean representation of the value.
*/
fluid.transforms.booleanToString = function (value) {
return value ? "true" : "false";
};
fluid.transforms.booleanToString.invert = function (transformSpec) {
transformSpec.type = "fluid.transforms.stringToBoolean";
return transformSpec;
};
fluid.defaults("fluid.transforms.booleanToString", {
gradeNames: ["fluid.standardTransformFunction", "fluid.lens"],
invertConfiguration: "fluid.transforms.booleanToString.invert"
});
/**
*
* Transform stringified JSON to an object using `JSON.parse`. Returns `undefined` if the JSON string is invalid.
*
* @param {String} value - The stringified JSON to be converted to an object.
* @return {Any} - The parsed value of the string, or `undefined` if it can't be parsed.
*/
fluid.transforms.JSONstringToObject = function (value) {
try {
return JSON.parse(value);
}
catch (e) {
return undefined;
}
};
fluid.transforms.JSONstringToObject.invert = function (transformSpec) {
transformSpec.type = "fluid.transforms.objectToJSONString";
return transformSpec;
};
fluid.defaults("fluid.transforms.JSONstringToObject", {
gradeNames: ["fluid.standardTransformFunction", "fluid.lens"],
invertConfiguration: "fluid.transforms.JSONstringToObject.invert"
});
/**
*
* Transform an object to a string using `JSON.stringify`. You can pass the `space` option to be used
* as part of your transform, as in:
*
* ```
* "": {
* transform: {
* funcName: "fluid.transforms.objectToJSONString",
* inputPath: "",
* space: 2
* }
* }
* ```
*
* The default value for `space` is 0, which disables spacing and line breaks.
*
* @param {Object} value - An object to be converted to stringified JSON.
* @param {Object} transformSpec - An object describing the transformation spec, see above.
* @return {String} - A string representation of the object.
*
*/
fluid.transforms.objectToJSONString = function (value, transformSpec) {
var space = transformSpec.space || 0;
return JSON.stringify(value, null, space);
};
fluid.transforms.objectToJSONString.invert = function (transformSpec) {
transformSpec.type = "fluid.transforms.JSONstringToObject";
return transformSpec;
};
fluid.defaults("fluid.transforms.objectToJSONString", {
gradeNames: ["fluid.standardTransformFunction", "fluid.lens"],
invertConfiguration: "fluid.transforms.objectToJSONString.invert"
});
/**
*
* Transform a string to a date using the Date constructor. Accepts (among other things) the date and dateTime
* values returned by HTML5 date and dateTime inputs.
*
* A string that cannot be parsed will be treated as `undefined`.
*
* Note: This function allows you to create Date objects from an ISO 8601 string such as `2017-01-23T08:51:25.891Z`.
* It is intended to provide a consistent mechanism for recreating Date objects stored as strings. Although the
* framework currently works as expected with Date objects stored in the model, this is very likely to change. If
* you are working with Date objects in your model, your best option for ensuring your code continues to work in the
* future is to handle serialisation and deserialisation yourself, for example, by using this transform and one of
* its inverse transforms, `fluid.transforms.dateToString` or `fluid.transforms.dateTimeToString`. See the Infusion
* documentation for details about supported model values:
*
* http://docs.fluidproject.org/infusion/development/FrameworkConcepts.html#model-objects
*
* @param {String} value - The String value to be transformed into a Date object.
* @return {Date} - A date object, or `undefined`.
*
*/
fluid.transforms.stringToDate = function (value) {
var date = new Date(value);
return isNaN(date.getTime()) ? undefined : date;
};
fluid.transforms.stringToDate.invert = function (transformSpec) {
transformSpec.type = "fluid.transforms.dateToString";
return transformSpec;
};
fluid.defaults("fluid.transforms.stringToDate", {
gradeNames: ["fluid.standardTransformFunction", "fluid.lens"],
invertConfiguration: "fluid.transforms.stringToDate.invert"
});
/**
*
* Transform a Date object into a date string using its toISOString method. Strips the "time" portion away to
* produce date strings that are suitable for use with both HTML5 "date" inputs and JSON Schema "date" format
* string validation, for example: `2016-11-23`
*
* If you wish to preserve the time, use `fluid.transforms.dateTimeToString` instead.
*
* A non-date object will be treated as `undefined`.
*
* Note: This function allows you to seralise Date objects (not including time information) as ISO 8601 strings such
* as `2017-01-23`. It is intended to provide a consistent mechanism for storing Date objects in a model. Although
* the framework currently works as expected with Date objects stored in the model, this is very likely to change.
* If you are working with Date objects in your model, your best option for ensuring your code continues to work in
* the future is to handle serialisation and deserialisation yourself, for example, by using this transform and its
* inverse, `fluid.transforms.stringToDate`. See the Infusion documentation for details about supported model
* values:
*
* http://docs.fluidproject.org/infusion/development/FrameworkConcepts.html#model-objects
*
* @param {Date} value - The Date object to be transformed into an ISO 8601 string.
* @return {String} - A {String} value representing the date, or `undefined` if the date is invalid.
*
*/
fluid.transforms.dateToString = function (value) {
if (value instanceof Date) {
var isoString = value.toISOString(); // A string like "2016-09-26T08:05:57.462Z"
var dateString = isoString.substring(0, isoString.indexOf("T")); // A string like "2016-09-26"
return dateString;
}
else {
return undefined;
}
};
fluid.transforms.dateToString.invert = function (transformSpec) {
transformSpec.type = "fluid.transforms.stringToDate";
return transformSpec;
};
fluid.defaults("fluid.transforms.dateToString", {
gradeNames: ["fluid.standardTransformFunction", "fluid.lens"],
invertConfiguration: "fluid.transforms.dateToString.invert"
});
/**
*
* Transform a Date object into a date/time string using its toISOString method. Results in date strings that are
* suitable for use with both HTML5 "dateTime" inputs and JSON Schema "date-time" format string validation, for\
* example: `2016-11-23T13:05:24.079Z`
*
* A non-date object will be treated as `undefined`.
*
* Note: This function allows you to seralise Date objects (including time information) as ISO 8601 strings such as
* `2017-01-23T08:51:25.891Z`. It is intended to provide a consistent mechanism for storing Date objects in a model.
* Although the framework currently works as expected with Date objects stored in the model, this is very likely to
* change. If you are working with Date objects in your model, your best option for ensuring your code continues to
* work in the future is to handle serialisation and deserialisation yourself, for example, by using this function
* and its inverse, `fluid.transforms.stringToDate`. See the Infusion documentation for details about supported
* model values:
*
* http://docs.fluidproject.org/infusion/development/FrameworkConcepts.html#model-objects
*
* @param {Date} value - The Date object to be transformed into an ISO 8601 string.
* @return {String} - A {String} value representing the date and time, or `undefined` if the date/time are invalid.
*
*/
fluid.transforms.dateTimeToString = function (value) {
return value instanceof Date ? value.toISOString() : undefined;
};
fluid.defaults("fluid.transforms.dateTimeToString", {
gradeNames: ["fluid.standardTransformFunction", "fluid.lens"],
invertConfiguration: "fluid.transforms.dateToString.invert"
});
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
var fluid = fluid || fluid_3_0_0;
(function ($, fluid) {
"use strict";
// $().fluid("selectable", args)
// $().fluid("selectable".that()
// $().fluid("pager.pagerBar", args)
// $().fluid("reorderer", options)
/** Create a "bridge" from code written in the Fluid standard "that-ist" style,
* to the standard JQuery UI plugin architecture specified at http://docs.jquery.com/UI/Guidelines .
* Every Fluid component corresponding to the top-level standard signature (JQueryable, options)
* will automatically convert idiomatically to the JQuery UI standard via this adapter.
* Any return value which is a primitive or array type will become the return value
* of the "bridged" function - however, where this function returns a general hash
* (object) this is interpreted as forming part of the Fluid "return that" pattern,
* and the function will instead be bridged to "return this" as per JQuery standard,
* permitting chaining to occur. However, as a courtesy, the particular "this" returned
* will be augmented with a function that() which will allow the original return
* value to be retrieved if desired.
* @param {String} name - The name under which the "plugin space" is to be injected into JQuery
* @param {Object} peer - The root of the namespace corresponding to the peer object.
* @return {Function} - A JQuery UI plugin function.
*/
fluid.thatistBridge = function (name, peer) {
var togo = function (funcname) {
var segs = funcname.split(".");
var move = peer;
for (var i = 0; i < segs.length; ++i) {
move = move[segs[i]];
}
var args = [this];
if (arguments.length === 2) {
args = args.concat($.makeArray(arguments[1]));
}
var ret = move.apply(null, args);
this.that = function () {
return ret;
};
var type = typeof(ret);
return !ret || type === "string" || type === "number" || type === "boolean" ||
(ret && ret.length !== undefined) ? ret : this;
};
$.fn[name] = togo;
return togo;
};
fluid.thatistBridge("fluid", fluid);
fluid.thatistBridge("fluid_3_0_0", fluid_3_0_0);
/*************************************************************************
* Tabindex normalization - compensate for browser differences in naming
* and function of "tabindex" attribute and tabbing order.
*/
// -- Private functions --
var normalizeTabindexName = function () {
return $.browser.msie ? "tabIndex" : "tabindex";
};
var canHaveDefaultTabindex = function (elements) {
if (elements.length <= 0) {
return false;
}
return $(elements[0]).is("a, input, button, select, area, textarea, object");
};
var getValue = function (elements) {
if (elements.length <= 0) {
return undefined;
}
if (!fluid.tabindex.hasAttr(elements)) {
return canHaveDefaultTabindex(elements) ? Number(0) : undefined;
}
// Get the attribute and return it as a number value.
var value = elements.attr(normalizeTabindexName());
return Number(value);
};
var setValue = function (elements, toIndex) {
return elements.each(function (i, item) {
$(item).attr(normalizeTabindexName(), toIndex);
});
};
// -- Public API --
/**
* Gets the value of the tabindex attribute for the first item, or sets the tabindex value of all elements
* if toIndex is specified.
*
* @param {jQuery} target - The target element.
* @param {String|Number} toIndex - (Optional) the tabIndex value to set on the target.
* @return {Any} - The result of the underlying "get" or "set" operation.
*/
fluid.tabindex = function (target, toIndex) {
target = $(target);
if (toIndex !== null && toIndex !== undefined) {
return setValue(target, toIndex);
} else {
return getValue(target);
}
};
/*
* Removes the tabindex attribute altogether from each element.
*/
fluid.tabindex.remove = function (target) {
target = $(target);
return target.each(function (i, item) {
$(item).removeAttr(normalizeTabindexName());
});
};
/*
* Determines if an element actually has a tabindex attribute present.
*/
fluid.tabindex.hasAttr = function (target) {
target = $(target);
if (target.length <= 0) {
return false;
}
var togo = target.map(
function () {
var attributeNode = this.getAttributeNode(normalizeTabindexName());
return attributeNode ? attributeNode.specified : false;
}
);
return togo.length === 1 ? togo[0] : togo;
};
/*
* Determines if an element either has a tabindex attribute or is naturally tab-focussable.
*/
fluid.tabindex.has = function (target) {
target = $(target);
return fluid.tabindex.hasAttr(target) || canHaveDefaultTabindex(target);
};
// Keyboard navigation
// Public, static constants needed by the rest of the library.
fluid.a11y = $.a11y || {};
fluid.a11y.orientation = {
HORIZONTAL: 0,
VERTICAL: 1,
BOTH: 2
};
var UP_DOWN_KEYMAP = {
next: $.ui.keyCode.DOWN,
previous: $.ui.keyCode.UP
};
var LEFT_RIGHT_KEYMAP = {
next: $.ui.keyCode.RIGHT,
previous: $.ui.keyCode.LEFT
};
// Private functions.
var unwrap = function (element) {
return element.jquery ? element[0] : element; // Unwrap the element if it's a jQuery.
};
var makeElementsTabFocussable = function (elements) {
// If each element doesn't have a tabindex, or has one set to a negative value, set it to 0.
elements.each(function (idx, item) {
item = $(item);
if (!item.fluid("tabindex.has") || item.fluid("tabindex") < 0) {
item.fluid("tabindex", 0);
}
});
};
// Public API.
/*
* Makes all matched elements available in the tab order by setting their tabindices to "0".
*/
fluid.tabbable = function (target) {
target = $(target);
makeElementsTabFocussable(target);
};
/***********************************************************************
* Selectable functionality - geometrising a set of nodes such that they
* can be navigated (by setting focus) using a set of directional keys
*/
var CONTEXT_KEY = "selectionContext";
var NO_SELECTION = -32768;
var cleanUpWhenLeavingContainer = function (selectionContext) {
if (selectionContext.activeItemIndex !== NO_SELECTION) {
if (selectionContext.options.onLeaveContainer) {
selectionContext.options.onLeaveContainer(
selectionContext.selectables[selectionContext.activeItemIndex]
);
} else if (selectionContext.options.onUnselect) {
selectionContext.options.onUnselect(
selectionContext.selectables[selectionContext.activeItemIndex]
);
}
}
if (!selectionContext.options.rememberSelectionState) {
selectionContext.activeItemIndex = NO_SELECTION;
}
};
/*
* Does the work of selecting an element and delegating to the client handler.
*/
var drawSelection = function (elementToSelect, handler) {
if (handler) {
handler(elementToSelect);
}
};
/*
* Does does the work of unselecting an element and delegating to the client handler.
*/
var eraseSelection = function (selectedElement, handler) {
if (handler && selectedElement) {
handler(selectedElement);
}
};
var unselectElement = function (selectedElement, selectionContext) {
eraseSelection(selectedElement, selectionContext.options.onUnselect);
};
var selectElement = function (elementToSelect, selectionContext) {
// It's possible that we're being called programmatically, in which case we should clear any previous selection.
unselectElement(selectionContext.selectedElement(), selectionContext);
elementToSelect = unwrap(elementToSelect);
var newIndex = selectionContext.selectables.index(elementToSelect);
// Next check if the element is a known selectable. If not, do nothing.
if (newIndex === -1) {
return;
}
// Select the new element.
selectionContext.activeItemIndex = newIndex;
drawSelection(elementToSelect, selectionContext.options.onSelect);
};
var selectableFocusHandler = function (selectionContext) {
return function (evt) {
// FLUID-3590: newer browsers (FF 3.6, Webkit 4) have a form of "bug" in that they will go bananas
// on attempting to move focus off an element which has tabindex dynamically set to -1.
$(evt.target).fluid("tabindex", 0);
selectElement(evt.target, selectionContext);
// Force focus not to bubble on some browsers.
return evt.stopPropagation();
};
};
var selectableBlurHandler = function (selectionContext) {
return function (evt) {
$(evt.target).fluid("tabindex", selectionContext.options.selectablesTabindex);
unselectElement(evt.target, selectionContext);
// Force blur not to bubble on some browsers.
return evt.stopPropagation();
};
};
var reifyIndex = function (sc_that) {
var elements = sc_that.selectables;
if (sc_that.activeItemIndex >= elements.length) {
sc_that.activeItemIndex = (sc_that.options.noWrap ? elements.length - 1 : 0);
}
if (sc_that.activeItemIndex < 0 && sc_that.activeItemIndex !== NO_SELECTION) {
sc_that.activeItemIndex = (sc_that.options.noWrap ? 0 : elements.length - 1);
}
if (sc_that.activeItemIndex >= 0) {
fluid.focus(elements[sc_that.activeItemIndex]);
}
};
var prepareShift = function (selectionContext) {
// FLUID-3590: FF 3.6 and Safari 4.x won't fire blur() when programmatically moving focus.
var selElm = selectionContext.selectedElement();
if (selElm) {
fluid.blur(selElm);
}
unselectElement(selectionContext.selectedElement(), selectionContext);
if (selectionContext.activeItemIndex === NO_SELECTION) {
selectionContext.activeItemIndex = -1;
}
};
var focusNextElement = function (selectionContext) {
prepareShift(selectionContext);
++selectionContext.activeItemIndex;
reifyIndex(selectionContext);
};
var focusPreviousElement = function (selectionContext) {
prepareShift(selectionContext);
--selectionContext.activeItemIndex;
reifyIndex(selectionContext);
};
var arrowKeyHandler = function (selectionContext, keyMap) {
return function (evt) {
if (evt.which === keyMap.next) {
focusNextElement(selectionContext);
evt.preventDefault();
} else if (evt.which === keyMap.previous) {
focusPreviousElement(selectionContext);
evt.preventDefault();
}
};
};
var getKeyMapForDirection = function (direction) {
// Determine the appropriate mapping for next and previous based on the specified direction.
var keyMap;
if (direction === fluid.a11y.orientation.HORIZONTAL) {
keyMap = LEFT_RIGHT_KEYMAP;
}
else if (direction === fluid.a11y.orientation.VERTICAL) {
// Assume vertical in any other case.
keyMap = UP_DOWN_KEYMAP;
}
return keyMap;
};
var tabKeyHandler = function (selectionContext) {
return function (evt) {
if (evt.which !== $.ui.keyCode.TAB) {
return;
}
cleanUpWhenLeavingContainer(selectionContext);
// Catch Shift-Tab and note that focus is on its way out of the container.
if (evt.shiftKey) {
selectionContext.focusIsLeavingContainer = true;
}
};
};
var containerFocusHandler = function (selectionContext) {
return function (evt) {
var shouldOrig = selectionContext.options.autoSelectFirstItem;
var shouldSelect = typeof(shouldOrig) === "function" ? shouldOrig() : shouldOrig;
// Override the autoselection if we're on the way out of the container.
if (selectionContext.focusIsLeavingContainer) {
shouldSelect = false;
}
// This target check works around the fact that sometimes focus bubbles, even though it shouldn't.
if (shouldSelect && evt.target === selectionContext.container.get(0)) {
if (selectionContext.activeItemIndex === NO_SELECTION) {
selectionContext.activeItemIndex = 0;
}
fluid.focus(selectionContext.selectables[selectionContext.activeItemIndex]);
}
// Force focus not to bubble on some browsers.
return evt.stopPropagation();
};
};
var containerBlurHandler = function (selectionContext) {
return function (evt) {
selectionContext.focusIsLeavingContainer = false;
// Force blur not to bubble on some browsers.
return evt.stopPropagation();
};
};
var makeElementsSelectable = function (container, defaults, userOptions) {
var options = $.extend(true, {}, defaults, userOptions);
var keyMap = getKeyMapForDirection(options.direction);
var selectableElements = options.selectableElements ? options.selectableElements :
container.find(options.selectableSelector);
// Context stores the currently active item(undefined to start) and list of selectables.
var that = {
container: container,
activeItemIndex: NO_SELECTION,
selectables: selectableElements,
focusIsLeavingContainer: false,
options: options
};
that.selectablesUpdated = function (focusedItem) {
// Remove selectables from the tab order and add focus/blur handlers
if (typeof(that.options.selectablesTabindex) === "number") {
that.selectables.fluid("tabindex", that.options.selectablesTabindex);
}
that.selectables.off("focus." + CONTEXT_KEY);
that.selectables.off("blur." + CONTEXT_KEY);
that.selectables.on("focus." + CONTEXT_KEY, selectableFocusHandler(that));
that.selectables.on("blur." + CONTEXT_KEY, selectableBlurHandler(that));
if (keyMap && that.options.noBubbleListeners) {
that.selectables.off("keydown." + CONTEXT_KEY);
that.selectables.on("keydown." + CONTEXT_KEY, arrowKeyHandler(that, keyMap));
}
if (focusedItem) {
selectElement(focusedItem, that);
}
else {
reifyIndex(that);
}
};
that.refresh = function () {
if (!that.options.selectableSelector) {
fluid.fail("Cannot refresh selectable context which was not initialised by a selector");
}
that.selectables = container.find(options.selectableSelector);
that.selectablesUpdated();
};
that.selectedElement = function () {
return that.activeItemIndex < 0 ? null : that.selectables[that.activeItemIndex];
};
// Add various handlers to the container.
if (keyMap && !that.options.noBubbleListeners) {
container.keydown(arrowKeyHandler(that, keyMap));
}
container.keydown(tabKeyHandler(that));
container.focus(containerFocusHandler(that));
container.blur(containerBlurHandler(that));
that.selectablesUpdated();
return that;
};
/*
* Makes all matched elements selectable with the arrow keys.
* Supply your own handlers object with onSelect: and onUnselect: properties for custom behaviour.
* Options provide configurability, including direction: and autoSelectFirstItem:
* Currently supported directions are jQuery.a11y.directions.HORIZONTAL and VERTICAL.
*/
fluid.selectable = function (target, options) {
target = $(target);
var that = makeElementsSelectable(target, fluid.selectable.defaults, options);
fluid.setScopedData(target, CONTEXT_KEY, that);
return that;
};
/*
* Selects the specified element.
*/
fluid.selectable.select = function (target, toSelect) {
fluid.focus(toSelect);
};
/*
* Selects the next matched element.
*/
fluid.selectable.selectNext = function (target) {
target = $(target);
focusNextElement(fluid.getScopedData(target, CONTEXT_KEY));
};
/*
* Selects the previous matched element.
*/
fluid.selectable.selectPrevious = function (target) {
target = $(target);
focusPreviousElement(fluid.getScopedData(target, CONTEXT_KEY));
};
/*
* Returns the currently selected item wrapped as a jQuery object.
*/
fluid.selectable.currentSelection = function (target) {
target = $(target);
var that = fluid.getScopedData(target, CONTEXT_KEY);
return $(that.selectedElement());
};
fluid.selectable.defaults = {
direction: fluid.a11y.orientation.VERTICAL,
selectablesTabindex: -1,
autoSelectFirstItem: true,
rememberSelectionState: true,
selectableSelector: ".selectable",
selectableElements: null,
onSelect: null,
onUnselect: null,
onLeaveContainer: null,
noWrap: false
};
/********************************************************************
* Activation functionality - declaratively associating actions with
* a set of keyboard bindings.
*/
var checkForModifier = function (binding, evt) {
// If no modifier was specified, just return true.
if (!binding.modifier) {
return true;
}
var modifierKey = binding.modifier;
var isCtrlKeyPresent = modifierKey && evt.ctrlKey;
var isAltKeyPresent = modifierKey && evt.altKey;
var isShiftKeyPresent = modifierKey && evt.shiftKey;
return isCtrlKeyPresent || isAltKeyPresent || isShiftKeyPresent;
};
/* Constructs a raw "keydown"-facing handler, given a binding entry. This
* checks whether the key event genuinely triggers the event and forwards it
* to any "activateHandler" registered in the binding.
*/
var makeActivationHandler = function (binding) {
return function (evt) {
var target = evt.target;
if (!fluid.enabled(target)) {
return;
}
// The following 'if' clause works in the real world, but there's a bug in the jQuery simulation
// that causes keyboard simulation to fail in Safari, causing our tests to fail:
// http://ui.jquery.com/bugs/ticket/3229
// The replacement 'if' clause works around this bug.
// When this issue is resolved, we should revert to the original clause.
// if (evt.which === binding.key && binding.activateHandler && checkForModifier(binding, evt)) {
var code = evt.which ? evt.which : evt.keyCode;
if (code === binding.key && binding.activateHandler && checkForModifier(binding, evt)) {
var event = $.Event("fluid-activate");
$(target).trigger(event, [binding.activateHandler]);
if (event.isDefaultPrevented()) {
evt.preventDefault();
}
}
};
};
var makeElementsActivatable = function (elements, onActivateHandler, defaultKeys, options) {
// Create bindings for each default key.
var bindings = [];
$(defaultKeys).each(function (index, key) {
bindings.push({
modifier: null,
key: key,
activateHandler: onActivateHandler
});
});
// Merge with any additional key bindings.
if (options && options.additionalBindings) {
bindings = bindings.concat(options.additionalBindings);
}
fluid.initEnablement(elements);
// Add listeners for each key binding.
for (var i = 0; i < bindings.length; ++i) {
var binding = bindings[i];
elements.keydown(makeActivationHandler(binding));
}
elements.on("fluid-activate", function (evt, handler) {
handler = handler || onActivateHandler;
return handler ? handler(evt) : null;
});
};
/*
* Makes all matched elements activatable with the Space and Enter keys.
* Provide your own handler function for custom behaviour.
* Options allow you to provide a list of additionalActivationKeys.
*/
fluid.activatable = function (target, fn, options) {
target = $(target);
makeElementsActivatable(target, fn, fluid.activatable.defaults.keys, options);
};
/*
* Activates the specified element.
*/
fluid.activate = function (target) {
$(target).trigger("fluid-activate");
};
// Public Defaults.
fluid.activatable.defaults = {
keys: [$.ui.keyCode.ENTER, $.ui.keyCode.SPACE]
};
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
/** This file contains functions which depend on the presence of a DOM document
* and which depend on the contents of Fluid.js **/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
fluid.defaults("fluid.viewComponent", {
gradeNames: ["fluid.modelComponent"],
initFunction: "fluid.initView",
argumentMap: {
container: 0,
options: 1
},
members: { // Used to allow early access to DOM binder via IoC, but to also avoid triggering evaluation of selectors
dom: "@expand:fluid.initDomBinder({that}, {that}.options.selectors)"
}
});
// unsupported, NON-API function
fluid.dumpSelector = function (selectable) {
return typeof (selectable) === "string" ? selectable :
selectable.selector ? selectable.selector : "";
};
// unsupported, NON-API function
// NOTE: this function represents a temporary strategy until we have more integrated IoC debugging.
// It preserves the 1.3 and previous framework behaviour for the 1.x releases, but provides a more informative
// diagnostic - in fact, it is perfectly acceptable for a component's creator to return no value and
// the failure is really in assumptions in fluid.initLittleComponent. Revisit this issue for 2.0
fluid.diagnoseFailedView = function (componentName, that, options, args) {
if (!that && fluid.hasGrade(options, "fluid.viewComponent")) {
var container = fluid.wrap(args[1]);
var message1 = "Instantiation of view component with type " + componentName + " failed, since ";
if (!container) {
fluid.fail(message1 + " container argument is empty");
}
else if (container.length === 0) {
fluid.fail(message1 + "selector \"", fluid.dumpSelector(args[1]), "\" did not match any markup in the document");
} else {
fluid.fail(message1 + " component creator function did not return a value");
}
}
};
fluid.checkTryCatchParameter = function () {
var location = window.location || { search: "", protocol: "file:" };
var GETparams = location.search.slice(1).split("&");
return fluid.find(GETparams, function (param) {
if (param.indexOf("notrycatch") === 0) {
return true;
}
}) === true;
};
fluid.notrycatch = fluid.checkTryCatchParameter();
/**
* Wraps an object in a jQuery if it isn't already one. This function is useful since
* it ensures to wrap a null or otherwise falsy argument to itself, rather than the
* often unhelpful jQuery default of returning the overall document node.
*
* @param {Object} obj - the object to wrap in a jQuery
* @param {jQuery} [userJQuery] - the jQuery object to use for the wrapping, optional - use the current jQuery if absent
* @return {jQuery} - The wrapped object.
*/
fluid.wrap = function (obj, userJQuery) {
userJQuery = userJQuery || $;
return ((!obj || obj.jquery) ? obj : userJQuery(obj));
};
/**
* If obj is a jQuery, this function will return the first DOM element within it. Otherwise, the object will be returned unchanged.
*
* @param {jQuery} obj - The jQuery instance to unwrap into a pure DOM element.
* @return {Object} - The unwrapped object.
*/
fluid.unwrap = function (obj) {
return obj && obj.jquery ? obj[0] : obj;
};
/**
* Fetches a single container element and returns it as a jQuery.
*
* @param {String|jQuery|element} containerSpec - an id string, a single-element jQuery, or a DOM element specifying a unique container
* @param {Boolean} fallible - <code>true</code> if an empty container is to be reported as a valid condition
* @param {jQuery} [userJQuery] - the jQuery object to use for the wrapping, optional - use the current jQuery if absent
* @return {jQuery} - A single-element jQuery container.
*/
fluid.container = function (containerSpec, fallible, userJQuery) {
var selector = containerSpec.selector || containerSpec;
if (userJQuery) {
containerSpec = fluid.unwrap(containerSpec);
}
var container = fluid.wrap(containerSpec, userJQuery);
if (fallible && (!container || container.length === 0)) {
return null;
}
if (!container || !container.jquery || container.length !== 1) {
if (typeof (containerSpec) !== "string") {
containerSpec = container.selector;
}
var count = container.length !== undefined ? container.length : 0;
fluid.fail((count > 1 ? "More than one (" + count + ") container elements were"
: "No container element was") + " found for selector " + containerSpec);
}
if (!fluid.isDOMNode(container[0])) {
fluid.fail("fluid.container was supplied a non-jQueryable element");
}
// To address FLUID-5966, manually adding back the selector and context properties that were removed from jQuery v3.0.
// ( see: https://jquery.com/upgrade-guide/3.0/#breaking-change-deprecated-context-and-selector-properties-removed )
// In most cases the "selector" property will already be restored through the DOM binder;
// however, when a selector or pure jQuery element is supplied directly as a component's container, we need to add them
// if it is possible to infer them. This feature is rarely used but is crucial for the prefs framework infrastructure
// in Panels.js fluid.prefs.subPanel.resetDomBinder
container.selector = selector;
container.context = container.context || containerSpec.ownerDocument || document;
return container;
};
/**
* Creates a new DOM Binder instance, used to locate elements in the DOM by name.
*
* @param {Object} container - the root element in which to locate named elements
* @param {Object} selectors - a collection of named jQuery selectors
* @return {Object} - The new DOM binder.
*/
fluid.createDomBinder = function (container, selectors) {
// don't put on a typename to avoid confusing primitive visitComponentChildren
var that = {
id: fluid.allocateGuid(),
cache: {}
};
var userJQuery = container.constructor;
function cacheKey(name, thisContainer) {
return fluid.allocateSimpleId(thisContainer) + "-" + name;
}
function record(name, thisContainer, result) {
that.cache[cacheKey(name, thisContainer)] = result;
}
that.locate = function (name, localContainer) {
var selector, thisContainer, togo;
selector = selectors[name];
if (selector === undefined) {
return undefined;
}
thisContainer = localContainer ? $(localContainer) : container;
if (!thisContainer) {
fluid.fail("DOM binder invoked for selector " + name + " without container");
}
if (selector === "") {
togo = thisContainer;
}
else if (!selector) {
togo = userJQuery();
}
else {
if (typeof (selector) === "function") {
togo = userJQuery(selector.call(null, fluid.unwrap(thisContainer)));
} else {
togo = userJQuery(selector, thisContainer);
}
}
if (!togo.selector) {
togo.selector = selector;
togo.context = thisContainer;
}
togo.selectorName = name;
record(name, thisContainer, togo);
return togo;
};
that.fastLocate = function (name, localContainer) {
var thisContainer = localContainer ? localContainer : container;
var key = cacheKey(name, thisContainer);
var togo = that.cache[key];
return togo ? togo : that.locate(name, localContainer);
};
that.clear = function () {
that.cache = {};
};
that.refresh = function (names, localContainer) {
var thisContainer = localContainer ? localContainer : container;
if (typeof names === "string") {
names = [names];
}
if (thisContainer.length === undefined) {
thisContainer = [thisContainer];
}
for (var i = 0; i < names.length; ++i) {
for (var j = 0; j < thisContainer.length; ++j) {
that.locate(names[i], thisContainer[j]);
}
}
};
that.resolvePathSegment = that.locate;
return that;
};
/* Expect that jQuery selector query has resulted in a non-empty set of
* results. If none are found, this function will fail with a diagnostic message,
* with the supplied message prepended.
*/
fluid.expectFilledSelector = function (result, message) {
if (result && result.length === 0 && result.jquery) {
fluid.fail(message + ": selector \"" + result.selector + "\" with name " + result.selectorName +
" returned no results in context " + fluid.dumpEl(result.context));
}
};
/**
* The central initialiation method called as the first act of every Fluid
* component. This function automatically merges user options with defaults,
* attaches a DOM Binder to the instance, and configures events.
*
* @param {String} componentName - The unique "name" of the component, which will be used
* to fetch the default options from store. By recommendation, this should be the global
* name of the component's creator function.
* @param {jQueryable} containerSpec - A specifier for the single root "container node" in the
* DOM which will house all the markup for this component.
* @param {Object} userOptions - The user configuration options for this component.
* @param {Object} localOptions - The local configuration options for this component. Unsupported, see comments for initLittleComponent.
* @return {Object|null} - The newly created component, or `null` id the container does not exist.
*/
fluid.initView = function (componentName, containerSpec, userOptions, localOptions) {
var container = fluid.container(containerSpec, true);
fluid.expectFilledSelector(container, "Error instantiating component with name \"" + componentName);
if (!container) {
return null;
}
// Need to ensure container is set early, without relying on an IoC mechanism - rethink this with asynchrony
var receiver = function (that) {
that.container = container;
};
var that = fluid.initLittleComponent(componentName, userOptions, localOptions || {gradeNames: ["fluid.viewComponent"]}, receiver);
if (!that.dom) {
fluid.initDomBinder(that);
}
// TODO: cannot afford a mutable container - put this into proper workflow
var userJQuery = that.options.jQuery; // Do it a second time to correct for jQuery injection
// if (userJQuery) {
// container = fluid.container(containerSpec, true, userJQuery);
// }
fluid.log("Constructing view component " + componentName + " with container " + container.constructor.expando +
(userJQuery ? " user jQuery " + userJQuery.expando : "") + " env: " + $.expando);
return that;
};
/**
* Creates a new DOM Binder instance for the specified component and mixes it in.
*
* @param {Object} that - The component instance to attach the new DOM Binder to.
* @param {Object} selectors - a collection of named jQuery selectors
* @return {Object} - The DOM for the component.
*/
fluid.initDomBinder = function (that, selectors) {
if (!that.container) {
fluid.fail("fluid.initDomBinder called for component with typeName " + that.typeName +
" without an initialised container - this has probably resulted from placing \"fluid.viewComponent\" in incorrect position in grade merging order. " +
" Make sure to place it to the right of any non-view grades in the gradeNames list to ensure that it overrides properly: resolved gradeNames is ", that.options.gradeNames, " for component ", that);
}
that.dom = fluid.createDomBinder(that.container, selectors || that.options.selectors || {});
that.locate = that.dom.locate;
return that.dom;
};
// DOM Utilities.
/**
* Finds the nearest ancestor of the element that matches a predicate
* @param {Element} element - DOM element
* @param {Function} test - A function (predicate) accepting a DOM element, returning a truthy value representing a match
* @return {Element|undefined} - The first element parent for which the predicate returns truthy - or undefined if no parent matches
*/
fluid.findAncestor = function (element, test) {
element = fluid.unwrap(element);
while (element) {
if (test(element)) {
return element;
}
element = element.parentNode;
}
};
fluid.findForm = function (node) {
return fluid.findAncestor(node, function (element) {
return element.nodeName.toLowerCase() === "form";
});
};
/* A utility with the same signature as jQuery.text and jQuery.html, but without the API irregularity
* that treats a single argument of undefined as different to no arguments */
// in jQuery 1.7.1, jQuery pulled the same dumb trick with $.text() that they did with $.val() previously,
// see comment in fluid.value below
fluid.each(["text", "html"], function (method) {
fluid[method] = function (node, newValue) {
node = $(node);
return newValue === undefined ? node[method]() : node[method](newValue);
};
});
/* A generalisation of jQuery.val to correctly handle the case of acquiring and
* setting the value of clustered radio button/checkbox sets, potentially, given
* a node corresponding to just one element.
*/
fluid.value = function (nodeIn, newValue) {
var node = fluid.unwrap(nodeIn);
var multiple = false;
if (node.nodeType === undefined && node.length > 1) {
node = node[0];
multiple = true;
}
if ("input" !== node.nodeName.toLowerCase() || !/radio|checkbox/.test(node.type)) {
// resist changes to contract of jQuery.val() in jQuery 1.5.1 (see FLUID-4113)
return newValue === undefined ? $(node).val() : $(node).val(newValue);
}
var name = node.name;
if (name === undefined) {
fluid.fail("Cannot acquire value from node " + fluid.dumpEl(node) + " which does not have name attribute set");
}
var elements;
if (multiple) {
elements = nodeIn;
} else {
elements = node.ownerDocument.getElementsByName(name);
var scope = fluid.findForm(node);
elements = $.grep(elements, function (element) {
if (element.name !== name) {
return false;
}
return !scope || fluid.dom.isContainer(scope, element);
});
}
if (newValue !== undefined) {
if (typeof(newValue) === "boolean") {
newValue = (newValue ? "true" : "false");
}
// jQuery gets this partially right, but when dealing with radio button array will
// set all of their values to "newValue" rather than setting the checked property
// of the corresponding control.
$.each(elements, function () {
this.checked = (newValue instanceof Array ?
newValue.indexOf(this.value) !== -1 : newValue === this.value);
});
} else { // this part jQuery will not do - extracting value from <input> array
var checked = $.map(elements, function (element) {
return element.checked ? element.value : null;
});
return node.type === "radio" ? checked[0] : checked;
}
};
fluid.BINDING_ROOT_KEY = "fluid-binding-root";
/* Recursively find any data stored under a given name from a node upwards
* in its DOM hierarchy **/
fluid.findData = function (elem, name) {
while (elem) {
var data = $.data(elem, name);
if (data) {
return data;
}
elem = elem.parentNode;
}
};
fluid.bindFossils = function (node, data, fossils) {
$.data(node, fluid.BINDING_ROOT_KEY, {data: data, fossils: fossils});
};
fluid.boundPathForNode = function (node, fossils) {
node = fluid.unwrap(node);
var key = node.name || node.id;
var record = fossils[key];
return record ? record.EL : null;
};
/* relevant, the changed value received at the given DOM node */
fluid.applyBoundChange = function (node, newValue, applier) {
node = fluid.unwrap(node);
if (newValue === undefined) {
newValue = fluid.value(node);
}
if (node.nodeType === undefined && node.length > 0) {
node = node[0];
} // assume here that they share name and parent
var root = fluid.findData(node, fluid.BINDING_ROOT_KEY);
if (!root) {
fluid.fail("Bound data could not be discovered in any node above " + fluid.dumpEl(node));
}
var name = node.name;
var fossil = root.fossils[name];
if (!fossil) {
fluid.fail("No fossil discovered for name " + name + " in fossil record above " + fluid.dumpEl(node));
}
if (typeof(fossil.oldvalue) === "boolean") { // deal with the case of an "isolated checkbox"
newValue = newValue[0] ? true : false;
}
var EL = root.fossils[name].EL;
if (applier) {
applier.fireChangeRequest({path: EL, value: newValue, source: "DOM:" + node.id});
} else {
fluid.set(root.data, EL, newValue);
}
};
/*
* Returns a jQuery object given the id of a DOM node. In the case the element
* is not found, will return an empty list.
*/
fluid.jById = function (id, dokkument) {
dokkument = dokkument && dokkument.nodeType === 9 ? dokkument : document;
var element = fluid.byId(id, dokkument);
var togo = element ? $(element) : [];
togo.selector = "#" + id;
togo.context = dokkument;
return togo;
};
/**
* Returns an DOM element quickly, given an id
*
* @param {Object} id - the id of the DOM node to find
* @param {Document} dokkument - the document in which it is to be found (if left empty, use the current document)
* @return {Object} - The DOM element with this id, or null, if none exists in the document.
*/
fluid.byId = function (id, dokkument) {
dokkument = dokkument && dokkument.nodeType === 9 ? dokkument : document;
var el = dokkument.getElementById(id);
if (el) {
// Use element id property here rather than attribute, to work around FLUID-3953
if (el.id !== id) {
fluid.fail("Problem in document structure - picked up element " +
fluid.dumpEl(el) + " for id " + id +
" without this id - most likely the element has a name which conflicts with this id");
}
return el;
} else {
return null;
}
};
/**
* Returns the id attribute from a jQuery or pure DOM element.
*
* @param {jQuery|Element} element - the element to return the id attribute for.
* @return {String} - The id attribute of the element.
*/
fluid.getId = function (element) {
return fluid.unwrap(element).id;
};
/*
* Allocate an id to the supplied element if it has none already, by a simple
* scheme resulting in ids "fluid-id-nnnn" where nnnn is an increasing integer.
*/
fluid.allocateSimpleId = function (element) {
element = fluid.unwrap(element);
if (!element || fluid.isPrimitive(element)) {
return null;
}
if (!element.id) {
var simpleId = "fluid-id-" + fluid.allocateGuid();
element.id = simpleId;
}
return element.id;
};
/**
* Returns the document to which an element belongs, or the element itself if it is already a document
*
* @param {jQuery|Element} element - The element to return the document for
* @return {Document} - The document in which it is to be found
*/
fluid.getDocument = function (element) {
var node = fluid.unwrap(element);
// DOCUMENT_NODE - guide to node types at https://developer.mozilla.org/en/docs/Web/API/Node/nodeType
return node.nodeType === 9 ? node : node.ownerDocument;
};
fluid.defaults("fluid.ariaLabeller", {
gradeNames: ["fluid.viewComponent"],
labelAttribute: "aria-label",
liveRegionMarkup: "<div class=\"liveRegion fl-hidden-accessible\" aria-live=\"polite\"></div>",
liveRegionId: "fluid-ariaLabeller-liveRegion",
invokers: {
generateLiveElement: {
funcName: "fluid.ariaLabeller.generateLiveElement",
args: "{that}"
},
update: {
funcName: "fluid.ariaLabeller.update",
args: ["{that}", "{arguments}.0"]
}
},
listeners: {
onCreate: {
func: "{that}.update",
args: [null]
}
}
});
fluid.ariaLabeller.update = function (that, newOptions) {
newOptions = newOptions || that.options;
that.container.attr(that.options.labelAttribute, newOptions.text);
if (newOptions.dynamicLabel) {
var live = fluid.jById(that.options.liveRegionId);
if (live.length === 0) {
live = that.generateLiveElement();
}
live.text(newOptions.text);
}
};
fluid.ariaLabeller.generateLiveElement = function (that) {
var liveEl = $(that.options.liveRegionMarkup);
liveEl.prop("id", that.options.liveRegionId);
$("body").append(liveEl);
return liveEl;
};
var LABEL_KEY = "aria-labelling";
fluid.getAriaLabeller = function (element) {
element = $(element);
var that = fluid.getScopedData(element, LABEL_KEY);
return that;
};
/* Manages an ARIA-mediated label attached to a given DOM element. An
* aria-labelledby attribute and target node is fabricated in the document
* if they do not exist already, and a "little component" is returned exposing a method
* "update" that allows the text to be updated. */
fluid.updateAriaLabel = function (element, text, options) {
options = $.extend({}, options || {}, {text: text});
var that = fluid.getAriaLabeller(element);
if (!that) {
that = fluid.ariaLabeller(element, options);
fluid.setScopedData(element, LABEL_KEY, that);
} else {
that.update(options);
}
return that;
};
/* "Global Dismissal Handler" for the entire page. Attaches a click handler to the
* document root that will cause dismissal of any elements (typically dialogs) which
* have registered themselves. Dismissal through this route will automatically clean up
* the record - however, the dismisser themselves must take care to deregister in the case
* dismissal is triggered through the dialog interface itself. This component can also be
* automatically configured by fluid.deadMansBlur by means of the "cancelByDefault" option */
var dismissList = {};
$(document).click(function (event) {
var target = fluid.resolveEventTarget(event);
while (target) {
if (dismissList[target.id]) {
return;
}
target = target.parentNode;
}
fluid.each(dismissList, function (dismissFunc, key) {
dismissFunc(event);
delete dismissList[key];
});
});
// TODO: extend a configurable equivalent of the above dealing with "focusin" events
/* Accepts a free hash of nodes and an optional "dismissal function".
* If dismissFunc is set, this "arms" the dismissal system, such that when a click
* is received OUTSIDE any of the hierarchy covered by "nodes", the dismissal function
* will be executed.
*/
fluid.globalDismissal = function (nodes, dismissFunc) {
fluid.each(nodes, function (node) {
// Don't bother to use the real id if it is from a foreign document - we will never receive events
// from it directly in any case - and foreign documents may be under the control of malign fiends
// such as tinyMCE who allocate the same id to everything
var id = fluid.unwrap(node).ownerDocument === document ? fluid.allocateSimpleId(node) : fluid.allocateGuid();
if (dismissFunc) {
dismissList[id] = dismissFunc;
}
else {
delete dismissList[id];
}
});
};
/* Provides an abstraction for determing the current time.
* This is to provide a fix for FLUID-4762, where IE6 - IE8
* do not support Date.now().
*/
fluid.now = function () {
return Date.now ? Date.now() : (new Date()).getTime();
};
/* Sets an interation on a target control, which morally manages a "blur" for
* a possibly composite region.
* A timed blur listener is set on the control, which waits for a short period of
* time (options.delay, defaults to 150ms) to discover whether the reason for the
* blur interaction is that either a focus or click is being serviced on a nominated
* set of "exclusions" (options.exclusions, a free hash of elements or jQueries).
* If no such event is received within the window, options.handler will be called
* with the argument "control", to service whatever interaction is required of the
* blur.
*/
fluid.deadMansBlur = function (control, options) {
// TODO: This should be rewritten as a proper component
var that = {options: $.extend(true, {}, fluid.defaults("fluid.deadMansBlur"), options)};
that.blurPending = false;
that.lastCancel = 0;
that.canceller = function (event) {
fluid.log("Cancellation through " + event.type + " on " + fluid.dumpEl(event.target));
that.lastCancel = fluid.now();
that.blurPending = false;
};
that.noteProceeded = function () {
fluid.globalDismissal(that.options.exclusions);
};
that.reArm = function () {
fluid.globalDismissal(that.options.exclusions, that.proceed);
};
that.addExclusion = function (exclusions) {
fluid.globalDismissal(exclusions, that.proceed);
};
that.proceed = function (event) {
fluid.log("Direct proceed through " + event.type + " on " + fluid.dumpEl(event.target));
that.blurPending = false;
that.options.handler(control);
};
fluid.each(that.options.exclusions, function (exclusion) {
exclusion = $(exclusion);
fluid.each(exclusion, function (excludeEl) {
$(excludeEl).on("focusin", that.canceller).
on("fluid-focus", that.canceller).
click(that.canceller).mousedown(that.canceller);
// Mousedown is added for FLUID-4212, as a result of Chrome bug 6759, 14204
});
});
if (!that.options.cancelByDefault) {
$(control).on("focusout", function (event) {
fluid.log("Starting blur timer for element " + fluid.dumpEl(event.target));
var now = fluid.now();
fluid.log("back delay: " + (now - that.lastCancel));
if (now - that.lastCancel > that.options.backDelay) {
that.blurPending = true;
}
setTimeout(function () {
if (that.blurPending) {
that.options.handler(control);
}
}, that.options.delay);
});
}
else {
that.reArm();
}
return that;
};
fluid.defaults("fluid.deadMansBlur", {
gradeNames: "fluid.function",
delay: 150,
backDelay: 100
});
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
/** NOTE: All contents of this file are DEPRECATED and no entry point should be considered a supported API **/
fluid.explodeLocalisedName = function (fileName, locale, defaultLocale) {
var lastDot = fileName.lastIndexOf(".");
if (lastDot === -1 || lastDot === 0) {
lastDot = fileName.length;
}
var baseName = fileName.substring(0, lastDot);
var extension = fileName.substring(lastDot);
var segs = locale.split("_");
var exploded = fluid.transform(segs, function (seg, index) {
var shortSegs = segs.slice(0, index + 1);
return baseName + "_" + shortSegs.join("_") + extension;
});
if (defaultLocale) {
exploded.unshift(baseName + "_" + defaultLocale + extension);
}
return exploded;
};
/** Framework-global caching state for fluid.fetchResources **/
var resourceCache = {};
var pendingClass = {};
/** Accepts a hash of structures with free keys, where each entry has either
* href/url or nodeId set - on completion, callback will be called with the populated
* structure with fetched resource text in the field "resourceText" for each
* entry. Each structure may contain "options" holding raw options to be forwarded
* to jQuery.ajax().
*/
fluid.fetchResources = function (resourceSpecs, callback, options) {
var that = {
options: fluid.copy(options || {})
};
that.resourceSpecs = resourceSpecs;
that.callback = callback;
that.operate = function () {
fluid.fetchResources.fetchResourcesImpl(that);
};
fluid.each(resourceSpecs, function (resourceSpec, key) {
resourceSpec.recurseFirer = fluid.makeEventFirer({name: "I/O completion for resource \"" + key + "\""});
resourceSpec.recurseFirer.addListener(that.operate);
if (resourceSpec.url && !resourceSpec.href) {
resourceSpec.href = resourceSpec.url;
}
// If options.defaultLocale is set, it will replace any
// defaultLocale set on an individual resourceSpec
if (that.options.defaultLocale) {
resourceSpec.defaultLocale = that.options.defaultLocale;
}
if (!resourceSpec.locale) {
resourceSpec.locale = resourceSpec.defaultLocale;
}
});
if (that.options.amalgamateClasses) {
fluid.fetchResources.amalgamateClasses(resourceSpecs, that.options.amalgamateClasses, that.operate);
}
fluid.fetchResources.explodeForLocales(resourceSpecs);
that.operate();
return that;
};
fluid.fetchResources.explodeForLocales = function (resourceSpecs) {
fluid.each(resourceSpecs, function (resourceSpec, key) {
if (resourceSpec.locale) {
var exploded = fluid.explodeLocalisedName(resourceSpec.href, resourceSpec.locale, resourceSpec.defaultLocale);
for (var i = 0; i < exploded.length; ++i) {
var newKey = key + "$localised-" + i;
var newRecord = $.extend(true, {}, resourceSpec, {
href: exploded[i],
localeExploded: true
});
resourceSpecs[newKey] = newRecord;
}
resourceSpec.localeExploded = exploded.length;
}
});
return resourceSpecs;
};
fluid.fetchResources.condenseOneResource = function (resourceSpecs, resourceSpec, key, localeCount) {
var localeSpecs = [resourceSpec];
for (var i = 0; i < localeCount; ++i) {
var localKey = key + "$localised-" + i;
localeSpecs.unshift(resourceSpecs[localKey]);
delete resourceSpecs[localKey];
}
var lastNonError = fluid.find_if(localeSpecs, function (spec) {
return !spec.fetchError;
});
if (lastNonError) {
resourceSpecs[key] = lastNonError;
}
};
fluid.fetchResources.condenseForLocales = function (resourceSpecs) {
fluid.each(resourceSpecs, function (resourceSpec, key) {
if (typeof(resourceSpec.localeExploded) === "number") {
fluid.fetchResources.condenseOneResource(resourceSpecs, resourceSpec, key, resourceSpec.localeExploded);
}
});
};
fluid.fetchResources.notifyResources = function (that, resourceSpecs, callback) {
fluid.fetchResources.condenseForLocales(resourceSpecs);
callback(resourceSpecs);
};
/*
* This function is unsupported: It is not really intended for use by implementors.
*/
// Add "synthetic" elements of *this* resourceSpec list corresponding to any
// still pending elements matching the PROLEPTICK CLASS SPECIFICATION supplied
fluid.fetchResources.amalgamateClasses = function (specs, classes, operator) {
fluid.each(classes, function (clazz) {
var pending = pendingClass[clazz];
fluid.each(pending, function (pendingrec, canon) {
specs[clazz + "!" + canon] = pendingrec;
pendingrec.recurseFirer.addListener(operator);
});
});
};
/*
* This function is unsupported: It is not really intended for use by implementors.
*/
fluid.fetchResources.timeSuccessCallback = function (resourceSpec) {
if (resourceSpec.timeSuccess && resourceSpec.options && resourceSpec.options.success) {
var success = resourceSpec.options.success;
resourceSpec.options.success = function () {
var startTime = new Date();
var ret = success.apply(null, arguments);
fluid.log("External callback for URL " + resourceSpec.href + " completed - callback time: " +
(new Date().getTime() - startTime.getTime()) + "ms");
return ret;
};
}
};
// TODO: Integrate punch-through from old Engage implementation
function canonUrl(url) {
return url;
}
fluid.fetchResources.clearResourceCache = function (url) {
if (url) {
delete resourceCache[canonUrl(url)];
}
else {
fluid.clear(resourceCache);
}
};
/*
* This function is unsupported: It is not really intended for use by implementors.
*/
fluid.fetchResources.handleCachedRequest = function (resourceSpec, response, fetchError) {
var canon = canonUrl(resourceSpec.href);
var cached = resourceCache[canon];
if (cached.$$firer$$) {
fluid.log("Handling request for " + canon + " from cache");
var fetchClass = resourceSpec.fetchClass;
if (fetchClass && pendingClass[fetchClass]) {
fluid.log("Clearing pendingClass entry for class " + fetchClass);
delete pendingClass[fetchClass][canon];
}
var result = {response: response, fetchError: fetchError};
resourceCache[canon] = result;
cached.fire(response, fetchError);
}
};
/*
* This function is unsupported: It is not really intended for use by implementors.
*/
fluid.fetchResources.completeRequest = function (thisSpec) {
thisSpec.queued = false;
thisSpec.completeTime = new Date();
fluid.log("Request to URL " + thisSpec.href + " completed - total elapsed time: " +
(thisSpec.completeTime.getTime() - thisSpec.initTime.getTime()) + "ms");
thisSpec.recurseFirer.fire();
};
/*
* This function is unsupported: It is not really intended for use by implementors.
*/
fluid.fetchResources.makeResourceCallback = function (thisSpec) {
return {
success: function (response) {
thisSpec.resourceText = response;
thisSpec.resourceKey = thisSpec.href;
if (thisSpec.forceCache) {
fluid.fetchResources.handleCachedRequest(thisSpec, response);
}
fluid.fetchResources.completeRequest(thisSpec);
},
error: function (response, textStatus, errorThrown) {
thisSpec.fetchError = {
status: response.status,
textStatus: response.textStatus,
errorThrown: errorThrown
};
if (thisSpec.forceCache) {
fluid.fetchResources.handleCachedRequest(thisSpec, null, thisSpec.fetchError);
}
fluid.fetchResources.completeRequest(thisSpec);
}
};
};
/*
* This function is unsupported: It is not really intended for use by implementors.
*/
fluid.fetchResources.issueCachedRequest = function (resourceSpec, options) {
var canon = canonUrl(resourceSpec.href);
var cached = resourceCache[canon];
if (!cached) {
fluid.log("First request for cached resource with url " + canon);
cached = fluid.makeEventFirer({name: "cache notifier for resource URL " + canon});
cached.$$firer$$ = true;
resourceCache[canon] = cached;
var fetchClass = resourceSpec.fetchClass;
if (fetchClass) {
if (!pendingClass[fetchClass]) {
pendingClass[fetchClass] = {};
}
pendingClass[fetchClass][canon] = resourceSpec;
}
options.cache = false; // TODO: Getting weird "not modified" issues on Firefox
$.ajax(options);
}
else {
if (!cached.$$firer$$) {
if (cached.response) {
options.success(cached.response);
} else {
options.error(cached.fetchError);
}
}
else {
fluid.log("Request for cached resource which is in flight: url " + canon);
cached.addListener(function (response, fetchError) {
if (response) {
options.success(response);
} else {
options.error(fetchError);
}
});
}
}
};
/*
* This function is unsupported: It is not really intended for use by implementors.
*/
// Compose callbacks in such a way that the 2nd, marked "external" will be applied
// first if it exists, but in all cases, the first, marked internal, will be
// CALLED WITHOUT FAIL
fluid.fetchResources.composeCallbacks = function (internal, external) {
return external ? (internal ?
function () {
try {
external.apply(null, arguments);
}
catch (e) {
fluid.log("Exception applying external fetchResources callback: " + e);
}
internal.apply(null, arguments); // call the internal callback without fail
} : external ) : internal;
};
// unsupported, NON-API function
fluid.fetchResources.composePolicy = function (target, source) {
return fluid.fetchResources.composeCallbacks(target, source);
};
fluid.defaults("fluid.fetchResources.issueRequest", {
mergePolicy: {
success: fluid.fetchResources.composePolicy,
error: fluid.fetchResources.composePolicy,
url: "reverse"
}
});
// unsupported, NON-API function
fluid.fetchResources.issueRequest = function (resourceSpec, key) {
var thisCallback = fluid.fetchResources.makeResourceCallback(resourceSpec);
var options = {
url: resourceSpec.href,
success: thisCallback.success,
error: thisCallback.error,
dataType: resourceSpec.dataType || "text"
};
fluid.fetchResources.timeSuccessCallback(resourceSpec);
options = fluid.merge(fluid.defaults("fluid.fetchResources.issueRequest").mergePolicy,
options, resourceSpec.options);
resourceSpec.queued = true;
resourceSpec.initTime = new Date();
fluid.log("Request with key " + key + " queued for " + resourceSpec.href);
if (resourceSpec.forceCache) {
fluid.fetchResources.issueCachedRequest(resourceSpec, options);
}
else {
$.ajax(options);
}
};
fluid.fetchResources.fetchResourcesImpl = function (that) {
var complete = true;
var resourceSpecs = that.resourceSpecs;
for (var key in resourceSpecs) {
var resourceSpec = resourceSpecs[key];
if (resourceSpec.href && !resourceSpec.completeTime) {
if (!resourceSpec.queued) {
fluid.fetchResources.issueRequest(resourceSpec, key);
}
if (resourceSpec.queued) {
complete = false;
}
}
else if (resourceSpec.nodeId && !resourceSpec.resourceText) {
var node = document.getElementById(resourceSpec.nodeId);
// upgrade this to somehow detect whether node is "armoured" somehow
// with comment or CDATA wrapping
resourceSpec.resourceText = fluid.dom.getElementText(node);
resourceSpec.resourceKey = resourceSpec.nodeId;
}
}
if (complete && that.callback && !that.callbackCalled) {
that.callbackCalled = true;
// Always defer notification in an anti-Zalgo scheme to ease problems like FLUID-6202
// In time this will be resolved by i) latched events, ii) global async ginger world
setTimeout(function () {
fluid.fetchResources.notifyResources(that, resourceSpecs, that.callback);
}, 1);
}
};
// TODO: This framework function is a stop-gap before the "ginger world" is capable of
// asynchronous instantiation. It currently performs very poor fidelity expansion of a
// component's options to discover "resources" only held in the static environment
fluid.fetchResources.primeCacheFromResources = function (componentName) {
var resources = fluid.defaults(componentName).resources;
var expanded = (fluid.expandOptions ? fluid.expandOptions : fluid.identity)(fluid.copy(resources));
fluid.fetchResources(expanded);
};
/** Utilities invoking requests for expansion **/
fluid.registerNamespace("fluid.expander");
/*
* This function is unsupported: It is not really intended for use by implementors.
*/
fluid.expander.makeDefaultFetchOptions = function (successdisposer, failid, options) {
return $.extend(true, {dataType: "text"}, options, {
success: function (response, environmentdisposer) {
var json = JSON.parse(response);
environmentdisposer(successdisposer(json));
},
error: function (response, textStatus) {
fluid.log("Error fetching " + failid + ": " + textStatus);
}
});
};
/*
* This function is unsupported: It is not really intended for use by implementors.
*/
fluid.expander.makeFetchExpander = function (options) {
return { expander: {
type: "fluid.expander.deferredFetcher",
href: options.url,
options: fluid.expander.makeDefaultFetchOptions(options.disposer, options.url, options.options),
resourceSpecCollector: "{resourceSpecCollector}",
fetchKey: options.fetchKey
}};
};
fluid.expander.deferredFetcher = function (deliverer, source, expandOptions) {
var expander = source.expander;
var spec = fluid.copy(expander);
// fetch the "global" collector specified in the external environment to receive
// this resourceSpec
var collector = fluid.expand(expander.resourceSpecCollector, expandOptions);
delete spec.type;
delete spec.resourceSpecCollector;
delete spec.fetchKey;
var environmentdisposer = function (disposed) {
deliverer(disposed);
};
// replace the callback which is there (taking 2 arguments) with one which
// directly responds to the request, passing in the result and OUR "disposer" -
// which once the user has processed the response (say, parsing JSON and repackaging)
// finally deposits it in the place of the expander in the tree to which this reference
// has been stored at the point this expander was evaluated.
spec.options.success = function (response) {
expander.options.success(response, environmentdisposer);
};
var key = expander.fetchKey || fluid.allocateGuid();
collector[key] = spec;
return fluid.NO_VALUE;
};
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
fluid.defaults("fluid.messageResolver", {
gradeNames: ["fluid.component"],
mergePolicy: {
messageBase: "nomerge",
parents: "nomerge"
},
resolveFunc: fluid.stringTemplate,
parseFunc: fluid.identity,
messageBase: {},
members: {
messageBase: "@expand:{that}.options.parseFunc({that}.options.messageBase)"
},
invokers: {
lookup: "fluid.messageResolver.lookup({that}, {arguments}.0)", // messagecodes
resolve: "fluid.messageResolver.resolve({that}, {arguments}.0, {arguments}.1)" // messagecodes, args
},
parents: []
});
/**
*
* Look up the first matching message template, starting with the current grade and working up through its parents.
* Returns both the template for the message and the function used to resolve the localised value. By default
* the resolve function is `fluid.stringTemplate`, and the template returned uses its syntax.
*
* @param {Object} that - The component itself.
* @param {Array} messagecodes - One or more message codes to look up templates for.
* @return {Object} - An object that contains`template` and `resolveFunc` members (see above).
*
*/
fluid.messageResolver.lookup = function (that, messagecodes) {
var resolved = fluid.messageResolver.resolveOne(that.messageBase, messagecodes);
if (resolved === undefined) {
return fluid.find(that.options.parents, function (parent) {
return parent ? parent.lookup(messagecodes) : undefined;
});
} else {
return {template: resolved, resolveFunc: that.options.resolveFunc};
}
};
/**
*
* Look up the first message that corresponds to a message code found in `messageCodes`. Then, resolve its
* localised value. By default, supports variable substitutions using `fluid.stringTemplate`.
*
* @param {Object} that - The component itself.
* @param {Array} messagecodes - A list of message codes to look for.
* @param {Object} args - A map of variables that may potentially be used as part of the final output.
* @return {String} - The final message, localised, with any variables found in `args`.
*
*/
fluid.messageResolver.resolve = function (that, messagecodes, args) {
if (!messagecodes) {
return "[No messagecodes provided]";
}
messagecodes = fluid.makeArray(messagecodes);
var looked = that.lookup(messagecodes);
return looked ? looked.resolveFunc(looked.template, args) :
"[Message string for key " + messagecodes[0] + " not found]";
};
// unsupported, NON-API function
fluid.messageResolver.resolveOne = function (messageBase, messagecodes) {
for (var i = 0; i < messagecodes.length; ++i) {
var code = messagecodes[i];
var message = messageBase[code];
if (message !== undefined) {
return message;
}
}
};
/**
*
* Converts a data structure consisting of a mapping of keys to message strings, into a "messageLocator" function
* which maps an array of message codes, to be tried in sequence until a key is found, and an array of substitution
* arguments, into a substituted message string.
*
* @param {Object} messageBase - A body of messages to wrap in a resolver function.
* @param {Function} resolveFunc (Optional) - A "resolver" function to use instead of the default `fluid.stringTemplate`.
* @return {Function} - A "messageLocator" function (see above).
*
*/
fluid.messageLocator = function (messageBase, resolveFunc) {
var resolver = fluid.messageResolver({messageBase: messageBase, resolveFunc: resolveFunc});
return function (messagecodes, args) {
return resolver.resolve(messagecodes, args);
};
};
/**
*
* Resolve a "message source", which is either itself a resolver, or an object representing a bundle of messages
* and the associated resolution function.
*
* When passing a "data" object, it is expected to have a `type` element that is set to `data`, and to have a
* `messages` array and a `resolveFunc` function that can be used to resolve messages.
*
* A "resolver" is expected to be an object with a `type` element that is set to `resolver` that exposes a `resolve`
* function.
*
* @param {Object} messageSource - See above.
* @return {Function|String} - A resolve function or a `String` representing the final resolved output.
*
*/
fluid.resolveMessageSource = function (messageSource) {
if (messageSource.type === "data") {
if (messageSource.url === undefined) {
return fluid.messageLocator(messageSource.messages, messageSource.resolveFunc);
}
else {
// TODO: fetch via AJAX, and convert format if necessary
}
}
else if (messageSource.type === "resolver") {
return messageSource.resolver.resolve;
}
};
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
/**
* A configurable component to allow users to load multiple resources via AJAX requests.
* The resources can be localised by means of options `locale`, `defaultLocale`. Once all
* resources are loaded, the event `onResourceLoaded` will be fired, which can be used
* to time the creation of components dependent on the resources.
*
* @param {Object} options - The component options.
*/
fluid.defaults("fluid.resourceLoader", {
gradeNames: ["fluid.component"],
listeners: {
"onCreate.loadResources": {
listener: "fluid.resourceLoader.loadResources",
args: ["{that}", {expander: {func: "{that}.resolveResources"}}]
}
},
defaultLocale: null,
locale: null,
terms: {}, // Must be supplied by integrators
resources: {}, // Must be supplied by integrators
resourceOptions: {},
// Unsupported, non-API option
invokers: {
transformURL: {
funcName: "fluid.stringTemplate",
args: ["{arguments}.0", "{that}.options.terms"]
},
resolveResources: {
funcName: "fluid.resourceLoader.resolveResources",
args: "{that}"
}
},
events: {
onResourcesLoaded: null
}
});
fluid.resourceLoader.resolveResources = function (that) {
var mapped = fluid.transform(that.options.resources, that.transformURL);
return fluid.transform(mapped, function (url) {
var resourceSpec = {url: url, forceCache: true, options: that.options.resourceOptions};
return $.extend(resourceSpec, fluid.filterKeys(that.options, ["defaultLocale", "locale"]));
});
};
fluid.resourceLoader.loadResources = function (that, resources) {
fluid.fetchResources(resources, function () {
that.resources = resources;
that.events.onResourcesLoaded.fire(resources);
});
};
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
/*
The contents of this file were adapted from ViewComponentSupport.js and ComponentGraph.js in fluid-authoring
See: https://github.com/fluid-project/fluid-authoring/blob/FLUID-4884/src/js/ViewComponentSupport.js
https://github.com/fluid-project/fluid-authoring/blob/FLUID-4884/src/js/ComponentGraph.js
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
/**
* A variant of fluid.viewComponent that bypasses the wacky "initView" and variant signature
* workflow, sourcing instead its "container" from an option of that name, so that this argument
* can participate in standard ginger resolution. This enables useful results such as a component
* which can render its own container into the DOM on startup, whilst the container remains immutable.
*/
fluid.defaults("fluid.newViewComponent", {
gradeNames: ["fluid.modelComponent"],
members: {
// 3rd argument is throwaway to force evaluation of container
dom: "@expand:fluid.initDomBinder({that}, {that}.options.selectors, {that}.container)",
container: "@expand:fluid.container({that}.options.container)"
}
});
/**
* Used to add an element to a parent container. Internally it can use either of jQuery's prepend or append methods.
*
* @param {jQuery|DOMElement|Selector} parentContainer - any jQueryable selector representing the parent element to
* inject the `elm` into.
* @param {DOMElement|jQuery} elm - a DOM element or jQuery element to be added to the parent.
* @param {String} method - (optional) a string representing the method to use to add the `elm` to the
* `parentContainer`. The method can be "append" (default), "prepend", or "html" (will
* replace the contents).
*/
fluid.newViewComponent.addToParent = function (parentContainer, elm, method) {
method = method || "append";
$(parentContainer)[method](elm);
};
/**
* Similar to fluid.newViewComponent; however, it will render its own markup including its container, into a
* specified parent container.
*/
fluid.defaults("fluid.containerRenderingView", {
gradeNames: ["fluid.newViewComponent"],
container: "@expand:{that}.renderContainer()",
// The DOM element which this component should inject its markup into on startup
parentContainer: "fluid.notImplemented", // must be overridden
injectionType: "append",
invokers: {
renderMarkup: "fluid.identity({that}.options.markup.container)",
renderContainer: "fluid.containerRenderingView.renderContainer({that}, {that}.renderMarkup, {that}.addToParent)",
addToParent: {
funcName: "fluid.newViewComponent.addToParent",
args: ["{that}.options.parentContainer", "{arguments}.0", "{that}.options.injectionType"]
}
}
});
/**
* Renders the components markup and inserts it into the parent container based on the addToParent method
*
* @param {Component} that - the component
* @param {Function} renderMarkup - a function returning the components container markup to be inserted into the
* parentContainer element
* @param {Function} addToParent - a function that inserts the container into the DOM
* @return {DOMElement} - the container
*/
fluid.containerRenderingView.renderContainer = function (that, renderMarkup, addToParent) {
fluid.log("Rendering container for " + that.id);
var containerMarkup = renderMarkup();
var container = $(containerMarkup);
addToParent(container);
return container;
};
/**
* Similar to fluid.newViewComponent; however, it will fetch a template and render it into the container.
*
* The template path must be supplied either via a top level `template` option or directly to the
* `resources.template` option. The path may optionally include "terms" to use as tokens which will be resolved
* from values specified in the `terms` option.
*
* The template is fetched on creation and rendered into the container after it has been fetched. After rendering
* the `afterRender` event is fired.
*/
fluid.defaults("fluid.templateRenderingView", {
gradeNames: ["fluid.newViewComponent", "fluid.resourceLoader"],
resources: {
template: "fluid.notImplemented"
},
injectionType: "append",
events: {
afterRender: null
},
listeners: {
"onResourcesLoaded.render": "{that}.render",
"onResourcesLoaded.afterRender": {
listener: "{that}.events.afterRender",
args: ["{that}"],
priority: "after:render"
}
},
invokers: {
render: {
funcName: "fluid.newViewComponent.addToParent",
args: ["{that}.container", "{that}.resources.template.resourceText", "{that}.options.injectionType"]
}
},
distributeOptions: {
"mapTemplateSource": {
source: "{that}.options.template",
removeSource: true,
target: "{that}.options.resources.template"
}
}
});
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
/*
* Provides a grade for creating and interacting with a Mutation Observer to listen/respond to DOM changes.
*/
fluid.defaults("fluid.mutationObserver", {
gradeNames: ["fluid.viewComponent"],
events: {
onNodeAdded: null,
onNodeRemoved: null,
onAttributeChanged: null
},
listeners: {
"onDestroy.disconnect": "{that}.disconnect"
},
members: {
observer: {
expander: {
func: "{that}.createObserver"
}
}
},
defaultObserveConfig: {
attributes: true,
childList: true,
subtree: true
},
invokers: {
observe: {
funcName: "fluid.mutationObserver.observe",
args: ["{that}", "{arguments}.0", "{arguments}.1"]
},
disconnect: {
"this": "{that}.observer",
method: "disconnect"
},
takeRecords: {
"this": "{that}.observer",
method: "takeRecords"
},
createObserver: {
funcName: "fluid.mutationObserver.createObserver",
args: ["{that}"]
}
}
});
/**
* A Mutation Observer; allows for tracking changes to the DOM.
* A mutation observer is created with a callback function, configured through its `observe` method.
* See: https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
*
* @typedef {Object} MutationObserver
*/
/**
* Instantiates a mutation observer, defining the callback function which relays the observations to component
* events. The configuration passed to the observe function will determine what mutations are observed and what
* information is returned. See `fluid.mutationObserver.observe` about configuring the mutation observer.
*
* Event Mapping:
* onNodeAdded - fired for each added node, includes the node and mutation record
* onNodeRemoved - fired for each removed node, includes the node and mutation record
* onAttributeChanged - fired for each attribute change, includes the node and mutation record
*
* @param {Component} that - an instance of `fluid.mutationObserver`
*
* @return {MutationObserver} - the created mutation observer`
*/
fluid.mutationObserver.createObserver = function (that) {
var observer = new MutationObserver(function (mutationRecords) {
fluid.each(mutationRecords, function (mutationRecord) {
// IE11 doesn't support forEach on NodeLists and NodeLists aren't real arrays so using fluid.each
// will iterate over the object properties. Therefore we use a for loop to iterate over the nodes.
for (var i = 0; i < mutationRecord.addedNodes.length; i++) {
that.events.onNodeAdded.fire(mutationRecord.addedNodes[i], mutationRecord);
}
for (var j = 0; j < mutationRecord.removedNodes.length; j++) {
that.events.onNodeRemoved.fire(mutationRecord.removedNodes[j], mutationRecord);
}
if (mutationRecord.type === "attributes") {
that.events.onAttributeChanged.fire(mutationRecord.target, mutationRecord);
}
});
});
return observer;
};
/**
* Starts observing the DOM changes. Optionally takes in a target and configuration for setting up the specific
* observation. The observe method may be called multiple times; however, if the same observer is set on the same
* node, the old one will be replaced. If an observation is disconnected, the observe method will need to be called
* again to re-instate the mutation observation.
* See: https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver/observe
*
* @param {Component} that - an instance of `fluid.mutationObserver`
* @param {DOMElement|jQuery} target - a DOM element or jQuery element to be observed. By default the component's
* container element is used.
* @param {Object} options - config options to pass to the observations. This specifies which mutations should be
* reported. See: https://developer.mozilla.org/en-US/docs/Web/API/MutationObserverInit
* By default the config specified at `that.options.defaultObserveConfig` is used.
*/
fluid.mutationObserver.observe = function (that, target, options) {
target = fluid.unwrap(target || that.container);
that.observer.observe(target, options || that.options.defaultObserveConfig);
};
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
/*******************************************************************************
* fluid.textNodeParser
*
* Parses out the text nodes from a DOM element and its descendants
*******************************************************************************/
fluid.defaults("fluid.textNodeParser", {
gradeNames: ["fluid.component"],
events: {
onParsedTextNode: null,
afterParse: null
},
invokers: {
parse: {
funcName: "fluid.textNodeParser.parse",
args: ["{that}", "{arguments}.0", "{arguments}.1", "{that}.events.afterParse.fire"]
},
hasTextToRead: "fluid.textNodeParser.hasTextToRead",
isWord: "fluid.textNodeParser.isWord",
getLang: "fluid.textNodeParser.getLang"
}
});
/**
* Tests if a string is a word; i.e. it has a value and is not only whitespace.
* inspired by https://stackoverflow.com/a/2031143
*
* @param {String} str - the String to test
*
* @return {Boolean} - `true` if a word, `false` otherwise.
*/
fluid.textNodeParser.isWord = function (str) {
return fluid.isValue(str) && /\S/.test(str);
};
/**
* Determines if there is text in an element that should be read.
* Will return false in the following conditions:
* - elm is falsey (undefined, null, etc.)
* - elm's offsetParent is falsey, unless elm is the `body` element
* - elm has no text or only whitespace
* - elm or an ancestor has "aria-hidden=true", unless the `acceptAriaHidden` parameter is set
*
* NOTE: Text added by pseudo elements (e.g. :before, :after) are not considered.
* NOTE: This method is not supported in IE 11 because innerText returns the text for some hidden elements,
* that is inconsistent with modern browsers.
*
* @param {jQuery|DomElement} elm - either a DOM node or a jQuery element
* @param {Boolean} acceptAriaHidden - if set, will return `true` even if the `elm` or one of its ancestors has
* `aria-hidden="true"`.
*
* @return {Boolean} - returns true if there is rendered text within the element and false otherwise.
* (See conditions in description above)
*/
fluid.textNodeParser.hasTextToRead = function (elm, acceptAriaHidden) {
elm = fluid.unwrap(elm);
return elm &&
(elm.tagName.toLowerCase() === "body" || elm.offsetParent) &&
fluid.textNodeParser.isWord(elm.innerText) &&
(acceptAriaHidden || !$(elm).closest("[aria-hidden=\"true\"]").length);
};
/**
* Uses jQuery's `closest` method to find the closest element with a lang attribute, and returns the value.
*
* @param {jQuery|DomElement} elm - either a DOM node or a jQuery element
*
* @return {String|Undefined} - a valid BCP 47 language code if found, otherwise undefined.
*/
fluid.textNodeParser.getLang = function (elm) {
return $(elm).closest("[lang]").attr("lang");
};
/**
* The parsed information of text node, including: the node itself, its specified language, and its index within its
* parent.
*
* @typedef {Object} TextNodeData
* @property {DomNode} node - The current child node being parsed
* @property {Integer} childIndex - The index of the child node being parsed relative to its parent
* @property {String} lang - a valid BCP 47 language code
*/
/**
* Recursively parses a DOM element and it's sub elements and fires the `onParsedTextNode` event for each text node
* found. The event is fired with the text node, language and index of the text node in the list of its parent's
* child nodes..
*
* Note: elements that return `false` from `that.hasTextToRead` are ignored.
*
* @param {fluid.textNodeParser} that - an instance of the component
* @param {jQuery|DomElement} elm - the DOM node to parse
* @param {String} lang - a valid BCP 47 language code.
* @param {Event} afterParseEvent - the event to fire after parsing has completed.
*
* @return {TextNodeData[]} the array of parsed elements. Only text nodes for elements that have passed the
* `that.hasTextToRead` check will be included.
*/
fluid.textNodeParser.parse = function (that, elm, lang, afterParseEvent) {
elm = fluid.unwrap(elm);
var parsed = [];
if (that.hasTextToRead(elm)) {
var childNodes = elm.childNodes;
var elementLang = elm.getAttribute("lang") || lang || that.getLang(elm);
// This funny iteration is a fix for FLUID-6435 on IE11
Array.prototype.forEach.call(childNodes, function (childNode, childIndex) {
if (childNode.nodeType === Node.TEXT_NODE) {
var textNodeData = {
node: childNode,
lang: elementLang,
childIndex: childIndex
};
parsed.push(textNodeData);
that.events.onParsedTextNode.fire(textNodeData);
} else if (childNode.nodeType === Node.ELEMENT_NODE) {
parsed = parsed.concat(fluid.textNodeParser.parse(that, childNode, elementLang));
}
});
}
if (afterParseEvent) {
afterParseEvent(that, parsed);
}
return parsed;
};
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
fluid.registerNamespace("fluid.undo");
// The three states of the undo component
fluid.undo.STATE_INITIAL = "state_initial";
fluid.undo.STATE_CHANGED = "state_changed";
fluid.undo.STATE_REVERTED = "state_reverted";
fluid.undo.defaultRenderer = function (that, targetContainer) {
var str = that.options.strings;
var markup = "<span class='flc-undo'>" +
"<a href='#' class='flc-undo-undoControl'>" + str.undo + "</a>" +
"<a href='#' class='flc-undo-redoControl'>" + str.redo + "</a>" +
"</span>";
var markupNode = $(markup).attr({
"role": "region",
"aria-live": "polite",
"aria-relevant": "all"
});
targetContainer.append(markupNode);
return markupNode;
};
fluid.undo.refreshView = function (that) {
if (that.state === fluid.undo.STATE_INITIAL) {
that.locate("undoContainer").hide();
that.locate("redoContainer").hide();
} else if (that.state === fluid.undo.STATE_CHANGED) {
that.locate("undoContainer").show();
that.locate("redoContainer").hide();
} else if (that.state === fluid.undo.STATE_REVERTED) {
that.locate("undoContainer").hide();
that.locate("redoContainer").show();
}
};
fluid.undo.undoControlClick = function (that) {
if (that.state !== fluid.undo.STATE_REVERTED) {
fluid.model.copyModel(that.extremalModel, that.component.model);
that.component.updateModel(that.initialModel, that);
that.state = fluid.undo.STATE_REVERTED;
fluid.undo.refreshView(that);
that.locate("redoControl").focus();
}
return false;
};
fluid.undo.redoControlClick = function (that) {
if (that.state !== fluid.undo.STATE_CHANGED) {
that.component.updateModel(that.extremalModel, that);
that.state = fluid.undo.STATE_CHANGED;
fluid.undo.refreshView(that);
that.locate("undoControl").focus();
}
return false;
};
fluid.undo.modelChanged = function (that, newModel, oldModel, source) {
if (source !== that) {
that.state = fluid.undo.STATE_CHANGED;
fluid.model.copyModel(that.initialModel, oldModel);
fluid.undo.refreshView(that);
}
};
fluid.undo.copyInitialModel = function (that) {
fluid.model.copyModel(that.initialModel, that.component.model);
fluid.model.copyModel(that.extremalModel, that.component.model);
};
fluid.undo.setTabindex = function (that) {
fluid.tabindex(that.locate("undoControl"), 0);
fluid.tabindex(that.locate("redoControl"), 0);
};
/**
* Decorates a target component with the function of "undoability". This component is intended to be attached as a
* subcomponent to the target component, which will bear a grade of "fluid.undoable"
*
* @param component {Object} a "model-bearing" standard Fluid component to receive the "undo" functionality
* @param options {Object} a collection of options settings
*/
fluid.defaults("fluid.undo", {
gradeNames: ["fluid.component"],
members: {
state: fluid.undo.STATE_INITIAL,
initialModel: {},
extremalModel: {},
component: "{fluid.undoable}",
container: {
expander: {
func: "{that}.options.renderer",
args: ["{that}", "{that}.component.container"]
}
},
dom: {
expander: {
funcName: "fluid.initDomBinder",
args: ["{that}", "{that}.options.selectors"]
}
}
},
invokers: {
undoControlClick: {
funcName: "fluid.undo.undoControlClick",
args: "{that}"
},
redoControlClick: {
funcName: "fluid.undo.redoControlClick",
args: "{that}"
}
},
listeners: {
"onCreate.copyInitialModel": {
funcName: "fluid.undo.copyInitialModel",
priority: "before:refreshView"
},
"onCreate.setTabindex": "fluid.undo.setTabindex",
"onCreate.refreshView": "fluid.undo.refreshView",
"onCreate.bindUndoClick": {
"this": "{that}.dom.undoControl",
method: "click",
args: "{that}.undoControlClick"
},
"onCreate.bindRedoClick": {
"this": "{that}.dom.redoControl",
method: "click",
args: "{that}.redoControlClick"
},
"{fluid.undoable}.events.modelChanged": {
funcName: "fluid.undo.modelChanged",
args: ["{that}", "{arguments}.0", "{arguments}.1", "{arguments}.2"]
}
},
selectors: {
undoContainer: ".flc-undo-undoControl",
undoControl: ".flc-undo-undoControl",
redoContainer: ".flc-undo-redoControl",
redoControl: ".flc-undo-redoControl"
},
strings: {
undo: "undo edit",
redo: "redo edit"
},
renderer: fluid.undo.defaultRenderer
});
// An uninstantiable grade expressing the contract of the "fluid.undoable" grade
fluid.defaults("fluid.undoable", {
gradeNames: ["fluid.modelComponent"],
invokers: {
updateModel: {} // will be implemented by concrete grades
},
events: {
modelChanged: null
}
});
// Backward compatibility for users of Infusion 1.4.x API
fluid.defaults("fluid.undoDecorator", {
gradeNames: ["fluid.undo"]
});
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
fluid.registerNamespace("fluid.tooltip");
fluid.tooltip.computeContentFunc = function (that) {
that.contentFunc = that.options.contentFunc ? that.options.contentFunc : that.modelToContentFunc();
};
fluid.tooltip.updateContentImpl = function (that) {
that.computeContentFunc();
if (that.initialised) {
that.container.tooltip("option", "content", that.contentFunc);
}
};
fluid.tooltip.idSearchFunc = function (idToContentFunc) {
return function (/* callback*/) {
var target = this;
if ($.contains( target.ownerDocument, target )) { // prevent widget from trying to open tooltip for element no longer in document (FLUID-5394)
var idToContent = idToContentFunc();
var ancestor = fluid.findAncestor(target, function (element) {
return idToContent[element.id];
});
return ancestor ? idToContent[ancestor.id] : null;
} else {
return null;
}
};
};
fluid.tooltip.modelToContentFunc = function (that) {
var model = that.model;
if (model.idToContent) {
return fluid.tooltip.idSearchFunc(function () {
return that.model.idToContent;
});
} else if (model.content) {
return function () {
return model.content;
};
}
};
// Resolve FLUID-5673 by resolving the event target upwards to the nearest match for "items" - this will
// reproduce the natural effect operated by event bubbling in conjunction with the widget
fluid.tooltip.resolveTooltipTarget = function (items, event) {
var originalTarget = fluid.resolveEventTarget(event);
var tooltipTarget = $(originalTarget).closest(items);
return tooltipTarget[0];
};
// Note that fluid.resolveEventTarget is required
// because of strange dispatching within tooltip widget's "_open" method
// -> this._trigger( "open", event, { tooltip: tooltip };
// the target of the outer event will be incorrect
fluid.tooltip.makeOpenHandler = function (that) {
return function (event, tooltip) {
fluid.tooltip.closeAll(that);
var originalTarget = fluid.tooltip.resolveTooltipTarget(that.options.items, event);
var key = fluid.allocateSimpleId(originalTarget);
that.openIdMap[key] = true;
if (that.initialised) {
that.events.afterOpen.fire(that, originalTarget, tooltip.tooltip, event);
}
};
};
fluid.tooltip.makeCloseHandler = function (that) {
return function (event, tooltip) {
if (that.initialised) { // underlying jQuery UI component will fire various spurious close events after it has been destroyed
var originalTarget = fluid.tooltip.resolveTooltipTarget(that.options.items, event);
delete that.openIdMap[originalTarget.id];
that.events.afterClose.fire(that, originalTarget, tooltip.tooltip, event);
}
};
};
fluid.tooltip.closeAll = function (that) {
var dokkument = fluid.getDocument(that.container);
fluid.each(that.openIdMap, function (value, key) {
var target = fluid.byId(key, dokkument);
// "white-box" behaviour - fabricating this fake event shell triggers the standard "close" sequence including notifying
// our own handler. This will be very fragile to changes in jQuery UI and the underlying widget code
that.container.tooltip("close", {
type: "close",
currentTarget: target,
target: target
});
});
fluid.clear(that.openIdMap);
};
fluid.tooltip.setup = function (that) {
fluid.tooltip.updateContentImpl(that);
var directOptions = {
content: that.contentFunc,
open: fluid.tooltip.makeOpenHandler(that),
close: fluid.tooltip.makeCloseHandler(that)
};
var fullOptions = $.extend(true, directOptions, that.options.widgetOptions);
that.container.tooltip(fullOptions);
that.initialised = true;
};
fluid.tooltip.doDestroy = function (that) {
if (that.initialised) {
fluid.tooltip.closeAll(that, true);
var dokkument = fluid.getDocument(that.container),
container = that.container[0];
// jQuery UI framework will throw a fit if we have instantiated a widget on a DOM element and then
// removed it from the DOM. This apparently can't be detected via the jQuery UI API itself.
if ($.contains(dokkument, container) || dokkument === container) {
that.container.tooltip("destroy");
}
that.initialised = false; // TODO: proper framework facility for this coming with FLUID-4890
}
};
fluid.defaults("fluid.tooltip", {
gradeNames: ["fluid.viewComponent"],
widgetOptions: {
tooltipClass: "{that}.options.styles.tooltip",
position: "{that}.options.position",
items: "{that}.options.items",
show: {
duration: "{that}.options.duration",
delay: "{that}.options.delay"
},
hide: {
duration: "{that}.options.duration",
delay: "{that}.options.delay"
}
},
invokers: {
/**
* Manually displays the tooltip
*/
open: {
"this": "{that}.container",
method: "tooltip",
args: "open"
},
/**
* Manually hides the tooltip
*/
close: {
funcName: "fluid.tooltip.closeAll",
args: "{that}"
},
updateContent: {
changePath: "content",
value: "{arguments}.0"
},
computeContentFunc: {
funcName: "fluid.tooltip.computeContentFunc",
args: ["{that}"]
},
modelToContentFunc: {
funcName: "fluid.tooltip.modelToContentFunc",
args: "{that}"
}
},
model: {
// backward compatibility for pre-1.5 users of Tooltip
content: "{that}.options.content"
// content: String,
// idToContent: Object {String -> String}
},
members: {
openIdMap: {}
},
styles: {
tooltip: ""
},
events: {
afterOpen: null, // arguments: that, event.target, tooltip, event
afterClose: null // arguments: that, event.target, tooltip, event
},
listeners: {
"onCreate.setup": "fluid.tooltip.setup",
"onDestroy.doDestroy": "fluid.tooltip.doDestroy"
},
modelListeners: {
// TODO: We could consider a more fine-grained scheme for this,
// listening to content and idToContent separately
"": {
funcName: "fluid.tooltip.updateContentImpl",
excludeSource: "init",
args: "{that}"
}
},
position: {
my: "left top",
at: "left bottom"
},
items: "*",
delay: 300
});
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
fluid.registerNamespace("fluid.inlineEdit");
fluid.inlineEdit.sendKey = function (control, event, virtualCode, charCode) {
var kE = document.createEvent("KeyEvents");
kE.initKeyEvent(event, 1, 1, null, 0, 0, 0, 0, virtualCode, charCode);
control.dispatchEvent(kE);
};
fluid.inlineEdit.switchToViewMode = function (that) {
that.editContainer.hide();
that.displayModeRenderer.show();
};
fluid.inlineEdit.cancel = function (that) {
if (that.isEditing()) {
// Roll the edit field back to its old value and close it up.
// This setTimeout is necessary on Firefox, since any attempt to modify the
// input control value during the stack processing the ESCAPE key will be ignored.
setTimeout(function () {
that.editView.value(that.model.value);
}, 1);
fluid.inlineEdit.switchToViewMode(that);
that.events.afterFinishEdit.fire(that.model.value, that.model.value,
that.editField[0], that.viewEl[0]);
}
};
fluid.inlineEdit.finish = function (that) {
var newValue = that.editView.value();
var oldValue = that.model.value;
var viewNode = that.viewEl[0];
var editNode = that.editField[0];
var ret = that.events.onFinishEdit.fire(newValue, oldValue, editNode, viewNode);
if (ret === false) {
return;
}
that.updateModelValue(newValue);
that.events.afterFinishEdit.fire(newValue, oldValue, editNode, viewNode);
fluid.inlineEdit.switchToViewMode(that);
};
/**
* Do not allow the textEditButton to regain focus upon completion unless
* the keypress is enter or esc.
*
* @param {Object} that - The component itself.
*/
fluid.inlineEdit.bindEditFinish = function (that) {
if (that.options.submitOnEnter === undefined) {
that.options.submitOnEnter = "textarea" !== fluid.unwrap(that.editField).nodeName.toLowerCase();
}
function keyCode(evt) {
// Fix for handling arrow key presses. See FLUID-760.
return evt.keyCode ? evt.keyCode : (evt.which ? evt.which : 0);
}
var button = that.textEditButton || $();
var escHandler = function (evt) {
var code = keyCode(evt);
if (code === $.ui.keyCode.ESCAPE) {
button.focus();
fluid.inlineEdit.cancel(that);
return false;
}
};
var finishHandler = function (evt) {
var code = keyCode(evt);
if (code !== $.ui.keyCode.ENTER) {
button.blur();
return true;
} else {
fluid.inlineEdit.finish(that);
button.focus();
}
return false;
};
if (that.options.submitOnEnter) {
that.editContainer.keypress(finishHandler);
}
that.editContainer.keydown(escHandler);
};
fluid.inlineEdit.bindBlurHandler = function (that) {
if (that.options.blurHandlerBinder) {
that.options.blurHandlerBinder(that);
} else {
var blurHandler = function () {
if (that.isEditing()) {
fluid.inlineEdit.finish(that);
}
return false;
};
that.editField.blur(blurHandler);
}
};
fluid.inlineEdit.initializeEditView = function (that, initial) {
if (!that.editInitialized) {
fluid.inlineEdit.renderEditContainer(that, !that.options.lazyEditView || !initial);
if (!that.options.lazyEditView || !initial) {
that.events.onCreateEditView.fire();
if (that.textEditButton) {
fluid.inlineEdit.bindEditFinish(that);
}
fluid.inlineEdit.bindBlurHandler(that);
that.editView.refreshView(that);
that.editInitialized = true;
}
}
};
fluid.inlineEdit.edit = function (that) {
fluid.inlineEdit.initializeEditView(that, false);
var viewEl = that.viewEl;
var displayText = that.displayView.value();
that.updateModelValue(that.model.value === "" ? "" : displayText);
if (that.options.applyEditPadding) {
that.editField.width(Math.max(viewEl.width() + that.options.paddings.edit, that.options.paddings.minimumEdit));
}
that.displayModeRenderer.hide();
that.editContainer.show();
// Work around for FLUID-726
// Without 'setTimeout' the finish handler gets called with the event and the edit field is inactivated.
setTimeout(function () {
that.editField.focus();
if (that.options.selectOnEdit) {
that.editField[0].select();
}
}, 0);
that.events.afterBeginEdit.fire();
};
fluid.inlineEdit.clearEmptyViewStyles = function (textEl, styles, originalViewPadding) {
textEl.removeClass(styles.defaultViewStyle);
textEl.css("padding-right", originalViewPadding);
textEl.removeClass(styles.emptyDefaultViewText);
};
fluid.inlineEdit.showDefaultViewText = function (that) {
that.displayView.value(that.options.strings.defaultViewText);
that.viewEl.css("padding-right", that.existingPadding);
that.viewEl.addClass(that.options.styles.defaultViewStyle);
};
fluid.inlineEdit.showNothing = function (that) {
that.displayView.value("");
// workaround for FLUID-938:
// IE can not style an empty inline element, so force element to be display: inline-block
if ($.browser.msie) {
if (that.viewEl.css("display") === "inline") {
that.viewEl.css("display", "inline-block");
}
}
};
fluid.inlineEdit.showEditedText = function (that) {
that.displayView.value(that.model.value);
fluid.inlineEdit.clearEmptyViewStyles(that.viewEl, that.options.styles, that.existingPadding);
};
fluid.inlineEdit.refreshView = function (that, source) {
that.displayView.refreshView(that, source);
if (that.editView) {
that.editView.refreshView(that, source);
}
};
fluid.inlineEdit.updateModelValue = function (that, newValue, source) {
var comparator = that.options.modelComparator;
var unchanged = comparator ? comparator(that.model.value, newValue) :
that.model.value === newValue;
if (!unchanged) {
var oldModel = $.extend(true, {}, that.model);
that.model.value = newValue;
that.events.modelChanged.fire(that.model, oldModel, source);
that.refreshView(source);
}
};
fluid.inlineEdit.editHandler = function (that) {
var prevent = that.events.onBeginEdit.fire();
if (prevent === false) {
return false;
}
fluid.inlineEdit.edit(that);
return true;
};
// Initialize the tooltip once the document is ready.
// For more details, see http://issues.fluidproject.org/browse/FLUID-1030
fluid.inlineEdit.initTooltips = function (that) {
var tooltipOptions = {
content: that.options.tooltipText,
position: {
my: "left top",
at: "left bottom+25%", // add a 25% offset to keep the tooltip from overlapping the element it is for
// setting the "of" property to ensure that the tooltip is positioned relative to that.viewEl
// even when keyboard focus is on that.textEditButton
of: that.viewEl
},
target: "*",
delay: that.options.tooltipDelay,
styles: {
tooltip: that.options.styles.tooltip
}
};
fluid.tooltip(that.viewEl, tooltipOptions);
if (that.textEditButton) {
fluid.tooltip(that.textEditButton, tooltipOptions);
}
};
fluid.inlineEdit.calculateInitialPadding = function (viewEl) {
var padding = viewEl.css("padding-right");
return padding ? parseFloat(padding) : 0;
};
/**
* Set up and style the edit field. If an edit field is not provided,
* default markup is created for the edit field
*
* @param {String} editStyle - The default styling for the edit field.
* @param {Object} editField - The existing edit field.
* @param {Object} editFieldMarkup - The edit field markup provided by the integrator.
*
* @return {Object} The styled edit field.
*/
fluid.inlineEdit.setupEditField = function (editStyle, editField, editFieldMarkup) {
var eField = $(editField);
eField = eField.length ? eField : $(editFieldMarkup);
eField.addClass(editStyle);
return eField;
};
/**
* Set up the edit container and append the edit field to the container. If an edit container
* is not provided, default markup is created.
*
* @param {Object} displayContainer - The display mode container
* @param {Object} editField - The edit field that is to be appended to the edit container
* @param {Object} editContainer - The edit container markup provided by the integrator
* @param {Object} editContainerMarkup - The edit container markup provided by the integrator.
*
* @return {Object} The edit container containing the edit field
*/
fluid.inlineEdit.setupEditContainer = function (displayContainer, editField, editContainer, editContainerMarkup) {
var eContainer = $(editContainer);
eContainer = eContainer.length ? eContainer : $(editContainerMarkup);
displayContainer.after(eContainer);
eContainer.append(editField);
return eContainer;
};
/**
* Default renderer for the edit mode view.
*
* @param {Object} that - The component itself.
* @return {Object} An object containing:
* - container The edit container containing the edit field
* - field The styled edit field
*/
fluid.inlineEdit.defaultEditModeRenderer = function (that) {
var editField = fluid.inlineEdit.setupEditField(that.options.styles.edit, that.editField, that.options.markup.editField);
var editContainer = fluid.inlineEdit.setupEditContainer(that.displayModeRenderer, editField, that.editContainer, that.options.markup.editContainer);
var editModeInstruction = fluid.inlineEdit.setupEditModeInstruction(that.options.styles.editModeInstruction,
that.options.strings.editModeInstruction, that.options.markup.editModeInstruction);
var id = fluid.allocateSimpleId(editModeInstruction);
editField.attr("aria-describedby", id);
fluid.inlineEdit.positionEditModeInstruction(editModeInstruction, editContainer, editField);
// Package up the container and field for the component.
return {
container: editContainer,
field: editField
};
};
/** Configures the edit container and view, and uses the component's editModeRenderer to render
* the edit container.
*
* @param {Object} that - The component itself.
* @param {Boolean} lazyEditView - If true, will delay rendering of the edit container; Default is false
*/
fluid.inlineEdit.renderEditContainer = function (that, lazyEditView) {
that.editContainer = that.locate("editContainer");
that.editField = that.locate("edit");
if (that.editContainer.length !== 1) {
if (that.editContainer.length > 1) {
fluid.fail("InlineEdit did not find a unique container for selector " + that.options.selectors.editContainer + ": " + fluid.dumpEl(that.editContainer));
}
}
if (!lazyEditView) {
return;
} // do not invoke the renderer, unless this is the "final" effective time
var editElms = that.options.editModeRenderer(that);
if (editElms) {
that.editContainer = editElms.container;
that.editField = editElms.field;
}
};
/** Set up the edit mode instruction with aria in edit mode
* @param {String} editModeInstructionStyle - The default styling for the instruction
* @param {String} editModeInstructionText - The default instruction text
* @param {Object} editModeInstructionMarkup - The markup to modify.
* @return {jQuery} The displayed instruction in edit mode
*/
fluid.inlineEdit.setupEditModeInstruction = function (editModeInstructionStyle, editModeInstructionText, editModeInstructionMarkup) {
var editModeInstruction = $(editModeInstructionMarkup);
editModeInstruction.addClass(editModeInstructionStyle);
editModeInstruction.text(editModeInstructionText);
return editModeInstruction;
};
/**
* Positions the edit mode instruction directly beneath the edit container
*
* @param {Object} editModeInstruction - The displayed instruction in edit mode
* @param {Object} editContainer - The edit container in edit mode
* @param {Object} editField - The edit field in edit mode
*/
fluid.inlineEdit.positionEditModeInstruction = function (editModeInstruction, editContainer, editField) {
editContainer.append(editModeInstruction);
editField.focus(function () {
editModeInstruction.show();
var editFieldPosition = editField.offset();
// For FLUID-5980 (https://issues.fluidproject.org/browse/FLUID-5980)
//
// From the jQuery height docs (http://api.jquery.com/height/)
// "As of jQuery 1.8, this may require retrieving the CSS height plus
// box-sizing property and then subtracting any potential border and
// padding on each element when the element has box-sizing: border-box.
// To avoid this penalty, use .css( "height" ) rather than .height()."
var editFieldHeight = parseInt(editField.css("height"), 10);
editModeInstruction.css({left: editFieldPosition.left});
editModeInstruction.css({top: editFieldPosition.top + editFieldHeight + 5});
});
};
/**
* Set up and style the display mode container for the viewEl and the textEditButton
*
* @param {Object} styles - The default styling for the display mode container
* @param {Object} displayModeWrapper - The markup used to generate the display mode container
*
* @return {jQuery} The styled display mode container
*/
fluid.inlineEdit.setupDisplayModeContainer = function (styles, displayModeWrapper) {
var displayModeContainer = $(displayModeWrapper);
displayModeContainer = displayModeContainer.length ? displayModeContainer : $("<span></span>");
displayModeContainer.addClass(styles.displayView);
return displayModeContainer;
};
/** Retrieve the display text from the DOM.
* @param {Object} viewEl - The view element.
* @param {String} textStyle - The classes to apply to the view element.
* @return {jQuery} The view element.
*/
fluid.inlineEdit.setupDisplayText = function (viewEl, textStyle) {
/* Remove the display from the tab order to prevent users to think they
* are able to access the inline edit field, but they cannot since the
* keyboard event binding is only on the button.
*/
viewEl.attr("tabindex", "-1");
viewEl.addClass(textStyle);
return viewEl;
};
/**
* Set up the textEditButton. Append a background image with appropriate
* descriptive text to the button.
*
* @param {Object} that - The component itself.
* @param {Object} model - The model data.
* @return {jQuery} The accessible button located after the display text
*/
fluid.inlineEdit.setupTextEditButton = function (that, model) {
var opts = that.options;
var textEditButton = that.locate("textEditButton");
if (textEditButton.length === 0) {
var markup = $(that.options.markup.textEditButton);
markup.addClass(opts.styles.textEditButton);
markup.text(opts.tooltipText);
/**
* Set text for the button and listen
* for modelChanged to keep it updated
*/
fluid.inlineEdit.updateTextEditButton(markup, model.value || opts.strings.defaultViewText, opts.strings.textEditButton);
that.events.modelChanged.addListener(function () {
fluid.inlineEdit.updateTextEditButton(markup, model.value || opts.strings.defaultViewText, opts.strings.textEditButton);
});
that.locate("text").after(markup);
// Refresh the textEditButton with the newly appended options
textEditButton = that.locate("textEditButton");
}
return textEditButton;
};
/**
* Update the textEditButton text with the current value of the field.
*
* @param {Object} textEditButton - the textEditButton
* @param {String} value - The current value of the inline editable text
* @param {String} stringTemplate - The string template to use in producing the button text.
*/
fluid.inlineEdit.updateTextEditButton = function (textEditButton, value, stringTemplate) {
var buttonText = fluid.stringTemplate(stringTemplate, {
text: value
});
textEditButton.text(buttonText);
};
/**
* Bind mouse hover event handler to the display mode container.
*
* @param {Object} displayModeRenderer - The display mode container
* @param {String} invitationStyle - The default styling for the display mode container on mouse hover
*/
fluid.inlineEdit.bindHoverHandlers = function (displayModeRenderer, invitationStyle) {
var over = function () {
displayModeRenderer.addClass(invitationStyle);
};
var out = function () {
displayModeRenderer.removeClass(invitationStyle);
};
displayModeRenderer.hover(over, out);
};
/**
* Bind keyboard focus and blur event handlers to an element
*
* Note: This function is an unsupported, NON-API function
*
* @param {Object} element - The element to which the event handlers are bound
* @param {Object} displayModeRenderer - The display mode container
* @param {Object} styles - The default styling for the display mode container on mouse hover
* @param {Object} strings - String messages to use if there is no model value.
* @param {Object} model - Model data to display.
*/
fluid.inlineEdit.bindHighlightHandler = function (element, displayModeRenderer, styles, strings, model) {
element = $(element);
var makeFocusSwitcher = function (focusOn) {
return function () {
displayModeRenderer.toggleClass(styles.focus, focusOn);
displayModeRenderer.toggleClass(styles.invitation, focusOn);
if (!model || !model.value) {
displayModeRenderer.prevObject.text(focusOn ? strings.defaultFocussedViewText : strings.defaultViewText);
}
};
};
element.focus(makeFocusSwitcher(true));
element.blur(makeFocusSwitcher(false));
};
/**
* Bind mouse click handler to an element
*
* @param {Object} element - The element to which the event handler is bound
* @param {Object} edit - Function to invoke the edit mode
*
*/
fluid.inlineEdit.bindMouseHandlers = function (element, edit) {
element = $(element);
var triggerGuard = fluid.inlineEdit.makeEditTriggerGuard(element, edit);
element.click(function (e) {
triggerGuard(e);
return false;
});
};
/**
* Bind keyboard press handler to an element
*
* @param {Object} element - The element to which the event handler is bound
* @param {Object} edit - Function to invoke the edit mode
*
*/
fluid.inlineEdit.bindKeyboardHandlers = function (element, edit) {
element = $(element);
element.attr("role", "button");
var guard = fluid.inlineEdit.makeEditTriggerGuard(element, edit);
fluid.activatable(element, function (event) {
return guard(event);
});
};
/**
* Creates an event handler that will trigger the edit mode if caused by something other
* than standard HTML controls. The event handler will return false if entering edit mode.
*
* @param {Object} jElement - The element to trigger the edit mode
* @param {Object} edit - Function to invoke the edit mode
*
* @return {Function} The event handler function
*/
fluid.inlineEdit.makeEditTriggerGuard = function (jElement, edit) {
var element = fluid.unwrap(jElement);
return function (event) {
// FLUID-2017 - avoid triggering edit mode when operating standard HTML controls. Ultimately this
// might need to be extensible, in more complex authouring scenarios.
var outer = fluid.findAncestor(event.target, function (elem) {
if (/input|select|textarea|button|a/i.test(elem.nodeName) || elem === element) {
return true;
}
});
if (outer === element) {
edit();
return false;
}
};
};
/* Bind all user-facing event handlers required by the component */
fluid.inlineEdit.bindEventHandlers = function (that, edit, displayModeContainer) {
var styles = that.options.styles;
fluid.inlineEdit.bindHoverHandlers(displayModeContainer, styles.invitation);
fluid.inlineEdit.bindMouseHandlers(that.viewEl, edit);
fluid.inlineEdit.bindMouseHandlers(that.textEditButton, edit);
fluid.inlineEdit.bindKeyboardHandlers(that.textEditButton, edit);
fluid.inlineEdit.bindHighlightHandler(that.viewEl, displayModeContainer, that.options.styles, that.options.strings, that.model);
fluid.inlineEdit.bindHighlightHandler(that.textEditButton, displayModeContainer, that.options.styles, that.options.strings, that.model);
};
/** Render the display mode view.
*
* @param {Object} that - The component itself.
* @param {Object} edit - Function to invoke the edit mode
* @param {Object} model - Model data to display.
* @return {jQuery} The display container containing the display text and textEditbutton for display mode view.
*/
fluid.inlineEdit.defaultDisplayModeRenderer = function (that, edit, model) {
var styles = that.options.styles;
var displayModeWrapper = fluid.inlineEdit.setupDisplayModeContainer(styles);
var displayModeContainer = that.viewEl.wrap(displayModeWrapper).parent();
that.textEditButton = fluid.inlineEdit.setupTextEditButton(that, model);
displayModeContainer.append(that.textEditButton);
fluid.inlineEdit.bindEventHandlers(that, edit, displayModeContainer);
return displayModeContainer;
};
fluid.inlineEdit.getNodeName = function (element) {
return fluid.unwrap(element).nodeName.toLowerCase();
};
fluid.defaults("fluid.inlineEdit.standardAccessor", {
gradeNames: ["fluid.viewComponent"],
members: {
nodeName: {
expander: {
funcName: "fluid.inlineEdit.getNodeName",
args: "{that}.container"
}
}
},
invokers: {
value: {
funcName: "fluid.inlineEdit.standardAccessor.value",
args: ["{that}.nodeName", "{that}.container", "{arguments}.0"]
}
}
});
fluid.inlineEdit.standardAccessor.value = function (nodeName, element, newValue) {
return fluid[nodeName === "input" || nodeName === "textarea" ? "value" : "text"]($(element), newValue);
};
fluid.defaults("fluid.inlineEdit.standardDisplayView", {
gradeNames: ["fluid.viewComponent"],
invokers: {
refreshView: {
funcName: "fluid.inlineEdit.standardDisplayView.refreshView",
args: ["{fluid.inlineEdit}", "{that}.container", "{arguments}.0"]
}
}
});
fluid.inlineEdit.standardDisplayView.refreshView = function (componentThat) {
if (componentThat.model.value) {
fluid.inlineEdit.showEditedText(componentThat);
} else if (componentThat.options.strings.defaultViewText) {
fluid.inlineEdit.showDefaultViewText(componentThat);
} else {
fluid.inlineEdit.showNothing(componentThat);
}
// If necessary, pad the view element enough that it will be evident to the user.
if ($.trim(componentThat.viewEl.text()).length === 0) {
componentThat.viewEl.addClass(componentThat.options.styles.emptyDefaultViewText);
if (componentThat.existingPadding < componentThat.options.paddings.minimumView) {
componentThat.viewEl.css("padding-right", componentThat.options.paddings.minimumView);
}
}
};
fluid.defaults("fluid.inlineEdit.standardEditView", {
gradeNames: ["fluid.viewComponent"],
invokers: {
refreshView: {
funcName: "fluid.inlineEdit.standardEditView.refreshView",
args: ["{fluid.inlineEdit}", "{that}.container", "{arguments}.0"]
}
}
});
fluid.inlineEdit.standardEditView.refreshView = function (componentThat, editField, source) {
if (!source || (editField && editField.index(source) === -1)) {
componentThat.editView.value(componentThat.model.value);
}
};
fluid.inlineEdit.setup = function (that) {
// Hide the edit container to start
if (that.editContainer) {
that.editContainer.hide();
}
// Add tooltip handler if required and available
if (that.tooltipEnabled()) {
fluid.inlineEdit.initTooltips(that);
}
};
// TODO: Should really be part of a "collateral" or "shadow model"
fluid.inlineEdit.setIsEditing = function (that, state) {
that.isEditingState = state;
};
fluid.inlineEdit.tooltipEnabled = function (useTooltip) {
return useTooltip && $.fn.tooltip;
};
// Backwards compatibility for users of the 1.4.x and below Infusion API - new users are recommended to directly attach
// a "fluid.undo" as a subcomponent with appropriate configuration - express this using FLUID-5022 system when it is available
fluid.inlineEdit.processUndoDecorator = function (that) {
if (that.options.componentDecorators) {
var decorators = fluid.makeArray(that.options.componentDecorators);
var decorator = decorators[0];
if (typeof(decorator) === "string") {
decorator = {type: decorator};
}
if (decorator.type === "fluid.undoDecorator") {
fluid.set(that.options, ["components", "undo"], { type: "fluid.undo", options: decorator.options});
that.decorators = [ fluid.initDependent(that, "undo")];
}
}
};
/**
* Instantiates a new Inline Edit component
*
* @param {Object} componentContainer - a selector, jQuery, or a DOM element representing the component's container
* @param {Object} options - a collection of options settings
*/
fluid.defaults("fluid.inlineEdit", {
gradeNames: ["fluid.undoable", "fluid.viewComponent"],
mergePolicy: {
"strings.defaultViewText": "defaultViewText"
},
members: {
isEditingState: false,
viewEl: {
expander: {
funcName: "fluid.inlineEdit.setupDisplayText",
args: ["{that}.dom.text", "{that}.options.styles.text"]
}
},
existingPadding: {
expander: {
funcName: "fluid.inlineEdit.calculateInitialPadding",
args: "{that}.viewEl"
}
},
displayModeRenderer: {
expander: {
func: "{that}.options.displayModeRenderer",
args: ["{that}", "{that}.edit", "{that}.model"]
}
}
},
invokers: {
/** Switches to edit mode. */
edit: {
funcName: "fluid.inlineEdit.editHandler",
args: "{that}"
},
/** Determines if the component is currently in edit mode.
* @return true if edit mode shown, false if view mode is shown
*/
isEditing: {
funcName: "fluid.identity",
args: "{that}.isEditingState"
},
/** Finishes editing, switching back to view mode. */
finish: {
funcName: "fluid.inlineEdit.finish",
args: "{that}"
},
/** Cancels the in-progress edit and switches back to view mode */
cancel: {
funcName: "fluid.inlineEdit.cancel",
args: "{that}"
},
/** Determines if the tooltip feature is enabled.
* @return true if the tooltip feature is turned on, false if not
*/
tooltipEnabled: {
funcName: "fluid.inlineEdit.tooltipEnabled",
args: "{that}.options.useTooltip"
},
/** Updates the state of the inline editor in the DOM, based on changes that may have
* happened to the model.
* @param {Object} [source] - An optional source object identifying the source of the change (see ChangeApplier documentation)
*/
refreshView: {
funcName: "fluid.inlineEdit.refreshView",
args: ["{that}", "{arguments}.0"]
},
/** Pushes external changes to the model into the inline editor, refreshing its
* rendering in the DOM. The modelChanged event will fire.
* @param {String} newValue - The bare value of the model, that is, the string being edited
* @param {Object} [source] - An optional "source" (perhaps a DOM element) which triggered this event
*/
updateModelValue: {
funcName: "fluid.inlineEdit.updateModelValue",
args: ["{that}", "{arguments}.0", "{arguments}.1"] // newValue, source
},
/** Pushes external changes to the model into the inline editor, refreshing its
* rendering in the DOM. The modelChanged event will fire. This honours the "fluid.undoable" contract
* @param {Object} newValue - The full value of the new model, that is, a model object which contains the editable value as the element named "value"
* @param {Object} [source] - An optional "source" (perhaps a DOM element) which triggered this event
*/
updateModel: {
funcName: "fluid.inlineEdit.updateModelValue",
args: ["{that}", "{arguments}.0.value", "{arguments}.1"] // newModel, source
}
},
components: {
displayView: {
type: "{that}.options.displayView.type",
container: "{that}.viewEl",
options: {
gradeNames: "{fluid.inlineEdit}.options.displayAccessor.type"
}
},
editView: {
type: "{that}.options.editView.type",
createOnEvent: "onCreateEditView",
container: "{that}.editField",
options: {
gradeNames: "{fluid.inlineEdit}.options.editAccessor.type"
}
}
},
model: {
value: {
expander: { func: "{that}.displayView.value"}
}
},
selectors: {
text: ".flc-inlineEdit-text",
editContainer: ".flc-inlineEdit-editContainer",
edit: ".flc-inlineEdit-edit",
textEditButton: ".flc-inlineEdit-textEditButton"
},
styles: {
text: "fl-inlineEdit-text",
edit: "fl-inlineEdit-edit",
invitation: "fl-inlineEdit-invitation",
defaultViewStyle: "fl-inlineEdit-emptyText-invitation",
emptyDefaultViewText: "fl-inlineEdit-emptyDefaultViewText",
focus: "fl-inlineEdit-focus",
tooltip: "fl-inlineEdit-tooltip",
editModeInstruction: "fl-inlineEdit-editModeInstruction",
displayView: "fl-inlineEdit-simple-editableText fl-inlineEdit-textContainer",
textEditButton: "fl-hidden-accessible"
},
events: {
modelChanged: null,
onBeginEdit: "preventable",
afterBeginEdit: null,
onFinishEdit: "preventable",
afterFinishEdit: null,
afterInitEdit: null,
onCreateEditView: null
},
listeners: {
onCreate: [{
func: "{that}.refreshView"
}, {
funcName: "fluid.inlineEdit.initializeEditView",
args: ["{that}", true]
}, {
funcName: "fluid.inlineEdit.setup",
args: "{that}"
}, {
funcName: "fluid.inlineEdit.processUndoDecorator",
args: "{that}"
}],
onBeginEdit: {
funcName: "fluid.inlineEdit.setIsEditing",
args: ["{that}", true]
},
afterFinishEdit: {
funcName: "fluid.inlineEdit.setIsEditing",
args: ["{that}", false]
}
},
strings: {
textEditButton: "Edit text %text",
editModeInstruction: "Escape to cancel, Enter or Tab when finished",
defaultViewText: "Click here to edit", /* this will override the direct option */
defaultFocussedViewText: "Click here or press enter to edit"
},
markup: {
editField: "<input type='text' class='flc-inlineEdit-edit'/>",
editContainer: "<span></span>",
editModeInstruction: "<p></p>",
textEditButton: "<a href='#_' class='flc-inlineEdit-textEditButton'></a>"
},
paddings: {
edit: 10,
minimumEdit: 80,
minimumView: 60
},
applyEditPadding: true,
blurHandlerBinder: null,
// set this to true or false to cause unconditional submission, otherwise it will
// be inferred from the edit element tag type.
submitOnEnter: undefined,
modelComparator: null,
displayAccessor: {
type: "fluid.inlineEdit.standardAccessor"
},
displayView: {
type: "fluid.inlineEdit.standardDisplayView"
},
editAccessor: {
type: "fluid.inlineEdit.standardAccessor"
},
editView: {
type: "fluid.inlineEdit.standardEditView"
},
displayModeRenderer: fluid.inlineEdit.defaultDisplayModeRenderer,
editModeRenderer: fluid.inlineEdit.defaultEditModeRenderer,
lazyEditView: false,
/** View Mode Tooltip Settings **/
useTooltip: true,
// this is here for backwards API compatibility, but should be in the strings block
tooltipText: "Select or press Enter to edit",
tooltipDelay: 1000,
selectOnEdit: false
});
/*
* Creates a whole list of inline editors as subcomponents of the supplied component
*/
fluid.setupInlineEdits = function (that, editables) {
// TODO: create useful framework for automated construction of component definitions, possibly using Model Transformation - FLUID-5022
return fluid.transform(editables, function (editable, i) {
var componentDef = {
type: "fluid.inlineEdit",
container: editable
};
var name = "inlineEdit-" + i;
fluid.set(that.options, ["components", name], componentDef);
return fluid.initDependent(that, name);
});
};
fluid.defaults("fluid.inlineEditsComponent", {
gradeNames: ["fluid.viewComponent"],
distributeOptions: {
source: "{that}.options",
// TODO: Appalling requirement to evade FLUID-5887 check - otherwise all of this fluid.modelComponent material is broadcast down to each component.
// "source" distributions are silly and dangerous in any case, but they have become fairly widely used, together with the expectation that the
// material from "defaults" can be broadcast too. But clearly material that is from base grade defaults is unwelcome to be distributed.
// This seems to imply that we've got no option but to start supporting "provenance" in options and defaults - highly expensive.
exclusions: ["members.inlineEdits", "members.modelRelay", "members.applier", "members.model", "selectors.editables", "events"],
removeSource: true,
target: "{that > fluid.inlineEdit}.options"
},
members: {
inlineEdits: {
expander: {
funcName: "fluid.setupInlineEdits",
args: ["{that}", "{that}.dom.editables"]
}
}
},
selectors: {
editables: ".flc-inlineEditable"
}
});
fluid.inlineEdits = function (container, options) {
var that = fluid.inlineEditsComponent(container, options);
return that.inlineEdits;
};
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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 CKEDITOR, tinyMCE */
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
/*************************************
* Shared Rich Text Editor functions *
*************************************/
fluid.defaults("fluid.inlineEdit.editorViewAccessor", {
gradeNames: ["fluid.viewComponent"],
invokers: {
value: {
funcName: "fluid.inlineEdit.editorViewAccessor.value",
args: ["{that}.container", "{that}.options", "{arguments}.0"]
}
}
});
fluid.inlineEdit.editorViewAccessor.value = function (editField, options, newValue) {
var editor = options.editorGetFn(editField);
if (!editor || editor.length === 0) {
if (newValue !== undefined) {
$(editField).val(newValue);
}
return "";
}
if (newValue !== undefined) {
options.setValueFn(editField, editor, newValue);
} else {
return options.getValueFn(editor);
}
};
fluid.defaults("fluid.inlineEdit.richTextViewAccessor", {
gradeNames: ["fluid.viewComponent"],
invokers: {
value: {
funcName: "fluid.inlineEdit.richTextViewAccessor.value",
args: ["{that}.container", "{arguments}.0"]
}
}
});
fluid.inlineEdit.richTextViewAccessor.value = function (element, newValue) {
return fluid.html(element, newValue);
};
fluid.inlineEdit.normalizeHTML = function (value) {
var togo = $.trim(value.replace(/\s+/g, " "));
togo = togo.replace(/\s+<\//g, "</");
togo = togo.replace(/<([a-z0-9A-Z\/]+)>/g, function (match) {
return match.toLowerCase();
});
return togo;
};
fluid.inlineEdit.htmlComparator = function (el1, el2) {
return fluid.inlineEdit.normalizeHTML(el1) === fluid.inlineEdit.normalizeHTML(el2);
};
fluid.inlineEdit.bindRichTextHighlightHandler = function (element, displayModeRenderer, invitationStyle) {
element = $(element);
var focusOn = function () {
displayModeRenderer.addClass(invitationStyle);
};
var focusOff = function () {
displayModeRenderer.removeClass(invitationStyle);
};
element.focus(focusOn);
element.blur(focusOff);
};
fluid.inlineEdit.setupRichTextEditButton = function (that) {
var opts = that.options;
var textEditButton = that.locate("textEditButton");
if (textEditButton.length === 0) {
var markup = $("<a href='#_' class='flc-inlineEdit-textEditButton'></a>");
markup.text(opts.strings.textEditButton);
that.locate("text").after(markup);
// Refresh the textEditButton with the newly appended options
textEditButton = that.locate("textEditButton");
}
return textEditButton;
};
/*
* Wrap the display text and the textEditButton with the display mode container
* for better style control.
*/
fluid.inlineEdit.richTextDisplayModeRenderer = function (that, edit) {
var styles = that.options.styles;
var displayModeWrapper = fluid.inlineEdit.setupDisplayModeContainer(styles);
var displayModeRenderer = that.viewEl.wrap(displayModeWrapper).parent();
that.textEditButton = fluid.inlineEdit.setupRichTextEditButton(that);
displayModeRenderer.append(that.textEditButton);
displayModeRenderer.addClass(styles.focus);
// Add event handlers.
fluid.inlineEdit.bindHoverHandlers(displayModeRenderer, styles.invitation);
fluid.inlineEdit.bindMouseHandlers(that.textEditButton, edit);
fluid.inlineEdit.bindKeyboardHandlers(that.textEditButton, edit);
fluid.inlineEdit.bindRichTextHighlightHandler(that.viewEl, displayModeRenderer, styles.invitation);
fluid.inlineEdit.bindRichTextHighlightHandler(that.textEditButton, displayModeRenderer, styles.invitation);
return displayModeRenderer;
};
/************************
* Tiny MCE Integration *
************************/
var flTinyMCE = fluid.registerNamespace("fluid.inlineEdit.tinyMCE");
fluid.inlineEdit.tinyMCE.getEditor = function (editField) {
return tinyMCE.get(editField.prop("id"));
};
fluid.inlineEdit.tinyMCE.setValue = function (editField, editor, value) {
// without this, there is an intermittent race condition if the editor has been created on this event.
$(editField).val(value);
editor.setContent(value, {format : "raw"});
};
fluid.inlineEdit.tinyMCE.getValue = function (editor) {
return editor.getContent();
};
fluid.defaults("fluid.inlineEdit.tinyMCE.viewAccessor", {
gradeNames: ["fluid.inlineEdit.editorViewAccessor"],
editorGetFn: flTinyMCE.getEditor,
setValueFn: flTinyMCE.setValue,
getValueFn: flTinyMCE.getValue
});
fluid.inlineEdit.tinyMCE.blurHandlerBinder = function (that) {
function focusEditor(editor) {
setTimeout(function () {
tinyMCE.execCommand("mceFocus", false, that.editField[0].id);
editor.selection.select(editor.getBody(), 1);
editor.selection.collapse(0);
}, 10);
}
that.events.afterInitEdit.addListener(function (editor) {
focusEditor(editor);
var editorBody = editor.getBody();
// NB - this section has no effect - on most browsers no focus events
// are delivered to the actual body - however, on recent TinyMCE, the
// "focusEditor" call DOES deliver a blur which causes FLUID-4681
that.deadMansBlur = fluid.deadMansBlur(that.editField, {
cancelByDefault: true,
exclusions: {body: $(editorBody), container: that.container},
handler: function () {
that[that.options.onBlur]();
}
});
});
that.events.afterBeginEdit.addListener(function () {
var editor = tinyMCE.get(that.editField[0].id);
if (editor) {
focusEditor(editor);
}
if (that.deadMansBlur) {
that.deadMansBlur.reArm();
}
});
that.events.afterFinishEdit.addListener(function () {
that.deadMansBlur.noteProceeded();
});
};
fluid.inlineEdit.tinyMCE.editModeRenderer = function (that) {
var options = that.options.tinyMCE;
options.elements = fluid.allocateSimpleId(that.editField);
var oldinit = options.init_instance_callback;
options.init_instance_callback = function (instance) {
that.events.afterInitEdit.fire(instance);
if (oldinit) {
oldinit();
}
};
// Ensure that instance creation is always asynchronous, to ensure that
// blurHandlerBinder always executes BEFORE instance is ready - so that
// its afterInitEdit listener is registered in time. All of this architecture
// is unsatisfactory, but can't be easily fixed until the whole component is
// migrated over to IoC with declarative listener registration.
setTimeout(function () {
tinyMCE.init(options);
}, 1);
};
/**
* Instantiate a rich-text InlineEdit component that uses an instance of TinyMCE.
*
* @param {Object} componentContainer - the element containing the inline editors
* @param {Object} options - configuration options for the components
*/
fluid.defaults("fluid.inlineEdit.tinyMCE", {
gradeNames: ["fluid.inlineEdit"],
tinyMCE : {
mode: "exact",
theme: "simple"
},
listeners: {
onCreate: {
"this": "tinyMCE",
method: "init",
namespace: "initTinyMCE",
args: "{that}.options.tinyMCE"
}
},
useTooltip: true,
selectors: {
edit: "textarea"
},
styles: {
invitation: "fl-inlineEdit-richText-invitation",
displayView: "fl-inlineEdit-textContainer",
text: ""
},
strings: {
textEditButton: "Edit"
},
displayAccessor: {
type: "fluid.inlineEdit.richTextViewAccessor"
},
editAccessor: {
type: "fluid.inlineEdit.tinyMCE.viewAccessor"
},
lazyEditView: true,
defaultViewText: "Click Edit",
modelComparator: fluid.inlineEdit.htmlComparator,
onBlur: "finish",
blurHandlerBinder: fluid.inlineEdit.tinyMCE.blurHandlerBinder,
displayModeRenderer: fluid.inlineEdit.richTextDisplayModeRenderer,
editModeRenderer: fluid.inlineEdit.tinyMCE.editModeRenderer
});
/****************************
* CKEditor 3.x Integration *
****************************/
var flCKEditor = fluid.registerNamespace("fluid.inlineEdit.CKEditor");
fluid.inlineEdit.CKEditor.getEditor = function (editField) {
return CKEDITOR.instances[editField.prop("id")];
};
fluid.inlineEdit.CKEditor.setValue = function (editField, editor, value) {
editor.setData(value);
};
fluid.inlineEdit.CKEditor.getValue = function (editor) {
return editor.getData();
};
fluid.defaults("fluid.inlineEdit.CKEditor.viewAccessor", {
gradeNames: ["fluid.inlineEdit.editorViewAccessor"],
editorGetFn: flCKEditor.getEditor,
setValueFn: flCKEditor.setValue,
getValueFn: flCKEditor.getValue
});
fluid.inlineEdit.CKEditor.focus = function (editor) {
setTimeout(function () {
// CKEditor won't focus itself except in a timeout.
editor.focus();
}, 0);
};
// Special hacked HTML normalisation for CKEditor which spuriously inserts whitespace
// just after the first opening tag
fluid.inlineEdit.CKEditor.normalizeHTML = function (value) {
var togo = fluid.inlineEdit.normalizeHTML(value);
var angpos = togo.indexOf(">");
if (angpos !== -1 && angpos < togo.length - 1) {
if (togo.charAt(angpos + 1) !== " ") {
togo = togo.substring(0, angpos + 1) + " " + togo.substring(angpos + 1);
}
}
return togo;
};
fluid.inlineEdit.CKEditor.htmlComparator = function (el1, el2) {
return fluid.inlineEdit.CKEditor.normalizeHTML(el1) ===
fluid.inlineEdit.CKEditor.normalizeHTML(el2);
};
fluid.inlineEdit.CKEditor.blurHandlerBinder = function (that) {
that.events.afterInitEdit.addListener(fluid.inlineEdit.CKEditor.focus);
that.events.afterBeginEdit.addListener(function () {
var editor = fluid.inlineEdit.CKEditor.getEditor(that.editField);
if (editor) {
fluid.inlineEdit.CKEditor.focus(editor);
}
});
};
fluid.inlineEdit.CKEditor.editModeRenderer = function (that) {
var id = fluid.allocateSimpleId(that.editField);
$.data(fluid.unwrap(that.editField), "fluid.inlineEdit.CKEditor", that);
var editor = CKEDITOR.replace(id, that.options.CKEditor);
editor.on("instanceReady", function (e) {
fluid.inlineEdit.CKEditor.focus(e.editor);
that.events.afterInitEdit.fire(e.editor);
});
};
fluid.defaults("fluid.inlineEdit.CKEditor", {
gradeNames: ["fluid.inlineEdit"],
selectors: {
edit: "textarea"
},
styles: {
invitation: "fl-inlineEdit-richText-invitation",
displayView: "fl-inlineEdit-textContainer",
text: ""
},
strings: {
textEditButton: "Edit"
},
displayAccessor: {
type: "fluid.inlineEdit.richTextViewAccessor"
},
editAccessor: {
type: "fluid.inlineEdit.CKEditor.viewAccessor"
},
lazyEditView: true,
defaultViewText: "Click Edit",
modelComparator: fluid.inlineEdit.CKEditor.htmlComparator,
blurHandlerBinder: fluid.inlineEdit.CKEditor.blurHandlerBinder,
displayModeRenderer: fluid.inlineEdit.richTextDisplayModeRenderer,
editModeRenderer: fluid.inlineEdit.CKEditor.editModeRenderer,
CKEditor: {
// CKEditor-specific configuration goes here.
}
});
/************************
* Dropdown Integration *
************************/
fluid.registerNamespace("fluid.inlineEdit.dropdown");
fluid.inlineEdit.dropdown.editModeRenderer = function (that) {
fluid.allocateSimpleId(that.editField);
that.editField.selectbox({
finishHandler: function () {
that.finish();
}
});
return {
container: that.editContainer,
field: $("input.selectbox", that.editContainer)
};
};
fluid.inlineEdit.dropdown.blurHandlerBinder = function (that) {
fluid.deadMansBlur(that.editField, {
exclusions: {selectBox: $("div.selectbox-wrapper", that.editContainer)},
handler: function () {
that.cancel();
}
});
};
/**
* Instantiate a drop-down InlineEdit component
*
* @param {Object} container - The container for this component.
* @param {Object} options - The component options.
*/
fluid.defaults("fluid.inlineEdit.dropdown", {
gradeNames: ["fluid.inlineEdit"],
applyEditPadding: false,
blurHandlerBinder: fluid.inlineEdit.dropdown.blurHandlerBinder,
editModeRenderer: fluid.inlineEdit.dropdown.editModeRenderer
});
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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 speechSynthesis, SpeechSynthesisUtterance*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
/*********************************************************************************************
* fluid.window is a singleton component to be used for registering event bindings to *
* events fired by the window object *
*********************************************************************************************/
fluid.defaults("fluid.window", {
gradeNames: ["fluid.component", "fluid.resolveRootSingle"],
singleRootType: "fluid.window",
members: {
window: window
},
listeners: {
"onCreate.bindEvents": {
funcName: "fluid.window.bindEvents",
args: ["{that}"]
}
}
});
/**
* Adds a lister to a window event for each event defined on the component.
* The name must match a valid window event.
*
* @param {Component} that - an instance of `fluid.window`
*/
fluid.window.bindEvents = function (that) {
fluid.each(that.options.events, function (type, eventName) {
window.addEventListener(eventName, that.events[eventName].fire);
});
};
/*********************************************************************************************
* fluid.textToSpeech provides a wrapper around the SpeechSynthesis Interface *
* from the Web Speech API ( https://w3c.github.io/speech-api/speechapi.html#tts-section ) *
*********************************************************************************************/
fluid.registerNamespace("fluid.textToSpeech");
fluid.textToSpeech.isSupported = function () {
return !!(window && window.speechSynthesis);
};
/*********************************************************************************************
* fluid.textToSpeech component
*********************************************************************************************/
fluid.defaults("fluid.textToSpeech", {
gradeNames: ["fluid.modelComponent", "fluid.resolveRootSingle"],
singleRootType: "fluid.textToSpeech",
events: {
onStart: null,
onStop: null,
onError: null,
onSpeechQueued: null,
utteranceOnBoundary: null,
utteranceOnEnd: null,
utteranceOnError: null,
utteranceOnMark: null,
utteranceOnPause: null,
utteranceOnResume: null,
utteranceOnStart: null
},
members: {
queue: []
},
components: {
wndw: {
type: "fluid.window",
options: {
events: {
beforeunload: null
}
}
}
},
dynamicComponents: {
utterance: {
type: "fluid.textToSpeech.utterance",
createOnEvent: "onSpeechQueued",
options: {
listeners: {
"onBoundary.relay": "{textToSpeech}.events.utteranceOnBoundary.fire",
"onEnd.relay": {
listener: "{textToSpeech}.events.utteranceOnEnd.fire",
priority: "before:resolvePromise"
},
"onError.relay": {
listener: "{textToSpeech}.events.utteranceOnError.fire",
priority: "before:rejectPromise"
},
"onMark.relay": "{textToSpeech}.events.utteranceOnMark.fire",
"onPause.relay": "{textToSpeech}.events.utteranceOnPause.fire",
"onResume.relay": "{textToSpeech}.events.utteranceOnResume.fire",
"onStart.relay": "{textToSpeech}.events.utteranceOnStart.fire",
"onCreate.followPromise": {
funcName: "fluid.promise.follow",
args: ["{that}.promise", "{that}.options.onSpeechQueuePromise"]
},
"onCreate.queue": {
"this": "{fluid.textToSpeech}.queue",
method: "push",
args: ["{that}"],
priority: "after:followPromise"
},
"onCreate.speak": {
listener: "{textToSpeech}.speak",
args: ["{that}.utterance"],
priority: "after:queue"
},
"onEnd.destroy": {
func: "{that}.destroy",
priority: "last"
}
},
onSpeechQueuePromise: "{arguments}.2",
utterance: "{arguments}.0"
}
}
},
// Model paths: speaking, pending, paused, utteranceOpts, pauseRequested, resumeRequested
model: {
// Changes to the utteranceOpts will only affect text that is queued after the change.
// All of these options can be overridden in the queueSpeech method by passing in
// options directly there. It is useful in cases where a single instance needs to be
// spoken with different options (e.g. single text in a different language.)
utteranceOpts: {
// text: "", // text to synthesize. Avoid using, it will be overwritten by text passed in directly to a queueSpeech
// lang: "", // the language of the synthesized text
// voice: {} // a WebSpeechSynthesis object; if not set, will use the default one provided by the browser
// volume: 1, // a Floating point number between 0 and 1
// rate: 1, // a Floating point number from 0.1 to 10 although different synthesizers may have a smaller range
// pitch: 1, // a Floating point number from 0 to 2
}
},
modelListeners: {
"speaking": {
listener: "fluid.textToSpeech.toggleSpeak",
args: ["{that}", "{change}.value"]
},
"pauseRequested": {
listener: "fluid.textToSpeech.requestControl",
args: ["{that}", "pause", "{change}"]
},
"resumeRequested": {
listener: "fluid.textToSpeech.requestControl",
args: ["{that}", "resume", "{change}"]
}
},
invokers: {
queueSpeech: {
funcName: "fluid.textToSpeech.queueSpeech",
args: ["{that}", "{arguments}.0", "{arguments}.1", "{arguments}.2"]
},
queueSpeechSequence: {
funcName: "fluid.textToSpeech.queueSpeechSequence",
args: ["{that}", "{arguments}.0", "{arguments}.1"]
},
cancel: {
funcName: "fluid.textToSpeech.cancel",
args: ["{that}"]
},
pause: {
changePath: "pauseRequested",
value: true,
source: "pause"
},
resume: {
changePath: "resumeRequested",
value: true,
source: "resume"
},
getVoices: {
func: "{that}.invokeSpeechSynthesisFunc",
args: ["getVoices"]
},
speak: {
func: "{that}.invokeSpeechSynthesisFunc",
args: ["speak", "{arguments}.0"]
},
invokeSpeechSynthesisFunc: "fluid.textToSpeech.invokeSpeechSynthesisFunc"
},
listeners: {
"utteranceOnStart.speaking": {
changePath: "speaking",
value: true,
source: "utteranceOnStart"
},
"utteranceOnEnd.stop": {
funcName: "fluid.textToSpeech.handleEnd",
args: ["{that}"]
},
"utteranceOnError.forward": "{that}.events.onError",
"utteranceOnPause.pause": {
changePath: "paused",
value: true,
source: "utteranceOnPause"
},
"utteranceOnResume.resume": {
changePath: "paused",
value: false,
source: "utteranceOnResume"
},
"onDestroy.cleanup": {
func: "{that}.invokeSpeechSynthesisFunc",
args: ["cancel"]
},
"{wndw}.events.beforeunload": {
funcName: "{that}.invokeSpeechSynthesisFunc",
args: ["cancel"],
namespace: "cancelSpeechSynthesisOnUnload"
}
}
});
/**
* Wraps the SpeechSynthesis API
*
* @param {String} method - a SpeechSynthesis method name
* @param {Array} args - arguments to call the method with. If args isn't an array, it will be added as the first
* element of one.
*/
fluid.textToSpeech.invokeSpeechSynthesisFunc = function (method, args) {
args = fluid.makeArray(args);
speechSynthesis[method].apply(speechSynthesis, args);
};
fluid.textToSpeech.toggleSpeak = function (that, speaking) {
that.events[speaking ? "onStart" : "onStop"].fire();
};
fluid.textToSpeech.requestControl = function (that, control, change) {
// If there's a control request (value change to true), clear and
// execute it
if (change.value) {
that.applier.change(change.path, false, "ADD", "requestControl");
that.invokeSpeechSynthesisFunc(control);
}
};
/*
* After an utterance has finished, the utterance is removed from the queue and the model is updated as needed.
*/
fluid.textToSpeech.handleEnd = function (that) {
that.queue.shift();
var resetValues = {
speaking: false,
pending: false,
paused: false
};
if (that.queue.length) {
that.applier.change("pending", true, "ADD", "handleEnd.pending");
} else if (!that.queue.length) {
var newModel = $.extend({}, that.model, resetValues);
that.applier.change("", newModel, "ADD", "handleEnd.reset");
}
};
/**
* Options to configure the SpeechSynthesis Utterance with.
* See: https://w3c.github.io/speech-api/speechapi.html#utterance-attributes
*
* @typedef {Object} UtteranceOpts
* @property {String} text - The text to Synthesize
* @property {String} lang - The BCP 47 language code for the synthesized text
* @property {WebSpeechSynthesis} voice - If not set, will use the default one provided by the browser
* @property {Float} volume - A Floating point number between 0 and 1
* @property {Float} rate - A Floating point number from 0.1 to 10 although different synthesizers may have a smaller range
* @property {Float} pitch - A Floating point number from 0 to 2
*/
/**
* Assembles the utterance options and fires onSpeechQueued which will kick off the creation of an utterance
* component. If "interrupt" is true, this utterance will replace any existing ones.
*
* @param {fluid.textToSpeech} that - an instance of the component
* @param {String} text - the text to be synthesized
* @param {Boolean} interrupt - used to indicate if this text should be queued or replace existing utterances
* @param {UtteranceOpts} options - options to configure the {SpeechSynthesisUtterance} with. It is merged on top of
* the `utteranceOpts` from the component's model.
*
* @return {Promise} - returns a promise that is resolved/rejected from the related `fluid.textToSpeech.utterance`
* instance.
*/
fluid.textToSpeech.queueSpeech = function (that, text, interrupt, options) {
var promise = fluid.promise();
if (interrupt) {
that.cancel();
}
var utteranceOpts = $.extend({}, that.model.utteranceOpts, options, {text: text});
// The setTimeout is needed for Safari to fully cancel out the previous speech.
// Without this the synthesizer gets confused and may play multiple utterances at once.
setTimeout(function () {
that.events.onSpeechQueued.fire(utteranceOpts, interrupt, promise);
}, 100);
return promise;
};
/**
* Values to configure the SpeechSynthesis Utterance with.
* See: https://w3c.github.io/speech-api/speechapi.html#utterance-attributes
*
* @typedef {Object} Speech
* @property {String} text - the text to Synthesize
* @property {UtteranceOpts} options - options to configure the {SpeechSynthesisUtterance} with. It is merged on top
* of the `utteranceOpts` from the component's model.
*/
/**
* Queues a {Speech[]}, calling `that.queueSpeech` for each. This is useful for sets of text that should be
* synthesized with differing {UtteranceOpts}, but still treated as an atomic unit. For example, if a set of text
* includes words from different languages.
*
* @param {fluid.textToSpeech} that - an instance of the component
* @param {Speech[]} speeches - the set of text to queue as a unit
* @param {Boolean} interrupt - used to indicate if the related text should be queued or replace existing
* utterances
*
* @return {Promise} - returns a promise that is resolved/rejected after all of the speeches have finish or any
* have been rejected.
*/
fluid.textToSpeech.queueSpeechSequence = function (that, speeches, interrupt) {
var sequence = fluid.transform(speeches, function (speech, index) {
var toInterrupt = interrupt && !index; // only interrupt on the first string
return that.queueSpeech(speech.text, toInterrupt, speech.options);
});
return fluid.promise.sequence(sequence);
};
/**
* Manually fires the `onEnd` event of each remaining `fluid.textToSpeech.utterance` component in the queue. This
* is required because if the SpeechSynthesis is cancelled remaining {SpeechSynthesisUtterance} are ignored and do
* not fire their `onend` event.
*
* @param {fluid.textToSpeech} that - an instance of the component
*/
fluid.textToSpeech.cancel = function (that) {
// Safari does not fire the onend event from an utterance when the speech synthesis is cancelled.
// Manually triggering the onEnd event for each utterance as we empty the queue, before calling cancel.
while (that.queue.length) {
var utterance = that.queue[0];
utterance.events.onEnd.fire();
}
that.invokeSpeechSynthesisFunc("cancel");
// clear any paused state.
that.invokeSpeechSynthesisFunc("resume");
};
/*********************************************************************************************
* fluid.textToSpeech.utterance component
*********************************************************************************************/
fluid.defaults("fluid.textToSpeech.utterance", {
gradeNames: ["fluid.modelComponent"],
members: {
utterance: {
expander: {
funcName: "fluid.textToSpeech.utterance.construct",
args: ["{that}", "{that}.options.utteranceEventMap", "{that}.options.utterance"]
}
},
promise: {
expander: {
funcName: "fluid.promise"
}
}
},
model: {
boundary: 0
},
utterance: {
// text: "", // text to synthesize. avoid as it will override any other text passed in
// lang: "", // the language of the synthesized text
// voice: {} // a WebSpeechSynthesis object; if not set, will use the default one provided by the browser
// volume: 1, // a Floating point number between 0 and 1
// rate: 1, // a Floating point number from 0.1 to 10 although different synthesizers may have a smaller range
// pitch: 1, // a Floating point number from 0 to 2
},
utteranceEventMap: {
onboundary: "onBoundary",
onend: "onEnd",
onerror: "onError",
onmark: "onMark",
onpause: "onPause",
onresume: "onResume",
onstart: "onStart"
},
events: {
onBoundary: null,
onEnd: null,
onError: null,
onMark: null,
onPause: null,
onResume: null,
onStart: null
},
listeners: {
"onBoundary.updateModel": {
changePath: "boundary",
value: "{arguments}.0.charIndex"
},
"onEnd.resolvePromise": "{that}.promise.resolve",
"onError.rejectPromise": "{that}.promise.reject"
}
});
/**
* Creates a SpeechSynthesisUtterance instance and configures it with the utteranceOpts and utteranceMap. For any
* event provided in the utteranceEventMap, any corresponding event binding passed in directly through the
* utteranceOpts will be rebound as component event listeners with the "external" namespace.
*
* @param {fluid.textToSpeech.utterance} that - an instance of the component
* @param {Object} utteranceEventMap - a mapping from {SpeechSynthesisUtterance} events to component events.
* @param {UtteranceOpts} utteranceOpts - options to configure the {SpeechSynthesisUtterance} with.
*
* @return {SpeechSynthesisUtterance} - returns the created {SpeechSynthesisUtterance} object
*/
fluid.textToSpeech.utterance.construct = function (that, utteranceEventMap, utteranceOpts) {
var utterance = new SpeechSynthesisUtterance();
$.extend(utterance, utteranceOpts);
fluid.each(utteranceEventMap, function (compEventName, utteranceEvent) {
var compEvent = that.events[compEventName];
var origHandler = utteranceOpts[utteranceEvent];
utterance[utteranceEvent] = compEvent.fire;
if (origHandler) {
compEvent.addListener(origHandler, "external");
}
});
return utterance;
};
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
/**********************************************
* fluid.orator
*
* A component for self voicing a web page
**********************************************/
fluid.defaults("fluid.orator", {
gradeNames: ["fluid.viewComponent"],
selectors: {
controller: ".flc-orator-controller",
content: ".flc-orator-content"
},
model: {
enabled: true,
play: false
},
components: {
tts: {
type: "fluid.textToSpeech"
},
controller: {
type: "fluid.orator.controller",
options: {
parentContainer: "{orator}.container",
model: {
playing: "{orator}.model.play",
enabled: "{orator}.model.enabled"
}
}
},
selectionReader: {
type: "fluid.orator.selectionReader",
container: "{that}.container",
options: {
model: {
enabled: "{orator}.model.enabled"
}
}
},
domReader: {
type: "fluid.orator.domReader",
container: "{that}.dom.content",
options: {
model: {
tts: {
enabled: "{orator}.model.enabled"
}
},
listeners: {
"onStop.domReaderStop": {
changePath: "{orator}.model.play",
value: false,
source: "domReader.onStop",
priority: "after:removeHighlight"
}
},
modelListeners: {
"{orator}.model.play": {
funcName: "fluid.orator.handlePlayToggle",
args: ["{that}", "{change}.value"],
namespace: "domReader.handlePlayToggle"
}
}
}
}
},
modelListeners: {
"enabled": {
listener: "fluid.orator.cancelWhenDisabled",
args: ["{tts}.cancel", "{change}.value"],
namespace: "orator.clearSpeech"
}
},
distributeOptions: [{
source: "{that}.options.tts",
target: "{that tts}.options",
removeSource: true,
namespace: "ttsOpts"
}, {
source: "{that}.options.controller",
target: "{that controller}.options",
removeSource: true,
namespace: "controllerOpts"
}, {
source: "{that}.options.domReader",
target: "{that domReader}.options",
removeSource: true,
namespace: "domReaderOpts"
}, {
source: "{that}.options.selectionReader",
target: "{that selectionReader}.options",
removeSource: true,
namespace: "selectionReaderOpts"
}]
});
// TODO: When https://issues.fluidproject.org/browse/FLUID-6393 has been addressed, it will be possible to remove
// this function and directly configure the modelListener to only trigger when a false value is passed.
fluid.orator.cancelWhenDisabled = function (cancelFn, state) {
if (!state) {
cancelFn();
}
};
fluid.orator.handlePlayToggle = function (that, state) {
if (state) {
that.play();
} else {
that.pause();
}
};
/**********************************************
* fluid.orator.controller
*
* Provides a UI Widget to control the Orator
**********************************************/
fluid.defaults("fluid.orator.controller", {
gradeNames: ["fluid.containerRenderingView"],
selectors: {
playToggle: ".flc-orator-controller-playToggle"
},
styles: {
play: "fl-orator-controller-play"
},
strings: {
play: "play",
pause: "pause"
},
model: {
playing: false,
enabled: true
},
injectionType: "prepend",
markup: {
container: "<div class=\"flc-orator-controller fl-orator-controller\">" +
"<div class=\"fl-icon-orator\" aria-hidden=\"true\"></div>" +
"<button class=\"flc-orator-controller-playToggle\">" +
"<span class=\"fl-orator-controller-playToggle fl-icon-orator-playToggle\" aria-hidden=\"true\"></span>" +
"</button></div>"
},
invokers: {
play: {
changePath: "playing",
value: true,
source: "play"
},
pause: {
changePath: "playing",
value: false,
source: "pause"
},
toggle: {
funcName: "fluid.orator.controller.toggleState",
args: ["{that}", "{arguments}.0", "{arguments}.1"]
}
},
listeners: {
"onCreate.bindClick": {
listener: "fluid.orator.controller.bindClick",
args: ["{that}"]
}
},
modelListeners: {
"playing": {
listener: "fluid.orator.controller.setToggleView",
args: ["{that}", "{change}.value"]
},
"enabled": {
"this": "{that}.container",
method: "toggle",
args: ["{change}.value"],
namespace: "toggleView"
}
}
});
/**
* Binds the click event for the "playToggle" element to trigger the `that.toggle` method.
* This is not bound declaratively to ensure that the correct arguments are passed along to the `that.toggle`
* method.
*
* @param {fluid.orator.controller} that - an instance of the component
*/
fluid.orator.controller.bindClick = function (that) {
that.locate("playToggle").click(function () {
that.toggle("playing");
});
};
/**
* Used to toggle the state of a model value at a specified path. The new state will be the inverse of the current
* boolean value at the specified model path, or can be set explicitly by passing in a `state` value. It's likely
* that this method will be used in conjunction with a click handler. In that case, it's most likely that the state
* will be toggling the existing model value.
*
* @param {fluid.orator.controller} that - an instance of the component
* @param {String|Array} path - the path, into the model, for the value to toggle
* @param {Boolean} state - (optional) explicit state to set the model value to
*/
fluid.orator.controller.toggleState = function (that, path, state) {
var newState = fluid.isValue(state) ? state : !fluid.get(that.model, path);
// the !! ensures that the newState is a boolean value.
that.applier.change(path, !!newState, "ADD", "toggleState");
};
/**
* Sets the view state of the toggle controller.
* True - play style added
* - aria-label set to the `pause` string
* False - play style removed
* - aria-label set to the `play` string
*
* @param {fluid.orator.controller} that - an instance of the component
* @param {Boolean} state - the state to set the controller to
*/
fluid.orator.controller.setToggleView = function (that, state) {
var playToggle = that.locate("playToggle");
playToggle.toggleClass(that.options.styles.play, state);
playToggle.attr({
"aria-label": that.options.strings[state ? "pause" : "play"]
});
};
/*******************************************************************************
* fluid.orator.domReader
*
* Reads in text from a DOM element and voices it
*******************************************************************************/
fluid.defaults("fluid.orator.domReader", {
gradeNames: ["fluid.viewComponent"],
selectors: {
highlight: ".flc-orator-highlight"
},
markup: {
highlight: "<mark class=\"flc-orator-highlight fl-orator-highlight\"></mark>"
},
events: {
onQueueSpeech: null,
onReadFromDOM: null,
utteranceOnEnd: null,
utteranceOnBoundary: null,
utteranceOnError: null,
utteranceOnMark: null,
utteranceOnPause: null,
utteranceOnResume: null,
utteranceOnStart: null,
onStop: null
},
utteranceEventMap: {
onboundary: "utteranceOnBoundary",
onend: "utteranceOnEnd",
onerror: "utteranceOnError",
onmark:"utteranceOnMark",
onpause: "utteranceOnPause",
onresume: "utteranceOnResume",
onstart: "utteranceOnStart"
},
model: {
tts: {
paused: false,
speaking: false,
enabled: true
},
parseQueueIndex: 0,
parseIndex: null,
ttsBoundary: null,
parseQueueCount: 0,
parseItemCount: 0
},
modelRelay: [{
target: "parseIndex",
backward: "never",
excludeSource: ["utteranceOnPause"],
namespace: "getClosestIndex",
singleTransform: {
type: "fluid.transforms.free",
func: "fluid.orator.domReader.getClosestIndex",
args: ["{that}", "{that}.model.ttsBoundary", "{that}.model.parseQueueIndex"]
}
}],
members: {
parseQueue: []
},
components: {
parser: {
type: "fluid.textNodeParser",
options: {
listeners: {
"onParsedTextNode.addToParseQueue": "{domReader}.addToParseQueue"
}
}
}
},
invokers: {
parsedToString: "fluid.orator.domReader.parsedToString",
readFromDOM: {
funcName: "fluid.orator.domReader.readFromDOM",
args: ["{that}", "{that}.container"]
},
removeHighlight: {
funcName: "fluid.orator.domReader.unWrap",
args: ["{that}.dom.highlight"]
},
addToParseQueue: {
funcName: "fluid.orator.domReader.addToParseQueue",
args: ["{that}", "{arguments}.0"]
},
resetParseQueue: {
funcName: "fluid.orator.domReader.resetParseQueue",
args: ["{that}"]
},
highlight: {
funcName: "fluid.orator.domReader.highlight",
args: ["{that}"]
},
play: {
funcName: "fluid.orator.domReader.play",
args: ["{that}", "{fluid.textToSpeech}.resume"]
},
pause: {
funcName: "fluid.orator.domReader.pause",
args: ["{that}", "{fluid.textToSpeech}.pause"]
},
queueSpeech: {
funcName: "fluid.orator.domReader.queueSpeech",
args: ["{that}", "{arguments}.0", "{arguments}.1"]
},
isWord: "fluid.textNodeParser.isWord"
},
modelListeners: {
"parseIndex": {
listener: "{that}.highlight",
namespace: "highlight",
excludeSource: ["init", "utteranceOnEnd", "resetParseQueue"]
}
},
listeners: {
"onQueueSpeech.removeExtraWhiteSpace": "fluid.orator.domReader.removeExtraWhiteSpace",
"onQueueSpeech.queueSpeech": {
func: "{fluid.textToSpeech}.queueSpeech",
args: ["{arguments}.0", "{arguments}.1.interrupt", "{arguments}.1"],
priority: "after:removeExtraWhiteSpace"
},
"onStop.resetParseQueue": {
listener: "{that}.resetParseQueue"
},
"onStop.removeHighlight": {
listener: "{that}.removeHighlight",
priority: "after:resetParseQueue"
},
"onStop.updateTTSModel": {
changePath: "tts",
value: {
speaking: false,
paused: false
},
source: "onStop"
},
"utteranceOnEnd.resetParseIndex": {
changePath: "",
value: {
parseIndex: null
},
source: "utteranceOnEnd"
},
"utteranceOnStart.updateTTSModel": {
changePath: "tts",
value: {
speaking: true,
paused: false
},
source: "utteranceOnStart"
},
"utteranceOnPause.updateTTSModel": {
changePath: "tts",
value: {
speaking: true,
paused: true
},
source: "utteranceOnPause"
},
// needed to prevent the parseQueueIndex from incrementing when the resume is called, instead of continuing on.
"utteranceOnPause.resetBoundary": {
changePath: "ttsBoundary",
value: null,
source: "utteranceOnPause"
},
"utteranceOnResume.updateTTSModel": {
changePath: "tts",
value: {
speaking: true,
paused: false
},
source: "utteranceOnResume"
},
"utteranceOnBoundary.setCurrentBoundary": {
listener: "fluid.orator.domReader.setCurrentBoundary",
args: ["{that}", "{arguments}.0.charIndex", "{arguments}.0.name"]
}
}
});
/**
* Updates the `ttsBoundary` and `parseQueueIndex` model paths based on the provided boundary. Attempts to determine
* if the supplied boundary is derived from the current queue or if the parseQueueIndex needs to be incremented.
*
* @param {fluid.orator.domReader} that - an instance of the component
* @param {Integer} boundary - the incoming boundary, typically from a {SpeechSynthesisUtterance} boundary event.
* This indicates the starting index of the word being Synthesized.
* @param {String} boundaryType - Boundary events can fire at the beginning of a "word" or "sentence". This is used
* to indicate which one it is related to. From the {SpeechSynthesisUtterance}
* boundary event this is found in the `name` property. Currently only `"word"`
* boundary events are supported. All others will be ignored.
*/
fluid.orator.domReader.setCurrentBoundary = function (that, boundary, boundaryType) {
// It is possible that the pause event triggers before all of the boundary events have been received.
// The following check prevents boundary events from updating the model if TTS is paused.
// Also we currently only support "word" boundary events. Some synthesizers also fire boundary events
// In those cases, we will get two boundary events for the beginning which will confuse the parseQueueIndex
// incrementing algorithm. At the moment we ignore any non-word boundary events. In the future we may also
// accept sentence boundary events for potentially highlighting sentences as well.
if (that.model.tts.paused || boundaryType !== "word") {
return;
}
var currentBoundary = fluid.isValue(that.model.ttsBoundary) ? that.model.ttsBoundary : -1;
var parseQueueIndex;
if (currentBoundary < boundary) {
parseQueueIndex = that.model.parseQueueIndex;
} else {
parseQueueIndex = that.model.parseQueueIndex + 1;
}
that.applier.change("", {
"ttsBoundary": boundary,
"parseQueueIndex": parseQueueIndex
}, "ADD", "setCurrentBoundary");
};
fluid.orator.domReader.play = function (that, resumeFn) {
if (that.model.tts.enabled) {
if (that.model.tts.paused) {
resumeFn();
} else if (!that.model.tts.speaking) {
that.readFromDOM();
}
}
};
fluid.orator.domReader.pause = function (that, pauseFn) {
if (that.model.tts.speaking && !that.model.tts.paused) {
pauseFn();
}
};
fluid.orator.domReader.mapUtteranceEvents = function (that, utterance, utteranceEventMap) {
fluid.each(utteranceEventMap, function (compEventName, utteranceEvent) {
var compEvent = that.events[compEventName];
utterance[utteranceEvent] = compEvent.fire;
});
};
fluid.orator.domReader.removeExtraWhiteSpace = function (text) {
var promise = fluid.promise();
// force a string value
var str = text.toString();
// trim whitespace
str = str.trim();
if (str) {
promise.resolve(str);
} else {
promise.reject("The text is empty");
}
return promise;
};
/**
* Operates the core "transforming promise workflow" for queuing an utterance. The initial listener is provided the
* initial text; which then proceeds through the transform chain to arrive at the final text.
* To change the speech function (e.g for testing) the `onQueueSpeech.queueSpeech` listener can be overridden.
*
* @param {fluid.orator.domReader} that - an instance of the component
* @param {String} text - The text to be synthesized
* @param {Object} options - (optional) options to configure the utterance with. This will also be interpolated with
* the event mappings. See: `fluid.textToSpeech.queueSpeech` in TextToSpeech.js for an
* example of utterance options for that speech function.
*
* @return {Promise} - A promise for the final resolved text
*/
fluid.orator.domReader.queueSpeech = function (that, text, options) {
options = options || {};
// map events
fluid.orator.domReader.mapUtteranceEvents(that, options, that.options.utteranceEventMap);
return fluid.promise.fireTransformEvent(that.events.onQueueSpeech, text, options);
};
/**
* Unwraps the contents of the element by removing the tag surrounding the content and placing the content
* as a node within the element's parent. The parent is also normalized to combine any adjacent text nodes.
*
* @param {String|jQuery|DomElement} elm - element to unwrap
*/
fluid.orator.domReader.unWrap = function (elm) {
elm = $(elm);
if (elm.length) {
var parent = elm.parent();
// Remove the element, but place its contents within the parent.
elm.contents().unwrap();
// Normalize the parent to cleanup text nodes
parent[0].normalize();
}
};
/**
* Positional information about a word parsed from the text in a {DomElement}. This can be used for mappings between
* a synthesizer's speech boundary and the word's location within the DOM.
*
* @typedef {Object} DomWordMap
* @property {Integer} blockIndex - The index into the entire block of text being parsed from the DOM
* @property {Integer} startOffset - The start offset of the current `word` relative to the closest
* enclosing DOM element
* @property {Integer} endOffset - The end offset of the current `word` relative to the closest
* enclosing DOM element
* @property {DomNode} node - The current child node being parsed
* @property {Integer} childIndex - The index of the child node being parsed relative to its parent
* @property {DomElement} parentNode - The parent DOM node
* @property {String} word - The text, `word`, parsed from the node. It may contain only whitespace.
*/
/**
* Retrieves the active parseQueue array to be used when updating from the latest parsed text node. Will increment
* the parseQueue with a new empty array if one doesn't already exist or if the language has changed.
*
* @param {fluid.orator.domReader} that - an instance of the component
* @param {String} lang - a valid BCP 47 language code.
*
* @return {Array} - the parseQueue array to update with the latest parsed text node.
*/
fluid.orator.domReader.retrieveActiveQueue = function (that, lang) {
var lastQueue = that.parseQueue[that.parseQueue.length - 1];
if (!lastQueue || (lastQueue.length && lastQueue[0].lang !== lang)) {
lastQueue = [];
that.parseQueue.push(lastQueue);
that.applier.change("parseQueueCount", that.parseQueue.length, "ADD", "retrieveActiveQueue");
}
return lastQueue;
};
/**
* Takes in a text node and separates the contained words into {DomWordMaps} that are added to the `parseQueue`.
* Typically this handles parsed data passed along by a Parser's (`fluid.textNodeParser`) `onParsedTextNode` event.
* Empty nodes are skipped and the subsequent text is analyzed to determine if it should be appended to the
* previous {DomWordMap} in the parseQueue. For example: when the syllabification separator tag is inserted
* between words.
*
* @param {fluid.orator.domReader} that - an instance of the component
* @param {TextNodeData} textNodeData - the parsed information of text node. Typically from `fluid.textNodeParser`
*/
fluid.orator.domReader.addToParseQueue = function (that, textNodeData) {
var activeQueue = fluid.orator.domReader.retrieveActiveQueue(that, textNodeData.lang);
var lastParsed = activeQueue[activeQueue.length - 1] || {};
var words = textNodeData.node.textContent.split(/(\s+)/); // split on whitespace, and capture whitespace
var parsed = $.extend({}, textNodeData, {
blockIndex: (lastParsed.blockIndex || 0) + (fluid.get(lastParsed, ["word", "length"]) || 0),
startOffset: 0,
parentNode: textNodeData.node.parentNode
});
fluid.each(words, function (word) {
var lastIsWord = that.isWord(lastParsed.word);
var currentIsWord = that.isWord(word);
// If the last parsed item is a word and the current item is a word, combine into the the last parsed block.
// Otherwise, if the new item is a word or non-empty string create a new parsed block.
if (lastIsWord && currentIsWord) {
lastParsed.word += word;
lastParsed.endOffset += word.length;
parsed.blockIndex += word.length;
parsed.startOffset += word.length;
} else {
parsed.word = word;
parsed.endOffset = parsed.startOffset + word.length;
if (currentIsWord || word && lastIsWord) {
lastParsed = fluid.copy(parsed);
activeQueue.push(lastParsed);
that.applier.change("parseItemCount", that.model.parseItemCount + 1, "ADD", "addToParseQueue");
parsed.blockIndex += word.length;
}
parsed.startOffset = parsed.endOffset;
}
});
};
/**
* Reset the parseQueue and related model values
*
* @param {fluid.orator.domReader} that - an instance of the component
*/
fluid.orator.domReader.resetParseQueue = function (that) {
that.parseQueue = [];
that.applier.change("", {
parseQueueIndex: 0,
parseIndex: null,
ttsBoundary: null,
parseQueueCount: 0,
parseItemCount: 0
}, "ADD", "resetParseQueue");
};
/**
* Combines the parsed text into a String.
*
* @param {DomWordMap[]} parsed - An array of {DomWordMap} objects containing the position mappings from a parsed
* {DomElement}.
*
* @return {String} - The parsed text combined into a String.
*/
fluid.orator.domReader.parsedToString = function (parsed) {
var words = fluid.transform(parsed, function (block) {
return block.word;
});
return words.join("");
};
/**
* Parses the DOM element into data points to use for highlighting the text, and queues the text into the self
* voicing engine. The parsed data points are added to the component's `parseQueue`. Once all of the text has been
* synthesized, the `onStop` event is fired.
*
* @param {fluid.orator.domReader} that - an instance of the component
* @param {String|jQuery|DomElement} elm - The DOM node to read
*/
fluid.orator.domReader.readFromDOM = function (that, elm) {
elm = $(elm);
// only execute if there are nodes to read from
if (elm.length) {
that.resetParseQueue();
that.parser.parse(elm[0]);
var queueSpeechPromises = fluid.transform(that.parseQueue, function (parsedBlock, index) {
var interrupt = !index; // only interrupt on the first string
var text = that.parsedToString(parsedBlock);
return that.queueSpeech(text, {lang: parsedBlock[0].lang, interrupt: interrupt});
});
fluid.promise.sequence(queueSpeechPromises).then(that.events.onStop.fire);
}
};
/**
* Returns the index of the closest data point from the parseQueue based on the boundary provided.
*
* @param {fluid.orator.domReader} that - an instance of the component
* @param {Integer} boundary - The boundary value used to compare against the blockIndex of the parsed data points.
* If the boundary is undefined or out of bounds, `undefined` will be returned.
* @param {Integer} parseQueueIndex - The index of into the parseQueue to determine which queue to use for
* calculating the boundary positions against.
*
* @return {Integer|undefined} - Will return the index of the closest data point in the parseQueue. If the boundary
* cannot be located within the parseQueue, `undefined` is returned.
*/
fluid.orator.domReader.getClosestIndex = function (that, boundary, parseQueueIndex) {
var parseQueue = that.parseQueue[parseQueueIndex];
if (!fluid.get(parseQueue, "length") || !fluid.isValue(boundary)) {
return undefined;
};
var maxIndex = Math.max(parseQueue.length - 1, 0);
var index = Math.max(Math.min(that.model.parseIndex || 0, maxIndex), 0);
var maxBoundary = parseQueue[maxIndex].blockIndex + parseQueue[maxIndex].word.length;
if (boundary > maxBoundary || boundary < 0) {
return undefined;
}
while (index >= 0) {
var nextIndex = index + 1;
var prevIndex = index - 1;
var currentBlockIndex = parseQueue[index].blockIndex;
var nextBlockIndex = index < maxIndex ? parseQueue[nextIndex].blockIndex : (maxBoundary + 1);
// Break if the boundary lies within the current block
if (boundary >= currentBlockIndex && boundary < nextBlockIndex) {
break;
}
if (currentBlockIndex > boundary) {
index = prevIndex;
} else {
index = nextIndex;
}
}
return index;
};
/**
* Searches down, starting from the provided node, returning the first text node found.
*
* @param {DomNode} node - the DOM Node to start searching from.
* @return {DomNode|Undefined} - Returns the first text node found, or `undefined` if none located.
*/
fluid.orator.domReader.findTextNode = function (node) {
if (!node) {
return;
}
if (node.nodeType === Node.TEXT_NODE) {
return node;
}
var children = node.childNodes;
for (var i = 0; i < children.length; i++) {
var textNode = fluid.orator.domReader.findTextNode(children[i]);
if (textNode !== undefined) {
return textNode;
}
}
};
fluid.orator.domReader.getTextNodeFromSibling = function (node) {
while (node.nextSibling) {
node = node.nextSibling;
var textNode = fluid.orator.domReader.findTextNode(node);
if (textNode) {
return textNode;
}
}
};
fluid.orator.domReader.getNextTextNode = function (node) {
var nextTextNode = fluid.orator.domReader.getTextNodeFromSibling(node);
if (nextTextNode) {
return nextTextNode;
}
var parent = node.parentNode;
if (parent) {
return fluid.orator.domReader.getNextTextNode(parent);
}
};
fluid.orator.domReader.setRangeEnd = function (range, node, end) {
var ranges = fluid.makeArray(range);
if (end <= node.length) {
range.setEnd(node, end);
} else {
var nextRange = document.createRange();
var nextTextNode = fluid.orator.domReader.getNextTextNode(node);
nextRange.selectNode(nextTextNode);
nextRange.setStart(nextTextNode, 0);
ranges = ranges.concat(fluid.orator.domReader.setRangeEnd(nextRange, nextTextNode, end - node.length));
}
return ranges;
};
/**
* Highlights text from the `parseQueue`. Highlights are performed by wrapping the appropriate text in the markup
* specified at `that.options.markup.highlight`.
*
* @param {fluid.orator.domReader} that - an instance of the component
*/
fluid.orator.domReader.highlight = function (that) {
that.removeHighlight();
if (that.model.parseQueueCount && fluid.isValue(that.model.parseIndex)) {
var data = that.parseQueue[that.model.parseQueueIndex][that.model.parseIndex];
var rangeNode = data.parentNode.childNodes[data.childIndex];
var startRange = document.createRange();
startRange.selectNode(rangeNode);
startRange.setStart(rangeNode, data.startOffset);
var ranges = fluid.orator.domReader.setRangeEnd (startRange, rangeNode, data.endOffset);
fluid.each(ranges, function (range) {
range.surroundContents($(that.options.markup.highlight)[0]);
range.detach(); // removes the range
});
}
};
/*******************************************************************************
* fluid.orator.selectionReader
*
* Reads in text from a selection and voices it
*******************************************************************************/
fluid.defaults("fluid.orator.selectionReader", {
gradeNames: ["fluid.viewComponent"],
selectors: {
control: ".flc-orator-selectionReader-control",
controlLabel: ".flc-orator-selectionReader-controlLabel"
},
strings: {
play: "play",
stop: "stop"
},
styles: {
above: "fl-orator-selectionReader-above",
below: "fl-orator-selectionReader-below",
control: "fl-orator-selectionReader-control"
},
markup: {
control: "<button class=\"flc-orator-selectionReader-control\"><span class=\"fl-icon-orator\"></span><span class=\"flc-orator-selectionReader-controlLabel\"></span></button>"
},
model: {
enabled: true,
play: false,
text: ""
},
events: {
onSelectionChanged: null,
onStop: null,
onToggleControl: null
},
components: {
parser: {
type: "fluid.textNodeParser"
}
},
listeners: {
"onCreate.bindEvents": {
funcName: "fluid.orator.selectionReader.bindSelectionEvents",
args: ["{that}"]
},
"onSelectionChanged.updateSelection": "{that}.getSelection",
"onStop.stop": {
changePath: "play",
value: false,
source: "stopMethod"
},
"onToggleControl.togglePlay": "{that}.toggle"
},
modelListeners: {
"text": [{
func: "{that}.stop",
namespace: "stopPlayingWhenTextChanges"
}, {
funcName: "fluid.orator.selectionReader.renderControl",
args: ["{that}", "{change}.value"],
namespace: "render"
}],
"play": [{
func: "fluid.orator.selectionReader.queueSpeech",
args: ["{that}", "{change}.value", "{fluid.textToSpeech}.queueSpeechSequence"],
namespace: "queueSpeech"
}, {
func: "fluid.orator.selectionReader.renderControlState",
args: ["{that}", "{that}.control", "{arguments}.0"],
excludeSource: ["init"],
namespace: "renderControlState"
}],
"enabled": {
funcName: "fluid.orator.selectionReader.updateText",
args: ["{that}", "{change}.value"],
namespace: "updateText"
}
},
invokers: {
getSelection: {
funcName: "fluid.orator.selectionReader.getSelection",
args: ["{that}"]
},
play: {
changePath: "play",
value: true,
source: "playMethod"
},
stop: {
funcName: "fluid.orator.selectionReader.stopSpeech",
args: ["{that}.model.play", "{fluid.textToSpeech}.cancel"]
},
toggle: {
funcName: "fluid.orator.selectionReader.togglePlay",
args: ["{that}", "{arguments}.0"]
}
}
});
// TODO: When https://issues.fluidproject.org/browse/FLUID-6393 has been addressed, it will be possible to remove
// this function and directly configure the modelListener to only trigger when a false value is passed.
fluid.orator.selectionReader.stopSpeech = function (state, cancelFn) {
if (state) {
cancelFn();
}
};
fluid.orator.selectionReader.queueSpeech = function (that, state, speechFn) {
if (state && that.model.enabled && that.model.text) {
var parsed = fluid.orator.selectionReader.parseRange(that.selection.getRangeAt(0), that.parser.parse);
var speechPromise = speechFn(parsed, true);
speechPromise.then(that.events.onStop.fire);
}
};
fluid.orator.selectionReader.bindSelectionEvents = function (that) {
$(document).on("selectionchange", function (e) {
if (that.model.enabled) {
that.events.onSelectionChanged.fire(e);
}
});
};
fluid.orator.selectionReader.updateText = function (that, state) {
if (state) {
that.getSelection();
} else {
that.applier.change("text", "", "ADD", "updateText");
}
};
/**
* Retrieves the text from the current selection
*
* @return {String} - the text from the current selection
*/
fluid.orator.selectionReader.getSelectedText = function () {
var selection = window.getSelection();
return selection.toString();
};
/**
* Retrieves the text from the current selection
*
* @param {fluid.orator.selectionReader} that - an instance of the component
*/
fluid.orator.selectionReader.getSelection = function (that) {
that.selection = window.getSelection();
that.applier.change("text", that.selection.toString(), "ADD", "getSelection");
};
/**
* Parses a selection into a {Speech[]}. If the selection includes multiple text nodes, the supplied domParser is
* used to do an initial parsing into a {TextNodeData[]}.
*
* @param {Range} range - a Range object representing a selection.
* @param {Function} domParser - a parser function to parse Dom Elements into a {TextNodeData[]}
*
* @return {Speech[]} - an array of {Speech} objects for configuring SpeechSynthesis Utterances with.
*/
fluid.orator.selectionReader.parseRange = function (range, domParser) {
// Handles the case where all of the selection is in a single text node. Don't need to parse in this case.
if (range.commonAncestorContainer.nodeType === Node.TEXT_NODE) {
return [{
text: range.commonAncestorContainer.textContent.slice(range.startOffset, range.endOffset),
options: {
lang: $(range.commonAncestorContainer.parentNode).closest("[lang]").attr("lang")
}
}];
}
// Handles the case were range.selectNode was called to create the selection
if (range.commonAncestorContainer === range.startContainer) {
return fluid.orator.selectionReader.parseElement(range.commonAncestorContainer.childNodes[range.startOffset], domParser);
}
return fluid.orator.selectionReader.parseElement(range.commonAncestorContainer, domParser, range);
};
/**
* The options for parsing an element into {Speech[]}. It has similar properties to a {Range} and is typically used
* for `fluid.orator.selectionReader.parseElement`.
* @type {Object} ParseElementOpts
* @property {Integer} startOffset - the starting offset of the first text node. Text before will be omitted
* @property {Integer} endOffset - the end offset of the last text node. Text after will be omitted.
* @property {DomNode} startContainer - the text node to start parsing from.
* @property {DomNode} endContainer - the text node to stop parsing at.
*/
/**
* Parses an element into a {Speech[]}. The supplied domParser is used to do an initial parsing of the element into
* a {TextNodeData[]}.
*
* @param {DomElement} element - The DOM Element to parse
* @param {Function} domParser - a parser function to parse Dom Elements into a {TextNodeData[]}
* @param {ParseElementOpts} options - (Optional) parsing configuration
* @return {Speech[]} - an array of {Speech} objects for configuring SpeechSynthesis Utterances with.
*/
fluid.orator.selectionReader.parseElement = function (element, domParser, options) {
options = options || {};
var parsed = [];
var fromParser = domParser(element);
var parsedNodes = fluid.getMembers(fromParser, "node");
var startIndex = options.startContainer ? parsedNodes.indexOf(options.startContainer) : 0;
var endIndex = options.endContainer ? parsedNodes.indexOf(options.endContainer) : parsedNodes.length - 1;
if (startIndex >= 0 && endIndex >= 0) {
for (var i = startIndex; i <= endIndex; i++) {
var startOffset = i === startIndex ? options.startOffset : 0;
var endOffset = i === endIndex ? options.endOffset : undefined;
var node = fromParser[i].node;
var lang = fromParser[i].lang;
var lastParsed = parsed[parsed.length - 1];
if (parsed.length && lastParsed.options.lang === lang) {
lastParsed.text += node.textContent.slice(startOffset, endOffset);
} else {
parsed.push({
text: node.textContent.slice(startOffset, endOffset),
options: {
lang: lang
}
});
}
}
}
return parsed;
};
/**
* Coordinates for an element, includes both viewPort and Document coordinates.
*
* @typedef {Object} ElementPosition
* @property {Object} viewPort - the coordinates relative to the viewPort
* @property {Float} viewPort.top - The `top` pixel coordinate relative to the top edge of the viewPort
* @property {Float} viewPort.left - The `left` pixel coordinate relative to the left edge of the viewPort
* @property {Object} offset - the coordinates relative to the offset parent (closest positioned ancestor)
* @property {Float} offset.top - The `top` pixel coordinate relative to the offset parent
* @property {Float} offset.left - The `left` pixel coordinate relative to the offset parent
*/
/**
* Returns a position object containing coordinates of the provided range. These can be used to position other
* elements in relation to it.
*
* @param {Range} range - A Range object for which to calculate the position of.
*
* @return {ElementPosition} - An object containing the coordinates of the provided `range`.
*/
fluid.orator.selectionReader.calculatePosition = function (range) {
// use getClientRects()[0] instead of getBoundingClientRect() because in cases where more than one rect
// is returned we only want the first one, not the aggregation of all of them.
var rangeRect = range.getClientRects()[0];
var rangeParent = range.startContainer.parentNode;
var rangeParentRect = rangeParent.getClientRects()[0];
var offsetParent = rangeParent.offsetParent;
var bodyBorderAdjustment = {
top: 0,
left: 0
};
// If the offset parent is the `body` element and it is positioned, if there is a border set
// on the `body` it may affect the offset value returned. In some browsers the outer edge of the
// border is used to calculate the offset, in others it is the inner edge. The algorithm below can calculate
// a needed adjustment value by comparing the offsetParent's offset and client values. In the case where the
// Outer edge of the border is used, the offset is 0. In cases where the inner edge is used, the offset is a
// negative value. The difference in the absolute value of the offset and the client values, is the amount
// that the positioning needs to be adjusted for.
if (offsetParent && offsetParent.tagName.toLowerCase() === "body") {
bodyBorderAdjustment.top = Math.abs(offsetParent.offsetTop) - offsetParent.clientTop;
bodyBorderAdjustment.left = Math.abs(offsetParent.offsetLeft) - offsetParent.clientLeft;
}
return {
viewPort: {
top: rangeRect.top,
bottom: rangeRect.bottom,
left: rangeRect.left
},
offset: {
top: rangeParent.offsetTop + rangeRect.top - rangeParentRect.top + bodyBorderAdjustment.top,
bottom: rangeParent.offsetTop + rangeRect.bottom - rangeParentRect.top + bodyBorderAdjustment.top,
left: rangeParent.offsetLeft + rangeRect.left - rangeParentRect.left + bodyBorderAdjustment.left
}
};
};
fluid.orator.selectionReader.renderControlState = function (that, control) {
var text = that.options.strings[that.model.play ? "stop" : "play"];
control.find(that.options.selectors.controlLabel).text(text);
};
fluid.orator.selectionReader.adjustForHorizontalCollision = function (control, position, viewPortWidth) {
viewPortWidth = viewPortWidth || document.body.clientWidth;
var controlMidPoint = parseFloat(control.css("width")) / 2;
// check for collision on left side
if (controlMidPoint > position.viewPort.left) {
control.css("left", position.offset.left + controlMidPoint - position.viewPort.left);
// check for collision on right side
} else if (controlMidPoint + position.viewPort.left > viewPortWidth) {
control.css("left", position.offset.left - viewPortWidth + position.viewPort.left);
}
};
fluid.orator.selectionReader.adjustForVerticalCollision = function (control, position, belowStyle, aboveStyle) {
var controlHeight = parseFloat(control.css("height"));
if (controlHeight > position.viewPort.top) {
control.css("top", position.offset.bottom);
control.removeClass(aboveStyle);
control.addClass(belowStyle);
} else {
control.removeClass(belowStyle);
control.addClass(aboveStyle);
}
};
fluid.orator.selectionReader.createControl = function (that) {
var control = $(that.options.markup.control);
control.addClass(that.options.styles.control);
control.click(function () {
// wrapped in an empty function so as not to pass along the jQuery event object
that.events.onToggleControl.fire();
});
return control;
};
fluid.orator.selectionReader.renderControl = function (that, state) {
if (state) {
var selectionRange = window.getSelection().getRangeAt(0);
var controlContainer = selectionRange.startContainer.parentNode.offsetParent || selectionRange.startContainer.parentNode;
var position = fluid.orator.selectionReader.calculatePosition(selectionRange);
that.control = that.control || fluid.orator.selectionReader.createControl(that);
// set the intial position
that.control.css({
top: position.offset.top,
left: position.offset.left
});
fluid.orator.selectionReader.renderControlState(that, that.control);
that.control.appendTo(controlContainer);
// check if there is space to display above, if not move to below selection
fluid.orator.selectionReader.adjustForVerticalCollision(
that.control,
position,
that.options.styles.below,
that.options.styles.above
);
// adjust horizontal position for collisions with the viewport edge.
fluid.orator.selectionReader.adjustForHorizontalCollision(that.control, position);
// cleanup range
selectionRange.detach();
} else {
if (that.control) {
that.control.detach();
}
}
};
fluid.orator.selectionReader.togglePlay = function (that, state) {
var newState = state || !that.model.play;
that[newState ? "play" : "stop"]();
};
})(jQuery, fluid_3_0_0);
;
// =========================================================================
//
// tinyxmlsax.js - an XML SAX parser in JavaScript compressed for downloading
//
// version 3.1
//
// =========================================================================
//
// Copyright (C) 2000 - 2002, 2003 Michael Houghton (mike@idle.org), Raymond Irving and David Joham (djoham@yahoo.com)
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Visit the XML for <SCRIPT> home page at http://xmljs.sourceforge.net
//
/*
The zlib/libpng License
Copyright (c) 2000 - 2002, 2003 Michael Houghton (mike@idle.org), Raymond Irving and David Joham (djoham@yahoo.com)
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
fluid.XMLP = function(strXML) {
return fluid.XMLP.XMLPImpl(strXML);
};
// List of closed HTML tags, taken from JQuery 1.2.3
fluid.XMLP.closedTags = {
abbr: true,
br: true,
col: true,
img: true,
input: true,
link: true,
meta: true,
param: true,
hr: true,
area: true,
embed:true
};
fluid.XMLP._NONE = 0;
fluid.XMLP._ELM_B = 1;
fluid.XMLP._ELM_E = 2;
fluid.XMLP._ELM_EMP = 3;
fluid.XMLP._ATT = 4;
fluid.XMLP._TEXT = 5;
fluid.XMLP._ENTITY = 6;
fluid.XMLP._PI = 7;
fluid.XMLP._CDATA = 8;
fluid.XMLP._COMMENT = 9;
fluid.XMLP._DTD = 10;
fluid.XMLP._ERROR = 11;
fluid.XMLP._CONT_XML = 0;
fluid.XMLP._CONT_ALT = 1;
fluid.XMLP._ATT_NAME = 0;
fluid.XMLP._ATT_VAL = 1;
fluid.XMLP._STATE_PROLOG = 1;
fluid.XMLP._STATE_DOCUMENT = 2;
fluid.XMLP._STATE_MISC = 3;
fluid.XMLP._errs = [];
fluid.XMLP._errs[fluid.XMLP.ERR_CLOSE_PI = 0 ] = "PI: missing closing sequence";
fluid.XMLP._errs[fluid.XMLP.ERR_CLOSE_DTD = 1 ] = "DTD: missing closing sequence";
fluid.XMLP._errs[fluid.XMLP.ERR_CLOSE_COMMENT = 2 ] = "Comment: missing closing sequence";
fluid.XMLP._errs[fluid.XMLP.ERR_CLOSE_CDATA = 3 ] = "CDATA: missing closing sequence";
fluid.XMLP._errs[fluid.XMLP.ERR_CLOSE_ELM = 4 ] = "Element: missing closing sequence";
fluid.XMLP._errs[fluid.XMLP.ERR_CLOSE_ENTITY = 5 ] = "Entity: missing closing sequence";
fluid.XMLP._errs[fluid.XMLP.ERR_PI_TARGET = 6 ] = "PI: target is required";
fluid.XMLP._errs[fluid.XMLP.ERR_ELM_EMPTY = 7 ] = "Element: cannot be both empty and closing";
fluid.XMLP._errs[fluid.XMLP.ERR_ELM_NAME = 8 ] = "Element: name must immediately follow \"<\"";
fluid.XMLP._errs[fluid.XMLP.ERR_ELM_LT_NAME = 9 ] = "Element: \"<\" not allowed in element names";
fluid.XMLP._errs[fluid.XMLP.ERR_ATT_VALUES = 10] = "Attribute: values are required and must be in quotes";
fluid.XMLP._errs[fluid.XMLP.ERR_ATT_LT_NAME = 11] = "Element: \"<\" not allowed in attribute names";
fluid.XMLP._errs[fluid.XMLP.ERR_ATT_LT_VALUE = 12] = "Attribute: \"<\" not allowed in attribute values";
fluid.XMLP._errs[fluid.XMLP.ERR_ATT_DUP = 13] = "Attribute: duplicate attributes not allowed";
fluid.XMLP._errs[fluid.XMLP.ERR_ENTITY_UNKNOWN = 14] = "Entity: unknown entity";
fluid.XMLP._errs[fluid.XMLP.ERR_INFINITELOOP = 15] = "Infinite loop";
fluid.XMLP._errs[fluid.XMLP.ERR_DOC_STRUCTURE = 16] = "Document: only comments, processing instructions, or whitespace allowed outside of document element";
fluid.XMLP._errs[fluid.XMLP.ERR_ELM_NESTING = 17] = "Element: must be nested correctly";
fluid.XMLP._checkStructure = function(that, iEvent) {
var stack = that.m_stack;
if (fluid.XMLP._STATE_PROLOG == that.m_iState) {
// disabled original check for text node in prologue
that.m_iState = fluid.XMLP._STATE_DOCUMENT;
}
if (fluid.XMLP._STATE_DOCUMENT === that.m_iState) {
if ((fluid.XMLP._ELM_B == iEvent) || (fluid.XMLP._ELM_EMP == iEvent)) {
that.m_stack[stack.length] = that.getName();
}
if ((fluid.XMLP._ELM_E == iEvent) || (fluid.XMLP._ELM_EMP == iEvent)) {
if (stack.length === 0) {
//return fluid.XMLP._setErr(XMLP.ERR_DOC_STRUCTURE);
return fluid.XMLP._NONE;
}
var strTop = stack[stack.length - 1];
that.m_stack.length--;
if (strTop === null || strTop !== that.getName()) {
return fluid.XMLP._setErr(that, fluid.XMLP.ERR_ELM_NESTING);
}
}
// disabled original check for text node in epilogue - "MISC" state is disused
}
return iEvent;
};
fluid.XMLP._parseCDATA = function(that, iB) {
var iE = that.m_xml.indexOf("]]>", iB);
if (iE == -1) { return fluid.XMLP._setErr(that, fluid.XMLP.ERR_CLOSE_CDATA);}
fluid.XMLP._setContent(that, fluid.XMLP._CONT_XML, iB, iE);
that.m_iP = iE + 3;
return fluid.XMLP._CDATA;
};
fluid.XMLP._parseComment = function(that, iB) {
var iE = that.m_xml.indexOf("-" + "->", iB);
if (iE == -1) {
return fluid.XMLP._setErr(that, fluid.XMLP.ERR_CLOSE_COMMENT);
}
fluid.XMLP._setContent(that, fluid.XMLP._CONT_XML, iB - 4, iE + 3);
that.m_iP = iE + 3;
return fluid.XMLP._COMMENT;
};
fluid.XMLP._parseDTD = function(that, iB) {
var iE, strClose, iInt, iLast;
iE = that.m_xml.indexOf(">", iB);
if (iE == -1) {
return fluid.XMLP._setErr(that, fluid.XMLP.ERR_CLOSE_DTD);
}
iInt = that.m_xml.indexOf("[", iB);
strClose = ((iInt != -1) && (iInt < iE)) ? "]>" : ">";
while (true) {
if (iE == iLast) {
return fluid.XMLP._setErr(that, fluid.XMLP.ERR_INFINITELOOP);
}
iLast = iE;
iE = that.m_xml.indexOf(strClose, iB);
if(iE == -1) {
return fluid.XMLP._setErr(that, fluid.XMLP.ERR_CLOSE_DTD);
}
if (that.m_xml.substring(iE - 1, iE + 2) != "]]>") { break;}
}
that.m_iP = iE + strClose.length;
return fluid.XMLP._DTD;
};
fluid.XMLP._parsePI = function(that, iB) {
var iE, iTB, iTE, iCB, iCE;
iE = that.m_xml.indexOf("?>", iB);
if (iE == -1) { return fluid.XMLP._setErr(that, fluid.XMLP.ERR_CLOSE_PI);}
iTB = fluid.SAXStrings.indexOfNonWhitespace(that.m_xml, iB, iE);
if (iTB == -1) { return fluid.XMLP._setErr(that, fluid.XMLP.ERR_PI_TARGET);}
iTE = fluid.SAXStrings.indexOfWhitespace(that.m_xml, iTB, iE);
if (iTE == -1) { iTE = iE;}
iCB = fluid.SAXStrings.indexOfNonWhitespace(that.m_xml, iTE, iE);
if (iCB == -1) { iCB = iE;}
iCE = fluid.SAXStrings.lastIndexOfNonWhitespace(that.m_xml, iCB, iE);
if (iCE == -1) { iCE = iE - 1;}
that.m_name = that.m_xml.substring(iTB, iTE);
fluid.XMLP._setContent(that, fluid.XMLP._CONT_XML, iCB, iCE + 1);
that.m_iP = iE + 2;
return fluid.XMLP._PI;
};
fluid.XMLP._parseText = function(that, iB) {
var iE = that.m_xml.indexOf("<", iB);
if (iE == -1) { iE = that.m_xml.length;}
fluid.XMLP._setContent(that, fluid.XMLP._CONT_XML, iB, iE);
that.m_iP = iE;
return fluid.XMLP._TEXT;
};
fluid.XMLP._setContent = function(that, iSrc) {
var args = arguments;
if (fluid.XMLP._CONT_XML == iSrc) {
that.m_cAlt = null;
that.m_cB = args[2];
that.m_cE = args[3];
}
else {
that.m_cAlt = args[2];
that.m_cB = 0;
that.m_cE = args[2].length;
}
that.m_cSrc = iSrc;
};
fluid.XMLP._setErr = function(that, iErr) {
var strErr = fluid.XMLP._errs[iErr];
that.m_cAlt = strErr;
that.m_cB = 0;
that.m_cE = strErr.length;
that.m_cSrc = fluid.XMLP._CONT_ALT;
return fluid.XMLP._ERROR;
};
fluid.XMLP._parseElement = function(that, iB) {
var iE, iDE, iRet;
var iType, strN, iLast;
iDE = iE = that.m_xml.indexOf(">", iB);
if (iE == -1) {
return fluid.XMLP._setErr(that, fluid.XMLP.ERR_CLOSE_ELM);
}
if (that.m_xml.charAt(iB) == "/") {
iType = fluid.XMLP._ELM_E;
iB++;
}
else {
iType = fluid.XMLP._ELM_B;
}
if (that.m_xml.charAt(iE - 1) == "/") {
if (iType == fluid.XMLP._ELM_E) {
return fluid.XMLP._setErr(that, fluid.XMLP.ERR_ELM_EMPTY);
}
iType = fluid.XMLP._ELM_EMP; iDE--;
}
that.nameRegex.lastIndex = iB;
var nameMatch = that.nameRegex.exec(that.m_xml);
if (!nameMatch) {
return fluid.XMLP._setErr(that, fluid.XMLP.ERR_ELM_NAME);
}
strN = nameMatch[1].toLowerCase();
// This branch is specially necessary for broken markup in IE. If we see an li
// tag apparently directly nested in another, first emit a synthetic close tag
// for the earlier one without advancing the pointer, and set a flag to ensure
// doing this just once.
if ("li" === strN && iType !== fluid.XMLP._ELM_E && that.m_stack.length > 0 &&
that.m_stack[that.m_stack.length - 1] === "li" && !that.m_emitSynthetic) {
that.m_name = "li";
that.m_emitSynthetic = true;
return fluid.XMLP._ELM_E;
}
// We have acquired the tag name, now set about parsing any attribute list
that.m_attributes = {};
that.m_cAlt = "";
if (that.nameRegex.lastIndex < iDE) {
that.m_iP = that.nameRegex.lastIndex;
while (that.m_iP < iDE) {
that.attrStartRegex.lastIndex = that.m_iP;
var attrMatch = that.attrStartRegex.exec(that.m_xml);
if (!attrMatch) {
return fluid.XMLP._setErr(that, fluid.XMLP.ERR_ATT_VALUES);
}
var attrname = attrMatch[1].toLowerCase();
var attrval;
if (that.m_xml.charCodeAt(that.attrStartRegex.lastIndex) === 61) { // =
var valRegex = that.m_xml.charCodeAt(that.attrStartRegex.lastIndex + 1) === 34? that.attrValRegex : that.attrValIERegex; // "
valRegex.lastIndex = that.attrStartRegex.lastIndex + 1;
attrMatch = valRegex.exec(that.m_xml);
if (!attrMatch) {
return fluid.XMLP._setErr(that, fluid.XMLP.ERR_ATT_VALUES);
}
attrval = attrMatch[1];
}
else { // accommodate insanity on unvalued IE attributes
attrval = attrname;
valRegex = that.attrStartRegex;
}
if (!that.m_attributes[attrname] || that.m_attributes[attrname] === attrval) {
// last branch required because of fresh duplicate attribute bug introduced in IE10 and above - FLUID-5204
that.m_attributes[attrname] = attrval;
}
else {
return fluid.XMLP._setErr(that, fluid.XMLP.ERR_ATT_DUP);
}
that.m_iP = valRegex.lastIndex;
}
}
if (strN.indexOf("<") != -1) {
return fluid.XMLP._setErr(that, fluid.XMLP.ERR_ELM_LT_NAME);
}
that.m_name = strN;
that.m_iP = iE + 1;
// Check for corrupted "closed tags" from innerHTML
if (fluid.XMLP.closedTags[strN]) {
that.closeRegex.lastIndex = iE + 1;
var closeMatch = that.closeRegex.exec;
if (closeMatch) {
var matchclose = that.m_xml.indexOf(strN, closeMatch.lastIndex);
if (matchclose === closeMatch.lastIndex) {
return iType; // bail out, a valid close tag is separated only by whitespace
}
else {
return fluid.XMLP._ELM_EMP;
}
}
}
that.m_emitSynthetic = false;
return iType;
};
fluid.XMLP._parse = function(that) {
var iP = that.m_iP;
var xml = that.m_xml;
if (iP === xml.length) { return fluid.XMLP._NONE;}
var c = xml.charAt(iP);
if (c === '<') {
var c2 = xml.charAt(iP + 1);
if (c2 === '?') {
return fluid.XMLP._parsePI(that, iP + 2);
}
else if (c2 === '!') {
if (iP === xml.indexOf("<!DOCTYPE", iP)) {
return fluid.XMLP._parseDTD(that, iP + 9);
}
else if (iP === xml.indexOf("<!--", iP)) {
return fluid.XMLP._parseComment(that, iP + 4);
}
else if (iP === xml.indexOf("<![CDATA[", iP)) {
return fluid.XMLP._parseCDATA(that, iP + 9);
}
}
else {
return fluid.XMLP._parseElement(that, iP + 1);
}
}
else {
return fluid.XMLP._parseText(that, iP);
}
};
fluid.XMLP.XMLPImpl = function(strXML) {
var that = {};
that.m_xml = strXML;
that.m_iP = 0;
that.m_iState = fluid.XMLP._STATE_PROLOG;
that.m_stack = [];
that.m_attributes = {};
that.m_emitSynthetic = false; // state used for emitting synthetic tags used to correct broken markup (IE)
that.getColumnNumber = function() {
return fluid.SAXStrings.getColumnNumber(that.m_xml, that.m_iP);
};
that.getContent = function() {
return (that.m_cSrc == fluid.XMLP._CONT_XML) ? that.m_xml : that.m_cAlt;
};
that.getContentBegin = function() { return that.m_cB;};
that.getContentEnd = function() { return that.m_cE;};
that.getLineNumber = function() {
return fluid.SAXStrings.getLineNumber(that.m_xml, that.m_iP);
};
that.getName = function() {
return that.m_name;
};
that.next = function() {
return fluid.XMLP._checkStructure(that, fluid.XMLP._parse(that));
};
that.nameRegex = /([^\s\/>]+)/g;
that.attrStartRegex = /\s*([\w:_][\w:_\-\.]*)/gm;
that.attrValRegex = /\"([^\"]*)\"\s*/gm; // "normal" XHTML attribute values
that.attrValIERegex = /([^\>\s]+)\s*/gm; // "stupid" unquoted IE attribute values (sometimes)
that.closeRegex = /\s*<\//g;
return that;
};
fluid.SAXStrings = {};
fluid.SAXStrings.WHITESPACE = " \t\n\r";
fluid.SAXStrings.QUOTES = "\"'";
fluid.SAXStrings.getColumnNumber = function (strD, iP) {
if (!strD) { return -1;}
iP = iP || strD.length;
var arrD = strD.substring(0, iP).split("\n");
arrD.length--;
var iLinePos = arrD.join("\n").length;
return iP - iLinePos;
};
fluid.SAXStrings.getLineNumber = function (strD, iP) {
if (!strD) { return -1;}
iP = iP || strD.length;
return strD.substring(0, iP).split("\n").length;
};
fluid.SAXStrings.indexOfNonWhitespace = function (strD, iB, iE) {
if (!strD) return -1;
iB = iB || 0;
iE = iE || strD.length;
for (var i = iB; i < iE; ++ i) {
var c = strD.charAt(i);
if (c !== ' ' && c !== '\t' && c !== '\n' && c !== '\r') return i;
}
return -1;
};
fluid.SAXStrings.indexOfWhitespace = function (strD, iB, iE) {
if (!strD) { return -1;}
iB = iB || 0;
iE = iE || strD.length;
for (var i = iB; i < iE; i++) {
if (fluid.SAXStrings.WHITESPACE.indexOf(strD.charAt(i)) != -1) { return i;}
}
return -1;
};
fluid.SAXStrings.lastIndexOfNonWhitespace = function (strD, iB, iE) {
if (!strD) { return -1;}
iB = iB || 0; iE = iE || strD.length;
for (var i = iE - 1; i >= iB; i--) {
if (fluid.SAXStrings.WHITESPACE.indexOf(strD.charAt(i)) == -1) {
return i;
}
}
return -1;
};
fluid.SAXStrings.replace = function(strD, iB, iE, strF, strR) {
if (!strD) { return "";}
iB = iB || 0;
iE = iE || strD.length;
return strD.substring(iB, iE).split(strF).join(strR);
};
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
// unsupported, non-API function
fluid.parseTemplate = function (template, baseURL, scanStart, cutpoints_in, opts) {
opts = opts || {};
if (!template) {
fluid.fail("empty template supplied to fluid.parseTemplate");
}
var t;
var parser;
var tagstack;
var lumpindex = 0;
var nestingdepth = 0;
var justended = false;
var defstart = -1;
var defend = -1;
var debugMode = false;
var cutpoints = []; // list of selector, tree, id
var simpleClassCutpoints = {};
var cutstatus = [];
var XMLLump = function (lumpindex, nestingdepth) {
return {
//rsfID: "",
//text: "",
//downmap: {},
//attributemap: {},
//finallump: {},
nestingdepth: nestingdepth,
lumpindex: lumpindex,
parent: t
};
};
function isSimpleClassCutpoint(tree) {
return tree.length === 1 && tree[0].predList.length === 1 && tree[0].predList[0].clazz;
}
function init(baseURLin, debugModeIn, cutpointsIn) {
t.rootlump = XMLLump(0, -1); // eslint-disable-line new-cap
tagstack = [t.rootlump];
lumpindex = 0;
nestingdepth = 0;
justended = false;
defstart = -1;
defend = -1;
baseURL = baseURLin;
debugMode = debugModeIn;
if (cutpointsIn) {
for (var i = 0; i < cutpointsIn.length; ++i) {
var tree = fluid.parseSelector(cutpointsIn[i].selector, fluid.simpleCSSMatcher);
var clazz = isSimpleClassCutpoint(tree);
if (clazz) {
simpleClassCutpoints[clazz] = cutpointsIn[i].id;
}
else {
cutstatus.push([]);
cutpoints.push($.extend({}, cutpointsIn[i], {tree: tree}));
}
}
}
}
function findTopContainer() {
for (var i = tagstack.length - 1; i >= 0; --i) {
var lump = tagstack[i];
if (lump.rsfID !== undefined) {
return lump;
}
}
return t.rootlump;
}
function newLump() {
var togo = XMLLump(lumpindex, nestingdepth); // eslint-disable-line new-cap
if (debugMode) {
togo.line = parser.getLineNumber();
togo.column = parser.getColumnNumber();
}
//togo.parent = t;
t.lumps[lumpindex] = togo;
++lumpindex;
return togo;
}
function addLump(mmap, ID, lump) {
var list = mmap[ID];
if (!list) {
list = [];
mmap[ID] = list;
}
list[list.length] = lump;
}
function checkContribute(ID, lump) {
if (ID.indexOf("scr=contribute-") !== -1) {
var scr = ID.substring("scr=contribute-".length);
addLump(t.collectmap, scr, lump);
}
}
function debugLump(lump) {
// TODO expand this to agree with the Firebug "self-selector" idiom
return "<" + lump.tagname + ">";
}
function hasCssClass(clazz, totest) {
if (!totest) {
return false;
}
// algorithm from jQuery
return (" " + totest + " ").indexOf(" " + clazz + " ") !== -1;
}
function matchNode(term, headlump, headclazz) {
if (term.predList) {
for (var i = 0; i < term.predList.length; ++i) {
var pred = term.predList[i];
if (pred.id && headlump.attributemap.id !== pred.id) {return false;}
if (pred.clazz && !hasCssClass(pred.clazz, headclazz)) {return false;}
if (pred.tag && headlump.tagname !== pred.tag) {return false;}
}
return true;
}
}
function tagStartCut(headlump) {
var togo;
var headclazz = headlump.attributemap["class"];
var i;
if (headclazz) {
var split = headclazz.split(" ");
for (i = 0; i < split.length; ++i) {
var simpleCut = simpleClassCutpoints[$.trim(split[i])];
if (simpleCut) {
return simpleCut;
}
}
}
for (i = 0; i < cutpoints.length; ++i) {
var cut = cutpoints[i];
var cutstat = cutstatus[i];
var nextterm = cutstat.length; // the next term for this node
if (nextterm < cut.tree.length) {
var term = cut.tree[nextterm];
if (nextterm > 0) {
if (cut.tree[nextterm - 1].child &&
cutstat[nextterm - 1] !== headlump.nestingdepth - 1) {
continue; // it is a failure to match if not at correct nesting depth
}
}
var isMatch = matchNode(term, headlump, headclazz);
if (isMatch) {
cutstat[cutstat.length] = headlump.nestingdepth;
if (cutstat.length === cut.tree.length) {
if (togo !== undefined) {
fluid.fail("Cutpoint specification error - node " +
debugLump(headlump) +
" has already matched with rsf:id of " + togo);
}
if (cut.id === undefined || cut.id === null) {
fluid.fail("Error in cutpoints list - entry at position " + i + " does not have an id set");
}
togo = cut.id;
}
}
}
}
return togo;
}
function tagEndCut() {
if (cutpoints) {
for (var i = 0; i < cutpoints.length; ++i) {
var cutstat = cutstatus[i];
if (cutstat.length > 0 && cutstat[cutstat.length - 1] === nestingdepth) {
cutstat.length--;
}
}
}
}
function processTagEnd() {
tagEndCut();
var endlump = newLump();
--nestingdepth;
endlump.text = "</" + parser.getName() + ">";
var oldtop = tagstack[tagstack.length - 1];
oldtop.close_tag = t.lumps[lumpindex - 1];
tagstack.length--;
justended = true;
}
function processTagStart(isempty) {
++nestingdepth;
if (justended) {
justended = false;
var backlump = newLump();
backlump.nestingdepth--;
}
if (t.firstdocumentindex === -1) {
t.firstdocumentindex = lumpindex;
}
var headlump = newLump();
var stacktop = tagstack[tagstack.length - 1];
headlump.uplump = stacktop;
var tagname = parser.getName();
headlump.tagname = tagname;
// NB - attribute names and values are now NOT DECODED!!
var attrs = headlump.attributemap = parser.m_attributes;
var ID = attrs[fluid.ID_ATTRIBUTE];
if (ID === undefined) {
ID = tagStartCut(headlump);
}
for (var attrname in attrs) {
if (ID === undefined) {
if (/href|src|codebase|action/.test(attrname)) {
ID = "scr=rewrite-url";
}
// port of TPI effect of IDRelationRewriter
else if (ID === undefined && /for|headers/.test(attrname)) {
ID = "scr=null";
}
}
}
if (ID) {
// TODO: ensure this logic is correct on RSF Server
if (ID.charCodeAt(0) === 126) { // "~"
ID = ID.substring(1);
headlump.elide = true;
}
checkContribute(ID, headlump);
headlump.rsfID = ID;
var downreg = findTopContainer();
if (!downreg.downmap) {
downreg.downmap = {};
}
while (downreg) { // TODO: unusual fix for locating branches in parent contexts (applies to repetitive leaves)
if (downreg.downmap) {
addLump(downreg.downmap, ID, headlump);
}
downreg = downreg.uplump;
}
addLump(t.globalmap, ID, headlump);
var colpos = ID.indexOf(":");
if (colpos !== -1) {
var prefix = ID.substring(0, colpos);
if (!stacktop.finallump) {
stacktop.finallump = {};
}
stacktop.finallump[prefix] = headlump;
}
}
// TODO: accelerate this by grabbing original template text (requires parser
// adjustment) as well as dealing with empty tags
headlump.text = "<" + tagname + fluid.dumpAttributes(attrs) + (isempty && !ID ? "/>" : ">");
tagstack[tagstack.length] = headlump;
if (isempty) {
if (ID) {
processTagEnd();
}
else {
--nestingdepth;
tagstack.length--;
}
}
}
function processDefaultTag() {
if (defstart !== -1) {
if (t.firstdocumentindex === -1) {
t.firstdocumentindex = lumpindex;
}
var text = parser.getContent().substr(defstart, defend - defstart);
justended = false;
var newlump = newLump();
newlump.text = text;
defstart = -1;
}
}
/** ACTUAL BODY of fluid.parseTemplate begins here **/
t = fluid.XMLViewTemplate();
init(baseURL, opts.debugMode, cutpoints_in);
var idpos = template.indexOf(fluid.ID_ATTRIBUTE);
if (scanStart) {
var brackpos = template.indexOf(">", idpos);
parser = fluid.XMLP(template.substring(brackpos + 1));
}
else {
parser = fluid.XMLP(template);
}
parseloop: // eslint-disable-line indent
while (true) {
var iEvent = parser.next();
switch (iEvent) {
case fluid.XMLP._ELM_B:
processDefaultTag();
//var text = parser.getContent().substr(parser.getContentBegin(), parser.getContentEnd() - parser.getContentBegin());
processTagStart(false, "");
break;
case fluid.XMLP._ELM_E:
processDefaultTag();
processTagEnd();
break;
case fluid.XMLP._ELM_EMP:
processDefaultTag();
//var text = parser.getContent().substr(parser.getContentBegin(), parser.getContentEnd() - parser.getContentBegin());
processTagStart(true, "");
break;
case fluid.XMLP._PI:
case fluid.XMLP._DTD:
defstart = -1;
continue; // not interested in reproducing these
case fluid.XMLP._TEXT:
case fluid.XMLP._ENTITY:
case fluid.XMLP._CDATA:
case fluid.XMLP._COMMENT:
if (defstart === -1) {
defstart = parser.m_cB;
}
defend = parser.m_cE;
break;
case fluid.XMLP._ERROR:
fluid.setLogging(true);
var message = "Error parsing template: " + parser.m_cAlt + " at line " + parser.getLineNumber();
fluid.log(message);
fluid.log("Just read: " + parser.m_xml.substring(parser.m_iP - 30, parser.m_iP));
fluid.log("Still to read: " + parser.m_xml.substring(parser.m_iP, parser.m_iP + 30));
fluid.fail(message);
break parseloop;
case fluid.XMLP._NONE:
break parseloop;
}
}
processDefaultTag();
var excess = tagstack.length - 1;
if (excess) {
fluid.fail("Error parsing template - unclosed tag(s) of depth " + (excess) +
": " + fluid.transform(tagstack.splice(1, excess), function (lump) {return debugLump(lump);}).join(", "));
}
return t;
};
// unsupported, non-API function
fluid.debugLump = function (lump) {
var togo = lump.text;
togo += " at ";
togo += "lump line " + lump.line + " column " + lump.column + " index " + lump.lumpindex;
togo += lump.parent.href === null ? "" : " in file " + lump.parent.href;
return togo;
};
// Public definitions begin here
fluid.ID_ATTRIBUTE = "rsf:id";
// unsupported, non-API function
fluid.getPrefix = function (id) {
var colpos = id.indexOf(":");
return colpos === -1 ? id : id.substring(0, colpos);
};
// unsupported, non-API function
fluid.SplitID = function (id) {
var that = {};
var colpos = id.indexOf(":");
if (colpos === -1) {
that.prefix = id;
}
else {
that.prefix = id.substring(0, colpos);
that.suffix = id.substring(colpos + 1);
}
return that;
};
// unsupported, non-API function
fluid.XMLViewTemplate = function () {
return {
globalmap: {},
collectmap: {},
lumps: [],
firstdocumentindex: -1
};
};
// TODO: find faster encoder
fluid.XMLEncode = function (text) {
return text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/\"/g, """);
};
// unsupported, non-API function
fluid.dumpAttributes = function (attrcopy) {
var togo = "";
for (var attrname in attrcopy) {
var attrvalue = attrcopy[attrname];
if (attrvalue !== null && attrvalue !== undefined) {
togo += " " + attrname + "=\"" + attrvalue + "\"";
}
}
return togo;
};
// unsupported, non-API function
fluid.aggregateMMap = function (target, source) {
for (var key in source) {
var targhas = target[key];
if (!targhas) {
target[key] = [];
}
target[key] = target[key].concat(source[key]);
}
};
/* Returns a "template structure", with globalmap in the root, and a list
* of entries {href, template, cutpoints} for each parsed template.
*/
fluid.parseTemplates = function (resourceSpec, templateList, opts) {
var togo = [];
opts = opts || {};
togo.globalmap = {};
for (var i = 0; i < templateList.length; ++i) {
var resource = resourceSpec[templateList[i]];
var lastslash = resource.href.lastIndexOf("/");
var baseURL = lastslash === -1 ? "" : resource.href.substring(0, lastslash + 1);
var template = fluid.parseTemplate(resource.resourceText, baseURL,
opts.scanStart && i === 0, resource.cutpoints, opts);
if (i === 0) {
fluid.aggregateMMap(togo.globalmap, template.globalmap);
}
template.href = resource.href;
template.baseURL = baseURL;
template.resourceKey = resource.resourceKey;
togo[i] = template;
fluid.aggregateMMap(togo.globalmap, template.rootlump.downmap);
}
return togo;
};
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
function debugPosition(component) {
return "as child of " + (component.parent.fullID ? "component with full ID " + component.parent.fullID : "root");
}
function computeFullID(component) {
var togo = "";
var move = component;
if (component.children === undefined) { // not a container
// unusual case on the client-side, since a repetitive leaf may have localID blasted onto it.
togo = component.ID + (component.localID !== undefined ? component.localID : "");
move = component.parent;
}
while (move.parent) {
var parent = move.parent;
if (move.fullID !== undefined) {
togo = move.fullID + togo;
return togo;
}
if (move.noID === undefined) {
var ID = move.ID;
if (ID === undefined) {
fluid.fail("Error in component tree - component found with no ID " +
debugPosition(parent) + ": please check structure");
}
var colpos = ID.indexOf(":");
var prefix = colpos === -1 ? ID : ID.substring(0, colpos);
togo = prefix + ":" + (move.localID === undefined ? "" : move.localID) + ":" + togo;
}
move = parent;
}
return togo;
}
var renderer = {};
renderer.isBoundPrimitive = function (value) {
return fluid.isPrimitive(value) || fluid.isArrayable(value) &&
(value.length === 0 || typeof (value[0]) === "string");
};
var unzipComponent;
function processChild(value, key) {
if (renderer.isBoundPrimitive(value)) {
return {componentType: "UIBound", value: value, ID: key};
}
else {
var unzip = unzipComponent(value);
if (unzip.ID) {
return {ID: key, componentType: "UIContainer", children: [unzip]};
} else {
unzip.ID = key;
return unzip;
}
}
}
function fixChildren(children) {
if (!fluid.isArrayable(children)) {
var togo = [];
for (var key in children) {
var value = children[key];
if (fluid.isArrayable(value)) {
for (var i = 0; i < value.length; ++i) {
var processed = processChild(value[i], key);
// if (processed.componentType === "UIContainer" &&
// processed.localID === undefined) {
// processed.localID = i;
// }
togo[togo.length] = processed;
}
} else {
togo[togo.length] = processChild(value, key);
}
}
return togo;
} else {return children; }
}
function fixupValue(uibound, model, resolverGetConfig) {
if (uibound.value === undefined && uibound.valuebinding !== undefined) {
uibound.value = fluid.get(model, uibound.valuebinding, resolverGetConfig);
}
}
function upgradeBound(holder, property, model, resolverGetConfig) {
if (holder[property] !== undefined) {
if (renderer.isBoundPrimitive(holder[property])) {
holder[property] = {value: holder[property]};
}
else if (holder[property].messagekey) {
holder[property].componentType = "UIMessage";
}
}
else {
holder[property] = {value: null};
}
fixupValue(holder[property], model, resolverGetConfig);
}
renderer.duckMap = {children: "UIContainer",
value: "UIBound", valuebinding: "UIBound", messagekey: "UIMessage",
markup: "UIVerbatim", selection: "UISelect", target: "UILink",
choiceindex: "UISelectChoice", functionname: "UIInitBlock"};
var boundMap = {
UISelect: ["selection", "optionlist", "optionnames"],
UILink: ["target", "linktext"],
UIVerbatim: ["markup"],
UIMessage: ["messagekey"]
};
renderer.boundMap = fluid.transform(boundMap, fluid.arrayToHash);
renderer.inferComponentType = function (component) {
for (var key in renderer.duckMap) {
if (component[key] !== undefined) {
return renderer.duckMap[key];
}
}
};
renderer.applyComponentType = function (component) {
component.componentType = renderer.inferComponentType(component);
if (component.componentType === undefined && component.ID !== undefined) {
component.componentType = "UIBound";
}
};
unzipComponent = function (component, model, resolverGetConfig) {
if (component) {
renderer.applyComponentType(component);
}
if (!component || component.componentType === undefined) {
var decorators = component.decorators;
if (decorators) {delete component.decorators;}
component = {componentType: "UIContainer", children: component};
component.decorators = decorators;
}
var cType = component.componentType;
if (cType === "UIContainer") {
component.children = fixChildren(component.children);
}
else {
var map = renderer.boundMap[cType];
if (map) {
fluid.each(map, function (value, key) {
upgradeBound(component, key, model, resolverGetConfig);
});
}
}
return component;
};
function fixupTree(tree, model, resolverGetConfig) {
if (tree.componentType === undefined) {
tree = unzipComponent(tree, model, resolverGetConfig);
}
if (tree.componentType !== "UIContainer" && !tree.parent) {
tree = {children: [tree]};
}
if (tree.children) {
tree.childmap = {};
for (var i = 0; i < tree.children.length; ++i) {
var child = tree.children[i];
if (child.componentType === undefined) {
child = unzipComponent(child, model, resolverGetConfig);
tree.children[i] = child;
}
child.parent = tree;
if (child.ID === undefined) {
fluid.fail("Error in component tree: component found with no ID " + debugPosition(child));
}
tree.childmap[child.ID] = child;
var colpos = child.ID.indexOf(":");
if (colpos === -1) {
// tree.childmap[child.ID] = child; // moved out of branch to allow
// "relative id expressions" to be easily parsed
}
else {
var prefix = child.ID.substring(0, colpos);
var childlist = tree.childmap[prefix];
if (!childlist) {
childlist = [];
tree.childmap[prefix] = childlist;
}
if (child.localID === undefined && childlist.length !== 0) {
child.localID = childlist.length;
}
childlist[childlist.length] = child;
}
child.fullID = computeFullID(child);
var componentType = child.componentType;
if (componentType === "UISelect") {
child.selection.fullID = child.fullID;
}
else if (componentType === "UIInitBlock") {
var call = child.functionname + "(";
var childArgs = child.arguments;
for (var j = 0; j < childArgs.length; ++j) {
if (childArgs[j] instanceof fluid.ComponentReference) {
// TODO: support more forms of id reference
childArgs[j] = child.parent.fullID + childArgs[j].reference;
}
call += JSON.stringify(childArgs[j]);
if (j < childArgs.length - 1) {
call += ", ";
}
}
child.markup = {value: call + ")\n"};
child.componentType = "UIVerbatim";
}
else if (componentType === "UIBound") {
fixupValue(child, model, resolverGetConfig);
}
fixupTree(child, model, resolverGetConfig);
}
}
return tree;
}
fluid.NULL_STRING = "\u25a9null\u25a9";
var LINK_ATTRIBUTES = {
a: "href",
link: "href",
img: "src",
frame: "src",
script: "src",
style: "src",
input: "src",
embed: "src",
form: "action",
applet: "codebase",
object: "codebase"
};
renderer.decoratorComponentPrefix = "**-renderer-";
renderer.IDtoComponentName = function (ID, num) {
return renderer.decoratorComponentPrefix + ID.replace(/\./g, "") + "-" + num;
};
renderer.invokeFluidDecorator = function (func, args, ID, num, options) {
var that;
if (options.parentComponent) {
var parent = options.parentComponent;
var name = renderer.IDtoComponentName(ID, num);
fluid.set(parent, ["options", "components", name], {
type: func,
container: args[0],
options: args[1]
});
that = fluid.initDependent(options.parentComponent, name);
}
else {
that = fluid.invokeGlobalFunction(func, args);
}
return that;
};
fluid.renderer = function (templates, tree, options, fossilsIn) {
options = options || {};
tree = tree || {};
var debugMode = options.debugMode;
if (!options.messageLocator && options.messageSource) {
options.messageLocator = fluid.resolveMessageSource(options.messageSource);
}
options.document = options.document || document;
options.jQuery = options.jQuery || $;
options.fossils = options.fossils || fossilsIn || {}; // map of submittingname to {EL, submittingname, oldvalue}
var globalmap = {};
var branchmap = {};
var rewritemap = {}; // map of rewritekey (for original id in template) to full ID
var seenset = {};
var collected = {};
var out = "";
var renderOptions = options;
var decoratorQueue = [];
var renderedbindings = {}; // map of fullID to true for UISelects which have already had bindings written
var usedIDs = {};
var that = {options: options};
function getRewriteKey(template, parent, id) {
return template.resourceKey + parent.fullID + id;
}
// returns: lump
function resolveInScope(searchID, defprefix, scope) {
var deflump;
var scopelook = scope ? scope[searchID] : null;
if (scopelook) {
for (var i = 0; i < scopelook.length; ++i) {
var scopelump = scopelook[i];
if (!deflump && scopelump.rsfID === defprefix) {
deflump = scopelump;
}
if (scopelump.rsfID === searchID) {
return scopelump;
}
}
}
return deflump;
}
// returns: lump
function resolveCall(sourcescope, child) {
var searchID = child.jointID ? child.jointID : child.ID;
var split = fluid.SplitID(searchID);
var defprefix = split.prefix + ":";
var match = resolveInScope(searchID, defprefix, sourcescope.downmap, child);
if (match) {return match;}
if (child.children) {
match = resolveInScope(searchID, defprefix, globalmap, child);
if (match) {return match;}
}
return null;
}
function noteCollected(template) {
if (!seenset[template.href]) {
fluid.aggregateMMap(collected, template.collectmap);
seenset[template.href] = true;
}
}
var fetchComponent;
function resolveRecurse(basecontainer, parentlump) {
var i;
var id;
var resolved;
for (i = 0; i < basecontainer.children.length; ++i) {
var branch = basecontainer.children[i];
if (branch.children) { // it is a branch
resolved = resolveCall(parentlump, branch);
if (resolved) {
branchmap[branch.fullID] = resolved;
id = resolved.attributemap.id;
if (id !== undefined) {
rewritemap[getRewriteKey(parentlump.parent, basecontainer, id)] = branch.fullID;
}
// on server-side this is done separately
noteCollected(resolved.parent);
resolveRecurse(branch, resolved);
}
}
}
// collect any rewritten ids for the purpose of later rewriting
if (parentlump.downmap) {
for (id in parentlump.downmap) {
//if (id.indexOf(":") === -1) {
var lumps = parentlump.downmap[id];
for (i = 0; i < lumps.length; ++i) {
var lump = lumps[i];
var lumpid = lump.attributemap.id;
if (lumpid !== undefined && lump.rsfID !== undefined) {
resolved = fetchComponent(basecontainer, lump.rsfID);
if (resolved !== null) {
var resolveID = resolved.fullID;
rewritemap[getRewriteKey(parentlump.parent, basecontainer,
lumpid)] = resolveID;
}
}
}
// }
}
}
}
function resolveBranches(globalmapp, basecontainer, parentlump) {
branchmap = {};
rewritemap = {};
seenset = {};
collected = {};
globalmap = globalmapp;
branchmap[basecontainer.fullID] = parentlump;
resolveRecurse(basecontainer, parentlump);
}
function dumpTillLump(lumps, start, limit) {
for (; start < limit; ++start) {
var text = lumps[start].text;
if (text) { // guard against "undefined" lumps from "justended"
out += lumps[start].text;
}
}
}
function dumpScan(lumps, renderindex, basedepth, closeparent, insideleaf) {
var start = renderindex;
while (true) {
if (renderindex === lumps.length) {
break;
}
var lump = lumps[renderindex];
if (lump.nestingdepth < basedepth) {
break;
}
if (lump.rsfID !== undefined) {
if (!insideleaf) {break;}
if (insideleaf && lump.nestingdepth > basedepth + (closeparent ? 0 : 1)) {
fluid.log("Error in component tree - leaf component found to contain further components - at " +
lump.toString());
}
else {break;}
}
// target.print(lump.text);
++renderindex;
}
// ASSUMPTIONS: close tags are ONE LUMP
if (!closeparent && (renderindex === lumps.length || !lumps[renderindex].rsfID)) {
--renderindex;
}
dumpTillLump(lumps, start, renderindex);
//target.write(buffer, start, limit - start);
return renderindex;
}
function isPlaceholder() {
// TODO: equivalent of server-side "placeholder" system
return false;
}
function isValue(value) {
return value !== null && value !== undefined && !isPlaceholder(value);
}
// In RSF Client, this is a "flyweight" "global" object that is reused for every tag,
// to avoid generating garbage. In RSF Server, it is an argument to the following rendering
// methods of type "TagRenderContext".
var trc = {};
/*** TRC METHODS ***/
function openTag() {
if (!trc.iselide) {
out += "<" + trc.uselump.tagname;
}
}
function closeTag() {
if (!trc.iselide) {
out += "</" + trc.uselump.tagname + ">";
}
}
function renderUnchanged() {
// TODO needs work since we don't keep attributes in text
dumpTillLump(trc.uselump.parent.lumps, trc.uselump.lumpindex + 1,
trc.close.lumpindex + (trc.iselide ? 0 : 1));
}
function isSelfClose() {
return trc.endopen.lumpindex === trc.close.lumpindex && fluid.XMLP.closedTags[trc.uselump.tagname];
}
function dumpTemplateBody() {
if (isSelfClose()) {
if (!trc.iselide) {
out += "/>";
}
}
else {
if (!trc.iselide) {
out += ">";
}
dumpTillLump(trc.uselump.parent.lumps, trc.endopen.lumpindex,
trc.close.lumpindex + (trc.iselide ? 0 : 1));
}
}
function replaceAttributes() {
if (!trc.iselide) {
out += fluid.dumpAttributes(trc.attrcopy);
}
dumpTemplateBody();
}
function replaceAttributesOpen() {
if (trc.iselide) {
replaceAttributes();
}
else {
out += fluid.dumpAttributes(trc.attrcopy);
var selfClose = isSelfClose();
// TODO: the parser does not ever produce empty tags
out += selfClose ? "/>" : ">";
trc.nextpos = selfClose ? trc.close.lumpindex + 1 : trc.endopen.lumpindex;
}
}
function replaceBody(value) {
out += fluid.dumpAttributes(trc.attrcopy);
if (!trc.iselide) {
out += ">";
}
out += fluid.XMLEncode(value.toString());
closeTag();
}
function rewriteLeaf(value) {
if (isValue(value)) {
replaceBody(value);
}
else {
replaceAttributes();
}
}
function rewriteLeafOpen(value) {
if (trc.iselide) {
rewriteLeaf(trc.value);
}
else {
if (isValue(value)) {
replaceBody(value);
}
else {
replaceAttributesOpen();
}
}
}
/*** END TRC METHODS**/
function rewriteUrl(template, url) {
if (renderOptions.urlRewriter) {
var rewritten = renderOptions.urlRewriter(url);
if (rewritten) {
return rewritten;
}
}
if (!renderOptions.rebaseURLs) {
return url;
}
var protpos = url.indexOf(":/");
if (url.charAt(0) === "/" || protpos !== -1 && protpos < 7) {
return url;
}
else {
return renderOptions.baseURL + url;
}
}
function dumpHiddenField(/** UIParameter **/ todump) {
out += "<input type=\"hidden\" ";
var isvirtual = todump.virtual;
var outattrs = {};
outattrs[isvirtual ? "id" : "name"] = todump.name;
outattrs.value = todump.value;
out += fluid.dumpAttributes(outattrs);
out += " />\n";
}
var outDecoratorsImpl;
function applyAutoBind(torender, finalID) {
if (!finalID) {
// if no id is assigned so far, this is a signal that this is a "virtual" component such as
// a non-HTML UISelect which will not have physical markup.
return;
}
var tagname = trc.uselump.tagname;
var applier = renderOptions.applier;
function applyFunc() {
fluid.applyBoundChange(fluid.byId(finalID, renderOptions.document), undefined, applier);
}
if (renderOptions.autoBind && /input|select|textarea/.test(tagname) && !renderedbindings[finalID]) {
var decorators = [{jQuery: ["change", applyFunc]}];
// Work around bug 193: http://webbugtrack.blogspot.com/2007/11/bug-193-onchange-does-not-fire-properly.html
if ($.browser.msie && tagname === "input" && /radio|checkbox/.test(trc.attrcopy.type)) {
decorators.push({jQuery: ["click", applyFunc]});
}
if ($.browser.safari && tagname === "input" && trc.attrcopy.type === "radio") {
decorators.push({jQuery: ["keyup", applyFunc]});
}
outDecoratorsImpl(torender, decorators, trc.attrcopy, finalID);
}
}
function dumpBoundFields(/** UIBound**/ torender, parent) {
if (torender) {
var holder = parent ? parent : torender;
if (renderOptions.fossils && holder.valuebinding !== undefined) {
var fossilKey = holder.submittingname || torender.finalID;
// TODO: this will store multiple times for each member of a UISelect
renderOptions.fossils[fossilKey] = {
name: fossilKey,
EL: holder.valuebinding,
oldvalue: holder.value
};
// But this has to happen multiple times
applyAutoBind(torender, torender.finalID);
}
if (torender.fossilizedbinding) {
dumpHiddenField(torender.fossilizedbinding);
}
if (torender.fossilizedshaper) {
dumpHiddenField(torender.fossilizedshaper);
}
}
}
function dumpSelectionBindings(uiselect) {
if (!renderedbindings[uiselect.selection.fullID]) {
renderedbindings[uiselect.selection.fullID] = true; // set this true early so that selection does not autobind twice
dumpBoundFields(uiselect.selection);
dumpBoundFields(uiselect.optionlist);
dumpBoundFields(uiselect.optionnames);
}
}
function isSelectedValue(torender, value) {
var selection = torender.selection;
return fluid.isArrayable(selection.value) ? selection.value.indexOf(value) !== -1 : selection.value === value;
}
function getRelativeComponent(component, relativeID) {
component = component.parent;
while (relativeID.indexOf("..::") === 0) {
relativeID = relativeID.substring(4);
component = component.parent;
}
return component.childmap[relativeID];
}
// TODO: This mechanism inefficiently handles the rare case of a target document
// id collision requiring a rewrite for FLUID-5048. In case it needs improving, we
// could hold an inverted index - however, these cases will become even rarer with FLUID-5047
function rewriteRewriteMap(from, to) {
fluid.each(rewritemap, function (value, key) {
if (value === from) {
rewritemap[key] = to;
}
});
}
function adjustForID(attrcopy, component, late, forceID) {
if (!late) {
delete attrcopy["rsf:id"];
}
if (component.finalID !== undefined) {
attrcopy.id = component.finalID;
}
else if (forceID !== undefined) {
attrcopy.id = forceID;
}
else {
if (attrcopy.id || late) {
attrcopy.id = component.fullID;
}
}
var count = 1;
var baseid = attrcopy.id;
while (renderOptions.document.getElementById(attrcopy.id) || usedIDs[attrcopy.id]) {
attrcopy.id = baseid + "-" + (count++);
}
if (count !== 1) {
rewriteRewriteMap(baseid, attrcopy.id);
}
component.finalID = attrcopy.id;
return attrcopy.id;
}
function assignSubmittingName(attrcopy, component, parent) {
var submitting = parent || component;
// if a submittingName is required, we must already go out to the document to
// uniquify the id that it will be derived from
adjustForID(attrcopy, component, true, component.fullID);
if (submitting.submittingname === undefined && submitting.willinput !== false) {
submitting.submittingname = submitting.finalID || submitting.fullID;
}
return submitting.submittingname;
}
function explodeDecorators(decorators) {
var togo = [];
if (decorators.type) {
togo[0] = decorators;
}
else {
for (var key in decorators) {
if (key === "$") {key = "jQuery";}
var value = decorators[key];
var decorator = {
type: key
};
if (key === "jQuery") {
decorator.func = value[0];
decorator.args = value.slice(1);
}
else if (key === "addClass" || key === "removeClass") {
decorator.classes = value;
}
else if (key === "attrs") {
decorator.attributes = value;
}
else if (key === "identify") {
decorator.key = value;
}
togo[togo.length] = decorator;
}
}
return togo;
}
outDecoratorsImpl = function (torender, decorators, attrcopy, finalID) {
var id;
var sanitizeAttrs = function (value, key) {
if (value === null || value === undefined) {
delete attrcopy[key];
}
else {
attrcopy[key] = fluid.XMLEncode(value);
}
};
renderOptions.idMap = renderOptions.idMap || {};
for (var i = 0; i < decorators.length; ++i) {
var decorator = decorators[i];
var type = decorator.type;
if (!type) {
var explodedDecorators = explodeDecorators(decorator);
outDecoratorsImpl(torender, explodedDecorators, attrcopy, finalID);
continue;
}
if (type === "$") {type = decorator.type = "jQuery";}
if (type === "jQuery" || type === "event" || type === "fluid") {
id = adjustForID(attrcopy, torender, true, finalID);
if (decorator.ids === undefined) {
decorator.ids = [];
decoratorQueue[decoratorQueue.length] = decorator;
}
decorator.ids.push(id);
}
// honour these remaining types immediately
else if (type === "attrs") {
fluid.each(decorator.attributes, sanitizeAttrs);
}
else if (type === "addClass" || type === "removeClass") {
// Using an unattached DOM node because jQuery will use the
// node's setAttribute method to add the class.
var fakeNode = $("<div>", {class: attrcopy["class"]})[0];
renderOptions.jQuery(fakeNode)[type](decorator.classes);
attrcopy["class"] = fakeNode.className;
}
else if (type === "identify") {
id = adjustForID(attrcopy, torender, true, finalID);
renderOptions.idMap[decorator.key] = id;
}
else if (type !== "null") {
fluid.log("Unrecognised decorator of type " + type + " found at component of ID " + finalID);
}
}
};
function outDecorators(torender, attrcopy) {
if (!torender.decorators) {return;}
if (torender.decorators.length === undefined) {
torender.decorators = explodeDecorators(torender.decorators);
}
outDecoratorsImpl(torender, torender.decorators, attrcopy);
}
function dumpBranchHead(branch, targetlump) {
if (targetlump.elide) {
return;
}
var attrcopy = {};
$.extend(true, attrcopy, targetlump.attributemap);
adjustForID(attrcopy, branch);
outDecorators(branch, attrcopy);
out += "<" + targetlump.tagname + " ";
out += fluid.dumpAttributes(attrcopy);
out += ">";
}
function resolveArgs(args) {
if (!args) {return args;}
args = fluid.copy(args); // FLUID-4737: Avoid corrupting material which may have been fetched from the model
return fluid.transform(args, function (arg, index) {
upgradeBound(args, index, renderOptions.model, renderOptions.resolverGetConfig);
return args[index].value;
});
}
function degradeMessage(torender) {
if (torender.componentType === "UIMessage") {
// degrade UIMessage to UIBound by resolving the message
torender.componentType = "UIBound";
if (!renderOptions.messageLocator) {
torender.value = "[No messageLocator is configured in options - please consult documentation on options.messageSource]";
}
else {
upgradeBound(torender, "messagekey", renderOptions.model, renderOptions.resolverGetConfig);
var resArgs = resolveArgs(torender.args);
torender.value = renderOptions.messageLocator(torender.messagekey.value, resArgs);
}
}
}
function renderComponent(torender) {
var value;
var attrcopy = trc.attrcopy;
degradeMessage(torender);
var componentType = torender.componentType;
var tagname = trc.uselump.tagname;
outDecorators(torender, attrcopy);
function makeFail(torender, end) {
fluid.fail("Error in component tree - UISelectChoice with id " + torender.fullID + end);
}
if (componentType === "UIBound" || componentType === "UISelectChoice") {
var parent;
if (torender.choiceindex !== undefined) {
if (torender.parentRelativeID !== undefined) {
parent = getRelativeComponent(torender, torender.parentRelativeID);
if (!parent) {
makeFail(torender, " has parentRelativeID of " + torender.parentRelativeID + " which cannot be resolved");
}
}
else {
makeFail(torender, " does not have parentRelativeID set");
}
assignSubmittingName(attrcopy, torender, parent.selection);
dumpSelectionBindings(parent);
}
var submittingname = parent ? parent.selection.submittingname : torender.submittingname;
if (!parent && torender.valuebinding) {
// Do this for all bound fields even if non submitting so that finalID is set in order to track fossils (FLUID-3387)
submittingname = assignSubmittingName(attrcopy, torender);
}
if (tagname === "input" || tagname === "textarea") {
if (submittingname !== undefined) {
attrcopy.name = submittingname;
}
}
// this needs to happen early on the client, since it may cause the allocation of the
// id in the case of a "deferred decorator". However, for server-side bindings, this
// will be an inappropriate time, unless we shift the timing of emitting the opening tag.
dumpBoundFields(torender, parent ? parent.selection : null);
if (typeof(torender.value) === "boolean" || attrcopy.type === "radio" || attrcopy.type === "checkbox") {
var underlyingValue;
var directValue = torender.value;
if (torender.choiceindex !== undefined) {
if (!parent.optionlist.value) {
fluid.fail("Error in component tree - selection control with full ID " + parent.fullID + " has no values");
}
underlyingValue = parent.optionlist.value[torender.choiceindex];
directValue = isSelectedValue(parent, underlyingValue);
}
if (isValue(directValue)) {
if (directValue) {
attrcopy.checked = "checked";
}
else {
delete attrcopy.checked;
}
}
attrcopy.value = fluid.XMLEncode(underlyingValue ? underlyingValue : "true");
rewriteLeaf(null);
}
else if (fluid.isArrayable(torender.value)) {
// Cannot be rendered directly, must be fake
renderUnchanged();
}
else { // String value
value = parent ?
parent[tagname === "textarea" || tagname === "input" ? "optionlist" : "optionnames"].value[torender.choiceindex] :
torender.value;
if (tagname === "textarea") {
if (isPlaceholder(value) && torender.willinput) {
// FORCE a blank value for input components if nothing from
// model, if input was intended.
value = "";
}
rewriteLeaf(value);
}
else if (tagname === "input") {
if (torender.willinput || isValue(value)) {
attrcopy.value = fluid.XMLEncode(String(value));
}
rewriteLeaf(null);
}
else {
delete attrcopy.name;
rewriteLeafOpen(value);
}
}
}
else if (componentType === "UISelect") {
var ishtmlselect = tagname === "select";
var ismultiple = false; // eslint-disable-line no-unused-vars
if (fluid.isArrayable(torender.selection.value)) {
ismultiple = true;
if (ishtmlselect) {
attrcopy.multiple = "multiple";
}
}
// assignSubmittingName is now the definitive trigger point for uniquifying output IDs
// However, if id is already assigned it is probably through attempt to decorate root select.
// in this case restore it.
assignSubmittingName(attrcopy, torender.selection);
if (ishtmlselect) {
// The HTML submitted value from a <select> actually corresponds
// with the selection member, not the top-level component.
if (torender.selection.willinput !== false) {
attrcopy.name = torender.selection.submittingname;
}
applyAutoBind(torender, attrcopy.id);
}
out += fluid.dumpAttributes(attrcopy);
if (ishtmlselect) {
out += ">";
var values = torender.optionlist.value;
var names = torender.optionnames === null || torender.optionnames === undefined || !torender.optionnames.value ? values : torender.optionnames.value;
if (!names || !names.length) {
fluid.fail("Error in component tree - UISelect component with fullID " +
torender.fullID + " does not have optionnames set");
}
for (var i = 0; i < names.length; ++i) {
out += "<option value=\"";
value = values[i];
if (value === null) {
value = fluid.NULL_STRING;
}
out += fluid.XMLEncode(value);
if (isSelectedValue(torender, value)) {
out += "\" selected=\"selected";
}
out += "\">";
out += fluid.XMLEncode(names[i]);
out += "</option>\n";
}
closeTag();
}
else {
dumpTemplateBody();
}
dumpSelectionBindings(torender);
}
else if (componentType === "UILink") {
var attrname = LINK_ATTRIBUTES[tagname];
if (attrname) {
degradeMessage(torender.target);
var target = torender.target.value;
if (!isValue(target)) {
target = attrcopy[attrname];
}
target = rewriteUrl(trc.uselump.parent, target);
// Note that all real browsers succeed in recovering the URL here even if it is presented in violation of XML
// seemingly due to the purest accident, the text & cannot occur in a properly encoded URL :P
attrcopy[attrname] = fluid.XMLEncode(target);
}
value = undefined;
if (torender.linktext) {
degradeMessage(torender.linktext);
value = torender.linktext.value;
}
if (!isValue(value)) {
replaceAttributesOpen();
}
else {
rewriteLeaf(value);
}
}
else if (torender.markup !== undefined) { // detect UIVerbatim
degradeMessage(torender.markup);
var rendered = torender.markup.value;
if (rendered === null) {
// TODO, doesn't quite work due to attr folding cf Java code
out += fluid.dumpAttributes(attrcopy);
out += ">";
renderUnchanged();
}
else {
if (!trc.iselide) {
out += fluid.dumpAttributes(attrcopy);
out += ">";
}
out += rendered;
closeTag();
}
}
if (attrcopy.id !== undefined) {
usedIDs[attrcopy.id] = true;
}
}
function rewriteIDRelation(context) {
var attrname;
var attrval = trc.attrcopy["for"];
if (attrval !== undefined) {
attrname = "for";
}
else {
attrval = trc.attrcopy.headers;
if (attrval !== undefined) {
attrname = "headers";
}
}
if (!attrname) {return;}
var tagname = trc.uselump.tagname;
if (attrname === "for" && tagname !== "label") {return;}
if (attrname === "headers" && tagname !== "td" && tagname !== "th") {return;}
var rewritten = rewritemap[getRewriteKey(trc.uselump.parent, context, attrval)];
if (rewritten !== undefined) {
trc.attrcopy[attrname] = rewritten;
}
}
function renderComment(message) {
out += ("<!-- " + fluid.XMLEncode(message) + "-->");
}
function renderDebugMessage(message) {
out += "<span style=\"background-color:#FF466B;color:white;padding:1px;\">";
out += message;
out += "</span><br/>";
}
function reportPath(/*UIComponent*/ branch) {
var path = branch.fullID;
return !path ? "component tree root" : "full path " + path;
}
function renderComponentSystem(context, torendero, lump) {
var lumpindex = lump.lumpindex;
var lumps = lump.parent.lumps;
var nextpos = -1;
var outerendopen = lumps[lumpindex + 1];
var outerclose = lump.close_tag;
nextpos = outerclose.lumpindex + 1;
var payloadlist = lump.downmap ? lump.downmap["payload-component"] : null;
var payload = payloadlist ? payloadlist[0] : null;
var iselide = lump.rsfID.charCodeAt(0) === 126; // "~"
var endopen = outerendopen;
var close = outerclose;
var uselump = lump;
var attrcopy = {};
$.extend(true, attrcopy, (payload === null ? lump : payload).attributemap);
trc.attrcopy = attrcopy;
trc.uselump = uselump;
trc.endopen = endopen;
trc.close = close;
trc.nextpos = nextpos;
trc.iselide = iselide;
rewriteIDRelation(context);
if (torendero === null) {
if (lump.rsfID.indexOf("scr=") === (iselide ? 1 : 0)) {
var scrname = lump.rsfID.substring(4 + (iselide ? 1 : 0));
if (scrname === "ignore") {
nextpos = trc.close.lumpindex + 1;
}
else if (scrname === "rewrite-url") {
torendero = {componentType: "UILink", target: {}};
}
else {
openTag();
replaceAttributesOpen();
nextpos = trc.endopen.lumpindex;
}
}
}
if (torendero !== null) {
// else there IS a component and we are going to render it. First make
// sure we render any preamble.
if (payload) {
trc.endopen = lumps[payload.lumpindex + 1];
trc.close = payload.close_tag;
trc.uselump = payload;
dumpTillLump(lumps, lumpindex, payload.lumpindex);
lumpindex = payload.lumpindex;
}
adjustForID(attrcopy, torendero);
//decoratormanager.decorate(torendero.decorators, uselump.getTag(), attrcopy);
// ALWAYS dump the tag name, this can never be rewritten. (probably?!)
openTag();
renderComponent(torendero);
// if there is a payload, dump the postamble.
if (payload !== null) {
// the default case is initialised to tag close
if (trc.nextpos === nextpos) {
dumpTillLump(lumps, trc.close.lumpindex + 1, outerclose.lumpindex + 1);
}
}
nextpos = trc.nextpos;
}
return nextpos;
}
var renderRecurse;
function renderContainer(child, targetlump) {
var t2 = targetlump.parent;
var firstchild = t2.lumps[targetlump.lumpindex + 1];
if (child.children !== undefined) {
dumpBranchHead(child, targetlump);
}
else {
renderComponentSystem(child.parent, child, targetlump);
}
renderRecurse(child, targetlump, firstchild);
}
fetchComponent = function (basecontainer, id) {
if (id.indexOf("msg=") === 0) {
var key = id.substring(4);
return {componentType: "UIMessage", messagekey: key};
}
while (basecontainer) {
var togo = basecontainer.childmap[id];
if (togo) {
return togo;
}
basecontainer = basecontainer.parent;
}
return null;
};
function fetchComponents(basecontainer, id) {
var togo;
while (basecontainer) {
togo = basecontainer.childmap[id];
if (togo) {
break;
}
basecontainer = basecontainer.parent;
}
return togo;
}
function findChild(sourcescope, child) {
var split = fluid.SplitID(child.ID);
var headlumps = sourcescope.downmap[child.ID];
if (!headlumps) {
headlumps = sourcescope.downmap[split.prefix + ":"];
}
return headlumps ? headlumps[0] : null;
}
renderRecurse = function (basecontainer, parentlump, baselump) {
var children;
var targetlump;
var child;
var renderindex = baselump.lumpindex;
var basedepth = parentlump.nestingdepth;
var t1 = parentlump.parent;
var rendered;
if (debugMode) {
rendered = {};
}
while (true) {
renderindex = dumpScan(t1.lumps, renderindex, basedepth, !parentlump.elide, false);
if (renderindex === t1.lumps.length) {
break;
}
var lump = t1.lumps[renderindex];
var id = lump.rsfID;
// new stopping rule - we may have been inside an elided tag
if (lump.nestingdepth < basedepth || id === undefined) {
break;
}
if (id.charCodeAt(0) === 126) { // "~"
id = id.substring(1);
}
//var ismessagefor = id.indexOf("message-for:") === 0;
if (id.indexOf(":") !== -1) {
var prefix = fluid.getPrefix(id);
children = fetchComponents(basecontainer, prefix);
var finallump = lump.uplump.finallump[prefix];
var closefinal = finallump.close_tag;
if (children) {
for (var i = 0; i < children.length; ++i) {
child = children[i];
if (child.children) { // it is a branch
if (debugMode) {
rendered[child.fullID] = true;
}
targetlump = branchmap[child.fullID];
if (targetlump) {
if (debugMode) {
renderComment("Branching for " + child.fullID + " from " +
fluid.debugLump(lump) + " to " + fluid.debugLump(targetlump));
}
renderContainer(child, targetlump);
if (debugMode) {
renderComment("Branch returned for " + child.fullID +
fluid.debugLump(lump) + " to " + fluid.debugLump(targetlump));
}
}
else if (debugMode) {
renderDebugMessage(
"No matching template branch found for branch container with full ID " +
child.fullID +
" rendering from parent template branch " +
fluid.debugLump(baselump));
}
}
else { // repetitive leaf
targetlump = findChild(parentlump, child);
if (!targetlump) {
if (debugMode) {
renderDebugMessage("Repetitive leaf with full ID " +
child.fullID +
" could not be rendered from parent template branch " +
fluid.debugLump(baselump));
}
continue;
}
var renderend = renderComponentSystem(basecontainer, child, targetlump);
var wasopentag = renderend < t1.lumps.lengtn && t1.lumps[renderend].nestingdepth >= targetlump.nestingdepth;
var newbase = child.children ? child : basecontainer;
if (wasopentag) {
renderRecurse(newbase, targetlump, t1.lumps[renderend]);
renderend = targetlump.close_tag.lumpindex + 1;
}
if (i !== children.length - 1) {
// TODO - fix this bug in RSF Server!
if (renderend < closefinal.lumpindex) {
dumpScan(t1.lumps, renderend, targetlump.nestingdepth - 1, false, false);
}
}
else {
dumpScan(t1.lumps, renderend, targetlump.nestingdepth, true, false);
}
}
} // end for each repetitive child
}
else {
if (debugMode) {
renderDebugMessage("No branch container with prefix " +
prefix + ": found in container " +
reportPath(basecontainer) +
" rendering at template position " +
fluid.debugLump(baselump) +
", skipping");
}
}
renderindex = closefinal.lumpindex + 1;
if (debugMode) {
renderComment("Stack returned from branch for ID " + id + " to " +
fluid.debugLump(baselump) + ": skipping from " + fluid.debugLump(lump) +
" to " + fluid.debugLump(closefinal));
}
}
else {
var component;
if (id) {
component = fetchComponent(basecontainer, id, lump);
if (debugMode && component) {
rendered[component.fullID] = true;
}
}
if (component && component.children !== undefined) {
renderContainer(component);
renderindex = lump.close_tag.lumpindex + 1;
}
else {
renderindex = renderComponentSystem(basecontainer, component, lump);
}
}
if (renderindex === t1.lumps.length) {
break;
}
}
if (debugMode) {
children = basecontainer.children;
for (var key = 0; key < children.length; ++key) {
child = children[key];
if (!rendered[child.fullID]) {
renderDebugMessage("Component " +
child.componentType + " with full ID " +
child.fullID + " could not be found within template " +
fluid.debugLump(baselump));
}
}
}
};
function renderCollect(collump) {
dumpTillLump(collump.parent.lumps, collump.lumpindex, collump.close_tag.lumpindex + 1);
}
// Let us pray
function renderCollects() {
for (var key in collected) {
var collist = collected[key];
for (var i = 0; i < collist.length; ++i) {
renderCollect(collist[i]);
}
}
}
function processDecoratorQueue() {
for (var i = 0; i < decoratorQueue.length; ++i) {
var decorator = decoratorQueue[i];
for (var j = 0; j < decorator.ids.length; ++j) {
var id = decorator.ids[j];
var node = fluid.byId(id, renderOptions.document);
if (!node) {
fluid.fail("Error during rendering - component with id " + id +
" which has a queued decorator was not found in the output markup");
}
if (decorator.type === "jQuery") {
var jnode = renderOptions.jQuery(node);
jnode[decorator.func].apply(jnode, fluid.makeArray(decorator.args));
}
else if (decorator.type === "fluid") {
var args = decorator.args;
if (!args) {
var thisContainer = renderOptions.jQuery(node);
if (!decorator.container) {
decorator.container = thisContainer;
}
else {
decorator.container.push(node);
}
args = [thisContainer, decorator.options];
}
var that = renderer.invokeFluidDecorator(decorator.func, args, id, i, options);
decorator.that = that;
}
else if (decorator.type === "event") {
node[decorator.event] = decorator.handler;
}
}
}
}
that.renderTemplates = function () {
tree = fixupTree(tree, options.model, options.resolverGetConfig);
var template = templates[0];
resolveBranches(templates.globalmap, tree, template.rootlump);
renderedbindings = {};
renderCollects();
renderRecurse(tree, template.rootlump, template.lumps[template.firstdocumentindex]);
return out;
};
that.processDecoratorQueue = function () {
processDecoratorQueue();
};
return that;
};
jQuery.extend(true, fluid.renderer, renderer);
/*
* This function is unsupported: It is not really intended for use by implementors.
*/
fluid.ComponentReference = function (reference) {
this.reference = reference;
};
// Explodes a raw "hash" into a list of UIOutput/UIBound entries
fluid.explode = function (hash, basepath) {
var togo = [];
for (var key in hash) {
var binding = basepath === undefined ? key : basepath + "." + key;
togo[togo.length] = {ID: key, value: hash[key], valuebinding: binding};
}
return togo;
};
/**
* A common utility function to make a simple view of rows, where each row has a selection control and a label
* @param {Object} optionlist - An array of the values of the options in the select
* @param {Object} opts - An object with this structure: {
* selectID: "",
* rowID: "",
* inputID: "",
* labelID: ""
* }
* @return {Object} - The results of transforming optionlist.
*/
fluid.explodeSelectionToInputs = function (optionlist, opts) {
return fluid.transform(optionlist, function (option, index) {
return {
ID: opts.rowID,
children: [
{ID: opts.inputID, parentRelativeID: "..::" + opts.selectID, choiceindex: index},
{ID: opts.labelID, parentRelativeID: "..::" + opts.selectID, choiceindex: index}
]
};
});
};
fluid.renderTemplates = function (templates, tree, options, fossilsIn) {
var renderer = fluid.renderer(templates, tree, options, fossilsIn);
var rendered = renderer.renderTemplates();
return rendered;
};
/** A driver to render and bind an already parsed set of templates onto
* a node. See documentation for fluid.selfRender.
* @param templates A parsed template set, as returned from fluid.selfRender or
* fluid.parseTemplates.
*/
fluid.reRender = function (templates, node, tree, options) {
options = options || {};
var renderer = fluid.renderer(templates, tree, options, options.fossils);
options = renderer.options;
// Empty the node first, to head off any potential id collisions when rendering
node = fluid.unwrap(node);
var lastFocusedElement = fluid.getLastFocusedElement ? fluid.getLastFocusedElement() : null;
var lastId;
if (lastFocusedElement && fluid.dom.isContainer(node, lastFocusedElement)) {
lastId = lastFocusedElement.id;
}
if ($.browser.msie) {
options.jQuery(node).empty(); //- this operation is very slow.
}
else {
node.innerHTML = "";
}
var rendered = renderer.renderTemplates();
if (options.renderRaw) {
rendered = fluid.XMLEncode(rendered);
rendered = rendered.replace(/\n/g, "<br/>");
}
if (options.model) {
fluid.bindFossils(node, options.model, options.fossils);
}
if ($.browser.msie) {
options.jQuery(node).html(rendered);
}
else {
node.innerHTML = rendered;
}
renderer.processDecoratorQueue();
if (lastId) {
var element = fluid.byId(lastId, options.document);
if (element) {
options.jQuery(element).focus();
}
}
return templates;
};
function findNodeValue(rootNode) {
var node = fluid.dom.iterateDom(rootNode, function (node) {
// NB, in Firefox at least, comment and cdata nodes cannot be distinguished!
return node.nodeType === 8 || node.nodeType === 4 ? "stop" : null;
}, true);
var value = node.nodeValue;
if (value.indexOf("[CDATA[") === 0) {
return value.substring(6, value.length - 2);
}
else {
return value;
}
}
fluid.extractTemplate = function (node, armouring) {
if (!armouring) {
return node.innerHTML;
}
else {
return findNodeValue(node);
}
};
/** A slightly generalised version of fluid.selfRender that does not assume that the
* markup used to source the template is within the target node.
* @param {Object | String} source - Either a structure {node: node, armouring: armourstyle} or a string
* holding a literal template
* @param {Object} target - The node to receive the rendered markup
* @param {Object} tree - The component tree to be rendered.
* @param {Object} options - An options structure to configure the rendering and binding process.
* @return {Object} - A templates structure, suitable for a further call to fluid.reRender or fluid.renderTemplates.
*/
fluid.render = function (source, target, tree, options) {
options = options || {};
var template = source;
if (typeof(source) === "object") {
template = fluid.extractTemplate(fluid.unwrap(source.node), source.armouring);
}
target = fluid.unwrap(target);
var resourceSpec = {base: {resourceText: template,
href: ".", resourceKey: ".", cutpoints: options.cutpoints}
};
var templates = fluid.parseTemplates(resourceSpec, ["base"], options);
return fluid.reRender(templates, target, tree, options);
};
/** A simple driver for single node self-templating. Treats the markup for a
* node as a template, parses it into a template structure, renders it using
* the supplied component tree and options, then replaces the markup in the
* node with the rendered markup, and finally performs any required data
* binding. The parsed template is returned for use with a further call to
* reRender.
* @param {Object} node - The node both holding the template, and whose markup is to be
* replaced with the rendered result.
* @param {Object} tree - The component tree to be rendered.
* @param {Object} options - An options structure to configure the rendering and binding process.
* @return {Object} - A templates structure, suitable for a further call to fluid.reRender or fluid.renderTemplates.
*/
fluid.selfRender = function (node, tree, options) {
options = options || {};
return fluid.render({node: node, armouring: options.armouring}, node, tree, options);
};
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
if (!fluid.renderer) {
fluid.fail("fluidRenderer.js is a necessary dependency of RendererUtilities");
}
// TODO: API status of these 3 functions is uncertain. So far, they have never
// appeared in documentation.
fluid.renderer.visitDecorators = function (that, visitor) {
fluid.visitComponentChildren(that, function (component, name) {
if (name.indexOf(fluid.renderer.decoratorComponentPrefix) === 0) {
visitor(component, name);
}
}, {flat: true}, []);
};
fluid.renderer.clearDecorators = function (that) {
var instantiator = fluid.getInstantiator(that);
fluid.renderer.visitDecorators(that, function (component, name) {
instantiator.clearComponent(that, name);
});
};
fluid.renderer.getDecoratorComponents = function (that) {
var togo = {};
fluid.renderer.visitDecorators(that, function (component, name) {
togo[name] = component;
});
return togo;
};
// Utilities for coordinating options in renderer components - this code is all pretty
// dreadful and needs to be organised as a suitable set of defaults and policies
fluid.renderer.modeliseOptions = function (options, defaults, baseOptions) {
return $.extend({}, defaults, fluid.filterKeys(baseOptions, ["model", "applier"]), options);
};
fluid.renderer.reverseMerge = function (target, source, names) {
names = fluid.makeArray(names);
fluid.each(names, function (name) {
if (target[name] === undefined && source[name] !== undefined) {
target[name] = source[name];
}
});
};
/** "Renderer component" infrastructure **/
// TODO: fix this up with IoC and improved handling of templateSource as well as better
// options layout (model appears in both rOpts and eOpts)
// "options" here is the original "rendererFnOptions"
fluid.renderer.createRendererSubcomponent = function (container, selectors, options, parentThat, fossils) {
options = options || {};
var source = options.templateSource ? options.templateSource : {node: $(container)};
var nativeModel = options.rendererOptions.model === undefined;
var rendererOptions = fluid.renderer.modeliseOptions(options.rendererOptions, null, parentThat);
rendererOptions.fossils = fossils || {};
rendererOptions.parentComponent = parentThat;
if (container.jquery) {
var cascadeOptions = {
document: container[0].ownerDocument,
jQuery: container.constructor
};
fluid.renderer.reverseMerge(rendererOptions, cascadeOptions, fluid.keys(cascadeOptions));
}
var that = {};
var templates = null;
that.render = function (tree) {
var cutpointFn = options.cutpointGenerator || "fluid.renderer.selectorsToCutpoints";
rendererOptions.cutpoints = rendererOptions.cutpoints || fluid.invokeGlobalFunction(cutpointFn, [selectors, options]);
if (nativeModel) { // check necessary since the component insanely supports the possibility the model is not the component's model!
// and the pagedTable uses this.
rendererOptions.model = parentThat.model; // fix FLUID-5664
}
var renderTarget = $(options.renderTarget ? options.renderTarget : container);
if (templates) {
fluid.clear(rendererOptions.fossils);
fluid.reRender(templates, renderTarget, tree, rendererOptions);
}
else {
if (typeof(source) === "function") { // TODO: make a better attempt than this at asynchrony
source = source();
}
templates = fluid.render(source, renderTarget, tree, rendererOptions);
}
};
return that;
};
fluid.defaults("fluid.rendererComponent", {
gradeNames: ["fluid.viewComponent"],
initFunction: "fluid.initRendererComponent",
mergePolicy: {
"rendererOptions.idMap": "nomerge",
protoTree: "noexpand, replace",
parentBundle: "nomerge",
"changeApplierOptions.resolverSetConfig": "resolverSetConfig"
},
invokers: {
refreshView: {
funcName: "fluid.rendererComponent.refreshView",
args: "{that}"
},
produceTree: {
funcName: "fluid.rendererComponent.produceTree",
args: "{that}"
}
},
rendererOptions: {
autoBind: true
},
events: {
onResourcesFetched: null,
prepareModelForRender: null,
onRenderTree: null,
afterRender: null
},
listeners: {
onCreate: {
funcName: "fluid.rendererComponent.renderOnInit",
args: ["{that}.options.renderOnInit", "{that}"],
priority: "last"
}
}
});
fluid.rendererComponent.renderOnInit = function (renderOnInit, that) {
if (renderOnInit || that.renderOnInit) {
that.refreshView();
}
};
fluid.protoExpanderForComponent = function (parentThat, options) {
var expanderOptions = fluid.renderer.modeliseOptions(options.expanderOptions, {ELstyle: "${}"}, parentThat);
fluid.renderer.reverseMerge(expanderOptions, options, ["resolverGetConfig", "resolverSetConfig"]);
var expander = fluid.renderer.makeProtoExpander(expanderOptions, parentThat);
return expander;
};
fluid.rendererComponent.refreshView = function (that) {
if (!that.renderer) {
// Terrible stopgap fix for FLUID-5279 - all of this implementation will be swept away
// model relay may cause this to be called during init, and we have no proper definition for "that.renderer" since it is
// constructed in a terrible way
that.renderOnInit = true;
return;
} else {
fluid.renderer.clearDecorators(that);
that.events.prepareModelForRender.fire(that.model, that.applier, that);
var tree = that.produceTree(that);
var rendererFnOptions = that.renderer.rendererFnOptions;
// Terrible stopgap fix for FLUID-5821 - given that model reference may be rebound, generate the expander from scratch on every render
if (!rendererFnOptions.noexpand) {
var expander = fluid.protoExpanderForComponent(that, rendererFnOptions);
tree = expander(tree);
}
that.events.onRenderTree.fire(that, tree);
that.renderer.render(tree);
that.events.afterRender.fire(that);
}
};
fluid.rendererComponent.produceTree = function (that) {
var produceTreeOption = that.options.produceTree;
return produceTreeOption ?
(typeof(produceTreeOption) === "string" ? fluid.getGlobalValue(produceTreeOption) : produceTreeOption) (that) :
that.options.protoTree;
};
fluid.initRendererComponent = function (componentName, container, options) {
var that = fluid.initView(componentName, container, options, {gradeNames: ["fluid.rendererComponent"]});
fluid.getForComponent(that, "model"); // Force resolution of these due to our terrible workflow
fluid.getForComponent(that, "applier");
fluid.diagnoseFailedView(componentName, that, fluid.defaults(componentName), arguments);
fluid.fetchResources(that.options.resources, that.events.onResourcesFetched.fire); // TODO: deal with asynchrony
var rendererOptions = fluid.renderer.modeliseOptions(that.options.rendererOptions, null, that);
var messageResolver;
if (!rendererOptions.messageSource && that.options.strings) {
messageResolver = fluid.messageResolver({
messageBase: that.options.strings,
resolveFunc: that.options.messageResolverFunction,
parents: fluid.makeArray(that.options.parentBundle)
});
rendererOptions.messageSource = {type: "resolver", resolver: messageResolver};
}
fluid.renderer.reverseMerge(rendererOptions, that.options, ["resolverGetConfig", "resolverSetConfig"]);
that.rendererOptions = rendererOptions;
var rendererFnOptions = $.extend({}, that.options.rendererFnOptions, {
rendererOptions: rendererOptions,
repeatingSelectors: that.options.repeatingSelectors,
selectorsToIgnore: that.options.selectorsToIgnore,
expanderOptions: {
envAdd: {styles: that.options.styles}
}
});
if (that.options.resources && that.options.resources.template) {
rendererFnOptions.templateSource = function () { // TODO: don't obliterate, multitemplates, etc.
return that.options.resources.template.resourceText;
};
}
fluid.renderer.reverseMerge(rendererFnOptions, that.options, ["resolverGetConfig", "resolverSetConfig"]);
if (rendererFnOptions.rendererTargetSelector) {
container = function () {return that.dom.locate(rendererFnOptions.rendererTargetSelector); };
}
var renderer = {
fossils: {},
rendererFnOptions: rendererFnOptions,
boundPathForNode: function (node) {
return fluid.boundPathForNode(node, renderer.fossils);
}
};
var rendererSub = fluid.renderer.createRendererSubcomponent(container, that.options.selectors, rendererFnOptions, that, renderer.fossils);
that.renderer = $.extend(renderer, rendererSub);
if (messageResolver) {
that.messageResolver = messageResolver;
}
renderer.refreshView = fluid.getForComponent(that, "refreshView"); // Stopgap implementation for FLUID-4334
return that;
};
var removeSelectors = function (selectors, selectorsToIgnore) {
fluid.each(fluid.makeArray(selectorsToIgnore), function (selectorToIgnore) {
delete selectors[selectorToIgnore];
});
return selectors;
};
var markRepeated = function (selectorKey, repeatingSelectors) {
if (repeatingSelectors) {
fluid.each(repeatingSelectors, function (repeatingSelector) {
if (selectorKey === repeatingSelector) {
selectorKey = selectorKey + ":";
}
});
}
return selectorKey;
};
fluid.renderer.selectorsToCutpoints = function (selectors, options) {
var togo = [];
options = options || {};
selectors = fluid.copy(selectors); // Make a copy before potentially destructively changing someone's selectors.
if (options.selectorsToIgnore) {
selectors = removeSelectors(selectors, options.selectorsToIgnore);
}
for (var selectorKey in selectors) {
togo.push({
id: markRepeated(selectorKey, options.repeatingSelectors),
selector: selectors[selectorKey]
});
}
return togo;
};
/** END of "Renderer Components" infrastructure **/
fluid.renderer.NO_COMPONENT = {};
/* A special "shallow copy" operation suitable for nondestructively
* merging trees of components. jQuery.extend in shallow mode will
* neglect null valued properties.
* This function is unsupported: It is not really intended for use by implementors.
*/
fluid.renderer.mergeComponents = function (target, source) {
for (var key in source) {
target[key] = source[key];
}
return target;
};
fluid.registerNamespace("fluid.renderer.selection");
/** Definition of expanders - firstly, "heavy" expanders **/
fluid.renderer.selection.inputs = function (options, container, key, config) {
fluid.expect("Selection to inputs expander", options, ["selectID", "inputID", "labelID", "rowID"]);
var selection = config.expander(options.tree);
// Remove the tree from option expansion as this is handled above, and
// the tree may have strings with similar syntax to IoC references.
var optsToExpand = fluid.censorKeys(options, ["tree"]);
var expandedOpts = config.expandLight(optsToExpand);
var rows = fluid.transform(selection.optionlist.value, function (option, index) {
var togo = {};
var element = {parentRelativeID: "..::" + expandedOpts.selectID, choiceindex: index};
togo[expandedOpts.inputID] = element;
togo[expandedOpts.labelID] = fluid.copy(element);
return togo;
});
var togo = {}; // TODO: JICO needs to support "quoted literal key initialisers" :P
togo[expandedOpts.selectID] = selection;
togo[expandedOpts.rowID] = {children: rows};
togo = config.expander(togo);
return togo;
};
fluid.renderer.repeat = function (options, container, key, config) {
fluid.expect("Repetition expander", options, ["controlledBy", "tree"]);
var env = config.threadLocal();
var path = fluid.extractContextualPath(options.controlledBy, {ELstyle: "ALL"}, env);
var list = fluid.get(config.model, path, config.resolverGetConfig);
var togo = {};
if (!list || list.length === 0) {
return options.ifEmpty ? config.expander(options.ifEmpty) : togo;
}
var expanded = [];
fluid.each(list, function (element, i) {
var EL = fluid.model.composePath(path, i);
var envAdd = {};
if (options.pathAs) {
envAdd[options.pathAs] = "${" + EL + "}";
}
if (options.valueAs) {
envAdd[options.valueAs] = fluid.get(config.model, EL, config.resolverGetConfig);
}
var expandrow = fluid.withEnvironment(envAdd, function () {
return config.expander(options.tree);
}, env);
if (fluid.isArrayable(expandrow)) {
if (expandrow.length > 0) {
expanded.push({children: expandrow});
}
}
else if (expandrow !== fluid.renderer.NO_COMPONENT) {
expanded.push(expandrow);
}
});
var repeatID = options.repeatID;
if (repeatID.indexOf(":") === -1) {
repeatID = repeatID + ":";
}
fluid.each(expanded, function (entry) {entry.ID = repeatID; });
return expanded;
};
fluid.renderer.condition = function (options, container, key, config) {
fluid.expect("Selection to condition expander", options, ["condition"]);
var condition;
if (options.condition.funcName) {
var args = config.expandLight(options.condition.args);
condition = fluid.invokeGlobalFunction(options.condition.funcName, args);
} else if (options.condition.expander) {
condition = config.expander(options.condition);
} else {
condition = config.expandLight(options.condition);
}
var tree = (condition ? options.trueTree : options.falseTree);
if (!tree) {
tree = fluid.renderer.NO_COMPONENT;
}
return config.expander(tree);
};
/* An EL extraction utility suitable for context expressions which occur in
* expanding component trees. It dispatches context expressions to fluid.transformContextPath
* in order to resolve them against EL references stored in the direct environment, and hence
* to the "true (direct) model" - however, if there is no entry in the direct environment, it will resort to the "externalFetcher".
* It satisfies a similar contract as fluid.extractEL, in that it will either return
* an EL path, or undefined if the string value supplied cannot be interpreted
* as an EL path with respect to the supplied options - it may also return {value: value}
* in the case the context can be resolved by the supplied "externalFetcher" (required for FLUID-4986)
*/
// unsupported, non-API function
fluid.extractContextualPath = function (string, options, env, externalFetcher) {
var parsed = fluid.extractELWithContext(string, options);
if (parsed) {
if (parsed.context) {
return env[parsed.context] ? fluid.transformContextPath(parsed, env).path : {value: externalFetcher(parsed)};
}
else {
return parsed.path;
}
}
};
// unsupported, non-API function
fluid.transformContextPath = function (parsed, env) {
if (parsed.context) {
var fetched = env[parsed.context];
var EL;
if (typeof(fetched) === "string") {
EL = fluid.extractEL(fetched, {ELstyle: "${}"});
}
if (EL) {
return {
noDereference: parsed.path === "",
path: fluid.model.composePath(EL, parsed.path)
};
}
}
return parsed;
};
// A forgiving variation of "makeStackFetcher" that returns nothing on failing to resolve an IoC reference,
// in keeping with current protoComponent semantics. Note to self: abolish protoComponents
fluid.renderer.makeExternalFetcher = function (contextThat) {
return function (parsed) {
var foundComponent = fluid.resolveContext(parsed.context, contextThat);
return foundComponent ? fluid.getForComponent(foundComponent, parsed.path) : undefined;
};
};
/** Create a "protoComponent expander" with the supplied set of options.
* The returned value will be a function which accepts a "protoComponent tree"
* as argument, and returns a "fully expanded" tree suitable for supplying
* directly to the renderer.
* A "protoComponent tree" is similar to the "dehydrated form" accepted by
* the historical renderer - only
* i) The input format is unambiguous - this expander will NOT accept hydrated
* components in the {ID: "myId, myfield: "myvalue"} form - but ONLY in
* the dehydrated {myID: {myfield: myvalue}} form.
* ii) This expander has considerably greater power to expand condensed trees.
* In particular, an "EL style" option can be supplied which will expand bare
* strings found as values in the tree into UIBound components by a configurable
* strategy. Supported values for "ELstyle" are a) "ALL" - every string will be
* interpreted as an EL reference and assigned to the "valuebinding" member of
* the UIBound, or b) any single character, which if it appears as the first
* character of the string, will mark it out as an EL reference - otherwise it
* will be considered a literal value, or c) the value "${}" which will be
* recognised bracketing any other EL expression.
*/
fluid.renderer.makeProtoExpander = function (expandOptions, parentThat) {
// shallow copy of options - cheaply avoid destroying model, and all others are primitive
var options = $.extend({
ELstyle: "${}"
}, expandOptions); // shallow copy of options
if (parentThat) {
options.externalFetcher = fluid.renderer.makeExternalFetcher(parentThat);
}
var threadLocal; // rebound on every expansion at entry point
function fetchEL(string) {
var env = threadLocal();
return fluid.extractContextualPath(string, options, env, options.externalFetcher);
}
var IDescape = options.IDescape || "\\";
var expandLight = function (source) {
return fluid.expand(source, options);
};
var expandBound = function (value, concrete) {
if (value.messagekey !== undefined) {
return {
componentType: "UIMessage",
messagekey: expandBound(value.messagekey),
args: expandLight(value.args)
};
}
var proto;
if (!fluid.isPrimitive(value) && !fluid.isArrayable(value)) {
proto = $.extend({}, value);
if (proto.decorators) {
proto.decorators = expandLight(proto.decorators);
}
value = proto.value;
delete proto.value;
} else {
proto = {};
}
var EL;
if (typeof (value) === "string") {
var fetched = fetchEL(value);
EL = typeof (fetched) === "string" ? fetched : null;
value = fluid.get(fetched, "value") || value;
}
if (EL) {
proto.valuebinding = EL;
} else if (value !== undefined) {
proto.value = value;
}
if (options.model && proto.valuebinding && proto.value === undefined) {
proto.value = fluid.get(options.model, proto.valuebinding, options.resolverGetConfig);
}
if (concrete) {
proto.componentType = "UIBound";
}
return proto;
};
options.filter = fluid.expander.lightFilter;
var expandCond;
var expandLeafOrCond;
var expandEntry = function (entry) {
var comp = [];
expandCond(entry, comp);
return {children: comp};
};
var expandExternal = function (entry) {
if (entry === fluid.renderer.NO_COMPONENT) {
return entry;
}
var singleTarget;
var target = [];
var pusher = function (comp) {
singleTarget = comp;
};
expandLeafOrCond(entry, target, pusher);
return singleTarget || target;
};
var expandConfig = {
model: options.model,
resolverGetConfig: options.resolverGetConfig,
resolverSetConfig: options.resolverSetConfig,
expander: expandExternal,
expandLight: expandLight
//threadLocal: threadLocal
};
var expandLeaf = function (leaf, componentType) {
var togo = {componentType: componentType};
var map = fluid.renderer.boundMap[componentType] || {};
for (var key in leaf) {
if (/decorators|args/.test(key)) {
togo[key] = expandLight(leaf[key]);
continue;
} else if (map[key]) {
togo[key] = expandBound(leaf[key]);
} else {
togo[key] = leaf[key];
}
}
return togo;
};
// A child entry may be a cond, a leaf, or another "thing with children".
// Unlike the case with a cond's contents, these must be homogeneous - at least
// they may either be ALL leaves, or else ALL cond/childed etc.
// In all of these cases, the key will be THE PARENT'S KEY
var expandChildren = function (entry, pusher) {
var children = entry.children;
for (var i = 0; i < children.length; ++i) {
// each child in this list will lead to a WHOLE FORKED set of children.
var target = [];
var comp = { children: target};
var child = children[i];
// This use of function creation within a loop is acceptable since
// the function does not attempt to close directly over the loop counter
var childPusher = function (comp) { // eslint-disable-line no-loop-func
target[target.length] = comp;
};
expandLeafOrCond(child, target, childPusher);
// Rescue the case of an expanded leaf into single component - TODO: check what sense this makes of the grammar
if (comp.children.length === 1 && !comp.children[0].ID) {
comp = comp.children[0];
}
pusher(comp);
}
};
function detectBareBound(entry) {
return fluid.find(entry, function (value, key) {
return key === "decorators";
}) !== false;
}
// We have reached something which is either a leaf or Cond - either inside
// a Cond or as an entry in children.
expandLeafOrCond = function (entry, target, pusher) {
var componentType = fluid.renderer.inferComponentType(entry);
if (!componentType && (fluid.isPrimitive(entry) || detectBareBound(entry))) {
componentType = "UIBound";
}
if (componentType) {
pusher(componentType === "UIBound" ? expandBound(entry, true) : expandLeaf(entry, componentType));
} else {
// we couldn't recognise it as a leaf, so it must be a cond
// this may be illegal if we are already in a cond.
if (!target) {
fluid.fail("Illegal cond->cond transition");
}
expandCond(entry, target);
}
};
// cond entry may be a leaf, "thing with children" or a "direct bound".
// a Cond can ONLY occur as a direct member of "children". Each "cond" entry may
// give rise to one or many elements with the SAME key - if "expandSingle" discovers
// "thing with children" they will all share the same key found in proto.
expandCond = function (proto, target) {
var key;
var expandToTarget = function (expander) {
var expanded = fluid.invokeGlobalFunction(expander.type, [expander, proto, key, expandConfig]);
if (expanded !== fluid.renderer.NO_COMPONENT) {
fluid.each(expanded, function (el) {target[target.length] = el; });
}
};
var condPusher = function (comp) {
comp.ID = key;
target[target.length] = comp;
};
for (key in proto) {
var entry = proto[key];
if (key.charAt(0) === IDescape) {
key = key.substring(1);
}
if (key === "expander") {
var expanders = fluid.makeArray(entry);
fluid.each(expanders, expandToTarget);
} else if (entry) {
if (entry.children) {
if (key.indexOf(":") === -1) {
key = key + ":";
}
expandChildren(entry, condPusher);
} else if (fluid.renderer.isBoundPrimitive(entry)) {
condPusher(expandBound(entry, true));
} else {
expandLeafOrCond(entry, null, condPusher);
}
}
}
};
return function (entry) {
threadLocal = fluid.threadLocal(function () {
return $.extend({}, options.envAdd);
});
options.fetcher = fluid.makeEnvironmentFetcher(options.model, fluid.transformContextPath, threadLocal, options.externalFetcher);
expandConfig.threadLocal = threadLocal;
return expandEntry(entry);
};
};
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
fluid.registerNamespace("fluid.overviewPanel");
fluid.overviewPanel.makeBooleanListener = function (that, selector, method, path, value) {
var elem = that.locate(selector);
elem[method](function (evt) {
that.applier.change(path, value === "toggle" ? !that.model[path] : value);
evt.preventDefault();
});
};
fluid.defaults("fluid.overviewPanel", {
gradeNames: ["fluid.rendererComponent"],
resources: {
template: {
href: "../html/overviewPanelTemplate.html"
}
},
listeners: {
"onCreate.setVisibility": "{that}.setVisibility",
"onCreate.showTemplate": "fluid.overviewPanel.showTemplate",
"afterRender.registerToggleListener": {
"funcName": "fluid.overviewPanel.makeBooleanListener",
"args": ["{that}", "toggleControl", "click", "showPanel", "toggle"]
},
"afterRender.registerCloseListener": {
"funcName": "fluid.overviewPanel.makeBooleanListener",
"args": ["{that}", "closeControl", "click", "showPanel", false]
},
"afterRender.setLinkHrefs": {
"funcName": "fluid.overviewPanel.setLinkHrefs",
"args": ["{that}", "{that}.options.links"]
},
"afterRender.setToggleControlAria": {
"this": "{that}.dom.toggleControl",
"method": "attr",
"args": {
"role": "button",
"aria-controls": "{that}.containerId"
}
},
"afterRender.setCloseControlAria": {
"this": "{that}.dom.closeControl",
"method": "attr",
"args": {
"role": "button",
"aria-label": "{that}.options.strings.closePanelLabel",
"aria-controls": "{that}.containerId"
}
},
"afterRender.setAriaStates": "{that}.setAriaStates"
},
model: {
showPanel: true
},
modelListeners: {
"setVisibility": {
path: "showPanel",
func: "{that}.setVisibility"
},
"setAriaStates": {
path: "showPanel",
func: "{that}.setAriaStates"
}
},
members: {
containerId: {
expander: {
// create an id for that.container, if it does not have one already,
// and set that.containerId to the id value
funcName: "fluid.allocateSimpleId",
args: "{that}.container"
}
}
},
invokers: {
setVisibility: {
funcName: "fluid.overviewPanel.setVisibility",
args: ["{that}", "{that}.model.showPanel"]
},
setAriaStates: {
funcName: "fluid.overviewPanel.setAriaStates",
args: ["{that}", "{that}.model.showPanel"]
}
},
selectors: {
toggleControl: ".flc-overviewPanel-toggleControl",
titleBegin: ".flc-overviewPanel-title-begin",
titleLink: ".flc-overviewPanel-titleLink",
titleLinkText: ".flc-overviewPanel-title-linkText",
titleEnd: ".flc-overviewPanel-title-end",
componentName: ".flc-overviewPanel-componentName",
description: ".flc-overviewPanel-description",
instructionsHeading: ".flc-overviewPanel-instructionsHeading",
instructions: ".flc-overviewPanel-instructions",
demoCodeLink: ".flc-overviewPanel-demoCodeLink",
demoCodeLinkText: ".flc-overviewPanel-demoCodeLinkText",
infusionCodeLink: ".flc-overviewPanel-infusionCodeLink",
infusionCodeLinkText: ".flc-overviewPanel-infusionCodeLinkText",
apiLink: ".flc-overviewPanel-apiLink",
apiLinkText: ".flc-overviewPanel-apiLinkText",
designLink: ".flc-overviewPanel-designLink",
designLinkText: ".flc-overviewPanel-designLinkText",
feedbackText: ".flc-overviewPanel-feedbackText",
feedbackLink: ".flc-overviewPanel-feedbackLink",
feedbackLinkText: ".flc-overviewPanel-feedbackLinkText",
closeControl: ".flc-overviewPanel-closeControl",
closeText: ".flc-overviewPanel-closeText"
},
selectorsToIgnore: ["toggleControl", "titleLink", "demoCodeLink", "infusionCodeLink", "apiLink", "designLink", "feedbackLink", "closeControl"],
protoTree: {
titleBegin: {messagekey: "titleBegin"},
titleLinkText: {messagekey: "titleLinkText"},
titleEnd: {messagekey: "titleEnd"},
componentName: {messagekey: "componentName"},
description: {markup: "${{that}.options.markup.description}"},
instructionsHeading: {messagekey: "instructionsHeading"},
instructions: {markup: "${{that}.options.markup.instructions}"},
demoCodeLinkText: {messagekey: "demoCodeLinkText"},
infusionCodeLinkText: {messagekey: "infusionCodeLinkText"},
apiLinkText: {messagekey: "apiLinkText"},
designLinkText: {messagekey: "designLinkText"},
feedbackText: {messagekey: "feedbackText"},
feedbackLinkText: {messagekey: "feedbackLinkText"},
closeText: {messagekey: "closeText"}
},
styles: {
hidden: "fl-overviewPanel-hidden"
},
strings: {
titleBegin: "An",
titleLinkText: "Infusion",
titleEnd: "component demo",
componentName: "Component Name",
instructionsHeading: "Instructions",
demoCodeLinkText: "demo code",
infusionCodeLinkText: "get Infusion",
apiLinkText: "API",
designLinkText: "design",
feedbackText: "Found a bug? Have a question?",
feedbackLinkText: "Let us know!",
closeText: "close",
openPanelLabel: "Open the overview panel",
closePanelLabel: "Close the overview panel"
},
markup: {
description: "A description of the component should appear here. It should say: <ul><li>What the component does.</li><li>Why it is interesting / useful.</li></ul>",
instructions: "<p>Do this to do this. Do that to do that.</p>"
},
links: {
titleLink: "http://fluidproject.org/infusion.html",
demoCodeLink: "#",
infusionCodeLink: "https://github.com/fluid-project/infusion/",
apiLink: "#",
designLink: "#",
feedbackLink: "#"
}
});
fluid.overviewPanel.setVisibility = function (that, showPanel) {
that.container.toggleClass(that.options.styles.hidden, !showPanel);
};
fluid.overviewPanel.showTemplate = function (that) {
fluid.fetchResources(that.options.resources, function () {
that.refreshView();
});
};
fluid.overviewPanel.setLinkHrefs = function (that, linkMap) {
fluid.each(linkMap, function (linkHref, selector) {
that.locate(selector).attr("href", linkHref);
});
};
fluid.overviewPanel.setAriaStates = function (that, showPanel) {
that.locate("toggleControl").attr("aria-pressed", !showPanel);
that.locate("toggleControl").attr("aria-expanded", showPanel);
that.locate("closeControl").attr("aria-expanded", showPanel);
if (showPanel) {
that.locate("toggleControl").attr("aria-label", that.options.strings.closePanelLabel);
} else {
that.locate("toggleControl").attr("aria-label", that.options.strings.openPanelLabel);
}
};
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
fluid.registerNamespace("fluid.pager");
/******************
* Pager Bar View *
******************/
// TODO: Convert one day to the "visibility model" system (FLUID-4928)
fluid.pager.updateStyles = function (pageListThat, newModel, oldModel) {
if (oldModel && oldModel.pageIndex !== undefined) {
var oldLink = pageListThat.pageLinks.eq(oldModel.pageIndex);
oldLink.removeClass(pageListThat.options.styles.currentPage);
}
var pageLink = pageListThat.pageLinks.eq(newModel.pageIndex);
pageLink.addClass(pageListThat.options.styles.currentPage);
};
fluid.pager.bindLinkClick = function (link, initiatePageChange, eventArg) {
link.off("click.fluid.pager");
link.on("click.fluid.pager", function () {
initiatePageChange.fire(eventArg);
return false;
});
};
// 10 -> 1, 11 -> 2
fluid.pager.computePageCount = function (model) {
return Math.max(1, Math.floor((model.totalRange - 1) / model.pageSize) + 1);
};
fluid.pager.computePageLimit = function (model) {
return Math.min(model.totalRange, (model.pageIndex + 1) * model.pageSize);
};
fluid.pager.bindLinkClicks = function (pageLinks, initiatePageChange) {
fluid.each(pageLinks, function (pageLink, i) {
fluid.pager.bindLinkClick($(pageLink), initiatePageChange, {pageIndex: i});
});
};
// Abstract grade representing all pageLists
fluid.defaults("fluid.pager.pageList", {
gradeNames: ["fluid.viewComponent"]
});
fluid.defaults("fluid.pager.directPageList", {
gradeNames: ["fluid.pager.pageList"],
listeners: {
onCreate: {
funcName: "fluid.pager.bindLinkClicks",
args: ["{that}.pageLinks", "{pager}.events.initiatePageChange"]
}
},
modelListeners: {
"{pager}.model": "fluid.pager.updateStyles({that}, {change}.value, {change}.oldValue)"
},
members: {
pageLinks: "{that}.dom.pageLinks",
defaultModel: {
totalRange: "{that}.pageLinks.length"
}
}
});
fluid.pager.everyPageStrategy = fluid.iota;
fluid.pager.gappedPageStrategy = function (locality, midLocality) {
if (!locality) {
locality = 3;
}
if (!midLocality) {
midLocality = locality;
}
return function (count, first, mid) {
var togo = [];
var j = 0;
var lastSkip = false;
for (var i = 0; i < count; ++i) {
if (i < locality || (count - i - 1) < locality || (i >= mid - midLocality && i <= mid + midLocality)) {
togo[j++] = i;
lastSkip = false;
} else if (!lastSkip) {
togo[j++] = -1;
lastSkip = true;
}
}
return togo;
};
};
/**
* An impl of a page strategy that will always display same number of page links (including skip place holders).
* @param {Number} endLinkCount - The number of elements first and last trunks of elements.
* @param {Number} midLinkCount - The number of elements from beside the selected number.
* @return {Function} - A paging function.
* @author Eric Dalquist
*/
fluid.pager.consistentGappedPageStrategy = function (endLinkCount, midLinkCount) {
if (!endLinkCount) {
endLinkCount = 1;
}
if (!midLinkCount) {
midLinkCount = endLinkCount;
}
var endWidth = endLinkCount + 2 + midLinkCount;
return function (count, first, mid) {
var pages = [];
var anchoredLeft = mid < endWidth;
var anchoredRight = mid >= count - endWidth;
var anchoredEndWidth = endWidth + midLinkCount;
var midStart = mid - midLinkCount;
var midEnd = mid + midLinkCount;
var lastSkip = false;
for (var page = 0; page < count; page++) {
if (page < endLinkCount || // start pages
count - page <= endLinkCount || // end pages
(anchoredLeft && page < anchoredEndWidth) || // pages if no skipped pages between start and mid
(anchoredRight && page >= count - anchoredEndWidth) || // pages if no skipped pages between mid and end
(page >= midStart && page <= midEnd) // pages around the mid
) {
pages.push(page);
lastSkip = false;
} else if (!lastSkip) {
pages.push(-1);
lastSkip = true;
}
}
return pages;
};
};
fluid.registerNamespace("fluid.pager.renderedPageList");
fluid.pager.renderedPageList.assembleComponent = function (page, isCurrent, initiatePageChange, currentPageStyle, currentPageIndexMsg) {
var obj = {
ID: "page-link:link",
localID: page + 1,
value: page + 1,
pageIndex: page,
decorators: [
{
identify: "pageLink:" + page
},
{
type: "jQuery",
func: "click",
args: function (event) {
initiatePageChange.fire({pageIndex: page});
event.preventDefault();
}
}
]
};
if (isCurrent) {
obj.current = true;
obj.decorators = obj.decorators.concat([
{
type: "addClass",
classes: currentPageStyle
},
{
type: "jQuery",
func: "attr",
args: ["aria-label", currentPageIndexMsg]
}
]);
}
return obj;
};
fluid.pager.renderedPageList.onModelChange = function (that, newModel) {
function pageToComponent(current) {
return function (page) {
return page === -1 ? {
ID: "page-link:skip"
} : that.assembleComponent(page, page === current);
};
}
var pages = that.options.pageStrategy(newModel.pageCount, 0, newModel.pageIndex);
var pageTree = fluid.transform(pages, pageToComponent(newModel.pageIndex));
if (pageTree.length > 1) {
pageTree[pageTree.length - 1].value = pageTree[pageTree.length - 1].value + that.options.strings.last;
}
that.events.onRenderPageLinks.fire(pageTree, newModel);
that.pageTree = pageTree;
that.refreshView();
};
fluid.pager.renderedPageList.renderLinkBody = function (linkBody, rendererOptions) {
if (linkBody) {
rendererOptions.cutpoints.push({
id: "payload-component",
selector: linkBody
});
}
};
fluid.defaults("fluid.pager.renderedPageList", {
gradeNames: ["fluid.pager.pageList", "fluid.rendererComponent"],
rendererOptions: {
idMap: {},
cutpoints: [
{
id: "page-link:link",
selector: "{that}.options.selectors.pageLinks"
},
{
id: "page-link:skip",
selector: "{that}.options.selectors.pageLinkSkip"
}
]
},
rendererFnOptions: {
noexpand: true,
templateSource: {node: "{that}.dom.root"},
renderTarget: "{that}.dom.root"
},
events: {
onRenderPageLinks: "{pager}.events.onRenderPageLinks"
},
listeners: {
onCreate: {
funcName: "fluid.pager.renderedPageList.renderLinkBody",
args: ["{that}.options.linkBody", "{that}.options.rendererOptions"]
}
},
modelListeners: {
"{pager}.model": "fluid.pager.renderedPageList.onModelChange({that}, {change}.value)"
},
invokers: {
produceTree: {
funcName: "fluid.identity",
args: "{that}.pageTree"
},
assembleComponent: {
funcName: "fluid.pager.renderedPageList.assembleComponent",
args: ["{arguments}.0", "{arguments}.1",
"{pager}.events.initiatePageChange", "{pagerBar}.options.styles.currentPage", "{pagerBar}.options.strings.currentPageIndexMsg"]
}
},
selectors: {
root: ".flc-pager-links",
pageLinks: "{pagerBar}.options.selectors.pageLinks",
pageLinkSkip: "{pagerBar}.options.selectors.pageLinkSkip"
},
strings: "{pager}.options.strings",
linkBody: "a",
pageStrategy: fluid.pager.everyPageStrategy
});
fluid.defaults("fluid.pager.previousNext", {
gradeNames: ["fluid.viewComponent"],
members: {
previous: "{that}.dom.previous",
next: "{that}.dom.next"
},
selectors: {
previous: ".flc-pager-previous",
next: ".flc-pager-next"
},
listeners: {
onCreate: [{
funcName: "fluid.pager.bindLinkClick",
args: ["{that}.previous", "{pager}.events.initiatePageChange", {relativePage: -1}]
}, {
funcName: "fluid.pager.bindLinkClick",
args: ["{that}.next", "{pager}.events.initiatePageChange", {relativePage: +1}]
}
]
},
modelListeners: {
"{pager}.model": "fluid.pager.previousNext.update({that}, {that}.options.styles.disabled, {change}.value)"
}
});
fluid.pager.previousNext.update = function (that, disabledStyle, newModel) {
that.previous.toggleClass(disabledStyle, newModel.pageIndex === 0);
that.next.toggleClass(disabledStyle, newModel.pageIndex === newModel.pageCount - 1);
};
fluid.defaults("fluid.pager.pagerBar", {
gradeNames: ["fluid.viewComponent"],
components: {
pageList: {
type: "fluid.pager.pageList",
container: "{pagerBar}.container",
options: {
selectors: {
pageLinks: "{pagerBar}.options.selectors.pageLinks"
},
styles: "{pagerBar}.options.styles"
}
},
previousNext: {
type: "fluid.pager.previousNext",
container: "{pagerBar}.container",
options: {
selectors: {
previous: "{pagerBar}.options.selectors.previous",
next: "{pagerBar}.options.selectors.next"
},
styles: "{pagerBar}.options.styles"
}
}
},
events: {
initiatePageChange: null,
onModelChange: null
},
selectors: {
pageLinks: ".flc-pager-pageLink",
pageLinkSkip: ".flc-pager-pageLink-skip",
previous: ".flc-pager-previous",
next: ".flc-pager-next"
},
styles: {
currentPage: "fl-pager-currentPage",
disabled: "fl-pager-disabled"
},
strings: {
currentPageIndexMsg: "Current page"
}
});
fluid.pager.summaryAria = function (element) {
element.attr({
"aria-relevant": "all",
"aria-atomic": "false",
"aria-live": "assertive",
"role": "status"
});
};
fluid.defaults("fluid.pager.summary", {
gradeNames: ["fluid.viewComponent"],
listeners: {
onCreate: {
funcName: "fluid.pager.summaryAria",
args: "{that}.container"
}
},
modelListeners: {
"{pager}.model": {
funcName: "fluid.pager.summary.onModelChange",
args: ["{that}.container", "{that}.options.strings.message", "{change}.value"]
}
}
});
fluid.pager.summary.onModelChange = function (node, message, newModel) {
var text = fluid.stringTemplate(message, {
first: newModel.pageIndex * newModel.pageSize + 1,
last: fluid.pager.computePageLimit(newModel),
total: newModel.totalRange,
currentPage: newModel.pageIndex + 1
});
node.text(text);
};
fluid.defaults("fluid.pager.directPageSize", {
gradeNames: ["fluid.viewComponent"],
listeners: {
onCreate: {
"this": "{that}.container",
method: "change",
args: {
expander: {
funcName: "fluid.pager.directPageSize.onChange",
args: ["{pager}.events.initiatePageSizeChange", "{that}.container"]
}
}
}
},
modelListeners: {
"{pager}.model.pageSize": "fluid.pager.updateNodeValue({that}.container, {change}.value)"
}
});
fluid.pager.directPageSize.onChange = function (initiatePageSizeChange, node) {
// Annoying function-returning function since with current framework this must be an onCreate listener to perform jQuery binding -
// replace with "new renderer decorator system" (FLUID-5047)
return function () {
initiatePageSizeChange.fire(node.val() || 1);
};
};
// Although this is much better with the new ChangeApplier, it still also needs to be replaced with a FLUID-5047 view-binding system
fluid.pager.updateNodeValue = function (node, value) {
node.val(value);
};
fluid.pager.initiatePageChangeListener = function (that, arg) {
var newPageIndex = arg.pageIndex;
if (arg.relativePage !== undefined) {
newPageIndex = that.model.pageIndex + arg.relativePage;
}
that.applier.change("pageIndex", newPageIndex);
};
/*******************
* Pager Component *
*******************/
fluid.defaults("fluid.pager", {
gradeNames: ["fluid.viewComponent"],
events: {
initiatePageChange: null,
initiatePageSizeChange: null,
onModelChange: null,
onRenderPageLinks: null,
afterRender: null
},
model: {
pageIndex: 0,
pageSize: 1,
totalRange: {
expander: {
func: "{that}.acquireDefaultRange"
}
}
},
selectors: {
pagerBar: ".flc-pager-top, .flc-pager-bottom",
summary: ".flc-pager-summary",
pageSize: ".flc-pager-page-size"
},
strings: {
last: " (last)"
},
markup: {
rangeAnnotation: "<b> %first </b><br/>—<br/><b> %last </b>"
},
distributeOptions: {
source: "{that}.options.pageList",
removeSource: true,
target: "{that fluid.pager.pageList}"
},
pageList: {
type: "fluid.pager.renderedPageList",
options: {
pageStrategy: fluid.pager.gappedPageStrategy(3, 1)
}
},
modelRelay: [{
target: "pageCount",
singleTransform: {
type: "fluid.transforms.free",
args: {
"totalRange": "{that}.model.totalRange",
"pageSize": "{that}.model.pageSize"
},
func: "fluid.pager.computePageCount"
}
}, {
target: "pageIndex",
singleTransform: {
type: "fluid.transforms.limitRange",
input: "{that}.model.pageIndex",
min: 0,
max: "{that}.model.pageCount",
excludeMax: 1
}
}],
modelListeners: {
"": "{that}.events.onModelChange.fire({change}.value, {change}.oldValue, {that})"
},
listeners: {
"initiatePageChange.updatePageIndex": {
funcName: "fluid.pager.initiatePageChangeListener",
args: ["{that}", "{arguments}.0"]
},
"initiatePageSizeChange.updateModel": {
changePath: "pageSize",
value: "{arguments}.0"
}
},
invokers: {
acquireDefaultRange: {
// TODO: problem here - pagerBar, etc. are dynamic components and so cannot be constructed gingerly
// This is why current (pre-FLUID-4925) framework must construct components before invokers
funcName: "fluid.identity",
args: "{that}.pagerBar.pageList.defaultModel.totalRange"
}
},
dynamicComponents: {
summary: {
sources: "{that}.dom.summary",
type: "fluid.pager.summary",
container: "{source}",
options: {
strings: {
message: "Viewing page %currentPage. Showing records %first - %last of %total items."
},
events: {
onModelChange: "{pager}.events.onModelChange"
}
}
},
pageSize: {
sources: "{that}.dom.pageSize",
type: "fluid.pager.directPageSize",
container: "{source}"
},
pagerBar: {
sources: "{that}.dom.pagerBar",
type: "fluid.pager.pagerBar",
container: "{source}",
options: {
strings: "{pager}.options.strings",
events: {
initiatePageChange: "{pager}.events.initiatePageChange",
onModelChange: "{pager}.events.onModelChange"
}
}
}
}
});
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
// cf. ancient SVN-era version in bitbucket at https://bitbucket.org/fluid/infusion/src/adf319d9b279/branches/FLUID-2881/src/webapp/components/pager/js/Table.js
fluid.registerNamespace("fluid.table");
fluid.table.findColumnDef = function (columnDefs, key) {
return fluid.find_if(columnDefs, function (def) {
return def.key === key;
});
};
fluid.table.getRoots = function (target, dataOffset, index) {
target.shortRoot = index;
target.longRoot = fluid.pathUtil.composePath(dataOffset, target.shortRoot);
};
// TODO: This crazed variable expansion system was a sketch for what eventually became the "protoComponent expansion system" delivered in 1.x versions of
// Infusion. It in turn should be abolished when FLUID-4260 is implemented, allowing users to code with standard Fluid components and standard IoC references
fluid.table.expandPath = function (EL, shortRoot, longRoot) {
if (EL.charAt(0) === "*") {
return longRoot + EL.substring(1);
} else {
return EL.replace("*", shortRoot);
}
};
fluid.table.fetchValue = function (dataOffset, dataModel, index, valuebinding, roots) {
fluid.table.getRoots(roots, dataOffset, index);
var path = fluid.table.expandPath(valuebinding, roots.shortRoot, roots.longRoot);
return fluid.get(dataModel, path);
};
fluid.table.rowComparator = function (sortDir) {
return function (arec, brec) {
return (arec.value > brec.value ? 1 : (arec.value < brec.value ? -1 : 0)) * sortDir;
};
};
fluid.table.basicSorter = function (columnDefs, dataModel, dataOffset, model) {
var roots = {};
var columnDef = fluid.table.findColumnDef(columnDefs, model.sortKey);
var sortrecs = [];
for (var i = 0; i < model.totalRange; ++i) {
sortrecs[i] = {
index: i,
value: fluid.table.fetchValue(dataOffset, dataModel, i, columnDef.valuebinding, roots)
};
}
sortrecs.sort(fluid.table.rowComparator(model.sortDir));
return fluid.getMembers(sortrecs, "index");
};
fluid.table.IDforColumn = function (columnDef, keyPrefix, roots) {
var EL = columnDef.valuebinding;
var key = columnDef.key;
if (!EL) {
fluid.fail("Error in definition for column with key " + key + ": valuebinding is not set");
}
if (!key) {
var segs = fluid.model.parseEL(EL);
key = segs[segs.length - 1];
}
return {
ID: (keyPrefix || "") + key,
EL: fluid.table.expandPath(EL, roots.shortRoot, roots.longRoot)
};
};
fluid.table.bigHeaderForKey = function (key, options) {
// TODO: ensure this is shared properly
var id = options.rendererOptions.idMap["header:" + key];
var smallHeader = fluid.jById(id);
if (smallHeader.length === 0) {
return null;
}
var headerSortStylisticOffset = options.selectors.headerSortStylisticOffset;
var bigHeader = fluid.findAncestor(smallHeader, function (element) {
return $(element).is(headerSortStylisticOffset);
});
return bigHeader;
};
fluid.table.setSortHeaderClass = function (styles, element, sort) {
element = $(element);
element.removeClass(styles.ascendingHeader);
element.removeClass(styles.descendingHeader);
if (sort !== 0) {
element.addClass(sort === 1 ? styles.ascendingHeader : styles.descendingHeader);
// aria-sort property are specified in the W3C WAI spec, ascending, descending, none, other.
// since pager currently uses ascending and descending, we do not support the others.
// http://www.w3.org/WAI/PF/aria/states_and_properties#aria-sort
element.attr("aria-sort", sort === 1 ? "ascending" : "descending");
}
};
fluid.table.isCurrentColumnSortable = function (columnDefs, model) {
var columnDef = model.sortKey ? fluid.table.findColumnDef(columnDefs, model.sortKey) : null;
return columnDef ? columnDef.sortable : false;
};
fluid.table.setModelSortHeaderClass = function (columnDefs, newModel, options) {
var styles = options.styles;
var sort = fluid.table.isCurrentColumnSortable(columnDefs, newModel) ? newModel.sortDir : 0;
fluid.table.setSortHeaderClass(styles, fluid.table.bigHeaderForKey(newModel.sortKey, options), sort);
};
fluid.table.generateColumnClick = function (tableThat, options, model, columnDef) {
return function () {
if (columnDef.sortable === true) {
var model = tableThat.model;
var newModel = fluid.copy(model);
var styles = tableThat.options.styles;
var oldKey = model.sortKey;
if (columnDef.key !== model.sortKey) {
newModel.sortKey = columnDef.key;
newModel.sortDir = 1;
var oldBig = fluid.table.bigHeaderForKey(oldKey, options);
if (oldBig) {
fluid.table.setSortHeaderClass(styles, oldBig, 0);
}
} else if (newModel.sortKey === columnDef.key) {
newModel.sortDir = -1 * newModel.sortDir;
} else {
return false;
}
newModel.pageIndex = 0;
tableThat.applier.change("", newModel);
// fluid.table.setModelSortHeaderClass(newModel, options); - done during rerender, surely
}
return false;
};
};
fluid.table.fetchHeaderDecorators = function (decorators, columnDef) {
return decorators[columnDef.sortable ? "sortableHeader" : "unsortableHeader"];
};
fluid.table.generateHeader = function (tableThat, options, newModel) { // arg 2 is renderThat.options
var sortableColumnTxt = options.strings.sortableColumnText;
if (newModel.sortDir === 1) {
sortableColumnTxt = options.strings.sortableColumnTextAsc;
} else if (newModel.sortDir === -1) {
sortableColumnTxt = options.strings.sortableColumnTextDesc;
}
var columnDefs = tableThat.options.columnDefs;
return {
children:
fluid.transform(columnDefs, function (columnDef) {
return {
ID: fluid.table.IDforColumn(columnDef, options.keyPrefix, {}).ID,
value: columnDef.label,
decorators: [
{"jQuery": ["click", fluid.table.generateColumnClick(tableThat, options, newModel, columnDef)]},
{identify: "header:" + columnDef.key},
{type: "attrs", attributes: { title: (columnDef.key === newModel.sortKey) ? sortableColumnTxt : options.strings.sortableColumnText}}
].concat(fluid.table.fetchHeaderDecorators(options.decorators, columnDef))
};
})
};
};
fluid.table.expandVariables = function (value, opts) {
var togo = "";
var index = 0;
while (true) {
var nextindex = value.indexOf("${", index);
if (nextindex === -1) {
togo += value.substring(index);
break;
} else {
togo += value.substring(index, nextindex);
var endi = value.indexOf("}", nextindex + 2);
var EL = value.substring(nextindex + 2, endi);
if (EL === "VALUE") {
EL = opts.EL;
} else {
EL = fluid.table.expandPath(EL, opts.shortRoot, opts.longRoot);
}
var val = fluid.get(opts.dataModel, EL);
togo += val;
index = endi + 1;
}
}
return togo;
};
fluid.table.expandPaths = function (target, tree, opts) {
for (var i in tree) {
var val = tree[i];
if (fluid.isMarker(val, fluid.VALUE)) { // TODO, in theory, we could prevent copying of columnDefs
if (i === "valuebinding") {
target[i] = opts.EL;
} else {
target[i] = {"valuebinding" : opts.EL};
}
} else if (i === "valuebinding") {
target[i] = fluid.table.expandPath(tree[i], opts);
} else if (typeof (val) === "object") {
target[i] = val.length !== undefined ? [] : {};
fluid.table.expandPaths(target[i], val, opts);
} else if (typeof (val) === "string") {
target[i] = fluid.table.expandVariables(val, opts);
} else {
target[i] = tree[i];
}
}
return target;
};
fluid.table.expandColumnDefs = function (columnDefs, keyPrefix, dataModel, filteredRow, roots) {
var tree = fluid.transform(columnDefs, function (columnDef) {
var record = fluid.table.IDforColumn(columnDef, keyPrefix, roots);
var opts = $.extend({
dataModel: dataModel
}, roots, record);
var togo;
if (!columnDef.components) {
return {
ID: record.ID,
valuebinding: record.EL
};
} else if (typeof columnDef.components === "function") {
togo = columnDef.components(filteredRow.row, filteredRow.index);
} else {
togo = columnDef.components;
}
togo = fluid.table.expandPaths({}, togo, opts);
togo.ID = record.ID;
return togo;
});
return tree;
};
fluid.table.fetchDataModel = function (dataModel, dataOffset) {
return fluid.get(dataModel, dataOffset);
};
fluid.table.produceTree = function (tableThat, renderThat) {
var options = renderThat.options;
var columnDefs = tableThat.options.columnDefs;
var roots = {};
var tree = fluid.transform(tableThat.filtered,
function (filteredRow) {
fluid.table.getRoots(roots, tableThat.options.dataOffset, filteredRow.index);
if (columnDefs === "explode") {
return fluid.explode(filteredRow.row, roots.longRoot);
} else if (columnDefs.length) {
return fluid.table.expandColumnDefs(columnDefs, renderThat.options.keyPrefix, tableThat.dataModel, filteredRow, roots);
}
});
var fullTree = {};
fullTree[options.row] = tree;
if (typeof (columnDefs) === "object") {
fullTree[options.header] = fluid.table.generateHeader(tableThat, renderThat.options, tableThat.model);
}
return fullTree;
};
fluid.table.sortInvoker = function (tableThat, newModel) {
var columnDefs = tableThat.options.columnDefs;
var sorted = fluid.table.isCurrentColumnSortable(columnDefs, newModel) ?
tableThat.options.sorter(columnDefs, tableThat.options.dataModel, tableThat.options.dataOffset, newModel) : null;
tableThat.permutation = sorted;
};
fluid.table.onModelChange = function (tableThat, renderThat, newModel) {
renderThat.sortInvoker(newModel);
tableThat.dataModel = tableThat.fetchDataModel();
tableThat.filtered = tableThat.options.modelFilter(tableThat.dataModel, newModel, tableThat.permutation);
};
/** A body renderer implementation which uses the Fluid renderer to render a table section **/
fluid.defaults("fluid.table.selfRender", {
gradeNames: ["fluid.rendererComponent"],
listeners: {
onCreate: [{
"this": "{that}.root",
method: "addClass",
args: "{that}.options.styles.root"
}],
onIndexModelChange: [{
funcName: "fluid.table.onModelChange",
namespace: "onModelChange",
args: ["{fluid.table}", "{fluid.table.selfRender}", "{arguments}.0", "{arguments}.1"] // newModel, oldModel
}, {
func: "{that}.sortInvoker",
namespace: "sortInvoker",
args: "{arguments}.0"
}, {
priority: "last",
namespace: "refreshView",
func: "{that}.refreshView"
}],
afterRender: { // TODO, should this not be actually renderable?
funcName: "fluid.table.setModelSortHeaderClass",
args: ["{that}.options.columnDefs", "{fluid.table}.model", "{that}.options"]
}
},
modelListeners: {
"{fluid.table}.model": "{that}.events.onIndexModelChange.fire({change}.value, {change}.oldValue)"
},
events: {
onIndexModelChange: null
},
invokers: {
sortInvoker: {
funcName: "fluid.table.sortInvoker",
args: ["{fluid.table}", "{arguments}.0"] // newModel
},
produceTree: {
funcName: "fluid.table.produceTree",
args: ["{fluid.table}", "{fluid.table.selfRender}"]
}
},
selectors: {
root: ".flc-pager-body-template",
headerSortStylisticOffset: "{table}.options.selectors.headerSortStylisticOffset",
header: ".flc-table-header",
row: ".flc-table-row"
},
repeatingSelectors: ["header", "row"],
selectorsToIgnore: ["root", "headerSortStylisticOffset"],
styles: {
root: "fl-pager",
ascendingHeader: "{table}.options.styles.ascendingHeader",
descendingHeader: "{table}.options.styles.descendingHeader"
},
members: {
root: "{that}.dom.root"
},
decorators: {
sortableHeader: [],
unsortableHeader: []
},
keyStrategy: "id",
keyPrefix: "",
row: "row:", // should match selector name, deprecated after v1.5
header: "header:", // should match selector name, deprecated after v1.5
strings: "{table}.options.strings",
columnDefs: "{table}.options.columnDefs",
// Options passed upstream to the renderer
rendererFnOptions: {
templateSource: {node: "{that}.dom.root"},
renderTarget: "{that}.dom.root",
noexpand: true
},
rendererOptions: {
model: "{table}.options.dataModel",
idMap: {}
}
});
fluid.table.checkTotalRange = function (totalRange, pagerBar) {
if (totalRange === undefined && !pagerBar) {
fluid.fail("Error in Pager configuration - cannot determine total range, " +
" since not configured in model.totalRange and no PagerBar is configured");
}
};
fluid.defaults("fluid.table", {
gradeNames: ["fluid.viewComponent"],
mergePolicy: {
dataModel: "preserve",
columnDefs: "noexpand"
},
components: {
bodyRenderer: {
type: "fluid.table.selfRender",
container: "{table}.container"
}
},
listeners: {
onCreate: {
funcName: "fluid.table.checkTotalRange",
namespace: "checkTotalRange",
args: ["{that}.model.totalRange", "{that}.pagerBar"]
}
},
modelFilter: fluid.table.directModelFilter, // TODO: no implementation for this yet
sorter: fluid.table.basicSorter,
members: {
dataModel: {
expander: {
func: "{that}.fetchDataModel"
}
}
},
invokers: {
fetchDataModel: {
funcName: "fluid.table.fetchDataModel",
args: ["{that}.options.dataModel", "{that}.options.dataOffset"]
}
},
styles: {
ascendingHeader: "fl-pager-asc",
descendingHeader: "fl-pager-desc"
},
selectors: {
headerSortStylisticOffset: ".flc-pager-sort-header"
},
strings: {
sortableColumnText: "Select to sort",
sortableColumnTextDesc: "Select to sort in ascending, currently in descending order.",
sortableColumnTextAsc: "Select to sort in descending, currently in ascending order."
},
// Offset of the tree's "main" data from the overall dataModel root
dataOffset: "",
// strategy for generating a tree row, either "explode" or an array of columnDef objects
columnDefs: [] // [{key: "columnName", valuebinding: "*.valuePath", sortable: true/false}]
});
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
fluid.registerNamespace("fluid.pagedTable");
// cf. ancient SVN-era version in bitbucket at https://bitbucket.org/fluid/infusion/src/adf319d9b279/branches/FLUID-2881/src/webapp/components/pager/js/PagedTable.js
fluid.defaults("fluid.pagedTable.rangeAnnotator", {
gradeNames: ["fluid.component"]
});
// TODO: Get rid of this old-style kind of architecture - we should just react to model changes directly and not inject this
// peculiar event up and down the place. Probably best to have new renderer first.
fluid.pagedTable.rangeAnnotator.onRenderPageLinks = function (that, tree, newModel, pagerBar) {
pagerBar.tooltip.close(); // Close any existing tooltips otherwise they will linger after their parent is destroyed
var roots = {};
var column = that.options.annotateColumnRange || (that.options.annotateSortedColumn ? newModel.sortKey : null);
if (!column) {
return;
}
var dataModel = that.options.dataModel;
var columnDefs = that.options.columnDefs;
var columnDef = fluid.table.findColumnDef(columnDefs, column);
function fetchValue(index) {
index = that.permutation ? that.permutation[index] : index;
return fluid.table.fetchValue(that.options.dataOffset, dataModel, index, columnDef.valuebinding, roots);
}
var tModel = {};
fluid.model.copyModel(tModel, newModel);
var tooltipInfo = {};
fluid.each(tree, function (cell) {
if (cell.ID === "page-link:link") {
var page = cell.pageIndex;
var start = page * tModel.pageSize;
tModel.pageIndex = page;
var limit = fluid.pager.computePageLimit(tModel);
var iValue = fetchValue(start);
var lValue = fetchValue(limit - 1);
tooltipInfo[page] = {
first: iValue,
last: lValue
};
}
});
pagerBar.tooltipInfo = tooltipInfo;
};
fluid.pagedTable.directModelFilter = function (model, pagerModel, perm) {
var togo = [];
var limit = fluid.pager.computePageLimit(pagerModel);
for (var i = pagerModel.pageIndex * pagerModel.pageSize; i < limit; ++i) {
var index = perm ? perm[i] : i;
togo[togo.length] = {index: index, row: model[index]};
}
return togo;
};
fluid.pagedTable.configureTooltip = function (pagedTable, pagerBar, renderedPageList) {
var idMap = renderedPageList.rendererOptions.idMap;
var idToContent = {};
fluid.each(pagerBar.tooltipInfo, function (value, index) {
idToContent[idMap["pageLink:" + index]] = fluid.stringTemplate(pagedTable.options.markup.rangeAnnotation, value);
});
pagerBar.tooltip.applier.change("idToContent", idToContent);
};
fluid.defaults("fluid.pagedTable", {
gradeNames: ["fluid.pager", "fluid.table"],
distributeOptions: [{
target: "{that renderedPageList}.options.listeners.afterRender",
record: {
funcName: "fluid.pagedTable.configureTooltip",
args: ["{pagedTable}", "{pagerBar}", "{arguments}.0"]
// NB! Use of "pagerBar" depends on FLUID-5258 - we will need a new annotation when this is fixed
}
}, {
target: "{that renderedPageList}.options.listeners.onRenderPageLinks",
record: {
funcName: "fluid.pagedTable.rangeAnnotator.onRenderPageLinks",
args: ["{pagedTable}", "{arguments}.0", "{arguments}.1", "{pagerBar}"] // FLUID-5258 as above
}
}, {
target: "{that pagerBar}.options.components.tooltip",
source: "{that}.options.tooltip"
}],
annotateSortedColumn: false,
annotateColumnRange: undefined, // specify a "key" from the columnDefs
markup: {
rangeAnnotation: "<b> %first </b><br/>—<br/><b> %last </b>"
},
tooltip: {
type: "fluid.tooltip",
container: "{that}.container",
options: {
}
},
invokers: {
acquireDefaultRange: {
funcName: "fluid.identity",
args: "{that}.dataModel.length"
}
},
modelFilter: fluid.pagedTable.directModelFilter,
model: {
pageSize: 10
}
});
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
fluid.registerNamespace("fluid.progress");
fluid.progress.animateDisplay = function (elm, animation, defaultAnimation, callback) {
animation = (animation) ? animation : defaultAnimation;
elm.animate(animation.params, animation.duration, callback);
};
fluid.progress.animateProgress = function (elm, width, speed) {
// de-queue any left over animations
elm.queue("fx", []);
elm.animate({
width: width,
queue: false
}, speed);
};
fluid.progress.showProgress = function (that, animation) {
var firer = that.events.onProgressBegin.fire;
if (animation === false) {
that.displayElement.show();
firer();
} else {
fluid.progress.animateDisplay(that.displayElement, animation, that.options.showAnimation, firer);
}
};
fluid.progress.hideProgress = function (that, delay, animation) {
if (delay) {
// use a setTimeout to delay the hide for n millis, note use of recursion
setTimeout(function () {
fluid.progress.hideProgress(that, 0, animation);
}, delay);
} else {
var firer = that.events.afterProgressHidden.fire;
if (animation === false) {
that.displayElement.hide();
firer();
} else {
fluid.progress.animateDisplay(that.displayElement, animation, that.options.hideAnimation, firer);
}
}
};
fluid.progress.updateWidth = function (that, newWidth, dontAnimate) {
var currWidth = that.indicator.width();
var direction = that.options.animate;
if ((newWidth > currWidth) && (direction === "both" || direction === "forward") && !dontAnimate) {
fluid.progress.animateProgress(that.indicator, newWidth, that.options.speed);
} else if ((newWidth < currWidth) && (direction === "both" || direction === "backward") && !dontAnimate) {
fluid.progress.animateProgress(that.indicator, newWidth, that.options.speed);
} else {
that.indicator.width(newWidth);
}
};
fluid.progress.percentToPixels = function (that, percent) {
// progress does not support percents over 100, also all numbers are rounded to integers
return Math.round((Math.min(percent, 100) * that.progressBar.innerWidth()) / 100);
};
fluid.progress.refreshRelativeWidth = function (that) {
var pixels = Math.max(fluid.progress.percentToPixels(that, parseFloat(that.storedPercent)), that.options.minWidth);
fluid.progress.updateWidth(that, pixels, true);
};
fluid.progress.initARIA = function (ariaElement, ariaBusyText) {
ariaElement.attr("role", "progressbar");
ariaElement.attr("aria-valuemin", "0");
ariaElement.attr("aria-valuemax", "100");
ariaElement.attr("aria-valuenow", "0");
// Empty value for ariaBusyText will default to aria-valuenow.
if (ariaBusyText) {
ariaElement.attr("aria-valuetext", "");
}
ariaElement.attr("aria-busy", "false");
};
fluid.progress.updateARIA = function (that, percent) {
var str = that.options.strings;
var busy = percent < 100 && percent > 0;
that.ariaElement.attr("aria-busy", busy);
that.ariaElement.attr("aria-valuenow", percent);
// Empty value for ariaBusyText will default to aria-valuenow.
if (str.ariaBusyText) {
if (busy) {
var busyString = fluid.stringTemplate(str.ariaBusyText, {percentComplete : percent});
that.ariaElement.attr("aria-valuetext", busyString);
} else if (percent === 100) {
// FLUID-2936: JAWS doesn't currently read the "Progress is complete" message to the user, even though we set it here.
that.ariaElement.attr("aria-valuetext", str.ariaDoneText);
}
}
};
fluid.progress.updateText = function (label, value) {
label.html(value);
};
fluid.progress.repositionIndicator = function (that) {
that.indicator.css("top", that.progressBar.position().top)
.css("left", 0)
.height(that.progressBar.height());
fluid.progress.refreshRelativeWidth(that);
};
fluid.progress.updateProgress = function (that, percent, labelText, animationForShow) {
// show progress before updating, jQuery will handle the case if the object is already displayed
fluid.progress.showProgress(that, animationForShow);
if (percent !== null) {
that.storedPercent = percent;
var pixels = Math.max(fluid.progress.percentToPixels(that, parseFloat(percent)), that.options.minWidth);
fluid.progress.updateWidth(that, pixels);
}
if (fluid.isValue(labelText)) {
var text = fluid.stringTemplate(labelText, {percentComplete: percent});
fluid.progress.updateText(that.label, text);
}
// update ARIA
if (that.ariaElement) {
fluid.progress.updateARIA(that, percent);
}
};
fluid.progress.hideElement = function (element, shouldHide) {
element.toggle(!shouldHide);
};
/**
* Instantiates a new Progress component.
*
* @param container {jQuery|Selector|Element} the DOM element in which the Uploader lives
* @param options {Object} configuration options for the component.
*/
fluid.defaults("fluid.progress", {
gradeNames: ["fluid.viewComponent"],
members: {
displayElement: "{that}.dom.displayElement",
progressBar: "{that}.dom.progressBar",
label: "{that}.dom.label",
indicator: "{that}.dom.indicator",
ariaElement: "{that}.dom.ariaElement",
storedPercent: 0
},
events: {
onProgressBegin: null,
afterProgressHidden: null
},
listeners: {
onCreate: [ {
"this": "{that}.dom.indicator",
method: "width",
args: "{that}.options.minWidth"
}, {
funcName: "fluid.progress.hideElement",
args: ["{that}.dom.displayElement", "{that}.options.initiallyHidden"]
}, {
funcName: "fluid.progress.initARIA",
args: ["{that}.ariaElement", "{that}.options.strings.ariaBusyText"]
}],
onProgressBegin: {
func: "{that}.options.showAnimation.onProgressBegin"
},
afterProgressHidden: {
func: "{that}.options.hideAnimation.afterProgressHidden"
}
},
invokers: {
/**
* Shows the progress bar if is currently hidden.
* @param animation {Object} a custom animation used when showing the progress bar
*/
show: {
funcName: "fluid.progress.showProgress",
args: ["{that}", "{arguments}.0"]
},
/**
* Hides the progress bar if it is visible.
* @param delay {Number} the amount of time to wait before hiding
* @param animation {Object} a custom animation used when hiding the progress bar
*/
hide: {
funcName: "fluid.progress.hideProgress",
args: ["{that}", "{arguments}.0", "{arguments}.1"]
},
/**
* Updates the state of the progress bar.
* This will automatically show the progress bar if it is currently hidden.
* Percentage is specified as a decimal value, but will be automatically converted if needed.
* @param percentage {Number|String} the current percentage, specified as a "float-ish" value
* @param labelValue {String} the value to set for the label; this can be an HTML string
* @param animationForShow {Object} the animation to use when showing the progress bar if it is hidden
*/
update: {
funcName: "fluid.progress.updateProgress",
args: ["{that}", "{arguments}.0", "{arguments}.1", "{arguments}.2"]
},
refreshView: {
funcName: "fluid.progress.repositionIndicator",
args: "{that}"
}
},
selectors: {
displayElement: ".flc-progress", // required, the element that gets displayed when progress is displayed, could be the indicator or bar or some larger outer wrapper as in an overlay effect
progressBar: ".flc-progress-bar", //required
indicator: ".flc-progress-indicator", //required
label: ".flc-progress-label", //optional
ariaElement: ".flc-progress-bar" // usually required, except in cases where there are more than one progressor for the same data such as a total and a sub-total
},
strings: {
//Empty value for ariaBusyText will default to aria-valuenow.
ariaBusyText: "Progress is %percentComplete percent complete",
ariaDoneText: "Progress is complete."
},
// progress display and hide animations, use the jQuery animation primatives, set to false to use no animation
// animations must be symetrical (if you hide with width, you'd better show with width) or you get odd effects
// see jQuery docs about animations to customize
showAnimation: {
params: {
opacity: "show"
},
duration: "slow",
onProgressBegin: fluid.identity
}, // equivalent of $().fadeIn("slow")
hideAnimation: {
params: {
opacity: "hide"
},
duration: "slow",
afterProgressHidden: fluid.identity
}, // equivalent of $().fadeOut("slow")
minWidth: 5, // 0 length indicators can look broken if there is a long pause between updates
delay: 0, // the amount to delay the fade out of the progress
speed: 200, // default speed for animations, pretty fast
animate: "forward", // suppport "forward", "backward", and "both", any other value is no animation either way
initiallyHidden: true, // supports progress indicators which may always be present
updatePosition: false
});
})(jQuery, fluid_3_0_0);
;
/*!
* jQuery UI Touch Punch 0.2.3
*
* Copyright 2011–2014, Dave Furfero
* Dual licensed under the MIT or GPL Version 2 licenses.
*
* Depends:
* jquery.ui.widget.js
* jquery.ui.mouse.js
*/
(function ($) {
// Detect touch support
$.support.touch = 'ontouchend' in document;
// Ignore browsers without touch support
if (!$.support.touch) {
return;
}
var mouseProto = $.ui.mouse.prototype,
_mouseInit = mouseProto._mouseInit,
_mouseDestroy = mouseProto._mouseDestroy,
touchHandled;
/**
* Simulate a mouse event based on a corresponding touch event
* @param {Object} event A touch event
* @param {String} simulatedType The corresponding mouse event
*/
function simulateMouseEvent (event, simulatedType) {
// Ignore multi-touch events
if (event.originalEvent.touches.length > 1) {
return;
}
event.preventDefault();
var touch = event.originalEvent.changedTouches[0],
simulatedEvent = document.createEvent('MouseEvents');
// Initialize the simulated mouse event using the touch event's coordinates
simulatedEvent.initMouseEvent(
simulatedType, // type
true, // bubbles
true, // cancelable
window, // view
1, // detail
touch.screenX, // screenX
touch.screenY, // screenY
touch.clientX, // clientX
touch.clientY, // clientY
false, // ctrlKey
false, // altKey
false, // shiftKey
false, // metaKey
0, // button
null // relatedTarget
);
// Dispatch the simulated event to the target element
event.target.dispatchEvent(simulatedEvent);
}
/**
* Handle the jQuery UI widget's touchstart events
* @param {Object} event The widget element's touchstart event
*/
mouseProto._touchStart = function (event) {
var self = this;
// Ignore the event if another widget is already being handled
if (touchHandled || !self._mouseCapture(event.originalEvent.changedTouches[0])) {
return;
}
// Set the flag to prevent other widgets from inheriting the touch event
touchHandled = true;
// Track movement to determine if interaction was a click
self._touchMoved = false;
// Simulate the mouseover event
simulateMouseEvent(event, 'mouseover');
// Simulate the mousemove event
simulateMouseEvent(event, 'mousemove');
// Simulate the mousedown event
simulateMouseEvent(event, 'mousedown');
};
/**
* Handle the jQuery UI widget's touchmove events
* @param {Object} event The document's touchmove event
*/
mouseProto._touchMove = function (event) {
// Ignore event if not handled
if (!touchHandled) {
return;
}
// Interaction was not a click
this._touchMoved = true;
// Simulate the mousemove event
simulateMouseEvent(event, 'mousemove');
};
/**
* Handle the jQuery UI widget's touchend events
* @param {Object} event The document's touchend event
*/
mouseProto._touchEnd = function (event) {
// Ignore event if not handled
if (!touchHandled) {
return;
}
// Simulate the mouseup event
simulateMouseEvent(event, 'mouseup');
// Simulate the mouseout event
simulateMouseEvent(event, 'mouseout');
// If the touch interaction did not move, it should trigger a click
if (!this._touchMoved) {
// Simulate the click event
simulateMouseEvent(event, 'click');
}
// Unset the flag to allow other widgets to inherit the touch event
touchHandled = false;
};
/**
* A duck punch of the $.ui.mouse _mouseInit method to support touch events.
* This method extends the widget with bound touch event handlers that
* translate touch events to mouse events and pass them to the widget's
* original mouse event handling methods.
*/
mouseProto._mouseInit = function () {
var self = this;
// Delegate the touch handlers to the widget's element
self.element.bind({
touchstart: $.proxy(self, '_touchStart'),
touchmove: $.proxy(self, '_touchMove'),
touchend: $.proxy(self, '_touchEnd')
});
// Call the original $.ui.mouse init method
_mouseInit.call(self);
};
/**
* Remove the touch event handlers
*/
mouseProto._mouseDestroy = function () {
var self = this;
// Delegate the touch handlers to the widget's element
self.element.unbind({
touchstart: $.proxy(self, '_touchStart'),
touchmove: $.proxy(self, '_touchMove'),
touchend: $.proxy(self, '_touchEnd')
});
// Call the original $.ui.mouse destroy method
_mouseDestroy.call(self);
};
})(jQuery);;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
/*
* Returns the absolute position of a supplied DOM node in pixels.
* Implementation taken from quirksmode http://www.quirksmode.org/js/findpos.html
* At the original time of writing considerably quicker and more reliable than jQuery.offset()
* - this should be reevaluated in time.
*/
fluid.dom.computeAbsolutePosition = function (element) {
var curleft = 0, curtop = 0;
if (element.offsetParent) {
do {
curleft += element.offsetLeft;
curtop += element.offsetTop;
element = element.offsetParent;
} while (element);
return [curleft, curtop];
}
};
/*
* Cleanse the children of a DOM node by removing all <script> tags.
* This is necessary to prevent the possibility that these blocks are
* reevaluated if the node were reattached to the document.
*/
fluid.dom.cleanseScripts = function (element) {
var cleansed = $.data(element, fluid.dom.cleanseScripts.MARKER);
if (!cleansed) {
fluid.dom.iterateDom(element, function (node) {
return node.tagName.toLowerCase() === "script" ? "delete" : null;
});
$.data(element, fluid.dom.cleanseScripts.MARKER, true);
}
};
fluid.dom.cleanseScripts.MARKER = "fluid-scripts-cleansed";
/**
* Inserts newChild as the next sibling of refChild.
* @param {Object} newChild - The new child element to insert.
* @param {Object} refChild - The existing child element.
*/
fluid.dom.insertAfter = function (newChild, refChild) {
var nextSib = refChild.nextSibling;
if (!nextSib) {
refChild.parentNode.appendChild(newChild);
} else {
refChild.parentNode.insertBefore(newChild, nextSib);
}
};
// The following two functions taken from http://developer.mozilla.org/En/Whitespace_in_the_DOM
/**
* Determine whether a node's text content is entirely whitespace.
*
* @param {Object} node - A node implementing the |CharacterData| interface (i.e., a |Text|, |Comment|, or |CDATASection| node).
* @return {Boolean} - True if all of the text content of `node` is whitespace, otherwise false.
*/
fluid.dom.isWhitespaceNode = function (node) {
// Use ECMA-262 Edition 3 String and RegExp features
return !(/[^\t\n\r ]/.test(node.data));
};
/**
* Determine if a node should be ignored by the iterator functions.
*
* @param {Object} node - An object implementing the DOM1 |Node| interface.
* @return {Boolean} - Returns `true` if the node is:
* 1) A |Text| node that is all whitespace
* 2) A |Comment| node
* and otherwise `false`.
*/
fluid.dom.isIgnorableNode = function (node) {
return (node.nodeType === 8) || // A comment node
((node.nodeType === 3) && fluid.dom.isWhitespaceNode(node)); // a text node, all ws
};
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
fluid.orientation = {
HORIZONTAL: 4,
VERTICAL: 1
};
fluid.rectSides = {
// agree with fluid.orientation
4: ["left", "right"],
1: ["top", "bottom"],
// agree with fluid.direction
8: "top",
12: "bottom",
2: "left",
3: "right"
};
/**
* This is the position, relative to a given drop target, that a dragged item should be dropped.
*/
fluid.position = {
BEFORE: -1,
AFTER: 1,
INSIDE: 2,
REPLACE: 3
};
/**
* For incrementing/decrementing a count or index, or moving in a rectilinear direction.
*/
fluid.direction = {
NEXT: 1,
PREVIOUS: -1,
UP: 8,
DOWN: 12,
LEFT: 2,
RIGHT: 3
};
fluid.directionSign = function (direction) {
return direction === fluid.direction.UP || direction === fluid.direction.LEFT ?
fluid.direction.PREVIOUS : fluid.direction.NEXT;
};
fluid.directionAxis = function (direction) {
return direction === fluid.direction.LEFT || direction === fluid.direction.RIGHT ?
0 : 1;
};
fluid.directionOrientation = function (direction) {
return fluid.directionAxis(direction) ? fluid.orientation.VERTICAL : fluid.orientation.HORIZONTAL;
};
fluid.keycodeDirection = {
up: fluid.direction.UP,
down: fluid.direction.DOWN,
left: fluid.direction.LEFT,
right: fluid.direction.RIGHT
};
fluid.registerNamespace("fluid.dom");
// moves a single node in the DOM to a new position relative to another
// unsupported, NON-API function
fluid.dom.moveDom = function (source, target, position) {
source = fluid.unwrap(source);
target = fluid.unwrap(target);
var scan;
// fluid.log("moveDom source " + fluid.dumpEl(source) + " target " + fluid.dumpEl(target) + " position " + position);
if (position === fluid.position.INSIDE) {
target.appendChild(source);
} else if (position === fluid.position.BEFORE) {
for (scan = target.previousSibling;; scan = scan.previousSibling) {
if (!scan || !fluid.dom.isIgnorableNode(scan)) {
if (scan !== source) {
fluid.dom.cleanseScripts(source);
target.parentNode.insertBefore(source, target);
}
break;
}
}
} else if (position === fluid.position.AFTER) {
for (scan = target.nextSibling;; scan = scan.nextSibling) {
if (!scan || !fluid.dom.isIgnorableNode(scan)) {
if (scan !== source) {
fluid.dom.cleanseScripts(source);
fluid.dom.insertAfter(source, target);
}
break;
}
}
} else {
fluid.fail("Unrecognised position supplied to fluid.moveDom: " + position);
}
};
// unsupported, NON-API function
fluid.dom.normalisePosition = function (position, samespan, targeti, sourcei) {
// convert a REPLACE into a primitive BEFORE/AFTER
if (position === fluid.position.REPLACE) {
position = samespan && targeti >= sourcei ? fluid.position.AFTER : fluid.position.BEFORE;
}
return position;
};
fluid.dom.permuteDom = function (element, target, position, sourceelements, targetelements) {
element = fluid.unwrap(element);
target = fluid.unwrap(target);
var sourcei = $.inArray(element, sourceelements);
if (sourcei === -1) {
fluid.fail("Error in permuteDom: source element " + fluid.dumpEl(element) +
" not found in source list " + fluid.dumpEl(sourceelements));
}
var targeti = $.inArray(target, targetelements);
if (targeti === -1) {
fluid.fail("Error in permuteDom: target element " + fluid.dumpEl(target) +
" not found in source list " + fluid.dumpEl(targetelements));
}
var samespan = sourceelements === targetelements;
position = fluid.dom.normalisePosition(position, samespan, targeti, sourcei);
//fluid.log("permuteDom sourcei " + sourcei + " targeti " + targeti);
// cache the old neighbourhood of the element for the final move
var oldn = {};
oldn[fluid.position.AFTER] = element.nextSibling;
oldn[fluid.position.BEFORE] = element.previousSibling;
fluid.dom.moveDom(sourceelements[sourcei], targetelements[targeti], position);
// perform the leftward-moving, AFTER shift
var frontlimit = samespan ? targeti - 1 : sourceelements.length - 2;
var i;
if (position === fluid.position.BEFORE && samespan) {
// we cannot do skip processing if the element was "fused against the grain"
frontlimit--;
}
if (!samespan || targeti > sourcei) {
for (i = frontlimit; i > sourcei; --i) {
fluid.dom.moveDom(sourceelements[i + 1], sourceelements[i], fluid.position.AFTER);
}
if (sourcei + 1 < sourceelements.length) {
fluid.dom.moveDom(sourceelements[sourcei + 1], oldn[fluid.position.AFTER], fluid.position.BEFORE);
}
}
// perform the rightward-moving, BEFORE shift
var backlimit = samespan ? sourcei - 1 : targetelements.length - 1;
if (position === fluid.position.AFTER) {
// we cannot do skip processing if the element was "fused against the grain"
targeti++;
}
if (!samespan || targeti < sourcei) {
for (i = targeti; i < backlimit; ++i) {
fluid.dom.moveDom(targetelements[i], targetelements[i + 1], fluid.position.BEFORE);
}
if (backlimit >= 0 && backlimit < targetelements.length - 1) {
fluid.dom.moveDom(targetelements[backlimit], oldn[fluid.position.BEFORE], fluid.position.AFTER);
}
}
};
var curCss = function (a, name) {
return window.getComputedStyle ? window.getComputedStyle(a, null).getPropertyValue(name) :
a.currentStyle[name];
};
fluid.dom.isAttached = function (node) {
while (node && node.nodeName) {
if (node.nodeName === "BODY") {
return true;
}
node = node.parentNode;
}
return false;
};
fluid.dom.generalHidden = function (a) {
return "hidden" === a.type || curCss(a, "display") === "none" || curCss(a, "visibility") === "hidden" || !fluid.dom.isAttached(a);
};
fluid.registerNamespace("fluid.geometricManager");
fluid.geometricManager.computeGeometry = function (element, orientation, disposition) {
var elem = {};
elem.element = element;
elem.orientation = orientation;
if (disposition === fluid.position.INSIDE) {
elem.position = disposition;
}
if (fluid.dom.generalHidden(element)) {
elem.clazz = "hidden";
}
var pos = fluid.dom.computeAbsolutePosition(element) || [0, 0];
var width = element.offsetWidth;
var height = element.offsetHeight;
elem.rect = {left: pos[0], top: pos[1]};
elem.rect.right = pos[0] + width;
elem.rect.bottom = pos[1] + height;
return elem;
};
// A "suitable large" value for the sentinel blocks at the ends of spans
var SENTINEL_DIMENSION = 10000;
fluid.geometricManager.dumprect = function (rect) {
return "Rect top: " + rect.top +
" left: " + rect.left +
" bottom: " + rect.bottom +
" right: " + rect.right;
};
fluid.geometricManager.dumpelem = function (cacheelem) {
if (!cacheelem || !cacheelem.rect) {
return "null";
} else {
return fluid.geometricManager.dumprect(cacheelem.rect) + " position: " +
cacheelem.position +
" for " +
fluid.dumpEl(cacheelem.element);
}
};
// unsupported, NON-API function
fluid.dropManager = function () {
var targets = [];
var cache = {};
var that = {};
var lastClosest;
var lastGeometry;
var displacementX, displacementY;
that.updateGeometry = function (geometricInfo) {
lastGeometry = geometricInfo;
targets = [];
cache = {};
var mapper = geometricInfo.elementMapper;
var geometryComputor = geometricInfo.geometryComputor || fluid.geometricManager.computeGeometry;
var processElement = function (element, extent, sentB, sentF, disposition, index) {
var orientation = extent.orientation;
var sides = fluid.rectSides[orientation];
var cacheelem = geometryComputor(element, orientation, disposition);
cacheelem.owner = extent;
if (cacheelem.clazz !== "hidden" && mapper) {
cacheelem.clazz = mapper(element);
}
cache[fluid.dropManager.cacheKey(element)] = cacheelem;
var backClass = fluid.dropManager.getRelativeClass(extent.elements, index, fluid.position.BEFORE, cacheelem.clazz, mapper);
var frontClass = fluid.dropManager.getRelativeClass(extent.elements, index, fluid.position.AFTER, cacheelem.clazz, mapper);
if (disposition === fluid.position.INSIDE) {
targets[targets.length] = cacheelem;
} else {
fluid.dropManager.splitElement(targets, sides, cacheelem, disposition, backClass, frontClass);
}
// deal with sentinel blocks by creating near-copies of the end elements
if (sentB && geometricInfo.sentinelize) {
fluid.dropManager.sentinelizeElement(targets, sides, cacheelem, 1, disposition, backClass);
}
if (sentF && geometricInfo.sentinelize) {
fluid.dropManager.sentinelizeElement(targets, sides, cacheelem, 0, disposition, frontClass);
}
//fluid.log(dumpelem(cacheelem));
return cacheelem;
};
for (var i = 0; i < geometricInfo.extents.length; ++i) {
var thisInfo = geometricInfo.extents[i];
var allHidden = true;
for (var j = 0; j < thisInfo.elements.length; ++j) {
var element = thisInfo.elements[j];
var cacheelem = processElement(element, thisInfo, j === 0, j === thisInfo.elements.length - 1,
fluid.position.INTERLEAVED, j);
if (cacheelem.clazz !== "hidden") {
allHidden = false;
}
}
if (allHidden && thisInfo.parentElement) {
processElement(thisInfo.parentElement, thisInfo, true, true, fluid.position.INSIDE);
}
}
fluid.dropManager.normalizeSentinels(targets);
};
that.startDrag = function (event, handlePos, handleWidth, handleHeight) {
var handleMidX = handlePos[0] + handleWidth / 2;
var handleMidY = handlePos[1] + handleHeight / 2;
var dX = handleMidX - event.pageX;
var dY = handleMidY - event.pageY;
that.updateGeometry(lastGeometry);
lastClosest = null;
displacementX = dX;
displacementY = dY;
$("body").on("mousemove.fluid-dropManager", that.mouseMove);
};
that.lastPosition = function () {
return lastClosest;
};
that.endDrag = function () {
$("body").off("mousemove.fluid-dropManager");
};
that.mouseMove = function (evt) {
var x = evt.pageX + displacementX;
var y = evt.pageY + displacementY;
//fluid.log("Mouse x " + x + " y " + y );
var closestTarget = that.closestTarget(x, y, lastClosest);
if (closestTarget && closestTarget !== fluid.dropManager.NO_CHANGE) {
lastClosest = closestTarget;
that.dropChangeFirer.fire(closestTarget);
}
};
that.dropChangeFirer = fluid.makeEventFirer();
var blankHolder = {
element: null
};
that.closestTarget = function (x, y, lastClosest) {
var mindistance = Number.MAX_VALUE;
var minelem = blankHolder;
var minlockeddistance = Number.MAX_VALUE;
var minlockedelem = blankHolder;
for (var i = 0; i < targets.length; ++i) {
var cacheelem = targets[i];
if (cacheelem.clazz === "hidden") {
continue;
}
var distance = fluid.geom.minPointRectangle(x, y, cacheelem.rect);
if (cacheelem.clazz === "locked") {
if (distance < minlockeddistance) {
minlockeddistance = distance;
minlockedelem = cacheelem;
}
} else {
if (distance < mindistance) {
mindistance = distance;
minelem = cacheelem;
}
if (distance === 0) {
break;
}
}
}
if (!minelem) {
return minelem;
}
if (minlockeddistance >= mindistance) {
minlockedelem = blankHolder;
}
//fluid.log("PRE: mindistance " + mindistance + " element " +
// fluid.dumpEl(minelem.element) + " minlockeddistance " + minlockeddistance
// + " locked elem " + dumpelem(minlockedelem));
if (lastClosest && lastClosest.position === minelem.position &&
fluid.unwrap(lastClosest.element) === fluid.unwrap(minelem.element) &&
fluid.unwrap(lastClosest.lockedelem) === fluid.unwrap(minlockedelem.element)
) {
return fluid.dropManager.NO_CHANGE;
}
//fluid.log("mindistance " + mindistance + " minlockeddistance " + minlockeddistance);
return {
position: minelem.position,
element: minelem.element,
lockedelem: minlockedelem.element
};
};
that.shuffleProjectFrom = function (element, direction, includeLocked, disableWrap) {
var togo = that.projectFrom(element, direction, includeLocked, disableWrap);
if (togo) {
togo.position = fluid.position.REPLACE;
}
return togo;
};
that.projectFrom = function (element, direction, includeLocked, disableWrap) {
that.updateGeometry(lastGeometry);
var cacheelem = cache[fluid.dropManager.cacheKey(element)];
var projected = fluid.geom.projectFrom(cacheelem.rect, direction, targets, includeLocked, disableWrap);
if (!projected.cacheelem) {
return null;
}
var retpos = projected.cacheelem.position;
return {element: projected.cacheelem.element,
position: retpos ? retpos : fluid.position.BEFORE
};
};
that.logicalFrom = function (element, direction, includeLocked, disableWrap) {
var orderables = that.getOwningSpan(element, fluid.position.INTERLEAVED, includeLocked);
return {element: fluid.dropManager.getRelativeElement(element, direction, orderables, disableWrap),
position: fluid.position.REPLACE};
};
that.lockedWrapFrom = function (element, direction, includeLocked, disableWrap) {
var base = that.logicalFrom(element, direction, includeLocked, disableWrap);
var selectables = that.getOwningSpan(element, fluid.position.INTERLEAVED, includeLocked);
var allElements = cache[fluid.dropManager.cacheKey(element)].owner.elements;
if (includeLocked || selectables[0] === allElements[0]) {
return base;
}
var directElement = fluid.dropManager.getRelativeElement(element, direction, allElements, disableWrap);
if (lastGeometry.elementMapper(directElement) === "locked") {
base.element = null;
base.clazz = "locked";
}
return base;
};
that.getOwningSpan = function (element, position, includeLocked) {
var owner = cache[fluid.dropManager.cacheKey(element)].owner;
var elements = position === fluid.position.INSIDE ? [owner.parentElement] : owner.elements;
if (!includeLocked && lastGeometry.elementMapper) {
elements = fluid.makeArray(elements);
fluid.remove_if(elements, function (element) {
return lastGeometry.elementMapper(element) === "locked";
});
}
return elements;
};
that.geometricMove = function (element, target, position) {
var sourceElements = that.getOwningSpan(element, null, true);
var targetElements = that.getOwningSpan(target, position, true);
fluid.dom.permuteDom(element, target, position, sourceElements, targetElements);
};
return that;
};
fluid.dropManager.NO_CHANGE = "no change";
fluid.dropManager.cacheKey = function (element) {
return fluid.allocateSimpleId(element);
};
fluid.dropManager.sentinelizeElement = function (targets, sides, cacheelem, fc, disposition, clazz) {
var elemCopy = $.extend(true, {}, cacheelem);
elemCopy.origRect = fluid.copy(elemCopy.rect);
elemCopy.rect[sides[fc]] = elemCopy.rect[sides[1 - fc]] + (fc ? 1 : -1);
elemCopy.rect[sides[1 - fc]] = (fc ? -1 : 1) * SENTINEL_DIMENSION;
elemCopy.position = disposition === fluid.position.INSIDE ?
disposition : (fc ? fluid.position.BEFORE : fluid.position.AFTER);
elemCopy.clazz = clazz;
targets[targets.length] = elemCopy;
};
// This function is necessary to prevent overlapping sentinels for FLUID-4692
// Very sadly this simple implementation now makes the setup O(n^2) in the number of elements
fluid.dropManager.normalizeSentinels = function (targets) {
for (var i = 0; i < targets.length; ++i) {
for (var j = 0; j < targets.length; ++j) {
var ti = targets[i], tj = targets[j];
var jrect = tj.origRect || tj.rect;
if (ti.element !== tj.element && ti.origRect && fluid.geom.minRectRect(ti.rect, jrect) === 0) {
ti.rect = ti.origRect;
delete ti.origRect;
}
}
}
};
fluid.dropManager.splitElement = function (targets, sides, cacheelem, disposition, clazz1, clazz2) {
var elem1 = $.extend(true, {}, cacheelem);
var elem2 = $.extend(true, {}, cacheelem);
var midpoint = (elem1.rect[sides[0]] + elem1.rect[sides[1]]) / 2;
elem1.rect[sides[1]] = midpoint;
elem1.position = fluid.position.BEFORE;
elem2.rect[sides[0]] = midpoint;
elem2.position = fluid.position.AFTER;
elem1.clazz = clazz1;
elem2.clazz = clazz2;
targets[targets.length] = elem1;
targets[targets.length] = elem2;
};
// Expand this configuration point if we ever go back to a full "permissions" model
fluid.dropManager.getRelativeClass = function (thisElements, index, relative, thisclazz, mapper) {
index += relative;
if (index < 0 && thisclazz === "locked") {
return "locked";
}
if (index >= thisElements.length || mapper === null) {
return null;
} else {
relative = thisElements[index];
return mapper(relative) === "locked" && thisclazz === "locked" ? "locked" : null;
}
};
fluid.dropManager.getRelativeElement = function (element, direction, elements, disableWrap) {
var folded = fluid.directionSign(direction);
var index = $(elements).index(element) + folded;
if (index < 0) {
index += elements.length;
}
// disable wrap
if (disableWrap) {
if (index === elements.length || index === (elements.length + folded)) {
return element;
}
}
index %= elements.length;
return elements[index];
};
fluid.geom = fluid.geom || {};
// These distance algorithms have been taken from
// http://www.cs.mcgill.ca/~cs644/Godfried/2005/Fall/fzamal/concepts.htm
/* Returns the minimum squared distance between a point and a rectangle */
fluid.geom.minPointRectangle = function (x, y, rectangle) {
var dx = x < rectangle.left ? (rectangle.left - x) :
(x > rectangle.right ? (x - rectangle.right) : 0);
var dy = y < rectangle.top ? (rectangle.top - y) :
(y > rectangle.bottom ? (y - rectangle.bottom) : 0);
return dx * dx + dy * dy;
};
/* Returns the minimum squared distance between two rectangles */
fluid.geom.minRectRect = function (rect1, rect2) {
var dx = rect1.right < rect2.left ? rect2.left - rect1.right :
rect2.right < rect1.left ? rect1.left - rect2.right : 0;
var dy = rect1.bottom < rect2.top ? rect2.top - rect1.bottom :
rect2.bottom < rect1.top ? rect1.top - rect2.bottom : 0;
return dx * dx + dy * dy;
};
var makePenCollect = function () {
return {
mindist: Number.MAX_VALUE,
minrdist: Number.MAX_VALUE
};
};
/** Determine the one amongst a set of rectangle targets which is the "best fit"
* for an axial motion from a "base rectangle" (commonly arising from the case
* of cursor key navigation).
* @param {Rectangle} baserect - The base rectangle from which the motion is to be referred.
* @param {Object} direction - The direction of motion, which should be an instance of fluid.direction.
* @param {Array} targets - An array of objects "cache elements" for which the member <code>rect</code> is the
* holder of the rectangle to be tested.
* @param {Boolean} forSelection - Set to `true` to indicate that we are dealing with a selection.
* @param {Boolean} disableWrap - Set to `true` to disable wrapping of elements.
* @return {Object} - The cache element which is the most appropriate for the requested motion.
*/
fluid.geom.projectFrom = function (baserect, direction, targets, forSelection, disableWrap) {
var axis = fluid.directionAxis(direction);
var frontSide = fluid.rectSides[direction];
var backSide = fluid.rectSides[axis * 15 + 5 - direction];
var dirSign = fluid.directionSign(direction);
var penrect = {left: (7 * baserect.left + 1 * baserect.right) / 8,
right: (5 * baserect.left + 3 * baserect.right) / 8,
top: (7 * baserect.top + 1 * baserect.bottom) / 8,
bottom: (5 * baserect.top + 3 * baserect.bottom) / 8};
penrect[frontSide] = dirSign * SENTINEL_DIMENSION;
penrect[backSide] = -penrect[frontSide];
function accPen(collect, cacheelem, backSign) {
var thisrect = cacheelem.rect;
var pdist = fluid.geom.minRectRect(penrect, thisrect);
var rdist = -dirSign * backSign * (baserect[backSign === 1 ? frontSide : backSide] -
thisrect[backSign === 1 ? backSide : frontSide]);
// fluid.log("pdist: " + pdist + " rdist: " + rdist);
// the oddity in the rdist comparison is intended to express "half-open"-ness of rectangles
// (backSign === 1 ? 0 : 1) - this is now gone - must be possible to move to perpendicularly abutting regions
if (pdist <= collect.mindist && rdist >= 0) {
if (pdist === collect.mindist && rdist * backSign > collect.minrdist) {
return;
}
collect.minrdist = rdist * backSign;
collect.mindist = pdist;
collect.minelem = cacheelem;
}
}
var collect = makePenCollect();
var backcollect = makePenCollect();
var lockedcollect = makePenCollect();
for (var i = 0; i < targets.length; ++i) {
var elem = targets[i];
var isPure = elem.owner && elem.element === elem.owner.parentElement;
if (elem.clazz === "hidden" || (forSelection && isPure)) {
continue;
} else if (!forSelection && elem.clazz === "locked") {
accPen(lockedcollect, elem, 1);
} else {
accPen(collect, elem, 1);
accPen(backcollect, elem, -1);
}
//fluid.log("Element " + i + " " + dumpelem(elem) + " mindist " + collect.mindist);
}
var wrap = !collect.minelem || backcollect.mindist < collect.mindist;
// disable wrap
wrap = wrap && !disableWrap;
var mincollect = wrap ? backcollect : collect;
var togo = {
wrapped: wrap,
cacheelem: mincollect.minelem
};
if (lockedcollect.mindist < mincollect.mindist) {
togo.lockedelem = lockedcollect.minelem;
}
return togo;
};
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
fluid.registerNamespace("fluid.reorderer");
fluid.reorderer.defaultAvatarCreator = function (item, cssClass, dropWarning) {
fluid.dom.cleanseScripts(fluid.unwrap(item));
var avatar = $(item).clone();
fluid.dom.iterateDom(avatar.get(0), function (node) {
node.removeAttribute("id");
if (node.tagName.toLowerCase() === "input") {
node.setAttribute("disabled", "disabled");
}
});
avatar.removeProp("id");
avatar.removeClass("ui-droppable");
avatar.addClass(cssClass);
if (dropWarning) {
// Will a 'div' always be valid in this position?
var avatarContainer = $(document.createElement("div"));
avatarContainer.append(avatar);
avatarContainer.append(dropWarning);
avatar = avatarContainer;
}
$("body").append(avatar);
if (!$.browser.safari) {
// FLUID-1597: Safari appears incapable of correctly determining the dimensions of elements
avatar.css("display", "block").width(item.offsetWidth).height(item.offsetHeight);
}
if ($.browser.opera) { // FLUID-1490. Without this detect, curCSS explodes on the avatar on Firefox.
avatar.hide();
}
return avatar;
};
// unsupported, NON-API function
fluid.reorderer.bindHandlersToContainer = function (container, keyDownHandler, keyUpHandler) {
var actualKeyDown = keyDownHandler;
var advancedPrevention = false;
// FLUID-1598 and others: Opera will refuse to honour a "preventDefault" on a keydown.
// http://forums.devshed.com/javascript-development-115/onkeydown-preventdefault-opera-485371.html
if ($.browser.opera) {
container.keypress(function (evt) {
if (advancedPrevention) {
advancedPrevention = false;
evt.preventDefault();
return false;
}
});
actualKeyDown = function (evt) {
var oldret = keyDownHandler(evt);
if (oldret === false) {
advancedPrevention = true;
}
};
}
container.keydown(actualKeyDown);
container.keyup(keyUpHandler);
};
// unsupported, NON-API function
fluid.reorderer.addRolesToContainer = function (that) {
that.container.attr("role", that.options.containerRole.container);
that.container.attr("aria-multiselectable", "false");
that.container.attr("aria-readonly", "false");
that.container.attr("aria-disabled", "false");
// FLUID-3707: We require to have BOTH application role as well as our named role
// This however breaks the component completely under NVDA and causes it to perpetually drop back into "browse mode"
//that.container.wrap("<div role=\"application\"></div>");
};
// unsupported, NON-API function
fluid.reorderer.createAvatarId = function (parentId) {
// Generating the avatar's id to be containerId_avatar
// This is safe since there is only a single avatar at a time
return parentId + "_avatar";
};
/**
* Constants for key codes in events.
*/
fluid.reorderer.keys = {
TAB: 9,
ENTER: 13,
SHIFT: 16,
CTRL: 17,
ALT: 18,
META: 19,
SPACE: 32,
LEFT: 37,
UP: 38,
RIGHT: 39,
DOWN: 40,
i: 73,
j: 74,
k: 75,
m: 77
};
/**
* The default key sets for the Reorderer. Should be moved into the proper component defaults.
*/
fluid.reorderer.defaultKeysets = [
{
modifier : function (evt) {
return evt.ctrlKey;
},
up : fluid.reorderer.keys.UP,
down : fluid.reorderer.keys.DOWN,
right : fluid.reorderer.keys.RIGHT,
left : fluid.reorderer.keys.LEFT
},
{
modifier : function (evt) {
return evt.ctrlKey;
},
up : fluid.reorderer.keys.i,
down : fluid.reorderer.keys.m,
right : fluid.reorderer.keys.k,
left : fluid.reorderer.keys.j
}
];
fluid.reorderer.keysetsPolicy = function (target, source) {
var value = source ? source : target;
return fluid.makeArray(value);
};
fluid.reorderer.copyDropWarning = function (dropWarning) {
return dropWarning ? dropWarning.clone() : dropWarning;
};
/**
* @param container - A jQueryable designator for the root node of the reorderer (a selector, a DOM node, or a jQuery instance)
* @param options - an object containing any of the available options:
* containerRole - indicates the role, or general use, for this instance of the Reorderer
* keysets - an object containing sets of keycodes to use for directional navigation. Must contain:
* modifier - a function that returns a boolean, indicating whether or not the required modifier(s) are activated
* up
* down
* right
* left
* styles - an object containing class names for styling the Reorderer
* defaultStyle
* selected
* dragging
* hover
* dropMarker
* mouseDrag
* avatar
* avatarCreator - a function that returns a valid DOM node to be used as the dragging avatar
*/
fluid.defaults("fluid.reorderer", {
gradeNames: ["fluid.viewComponent"],
styles: {
defaultStyle: "fl-reorderer-movable-default",
selected: "fl-reorderer-movable-selected",
dragging: "fl-reorderer-movable-dragging",
mouseDrag: "fl-reorderer-movable-dragging",
hover: "fl-reorderer-movable-hover",
dropMarker: "fl-reorderer-dropMarker",
avatar: "fl-reorderer-avatar"
},
selectors: {
dropWarning: ".flc-reorderer-dropWarning",
movables: ".flc-reorderer-movable",
selectables: ".flc-reorderer-movable",
dropTargets: ".flc-reorderer-movable",
grabHandle: ""
},
avatarCreator: fluid.reorderer.defaultAvatarCreator,
keysets: fluid.reorderer.defaultKeysets,
// These two ginger options injected "upwards" from layoutHandler and actually time its construction (before FLUID-4925)
containerRole: "{that}.layoutHandler.options.containerRole",
selectablesTabindex: "{that}.layoutHandler.options.selectablesTabindex",
layoutHandler: "fluid.listLayoutHandler",
members: {
dropManager: "@expand:fluid.dropManager()", // TODO: this is an old-style "that" which can no longer be supported as a component
activeItem: null,
kbDropWarning: "{that}.dom.dropWarning",
mouseDropWarning: "@expand:fluid.reorderer.copyDropWarning({that}.kbDropWarning)"
},
events: {
onShowKeyboardDropWarning: null,
onSelect: null,
onBeginMove: "preventable",
onMove: null,
afterMove: null,
onHover: null, // item, state
onRefresh: null
},
listeners: {
onCreate: [ {
namespace: "bindKeyHandlers",
funcName: "fluid.reorderer.bindHandlersToContainer",
args: ["{that}.container", "{that}.handleKeyDown", "{that}.handleKeyUp"]
}, {
namespace: "addContainerRoles",
funcName: "fluid.reorderer.addRolesToContainer",
args: "{that}"
}, {
namespace: "makeTabbable",
funcName: "fluid.tabbable",
args: "{that}.container"
}, {
namespace: "processAfterMoveCallback",
funcName: "fluid.reorderer.processAfterMoveCallbackUrl",
args: "{that}"
},
"{that}.refresh"],
onRefresh: {
listener: "fluid.reorderer.initItems",
args: "{that}",
priority: -1000 // TODO: Can't be "first" since moduleLayout needs to respond first
},
onHover: {
funcName: "fluid.reorderer.hoverStyleHandler",
args: ["{that}.dom", "{that}.options.styles", "{arguments}.0", "{arguments}.1"] // item, state
}
},
invokers: {
changeSelectedToDefault: {
funcName: "fluid.reorderer.changeSelectedToDefault",
args: ["{arguments}.0", "{that}.options.styles"]
},
setDropEffects: {
funcName: "fluid.reorderer.setDropEffects",
args: ["{that}.dom", "{arguments}.0"]
},
createDropMarker: {
funcName: "fluid.reorderer.createDropMarker",
args: ["{arguments}.0", "{that}.options.styles.dropMarker"]
},
refresh: {
funcName: "fluid.reorderer.refresh",
args: ["{that}.dom", "{that}.events", "{that}.selectableContext", "{that}.activeItem"]
},
selectItem: {
funcName: "fluid.reorderer.selectItem",
args: ["{that}", "{arguments}.0"]
},
initSelectables: { // unsupported, NON-API function
funcName: "fluid.reorderer.initSelectables",
args: ["{that}"]
},
initMovable: { // unsupported, NON-API function
funcName: "fluid.reorderer.initMovable",
args: ["{that}", "{that}.dropManager", "{arguments}.0"]
},
isMove: { // unsupported, NON-API function
funcName: "fluid.reorderer.isMove",
args: ["{that}.options.keysets", "{arguments}.0"] // evt
},
isActiveItemMovable: { // unsupported, NON-API function
funcName: "fluid.reorderer.isActiveItemMovable",
args: ["{that}.activeItem", "{that}.dom"]
},
handleKeyDown: { // unsupported, NON-API function
funcName: "fluid.reorderer.handleKeyDown",
args: ["{that}", "{that}.options.styles", "{arguments}.0"] // evt
},
handleDirectionKeyDown: { // unsupported, NON-API function
funcName: "fluid.reorderer.handleDirectionKeyDown",
args: ["{that}", "{arguments}.0"] // evt
},
handleKeyUp: { // unsupported, NON-API function
funcName: "fluid.reorderer.handleKeyUp",
args: ["{that}", "{that}.options.styles", "{arguments}.0"] // evt
},
requestMovement: { // unsupported, NON-API function
funcName: "fluid.reorderer.requestMovement",
args: ["{that}", "{arguments}.0", "{arguments}.1"] // requestedPosition, item
}
},
mergePolicy: {
keysets: fluid.reorderer.keysetsPolicy,
"selectors.labelSource": "selectors.grabHandle",
"selectors.selectables": "selectors.movables",
"selectors.dropTargets": "selectors.movables"
},
components: {
layoutHandler: {
type: "{that}.options.layoutHandler",
container: "{reorderer}.container"
},
labeller: {
type: "fluid.reorderer.labeller",
options: {
members: {
dom: "{reorderer}.dom"
},
getGeometricInfo: "{reorderer}.layoutHandler.getGeometricInfo",
orientation: "{reorderer}.layoutHandler.options.orientation",
layoutType: "{reorderer}.options.layoutHandler"
}
}
},
// The user option to enable or disable wrapping of elements within the container
disableWrap: false
});
fluid.reorderer.noModifier = function (evt) {
return (!evt.ctrlKey && !evt.altKey && !evt.shiftKey && !evt.metaKey);
};
// unsupported, NON-API function
fluid.reorderer.isMove = function (keysets, evt) { // NB, needs dynamic binding
for (var i = 0; i < keysets.length; i++) {
if (keysets[i].modifier(evt)) {
return true;
}
}
return false;
};
// unsupported, NON-API function
fluid.reorderer.isActiveItemMovable = function (activeItem, dom) {
return $.inArray(activeItem, dom.fastLocate("movables")) >= 0;
};
// unsupported, NON-API function
fluid.reorderer.handleKeyDown = function (thatReorderer, styles, evt) {
if (!thatReorderer.activeItem || thatReorderer.activeItem !== evt.target) {
return true;
}
// If the key pressed is ctrl, and the active item is movable we want to restyle the active item.
var jActiveItem = $(thatReorderer.activeItem);
if (!jActiveItem.hasClass(styles.dragging) && thatReorderer.isMove(evt)) {
// Don't treat the active item as dragging unless it is a movable.
if (thatReorderer.isActiveItemMovable()) {
jActiveItem.removeClass(styles.selected);
jActiveItem.addClass(styles.dragging);
jActiveItem.attr("aria-grabbed", "true");
thatReorderer.setDropEffects("move");
}
return false;
}
// The only other keys we listen for are the arrows.
return thatReorderer.handleDirectionKeyDown(evt);
};
// unsupported, NON-API function
fluid.reorderer.handleDirectionKeyDown = function (thatReorderer, evt) {
var item = thatReorderer.activeItem;
if (!item) {
return true;
}
var keysets = thatReorderer.options.keysets;
for (var i = 0; i < keysets.length; i++) {
var keyset = keysets[i];
var keydir = fluid.keyForValue(keyset, evt.keyCode);
if (!keydir) {
continue;
}
var isMovement = keyset.modifier(evt);
var dirnum = fluid.keycodeDirection[keydir];
var relativeItem = thatReorderer.layoutHandler.getRelativePosition(item, dirnum, !isMovement);
if (!relativeItem) {
continue;
}
if (isMovement) {
var prevent = thatReorderer.events.onBeginMove.fire(item);
if (prevent === false) {
return false;
}
var kbDropWarning = thatReorderer.kbDropWarning;
if (kbDropWarning.length > 0) {
if (relativeItem.clazz === "locked") {
thatReorderer.events.onShowKeyboardDropWarning.fire(item, kbDropWarning);
kbDropWarning.show();
} else {
kbDropWarning.hide();
}
}
if (relativeItem.element) {
thatReorderer.requestMovement(relativeItem, item);
}
} else if (fluid.reorderer.noModifier(evt)) {
fluid.blur(item);
fluid.focus($(relativeItem.element));
}
return false;
}
return true;
};
// unsupported, NON-API function
fluid.reorderer.handleKeyUp = function (thatReorderer, styles, evt) {
if (!thatReorderer.activeItem || thatReorderer.activeItem !== evt.target) {
return true;
}
var jActiveItem = $(thatReorderer.activeItem);
// Handle a key up event for the modifier
if (jActiveItem.hasClass(styles.dragging) && !thatReorderer.isMove(evt)) {
if (thatReorderer.kbDropWarning) {
thatReorderer.kbDropWarning.hide();
}
jActiveItem.removeClass(styles.dragging);
jActiveItem.addClass(styles.selected);
jActiveItem.attr("aria-grabbed", "false");
thatReorderer.setDropEffects("none");
return false;
}
return false;
};
// unsupported, NON-API function
fluid.reorderer.requestMovement = function (thatReorderer, requestedPosition, item) {
item = fluid.unwrap(item);
// Temporary censoring to get around ModuleLayout inability to update relative to self.
if (!requestedPosition || fluid.unwrap(requestedPosition.element) === item) {
return;
}
var activeItem = $(thatReorderer.activeItem);
// Fixes FLUID-3288.
// Need to remove the blur event as safari will call blur on movements.
// This caused the user to have to double tap the arrow keys to move.
activeItem.off("blur.fluid.reorderer");
thatReorderer.events.onMove.fire(item, requestedPosition);
thatReorderer.dropManager.geometricMove(item, requestedPosition.element, requestedPosition.position);
//$(thatReorderer.activeItem).removeClass(options.styles.selected);
// refocus on the active item because moving places focus on the body
fluid.focus(activeItem);
thatReorderer.refresh();
thatReorderer.dropManager.updateGeometry(thatReorderer.layoutHandler.getGeometricInfo());
thatReorderer.events.afterMove.fire(item, requestedPosition, thatReorderer.dom.fastLocate("movables"));
};
// unsupported, NON-API function
fluid.reorderer.hoverStyleHandler = function (dom, styles, item, state) {
dom.fastLocate("grabHandle", item)[state ? "addClass" : "removeClass"](styles.hover);
};
// unsupported, NON-API function
fluid.reorderer.processAfterMoveCallbackUrl = function (thatReorderer) {
var options = thatReorderer.options;
if (options.afterMoveCallbackUrl) {
thatReorderer.events.afterMove.addListener(function () {
var layoutHandler = thatReorderer.layoutHandler;
var model = layoutHandler.getModel ? layoutHandler.getModel() :
options.acquireModel(thatReorderer);
$.post(options.afterMoveCallbackUrl, JSON.stringify(model));
}, "postModel");
}
};
fluid.reorderer.setDropEffects = function (dom, value) {
dom.fastLocate("dropTargets").attr("aria-dropeffect", value);
};
fluid.reorderer.createDropMarker = function (tagName, dropClass) {
var dropMarker = $(document.createElement(tagName));
dropMarker.addClass(dropClass);
dropMarker.hide();
return dropMarker;
};
fluid.reorderer.changeSelectedToDefault = function (jItem, styles) {
jItem.removeClass(styles.selected);
jItem.removeClass(styles.dragging);
jItem.addClass(styles.defaultStyle);
jItem.attr("aria-selected", "false");
};
fluid.reorderer.initSelectables = function (thatReorderer) {
var handleBlur = function (evt) {
thatReorderer.changeSelectedToDefault($(this));
return evt.stopPropagation();
};
var handleFocus = function (evt) {
thatReorderer.selectItem(this);
return evt.stopPropagation();
};
var handleClick = function (evt) {
var handle = fluid.unwrap(thatReorderer.dom.fastLocate("grabHandle", this));
if (fluid.dom.isContainer(handle, evt.target)) {
$(this).focus();
}
};
var selectables = thatReorderer.dom.fastLocate("selectables");
for (var i = 0; i < selectables.length; ++i) {
var selectable = $(selectables[i]);
if (!$.data(selectable[0], "fluid.reorderer.selectable-initialised")) {
selectable.addClass(thatReorderer.options.styles.defaultStyle);
selectable.on("blur.fluid.reorderer", handleBlur);
selectable.focus(handleFocus);
selectable.click(handleClick);
selectable.attr("role", thatReorderer.options.containerRole.item);
selectable.attr("aria-selected", "false");
selectable.attr("aria-disabled", "false");
$.data(selectable[0], "fluid.reorderer.selectable-initialised", true);
}
}
if (!thatReorderer.selectableContext) {
thatReorderer.selectableContext = fluid.selectable(thatReorderer.container, {
selectableElements: selectables,
selectablesTabindex: thatReorderer.options.selectablesTabindex,
direction: null
});
}
};
fluid.reorderer.selectItem = function (thatReorderer, anItem) {
thatReorderer.events.onSelect.fire(anItem);
// Set the previous active item back to its default state.
if (thatReorderer.activeItem && thatReorderer.activeItem !== anItem) {
thatReorderer.changeSelectedToDefault($(thatReorderer.activeItem));
}
// Then select the new item.
thatReorderer.activeItem = anItem;
var jItem = $(anItem);
var styles = thatReorderer.options.styles;
jItem.removeClass(styles.defaultStyle);
jItem.addClass(styles.selected);
jItem.attr("aria-selected", "true");
};
/*
* Takes a $ object and adds 'movable' functionality to it
*/
fluid.reorderer.initMovable = function (thatReorderer, dropManager, item) {
var options = thatReorderer.options;
var styles = options.styles;
item.attr("aria-grabbed", "false");
item.mouseover(
function () {
thatReorderer.events.onHover.fire(item, true);
}
);
item.mouseout(
function () {
thatReorderer.events.onHover.fire(item, false);
}
);
var avatar;
var handle = thatReorderer.dom.fastLocate("grabHandle", item);
item.draggable({
refreshPositions: false,
scroll: true,
helper: function () {
var dropWarningEl;
if (thatReorderer.mouseDropWarning) {
dropWarningEl = thatReorderer.mouseDropWarning[0];
}
avatar = $(options.avatarCreator(item[0], styles.avatar, dropWarningEl));
avatar.prop("id", fluid.reorderer.createAvatarId(thatReorderer.container.id));
return avatar;
},
start: function (e) {
var prevent = thatReorderer.events.onBeginMove.fire(item);
if (prevent === false) {
return false;
}
var handle = thatReorderer.dom.fastLocate("grabHandle", item)[0];
var handlePos = fluid.dom.computeAbsolutePosition(handle);
var handleWidth = handle.offsetWidth;
var handleHeight = handle.offsetHeight;
item.focus();
item.removeClass(options.styles.selected);
// all this junk should happen in handler for a new event - although note that mouseDrag style might cause display: none,
// invalidating dimensions
item.addClass(options.styles.mouseDrag);
item.attr("aria-grabbed", "true");
thatReorderer.setDropEffects("move");
dropManager.startDrag(e, handlePos, handleWidth, handleHeight);
avatar.show();
},
stop: function (e, ui) {
item.removeClass(options.styles.mouseDrag);
item.addClass(options.styles.selected);
$(thatReorderer.activeItem).attr("aria-grabbed", "false");
var markerNode = fluid.unwrap(thatReorderer.dropMarker);
if (markerNode.parentNode) {
markerNode.parentNode.removeChild(markerNode);
}
avatar.hide();
ui.helper = null;
thatReorderer.setDropEffects("none");
dropManager.endDrag();
thatReorderer.requestMovement(dropManager.lastPosition(), item);
// refocus on the active item because moving places focus on the body
thatReorderer.activeItem.focus();
},
// This explicit detection is now required for jQuery UI after version 1.10.2 since the upstream API has been broken permanently.
// See https://github.com/jquery/jquery-ui/pull/963
handle: fluid.unwrap(handle) === fluid.unwrap(item) ? null : handle
});
};
fluid.reorderer.initItems = function (thatReorderer) {
var movables = thatReorderer.dom.fastLocate("movables");
var dropTargets = thatReorderer.dom.fastLocate("dropTargets");
thatReorderer.initSelectables();
// Setup movables
for (var i = 0; i < movables.length; i++) {
var item = movables[i];
if (!$.data(item, "fluid.reorderer.movable-initialised")) {
thatReorderer.initMovable($(item));
$.data(item, "fluid.reorderer.movable-initialised", true);
}
}
// In order to create valid html, the drop marker is the same type as the node being dragged.
// This creates a confusing UI in cases such as an ordered list.
if (movables.length > 0 && !thatReorderer.dropMarker) {
thatReorderer.dropMarker = thatReorderer.createDropMarker(movables[0].tagName);
}
thatReorderer.dropManager.updateGeometry(thatReorderer.layoutHandler.getGeometricInfo());
var dropChangeListener = function (dropTarget) {
fluid.dom.moveDom(thatReorderer.dropMarker, dropTarget.element, dropTarget.position);
thatReorderer.dropMarker.css("display", "");
if (thatReorderer.mouseDropWarning) {
if (dropTarget.lockedelem) {
thatReorderer.mouseDropWarning.show();
} else {
thatReorderer.mouseDropWarning.hide();
}
}
};
thatReorderer.dropManager.dropChangeFirer.addListener(dropChangeListener, "fluid.reorderer");
// Set up dropTargets
dropTargets.attr("aria-dropeffect", "none");
};
fluid.reorderer.refresh = function (dom, events, selectableContext, activeItem) {
dom.refresh("movables");
dom.refresh("selectables");
dom.refresh("grabHandle", dom.fastLocate("movables"));
dom.refresh("dropTargets");
if (selectableContext) { // if it didn't exist on dispatch, it must be up to date now
selectableContext.selectables = dom.fastLocate("selectables");
selectableContext.selectablesUpdated(activeItem);
}
events.onRefresh.fire(); // This should be last otherwise handlers will see stale DOM binder contents
};
/**
* These roles are used to add ARIA roles to orderable items. This list can be extended as needed,
* but the values of the container and item roles must match ARIA-specified roles.
*/
fluid.reorderer.roles = {
GRID: { container: "grid", item: "gridcell" },
LIST: { container: "list", item: "listitem" },
REGIONS: { container: "main", item: "article" }
};
fluid.defaults("fluid.reorderList", {
gradeNames: ["fluid.reorderer"],
layoutHandler: "fluid.listLayoutHandler"
});
fluid.defaults("fluid.reorderGrid", {
gradeNames: ["fluid.reorderer"],
layoutHandler: "fluid.gridLayoutHandler"
});
fluid.reorderer.SHUFFLE_GEOMETRIC_STRATEGY = "shuffleProjectFrom";
fluid.reorderer.GEOMETRIC_STRATEGY = "projectFrom";
fluid.reorderer.LOGICAL_STRATEGY = "logicalFrom";
fluid.reorderer.WRAP_LOCKED_STRATEGY = "lockedWrapFrom";
fluid.reorderer.NO_STRATEGY = null;
// unsupported, NON-API function
fluid.reorderer.relativeInfoGetter = function (orientation, coStrategy, contraStrategy, dropManager, disableWrap) {
return function (item, direction, forSelection) {
var dirorient = fluid.directionOrientation(direction);
var strategy = dirorient === orientation ? coStrategy : contraStrategy;
return strategy !== null ? dropManager[strategy](item, direction, forSelection, disableWrap) : null;
};
};
/*******************
* Layout Handlers *
*******************/
// unsupported, NON-API function
fluid.reorderer.makeGeometricInfoGetter = function (orientation, sentinelize, dom) {
var that = {
sentinelize: sentinelize,
extents: [{
orientation: orientation,
elements: dom.fastLocate("dropTargets")
}],
elementMapper: function (element) {
return $.inArray(element, dom.fastLocate("movables")) === -1 ? "locked" : null;
},
elementIndexer: function (element) {
var selectables = dom.fastLocate("selectables");
return {
elementClass: that.elementMapper(element),
index: $.inArray(element, selectables),
length: selectables.length
};
}
};
return that;
};
fluid.defaults("fluid.layoutHandler", {
gradeNames: ["fluid.viewComponent"],
disableWrap: "{reorderer}.options.disableWrap",
members: {
reordererDom: "{reorderer}.dom",
dropManager: "{reorderer}.dropManager"
},
invokers: { // overridden in moduleLayoutHandler
getGeometricInfo: "fluid.reorderer.makeGeometricInfoGetter({that}.options.orientation, {that}.options.sentinelize, {that}.reordererDom)"
}
});
// Public layout handlers.
fluid.defaults("fluid.listLayoutHandler", {
gradeNames: ["fluid.layoutHandler"],
orientation: fluid.orientation.VERTICAL,
containerRole: fluid.reorderer.roles.LIST,
selectablesTabindex: -1,
sentinelize: true,
members: {
getRelativePosition: { // TODO: an old-fashioned function member - convert to invoker
expander: {
funcName: "fluid.reorderer.relativeInfoGetter",
args: [ "{that}.options.orientation", fluid.reorderer.LOGICAL_STRATEGY, null,
"{that}.dropManager", "{that}.options.disableWrap"]
}
}
}
});
/*
* Items in the Lightbox are stored in a list, but they are visually presented as a grid that
* changes dimensions when the window changes size. As a result, when the user presses the up or
* down arrow key, what lies above or below depends on the current window size.
*
* The GridLayoutHandler is responsible for handling changes to this virtual 'grid' of items
* in the window, and of informing the Lightbox of which items surround a given item.
*/
fluid.defaults("fluid.gridLayoutHandler", {
gradeNames: ["fluid.layoutHandler"],
orientation: fluid.orientation.HORIZONTAL,
containerRole: fluid.reorderer.roles.GRID,
selectablesTabindex: -1,
sentinelize: false,
coStrategy: "@expand:fluid.gridLayoutHandler.computeCoStrategy({that}.options.disableWrap)",
members: {
getRelativePosition: { // TODO: an old-fashioned function member - convert to invoker
expander: {
funcName: "fluid.reorderer.relativeInfoGetter",
args: [ "{that}.options.orientation", "{that}.options.coStrategy", fluid.reorderer.SHUFFLE_GEOMETRIC_STRATEGY,
"{that}.dropManager", "{that}.options.disableWrap"]
}
}
}
});
fluid.gridLayoutHandler.computeCoStrategy = function (disableWrap) {
return disableWrap ? fluid.reorderer.SHUFFLE_GEOMETRIC_STRATEGY : fluid.reorderer.LOGICAL_STRATEGY;
};
/*************
* Labelling *
*************/
/** ARIA labeller component which decorates the reorderer with the function of announcing the current
* focused position of the reorderer as well as the coordinates of any requested move */
fluid.defaults("fluid.reorderer.labeller", {
gradeNames: ["fluid.component"],
members: {
movedMap: {},
moduleCell: {
expander: {
funcName: "fluid.reorderer.labeller.computeModuleCell",
args: ["{that}.resolver", "{that}.options.orientation"]
}
},
layoutType: {
expander: {
funcName: "fluid.computeNickName",
args: "{that}.options.layoutType"
}
},
positionTemplate: {
expander: {
funcName: "fluid.reorderer.labeller.computePositionTemplate",
args: ["{that}.resolver", "{that}.layoutType"]
}
}
},
strings: {
overallTemplate: "%recentStatus %item %position %movable",
position: "%index of %length",
position_moduleLayoutHandler: "%index of %length in %moduleCell %moduleIndex of %moduleLength",
moduleCell_0: "row", // NB, these keys must agree with fluid.a11y.orientation constants
moduleCell_1: "column",
movable: "movable",
fixed: "fixed",
recentStatus: "moved from position %position"
},
components: {
resolver: {
type: "fluid.messageResolver",
options: {
messageBase: "{labeller}.options.strings"
}
}
},
invokers: {
renderLabel: {
funcName: "fluid.reorderer.labeller.renderLabel",
args: ["{labeller}", "{arguments}.0", "{arguments}.1"]
}
},
listeners: {
"{reorderer}.events.onRefresh": {
listener: "fluid.reorderer.labeller.onRefresh",
args: "{that}"
},
"{reorderer}.events.onMove": {
listener: "fluid.reorderer.labeller.onMove",
args: ["{that}", "{arguments}.0", "{arguments}.1"] // item, newPosition
}
}
});
// unsupported, NON-API function
fluid.reorderer.labeller.computeModuleCell = function (resolver, orientation) {
return resolver.resolve("moduleCell_" + orientation);
};
// unsupported, NON-API function
fluid.reorderer.labeller.computePositionTemplate = function (resolver, layoutType) {
return resolver.lookup(["position_" + layoutType, "position"]);
};
// unsupported, NON-API function
fluid.reorderer.labeller.onRefresh = function (that) {
var selectables = that.dom.locate("selectables");
var movedMap = that.movedMap;
fluid.each(selectables, function (selectable) {
var labelOptions = {};
var id = fluid.allocateSimpleId(selectable);
var moved = movedMap[id];
var label = that.renderLabel(selectable);
var plainLabel = label;
if (moved) {
moved.newRender = plainLabel;
label = that.renderLabel(selectable, moved.oldRender.position);
// once we move focus out of the element which just moved, return its ARIA label to be the new plain label
$(selectable).one("focusout.ariaLabeller", function () {
if (movedMap[id]) {
var oldLabel = movedMap[id].newRender.label;
delete movedMap[id];
fluid.updateAriaLabel(selectable, oldLabel);
}
});
labelOptions.dynamicLabel = true;
}
fluid.updateAriaLabel(selectable, label.label, labelOptions);
});
};
// unsupported, NON-API function
fluid.reorderer.labeller.onMove = function (that, item) {
fluid.clear(that.movedMap); // if we somehow were fooled into missing a defocus, at least clear the map on a 2nd move
// This "off" is needed for FLUID-4693 with Chrome 18, which generates a focusOut when
// simply doing the DOM manipulation to move the element to a new position.
$(item).off("focusout.ariaLabeller");
var movingId = fluid.allocateSimpleId(item);
that.movedMap[movingId] = {
oldRender: that.renderLabel(item)
};
};
// unsupported, NON-API function
// Convert from 0-based to 1-based indices for announcement
fluid.reorderer.indexRebaser = function (indices) {
indices.index++;
if (indices.moduleIndex !== undefined) {
indices.moduleIndex++;
}
return indices;
};
// unsupported, NON-API function
fluid.reorderer.labeller.renderLabel = function (that, selectable, recentPosition) {
var geom = that.options.getGeometricInfo();
var indices = fluid.reorderer.indexRebaser(geom.elementIndexer(selectable));
indices.moduleCell = that.moduleCell;
var elementClass = geom.elementMapper(selectable);
var labelSource = that.dom.locate("labelSource", selectable);
var recentStatus;
if (recentPosition) {
recentStatus = that.resolver.resolve("recentStatus", {position: recentPosition});
}
var topModel = {
item: typeof (labelSource) === "string" ? labelSource : fluid.dom.getElementText(fluid.unwrap(labelSource)),
position: that.positionTemplate.resolveFunc(that.positionTemplate.template, indices),
movable: that.resolver.resolve(elementClass === "locked" ? "fixed" : "movable"),
recentStatus: recentStatus || ""
};
var template = that.resolver.lookup(["overallTemplate"]);
var label = template.resolveFunc(template.template, topModel);
return {
position: topModel.position,
label: label
};
};
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
fluid.registerNamespace("fluid.reorderImages");
fluid.reorderImages.deriveLightboxCellBase = function (namebase, index) {
return namebase + "lightbox-cell:" + index + ":";
};
fluid.reorderImages.addThumbnailActivateHandler = function (container) {
var enterKeyHandler = function (evt) {
if (evt.which === fluid.reorderer.keys.ENTER) {
var thumbnailAnchors = $("a", evt.target);
document.location = thumbnailAnchors.attr("href");
}
};
container.keypress(enterKeyHandler);
};
// Custom query method seeks all tags descended from a given root with a
// particular tag name, whose id matches a regex.
fluid.reorderImages.seekNodesById = function (rootnode, tagname, idmatch) {
var inputs = rootnode.getElementsByTagName(tagname);
var togo = [];
for (var i = 0; i < inputs.length; i += 1) {
var input = inputs[i];
var id = input.id;
if (id && id.match(idmatch)) {
togo.push(input);
}
}
return togo;
};
fluid.reorderImages.createImageCellFinder = function (parentNode, containerId) {
containerId = containerId || parentNode.prop("id");
parentNode = fluid.unwrap(parentNode);
var lightboxCellNamePattern = "^" + fluid.reorderImages.deriveLightboxCellBase(containerId, "[0-9]+") + "$";
return function () {
// This orderable finder assumes that the lightbox thumbnails are 'div' elements
return fluid.reorderImages.seekNodesById(parentNode, "div", lightboxCellNamePattern);
};
};
fluid.reorderImages.seekForm = function (container) {
return fluid.findAncestor(container, function (element) {
return $(element).is("form");
});
};
fluid.reorderImages.seekInputs = function (container, reorderform) {
return fluid.reorderImages.seekNodesById(reorderform,
"input",
"^" + fluid.reorderImages.deriveLightboxCellBase(container.prop("id"), "[^:]*") + "reorder-index$");
};
fluid.reorderImages.mapIdsToNames = function (container, reorderform) {
var inputs = fluid.reorderImages.seekInputs(container, reorderform);
for (var i = 0; i < inputs.length; i++) {
var input = inputs[i];
var name = input.name;
input.name = name || input.id;
}
};
/**
* Returns a default afterMove listener using the id-based, form-driven scheme for communicating with the server.
* It is implemented by nesting hidden form fields inside each thumbnail container. The value of these form elements
* represent the order for each image. This default listener submits the form's default
* action via AJAX.
*
* @param {jQueryable} container - The Image Reorderer's container element.
* @return {Function} - A function which can be used as a listener for the afterMove event.
*/
fluid.reorderImages.createIDAfterMoveListener = function (container) {
var reorderform = fluid.reorderImages.seekForm(container);
fluid.reorderImages.mapIdsToNames(container, reorderform);
return function () {
var inputs, i;
inputs = fluid.reorderImages.seekInputs(container, reorderform);
for (i = 0; i < inputs.length; i += 1) {
inputs[i].value = i;
}
if (reorderform && reorderform.action) {
var order = $(reorderform).serialize();
$.post(reorderform.action,
order,
function () { /* No-op response */ });
}
};
};
// Public Lightbox API
/**
* Creates a new Lightbox instance from the specified parameters, providing full control over how
* the Lightbox is configured.
*
* @param container {Object}
* @param options {Object}
*/
fluid.defaults("fluid.reorderImages", {
gradeNames: ["fluid.reorderer"],
layoutHandler: "fluid.gridLayoutHandler",
listeners: {
"afterMove.postModel": {
expander: {
funcName: "fluid.reorderImages.createIDAfterMoveListener",
args: "{that}.container"
}
}
},
selectors: {
movables: {
expander: {
funcName: "fluid.reorderImages.createImageCellFinder",
args: "{that}.container"
}
},
labelSource: ".flc-reorderer-imageTitle"
}
});
// This function now deprecated. Please use fluid.reorderImages() instead.
fluid.lightbox = fluid.reorderImages;
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
fluid.registerNamespace("fluid.moduleLayout");
/**
* Calculate the location of the item and the column in which it resides.
* @param {Object} - The item.
* @param {Object} - The layout object.
* @return An object with column index and item index (within that column) properties.
* These indices are -1 if the item does not exist in the grid.
*/
// unsupported - NON-API function
fluid.moduleLayout.findColumnAndItemIndices = function (item, layout) {
return fluid.find(layout.columns,
function (column, colIndex) {
var index = $.inArray(item, column.elements);
return index === -1 ? undefined : {columnIndex: colIndex, itemIndex: index};
}, {columnIndex: -1, itemIndex: -1});
};
// unsupported - NON-API function
fluid.moduleLayout.findColIndex = function (item, layout) {
return fluid.find(layout.columns,
function (column, colIndex) {
return item === column.container ? colIndex : undefined;
}, -1);
};
/**
* Move an item within the layout object.
*/
// unsupported - NON-API function
fluid.moduleLayout.updateLayout = function (item, target, position, layout) {
item = fluid.unwrap(item);
target = fluid.unwrap(target);
var itemIndices = fluid.moduleLayout.findColumnAndItemIndices(item, layout);
layout.columns[itemIndices.columnIndex].elements.splice(itemIndices.itemIndex, 1);
var targetCol;
if (position === fluid.position.INSIDE) {
targetCol = layout.columns[fluid.moduleLayout.findColIndex(target, layout)].elements;
targetCol.splice(targetCol.length, 0, item);
} else {
var relativeItemIndices = fluid.moduleLayout.findColumnAndItemIndices(target, layout);
targetCol = layout.columns[relativeItemIndices.columnIndex].elements;
position = fluid.dom.normalisePosition(position,
itemIndices.columnIndex === relativeItemIndices.columnIndex,
relativeItemIndices.itemIndex, itemIndices.itemIndex);
var relative = position === fluid.position.BEFORE ? 0 : 1;
targetCol.splice(relativeItemIndices.itemIndex + relative, 0, item);
}
};
/**
* Builds a layout object from a set of columns and modules.
* @param {jQuery} container - The container element.
* @param {jQuery} columns - One or more jQuery objects representing columns of data.
* @param {jQuery} portlets - One or more "portlet" elements to include in the layout.
* @return {Object} - A layout object.
*/
fluid.moduleLayout.layoutFromFlat = function (container, columns, portlets) {
var layout = {};
layout.container = container;
layout.columns = fluid.transform(columns,
function (column) {
return {
container: column,
elements: fluid.makeArray(portlets.filter(function () {
// is this a bug in filter? would have expected "this" to be 1st arg
return fluid.dom.isContainer(column, this);
}))
};
});
return layout;
};
/*
* Builds a layout object from a serialisable "layout" object consisting of id lists
*/
fluid.moduleLayout.layoutFromIds = function (idLayout) {
return {
container: fluid.byId(idLayout.id),
columns: fluid.transform(idLayout.columns, function (column) {
return {
container: fluid.byId(column.id),
elements: fluid.transform(column.children, fluid.byId)
};
})
};
};
/*
* Serializes the current layout into a structure of ids
*/
fluid.moduleLayout.layoutToIds = function (idLayout) {
return {
id: fluid.getId(idLayout.container),
columns: fluid.transform(idLayout.columns, function (column) {
return {
id: fluid.getId(column.container),
children: fluid.transform(column.elements, fluid.getId)
};
})
};
};
fluid.moduleLayout.defaultOnShowKeyboardDropWarning = function (item, dropWarning) {
if (dropWarning) {
var offset = $(item).offset();
dropWarning = $(dropWarning);
dropWarning.css("position", "absolute");
dropWarning.css("top", offset.top);
dropWarning.css("left", offset.left);
}
};
/*
* Module Layout Handler for reordering content modules.
*
* General movement guidelines:
*
* - Arrowing sideways will always go to the top (moveable) module in the column
* - Moving sideways will always move to the top available drop target in the column
* - Wrapping is not necessary at this first pass, but is ok
*/
fluid.defaults("fluid.moduleLayoutHandler", {
gradeNames: ["fluid.layoutHandler"],
orientation: fluid.orientation.VERTICAL,
containerRole: fluid.reorderer.roles.REGIONS,
selectablesTabindex: -1,
sentinelize: true,
events: {
onMove: "{reorderer}.events.onMove",
onRefresh: "{reorderer}.events.onRefresh",
onShowKeyboardDropWarning: "{reorderer}.events.onShowKeyboardDropWarning"
},
listeners: {
"onShowKeyboardDropWarning.setPosition": "fluid.moduleLayout.defaultOnShowKeyboardDropWarning",
onRefresh: {
priority: "first",
listener: "{that}.computeLayout"
},
onMove: {
priority: "last",
listener: "fluid.moduleLayout.onMoveListener",
args: ["{arguments}.0", "{arguments}.1", "{that}.layout"]
}
},
members: {
layout: {
expander: {
func: "{that}.computeLayout"
}
},
getRelativePosition: { // TODO: an old-fashioned function member - convert to invoker
expander: {
funcName: "fluid.reorderer.relativeInfoGetter",
args: [ "{that}.options.orientation", fluid.reorderer.WRAP_LOCKED_STRATEGY, fluid.reorderer.GEOMETRIC_STRATEGY,
"{that}.dropManager", "{that}.options.disableWrap"]
}
}
},
invokers: { // Use very specific arguments for selectors to avoid circularity
// also, do not share our DOM binder for our own selectors with parent, to avoid inability to
// update DOM binder's selectors after initialisation - and since we require a DOM binder in order to compute
// the modified selectors for upward injection
computeLayout: {
funcName: "fluid.moduleLayout.computeLayout",
args: ["{that}", "{reorderer}.options.selectors.modules", "{that}.dom"]
},
computeModules: { // guarantees to read "layout" on every call
funcName: "fluid.moduleLayout.computeModules",
args: ["{that}.layout", "{that}.isLocked", "{arguments}.0"]
},
makeComputeModules: { // expander function to create DOM locators
funcName: "fluid.moduleLayout.makeComputeModules",
args: ["{that}", "{arguments}.0"]
},
isLocked: {
funcName: "fluid.moduleLayout.isLocked",
args: ["{arguments}.0", "{reorderer}.options.selectors.lockedModules", "{that}.reordererDom"]
},
getGeometricInfo: "fluid.moduleLayout.getGeometricInfo({that})",
getModel: "fluid.moduleLayout.getModel({that})"
},
selectors: {
modules: "{reorderer}.options.selectors.modules",
columns: "{reorderer}.options.selectors.columns"
},
distributeOptions: {
target: "{reorderer}.options",
record: {
selectors: {
movables: {
expander: {
func: "{that}.makeComputeModules",
args: [false]
}
},
dropTargets: {
expander: {
func: "{that}.makeComputeModules",
args: [false]
}
},
selectables: {
expander: {
func: "{that}.makeComputeModules",
args: [true]
}
}
}
}
}
});
fluid.moduleLayout.getGeometricInfo = function (that) {
var options = that.options;
var extents = [];
var togo = {extents: extents,
sentinelize: options.sentinelize};
togo.elementMapper = function (element) {
return that.isLocked(element) ? "locked" : null;
};
togo.elementIndexer = function (element) {
var indices = fluid.moduleLayout.findColumnAndItemIndices(element, that.layout);
return {
index: indices.itemIndex,
length: that.layout.columns[indices.columnIndex].elements.length,
moduleIndex: indices.columnIndex,
moduleLength: that.layout.columns.length
};
};
for (var col = 0; col < that.layout.columns.length; col++) {
var column = that.layout.columns[col];
var thisEls = {
orientation: options.orientation,
elements: fluid.makeArray(column.elements),
parentElement: column.container
};
// fluid.log("Geometry col " + col + " elements " + fluid.dumpEl(thisEls.elements) + " isLocked [" +
// fluid.transform(thisEls.elements, togo.elementMapper).join(", ") + "]");
extents.push(thisEls);
}
return togo;
};
fluid.moduleLayout.getModel = function (that) {
return fluid.moduleLayout.layoutToIds(that.layout); // note that that.layout is a "volatile member"
};
fluid.moduleLayout.computeLayout = function (that, modulesSelector, dom) {
var togo;
if (modulesSelector) {
togo = fluid.moduleLayout.layoutFromFlat(that.container, dom.locate("columns"), dom.locate("modules"));
}
if (!togo) { // TODO: this branch appears to be unspecified and untested
var idLayout = fluid.get(that.options, "moduleLayout.layout");
togo = fluid.moduleLayout.layoutFromIds(idLayout);
}
that.layout = togo;
return togo;
};
fluid.moduleLayout.computeModules = function (layout, isLocked, all) {
var modules = fluid.accumulate(layout.columns, function (column, list) {
return list.concat(column.elements); // note that concat will not work on a jQuery
}, []);
if (!all) {
fluid.remove_if(modules, isLocked);
}
return modules;
};
fluid.moduleLayout.makeComputeModules = function (that, all) {
return function () {
return that.computeModules(all);
};
};
fluid.moduleLayout.isLocked = function (item, lockedModulesSelector, dom) {
var lockedModules = lockedModulesSelector ? dom.fastLocate("lockedModules") : [];
return $.inArray(item, lockedModules) !== -1;
};
fluid.moduleLayout.onMoveListener = function (item, requestedPosition, layout) {
fluid.moduleLayout.updateLayout(item, requestedPosition.element, requestedPosition.position, layout);
};
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
/**
* A convenience function for applying the Reorderer to portlets, content blocks, or other chunks of layout with
* minimal effort.
*
* @param {String|Object} container - A CSS-based selector, single-element jQuery object, or DOM element that identifies the DOM element containing the layout.
* @param {Object} [userOptions] - An optional collection of key/value pairs that can be used to further configure the Layout Reorderer. See: https://wiki.fluidproject.org/display/docs/Layout+Reorderer+API
* @return {Object} - A newly constructed reorderer component.
*/
fluid.reorderLayout = function (container, userOptions) {
var assembleOptions = {
layoutHandler: "fluid.moduleLayoutHandler",
selectors: {
columns: ".flc-reorderer-column",
modules: ".flc-reorderer-module"
}
};
var options = $.extend(true, assembleOptions, userOptions);
return fluid.reorderer(container, options);
};
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
/**********************
* Sliding Panel *
*********************/
fluid.defaults("fluid.slidingPanel", {
gradeNames: ["fluid.viewComponent"],
selectors: {
panel: ".flc-slidingPanel-panel",
toggleButton: ".flc-slidingPanel-toggleButton",
toggleButtonLabel: ".flc-slidingPanel-toggleButton"
},
strings: {
showText: "show",
hideText: "hide",
panelLabel: "panel"
},
events: {
onPanelHide: null,
onPanelShow: null,
afterPanelHide: null,
afterPanelShow: null
},
listeners: {
"onCreate.bindClick": {
"this": "{that}.dom.toggleButton",
"method": "click",
"args": ["{that}.togglePanel"]
},
"onCreate.bindModelChange": {
listener: "{that}.applier.modelChanged.addListener",
args: ["isShowing", "{that}.refreshView"]
},
"onCreate.setAriaProps": "{that}.setAriaProps",
"onCreate.setInitialState": {
listener: "{that}.refreshView"
},
"onPanelHide.setText": {
"this": "{that}.dom.toggleButtonLabel",
"method": "text",
"args": ["{that}.options.strings.showText"],
"priority": "first"
},
"onPanelHide.setAriaLabel": {
"this": "{that}.dom.toggleButtonLabel",
"method": "attr",
"args": ["aria-label", "{that}.options.strings.showTextAriaLabel"]
},
"onPanelShow.setText": {
"this": "{that}.dom.toggleButtonLabel",
"method": "text",
"args": ["{that}.options.strings.hideText"],
"priority": "first"
},
"onPanelShow.setAriaLabel": {
"this": "{that}.dom.toggleButtonLabel",
"method": "attr",
"args": ["aria-label", "{that}.options.strings.hideTextAriaLabel"]
},
"onPanelHide.operate": {
listener: "{that}.operateHide"
},
"onPanelShow.operate": {
listener: "{that}.operateShow"
},
"onCreate.setAriaStates": "{that}.setAriaStates"
},
members: {
panelId: {
expander: {
// create an id for panel
// and set that.panelId to the id value
funcName: "fluid.allocateSimpleId",
args: "{that}.dom.panel"
}
}
},
model: {
isShowing: false
},
modelListeners: {
"isShowing": {
funcName: "{that}.setAriaStates",
excludeSource: "init"
}
},
invokers: {
operateHide: {
"this": "{that}.dom.panel",
"method": "slideUp",
"args": ["{that}.options.animationDurations.hide", "{that}.events.afterPanelHide.fire"]
},
operateShow: {
"this": "{that}.dom.panel",
"method": "slideDown",
"args": ["{that}.options.animationDurations.show", "{that}.events.afterPanelShow.fire"]
},
hidePanel: {
func: "{that}.applier.change",
args: ["isShowing", false]
},
showPanel: {
func: "{that}.applier.change",
args: ["isShowing", true]
},
setAriaStates: {
funcName: "fluid.slidingPanel.setAriaStates",
args: ["{that}", "{that}.model.isShowing"]
},
setAriaProps: {
funcName: "fluid.slidingPanel.setAriaProperties",
args: ["{that}", "{that}.panelId"]
},
togglePanel: {
funcName: "fluid.slidingPanel.togglePanel",
args: ["{that}"]
},
refreshView: {
funcName: "fluid.slidingPanel.refreshView",
args: ["{that}"]
}
},
animationDurations: {
hide: 400,
show: 400
}
});
fluid.slidingPanel.togglePanel = function (that) {
that.applier.change("isShowing", !that.model.isShowing);
};
fluid.slidingPanel.refreshView = function (that) {
that.events[that.model.isShowing ? "onPanelShow" : "onPanelHide"].fire();
};
// panelId is passed in to ensure that it is evaluated before this
// function is called.
fluid.slidingPanel.setAriaProperties = function (that, panelId) {
that.locate("toggleButton").attr({
"role": "button",
"aria-controls": panelId
});
that.locate("panel").attr({
"aria-label": that.options.strings.panelLabel,
"role": "group"
});
};
fluid.slidingPanel.setAriaStates = function (that, isShowing) {
that.locate("toggleButton").attr({
"aria-pressed": isShowing,
"aria-expanded": isShowing
});
};
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
/**********
* Switch *
**********/
fluid.defaults("fluid.switchUI", {
gradeNames: ["fluid.viewComponent"],
selectors: {
on: ".flc-switchUI-on",
off: ".flc-switchUI-off",
control: ".flc-switchUI-control"
},
strings: {
// Specified by implementor
// text of label to apply the switch, must add to "aria-label" in the attrs block
label: "",
on: "on",
off: "off"
},
attrs: {
// Specified by implementor
// ID of an element to use as a label for the switch
// "aria-labelledby": "",
// Should specify either "aria-label" or "aria-labelledby"
// "aria-label": "{that}.options.strings.label",
// ID of an element that is controlled by the switch.
// "aria-controls": ""
role: "switch",
tabindex: 0
},
model: {
enabled: false
},
modelListeners: {
enabled: {
"this": "{that}.dom.control",
method: "attr",
args: ["aria-checked", "{change}.value"]
}
},
listeners: {
"onCreate.addAttrs": {
"this": "{that}.dom.control",
method: "attr",
args: ["{that}.options.attrs"]
},
"onCreate.addOnText": {
"this": "{that}.dom.on",
method: "text",
args: ["{that}.options.strings.on"]
},
"onCreate.addOffText": {
"this": "{that}.dom.off",
method: "text",
args: ["{that}.options.strings.off"]
},
"onCreate.activateable": {
listener: "fluid.activatable",
args: ["{that}.dom.control", "{that}.activateHandler"]
},
"onCreate.bindClick": {
"this": "{that}.dom.control",
method: "on",
args: ["click", "{that}.toggleModel"]
}
},
invokers: {
toggleModel: {
funcName: "fluid.switchUI.toggleModel",
args: ["{that}"]
},
activateHandler: {
funcName: "fluid.switchUI.activateHandler",
args: ["{arguments}.0", "{that}.toggleModel"]
}
}
});
fluid.switchUI.toggleModel = function (that) {
that.applier.change("enabled", !that.model.enabled);
};
fluid.switchUI.activateHandler = function (event, fn) {
event.preventDefault();
fn();
};
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
/******
* ToC *
*******/
fluid.registerNamespace("fluid.tableOfContents");
fluid.tableOfContents.headingTextToAnchorInfo = function (heading) {
var id = fluid.allocateSimpleId(heading);
var anchorInfo = {
id: id,
url: "#" + id
};
return anchorInfo;
};
fluid.tableOfContents.locateHeadings = function (that) {
var headings = that.locate("headings");
fluid.each(that.options.ignoreForToC, function (sel) {
headings = headings.not(sel).not(sel + " :header");
});
return headings;
};
fluid.tableOfContents.refreshView = function (that) {
var headings = that.locateHeadings();
that.anchorInfo = fluid.transform(headings, function (heading) {
return that.headingTextToAnchorInfo(heading);
});
var headingsModel = that.modelBuilder.assembleModel(headings, that.anchorInfo);
that.applier.change("", headingsModel);
that.events.onRefresh.fire();
};
fluid.defaults("fluid.tableOfContents", {
gradeNames: ["fluid.viewComponent"],
components: {
levels: {
type: "fluid.tableOfContents.levels",
createOnEvent: "onCreate",
container: "{tableOfContents}.dom.tocContainer",
options: {
model: {
headings: "{tableOfContents}.model"
},
events: {
afterRender: "{tableOfContents}.events.afterRender"
},
listeners: {
"{tableOfContents}.events.onRefresh": "{that}.refreshView"
},
strings: "{tableOfContents}.options.strings"
}
},
modelBuilder: {
type: "fluid.tableOfContents.modelBuilder"
}
},
model: [],
invokers: {
headingTextToAnchorInfo: "fluid.tableOfContents.headingTextToAnchorInfo",
locateHeadings: {
funcName: "fluid.tableOfContents.locateHeadings",
args: ["{that}"]
},
refreshView: {
funcName: "fluid.tableOfContents.refreshView",
args: ["{that}"]
},
// TODO: is it weird to have hide and show on a component?
hide: {
"this": "{that}.dom.tocContainer",
"method": "hide"
},
show: {
"this": "{that}.dom.tocContainer",
"method": "show"
}
},
strings: {
tocHeader: "Table of Contents"
},
selectors: {
headings: ":header:visible",
tocContainer: ".flc-toc-tocContainer"
},
ignoreForToC: {
tocContainer: "{that}.options.selectors.tocContainer"
},
events: {
onRefresh: null,
afterRender: null,
onReady: {
events: {
"onCreate": "onCreate",
"afterRender": "afterRender"
},
args: ["{that}"]
}
},
listeners: {
"onCreate.refreshView": "{that}.refreshView"
}
});
/*******************
* ToC ModelBuilder *
********************/
fluid.registerNamespace("fluid.tableOfContents.modelBuilder");
fluid.tableOfContents.modelBuilder.toModel = function (headingInfo, modelLevelFn) {
var headings = fluid.copy(headingInfo);
var buildModelLevel = function (headings, level) {
var modelLevel = [];
while (headings.length > 0) {
var heading = headings[0];
if (heading.level < level) {
break;
}
if (heading.level > level) {
var subHeadings = buildModelLevel(headings, level + 1);
if (modelLevel.length > 0) {
modelLevel[modelLevel.length - 1].headings = subHeadings;
} else {
modelLevel = modelLevelFn(modelLevel, subHeadings);
}
}
if (heading.level === level) {
modelLevel.push(heading);
headings.shift();
}
}
return modelLevel;
};
return buildModelLevel(headings, 1);
};
fluid.tableOfContents.modelBuilder.gradualModelLevelFn = function (modelLevel, subHeadings) {
// Clone the subHeadings because we don't want to modify the reference of the subHeadings.
// the reference will affect the equality condition in generateTree(), resulting an unwanted tree.
var subHeadingsClone = fluid.copy(subHeadings);
subHeadingsClone[0].level--;
return subHeadingsClone;
};
fluid.tableOfContents.modelBuilder.skippedModelLevelFn = function (modelLevel, subHeadings) {
modelLevel.push({headings: subHeadings});
return modelLevel;
};
fluid.tableOfContents.modelBuilder.convertToHeadingObjects = function (that, headings, anchorInfo) {
headings = $(headings);
return fluid.transform(headings, function (heading, index) {
return {
level: that.headingCalculator.getHeadingLevel(heading),
text: $(heading).text(),
url: anchorInfo[index].url
};
});
};
fluid.tableOfContents.modelBuilder.assembleModel = function (that, headings, anchorInfo) {
var headingInfo = that.convertToHeadingObjects(headings, anchorInfo);
return that.toModel(headingInfo);
};
fluid.defaults("fluid.tableOfContents.modelBuilder", {
gradeNames: ["fluid.component"],
components: {
headingCalculator: {
type: "fluid.tableOfContents.modelBuilder.headingCalculator"
}
},
invokers: {
toModel: {
funcName: "fluid.tableOfContents.modelBuilder.toModel",
args: ["{arguments}.0", "{modelBuilder}.modelLevelFn"]
},
modelLevelFn: "fluid.tableOfContents.modelBuilder.gradualModelLevelFn",
convertToHeadingObjects: "fluid.tableOfContents.modelBuilder.convertToHeadingObjects({that}, {arguments}.0, {arguments}.1)", // headings, anchorInfo
assembleModel: "fluid.tableOfContents.modelBuilder.assembleModel({that}, {arguments}.0, {arguments}.1)" // headings, anchorInfo
}
});
/*************************************
* ToC ModelBuilder headingCalculator *
**************************************/
fluid.registerNamespace("fluid.tableOfContents.modelBuilder.headingCalculator");
fluid.tableOfContents.modelBuilder.headingCalculator.getHeadingLevel = function (that, heading) {
return that.options.levels.indexOf(heading.tagName) + 1;
};
fluid.defaults("fluid.tableOfContents.modelBuilder.headingCalculator", {
gradeNames: ["fluid.component"],
invokers: {
getHeadingLevel: "fluid.tableOfContents.modelBuilder.headingCalculator.getHeadingLevel({that}, {arguments}.0)" // heading
},
levels: ["H1", "H2", "H3", "H4", "H5", "H6"]
});
/*************
* ToC Levels *
**************/
fluid.registerNamespace("fluid.tableOfContents.levels");
/**
* Create an object model based on the type and ID. The object should contain an
* ID that maps the selectors (ie. level1:), and the object should contain a children
* @param {String} type - Accepted values are: level, items
* @param {Integer} ID - The current level which is used here as the ID.
* @return {Object} - An object that models the level based on the type and ID.
*/
fluid.tableOfContents.levels.objModel = function (type, ID) {
var objModel = {
ID: type + ID + ":",
children: []
};
return objModel;
};
/*
* Configure item object when item object has no text, uri, level in it.
* defaults to add a decorator to hide the bullets.
*/
fluid.tableOfContents.levels.handleEmptyItemObj = function (itemObj) {
itemObj.decorators = [{
type: "addClass",
classes: "fl-tableOfContents-hide-bullet"
}];
};
/**
* @param {Object} headingsModel - that.model, the model with all the headings, it should be in the format of {headings: [...]}
* @param {Integer} currentLevel - the current level we want to generate the tree for. default to 1 if not defined.
* @return {Object} - A tree that looks like {children: [{ID: x, subTree:[...]}, ...]}
*/
fluid.tableOfContents.levels.generateTree = function (headingsModel, currentLevel) {
currentLevel = currentLevel || 0;
var levelObj = fluid.tableOfContents.levels.objModel("level", currentLevel);
// FLUID-4352, run generateTree if there are headings in the model.
if (headingsModel.headings.length === 0) {
return currentLevel ? [] : {children: []};
}
// base case: level is 0, returns {children:[generateTree(nextLevel)]}
// purpose is to wrap the first level with a children object.
if (currentLevel === 0) {
var tree = {
children: [
fluid.tableOfContents.levels.generateTree(headingsModel, currentLevel + 1)
]
};
return tree;
}
// Loop through the heading array, which can have multiple headings on the same level
$.each(headingsModel.headings, function (index, model) {
var itemObj = fluid.tableOfContents.levels.objModel("items", currentLevel);
var linkObj = {
ID: "link" + currentLevel,
target: model.url,
linktext: model.text
};
// If level is undefined, then add decorator to it, otherwise add the links to it.
if (!model.level) {
fluid.tableOfContents.levels.handleEmptyItemObj(itemObj);
} else {
itemObj.children.push(linkObj);
}
// If there are sub-headings, go into the next level recursively
if (model.headings) {
itemObj.children.push(fluid.tableOfContents.levels.generateTree(model, currentLevel + 1));
}
// At this point, the itemObj should be in a tree format with sub-headings children
levelObj.children.push(itemObj);
});
return levelObj;
};
/**
* @param {Object} that - The component itself.
* @return {Object} - Returned produceTree must be in {headings: [trees]}
*/
fluid.tableOfContents.levels.produceTree = function (that) {
var tree = fluid.tableOfContents.levels.generateTree(that.model);
// Add the header to the tree
tree.children.push({
ID: "tocHeader",
messagekey: "tocHeader"
});
return tree;
};
fluid.tableOfContents.levels.fetchResources = function (that) {
fluid.fetchResources(that.options.resources, function () {
that.container.append(that.options.resources.template.resourceText);
that.refreshView();
});
};
fluid.defaults("fluid.tableOfContents.levels", {
gradeNames: ["fluid.rendererComponent"],
produceTree: "fluid.tableOfContents.levels.produceTree",
strings: {
tocHeader: "Table of Contents"
},
selectors: {
tocHeader: ".flc-toc-header",
level1: ".flc-toc-levels-level1",
level2: ".flc-toc-levels-level2",
level3: ".flc-toc-levels-level3",
level4: ".flc-toc-levels-level4",
level5: ".flc-toc-levels-level5",
level6: ".flc-toc-levels-level6",
items1: ".flc-toc-levels-items1",
items2: ".flc-toc-levels-items2",
items3: ".flc-toc-levels-items3",
items4: ".flc-toc-levels-items4",
items5: ".flc-toc-levels-items5",
items6: ".flc-toc-levels-items6",
link1: ".flc-toc-levels-link1",
link2: ".flc-toc-levels-link2",
link3: ".flc-toc-levels-link3",
link4: ".flc-toc-levels-link4",
link5: ".flc-toc-levels-link5",
link6: ".flc-toc-levels-link6"
},
repeatingSelectors: ["level1", "level2", "level3", "level4", "level5", "level6", "items1", "items2", "items3", "items4", "items5", "items6"],
model: {
headings: [] // [text: heading, url: linkURL, headings: [ an array of subheadings in the same format]
},
listeners: {
"onCreate.fetchResources": "fluid.tableOfContents.levels.fetchResources"
},
resources: {
template: {
forceCache: true,
url: "../html/TableOfContents.html"
}
},
rendererFnOptions: {
noexpand: true
},
rendererOptions: {
debugMode: false
}
});
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
/*************
* Textfield *
*************/
/*
* A component for controlling a textfield and handling data binding.
* Typically this will be used in conjunction with a UI control widget such as
* button steppers or slider.
*/
fluid.defaults("fluid.textfield", {
gradeNames: ["fluid.viewComponent"],
attrs: {
// Specified by implementor
// ID of an external label to refer to with aria-labelledby
// attribute
// "aria-labelledby": "",
// Should specify either "aria-label" or "aria-labelledby"
// aria-label: "{that}.options.strings.label",
// ID of an element that is controlled by the textfield.
// "aria-controls": ""
},
strings: {
// Specified by implementor
// text of label to apply to both textfield and slider input
// via aria-label attribute
// "label": ""
},
modelListeners: {
value: {
"this": "{that}.container",
"method": "val",
args: ["{change}.value"]
}
},
listeners: {
"onCreate.bindChangeEvt": {
"this": "{that}.container",
"method": "change",
"args": ["{that}.setModel"]
},
"onCreate.initTextfieldAttributes": {
"this": "{that}.container",
method: "attr",
args: ["{that}.options.attrs"]
}
},
invokers: {
setModel: {
changePath: "value",
value: "{arguments}.0.target.value"
}
}
});
/**
* Sets the model value only if the new value is a valid number, and will reset the textfield to the current model
* value otherwise.
*
* @param {Object} that - The component.
* @param {Number} value - The new numerical entry.
* @param {String} path - The path into the model for which the value should be set.
*/
fluid.textfield.setModelRestrictToNumbers = function (that, value, path) {
var isNumber = !isNaN(Number(value));
if (isNumber) {
that.applier.change(path, value);
}
// Set the textfield to the latest valid entry.
// This handles both the cases where an invalid entry was provided, as well as cases where a valid number is
// rounded. In the case of rounded numbers this ensures that entering a number that rounds to the current
// set value, doesn't leave the textfield with the unrounded number present.
that.container.val(that.model.value);
};
/******************************
* TextField Range Controller *
******************************/
/*
* Range Controller is intended to be used as a grade on a fluid.textfield component. It will limit the input
* to be constrained within a given numerical range. This should be paired with configuring the textfield.setModel
* invoker to use fluid.textfield.setModelRestrictToNumbers.
* The Range Controller is useful when combining the textfield with a UI control element such as stepper buttons
* or a slider to enter numerical values.
*/
fluid.defaults("fluid.textfield.rangeController", {
gradeNames: ["fluid.textfield"],
components: {
controller: {
type: "fluid.modelComponent",
options: {
model: {
value: null
},
modelRelay: [{
source: "value",
target: "{fluid.textfield}.model.value",
singleTransform: {
type: "fluid.transforms.numberToString",
// The scale option sets the number of decimal places to round
// the number to. If no scale is specified, the number will not be rounded.
// Scaling is useful to avoid long decimal places due to floating point imprecision.
scale: "{that}.options.scale"
}
}, {
target: "value",
singleTransform: {
type: "fluid.transforms.limitRange",
input: "{that}.model.value",
min: "{that}.model.range.min",
max: "{that}.model.range.max"
}
}]
}
}
},
invokers: {
setModel: {
funcName: "fluid.textfield.setModelRestrictToNumbers",
args: ["{that}", "{arguments}.0.target.value", "value"]
}
}
});
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
/********************
* Textfield Slider *
********************/
fluid.defaults("fluid.textfieldSlider", {
gradeNames: ["fluid.viewComponent"],
components: {
textfield: {
type: "fluid.textfield.rangeController",
container: "{that}.dom.textfield",
options: {
components: {
controller: {
options: {
model: "{textfieldSlider}.model"
}
}
},
attrs: "{textfieldSlider}.options.attrs",
strings: "{textfieldSlider}.options.strings"
}
},
slider: {
type: "fluid.slider",
container: "{textfieldSlider}.dom.slider",
options: {
model: "{textfieldSlider}.model",
attrs: "{textfieldSlider}.options.attrs",
strings: "{textfieldSlider}.options.strings"
}
}
},
selectors: {
textfield: ".flc-textfieldSlider-field",
slider: ".flc-textfieldSlider-slider"
},
styles: {
container: "fl-textfieldSlider fl-focus"
},
model: {
value: null,
step: 1.0,
range: {
min: 0,
max: 100
}
},
modelRelay: {
target: "value",
singleTransform: {
type: "fluid.transforms.limitRange",
input: "{that}.model.value",
min: "{that}.options.range.min",
max: "{that}.options.range.max"
}
},
attrs: {
// Specified by implementor
// ID of an external label to refer to with aria-labelledby
// attribute
// "aria-labelledby": "",
// Should specify either "aria-label" or "aria-labelledby"
// aria-label: "{that}.options.strings.label",
// ID of an element that is controlled by the textfield.
// "aria-controls": ""
},
strings: {
// Specified by implementor
// text of label to apply to both textfield and slider input
// via aria-label attribute
// "label": ""
},
listeners: {
"onCreate.addContainerStyle": {
"this": "{that}.container",
method: "addClass",
args: ["{that}.options.styles.container"]
}
},
distributeOptions: [{
// The scale option sets the number of decimal places to round
// the number to. If no scale is specified, the number will not be rounded.
// Scaling is useful to avoid long decimal places due to floating point imprecision.
source: "{that}.options.scale",
target: "{that > fluid.textfield > controller}.options.scale"
}]
});
fluid.defaults("fluid.slider", {
gradeNames: ["fluid.viewComponent"],
modelRelay: {
target: "value",
singleTransform: {
type: "fluid.transforms.stringToNumber",
input: "{that}.model.stringValue"
}
},
invokers: {
setModel: {
changePath: "stringValue",
value: {
expander: {
"this": "{that}.container",
"method": "val"
}
}
},
updateSliderAttributes: {
"this": "{that}.container",
method: "attr",
args: [{
"min": "{that}.model.range.min",
"max": "{that}.model.range.max",
"step": "{that}.model.step",
"type": "range",
"value": "{that}.model.value",
"aria-labelledby": "{that}.options.attrs.aria-labelledby",
"aria-label": "{that}.options.attrs.aria-label"
}]
}
},
listeners: {
"onCreate.initSliderAttributes": "{that}.updateSliderAttributes",
"onCreate.bindSlideEvt": {
"this": "{that}.container",
"method": "on",
"args": ["input", "{that}.setModel"]
},
"onCreate.bindRangeChangeEvt": {
"this": "{that}.container",
"method": "on",
"args": ["change", "{that}.setModel"]
}
},
modelListeners: {
// If we don't exclude init, the value can get
// set before onCreate.initSliderAttributes
// sets min / max / step, which messes up the
// initial slider rendering
"value": [{
"this": "{that}.container",
"method": "val",
args: ["{change}.value"],
excludeSource: "init"
}],
"range": {
listener: "{that}.updateSliderAttributes",
excludeSource: "init"
},
"step": {
listener: "{that}.updateSliderAttributes",
excludeSource: "init"
}
}
});
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
/*********************
* Textfield Stepper *
*********************/
fluid.defaults("fluid.textfieldStepper", {
gradeNames: ["fluid.viewComponent"],
strings: {
// Specified by implementor
// text of label to apply to both textfield and control
// via aria-label attribute
// "aria-label": "",
increaseLabel: "increment",
decreaseLabel: "decrement"
},
selectors: {
textfield: ".flc-textfieldStepper-field",
focusContainer: ".flc-textfieldStepper-focusContainer",
increaseButton: ".flc-textfieldStepper-increase",
decreaseButton: ".flc-textfieldStepper-decrease"
},
styles: {
container: "fl-textfieldStepper",
focus: "fl-textfieldStepper-focus"
},
components: {
textfield: {
type: "fluid.textfield.rangeController",
container: "{that}.dom.textfield",
options: {
components: {
controller: {
options: {
model: "{textfieldStepper}.model",
modelListeners: {
"range.min": {
"this": "{textfield}.container",
method: "attr",
args: ["aria-valuemin", "{change}.value"]
},
"range.max": {
"this": "{textfield}.container",
method: "attr",
args: ["aria-valuemax", "{change}.value"]
}
}
}
}
},
attrs: "{textfieldStepper}.options.attrs",
strings: "{textfieldStepper}.options.strings",
listeners: {
"onCreate.bindUpArrow": {
listener: "fluid.textfieldStepper.bindKeyEvent",
// up arrow === 38
args: ["{that}.container", "keydown", 38, "{textfieldStepper}.increase"]
},
"onCreate.bindDownArrow": {
listener: "fluid.textfieldStepper.bindKeyEvent",
// down arrow === 40
args: ["{that}.container", "keydown", 40, "{textfieldStepper}.decrease"]
},
"onCreate.addRole": {
"this": "{that}.container",
method: "attr",
args: ["role", "spinbutton"]
}
},
modelListeners: {
"value": {
"this": "{that}.container",
method: "attr",
args: ["aria-valuenow", "{change}.value"]
}
}
}
},
increaseButton: {
type: "fluid.textfieldStepper.button",
container: "{textfieldStepper}.dom.increaseButton",
options: {
strings: {
label: "{textfieldStepper}.options.strings.increaseLabel"
},
listeners: {
"onClick.increase": "{textfieldStepper}.increase"
},
modelRelay: {
target: "disabled",
singleTransform: {
type: "fluid.transforms.binaryOp",
left: "{textfieldStepper}.model.value",
right: "{textfieldStepper}.model.range.max",
operator: ">="
}
}
}
},
decreaseButton: {
type: "fluid.textfieldStepper.button",
container: "{textfieldStepper}.dom.decreaseButton",
options: {
strings: {
label: "{textfieldStepper}.options.strings.decreaseLabel"
},
listeners: {
"onClick.decrease": "{textfieldStepper}.decrease"
},
modelRelay: {
target: "disabled",
singleTransform: {
type: "fluid.transforms.binaryOp",
left: "{textfieldStepper}.model.value",
right: "{textfieldStepper}.model.range.min",
operator: "<="
}
}
}
}
},
invokers: {
increase: {
funcName: "fluid.textfieldStepper.step",
args: ["{that}"]
},
decrease: {
funcName: "fluid.textfieldStepper.step",
args: ["{that}", -1]
},
addFocus: {
"this": "{that}.dom.focusContainer",
method: "addClass",
args: ["{that}.options.styles.focus"]
},
removeFocus: {
"this": "{that}.dom.focusContainer",
method: "removeClass",
args: ["{that}.options.styles.focus"]
}
},
listeners: {
"onCreate.addContainerStyle": {
"this": "{that}.container",
method: "addClass",
args: ["{that}.options.styles.container"]
},
"onCreate.bindFocusin": {
"this": "{that}.container",
method: "on",
args: ["focusin", "{that}.addFocus"]
},
"onCreate.bindFocusout": {
"this": "{that}.container",
method: "on",
args: ["focusout", "{that}.removeFocus"]
}
},
model: {
value: null,
step: 1,
range: {
min: 0,
max: 100
}
},
attrs: {
// Specified by implementor
// ID of an element to use as a label for the stepper
// attribute
// "aria-labelledby": ""
// Should specify either "aria-label" or "aria-labelledby"
// aria-label: "{that}.options.strings.label",
// ID of an element that is controlled by the textfield.
// "aria-controls": ""
},
distributeOptions: [{
// The scale option sets the number of decimal places to round
// the number to. If no scale is specified, the number will not be rounded.
// Scaling is useful to avoid long decimal places due to floating point imprecision.
source: "{that}.options.scale",
target: "{that > fluid.textfield > controller}.options.scale"
}]
});
fluid.textfieldStepper.step = function (that, coefficient) {
coefficient = coefficient || 1;
var newValue = that.model.value + (coefficient * that.model.step);
that.applier.change("value", newValue);
};
fluid.textfieldStepper.bindKeyEvent = function (elm, keyEvent, keyCode, fn) {
$(elm).on(keyEvent, function (event) {
if (event.which === keyCode) {
fn();
event.preventDefault();
}
});
};
fluid.defaults("fluid.textfieldStepper.button", {
gradeNames: ["fluid.viewComponent"],
strings: {
// to be specified by an implementor.
// to provide a label for the button.
// label: ""
},
styles: {
container: "fl-textfieldStepper-button"
},
model: {
disabled: false
},
events: {
onClick: null
},
listeners: {
"onCreate.bindClick": {
"this": "{that}.container",
"method": "click",
"args": "{that}.events.onClick.fire"
},
"onCreate.addLabel": {
"this": "{that}.container",
method: "attr",
args: ["aria-label", "{that}.options.strings.label"]
},
"onCreate.addContainerStyle": {
"this": "{that}.container",
method: "addClass",
args: ["{that}.options.styles.container"]
},
// removing from tab order as keyboard users will
// increment and decrement the stepper using the up/down arrow keys.
"onCreate.removeFromTabOrder": {
"this": "{that}.container",
method: "attr",
args: ["tabindex", "-1"]
}
},
modelListeners: {
disabled: {
"this": "{that}.container",
method: "prop",
args: ["disabled", "{change}.value"]
}
}
});
})(jQuery, fluid_3_0_0);
;
(function () {
var module = {
exports: null
};
/**
* @constructor
* @param {!{patterns: !Object, leftmin: !number, rightmin: !number}} language The language pattern file. Compatible with Hyphenator.js.
*/
function Hypher(language) {
var exceptions = [],
i = 0;
/**
* @type {!Hypher.TrieNode}
*/
this.trie = this.createTrie(language['patterns']);
/**
* @type {!number}
* @const
*/
this.leftMin = language['leftmin'];
/**
* @type {!number}
* @const
*/
this.rightMin = language['rightmin'];
/**
* @type {!Object.<string, !Array.<string>>}
*/
this.exceptions = {};
if (language['exceptions']) {
exceptions = language['exceptions'].split(/,\s?/g);
for (; i < exceptions.length; i += 1) {
this.exceptions[exceptions[i].replace(/\u2027/g, '').toLowerCase()] = new RegExp('(' + exceptions[i].split('\u2027').join(')(') + ')', 'i');
}
}
}
/**
* @typedef {{_points: !Array.<number>}}
*/
Hypher.TrieNode;
/**
* Creates a trie from a language pattern.
* @private
* @param {!Object} patternObject An object with language patterns.
* @return {!Hypher.TrieNode} An object trie.
*/
Hypher.prototype.createTrie = function (patternObject) {
var size = 0,
i = 0,
c = 0,
p = 0,
chars = null,
points = null,
codePoint = null,
t = null,
tree = {
_points: []
},
patterns;
for (size in patternObject) {
if (patternObject.hasOwnProperty(size)) {
patterns = patternObject[size].match(new RegExp('.{1,' + (+size) + '}', 'g'));
for (i = 0; i < patterns.length; i += 1) {
chars = patterns[i].replace(/[0-9]/g, '').split('');
points = patterns[i].split(/\D/);
t = tree;
for (c = 0; c < chars.length; c += 1) {
codePoint = chars[c].charCodeAt(0);
if (!t[codePoint]) {
t[codePoint] = {};
}
t = t[codePoint];
}
t._points = [];
for (p = 0; p < points.length; p += 1) {
t._points[p] = points[p] || 0;
}
}
}
}
return tree;
};
/**
* Hyphenates a text.
*
* @param {!string} str The text to hyphenate.
* @return {!string} The same text with soft hyphens inserted in the right positions.
*/
Hypher.prototype.hyphenateText = function (str, minLength) {
minLength = minLength || 4;
// Regexp("\b", "g") splits on word boundaries,
// compound separators and ZWNJ so we don't need
// any special cases for those characters. Unfortunately
// it does not support unicode word boundaries, so
// we implement it manually.
var words = str.split(/([a-zA-Z0-9_\u0027\u00DF-\u00EA\u00EC-\u00EF\u00F1-\u00F6\u00F8-\u00FD\u0101\u0103\u0105\u0107\u0109\u010D\u010F\u0111\u0113\u0117\u0119\u011B\u011D\u011F\u0123\u0125\u012B\u012F\u0131\u0135\u0137\u013C\u013E\u0142\u0144\u0146\u0148\u0151\u0153\u0155\u0159\u015B\u015D\u015F\u0161\u0165\u016B\u016D\u016F\u0171\u0173\u017A\u017C\u017E\u017F\u0219\u021B\u02BC\u0390\u03AC-\u03CE\u03F2\u0401\u0410-\u044F\u0451\u0454\u0456\u0457\u045E\u0491\u0531-\u0556\u0561-\u0587\u0902\u0903\u0905-\u090B\u090E-\u0910\u0912\u0914-\u0928\u092A-\u0939\u093E-\u0943\u0946-\u0948\u094A-\u094D\u0982\u0983\u0985-\u098B\u098F\u0990\u0994-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BE-\u09C3\u09C7\u09C8\u09CB-\u09CD\u09D7\u0A02\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A14-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A82\u0A83\u0A85-\u0A8B\u0A8F\u0A90\u0A94-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABE-\u0AC3\u0AC7\u0AC8\u0ACB-\u0ACD\u0B02\u0B03\u0B05-\u0B0B\u0B0F\u0B10\u0B14-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3E-\u0B43\u0B47\u0B48\u0B4B-\u0B4D\u0B57\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB5\u0BB7-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C02\u0C03\u0C05-\u0C0B\u0C0E-\u0C10\u0C12\u0C14-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C3E-\u0C43\u0C46-\u0C48\u0C4A-\u0C4D\u0C82\u0C83\u0C85-\u0C8B\u0C8E-\u0C90\u0C92\u0C94-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBE-\u0CC3\u0CC6-\u0CC8\u0CCA-\u0CCD\u0D02\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D28\u0D2A-\u0D39\u0D3E-\u0D43\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D60\u0D61\u0D7A-\u0D7F\u1F00-\u1F07\u1F10-\u1F15\u1F20-\u1F27\u1F30-\u1F37\u1F40-\u1F45\u1F50-\u1F57\u1F60-\u1F67\u1F70-\u1F7D\u1F80-\u1F87\u1F90-\u1F97\u1FA0-\u1FA7\u1FB2-\u1FB4\u1FB6\u1FB7\u1FBD\u1FBF\u1FC2-\u1FC4\u1FC6\u1FC7\u1FD2\u1FD3\u1FD6\u1FD7\u1FE2-\u1FE7\u1FF2-\u1FF4\u1FF6\u1FF7\u200D\u2019]+)/g);
for (var i = 0; i < words.length; i += 1) {
if (words[i].indexOf('/') !== -1) {
// Don't insert a zero width space if the slash is at the beginning or end
// of the text, or right after or before a space.
if (i !== 0 && i !== words.length - 1 && !(/\s+\/|\/\s+/.test(words[i]))) {
words[i] += '\u200B';
}
} else if (words[i].length > minLength) {
words[i] = this.hyphenate(words[i]).join('\u00AD');
}
}
return words.join('');
};
/**
* Hyphenates a word.
*
* @param {!string} word The word to hyphenate
* @return {!Array.<!string>} An array of word fragments indicating valid hyphenation points.
*/
Hypher.prototype.hyphenate = function (word) {
var characters,
characterPoints = [],
originalCharacters,
i,
j,
k,
node,
points = [],
wordLength,
lowerCaseWord = word.toLowerCase(),
nodePoints,
nodePointsLength,
m = Math.max,
trie = this.trie,
result = [''];
if (this.exceptions.hasOwnProperty(lowerCaseWord)) {
return word.match(this.exceptions[lowerCaseWord]).slice(1);
}
if (word.indexOf('\u00AD') !== -1) {
return [word];
}
word = '_' + word + '_';
characters = word.toLowerCase().split('');
originalCharacters = word.split('');
wordLength = characters.length;
for (i = 0; i < wordLength; i += 1) {
points[i] = 0;
characterPoints[i] = characters[i].charCodeAt(0);
}
for (i = 0; i < wordLength; i += 1) {
node = trie;
for (j = i; j < wordLength; j += 1) {
node = node[characterPoints[j]];
if (node) {
nodePoints = node._points;
if (nodePoints) {
for (k = 0, nodePointsLength = nodePoints.length; k < nodePointsLength; k += 1) {
points[i + k] = m(points[i + k], nodePoints[k]);
}
}
} else {
break;
}
}
}
for (i = 1; i < wordLength - 1; i += 1) {
if (i > this.leftMin && i < (wordLength - this.rightMin) && points[i] % 2) {
result.push(originalCharacters[i]);
} else {
result[result.length - 1] += originalCharacters[i];
}
}
return result;
};
module.exports = Hypher;
window['Hypher'] = module.exports;
window['Hypher']['languages'] = {};
}());(function ($) {
$.fn.hyphenate = function (language) {
if (window['Hypher']['languages'][language]) {
return this.each(function () {
var i = 0, len = this.childNodes.length;
for (; i < len; i += 1) {
if (this.childNodes[i].nodeType === 3) {
this.childNodes[i].nodeValue = window['Hypher']['languages'][language].hyphenateText(this.childNodes[i].nodeValue);
}
}
});
}
};
}(jQuery));;
(function(global) {
/**
* Polyfill URLSearchParams
*
* Inspired from : https://github.com/WebReflection/url-search-params/blob/master/src/url-search-params.js
*/
var checkIfIteratorIsSupported = function() {
try {
return !!Symbol.iterator;
} catch (error) {
return false;
}
};
var iteratorSupported = checkIfIteratorIsSupported();
var createIterator = function(items) {
var iterator = {
next: function() {
var value = items.shift();
return { done: value === void 0, value: value };
}
};
if (iteratorSupported) {
iterator[Symbol.iterator] = function() {
return iterator;
};
}
return iterator;
};
/**
* Search param name and values should be encoded according to https://url.spec.whatwg.org/#urlencoded-serializing
* encodeURIComponent() produces the same result except encoding spaces as `%20` instead of `+`.
*/
var serializeParam = function(value) {
return encodeURIComponent(value).replace(/%20/g, '+');
};
var deserializeParam = function(value) {
return decodeURIComponent(value).replace(/\+/g, ' ');
};
var polyfillURLSearchParams = function() {
var URLSearchParams = function(searchString) {
Object.defineProperty(this, '_entries', { writable: true, value: {} });
var typeofSearchString = typeof searchString;
if (typeofSearchString === 'undefined') {
// do nothing
} else if (typeofSearchString === 'string') {
if (searchString !== '') {
this._fromString(searchString);
}
} else if (searchString instanceof URLSearchParams) {
var _this = this;
searchString.forEach(function(value, name) {
_this.append(name, value);
});
} else if ((searchString !== null) && (typeofSearchString === 'object')) {
if (Object.prototype.toString.call(searchString) === '[object Array]') {
for (var i = 0; i < searchString.length; i++) {
var entry = searchString[i];
if ((Object.prototype.toString.call(entry) === '[object Array]') || (entry.length !== 2)) {
this.append(entry[0], entry[1]);
} else {
throw new TypeError('Expected [string, any] as entry at index ' + i + ' of URLSearchParams\'s input');
}
}
} else {
for (var key in searchString) {
if (searchString.hasOwnProperty(key)) {
this.append(key, searchString[key]);
}
}
}
} else {
throw new TypeError('Unsupported input\'s type for URLSearchParams');
}
};
var proto = URLSearchParams.prototype;
proto.append = function(name, value) {
if (name in this._entries) {
this._entries[name].push(String(value));
} else {
this._entries[name] = [String(value)];
}
};
proto.delete = function(name) {
delete this._entries[name];
};
proto.get = function(name) {
return (name in this._entries) ? this._entries[name][0] : null;
};
proto.getAll = function(name) {
return (name in this._entries) ? this._entries[name].slice(0) : [];
};
proto.has = function(name) {
return (name in this._entries);
};
proto.set = function(name, value) {
this._entries[name] = [String(value)];
};
proto.forEach = function(callback, thisArg) {
var entries;
for (var name in this._entries) {
if (this._entries.hasOwnProperty(name)) {
entries = this._entries[name];
for (var i = 0; i < entries.length; i++) {
callback.call(thisArg, entries[i], name, this);
}
}
}
};
proto.keys = function() {
var items = [];
this.forEach(function(value, name) {
items.push(name);
});
return createIterator(items);
};
proto.values = function() {
var items = [];
this.forEach(function(value) {
items.push(value);
});
return createIterator(items);
};
proto.entries = function() {
var items = [];
this.forEach(function(value, name) {
items.push([name, value]);
});
return createIterator(items);
};
if (iteratorSupported) {
proto[Symbol.iterator] = proto.entries;
}
proto.toString = function() {
var searchArray = [];
this.forEach(function(value, name) {
searchArray.push(serializeParam(name) + '=' + serializeParam(value));
});
return searchArray.join('&');
};
global.URLSearchParams = URLSearchParams;
};
if (!('URLSearchParams' in global) || (new URLSearchParams('?a=1').toString() !== 'a=1')) {
polyfillURLSearchParams();
}
var proto = URLSearchParams.prototype;
if (typeof proto.sort !== 'function') {
proto.sort = function() {
var _this = this;
var items = [];
this.forEach(function(value, name) {
items.push([name, value]);
if (!_this._entries) {
_this.delete(name);
}
});
items.sort(function(a, b) {
if (a[0] < b[0]) {
return -1;
} else if (a[0] > b[0]) {
return +1;
} else {
return 0;
}
});
if (_this._entries) { // force reset because IE keeps keys index
_this._entries = {};
}
for (var i = 0; i < items.length; i++) {
this.append(items[i][0], items[i][1]);
}
};
}
if (typeof proto._fromString !== 'function') {
Object.defineProperty(proto, '_fromString', {
enumerable: false,
configurable: false,
writable: false,
value: function(searchString) {
if (this._entries) {
this._entries = {};
} else {
var keys = [];
this.forEach(function(value, name) {
keys.push(name);
});
for (var i = 0; i < keys.length; i++) {
this.delete(keys[i]);
}
}
searchString = searchString.replace(/^\?/, '');
var attributes = searchString.split('&');
var attribute;
for (var i = 0; i < attributes.length; i++) {
attribute = attributes[i].split('=');
this.append(
deserializeParam(attribute[0]),
(attribute.length > 1) ? deserializeParam(attribute[1]) : ''
);
}
}
});
}
// HTMLAnchorElement
})(
(typeof global !== 'undefined') ? global
: ((typeof window !== 'undefined') ? window
: ((typeof self !== 'undefined') ? self : this))
);
(function(global) {
/**
* Polyfill URL
*
* Inspired from : https://github.com/arv/DOM-URL-Polyfill/blob/master/src/url.js
*/
var checkIfURLIsSupported = function() {
try {
var u = new URL('b', 'http://a');
u.pathname = 'c%20d';
return (u.href === 'http://a/c%20d') && u.searchParams;
} catch (e) {
return false;
}
};
var polyfillURL = function() {
var _URL = global.URL;
var URL = function(url, base) {
if (typeof url !== 'string') url = String(url);
// Only create another document if the base is different from current location.
var doc = document, baseElement;
if (base && (global.location === void 0 || base !== global.location.href)) {
doc = document.implementation.createHTMLDocument('');
baseElement = doc.createElement('base');
baseElement.href = base;
doc.head.appendChild(baseElement);
try {
if (baseElement.href.indexOf(base) !== 0) throw new Error(baseElement.href);
} catch (err) {
throw new Error('URL unable to set base ' + base + ' due to ' + err);
}
}
var anchorElement = doc.createElement('a');
anchorElement.href = url;
if (baseElement) {
doc.body.appendChild(anchorElement);
anchorElement.href = anchorElement.href; // force href to refresh
}
if (anchorElement.protocol === ':' || !/:/.test(anchorElement.href)) {
throw new TypeError('Invalid URL');
}
Object.defineProperty(this, '_anchorElement', {
value: anchorElement
});
// create a linked searchParams which reflect its changes on URL
var searchParams = new URLSearchParams(this.search);
var enableSearchUpdate = true;
var enableSearchParamsUpdate = true;
var _this = this;
['append', 'delete', 'set'].forEach(function(methodName) {
var method = searchParams[methodName];
searchParams[methodName] = function() {
method.apply(searchParams, arguments);
if (enableSearchUpdate) {
enableSearchParamsUpdate = false;
_this.search = searchParams.toString();
enableSearchParamsUpdate = true;
}
};
});
Object.defineProperty(this, 'searchParams', {
value: searchParams,
enumerable: true
});
var search = void 0;
Object.defineProperty(this, '_updateSearchParams', {
enumerable: false,
configurable: false,
writable: false,
value: function() {
if (this.search !== search) {
search = this.search;
if (enableSearchParamsUpdate) {
enableSearchUpdate = false;
this.searchParams._fromString(this.search);
enableSearchUpdate = true;
}
}
}
});
};
var proto = URL.prototype;
var linkURLWithAnchorAttribute = function(attributeName) {
Object.defineProperty(proto, attributeName, {
get: function() {
return this._anchorElement[attributeName];
},
set: function(value) {
this._anchorElement[attributeName] = value;
},
enumerable: true
});
};
['hash', 'host', 'hostname', 'port', 'protocol']
.forEach(function(attributeName) {
linkURLWithAnchorAttribute(attributeName);
});
Object.defineProperty(proto, 'search', {
get: function() {
return this._anchorElement['search'];
},
set: function(value) {
this._anchorElement['search'] = value;
this._updateSearchParams();
},
enumerable: true
});
Object.defineProperties(proto, {
'toString': {
get: function() {
var _this = this;
return function() {
return _this.href;
};
}
},
'href': {
get: function() {
return this._anchorElement.href.replace(/\?$/, '');
},
set: function(value) {
this._anchorElement.href = value;
this._updateSearchParams();
},
enumerable: true
},
'pathname': {
get: function() {
return this._anchorElement.pathname.replace(/(^\/?)/, '/');
},
set: function(value) {
this._anchorElement.pathname = value;
},
enumerable: true
},
'origin': {
get: function() {
// get expected port from protocol
var expectedPort = { 'http:': 80, 'https:': 443, 'ftp:': 21 }[this._anchorElement.protocol];
// add port to origin if, expected port is different than actual port
// and it is not empty f.e http://foo:8080
// 8080 != 80 && 8080 != ''
var addPortToOrigin = this._anchorElement.port != expectedPort &&
this._anchorElement.port !== '';
return this._anchorElement.protocol +
'//' +
this._anchorElement.hostname +
(addPortToOrigin ? (':' + this._anchorElement.port) : '');
},
enumerable: true
},
'password': { // TODO
get: function() {
return '';
},
set: function(value) {
},
enumerable: true
},
'username': { // TODO
get: function() {
return '';
},
set: function(value) {
},
enumerable: true
},
});
URL.createObjectURL = function(blob) {
return _URL.createObjectURL.apply(_URL, arguments);
};
URL.revokeObjectURL = function(url) {
return _URL.revokeObjectURL.apply(_URL, arguments);
};
global.URL = URL;
};
if (!checkIfURLIsSupported()) {
polyfillURL();
}
if ((global.location !== void 0) && !('origin' in global.location)) {
var getOrigin = function() {
return global.location.protocol + '//' + global.location.hostname + (global.location.port ? (':' + global.location.port) : '');
};
try {
Object.defineProperty(global.location, 'origin', {
get: getOrigin,
enumerable: true
});
} catch (e) {
setInterval(function() {
global.location.origin = getOrigin();
}, 100);
}
}
})(
(typeof global !== 'undefined') ? global
: ((typeof window !== 'undefined') ? window
: ((typeof self !== 'undefined') ? self : this))
);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
fluid.registerNamespace("fluid.contextAware");
fluid.defaults("fluid.contextAware.marker", {
gradeNames: ["fluid.component"]
});
// unsupported, NON-API function
fluid.contextAware.makeCheckMarkers = function (checks, path, instantiator) {
fluid.each(checks, function (value, markerTypeName) {
fluid.constructSingle(path, {
type: markerTypeName,
gradeNames: "fluid.contextAware.marker",
value: value
}, instantiator);
});
};
/** Peforms the computation for `fluid.contextAware.makeChecks` and returns a structure suitable for being sent to `fluid.contextAware.makeCheckMarkers` -
*
* @return A hash of marker type names to grade names - this can be sent to fluid.contextAware.makeCheckMarkers
*/
// unsupported, NON-API function
fluid.contextAware.performChecks = function (checkHash) {
return fluid.transform(checkHash, function (checkRecord) {
if (typeof(checkRecord) === "function") {
checkRecord = {func: checkRecord};
} else if (typeof(checkRecord) === "string") {
checkRecord = {funcName: checkRecord};
}
if (fluid.isPrimitive(checkRecord)) {
return checkRecord;
} else if ("value" in checkRecord) {
return checkRecord.value;
} else if ("func" in checkRecord) {
return checkRecord.func();
} else if ("funcName" in checkRecord) {
return fluid.invokeGlobalFunction(checkRecord.funcName);
} else {
fluid.fail("Error in contextAwareness check record ", checkRecord, " - must contain an entry with name value, func, or funcName");
}
});
};
/**
* Takes an object whose keys are check context names and whose values are check records, designating a collection of context markers which might be registered at a location
* in the component tree.
*
* @param {Object} checkHash - The keys in this structure are the context names to be supplied if the check passes, and the values are check records.
* A check record contains:
* ONE OF:
* value {Any} [optional] A literal value name to be attached to the context
* func {Function} [optional] A zero-arg function to be called to compute the value
* funcName {String} [optional] The name of a zero-arg global function which will compute the value
* If the check record consists of a Number or Boolean, it is assumed to be the value given to "value".
* @param {String|Array} [path] - [optional] The path in the component tree at which the check markers are to be registered. If omitted, "" is assumed
* @param {Instantiator} [instantiator] - [optional] The instantiator holding the component tree which will receive the markers. If omitted, use `fluid.globalInstantiator`.
*/
fluid.contextAware.makeChecks = function (checkHash, path, instantiator) {
var checkOptions = fluid.contextAware.performChecks(checkHash);
fluid.contextAware.makeCheckMarkers(checkOptions, path, instantiator);
};
/**
* Forgets a check made at a particular level of the component tree.
*
* @param {String[]} markerNames - The marker typeNames whose check values are to be forgotten.
* @param {String|String[]} [path] - [optional] The path in the component tree at which the check markers are to be removed. If omitted, "" is assumed
* @param {Instantiator} [instantiator] - [optional] The instantiator holding the component tree the markers are to be removed from. If omitted, use `fluid.globalInstantiator`.
*/
fluid.contextAware.forgetChecks = function (markerNames, path, instantiator) {
instantiator = instantiator || fluid.globalInstantiator;
path = path || [];
var markerArray = fluid.makeArray(markerNames);
fluid.each(markerArray, function (markerName) {
var memberName = fluid.typeNameToMemberName(markerName);
var segs = fluid.model.parseToSegments(path, instantiator.parseEL, true);
segs.push(memberName);
fluid.destroy(segs, instantiator);
});
};
/** A grade to be given to a component which requires context-aware adaptation.
* This grade consumes configuration held in the block named "contextAwareness", which is an object whose keys are check namespaces and whose values hold
* sequences of "checks" to be made in the component tree above the component. The value searched by
* each check is encoded as the element named `contextValue` - this either represents an IoC reference to a component
* or a particular value held at the component. If this reference has no path component, the path ".options.value" will be assumed.
* These checks seek contexts which
* have been previously registered using fluid.contextAware.makeChecks. The first context which matches
* with a value of `true` terminates the search, and returns by applying the grade names held in `gradeNames` to the current component.
* If no check matches, the grades held in `defaultGradeNames` will be applied.
*/
fluid.defaults("fluid.contextAware", {
gradeNames: ["{that}.check"],
mergePolicy: {
contextAwareness: "noexpand"
},
contextAwareness: {
// Hash of names (check namespaces) to records: {
// checks: {}, // Hash of check namespace to: {
// contextValue: IoCExpression testing value in environment,
// gradeNames: gradeNames which will be output,
// priority: String/Number for priority of check [optional]
// equals: Value to be compared to contextValue [optional - default is `true`]
// defaultGradeNames: // String or String[] holding default gradeNames which will be output if no check matches [optional]
// priority: // Number or String encoding priority relative to other records (same format as with event listeners) [optional]
// }
},
invokers: {
check: {
funcName: "fluid.contextAware.check",
args: ["{that}", "{that}.options.contextAwareness"]
}
}
});
fluid.contextAware.getCheckValue = function (that, reference) {
// cf. core of distributeOptions!
var targetRef = fluid.parseContextReference(reference);
var targetComponent = fluid.resolveContext(targetRef.context, that);
var path = targetRef.path || ["options", "value"];
var value = fluid.getForComponent(targetComponent, path);
return value;
};
// unsupported, NON-API function
fluid.contextAware.checkOne = function (that, contextAwareRecord) {
if (contextAwareRecord.checks && contextAwareRecord.checks.contextValue) {
fluid.fail("Nesting error in contextAwareness record ", contextAwareRecord, " - the \"checks\" entry must contain a hash and not a contextValue/gradeNames record at top level");
}
var checkList = fluid.parsePriorityRecords(contextAwareRecord.checks, "contextAwareness checkRecord");
return fluid.find(checkList, function (check) {
if (!check.contextValue) {
fluid.fail("Cannot perform check for contextAwareness record ", check, " without a valid field named \"contextValue\"");
}
var value = fluid.contextAware.getCheckValue(that, check.contextValue);
if (check.equals === undefined ? value : value === check.equals) {
return check.gradeNames;
}
}, contextAwareRecord.defaultGradeNames);
};
// unsupported, NON-API function
fluid.contextAware.check = function (that, contextAwarenessOptions) {
var gradeNames = [];
var contextAwareList = fluid.parsePriorityRecords(contextAwarenessOptions, "contextAwareness adaptationRecord");
fluid.each(contextAwareList, function (record) {
var matched = fluid.contextAware.checkOne(that, record);
gradeNames = gradeNames.concat(fluid.makeArray(matched));
});
return gradeNames;
};
/** Given a set of options, broadcast an adaptation to all instances of a particular component in a particular context. ("new demands blocks").
* This has the effect of fabricating a grade with a particular name with an options distribution to `{/ typeName}` for the required component,
* and then constructing a single well-known instance of it.
* Options layout:
* distributionName {String} A grade name - the name to be given to the fabricated grade
* targetName {String} A grade name - the name of the grade to receive the adaptation
* adaptationName {String} the name of the contextAwareness record to receive the record - this will be a simple string
* checkName {String} the name of the check within the contextAwareness record to receive the record - this will be a simple string
* record {Object} the record to be broadcast into contextAwareness - should contain entries
* contextValue {IoC expression} the context value to be checked to activate the adaptation
* gradeNames {String/String[]} the grade names to be supplied to the adapting target (matching advisedName)
*
* @param {Object} options - The options to use when making an adaptation. See above for supported sub-options.
*/
fluid.contextAware.makeAdaptation = function (options) {
fluid.expect("fluid.contextAware.makeAdaptation", options, ["distributionName", "targetName", "adaptationName", "checkName", "record"]);
fluid.defaults(options.distributionName, {
gradeNames: ["fluid.component"],
distributeOptions: {
target: "{/ " + options.targetName + "}.options.contextAwareness." + options.adaptationName + ".checks." + options.checkName,
record: options.record
}
});
fluid.constructSingle([], options.distributionName);
};
// Context awareness for the browser environment
fluid.contextAware.isBrowser = function () {
return typeof(window) !== "undefined" && !!window.document;
};
fluid.contextAware.makeChecks({
"fluid.browser": {
funcName: "fluid.contextAware.isBrowser"
}
});
// Context awareness for the reported browser platform name (operating system)
fluid.registerNamespace("fluid.contextAware.browser");
fluid.contextAware.browser.getPlatformName = function () {
return typeof(navigator) !== "undefined" && navigator.platform ? navigator.platform : undefined;
};
// Context awareness for the reported user agent name
fluid.contextAware.browser.getUserAgent = function () {
return typeof(navigator) !== "undefined" && navigator.userAgent ? navigator.userAgent : undefined;
};
fluid.contextAware.makeChecks({
"fluid.browser.platformName": {
funcName: "fluid.contextAware.browser.getPlatformName"
},
"fluid.browser.userAgent": {
funcName: "fluid.contextAware.browser.getUserAgent"
}
});
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
fluid.registerNamespace("fluid.enhance");
/**********************************************************
* This code runs immediately upon inclusion of this file *
**********************************************************/
// Use JavaScript to hide any markup that is specifically in place for cases when JavaScript is off.
// Note: the use of fl-ProgEnhance-basic is deprecated, and replaced by fl-progEnhance-basic.
// It is included here for backward compatibility only.
// Distinguish the standalone jQuery from the real one so that this can be included in IoC standalone tests
if (fluid.contextAware.isBrowser() && $.fn) {
$("head").append("<style type='text/css'>.fl-progEnhance-basic, .fl-ProgEnhance-basic { display: none; } .fl-progEnhance-enhanced, .fl-ProgEnhance-enhanced { display: block; }</style>");
}
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
/** URL utilities salvaged from kettle - these should go into core framework **/
fluid.registerNamespace("fluid.url");
fluid.url.generateDepth = function (depth) {
return fluid.generate(depth, "../").join("");
};
fluid.url.parsePathInfo = function (pathInfo) {
var togo = {};
var segs = pathInfo.split("/");
if (segs.length > 0) {
var top = segs.length - 1;
var dotpos = segs[top].indexOf(".");
if (dotpos !== -1) {
togo.extension = segs[top].substring(dotpos + 1);
segs[top] = segs[top].substring(0, dotpos);
}
}
togo.pathInfo = segs;
return togo;
};
fluid.url.parsePathInfoTrim = function (pathInfo) {
var togo = fluid.url.parsePathInfo(pathInfo);
if (togo.pathInfo[togo.pathInfo.length - 1] === "") {
togo.pathInfo.length--;
}
return togo;
};
/* Collapse the array of segments into a URL path, starting at the specified
* segment index - this will not terminate with a slash, unless the final segment
* is the empty string
*/
fluid.url.collapseSegs = function (segs, from, to) {
var togo = "";
if (from === undefined) {
from = 0;
}
if (to === undefined) {
to = segs.length;
}
for (var i = from; i < to - 1; ++i) {
togo += segs[i] + "/";
}
if (to > from) { // TODO: bug in Kettle version
togo += segs[to - 1];
}
return togo;
};
fluid.url.makeRelPath = function (parsed, index) {
var togo = fluid.kettle.collapseSegs(parsed.pathInfo, index);
if (parsed.extension) {
togo += "." + parsed.extension;
}
return togo;
};
/* Canonicalise IN PLACE the supplied segment array derived from parsing a
* pathInfo structure. Warning, this destructively modifies the argument.
*/
fluid.url.cononocolosePath = function (pathInfo) {
var consume = 0;
for (var i = 0; i < pathInfo.length; ++i) {
if (pathInfo[i] === "..") {
++consume;
}
else if (consume !== 0) {
pathInfo.splice(i - consume * 2, consume * 2);
i -= consume * 2;
consume = 0;
}
}
return pathInfo;
};
// parseUri 1.2.2
// (c) Steven Levithan <stevenlevithan.com>
// MIT License
fluid.url.parseUri = function (str) {
var o = fluid.url.parseUri.options,
m = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
uri = {},
i = 14;
while (i--) { uri[o.key[i]] = m[i] || ""; }
uri[o.q.name] = {};
uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
if ($1) { uri[o.q.name][$1] = $2; }
});
return uri;
};
fluid.url.parseUri.options = {
strictMode: true,
key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
q: {
name: "queryKey",
parser: /(?:^|&)([^&=]*)=?([^&]*)/g
},
parser: {
strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
}
};
fluid.url.parseSegs = function (url) {
var parsed = fluid.url.parseUri(url);
var parsedSegs = fluid.url.parsePathInfoTrim(parsed.directory);
return parsedSegs.pathInfo;
};
fluid.url.isAbsoluteUrl = function (url) {
var parseRel = fluid.url.parseUri(url);
return (parseRel.host || parseRel.protocol || parseRel.directory.charAt(0) === "/");
};
fluid.url.computeRelativePrefix = function (outerLocation, iframeLocation, relPath) {
if (fluid.url.isAbsoluteUrl(relPath)) {
return relPath;
}
var relSegs = fluid.url.parsePathInfo(relPath).pathInfo;
var parsedOuter = fluid.url.parseSegs(outerLocation);
var parsedRel = parsedOuter.concat(relSegs);
fluid.url.cononocolosePath(parsedRel);
var parsedInner = fluid.url.parseSegs(iframeLocation);
var seg = 0;
for (; seg < parsedRel.length; ++seg) {
if (parsedRel[seg] !== parsedInner[seg]) { break; }
}
var excess = parsedInner.length - seg;
var back = fluid.url.generateDepth(excess);
var front = fluid.url.collapseSegs(parsedRel, seg);
return back + front;
};
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
fluid.defaults("fluid.prefs.store", {
gradeNames: ["fluid.dataSource", "fluid.contextAware"],
contextAwareness: {
strategy: {
defaultGradeNames: "fluid.prefs.cookieStore"
}
}
});
fluid.prefs.store.decodeURIComponent = function (payload) {
if (typeof payload === "string") {
return decodeURIComponent(payload);
}
};
fluid.prefs.store.encodeURIComponent = function (payload) {
if (typeof payload === "string") {
return encodeURIComponent(payload);
}
};
/****************
* Cookie Store *
****************/
/**
* SettingsStore Subcomponent that uses a cookie for persistence.
* @param options {Object}
*/
fluid.defaults("fluid.prefs.cookieStore", {
gradeNames: ["fluid.dataSource"],
cookie: {
name: "fluid-ui-settings",
path: "/",
expires: ""
},
listeners: {
"onRead.impl": {
listener: "fluid.prefs.cookieStore.getCookie",
args: ["{arguments}.1"]
},
"onRead.decodeURI": {
listener: "fluid.prefs.store.decodeURIComponent",
priority: "before:encoding"
}
},
invokers: {
get: {
args: ["{that}", "{arguments}.0", "{that}.options.cookie"] // directModel, options/callback
}
}
});
fluid.defaults("fluid.prefs.cookieStore.writable", {
gradeNames: ["fluid.dataSource.writable"],
listeners: {
"onWrite.encodeURI": {
func: "fluid.prefs.store.encodeURIComponent",
priority: "before:impl"
},
"onWrite.impl": {
listener: "fluid.prefs.cookieStore.writeCookie"
},
"onWriteResponse.decodeURI": {
listener: "fluid.prefs.store.decodeURIComponent",
priority: "before:encoding"
}
},
invokers: {
set: {
args: ["{that}", "{arguments}.0", "{arguments}.1", "{that}.options.cookie"] // directModel, model, options/callback
}
}
});
fluid.makeGradeLinkage("fluid.prefs.cookieStore.linkage", ["fluid.dataSource.writable", "fluid.prefs.cookieStore"], "fluid.prefs.cookieStore.writable");
/*
* Retrieve and return the value of the cookie
*/
fluid.prefs.cookieStore.getCookie = function (options) {
var cookieName = fluid.get(options, ["directModel", "cookieName"]) || options.name;
var cookie = document.cookie;
if (cookie.length <= 0) {
return;
}
var cookiePrefix = cookieName + "=";
var startIndex = cookie.indexOf(cookiePrefix);
if (startIndex < 0) {
return;
}
startIndex = startIndex + cookiePrefix.length;
var endIndex = cookie.indexOf(";", startIndex);
if (endIndex < startIndex) {
endIndex = cookie.length;
}
return cookie.substring(startIndex, endIndex);
};
/**
* Assembles the cookie string
* @param {String} cookieName - name of the cookie
* @param {String} data - the serialized data to be stored in the cookie
* @param {Object} options - settings
* @return {String} - A string representing the assembled cookie.
*/
fluid.prefs.cookieStore.assembleCookie = function (cookieName, data, options) {
options = options || {};
var cookieStr = cookieName + "=" + data;
if (options.expires) {
cookieStr += "; expires=" + options.expires;
}
if (options.path) {
cookieStr += "; path=" + options.path;
}
return cookieStr;
};
/**
* Saves the settings into a cookie
* @param {Object} payload - the serialized data to write to the cookie
* @param {Object} options - settings
* @return {Object} - The original payload.
*/
fluid.prefs.cookieStore.writeCookie = function (payload, options) {
var cookieName = fluid.get(options, ["directModel", "cookieName"]) || options.name;
var cookieStr = fluid.prefs.cookieStore.assembleCookie(cookieName, payload, options);
document.cookie = cookieStr;
return payload;
};
/**************
* Temp Store *
**************/
fluid.defaults("fluid.dataSource.encoding.model", {
gradeNames: "fluid.component",
invokers: {
parse: "fluid.identity",
render: "fluid.identity"
},
contentType: "application/json"
});
/**
* SettingsStore mock that doesn't do persistence.
* @param options {Object}
*/
fluid.defaults("fluid.prefs.tempStore", {
gradeNames: ["fluid.dataSource", "fluid.modelComponent"],
components: {
encoding: {
type: "fluid.dataSource.encoding.model"
}
},
listeners: {
"onRead.impl": {
listener: "fluid.identity",
args: ["{that}.model"]
}
}
});
fluid.defaults("fluid.prefs.tempStore.writable", {
gradeNames: ["fluid.dataSource.writable", "fluid.modelComponent"],
components: {
encoding: {
type: "fluid.dataSource.encoding.model"
}
},
listeners: {
"onWrite.impl": {
listener: "fluid.prefs.tempStore.write",
args: ["{that}", "{arguments}.0", "{arguments}.1"]
}
}
});
fluid.prefs.tempStore.write = function (that, settings) {
var transaction = that.applier.initiate();
transaction.fireChangeRequest({path: "", type: "DELETE"});
transaction.change("", settings);
transaction.commit();
return that.model;
};
fluid.makeGradeLinkage("fluid.prefs.tempStore.linkage", ["fluid.dataSource.writable", "fluid.prefs.tempStore"], "fluid.prefs.tempStore.writable");
fluid.defaults("fluid.prefs.globalSettingsStore", {
gradeNames: ["fluid.component"],
components: {
settingsStore: {
type: "fluid.prefs.store",
options: {
gradeNames: ["fluid.resolveRootSingle", "fluid.dataSource.writable"],
singleRootType: "fluid.prefs.store"
}
}
}
});
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
/*******************************************************************************
* Root Model *
* *
* Holds the default values for enactors and panel model values *
*******************************************************************************/
fluid.defaults("fluid.prefs.initialModel", {
gradeNames: ["fluid.component"],
members: {
// TODO: This information is supposed to be generated from the JSON
// schema describing various preferences. For now it's kept in top
// level prefsEditor to avoid further duplication.
initialModel: {
preferences: {} // To keep initial preferences
}
}
});
/***********************************************
* UI Enhancer *
* *
* Transforms the page based on user settings. *
***********************************************/
fluid.defaults("fluid.uiEnhancer", {
gradeNames: ["fluid.viewComponent"],
defaultLocale: "en",
invokers: {
updateModel: {
func: "{that}.applier.change",
args: ["", "{arguments}.0"]
}
},
userGrades: "@expand:fluid.prefs.filterEnhancerGrades({that}.options.gradeNames)",
distributeOptions: {
"uiEnhancer.messageLoader.defaultLocale": {
source: "{that}.options.defaultLocale",
target: "{that messageLoader}.options.defaultLocale"
},
// TODO: This needs to be improved as it is static and should be dynamic. Unfortunately the resource loader
// accepts the locale as an option instead of a model value.
"uiEnhancer.messageLoader.locale": {
source: "{that}.options.locale",
target: "{that messageLoader}.model.locale"
}
}
});
// Make this a standalone grade since options merging can't see 2 levels deep into merging
// trees and will currently trash "gradeNames" for 2nd level nested components!
fluid.defaults("fluid.uiEnhancer.root", {
gradeNames: ["fluid.uiEnhancer", "fluid.resolveRootSingle"],
singleRootType: "fluid.uiEnhancer"
});
fluid.uiEnhancer.ignorableGrades = ["fluid.uiEnhancer", "fluid.uiEnhancer.root", "fluid.resolveRoot", "fluid.resolveRootSingle"];
// These function is necessary so that we can "clone" a UIEnhancer (e.g. one in an iframe) from another.
// This reflects a long-standing mistake in UIEnhancer design - we should separate the logic in an enhancer
// from a particular binding onto a container.
fluid.prefs.filterEnhancerGrades = function (gradeNames) {
return fluid.remove_if(fluid.makeArray(gradeNames), function (gradeName) {
return fluid.frameworkGrades.indexOf(gradeName) !== -1 || fluid.uiEnhancer.ignorableGrades.indexOf(gradeName) !== -1;
});
};
// This just the options that we are clear safely represent user options - naturally this all has
// to go when we refactor UIEnhancer
fluid.prefs.filterEnhancerOptions = function (options) {
return fluid.filterKeys(options, ["classnameMap", "fontSizeMap", "tocTemplate", "tocMessage", "components"]);
};
/********************************************************************************
* PageEnhancer *
* *
* A UIEnhancer wrapper that concerns itself with the entire page. *
* *
* "originalEnhancerOptions" is a grade component to keep track of the original *
* uiEnhancer user options *
********************************************************************************/
// TODO: Both the pageEnhancer and the uiEnhancer need to be available separately - some
// references to "{uiEnhancer}" are present in prefsEditorConnections, whilst other
// sites refer to "{pageEnhancer}". The fact that uiEnhancer requires "body" prevents it
// being top-level until we have the options flattening revolution. Also one day we want
// to make good of advertising an unmerged instance of the "originalEnhancerOptions"
fluid.defaults("fluid.pageEnhancer", {
gradeNames: ["fluid.component", "fluid.originalEnhancerOptions",
"fluid.prefs.initialModel", "fluid.prefs.settingsGetter",
"fluid.resolveRootSingle"],
distributeOptions: {
"pageEnhancer.uiEnhancer": {
source: "{that}.options.uiEnhancer",
target: "{that > uiEnhancer}.options"
}
},
singleRootType: "fluid.pageEnhancer",
components: {
uiEnhancer: {
type: "fluid.uiEnhancer.root",
container: "body"
}
},
originalUserOptions: "@expand:fluid.prefs.filterEnhancerOptions({uiEnhancer}.options)",
listeners: {
"onCreate.initModel": "fluid.pageEnhancer.init"
}
});
fluid.pageEnhancer.init = function (that) {
var fetchPromise = that.getSettings();
fetchPromise.then(function (fetchedSettings) {
that.uiEnhancer.updateModel(fluid.get(fetchedSettings, "preferences"));
});
};
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
/*****************************
* Preferences Editor Loader *
*****************************/
/**
* An Preferences Editor top-level component that reflects the collaboration between prefsEditor, templateLoader and messageLoader.
* This component is the only Preferences Editor component that is intended to be called by the outside world.
*
* @param options {Object}
*/
fluid.defaults("fluid.prefs.prefsEditorLoader", {
gradeNames: ["fluid.prefs.settingsGetter", "fluid.prefs.initialModel", "fluid.viewComponent"],
defaultLocale: "en",
components: {
prefsEditor: {
priority: "last",
type: "fluid.prefs.prefsEditor",
createOnEvent: "onCreatePrefsEditorReady",
options: {
members: {
initialModel: "{prefsEditorLoader}.initialModel"
},
invokers: {
getSettings: "{prefsEditorLoader}.getSettings"
},
listeners: {
"onReady.boil": {
listener: "{prefsEditorLoader}.events.onReady",
args: ["{prefsEditorLoader}"]
}
}
}
},
templateLoader: {
type: "fluid.resourceLoader",
options: {
events: {
onResourcesLoaded: "{prefsEditorLoader}.events.onPrefsEditorTemplatesLoaded"
}
}
},
messageLoader: {
type: "fluid.resourceLoader",
createOnEvent: "afterInitialSettingsFetched",
options: {
defaultLocale: "{prefsEditorLoader}.options.defaultLocale",
locale: "{prefsEditorLoader}.settings.preferences.locale",
resourceOptions: {
dataType: "json"
},
events: {
onResourcesLoaded: "{prefsEditorLoader}.events.onPrefsEditorMessagesLoaded"
}
}
}
},
listeners: {
"onCreate.getInitialSettings": {
listener: "fluid.prefs.prefsEditorLoader.getInitialSettings",
args: ["{that}"]
}
},
events: {
afterInitialSettingsFetched: null,
onPrefsEditorTemplatesLoaded: null,
onPrefsEditorMessagesLoaded: null,
onCreatePrefsEditorReady: {
events: {
templateLoaded: "onPrefsEditorTemplatesLoaded",
prefsEditorMessagesLoaded: "onPrefsEditorMessagesLoaded"
}
},
onReady: null
},
distributeOptions: {
"prefsEditorLoader.templateLoader": {
source: "{that}.options.templateLoader",
removeSource: true,
target: "{that > templateLoader}.options"
},
"prefsEditorLoader.templateLoader.terms": {
source: "{that}.options.terms",
target: "{that > templateLoader}.options.terms"
},
"prefsEditorLoader.messageLoader": {
source: "{that}.options.messageLoader",
removeSource: true,
target: "{that > messageLoader}.options"
},
"prefsEditorLoader.messageLoader.terms": {
source: "{that}.options.terms",
target: "{that > messageLoader}.options.terms"
},
"prefsEditorLoader.prefsEditor": {
source: "{that}.options.prefsEditor",
removeSource: true,
target: "{that > prefsEditor}.options"
}
}
});
fluid.prefs.prefsEditorLoader.getInitialSettings = function (that) {
var promise = fluid.promise();
var fetchPromise = that.getSettings();
fetchPromise.then(function (savedSettings) {
that.settings = $.extend(true, {}, that.initialModel, savedSettings);
that.events.afterInitialSettingsFetched.fire(that.settings);
}, function (error) {
fluid.log(fluid.logLevel.WARN, error);
that.settings = that.initialModel;
that.events.afterInitialSettingsFetched.fire(that.settings);
});
fluid.promise.follow(fetchPromise, promise);
return promise;
};
// TODO: This mixin grade appears to be supplied manually by various test cases but no longer appears in
// the main configuration. We should remove the need for users to supply this - also the use of "defaultPanels" in fact
// refers to "starter panels"
fluid.defaults("fluid.prefs.transformDefaultPanelsOptions", {
// Do not supply "fluid.prefs.inline" here, since when this is used as a mixin for separatedPanel, it ends up displacing the
// more refined type of the prefsEditorLoader
gradeNames: ["fluid.viewComponent"],
distributeOptions: {
"transformDefaultPanelsOptions.textSize": {
source: "{that}.options.textSize",
removeSource: true,
target: "{that textSize}.options"
},
"transformDefaultPanelsOptions.lineSpace": {
source: "{that}.options.lineSpace",
removeSource: true,
target: "{that lineSpace}.options"
},
"transformDefaultPanelsOptions.textFont": {
source: "{that}.options.textFont",
removeSource: true,
target: "{that textFont}.options"
},
"transformDefaultPanelsOptions.contrast": {
source: "{that}.options.contrast",
removeSource: true,
target: "{that contrast}.options"
},
"transformDefaultPanelsOptions.layoutControls": {
source: "{that}.options.layoutControls",
removeSource: true,
target: "{that layoutControls}.options"
},
"transformDefaultPanelsOptions.enhanceInputs": {
source: "{that}.options.enhanceInputs",
removeSource: true,
target: "{that enhanceInputs}.options"
}
}
});
/**********************
* Preferences Editor *
**********************/
fluid.defaults("fluid.prefs.settingsGetter", {
gradeNames: ["fluid.component"],
members: {
getSettings: "{fluid.prefs.store}.get"
}
});
fluid.defaults("fluid.prefs.settingsSetter", {
gradeNames: ["fluid.component"],
invokers: {
setSettings: {
funcName: "fluid.prefs.settingsSetter.setSettings",
args: ["{arguments}.0", "{arguments}.1", "{fluid.prefs.store}.set"]
}
}
});
fluid.prefs.settingsSetter.setSettings = function (model, directModel, set) {
var userSettings = fluid.copy(model);
return set(directModel, userSettings);
};
fluid.defaults("fluid.prefs.uiEnhancerRelay", {
gradeNames: ["fluid.modelComponent"],
listeners: {
"onCreate.addListener": "{that}.addListener",
"onDestroy.removeListener": "{that}.removeListener"
},
events: {
updateEnhancerModel: "{fluid.prefs.prefsEditor}.events.onUpdateEnhancerModel"
},
invokers: {
addListener: {
funcName: "fluid.prefs.uiEnhancerRelay.addListener",
args: ["{that}.events.updateEnhancerModel", "{that}.updateEnhancerModel"]
},
removeListener: {
funcName: "fluid.prefs.uiEnhancerRelay.removeListener",
args: ["{that}.events.updateEnhancerModel", "{that}.updateEnhancerModel"]
},
updateEnhancerModel: {
funcName: "fluid.prefs.uiEnhancerRelay.updateEnhancerModel",
args: ["{uiEnhancer}", "{fluid.prefs.prefsEditor}.model.preferences"]
}
}
});
fluid.prefs.uiEnhancerRelay.addListener = function (modelChanged, listener) {
modelChanged.addListener(listener);
};
fluid.prefs.uiEnhancerRelay.removeListener = function (modelChanged, listener) {
modelChanged.removeListener(listener);
};
fluid.prefs.uiEnhancerRelay.updateEnhancerModel = function (uiEnhancer, newModel) {
uiEnhancer.updateModel(newModel);
};
/**
* A component that works in conjunction with the UI Enhancer component
* to allow users to set personal user interface preferences. The Preferences Editor component provides a user
* interface for setting and saving personal preferences, and the UI Enhancer component carries out the
* work of applying those preferences to the user interface.
*
* @param container {Object}
* @param options {Object}
*/
fluid.defaults("fluid.prefs.prefsEditor", {
gradeNames: ["fluid.prefs.settingsGetter", "fluid.prefs.settingsSetter", "fluid.prefs.initialModel", "fluid.remoteModelComponent", "fluid.viewComponent"],
invokers: {
/**
* Updates the change applier and fires modelChanged on subcomponent fluid.prefs.controls
*
* @param newModel {Object}
* @param source {Object}
*/
fetchImpl: {
funcName: "fluid.prefs.prefsEditor.fetchImpl",
args: ["{that}"]
},
writeImpl: {
funcName: "fluid.prefs.prefsEditor.writeImpl",
args: ["{that}", "{arguments}.0"]
},
applyChanges: {
funcName: "fluid.prefs.prefsEditor.applyChanges",
args: ["{that}"]
},
save: {
funcName: "fluid.prefs.prefsEditor.save",
args: ["{that}"]
},
saveAndApply: {
funcName: "fluid.prefs.prefsEditor.saveAndApply",
args: ["{that}"]
},
reset: {
funcName: "fluid.prefs.prefsEditor.reset",
args: ["{that}"]
},
cancel: {
funcName: "fluid.prefs.prefsEditor.cancel",
args: ["{that}"]
}
},
selectors: {
panels: ".flc-prefsEditor-panel",
cancel: ".flc-prefsEditor-cancel",
reset: ".flc-prefsEditor-reset",
save: ".flc-prefsEditor-save",
previewFrame : ".flc-prefsEditor-preview-frame"
},
events: {
onSave: null,
onCancel: null,
beforeReset: null,
afterReset: null,
onAutoSave: null,
modelChanged: null,
onPrefsEditorRefresh: null,
onUpdateEnhancerModel: null,
onPrefsEditorMarkupReady: null,
onReady: null
},
listeners: {
"onCreate.init": "fluid.prefs.prefsEditor.init",
"onAutoSave.save": "{that}.save"
},
model: {
local: {
preferences: "{that}.model.preferences"
}
},
modelListeners: {
"preferences": [{
listener: "fluid.prefs.prefsEditor.handleAutoSave",
args: ["{that}"],
namespace: "autoSave",
excludeSource: ["init"]
}, {
listener: "{that}.events.modelChanged.fire",
args: ["{change}.value"],
namespace: "modelChange"
}]
},
resources: {
template: "{templateLoader}.resources.prefsEditor"
},
autoSave: false
});
/*
* Refresh PrefsEditor
*/
fluid.prefs.prefsEditor.applyChanges = function (that) {
that.events.onUpdateEnhancerModel.fire();
};
fluid.prefs.prefsEditor.fetchImpl = function (that) {
var promise = fluid.promise(),
fetchPromise = that.getSettings();
fetchPromise.then(function (savedModel) {
var completeModel = $.extend(true, {}, that.initialModel, savedModel);
promise.resolve(completeModel);
}, promise.reject);
return promise;
};
fluid.prefs.prefsEditor.writeImpl = function (that, modelToSave) {
var promise = fluid.promise(),
stats = {changes: 0, unchanged: 0, changeMap: {}},
changedPrefs = {};
modelToSave = fluid.copy(modelToSave);
// To address https://issues.fluidproject.org/browse/FLUID-4686
fluid.model.diff(modelToSave.preferences, fluid.get(that.initialModel, ["preferences"]), stats);
if (stats.changes === 0) {
delete modelToSave.preferences;
} else {
fluid.each(stats.changeMap, function (state, pref) {
fluid.set(changedPrefs, pref, modelToSave.preferences[pref]);
});
modelToSave.preferences = changedPrefs;
}
that.events.onSave.fire(modelToSave);
var setPromise = that.setSettings(modelToSave);
fluid.promise.follow(setPromise, promise);
return promise;
};
/**
* Sends the prefsEditor.model to the store and fires onSave
* @param {Object} that: A fluid.prefs.prefsEditor instance
* @return {Promise} A promise that will be resolved with the saved model or rejected on error.
*/
fluid.prefs.prefsEditor.save = function (that) {
var promise = fluid.promise();
if (!that.model || $.isEmptyObject(that.model)) { // Don't save a reset model
promise.resolve({});
} else {
var writePromise = that.write();
fluid.promise.follow(writePromise, promise);
}
return promise;
};
fluid.prefs.prefsEditor.saveAndApply = function (that) {
var promise = fluid.promise();
var prevSettingsPromise = that.getSettings(),
savePromise = that.save();
prevSettingsPromise.then(function (prevSettings) {
savePromise.then(function (changedSelections) {
// Only when preferences are changed, re-render panels and trigger enactors to apply changes
if (!fluid.model.diff(fluid.get(changedSelections, "preferences"), fluid.get(prevSettings, "preferences"))) {
that.events.onPrefsEditorRefresh.fire();
that.applyChanges();
}
});
fluid.promise.follow(savePromise, promise);
});
return promise;
};
/*
* Resets the selections to the integrator's defaults and fires afterReset
*/
fluid.prefs.prefsEditor.reset = function (that) {
var transaction = that.applier.initiate();
that.events.beforeReset.fire(that);
transaction.fireChangeRequest({path: "preferences", type: "DELETE"});
transaction.change("", fluid.copy(that.initialModel));
transaction.commit();
that.events.onPrefsEditorRefresh.fire();
that.events.afterReset.fire(that);
};
/*
* Resets the selections to the last saved selections and fires onCancel
*/
fluid.prefs.prefsEditor.cancel = function (that) {
that.events.onCancel.fire();
var fetchPromise = that.fetch();
fetchPromise.then(function () {
var transaction = that.applier.initiate();
transaction.fireChangeRequest({path: "preferences", type: "DELETE"});
transaction.change("", that.model.remote);
transaction.commit();
that.events.onPrefsEditorRefresh.fire();
});
};
// called once markup is applied to the document containing tab component roots
fluid.prefs.prefsEditor.finishInit = function (that) {
var bindHandlers = function (that) {
var saveButton = that.locate("save");
if (saveButton.length > 0) {
saveButton.click(that.saveAndApply);
var form = fluid.findForm(saveButton);
$(form).submit(function () {
that.saveAndApply();
});
}
that.locate("reset").click(that.reset);
that.locate("cancel").click(that.cancel);
};
that.container.append(that.options.resources.template.resourceText);
bindHandlers(that);
var fetchPromise = that.fetch();
fetchPromise.then(function () {
that.events.onPrefsEditorMarkupReady.fire();
that.events.onPrefsEditorRefresh.fire();
that.applyChanges();
that.events.onReady.fire(that);
});
};
fluid.prefs.prefsEditor.handleAutoSave = function (that) {
if (that.options.autoSave) {
that.events.onAutoSave.fire();
}
};
fluid.prefs.prefsEditor.init = function (that) {
// This setTimeout is to ensure that fetching of resources is asynchronous,
// and so that component construction does not run ahead of subcomponents for SeparatedPanel
// (FLUID-4453 - this may be a replacement for a branch removed for a FLUID-2248 fix)
setTimeout(function () {
if (!fluid.isDestroyed(that)) {
fluid.prefs.prefsEditor.finishInit(that);
}
}, 1);
};
/******************************
* Preferences Editor Preview *
******************************/
fluid.defaults("fluid.prefs.preview", {
gradeNames: ["fluid.viewComponent"],
components: {
enhancer: {
type: "fluid.uiEnhancer",
container: "{preview}.enhancerContainer",
createOnEvent: "onReady"
},
templateLoader: "{templateLoader}"
},
invokers: {
updateModel: {
funcName: "fluid.prefs.preview.updateModel",
args: [
"{preview}",
"{prefsEditor}.model.preferences"
]
}
},
events: {
onReady: null
},
listeners: {
"onCreate.startLoadingContainer": "fluid.prefs.preview.startLoadingContainer",
"{prefsEditor}.events.modelChanged": {
listener: "{that}.updateModel",
namespace: "updateModel"
},
"onReady.updateModel": "{that}.updateModel"
},
templateUrl: "%prefix/PrefsEditorPreview.html"
});
fluid.prefs.preview.updateModel = function (that, preferences) {
/**
* SetTimeout is temp fix for http://issues.fluidproject.org/browse/FLUID-2248
*/
setTimeout(function () {
if (that.enhancer) {
that.enhancer.updateModel(preferences);
}
}, 0);
};
fluid.prefs.preview.startLoadingContainer = function (that) {
var templateUrl = that.templateLoader.transformURL(that.options.templateUrl);
that.container.on("load", function () {
that.enhancerContainer = $("body", that.container.contents());
that.events.onReady.fire();
});
that.container.attr("src", templateUrl);
};
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
/**********************
* msgLookup grade *
**********************/
fluid.defaults("fluid.prefs.msgLookup", {
gradeNames: ["fluid.component"],
members: {
msgLookup: {
expander: {
funcName: "fluid.prefs.stringLookup",
args: ["{msgResolver}", "{that}.options.stringArrayIndex"]
}
}
},
stringArrayIndex: {}
});
fluid.prefs.stringLookup = function (messageResolver, stringArrayIndex) {
var that = {id: fluid.allocateGuid()};
that.singleLookup = function (value) {
var looked = messageResolver.lookup([value]);
return fluid.get(looked, "template");
};
that.multiLookup = function (values) {
return fluid.transform(values, function (value) {
return that.singleLookup(value);
});
};
that.lookup = function (value) {
var values = fluid.get(stringArrayIndex, value) || value;
var lookupFn = fluid.isArrayable(values) ? "multiLookup" : "singleLookup";
return that[lookupFn](values);
};
that.resolvePathSegment = that.lookup;
return that;
};
/***********************************************
* Base grade panel
***********************************************/
fluid.defaults("fluid.prefs.panel", {
gradeNames: ["fluid.prefs.msgLookup", "fluid.rendererComponent"],
events: {
onDomBind: null
},
// Any listener that requires a DOM element, should be registered
// to the onDomBind listener. By default it is fired by onCreate, but
// when used as a subpanel, it will be triggered by the resetDomBinder invoker.
listeners: {
"onCreate.onDomBind": "{that}.events.onDomBind"
},
components: {
msgResolver: {
type: "fluid.messageResolver"
}
},
rendererOptions: {
messageLocator: "{msgResolver}.resolve"
},
distributeOptions: {
"panel.msgResolver.messageBase": {
source: "{that}.options.messageBase",
target: "{that > msgResolver}.options.messageBase"
}
}
});
/***************************
* Base grade for subpanel *
***************************/
fluid.defaults("fluid.prefs.subPanel", {
gradeNames: ["fluid.prefs.panel", "{that}.getDomBindGrade"],
listeners: {
"{compositePanel}.events.afterRender": {
listener: "{that}.events.afterRender",
args: ["{that}"],
namespce: "boilAfterRender"
},
// Changing the firing of onDomBind from the onCreate.
// This is due to the fact that the rendering process, controlled by the
// composite panel, will set/replace the DOM elements.
"onCreate.onDomBind": null, // remove listener
"afterRender.onDomBind": "{that}.resetDomBinder"
},
rules: {
expander: {
func: "fluid.prefs.subPanel.generateRules",
args: ["{that}.options.preferenceMap"]
}
},
invokers: {
refreshView: "{compositePanel}.refreshView",
// resetDomBinder must fire the onDomBind event
resetDomBinder: {
funcName: "fluid.prefs.subPanel.resetDomBinder",
args: ["{that}"]
},
getDomBindGrade: {
funcName: "fluid.prefs.subPanel.getDomBindGrade",
args: ["{prefsEditor}"]
}
},
strings: {},
parentBundle: "{compositePanel}.messageResolver",
renderOnInit: false
});
fluid.defaults("fluid.prefs.subPanel.domBind", {
gradeNames: ["fluid.component"],
listeners: {
"onDomBind.domChange": {
listener: "{prefsEditor}.events.onSignificantDOMChange"
}
}
});
fluid.prefs.subPanel.getDomBindGrade = function (prefsEditor) {
var hasListener = fluid.get(prefsEditor, "options.events.onSignificantDOMChange") !== undefined;
if (hasListener) {
return "fluid.prefs.subPanel.domBind";
}
};
/*
* Since the composite panel manages the rendering of the subpanels
* the markup used by subpanels needs to be completely replaced.
* The subpanel's container is refereshed to point at the newly
* rendered markup, and the domBinder is re-initialized. Once
* this is all done, the onDomBind event is fired.
*/
fluid.prefs.subPanel.resetDomBinder = function (that) {
// TODO: The line below to find the container jQuery instance was copied from the framework code -
// https://github.com/fluid-project/infusion/blob/master/src/framework/core/js/FluidView.js#L145
// in order to reset the dom binder when panels are in an iframe.
// It can be be eliminated once we have the new renderer.
var userJQuery = that.container.constructor;
var context = that.container[0].ownerDocument;
var selector = that.container.selector;
that.container = userJQuery(selector, context);
// To address FLUID-5966, manually adding back the selector and context properties that were removed from jQuery v3.0.
// ( see: https://jquery.com/upgrade-guide/3.0/#breaking-change-deprecated-context-and-selector-properties-removed )
// In most cases the "selector" property will already be restored through the DOM binder or fluid.container.
// However, in this case we are manually recreating the container to ensure that it is referencing an element currently added
// to the correct Document ( e.g. iframe ) (also see: FLUID-4536). This manual recreation of the container requires us to
// manually add back the selector and context from the original container. This code and fix parallels that in
// FluidView.js fluid.container line 129
that.container.selector = selector;
that.container.context = context;
if (that.container.length === 0) {
fluid.fail("resetDomBinder got no elements in DOM for container searching for selector " + that.container.selector);
}
fluid.initDomBinder(that, that.options.selectors);
that.events.onDomBind.fire(that);
};
fluid.prefs.subPanel.safePrefKey = function (prefKey) {
return prefKey.replace(/[.]/g, "_");
};
/*
* Generates the model relay rules for a subpanel.
* Takes advantage of the fact that compositePanel
* uses the preference key (with "." replaced by "_"),
* as its model path.
*/
fluid.prefs.subPanel.generateRules = function (preferenceMap) {
var rules = {};
fluid.each(preferenceMap, function (prefObj, prefKey) {
fluid.each(prefObj, function (value, prefRule) {
if (prefRule.indexOf("model.") === 0) {
rules[fluid.prefs.subPanel.safePrefKey(prefKey)] = prefRule.slice("model.".length);
}
});
});
return rules;
};
/**********************************
* Base grade for composite panel *
**********************************/
fluid.registerNamespace("fluid.prefs.compositePanel");
fluid.prefs.compositePanel.arrayMergePolicy = function (target, source) {
target = fluid.makeArray(target);
source = fluid.makeArray(source);
fluid.each(source, function (selector) {
if (target.indexOf(selector) < 0) {
target.push(selector);
}
});
return target;
};
fluid.defaults("fluid.prefs.compositePanel", {
gradeNames: ["fluid.prefs.panel", "{that}.getDistributeOptionsGrade", "{that}.getSubPanelLifecycleBindings"],
mergePolicy: {
subPanelOverrides: "noexpand",
selectorsToIgnore: fluid.prefs.compositePanel.arrayMergePolicy
},
selectors: {}, // requires selectors into the template which will act as the containers for the subpanels
selectorsToIgnore: [], // should match the selectors that are used to identify the containers for the subpanels
repeatingSelectors: [],
events: {
initSubPanels: null
},
listeners: {
"onCreate.combineResources": "{that}.combineResources",
"onCreate.appendTemplate": {
"this": "{that}.container",
"method": "append",
"args": ["{that}.options.resources.template.resourceText"]
},
"onCreate.initSubPanels": "{that}.events.initSubPanels",
"onCreate.hideInactive": "{that}.hideInactive",
"afterRender.hideInactive": "{that}.hideInactive"
},
invokers: {
getDistributeOptionsGrade: {
funcName: "fluid.prefs.compositePanel.assembleDistributeOptions",
args: ["{that}.options.components"]
},
getSubPanelLifecycleBindings: {
funcName: "fluid.prefs.compositePanel.subPanelLifecycleBindings",
args: ["{that}", "{that}.options.components"]
},
combineResources: {
funcName: "fluid.prefs.compositePanel.combineTemplates",
args: ["{that}.options.resources", "{that}.options.selectors"]
},
produceSubPanelTrees: {
funcName: "fluid.prefs.compositePanel.produceSubPanelTrees",
args: ["{that}"]
},
expandProtoTree: {
funcName: "fluid.prefs.compositePanel.expandProtoTree",
args: ["{that}"]
},
produceTree: {
funcName: "fluid.prefs.compositePanel.produceTree",
args: ["{that}"]
},
hideInactive: {
funcName: "fluid.prefs.compositePanel.hideInactive",
args: ["{that}"]
},
handleRenderOnPreference: {
funcName: "fluid.prefs.compositePanel.handleRenderOnPreference",
args: ["{that}", "{that}.refreshView", "{that}.conditionalCreateEvent", "{arguments}.0", "{arguments}.1", "{arguments}.2"]
},
conditionalCreateEvent: {
funcName: "fluid.prefs.compositePanel.conditionalCreateEvent"
}
},
subPanelOverrides: {
gradeNames: ["fluid.prefs.subPanel"]
},
rendererFnOptions: {
noexpand: true,
cutpointGenerator: "fluid.prefs.compositePanel.cutpointGenerator",
subPanelRepeatingSelectors: {
expander: {
funcName: "fluid.prefs.compositePanel.surfaceRepeatingSelectors",
args: ["{that}.options.components"]
}
}
},
components: {},
resources: {} // template is reserved for the compositePanel's template, the subpanel template should have same key as the selector for its container.
});
/*
* Attempts to prefetch a components options before it is instantiated.
* Only use in cases where the instantiated component cannot be used.
*/
fluid.prefs.compositePanel.prefetchComponentOptions = function (type, options) {
var baseOptions = fluid.getMergedDefaults(type, fluid.get(options, "gradeNames"));
// TODO: awkwardly, fluid.merge is destructive on each argument!
return fluid.merge(baseOptions.mergePolicy, fluid.copy(baseOptions), options);
};
/*
* Should only be used when fluid.prefs.compositePanel.isActivatePanel cannot.
* While this implementation doesn't require an instantiated component, it may in
* the process miss some configuration provided by distribute options and demands.
*/
fluid.prefs.compositePanel.isPanel = function (type, options) {
var opts = fluid.prefs.compositePanel.prefetchComponentOptions(type, options);
return fluid.hasGrade(opts, "fluid.prefs.panel");
};
fluid.prefs.compositePanel.isActivePanel = function (comp) {
return comp && fluid.hasGrade(comp.options, "fluid.prefs.panel");
};
/*
* Creates a grade containing the distributeOptions rules needed for the subcomponents
*/
fluid.prefs.compositePanel.assembleDistributeOptions = function (components) {
var gradeName = "fluid.prefs.compositePanel.distributeOptions_" + fluid.allocateGuid();
var distributeOptions = {};
var relayOption = {};
fluid.each(components, function (componentOptions, componentName) {
if (fluid.prefs.compositePanel.isPanel(componentOptions.type, componentOptions.options)) {
distributeOptions[componentName + ".subPanelOverrides"] = {
source: "{that}.options.subPanelOverrides",
target: "{that > " + componentName + "}.options"
};
}
// Construct the model relay btw the composite panel and its subpanels
var componentRelayRules = {};
var definedOptions = fluid.prefs.compositePanel.prefetchComponentOptions(componentOptions.type, componentOptions.options);
var preferenceMap = fluid.get(definedOptions, ["preferenceMap"]);
fluid.each(preferenceMap, function (prefObj, prefKey) {
fluid.each(prefObj, function (value, prefRule) {
if (prefRule.indexOf("model.") === 0) {
fluid.set(componentRelayRules, prefRule.slice("model.".length), "{compositePanel}.model." + fluid.prefs.subPanel.safePrefKey(prefKey));
}
});
});
relayOption[componentName] = componentRelayRules;
distributeOptions[componentName + ".modelRelay"] = {
source: "{that}.options.relayOption." + componentName,
target: "{that > " + componentName + "}.options.model"
};
});
fluid.defaults(gradeName, {
relayOption: relayOption,
distributeOptions: distributeOptions
});
return gradeName;
};
fluid.prefs.compositePanel.conditionalCreateEvent = function (value, createEvent) {
if (value) {
createEvent();
}
};
fluid.prefs.compositePanel.handleRenderOnPreference = function (that, refreshViewFunc, conditionalCreateEventFunc, value, createEvent, componentNames) {
componentNames = fluid.makeArray(componentNames);
conditionalCreateEventFunc(value, createEvent);
fluid.each(componentNames, function (componentName) {
var comp = that[componentName];
if (!value && comp) {
comp.destroy();
}
});
refreshViewFunc();
};
fluid.prefs.compositePanel.creationEventName = function (pref) {
return "initOn_" + pref;
};
fluid.prefs.compositePanel.generateModelListeners = function (conditionals) {
return fluid.transform(conditionals, function (componentNames, pref) {
var eventName = fluid.prefs.compositePanel.creationEventName(pref);
return {
func: "{that}.handleRenderOnPreference",
args: ["{change}.value", "{that}.events." + eventName + ".fire", componentNames],
namespace: "handleRenderOnPreference_" + pref
};
});
};
fluid.prefs.compositePanel.rebaseSelectorName = function (memberName, selectorName) {
return memberName + "_" + selectorName;
};
fluid.prefs.compositePanel.rebaseSelector = function (compositePanelSelector, selector) {
return compositePanelSelector + " " + selector;
};
/*
* Creates a grade containing all of the lifecycle binding configuration needed for the subpanels.
* This includes the following:
* - adding events used to trigger the initialization of the subpanels
* - adding the createOnEvent configuration for the subpanels
* - binding handlers to model changed events
* - binding handlers to afterRender and onCreate
* - surfacing selectors from the subpanels to the composite panel
*/
fluid.prefs.compositePanel.subPanelLifecycleBindings = function (that, components) {
var gradeName = "fluid.prefs.compositePanel.subPanelCreationTimingDistibution_" + fluid.allocateGuid();
var distributeOptions = {};
var subPanelCreationOpts = {
"default": "initSubPanels"
};
var conditionals = {};
var listeners = {};
var events = {};
var selectors = {};
fluid.each(components, function (componentOptions, componentName) {
if (fluid.prefs.compositePanel.isPanel(componentOptions.type, componentOptions.options)) {
var creationEventOpt = "default";
// would have had renderOnPreference directly sourced from the componentOptions
// however, the set of configuration specified there is restricted.
var renderOnPreference = fluid.get(componentOptions, "options.renderOnPreference");
if (renderOnPreference) {
var pref = fluid.prefs.subPanel.safePrefKey(renderOnPreference);
var onCreateListener = "onCreate." + pref;
creationEventOpt = fluid.prefs.compositePanel.creationEventName(pref);
subPanelCreationOpts[creationEventOpt] = creationEventOpt;
events[creationEventOpt] = null;
conditionals[pref] = conditionals[pref] || [];
conditionals[pref].push(componentName);
listeners[onCreateListener] = {
listener: "{that}.conditionalCreateEvent",
args: ["{that}.model." + pref, "{that}.events." + creationEventOpt + ".fire"]
};
}
distributeOptions[componentName + ".subPanelCreationOpts"] = {
source: "{that}.options.subPanelCreationOpts." + creationEventOpt,
target: "{that}.options.components." + componentName + ".createOnEvent"
};
var opts = fluid.prefs.compositePanel.prefetchComponentOptions(componentOptions.type, componentOptions.options);
fluid.each(opts.selectors, function (selector, selName) {
if (!opts.selectorsToIgnore || opts.selectorsToIgnore.indexOf(selName) < 0) {
// Sets an expander for each surfaced selector because we need to prepend the the subpanel's own
// container selector to ensure that the dom binder scopes those selectors to the appropriate
// component's container. Other options for obtaining the composite panel's container required
// either modifying the options after resolution or would trigger the resolution of composite
// panel's selectors and prevent accepting any more options merged on top.
selectors[fluid.prefs.compositePanel.rebaseSelectorName(componentName, selName)] = {
expander: {
funcName: "fluid.prefs.compositePanel.rebaseSelector",
args: ["{that}.options.selectors." + componentName, selector]
}
};
}
});
}
});
fluid.defaults(gradeName, {
events: events,
listeners: listeners,
modelListeners: fluid.prefs.compositePanel.generateModelListeners(conditionals),
subPanelCreationOpts: subPanelCreationOpts,
distributeOptions: distributeOptions,
selectors: selectors
});
return gradeName;
};
/*
* Used to hide the containers of inactive sub panels.
* This is necessary as the composite panel's template is the one that has their containers and
* it would be undesirable to have them visible when their associated panel has not been created.
* Also, hiding them allows for the subpanel to initialize, as it requires their container to be present.
* The subpanels need to be initialized before rendering, for the produce function to source the rendering
* information from it.
*/
fluid.prefs.compositePanel.hideInactive = function (that) {
fluid.each(that.options.components, function (componentOpts, componentName) {
if (fluid.prefs.compositePanel.isPanel(componentOpts.type, componentOpts.options) && !fluid.prefs.compositePanel.isActivePanel(that[componentName])) {
that.locate(componentName).hide();
}
});
};
/*
* Use the renderer directly to combine the templates into a single
* template to be used by the components actual rendering.
*/
fluid.prefs.compositePanel.combineTemplates = function (resources, selectors) {
var cutpoints = [];
var tree = {children: []};
fluid.each(resources, function (resource, resourceName) {
if (resourceName !== "template") {
tree.children.push({
ID: resourceName,
markup: resource.resourceText
});
cutpoints.push({
id: resourceName,
selector: selectors[resourceName]
});
}
});
var resourceSpec = {
base: {
resourceText: resources.template.resourceText,
href: ".",
resourceKey: ".",
cutpoints: cutpoints
}
};
var templates = fluid.parseTemplates(resourceSpec, ["base"]);
var renderer = fluid.renderer(templates, tree, {cutpoints: cutpoints, debugMode: true});
resources.template.resourceText = renderer.renderTemplates();
};
fluid.prefs.compositePanel.surfaceRepeatingSelectors = function (components) {
var repeatingSelectors = [];
fluid.each(components, function (compOpts, compName) {
if (fluid.prefs.compositePanel.isPanel(compOpts.type, compOpts.options)) {
var opts = fluid.prefs.compositePanel.prefetchComponentOptions(compOpts.type, compOpts.options);
var rebasedRepeatingSelectors = fluid.transform(opts.repeatingSelectors, function (selector) {
return fluid.prefs.compositePanel.rebaseSelectorName(compName, selector);
});
repeatingSelectors = repeatingSelectors.concat(rebasedRepeatingSelectors);
}
});
return repeatingSelectors;
};
fluid.prefs.compositePanel.cutpointGenerator = function (selectors, options) {
var opts = {
selectorsToIgnore: options.selectorsToIgnore,
repeatingSelectors: options.repeatingSelectors.concat(options.subPanelRepeatingSelectors)
};
return fluid.renderer.selectorsToCutpoints(selectors, opts);
};
fluid.prefs.compositePanel.rebaseID = function (value, memberName) {
return memberName + "_" + value;
};
fluid.prefs.compositePanel.rebaseParentRelativeID = function (val, memberName) {
var slicePos = "..::".length; // ..:: refers to the parentRelativeID prefix used in the renderer
return val.slice(0, slicePos) + fluid.prefs.compositePanel.rebaseID(val.slice(slicePos), memberName);
};
fluid.prefs.compositePanel.rebaseValueBinding = function (value, modelRelayRules) {
return fluid.find(modelRelayRules, function (oldModelPath, newModelPath) {
if (value === oldModelPath) {
return newModelPath;
} else if (value.indexOf(oldModelPath) === 0) {
return value.replace(oldModelPath, newModelPath);
}
}) || value;
};
fluid.prefs.compositePanel.rebaseTreeComp = function (msgResolver, model, treeComp, memberName, modelRelayRules) {
var rebased = fluid.copy(treeComp);
if (rebased.ID) {
rebased.ID = fluid.prefs.compositePanel.rebaseID(rebased.ID, memberName);
}
if (rebased.children) {
rebased.children = fluid.prefs.compositePanel.rebaseTree(msgResolver, model, rebased.children, memberName, modelRelayRules);
} else if (rebased.selection) {
rebased.selection = fluid.prefs.compositePanel.rebaseTreeComp(msgResolver, model, rebased.selection, memberName, modelRelayRules);
} else if (rebased.messagekey) {
// converts the "UIMessage" renderer component into a "UIBound"
// and passes in the resolved message as the value.
rebased.componentType = "UIBound";
rebased.value = msgResolver.resolve(rebased.messagekey.value, rebased.messagekey.args);
delete rebased.messagekey;
} else if (rebased.parentRelativeID) {
rebased.parentRelativeID = fluid.prefs.compositePanel.rebaseParentRelativeID(rebased.parentRelativeID, memberName);
} else if (rebased.valuebinding) {
rebased.valuebinding = fluid.prefs.compositePanel.rebaseValueBinding(rebased.valuebinding, modelRelayRules);
if (rebased.value) {
var modelValue = fluid.get(model, rebased.valuebinding);
rebased.value = modelValue !== undefined ? modelValue : rebased.value;
}
}
return rebased;
};
fluid.prefs.compositePanel.rebaseTree = function (msgResolver, model, tree, memberName, modelRelayRules) {
var rebased;
if (fluid.isArrayable(tree)) {
rebased = fluid.transform(tree, function (treeComp) {
return fluid.prefs.compositePanel.rebaseTreeComp(msgResolver, model, treeComp, memberName, modelRelayRules);
});
} else {
rebased = fluid.prefs.compositePanel.rebaseTreeComp(msgResolver, model, tree, memberName, modelRelayRules);
}
return rebased;
};
fluid.prefs.compositePanel.produceTree = function (that) {
var produceTreeOption = that.options.produceTree;
var ownTree = produceTreeOption ?
(typeof (produceTreeOption) === "string" ? fluid.getGlobalValue(produceTreeOption) : produceTreeOption)(that) :
that.expandProtoTree();
var subPanelTree = that.produceSubPanelTrees();
var tree = {
children: ownTree.children.concat(subPanelTree.children)
};
return tree;
};
fluid.prefs.compositePanel.expandProtoTree = function (that) {
var expanderOptions = fluid.renderer.modeliseOptions(that.options.expanderOptions, {ELstyle: "${}"}, that);
var expander = fluid.renderer.makeProtoExpander(expanderOptions, that);
return expander(that.options.protoTree || {});
};
fluid.prefs.compositePanel.produceSubPanelTrees = function (that) {
var tree = {children: []};
fluid.each(that.options.components, function (options, componentName) {
var subPanel = that[componentName];
if (fluid.prefs.compositePanel.isActivePanel(subPanel)) {
var expanderOptions = fluid.renderer.modeliseOptions(subPanel.options.expanderOptions, {ELstyle: "${}"}, subPanel);
var expander = fluid.renderer.makeProtoExpander(expanderOptions, subPanel);
var subTree = subPanel.produceTree();
subTree = fluid.get(subPanel.options, "rendererFnOptions.noexpand") ? subTree : expander(subTree);
var rebasedTree = fluid.prefs.compositePanel.rebaseTree(subPanel.msgResolver, that.model, subTree, componentName, subPanel.options.rules);
tree.children = tree.children.concat(rebasedTree.children);
}
});
return tree;
};
/********************************************************************************
* The grade that contains the connections between a panel and the prefs editor *
********************************************************************************/
fluid.defaults("fluid.prefs.prefsEditorConnections", {
gradeNames: ["fluid.component"],
listeners: {
// No namespace supplied because this grade is added to every panel. Suppling a
// namespace would mean that only one panel's refreshView method was bound to the
// onPrefsEditorRefresh event.
"{fluid.prefs.prefsEditor}.events.onPrefsEditorRefresh": "{fluid.prefs.panel}.refreshView"
},
strings: {},
parentBundle: "{fluid.prefs.prefsEditorLoader}.msgResolver"
});
/*******************************************
* A base grade for switch adjuster panels *
*******************************************/
fluid.defaults("fluid.prefs.panel.switchAdjuster", {
gradeNames: ["fluid.prefs.panel"],
// preferences maps should map model values to "model.value"
// model: {value: ""}
selectors: {
header: ".flc-prefsEditor-header",
switchContainer: ".flc-prefsEditor-switch",
label: ".flc-prefsEditor-label",
description: ".flc-prefsEditor-description"
},
selectorsToIgnore: ["header", "switchContainer"],
components: {
switchUI: {
type: "fluid.switchUI",
container: "{that}.dom.switchContainer",
createOnEvent: "afterRender",
options: {
strings: {
on: "{fluid.prefs.panel.switchAdjuster}.msgLookup.switchOn",
off: "{fluid.prefs.panel.switchAdjuster}.msgLookup.switchOff"
},
model: {
enabled: "{fluid.prefs.panel.switchAdjuster}.model.value"
},
attrs: {
"aria-labelledby": {
expander: {
funcName: "fluid.allocateSimpleId",
args: ["{fluid.prefs.panel.switchAdjuster}.dom.description"]
}
}
}
}
}
},
protoTree: {
label: {messagekey: "label"},
description: {messagekey: "description"}
}
});
/************************************************
* A base grade for themePicker adjuster panels *
************************************************/
fluid.defaults("fluid.prefs.panel.themePicker", {
gradeNames: ["fluid.prefs.panel"],
mergePolicy: {
"controlValues.theme": "replace",
"stringArrayIndex.theme": "replace"
},
// The controlValues are the ordered set of possible modelValues corresponding to each theme option.
// The order in which they are listed will determine the order they are presented in the UI.
// The stringArrayIndex contains the ordered set of namespaced strings in the message bundle.
// The order must match the controlValues in order to provide the proper labels to the theme options.
controlValues: {
theme: [] // must be supplied by the integrator
},
stringArrayIndex: {
theme: [] // must be supplied by the integrator
},
selectID: "{that}.id", // used for the name attribute to group the selection options
listeners: {
"afterRender.style": "{that}.style"
},
selectors: {
themeRow: ".flc-prefsEditor-themeRow",
themeLabel: ".flc-prefsEditor-theme-label",
themeInput: ".flc-prefsEditor-themeInput",
label: ".flc-prefsEditor-themePicker-label",
description: ".flc-prefsEditor-themePicker-descr"
},
styles: {
defaultThemeLabel: "fl-prefsEditor-themePicker-defaultThemeLabel"
},
repeatingSelectors: ["themeRow"],
protoTree: {
label: {messagekey: "label"},
description: {messagekey: "description"},
expander: {
type: "fluid.renderer.selection.inputs",
rowID: "themeRow",
labelID: "themeLabel",
inputID: "themeInput",
selectID: "{that}.options.selectID",
tree: {
optionnames: "${{that}.msgLookup.theme}",
optionlist: "${{that}.options.controlValues.theme}",
selection: "${value}"
}
}
},
markup: {
// Aria-hidden needed on fl-preview-A and Display 'a' created as pseudo-content in css to prevent AT from reading out display 'a' on IE, Chrome, and Safari
// Aria-hidden needed on fl-crossout to prevent AT from trying to read crossout symbol in Safari
label: "<span class=\"fl-preview-A\" aria-hidden=\"true\"></span><span class=\"fl-hidden-accessible\">%theme</span><div class=\"fl-crossout\" aria-hidden=\"true\"></div>"
},
invokers: {
style: {
funcName: "fluid.prefs.panel.themePicker.style",
args: [
"{that}.dom.themeLabel",
"{that}.msgLookup.theme",
"{that}.options.markup.label",
"{that}.options.controlValues.theme",
"default",
"{that}.options.classnameMap.theme",
"{that}.options.styles.defaultThemeLabel"
]
}
}
});
fluid.prefs.panel.themePicker.style = function (labels, strings, markup, theme, defaultThemeName, style, defaultLabelStyle) {
fluid.each(labels, function (label, index) {
label = $(label);
var themeValue = strings[index];
label.html(fluid.stringTemplate(markup, {
theme: themeValue
}));
// Aria-label set to prevent Firefox from reading out the display 'a'
label.attr("aria-label", themeValue);
var labelTheme = theme[index];
if (labelTheme === defaultThemeName) {
label.addClass(defaultLabelStyle);
}
label.addClass(style[labelTheme]);
});
};
/******************************************************
* A base grade for textfield stepper adjuster panels *
******************************************************/
fluid.defaults("fluid.prefs.panel.stepperAdjuster", {
gradeNames: ["fluid.prefs.panel"],
// preferences maps should map model values to "model.value"
// model: {value: ""}
selectors: {
header: ".flc-prefsEditor-header",
textfieldStepperContainer: ".flc-prefsEditor-textfieldStepper",
label: ".flc-prefsEditor-label",
descr: ".flc-prefsEditor-descr"
},
selectorsToIgnore: ["header", "textfieldStepperContainer"],
components: {
textfieldStepper: {
type: "fluid.textfieldStepper",
container: "{that}.dom.textfieldStepperContainer",
createOnEvent: "afterRender",
options: {
model: {
value: "{fluid.prefs.panel.stepperAdjuster}.model.value",
range: {
min: "{fluid.prefs.panel.stepperAdjuster}.options.range.min",
max: "{fluid.prefs.panel.stepperAdjuster}.options.range.max"
},
step: "{fluid.prefs.panel.stepperAdjuster}.options.step"
},
scale: 1,
strings: {
increaseLabel: "{fluid.prefs.panel.stepperAdjuster}.msgLookup.increaseLabel",
decreaseLabel: "{fluid.prefs.panel.stepperAdjuster}.msgLookup.decreaseLabel"
},
attrs: {
"aria-labelledby": "{fluid.prefs.panel.stepperAdjuster}.options.panelOptions.labelId"
}
}
}
},
protoTree: {
label: {
messagekey: "label",
decorators: {
attrs: {id: "{that}.options.panelOptions.labelId"}
}
},
descr: {messagekey: "description"}
},
panelOptions: {
labelIdTemplate: "%guid",
labelId: {
expander: {
funcName: "fluid.prefs.panel.stepperAdjuster.setLabelID",
args: ["{that}.options.panelOptions.labelIdTemplate"]
}
}
}
});
/**
* @param {String} template - take string template with a token "%guid" to be replaced by the a unique ID.
* @return {String} - the resolved templated with the injected unique ID.
*/
fluid.prefs.panel.stepperAdjuster.setLabelID = function (template) {
return fluid.stringTemplate(template, {
guid: fluid.allocateGuid()
});
};
/********************************
* Preferences Editor Text Size *
********************************/
/**
* A sub-component of fluid.prefs that renders the "text size" panel of the user preferences interface.
*/
fluid.defaults("fluid.prefs.panel.textSize", {
gradeNames: ["fluid.prefs.panel.stepperAdjuster"],
preferenceMap: {
"fluid.prefs.textSize": {
"model.value": "value",
"range.min": "minimum",
"range.max": "maximum",
"step": "multipleOf"
}
},
panelOptions: {
labelIdTemplate: "textSize-label-%guid"
}
});
/********************************
* Preferences Editor Text Font *
********************************/
/**
* A sub-component of fluid.prefs that renders the "text font" panel of the user preferences interface.
*/
fluid.defaults("fluid.prefs.panel.textFont", {
gradeNames: ["fluid.prefs.panel"],
preferenceMap: {
"fluid.prefs.textFont": {
"model.value": "value",
"controlValues.textFont": "enum",
"stringArrayIndex.textFont": "enumLabels"
}
},
mergePolicy: {
"controlValues.textFont": "replace",
"stringArrayIndex.textFont": "replace"
},
selectors: {
header: ".flc-prefsEditor-text-font-header",
textFont: ".flc-prefsEditor-text-font",
label: ".flc-prefsEditor-text-font-label",
textFontDescr: ".flc-prefsEditor-text-font-descr"
},
selectorsToIgnore: ["header"],
protoTree: {
label: {messagekey: "textFontLabel"},
textFontDescr: {messagekey: "textFontDescr"},
textFont: {
optionnames: "${{that}.msgLookup.textFont}",
optionlist: "${{that}.options.controlValues.textFont}",
selection: "${value}",
decorators: {
type: "fluid",
func: "fluid.prefs.selectDecorator",
options: {
styles: "{that}.options.classnameMap.textFont"
}
}
}
},
classnameMap: null // must be supplied by implementors
});
/*********************************
* Preferences Editor Line Space *
*********************************/
/**
* A sub-component of fluid.prefs that renders the "line space" panel of the user preferences interface.
*/
fluid.defaults("fluid.prefs.panel.lineSpace", {
gradeNames: ["fluid.prefs.panel.stepperAdjuster"],
preferenceMap: {
"fluid.prefs.lineSpace": {
"model.value": "value",
"range.min": "minimum",
"range.max": "maximum",
"step": "multipleOf"
}
},
panelOptions: {
labelIdTemplate: "lineSpace-label-%guid"
}
});
/*******************************
* Preferences Editor Contrast *
*******************************/
/**
* A sub-component of fluid.prefs that renders the "contrast" panel of the user preferences interface.
*/
fluid.defaults("fluid.prefs.panel.contrast", {
gradeNames: ["fluid.prefs.panel.themePicker"],
preferenceMap: {
"fluid.prefs.contrast": {
"model.value": "value",
"controlValues.theme": "enum",
"stringArrayIndex.theme": "enumLabels"
}
},
listeners: {
"afterRender.style": "{that}.style"
},
selectors: {
header: ".flc-prefsEditor-contrast-header",
themeRow: ".flc-prefsEditor-themeRow",
themeLabel: ".flc-prefsEditor-theme-label",
themeInput: ".flc-prefsEditor-themeInput",
label: ".flc-prefsEditor-themePicker-label",
contrastDescr: ".flc-prefsEditor-themePicker-descr"
},
selectorsToIgnore: ["header"],
styles: {
defaultThemeLabel: "fl-prefsEditor-themePicker-defaultThemeLabel"
}
});
/**************************************
* Preferences Editor Layout Controls *
**************************************/
/**
* A sub-component of fluid.prefs that renders the "layout and navigation" panel of the user preferences interface.
*/
fluid.defaults("fluid.prefs.panel.layoutControls", {
gradeNames: ["fluid.prefs.panel.switchAdjuster"],
preferenceMap: {
"fluid.prefs.tableOfContents": {
"model.value": "value"
}
}
});
/*************************************
* Preferences Editor Enhance Inputs *
*************************************/
/**
* A sub-component of fluid.prefs that renders the "enhance inputs" panel of the user preferences interface.
*/
fluid.defaults("fluid.prefs.panel.enhanceInputs", {
gradeNames: ["fluid.prefs.panel.switchAdjuster"],
preferenceMap: {
"fluid.prefs.enhanceInputs": {
"model.value": "value"
}
}
});
/********************************************************
* Preferences Editor Select Dropdown Options Decorator *
********************************************************/
/**
* A sub-component that decorates the options on the select dropdown list box with the css style
*/
fluid.defaults("fluid.prefs.selectDecorator", {
gradeNames: ["fluid.viewComponent"],
listeners: {
"onCreate.decorateOptions": "fluid.prefs.selectDecorator.decorateOptions"
},
styles: {
preview: "fl-preview-theme"
}
});
fluid.prefs.selectDecorator.decorateOptions = function (that) {
fluid.each($("option", that.container), function (option) {
var styles = that.options.styles;
$(option).addClass(styles.preview + " " + styles[fluid.value(option)]);
});
};
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
/**********************************************************************************
* Captions Panel
**********************************************************************************/
fluid.defaults("fluid.prefs.panel.captions", {
gradeNames: ["fluid.prefs.panel.switchAdjuster"],
preferenceMap: {
"fluid.prefs.captions": {
"model.value": "value"
}
}
});
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
/*************************************
* Preferences Editor Letter Spacing *
*************************************/
/**
* A sub-component of fluid.prefs that renders the "letter spacing" panel of the user preferences interface.
*/
fluid.defaults("fluid.prefs.panel.letterSpace", {
gradeNames: ["fluid.prefs.panel.stepperAdjuster"],
preferenceMap: {
"fluid.prefs.letterSpace": {
"model.value": "value",
"range.min": "minimum",
"range.max": "maximum",
"step": "multipleOf"
}
},
panelOptions: {
labelIdTemplate: "letterSpace-label-%guid"
}
});
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
/**********************************************************************************
* speakPanel
**********************************************************************************/
fluid.defaults("fluid.prefs.panel.speak", {
gradeNames: ["fluid.prefs.panel.switchAdjuster"],
preferenceMap: {
"fluid.prefs.speak": {
"model.value": "value"
}
}
});
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
/**********************************************************************************
* Captions Panel
**********************************************************************************/
fluid.defaults("fluid.prefs.panel.syllabification", {
gradeNames: ["fluid.prefs.panel.switchAdjuster"],
preferenceMap: {
"fluid.prefs.syllabification": {
"model.value": "value"
}
}
});
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
/***********************************
* Preferences Editor Localization *
***********************************/
/**
* A sub-component of fluid.prefs that renders the "localization" panel of the user preferences interface.
*/
fluid.defaults("fluid.prefs.panel.localization", {
gradeNames: ["fluid.prefs.panel"],
preferenceMap: {
"fluid.prefs.localization": {
"model.value": "value",
"controlValues.localization": "enum",
"stringArrayIndex.localization": "enumLabels"
}
},
mergePolicy: {
"controlValues.localization": "replace",
"stringArrayIndex.localization": "replace"
},
selectors: {
header: ".flc-prefsEditor-localization-header",
localization: ".flc-prefsEditor-localization",
label: ".flc-prefsEditor-localization-label",
localizationDescr: ".flc-prefsEditor-localization-descr"
},
selectorsToIgnore: ["header"],
protoTree: {
label: {messagekey: "label"},
localizationDescr: {messagekey: "description"},
localization: {
optionnames: "${{that}.msgLookup.localization}",
optionlist: "${{that}.options.controlValues.localization}",
selection: "${value}"
}
}
});
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
/*************************************
* Preferences Editor Word Spacing *
*************************************/
/**
* A sub-component of fluid.prefs that renders the "word spacing" panel of the user preferences interface.
*/
fluid.defaults("fluid.prefs.panel.wordSpace", {
gradeNames: ["fluid.prefs.panel.stepperAdjuster"],
preferenceMap: {
"fluid.prefs.wordSpace": {
"model.value": "value",
"range.min": "minimum",
"range.max": "maximum",
"step": "multipleOf"
}
},
panelOptions: {
labelIdTemplate: "wordSpace-label-%guid"
}
});
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
fluid.defaults("fluid.prefs.enactor", {
gradeNames: ["fluid.modelComponent"]
});
/**********************************************************************************
* styleElements
*
* Adds or removes the classname to/from the elements based upon the model value.
* This component is used as a grade by enhanceInputs
**********************************************************************************/
fluid.defaults("fluid.prefs.enactor.styleElements", {
gradeNames: ["fluid.prefs.enactor"],
cssClass: null, // Must be supplied by implementors
elementsToStyle: null, // Must be supplied by implementors
invokers: {
applyStyle: {
funcName: "fluid.prefs.enactor.styleElements.applyStyle",
args: ["{arguments}.0", "{arguments}.1"]
},
resetStyle: {
funcName: "fluid.prefs.enactor.styleElements.resetStyle",
args: ["{arguments}.0", "{arguments}.1"]
},
handleStyle: {
funcName: "fluid.prefs.enactor.styleElements.handleStyle",
args: ["{arguments}.0", "{that}.options.elementsToStyle", "{that}.options.cssClass", "{that}.applyStyle", "{that}.resetStyle"]
}
},
modelListeners: {
value: {
listener: "{that}.handleStyle",
args: ["{change}.value"],
namespace: "handleStyle"
}
}
});
fluid.prefs.enactor.styleElements.applyStyle = function (elements, cssClass) {
elements.addClass(cssClass);
};
fluid.prefs.enactor.styleElements.resetStyle = function (elements, cssClass) {
$(elements, "." + cssClass).addBack().removeClass(cssClass);
};
fluid.prefs.enactor.styleElements.handleStyle = function (value, elements, cssClass, applyStyleFunc, resetStyleFunc) {
var func = value ? applyStyleFunc : resetStyleFunc;
func(elements, cssClass);
};
/*******************************************************************************
* ClassSwapper
*
* Has a hash of classes it cares about and will remove all those classes from
* its container before setting the new class.
* This component tends to be used as a grade by textFont and contrast
*******************************************************************************/
fluid.defaults("fluid.prefs.enactor.classSwapper", {
gradeNames: ["fluid.prefs.enactor", "fluid.viewComponent"],
classes: {}, // Must be supplied by implementors
invokers: {
clearClasses: {
funcName: "fluid.prefs.enactor.classSwapper.clearClasses",
args: ["{that}.container", "{that}.classStr"]
},
swap: {
funcName: "fluid.prefs.enactor.classSwapper.swap",
args: ["{arguments}.0", "{that}", "{that}.clearClasses"]
}
},
modelListeners: {
value: {
listener: "{that}.swap",
args: ["{change}.value"],
namespace: "swapClass"
}
},
members: {
classStr: {
expander: {
func: "fluid.prefs.enactor.classSwapper.joinClassStr",
args: "{that}.options.classes"
}
}
}
});
fluid.prefs.enactor.classSwapper.clearClasses = function (container, classStr) {
container.removeClass(classStr);
};
fluid.prefs.enactor.classSwapper.swap = function (value, that, clearClassesFunc) {
clearClassesFunc();
that.container.addClass(that.options.classes[value]);
};
fluid.prefs.enactor.classSwapper.joinClassStr = function (classes) {
var classStr = "";
fluid.each(classes, function (oneClassName) {
if (oneClassName) {
classStr += classStr ? " " + oneClassName : oneClassName;
}
});
return classStr;
};
/*******************************************************************************
* enhanceInputs
*
* The enactor to enhance inputs in the container according to the value
*******************************************************************************/
// Note that the implementors need to provide the container for this view component
fluid.defaults("fluid.prefs.enactor.enhanceInputs", {
gradeNames: ["fluid.prefs.enactor.styleElements", "fluid.viewComponent"],
preferenceMap: {
"fluid.prefs.enhanceInputs": {
"model.value": "value"
}
},
cssClass: null, // Must be supplied by implementors
elementsToStyle: "{that}.container"
});
/*******************************************************************************
* textFont
*
* The enactor to change the font face used according to the value
*******************************************************************************/
// Note that the implementors need to provide the container for this view component
fluid.defaults("fluid.prefs.enactor.textFont", {
gradeNames: ["fluid.prefs.enactor.classSwapper"],
preferenceMap: {
"fluid.prefs.textFont": {
"model.value": "value"
}
}
});
/*******************************************************************************
* contrast
*
* The enactor to change the contrast theme according to the value
*******************************************************************************/
// Note that the implementors need to provide the container for this view component
fluid.defaults("fluid.prefs.enactor.contrast", {
gradeNames: ["fluid.prefs.enactor.classSwapper"],
preferenceMap: {
"fluid.prefs.contrast": {
"model.value": "value"
}
}
});
/*******************************************************************************
* Functions shared by textSize and lineSpace
*******************************************************************************/
/**
* return "font-size" in px
* @param {Object} container - The container to evaluate.
* @param {Object} fontSizeMap - The mapping between the font size string values ("small", "medium" etc) to px values.
* @return {Number} - The size of the container, in px units.
*/
fluid.prefs.enactor.getTextSizeInPx = function (container, fontSizeMap) {
var fontSize = container.css("font-size");
if (fontSizeMap[fontSize]) {
fontSize = fontSizeMap[fontSize];
}
// return fontSize in px
return parseFloat(fontSize);
};
/*******************************************************************************
* textRelatedSizer
*
* Provides an abstraction for enactors that need to adjust sizes based on
* a text size value from the DOM. This could include things such as:
* font-size, line-height, letter-spacing, and etc.
*******************************************************************************/
fluid.defaults("fluid.prefs.enactor.textRelatedSizer", {
gradeNames: ["fluid.prefs.enactor", "fluid.viewComponent"],
fontSizeMap: {}, // must be supplied by implementors
invokers: {
set: "fluid.notImplemented", // must be supplied by a concrete implementation
getTextSizeInPx: {
funcName: "fluid.prefs.enactor.getTextSizeInPx",
args: ["{that}.container", "{that}.options.fontSizeMap"]
}
},
modelListeners: {
value: {
listener: "{that}.set",
args: ["{change}.value"],
namespace: "setAdaptation"
}
}
});
/*******************************************************************************
* spacingSetter
*
* Sets the css spacing value on the container to the number of units to
* increase the space by. If a negative number is provided, the space between
* will decrease. Setting the value to 1 or unit to 0 will use the default.
*******************************************************************************/
fluid.defaults("fluid.prefs.enactor.spacingSetter", {
gradeNames: ["fluid.prefs.enactor.textRelatedSizer"],
members: {
originalSpacing: {
expander: {
func: "{that}.getSpacing"
}
}
},
cssProp: "",
invokers: {
set: {
funcName: "fluid.prefs.enactor.spacingSetter.set",
args: ["{that}", "{that}.options.cssProp", "{arguments}.0"]
},
getSpacing: {
funcName: "fluid.prefs.enactor.spacingSetter.getSpacing",
args: ["{that}", "{that}.options.cssProp", "{that}.getTextSizeInPx"]
}
},
modelListeners: {
unit: {
listener: "{that}.set",
args: ["{change}.value"],
namespace: "setAdaptation"
},
// Replace default model listener, because `value` needs be transformed before being applied.
// The `unit` model value should be used for setting the adaptation.
value: {
listener: "fluid.identity",
namespace: "setAdaptation"
}
},
modelRelay: {
target: "unit",
namespace: "toUnit",
singleTransform: {
type: "fluid.transforms.round",
scale: 1,
input: {
transform: {
"type": "fluid.transforms.linearScale",
"offset": -1,
"input": "{that}.model.value"
}
}
}
}
});
fluid.prefs.enactor.spacingSetter.getSpacing = function (that, cssProp, getTextSizeFn) {
var current = parseFloat(that.container.css(cssProp));
var textSize = getTextSizeFn();
return fluid.roundToDecimal(current / textSize, 2);
};
fluid.prefs.enactor.spacingSetter.set = function (that, cssProp, units) {
var targetSize = that.originalSpacing;
if (units) {
targetSize = targetSize + units;
}
// setting the style value to "" will remove it.
var spacingSetter = targetSize ? fluid.roundToDecimal(targetSize, 2) + "em" : "";
that.container.css(cssProp, spacingSetter);
};
/*******************************************************************************
* textSize
*
* Sets the text size on the root element to the multiple provided.
*******************************************************************************/
// Note that the implementors need to provide the container for this view component
fluid.defaults("fluid.prefs.enactor.textSize", {
gradeNames: ["fluid.prefs.enactor.textRelatedSizer"],
preferenceMap: {
"fluid.prefs.textSize": {
"model.value": "value"
}
},
members: {
root: {
expander: {
"this": "{that}.container",
"method": "closest", // ensure that the correct document is being used. i.e. in an iframe
"args": ["html"]
}
}
},
invokers: {
set: {
funcName: "fluid.prefs.enactor.textSize.set",
args: ["{arguments}.0", "{that}", "{that}.getTextSizeInPx"]
},
getTextSizeInPx: {
args: ["{that}.root", "{that}.options.fontSizeMap"]
}
}
});
fluid.prefs.enactor.textSize.set = function (times, that, getTextSizeInPxFunc) {
times = times || 1;
// Calculating the initial size here rather than using a members expand because the "font-size"
// cannot be detected on hidden containers such as separated paenl iframe.
if (!that.initialSize) {
that.initialSize = getTextSizeInPxFunc();
}
if (that.initialSize) {
var targetSize = times * that.initialSize;
that.root.css("font-size", targetSize + "px");
}
};
/*******************************************************************************
* lineSpace
*
* Sets the line space on the container to the multiple provided.
*******************************************************************************/
// Note that the implementors need to provide the container for this view component
fluid.defaults("fluid.prefs.enactor.lineSpace", {
gradeNames: ["fluid.prefs.enactor.textRelatedSizer"],
preferenceMap: {
"fluid.prefs.lineSpace": {
"model.value": "value"
}
},
invokers: {
set: {
funcName: "fluid.prefs.enactor.lineSpace.set",
args: ["{that}", "{arguments}.0"]
},
getLineHeight: {
funcName: "fluid.prefs.enactor.lineSpace.getLineHeight",
args: "{that}.container"
},
getLineHeightMultiplier: {
funcName: "fluid.prefs.enactor.lineSpace.getLineHeightMultiplier",
args: [{expander: {func: "{that}.getLineHeight"}}, {expander: {func: "{that}.getTextSizeInPx"}}]
}
}
});
// Get the line-height of an element
// In IE8 and IE9 this will return the line-height multiplier
// In other browsers it will return the pixel value of the line height.
fluid.prefs.enactor.lineSpace.getLineHeight = function (container) {
return container.css("line-height");
};
// Interprets browser returned "line-height" value, either a string "normal", a number with "px" suffix or "undefined"
// into a numeric value in em.
// Return 0 when the given "lineHeight" argument is "undefined" (http://issues.fluidproject.org/browse/FLUID-4500).
fluid.prefs.enactor.lineSpace.getLineHeightMultiplier = function (lineHeight, fontSize) {
// Handle the given "lineHeight" argument is "undefined", which occurs when firefox detects
// "line-height" css value on a hidden container. (http://issues.fluidproject.org/browse/FLUID-4500)
if (!lineHeight) {
return 0;
}
// Needs a better solution. For now, "line-height" value "normal" is defaulted to 1.2em
// according to https://developer.mozilla.org/en/CSS/line-height
if (lineHeight === "normal") {
return 1.2;
}
// Continuing the work-around of jQuery + IE bug - http://bugs.jquery.com/ticket/2671
if (lineHeight.match(/[0-9]$/)) {
return Number(lineHeight);
}
return fluid.roundToDecimal(parseFloat(lineHeight) / fontSize, 2);
};
fluid.prefs.enactor.lineSpace.set = function (that, times) {
// Calculating the initial size here rather than using a members expand because the "line-height"
// cannot be detected on hidden containers such as separated panel iframe.
if (!that.initialSize) {
that.initialSize = that.getLineHeight();
that.lineHeightMultiplier = that.getLineHeightMultiplier();
}
// that.initialSize === 0 when the browser returned "lineHeight" css value is undefined,
// which occurs when firefox detects "line-height" value on a hidden container.
// @ See getLineHeightMultiplier() & http://issues.fluidproject.org/browse/FLUID-4500
if (that.lineHeightMultiplier) {
var targetLineSpace = that.initialSize === "normal" && times === 1 ? that.initialSize : times * that.lineHeightMultiplier;
that.container.css("line-height", targetLineSpace);
}
};
/*******************************************************************************
* tableOfContents
*
* To create and show/hide table of contents
*******************************************************************************/
// Note that the implementors need to provide the container for this view component
fluid.defaults("fluid.prefs.enactor.tableOfContents", {
gradeNames: ["fluid.prefs.enactor", "fluid.viewComponent"],
preferenceMap: {
"fluid.prefs.tableOfContents": {
"model.toc": "value"
}
},
tocTemplate: null, // must be supplied by implementors
tocMessage: null, // must be supplied by implementors
components: {
// TODO: When FLUID-6312 and FLUID-6300 are addressed, make sure that this message loader is updated when
// the locale is changed. It should also trigger the table of contents to re-render with the
// correct message bundle applied.
messageLoader: {
type: "fluid.resourceLoader",
options: {
resourceOptions: {
dataType: "json"
},
events: {
onResourcesLoaded: "{fluid.prefs.enactor.tableOfContents}.events.onMessagesLoaded"
}
}
},
tableOfContents: {
type: "fluid.tableOfContents",
container: "{fluid.prefs.enactor.tableOfContents}.container",
createOnEvent: "onCreateTOCReady",
options: {
listeners: {
"afterRender.boilAfterTocRender": "{fluid.prefs.enactor.tableOfContents}.events.afterTocRender"
},
strings: {
tocHeader: "{messageLoader}.resources.tocMessage.resourceText.tocHeader"
}
}
}
},
invokers: {
applyToc: {
funcName: "fluid.prefs.enactor.tableOfContents.applyToc",
args: ["{arguments}.0", "{that}"]
}
},
events: {
afterTocRender: null,
onCreateTOC: null,
onMessagesLoaded: null,
onCreateTOCReady: {
events: {
onCreateTOC: "onCreateTOC",
onMessagesLoaded: "onMessagesLoaded"
}
}
},
modelListeners: {
toc: {
listener: "{that}.applyToc",
args: ["{change}.value"],
namespace: "toggleToc"
}
},
distributeOptions: {
"tocEnactor.tableOfContents.ignoreForToC": {
source: "{that}.options.ignoreForToC",
target: "{that tableOfContents}.options.ignoreForToC"
},
"tocEnactor.tableOfContents.tocTemplate": {
source: "{that}.options.tocTemplate",
target: "{that > tableOfContents > levels}.options.resources.template.url"
},
"tocEnactor.messageLoader.tocMessage": {
source: "{that}.options.tocMessage",
target: "{that messageLoader}.options.resources.tocMessage"
}
}
});
fluid.prefs.enactor.tableOfContents.applyToc = function (value, that) {
if (value) {
if (that.tableOfContents) {
that.tableOfContents.show();
} else {
that.events.onCreateTOC.fire();
}
} else if (that.tableOfContents) {
that.tableOfContents.hide();
}
};
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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 YT */
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
/*******************************************************************************
* captions
*
* An enactor that is capable of enabling captions on embedded YouTube videos
*******************************************************************************/
fluid.defaults("fluid.prefs.enactor.captions", {
gradeNames: ["fluid.prefs.enactor", "fluid.viewComponent"],
preferenceMap: {
"fluid.prefs.captions": {
"model.enabled": "value"
}
},
events: {
onVideoElementLocated: null
},
selectors: {
videos: "iframe[src^=\"https://www.youtube.com/embed/\"]"
},
model: {
enabled: false
},
components: {
ytAPI: {
type: "fluid.prefs.enactor.captions.ytAPI"
}
},
dynamicComponents: {
player: {
type: "fluid.prefs.enactor.captions.youTubePlayer",
createOnEvent: "onVideoElementLocated",
container: "{arguments}.0",
options: {
model: {
captions: "{captions}.model.enabled"
}
}
}
},
listeners: {
"onCreate.initPlayers": "{that}.initPlayers"
},
invokers: {
initPlayers: {
funcName: "fluid.prefs.enactor.captions.initPlayers",
args: ["{that}", "{ytAPI}.notifyWhenLoaded", "{that}.dom.videos"]
}
}
});
/**
* When the YouTube API is available, the onVideoElementLocated event will fire for each video element located by
* the `videos` argument. Each of these event calls will fire with a jQuery object containing a single video
* element. This allows for initializing dynamicComponents (fluid.prefs.enactor.captions.youTubePlayer) for each
* video element.
*
* @param {Component} that - the component
* @param {Function} getYtApi - a function that returns a promise indicating if the YouTube API is available
* @param {jQuery|Element} videos - the videos to fire onVideoElementLocated events with
*
* @return {Promise} - A promise that follows the promise returned by the getYtApi function
*/
fluid.prefs.enactor.captions.initPlayers = function (that, getYtApi, videos) {
var promise = fluid.promise();
var ytAPINotice = getYtApi();
promise.then(function () {
$(videos).each(function (index, elm) {
that.events.onVideoElementLocated.fire($(elm));
});
});
fluid.promise.follow(ytAPINotice, promise);
return promise;
};
/*********************************************************************************************
* fluid.prefs.enactor.captions.window is a singleton component to be used for assigning *
* values onto the window object. *
*********************************************************************************************/
fluid.defaults("fluid.prefs.enactor.captions.ytAPI", {
gradeNames: ["fluid.component", "fluid.resolveRootSingle"],
singleRootType: "fluid.prefs.enactor.captions.window",
events: {
onYouTubeAPILoaded: null
},
members: {
global: window
},
invokers: {
notifyWhenLoaded: {
funcName: "fluid.prefs.enactor.captions.ytAPI.notifyWhenLoaded",
args: ["{that}"]
}
}
});
/**
* Used to determine when the YouTube API is available for use. It will test if the API is already available, and if
* not, will bind to the onYouTubeIframeAPIReady method that is called when the YouTube API finishes loading.
* When the YouTube API is ready, the promise will resolve an the onYouTubeAPILoaded event will fire.
*
* NOTE: After FLUID-6148 (https://issues.fluidproject.org/browse/FLUID-6148) is complete, it should be possible for
* the framework to handle this asynchrony directly in an expander for the player member in
* fluid.prefs.enactor.captions.youTubePlayer.
*
* @param {Component} that - the component itself
*
* @return {Promise} - a promise resolved after the YouTube API has loaded.
*/
fluid.prefs.enactor.captions.ytAPI.notifyWhenLoaded = function (that) {
var promise = fluid.promise();
promise.then(function () {
that.events.onYouTubeAPILoaded.fire();
}, function (error) {
fluid.log(fluid.logLevel.WARN, error);
});
if (fluid.get(window, ["YT", "Player"])) {
promise.resolve();
} else {
// the YouTube iframe api will call onYouTubeIframeAPIReady after the api has loaded
fluid.set(that.global, "onYouTubeIframeAPIReady", promise.resolve);
}
return promise;
};
/**
* See: https://developers.google.com/youtube/iframe_api_reference#Events for details on the YouTube player
* events. This includes when they are fired and what data is passed along.
*/
fluid.defaults("fluid.prefs.enactor.captions.youTubePlayer", {
gradeNames: ["fluid.viewComponent"],
events: {
onReady: null,
onStateChange: null,
onPlaybackQualityChange: null,
onPlaybackRateChange: null,
onError: null,
onApiChange: null
},
model: {
captions: false,
track: {}
},
members: {
player: {
expander: {
funcName: "fluid.prefs.enactor.captions.youTubePlayer.initYTPlayer",
args: ["{that}"]
}
},
tracklist: []
},
invokers: {
applyCaptions: {
funcName: "fluid.prefs.enactor.captions.youTubePlayer.applyCaptions",
args: ["{that}.player", "{that}.model.track", "{that}.model.captions"]
}
},
modelListeners: {
"setCaptions": {
listener: "{that}.applyCaptions",
path: ["captions", "track"],
excludeSource: "init"
}
},
listeners: {
"onApiChange.prepTrack": {
listener: "fluid.prefs.enactor.captions.youTubePlayer.prepTrack",
args: ["{that}", "{that}.player"]
},
"onApiChange.applyCaptions": {
listener: "{that}.applyCaptions",
priority: "after:prepTrack"
}
}
});
/**
* Adds the "enablejsapi=1" query parameter to the query string at the end of the src attribute.
* If "enablejsapi" already exists it will modify its value to 1. This is required for API access
* to the embedded YouTube video.
*
* @param {jQuery|Element} videoElm - a reference to the existing embedded YouTube video.
*/
fluid.prefs.enactor.captions.youTubePlayer.enableJSAPI = function (videoElm) {
videoElm = $(videoElm);
var url = new URL(videoElm.attr("src"));
url.searchParams.set("enablejsapi", 1);
videoElm.attr("src", url.toString());
};
/**
* An instance of a YouTube player from the YouTube iframe API
*
* @typedef {Object} YTPlayer
*/
/**
* Initializes the YT.Player using the existing embedded video (component's container). An ID will be added to the
* video element if one does not already exist.
*
* @param {Component} that - the component
* @return {YTPlayer} - an instance of a YouTube player controlling the embedded video
*/
fluid.prefs.enactor.captions.youTubePlayer.initYTPlayer = function (that) {
var id = fluid.allocateSimpleId(that.container);
fluid.prefs.enactor.captions.youTubePlayer.enableJSAPI(that.container);
return new YT.Player(id, {
events: {
onReady: that.events.onReady.fire,
onStateChange: that.events.onStateChange.fire,
onPlaybackQualityChange: that.events.onPlaybackQualityChange.fire,
onPlaybackRateChange: that.events.onPlaybackRateChange.fire,
onError: that.events.onError.fire,
onApiChange: that.events.onApiChange.fire
}
});
};
/**
* Enables/disables the captions on an embedded YouTube video. Requires that the player be initiallized and the API
* ready for use.
*
* @param {YTPlayer} player - an instance of a YouTube player
* @param {Object} track - a track object for the {YTPlayer}
* @param {Boolean} state - true - captions enabled; false - captions disabled.
*/
fluid.prefs.enactor.captions.youTubePlayer.applyCaptions = function (player, track, state) {
// The loadModule method from the player must be ready first. This is made available after
// the onApiChange event has fired.
if (player.loadModule) {
if (state) {
player.loadModule("captions");
player.setOption("captions", "track", track);
} else {
player.unloadModule("captions");
}
}
};
/**
* Prepares the track to be used when captions are enabled. It will use the first track in the tracklist, and update
* the "track" model path with it.
*
* @param {Component} that - the component
* @param {YTPlayer} player - an instance of a YouTube player
*/
fluid.prefs.enactor.captions.youTubePlayer.prepTrack = function (that, player) {
player.loadModule("captions");
var tracklist = player.getOption("captions", "tracklist");
if (tracklist.length && !that.tracklist.length) {
// set the tracklist and use first track for the captions
that.tracklist = tracklist;
that.applier.change("track", tracklist[0], "ADD", "prepTrack");
}
};
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
/*******************************************************************************
* letterSpace
*
* Sets the letter space on the container to the number of units to increase
* the letter space by. If a negative number is provided, the space between
* characters will decrease. Setting the value to 1 or unit to 0 will use the
* default letter space.
*******************************************************************************/
// Note that the implementors need to provide the container for this view component
fluid.defaults("fluid.prefs.enactor.letterSpace", {
gradeNames: ["fluid.prefs.enactor.spacingSetter"],
preferenceMap: {
"fluid.prefs.letterSpace": {
"model.value": "value"
}
},
cssProp: "letter-spacing"
});
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
/*******************************************************************************
* selfVoicing
*
* The enactor that enables self voicing of the DOM
*******************************************************************************/
fluid.defaults("fluid.prefs.enactor.selfVoicing", {
gradeNames: ["fluid.prefs.enactor", "fluid.viewComponent"],
preferenceMap: {
"fluid.prefs.speak": {
"model.enabled": "value"
}
},
selectors: {
controller: ".flc-prefs-selfVoicingWidget"
},
events: {
onInitOrator: null
},
modelListeners: {
"enabled": {
funcName: "fluid.prefs.enactor.selfVoicing.initOrator",
args: ["{that}", "{change}.value"],
namespace: "initOrator"
}
},
components: {
orator: {
type: "fluid.orator",
createOnEvent: "onInitOrator",
container: "{fluid.prefs.enactor.selfVoicing}.container",
options: {
model: {
enabled: "{selfVoicing}.model.enabled"
},
controller: {
parentContainer: "{fluid.prefs.enactor.selfVoicing}.dom.controller"
}
}
}
},
distributeOptions: [{
source: "{that}.options.orator",
target: "{that > orator}.options",
removeSource: true,
namespace: "oratorOpts"
}]
});
fluid.prefs.enactor.selfVoicing.initOrator = function (that, enabled) {
if (enabled && !that.orator) {
that.events.onInitOrator.fire();
}
};
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
/*******************************************************************************
* syllabification
*
* An enactor that is capable of breaking words down into syllables
*******************************************************************************/
/*
* `fluid.prefs.enactor.syllabification` makes use of the "hypher" library to split up words into their phonetic
* parts. Because different localizations may have different means of splitting up words, pattern files for the
* supported languages are used. The language patterns are pulled in dynamically based on the language codes
* encountered in the content. The language patterns available are configured through the patterns option,
* populated by the `fluid.prefs.enactor.syllabification.patterns` grade.
*/
fluid.defaults("fluid.prefs.enactor.syllabification", {
gradeNames: ["fluid.prefs.enactor", "fluid.prefs.enactor.syllabification.patterns", "fluid.viewComponent"],
preferenceMap: {
"fluid.prefs.syllabification": {
"model.enabled": "value"
}
},
selectors: {
separator: ".flc-syllabification-separator"
},
strings: {
languageUnavailable: "Syllabification not available for %lang",
patternLoadError: "The pattern file %src could not be loaded. %errorMsg"
},
markup: {
separator: "<span class=\"flc-syllabification-separator fl-syllabification-separator\"></span>"
},
model: {
enabled: false
},
events: {
afterParse: null,
afterSyllabification: null,
onParsedTextNode: null,
onNodeAdded: null,
onError: null
},
listeners: {
"afterParse.waitForHyphenators": {
listener: "fluid.prefs.enactor.syllabification.waitForHyphenators",
args: ["{that}"]
},
"onParsedTextNode.syllabify": {
listener: "{that}.apply",
args: ["{arguments}.0.node", "{arguments}.0.lang"]
},
"onNodeAdded.syllabify": {
listener: "{that}.parse",
args: ["{arguments}.0", "{that}.model.enabled"]
}
},
components: {
parser: {
type: "fluid.textNodeParser",
options: {
listeners: {
"afterParse.boil": "{syllabification}.events.afterParse",
"onParsedTextNode.boil": "{syllabification}.events.onParsedTextNode"
},
invokers: {
hasTextToRead: {
// apply to text nodes even if they have the ariaHidden attribute set
funcName: "fluid.textNodeParser.hasTextToRead",
args: ["{arguments}.0", true]
}
}
}
},
observer: {
type: "fluid.mutationObserver",
container: "{that}.container",
options: {
defaultObserveConfig: {
attributes: false
},
modelListeners: {
"{syllabification}.model.enabled": {
funcName: "fluid.prefs.enactor.syllabification.disconnectObserver",
priority: "before:setPresentation",
args: ["{that}", "{change}.value"],
namespace: "disconnectObserver"
}
},
listeners: {
"onNodeAdded.boil": "{syllabification}.events.onNodeAdded",
"{syllabification}.events.afterSyllabification": {
listener: "{that}.observe",
namespace: "enableObserver"
}
}
}
}
},
members: {
// `hyphenators` is a mapping of strings, representing the source paths of pattern files, to Promises
// linked to the resolutions of loading and initially applying those syllabification patterns.
hyphenators: {}
},
modelListeners: {
"enabled": {
listener: "{that}.setPresentation",
args: ["{that}.container", "{change}.value"],
namespace: "setPresentation"
}
},
invokers: {
apply: {
funcName: "fluid.prefs.enactor.syllabification.syllabify",
args: ["{that}", "{arguments}.0", "{arguments}.1"]
},
remove: {
funcName: "fluid.prefs.enactor.syllabification.removeSyllabification",
args: ["{that}"]
},
setPresentation: {
funcName: "fluid.prefs.enactor.syllabification.setPresentation",
args: ["{that}", "{arguments}.0", "{arguments}.1"]
},
parse: {
funcName: "fluid.prefs.enactor.syllabification.parse",
args: ["{that}", "{arguments}.0"]
},
createHyphenator: {
funcName: "fluid.prefs.enactor.syllabification.createHyphenator",
args: ["{that}", "{arguments}.0", "{arguments}.1"]
},
getHyphenator: {
funcName: "fluid.prefs.enactor.syllabification.getHyphenator",
args: ["{that}", "{arguments}.0"]
},
getPattern: "fluid.prefs.enactor.syllabification.getPattern",
hyphenateNode: {
funcName: "fluid.prefs.enactor.syllabification.hyphenateNode",
args: ["{arguments}.0", "{arguments}.1", "{that}.options.markup.separator"]
},
injectScript: {
this: "$",
method: "ajax",
args: [{
url: "{arguments}.0",
dataType: "script",
cache: true
}]
}
}
});
/**
* Only disconnect the observer if the state is set to false.
* This corresponds to the syllabification's `enabled` model path being set to false.
*
* @param {Component} that - an instance of `fluid.mutationObserver`
* @param {Boolean} state - if `false` disconnect, otherwise do nothing
*/
fluid.prefs.enactor.syllabification.disconnectObserver = function (that, state) {
if (!state) {
that.disconnect();
}
};
/**
* Wait for all hyphenators to be resolved. After they are resolved the `afterSyllabification` event is fired.
* If any of the hyphenator promises is rejected, the `onError` event is fired instead.
*
* @param {Component} that - an instance of `fluid.prefs.enactor.syllabification`
*
* @return {Promise} - returns the sequence promise; which is constructed from the hyphenator promises.
*/
fluid.prefs.enactor.syllabification.waitForHyphenators = function (that) {
var hyphenatorPromises = fluid.values(that.hyphenators);
var promise = fluid.promise.sequence(hyphenatorPromises);
promise.then(function () {
that.events.afterSyllabification.fire();
}, that.events.onError.fire);
return promise;
};
fluid.prefs.enactor.syllabification.parse = function (that, elm) {
elm = fluid.unwrap(elm);
elm = elm.nodeType === Node.ELEMENT_NODE ? $(elm) : $(elm.parentNode);
that.parser.parse(elm);
};
/**
* Creates a hyphenator instance making use of the pattern supplied by the path; which is injected into the Document
* if it hasn't already been loaded. If the pattern file cannot be loaded, the onError event is fired.
*
* @param {Component} that - an instance of `fluid.prefs.enactor.syllabification`
* @param {Object} pattern - the `file path` to the pattern file. The path may include a string template token to
* resolve a portion of its path from. The token will be resolved from the component's
* `terms` option. (e.g. "%patternPrefix/en-us.js");
* @param {String} lang - a valid BCP 47 language code. (NOTE: supported lang codes are defined in the
* `patterns`) option.
*
* @return {Promise} - If a hyphenator is successfully created, the promise is resolved with it. Otherwise it is
* resolved with undefined and the `onError` event fired.
*/
fluid.prefs.enactor.syllabification.createHyphenator = function (that, pattern, lang) {
var promise = fluid.promise();
var globalPath = ["Hypher", "languages", lang];
var hyphenator = fluid.getGlobalValue(globalPath);
// If the pattern file has already been loaded, return the hyphenator.
// This could happen if the pattern file is statically linked to the page.
if (hyphenator) {
promise.resolve(hyphenator);
return promise;
}
var src = fluid.stringTemplate(pattern, that.options.terms);
var injectPromise = that.injectScript(src);
injectPromise.then(function () {
hyphenator = fluid.getGlobalValue(globalPath);
promise.resolve(hyphenator);
}, function (error) {
var errorInfo = {
src: src,
errorMsg: typeof(error) === "string" ? error : ""
};
var errorMessage = fluid.stringTemplate(that.options.strings.patternLoadError, errorInfo);
fluid.log(fluid.logLevel.WARN, errorMessage, error);
that.events.onError.fire(errorMessage, error);
//TODO: A promise rejection would be more appropriate. However, we need to know when all of the hyphenators
// have attempted to load and apply syllabification. The current promise utility,
// fluid.promise.sequence, will reject the whole sequence if a promise is rejected, and prevent us from
// knowing if all of the hyphenators have been attempted. We should be able to improve this
// implementation once https://issues.fluidproject.org/browse/FLUID-5938 has been resolved.
//
// If the pattern file could not be loaded, resolve the promise without a hyphenator (undefined).
promise.resolve();
});
return promise;
};
/**
* Information about a pattern, including the resolved language code and the file path to the pattern file.
*
* @typedef {Object} PatternInfo
* @property {String} lang - The resolved language code
* @property {String|Undefined} src - The file path to the pattern file for the resolved language. If no pattern
* file is available, the value should be `undefined`.
*/
/**
* Assembles an Object containing the information for locating the pattern file. If a pattern for the specific
* requested language code cannot be located, it will attempt to locate a fall back, by looking for a pattern
* supporting the generic language code. If no pattern can be found, `undefined` is returned as the `src` value.
*
*
* @param {String} lang - a valid BCP 47 language code. (NOTE: supported lang codes are defined in the
* `patterns`) option.
* @param {Object.<String, String>} patterns - an object mapping language codes to file paths for the pattern files. For example:
* {"en": "./patterns/en-us.js"}
*
* @return {PatternInfo} - returns a PatternInfo Object for the resolved language code. If a pattern file is not
* available for the language, the `src` property will be `undefined`.
*/
fluid.prefs.enactor.syllabification.getPattern = function (lang, patterns) {
var src = patterns[lang];
if (!src) {
lang = lang.split("-")[0];
src = patterns[lang];
}
return {
lang: lang,
src: src
};
};
/**
* Retrieves a promise for the appropriate hyphenator. If a hyphenator has not already been created, it will attempt
* to create one and assign the related promise to the `hyphenators` member for future retrieval.
*
* When creating a hyphenator, it first checks if there is configuration for the specified `lang`. If that fails,
* it attempts to fall back to a less specific localization.
*
* @param {Component} that - an instance of `fluid.prefs.enactor.syllabification`
* @param {String} lang - a valid BCP 47 language code. (NOTE: supported lang codes are defined in the
* `patterns`) option.
*
* @return {Promise} - returns a promise. If a hyphenator is successfully created, it is resolved with it.
* Otherwise, it resolves with undefined.
*/
fluid.prefs.enactor.syllabification.getHyphenator = function (that, lang) {
//TODO: For all of the instances where an empty promise is resolved, a promise rejection would be more
// appropriate. However, we need to know when all of the hyphenators have attempted to load and apply
// syllabification. The current promise utility, fluid.promise.sequence, will reject the whole sequence if
// a promise is rejected, and prevent us from knowing if all of the hyphenators have been attempted. We
// should be able to improve this implementation once https://issues.fluidproject.org/browse/FLUID-5938 has
// been resolved.
var promise = fluid.promise();
var hyphenatorPromise;
if (!lang) {
promise.resolve();
return promise;
}
var pattern = that.getPattern(lang.toLowerCase(), that.options.patterns);
if (!pattern.src) {
hyphenatorPromise = promise;
promise.resolve();
return promise;
}
if (that.hyphenators[pattern.src]) {
return that.hyphenators[pattern.src];
}
hyphenatorPromise = that.createHyphenator(pattern.src, pattern.lang);
fluid.promise.follow(hyphenatorPromise, promise);
that.hyphenators[pattern.src] = hyphenatorPromise;
return promise;
};
fluid.prefs.enactor.syllabification.syllabify = function (that, node, lang) {
var hyphenatorPromise = that.getHyphenator(lang);
hyphenatorPromise.then(function (hyphenator) {
that.hyphenateNode(hyphenator, node);
});
};
fluid.prefs.enactor.syllabification.hyphenateNode = function (hyphenator, node, separatorMarkup) {
if (!hyphenator) {
return;
}
// remove \u200B characters added hyphenateText
var hyphenated = hyphenator.hyphenateText(node.textContent).replace(/\u200B/gi, "");
// split words on soft hyphens
var segs = hyphenated.split("\u00AD");
// remove the last segment as we only need to place separators in between the parts of the words
segs.pop();
fluid.each(segs, function (seg) {
var separator = $(separatorMarkup)[0];
node = node.splitText(seg.length);
node.parentNode.insertBefore(separator, node);
});
};
/**
* Collapses adjacent text nodes within an element.
* Similar to NODE.normalize() but works in IE 11.
* See: https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/8727426/
*
* @param {jQuery|DomElement} elm - The element to normalize.
*/
fluid.prefs.enactor.syllabification.normalize = function (elm) {
elm = fluid.unwrap(elm);
var childNode = elm.childNodes[0];
while (childNode && childNode.nextSibling) {
var nextSibling = childNode.nextSibling;
if (childNode.nodeType === Node.TEXT_NODE && nextSibling.nodeType === Node.TEXT_NODE) {
childNode.textContent += nextSibling.textContent;
elm.removeChild(nextSibling);
} else {
childNode = nextSibling;
}
}
};
fluid.prefs.enactor.syllabification.removeSyllabification = function (that) {
that.locate("separator").each(function (index, elm) {
var parent = elm.parentNode;
$(elm).remove();
// Because Node.normalize doesn't work properly in IE 11, we use a custom function
// to normalize the text nodes in the parent.
fluid.prefs.enactor.syllabification.normalize(parent);
});
};
fluid.prefs.enactor.syllabification.setPresentation = function (that, elm, state) {
if (state) {
that.parse(elm);
} else {
that.remove();
}
};
/**********************************************************************
* Language Pattern File Configuration
*
*
* Supplies the source paths for the language pattern files used to
* separate words into their phonetic parts.
**********************************************************************/
fluid.defaults("fluid.prefs.enactor.syllabification.patterns", {
terms: {
patternPrefix: "../../../lib/hypher/patterns"
},
patterns: {
be: "%patternPrefix/bg.js",
bn: "%patternPrefix/bn.js",
ca: "%patternPrefix/ca.js",
cs: "%patternPrefix/cs.js",
da: "%patternPrefix/da.js",
de: "%patternPrefix/de.js",
el: "%patternPrefix/el-monoton.js",
"el-monoton": "%patternPrefix/el-monoton.js",
"el-polyton": "%patternPrefix/el-polyton.js",
en: "%patternPrefix/en-us.js",
"en-gb": "%patternPrefix/en-gb.js",
"en-us": "%patternPrefix/en-us.js",
es: "%patternPrefix/es.js",
fi: "%patternPrefix/fi.js",
fr: "%patternPrefix/fr.js",
grc: "%patternPrefix/grc.js",
gu: "%patternPrefix/gu.js",
hi: "%patternPrefix/hi.js",
hu: "%patternPrefix/hu.js",
hy: "%patternPrefix/hy.js",
is: "%patternPrefix/is.js",
it: "%patternPrefix/it.js",
kn: "%patternPrefix/kn.js",
la: "%patternPrefix/la.js",
lt: "%patternPrefix/lt.js",
lv: "%patternPrefix/lv.js",
ml: "%patternPrefix/ml.js",
nb: "%patternPrefix/nb-no.js",
"nb-no": "%patternPrefix/nb-no.js",
no: "%patternPrefix/nb-no.js",
nl: "%patternPrefix/nl.js",
or: "%patternPrefix/or.js",
pa: "%patternPrefix/pa.js",
pl: "%patternPrefix/pl.js",
pt: "%patternPrefix/pt.js",
ru: "%patternPrefix/ru.js",
sk: "%patternPrefix/sk.js",
sl: "%patternPrefix/sl.js",
sv: "%patternPrefix/sv.js",
ta: "%patternPrefix/ta.js",
te: "%patternPrefix/te.js",
tr: "%patternPrefix/tr.js",
uk: "%patternPrefix/uk.js"
}
});
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
/*******************************************************************************
* Localization
*
* The enactor to change the locale shown according to the value
*
* This grade is resolvable from the root to allow for setting up of model relays
* from other components on a page that may want to be notified of a language
* change and update their own UI automatically.
*******************************************************************************/
fluid.defaults("fluid.prefs.enactor.localization", {
gradeNames: ["fluid.prefs.enactor", "fluid.contextAware", "fluid.resolveRoot"],
preferenceMap: {
"fluid.prefs.localization": {
"model.lang": "value"
}
},
contextAwareness: {
localeChange: {
checks: {
// This check determines if the enactor is being run inside of the separated panel's iframe.
// At the moment, all enactors are copied into the iframe to apply settings to the panel as well.
// However, the strings for the panel will be localized through the prefsEditorLoader and do not
// require the iframe URL to change. When in the panel, we do not run the urlPathLocale changes.
inPanel: {
contextValue: "{iframeRenderer}.id",
// The following undefined grade is needed to prevent the `urlPath` check from supplying its
// grade even when the `inPanel` check passes.
gradeNames: "fluid.prefs.enactor.localization.inPanel"
},
urlPath: {
contextValue: "{localization}.options.localizationScheme",
equals: "urlPath",
gradeNames: "fluid.prefs.enactor.localization.urlPathLocale",
priority: "after:inPanel"
}
}
}
}
});
/*******************************************************************************
* URL Path
*
* Changes the URL path to specify which language should be displayed. Useful
* if languages are served at different URLs based on a language resource.
* E.g. www.example.com/about/ -> www.example.com/fr/about/
*******************************************************************************/
fluid.defaults("fluid.prefs.enactor.localization.urlPathLocale", {
langMap: {}, // must be supplied by integrator
langSegValues: {
expander: {
funcName: "fluid.values",
args: ["{that}.options.langMap"]
}
},
// langSegIndex: 1, should be supplied by the integrator. Will default to 1 in `fluid.prefs.enactor.localization.urlPathLocale.updatePathname`
modelRelay: [{
target: "urlLangSeg",
singleTransform: {
type: "fluid.transforms.valueMapper",
defaultInput: "{that}.model.lang",
match: "{that}.options.langMap"
}
}],
modelListeners: {
urlLangSeg: {
funcName: "{that}.updatePathname",
args: ["{change}.value"],
namespace: "updateURLPathname"
}
},
invokers: {
updatePathname: {
funcName: "fluid.prefs.enactor.localization.urlPathLocale.updatePathname",
args: ["{that}", "{arguments}.0", "{that}.options.langSegValues", "{that}.options.langSegIndex"]
},
getPathname: "fluid.prefs.enactor.localization.urlPathLocale.getPathname",
setPathname: "fluid.prefs.enactor.localization.urlPathLocale.setPathname"
}
});
/**
* A simple wrapper around the location.pathname getter.
*
* @return {String} - If the `pathname` argument is not provided, the current pathname is returned
*/
fluid.prefs.enactor.localization.urlPathLocale.getPathname = function () {
return location.pathname;
};
/**
* A simple wrapper around the location.pathname setter.
*
* @param {String} pathname - The pathname to set.
*/
fluid.prefs.enactor.localization.urlPathLocale.setPathname = function (pathname) {
location.pathname = pathname;
};
/**
* Modifies the URL Path to navigate to the specified localized version of the page. If the "default" language is
* selected. The function exits without modifying the URL. This allows for the server to automatically, or the user
* to manually, navigate to a localized page when a language preference hasn't been set.
*
* @param {Component} that - an instance of `fluid.prefs.enactor.localization.urlPathLocale`
* @param {String} urlLangSeg - a language value used in the URL pathname
* @param {Object} langSegValues - An array of the potential `urlLangSeg` values that can be set.
* @param {Integer} langSegIndex - (Optional) An index into the path where the language resource identifier is held.
* By default this value is 1, which represents the first path segment.
*/
fluid.prefs.enactor.localization.urlPathLocale.updatePathname = function (that, urlLangSeg, langSegValues, langSegIndex) {
if (fluid.isValue(urlLangSeg)) {
langSegIndex = langSegIndex || 1;
var pathname = that.getPathname();
var pathSegs = pathname.split("/");
var currentLang = pathSegs[langSegIndex];
var hasLang = !!currentLang && langSegValues.indexOf(currentLang) >= 0;
if (hasLang) {
if (urlLangSeg) {
pathSegs[langSegIndex] = urlLangSeg;
} else {
if (langSegIndex === pathSegs.length - 1) {
pathSegs.pop();
} else {
pathSegs.splice(langSegIndex, 1);
}
}
} else if (urlLangSeg) {
pathSegs.splice(langSegIndex, 0, urlLangSeg);
}
var newPathname = pathSegs.join("/");
if (newPathname !== pathname) {
that.setPathname(newPathname);
}
}
};
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
/*******************************************************************************
* wordSpace
*
* Sets the word space on the container to the number of units to increase
* the word space by. If a negative number is provided, the space between
* characters will decrease. Setting the value to 1 or unit to 0 will use the
* default word space.
*******************************************************************************/
// Note that the implementors need to provide the container for this view component
fluid.defaults("fluid.prefs.enactor.wordSpace", {
gradeNames: ["fluid.prefs.enactor.spacingSetter"],
preferenceMap: {
"fluid.prefs.wordSpace": {
"model.value": "value"
}
},
cssProp: "word-spacing"
});
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
/*******************************************************************************
* Starter prefsEditor Model
*
* Provides the default values for the starter prefsEditor model
*******************************************************************************/
fluid.defaults("fluid.prefs.initialModel.starter", {
gradeNames: ["fluid.prefs.initialModel"],
members: {
// TODO: This information is supposed to be generated from the JSON
// schema describing various preferences. For now it's kept in top
// level prefsEditor to avoid further duplication.
initialModel: {
preferences: {
textFont: "default", // key from classname map
theme: "default", // key from classname map
textSize: 1, // in points
lineSpace: 1, // in ems
toc: false, // boolean
inputs: false // boolean
}
}
}
});
/*******************************************************************************
* CSSClassEnhancerBase
*
* Provides the map between the settings and css classes to be applied.
* Used as a UIEnhancer base grade that can be pulled in as requestd.
*******************************************************************************/
fluid.defaults("fluid.uiEnhancer.cssClassEnhancerBase", {
gradeNames: ["fluid.component"],
classnameMap: {
"textFont": {
"default": "",
"times": "fl-font-times",
"comic": "fl-font-comic-sans",
"arial": "fl-font-arial",
"verdana": "fl-font-verdana",
"open-dyslexic": "fl-font-open-dyslexic"
},
"theme": {
"default": "fl-theme-prefsEditor-default",
"bw": "fl-theme-bw",
"wb": "fl-theme-wb",
"by": "fl-theme-by",
"yb": "fl-theme-yb",
"lgdg": "fl-theme-lgdg",
"gd": "fl-theme-gd",
"gw": "fl-theme-gw",
"bbr": "fl-theme-bbr"
},
"inputs": "fl-input-enhanced"
}
});
/*******************************************************************************
* BrowserTextEnhancerBase
*
* Provides the default font size translation between the strings and actual pixels.
* Used as a UIEnhancer base grade that can be pulled in as requestd.
*******************************************************************************/
fluid.defaults("fluid.uiEnhancer.browserTextEnhancerBase", {
gradeNames: ["fluid.component"],
fontSizeMap: {
"xx-small": "9px",
"x-small": "11px",
"small": "13px",
"medium": "15px",
"large": "18px",
"x-large": "23px",
"xx-large": "30px"
}
});
/*******************************************************************************
* UI Enhancer Starter Enactors
*
* A grade component for UIEnhancer. It is a collection of default UI Enhancer
* action ants.
*******************************************************************************/
fluid.defaults("fluid.uiEnhancer.starterEnactors", {
gradeNames: ["fluid.uiEnhancer", "fluid.uiEnhancer.cssClassEnhancerBase", "fluid.uiEnhancer.browserTextEnhancerBase"],
model: "{fluid.prefs.initialModel}.initialModel.preferences",
components: {
textSize: {
type: "fluid.prefs.enactor.textSize",
container: "{uiEnhancer}.container",
options: {
fontSizeMap: "{uiEnhancer}.options.fontSizeMap",
model: {
value: "{uiEnhancer}.model.textSize"
}
}
},
textFont: {
type: "fluid.prefs.enactor.textFont",
container: "{uiEnhancer}.container",
options: {
classes: "{uiEnhancer}.options.classnameMap.textFont",
model: {
value: "{uiEnhancer}.model.textFont"
}
}
},
lineSpace: {
type: "fluid.prefs.enactor.lineSpace",
container: "{uiEnhancer}.container",
options: {
fontSizeMap: "{uiEnhancer}.options.fontSizeMap",
model: {
value: "{uiEnhancer}.model.lineSpace"
}
}
},
contrast: {
type: "fluid.prefs.enactor.contrast",
container: "{uiEnhancer}.container",
options: {
classes: "{uiEnhancer}.options.classnameMap.theme",
model: {
value: "{uiEnhancer}.model.theme"
}
}
},
enhanceInputs: {
type: "fluid.prefs.enactor.enhanceInputs",
container: "{uiEnhancer}.container",
options: {
cssClass: "{uiEnhancer}.options.classnameMap.inputs",
model: {
value: "{uiEnhancer}.model.inputs"
}
}
},
tableOfContents: {
type: "fluid.prefs.enactor.tableOfContents",
container: "{uiEnhancer}.container",
options: {
tocTemplate: "{uiEnhancer}.options.tocTemplate",
tocMessage: "{uiEnhancer}.options.tocMessage",
model: {
toc: "{uiEnhancer}.model.toc"
}
}
}
}
});
/*********************************************************************************************************
* Starter Settings Panels
*
* A collection of all the default Preferences Editorsetting panels.
*********************************************************************************************************/
fluid.defaults("fluid.prefs.starterPanels", {
gradeNames: ["fluid.prefs.prefsEditor"],
selectors: {
textSize: ".flc-prefsEditor-text-size",
textFont: ".flc-prefsEditor-text-font",
lineSpace: ".flc-prefsEditor-line-space",
contrast: ".flc-prefsEditor-contrast",
layoutControls: ".flc-prefsEditor-layout-controls",
enhanceInputs: ".flc-prefsEditor-enhanceInputs"
},
components: {
textSize: {
type: "fluid.prefs.panel.textSize",
container: "{prefsEditor}.dom.textSize",
createOnEvent: "onPrefsEditorMarkupReady",
options: {
gradeNames: "fluid.prefs.prefsEditorConnections",
model: {
value: "{prefsEditor}.model.preferences.textSize"
},
messageBase: "{messageLoader}.resources.textSize.resourceText",
resources: {
template: "{templateLoader}.resources.textSize"
},
step: 0.1,
range: {
min: 1,
max: 2
}
}
},
lineSpace: {
type: "fluid.prefs.panel.lineSpace",
container: "{prefsEditor}.dom.lineSpace",
createOnEvent: "onPrefsEditorMarkupReady",
options: {
gradeNames: "fluid.prefs.prefsEditorConnections",
model: {
value: "{prefsEditor}.model.preferences.lineSpace"
},
messageBase: "{messageLoader}.resources.lineSpace.resourceText",
resources: {
template: "{templateLoader}.resources.lineSpace"
},
step: 0.1,
range: {
min: 1,
max: 2
}
}
},
textFont: {
type: "fluid.prefs.panel.textFont",
container: "{prefsEditor}.dom.textFont",
createOnEvent: "onPrefsEditorMarkupReady",
options: {
gradeNames: "fluid.prefs.prefsEditorConnections",
classnameMap: "{uiEnhancer}.options.classnameMap",
model: {
value: "{prefsEditor}.model.preferences.textFont"
},
messageBase: "{messageLoader}.resources.textFont.resourceText",
resources: {
template: "{templateLoader}.resources.textFont"
},
stringArrayIndex: {
textFont: [
"textFont-default",
"textFont-times",
"textFont-comic",
"textFont-arial",
"textFont-verdana",
"textFont-open-dyslexic"
]
},
controlValues: {
textFont: ["default", "times", "comic", "arial", "verdana", "open-dyslexic"]
}
}
},
contrast: {
type: "fluid.prefs.panel.contrast",
container: "{prefsEditor}.dom.contrast",
createOnEvent: "onPrefsEditorMarkupReady",
options: {
gradeNames: "fluid.prefs.prefsEditorConnections",
classnameMap: "{uiEnhancer}.options.classnameMap",
model: {
value: "{prefsEditor}.model.preferences.theme"
},
messageBase: "{messageLoader}.resources.contrast.resourceText",
resources: {
template: "{templateLoader}.resources.contrast"
},
stringArrayIndex: {
theme: [
"contrast-default",
"contrast-bw",
"contrast-wb",
"contrast-by",
"contrast-yb",
"contrast-lgdg",
"contrast-gw",
"contrast-gd",
"contrast-bbr"
]
},
controlValues: {
theme: ["default", "bw", "wb", "by", "yb", "lgdg", "gw", "gd", "bbr"]
}
}
},
layoutControls: {
type: "fluid.prefs.panel.layoutControls",
container: "{prefsEditor}.dom.layoutControls",
createOnEvent: "onPrefsEditorMarkupReady",
options: {
gradeNames: "fluid.prefs.prefsEditorConnections",
model: {
value: "{prefsEditor}.model.preferences.toc"
},
messageBase: "{messageLoader}.resources.layoutControls.resourceText",
resources: {
template: "{templateLoader}.resources.layoutControls"
}
}
},
enhanceInputs: {
type: "fluid.prefs.panel.enhanceInputs",
container: "{prefsEditor}.dom.enhanceInputs",
createOnEvent: "onPrefsEditorMarkupReady",
options: {
gradeNames: "fluid.prefs.prefsEditorConnections",
model: {
value: "{prefsEditor}.model.preferences.inputs"
},
messageBase: "{messageLoader}.resources.enhanceInputs.resourceText",
resources: {
template: "{templateLoader}.resources.enhanceInputs"
}
}
}
}
});
/******************************
* Starter Template Loader
******************************/
/**
* A template loader component that expands the resources blocks for loading resources used by starterPanels
*
* @param options {Object}
*/
fluid.defaults("fluid.prefs.starterTemplateLoader", {
gradeNames: ["fluid.resourceLoader"],
resources: {
textSize: "%templatePrefix/PrefsEditorTemplate-textSize.html",
lineSpace: "%templatePrefix/PrefsEditorTemplate-lineSpace.html",
textFont: "%templatePrefix/PrefsEditorTemplate-textFont.html",
contrast: "%templatePrefix/PrefsEditorTemplate-contrast.html",
layoutControls: "%templatePrefix/PrefsEditorTemplate-layout.html",
enhanceInputs: "%templatePrefix/PrefsEditorTemplate-enhanceInputs.html"
}
});
fluid.defaults("fluid.prefs.starterSeparatedPanelTemplateLoader", {
gradeNames: ["fluid.prefs.starterTemplateLoader"],
resources: {
prefsEditor: "%templatePrefix/SeparatedPanelPrefsEditor.html"
}
});
fluid.defaults("fluid.prefs.starterFullPreviewTemplateLoader", {
gradeNames: ["fluid.prefs.starterTemplateLoader"],
resources: {
prefsEditor: "%templatePrefix/FullPreviewPrefsEditor.html"
}
});
fluid.defaults("fluid.prefs.starterFullNoPreviewTemplateLoader", {
gradeNames: ["fluid.prefs.starterTemplateLoader"],
resources: {
prefsEditor: "%templatePrefix/FullNoPreviewPrefsEditor.html"
}
});
/******************************
* Starter Message Loader
******************************/
/**
* A message loader component that expands the resources blocks for loading messages for starter panels
*
* @param options {Object}
*/
fluid.defaults("fluid.prefs.starterMessageLoader", {
gradeNames: ["fluid.resourceLoader"],
resources: {
prefsEditor: "%messagePrefix/prefsEditor.json",
textSize: "%messagePrefix/textSize.json",
textFont: "%messagePrefix/textFont.json",
lineSpace: "%messagePrefix/lineSpace.json",
contrast: "%messagePrefix/contrast.json",
layoutControls: "%messagePrefix/tableOfContents.json",
enhanceInputs: "%messagePrefix/enhanceInputs.json"
}
});
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
/************************************************************************************
* Scrolling Panel Prefs Editor: *
* This is a mixin grade to be applied to a fluid.prefs.prefsEditor type component. *
* Typically used for responsive small screen presentations of the separated panel *
* to allow for scrolling by clicking on left/right arrows *
************************************************************************************/
fluid.defaults("fluid.prefs.arrowScrolling", {
gradeNames: ["fluid.modelComponent"],
selectors: {
// panels: "", // should be supplied by the fluid.prefs.prefsEditor grade.
scrollContainer: ".flc-prefsEditor-scrollContainer"
},
onScrollDelay: 100, // in ms, used to set the delay for debouncing the scroll event relay
model: {
// panelMaxIndex: null, // determined by the number of panels calculated after the onPrefsEditorMarkupReady event fired
// Due to FLUID-6249 ( https://issues.fluidproject.org/browse/FLUID-6249 ) the default value for panelIndex
// needs to be commented out or it will interfere with reading in the panelIndex value saved in the store.
// panelIndex: 0 // the index of the panel to open on
},
events: {
beforeReset: null, // should be fired by the fluid.prefs.prefsEditor grade
onScroll: null
},
modelRelay: {
target: "panelIndex",
forward: {excludeSource: "init"},
namespace: "limitPanelIndex",
singleTransform: {
type: "fluid.transforms.limitRange",
input: "{that}.model.panelIndex",
min: 0,
max: "{that}.model.panelMaxIndex"
}
},
modelListeners: {
"panelIndex": {
listener: "fluid.prefs.arrowScrolling.scrollToPanel",
args: ["{that}", "{change}.value"],
excludeSource: ["scrollEvent"],
namespace: "scrollToPanel"
}
},
listeners: {
"onReady.scrollEvent": {
"this": "{that}.dom.scrollContainer",
method: "scroll",
args: [{
expander: {
// Relaying the scroll event to onScroll but debounced to reduce the rate of fire. A high rate
// of fire may negatively effect performance for complex handlers.
func: "fluid.debounce",
args: ["{that}.events.onScroll.fire", "{that}.options.onScrollDelay"]
}
}]
},
"onReady.windowResize": {
"this": window,
method: "addEventListener",
args: ["resize", "{that}.events.onSignificantDOMChange.fire"]
},
"onDestroy.removeWindowResize": {
"this": window,
method: "removeEventListener",
args: ["resize", "{that}.events.onSignificantDOMChange.fire"]
},
// Need to set panelMaxIndex after onPrefsEditorMarkupReady to ensure that the template has been
// rendered before we try to get the number of panels.
"onPrefsEditorMarkupReady.setPanelMaxIndex": {
changePath: "panelMaxIndex",
value: {
expander: {
funcName: "fluid.prefs.arrowScrolling.calculatePanelMaxIndex",
args: ["{that}.dom.panels"]
}
}
},
"beforeReset.resetPanelIndex": {
listener: "{that}.applier.fireChangeRequest",
args: {path: "panelIndex", value: 0, type: "ADD", source: "reset"}
},
"onScroll.setPanelIndex": {
changePath: "panelIndex",
value: {
expander: {
funcName: "fluid.prefs.arrowScrolling.getClosestPanelIndex",
args: "{that}.dom.panels"
}
},
source: "scrollEvent"
}
},
invokers: {
eventToScrollIndex: {
funcName: "fluid.prefs.arrowScrolling.eventToScrollIndex",
args: ["{that}", "{arguments}.0"]
}
},
distributeOptions: {
"arrowScrolling.panel.listeners.bindScrollArrows": {
record: {
"afterRender.bindScrollArrows": {
"this": "{that}.dom.header",
method: "click",
args: ["{prefsEditor}.eventToScrollIndex"]
}
},
target: "{that > fluid.prefs.panel}.options.listeners"
}
}
});
fluid.prefs.arrowScrolling.calculatePanelMaxIndex = function (panels) {
return Math.max(0, panels.length - 1);
};
fluid.prefs.arrowScrolling.eventToScrollIndex = function (that, event) {
event.preventDefault();
var target = $(event.target);
var midPoint = target.width() / 2;
var currentIndex = that.model.panelIndex || 0;
var scrollToIndex = currentIndex + (event.offsetX < midPoint ? -1 : 1);
that.applier.change("panelIndex", scrollToIndex, "ADD", "eventToScrollIndex");
};
fluid.prefs.arrowScrolling.scrollToPanel = function (that, panelIndex) {
panelIndex = panelIndex || 0;
var panels = that.locate("panels");
var scrollContainer = that.locate("scrollContainer");
var panel = panels.eq(panelIndex);
// only attempt to scroll the container if the panel exists and has been rendered.
if (panel.width()) {
scrollContainer.scrollLeft(scrollContainer.scrollLeft() + panels.eq(panelIndex).offset().left);
}
};
fluid.prefs.arrowScrolling.getClosestPanelIndex = function (panels) {
var panelArray = fluid.transform(panels, function (panel, idx) {
return {
index: idx,
offset: Math.abs($(panel).offset().left)
};
});
panelArray.sort(function (a, b) {
return a.offset - b.offset;
});
return fluid.get(panelArray, ["0", "index"]) || 0;
};
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
fluid.registerNamespace("fluid.dom");
fluid.dom.getDocumentHeight = function (dokkument) {
var body = $("body", dokkument)[0];
return body.offsetHeight;
};
/*******************************************************
* Separated Panel Preferences Editor Top Level Driver *
*******************************************************/
fluid.defaults("fluid.prefs.separatedPanel", {
gradeNames: ["fluid.prefs.prefsEditorLoader", "fluid.contextAware"],
events: {
afterRender: null,
onReady: null,
onCreateSlidingPanelReady: {
events: {
iframeRendered: "afterRender",
onPrefsEditorMessagesLoaded: "onPrefsEditorMessagesLoaded"
}
},
templatesAndIframeReady: {
events: {
iframeReady: "afterRender",
templatesLoaded: "onPrefsEditorTemplatesLoaded",
messagesLoaded: "onPrefsEditorMessagesLoaded"
}
}
},
lazyLoad: false,
contextAwareness: {
lazyLoad: {
checks: {
lazyLoad: {
contextValue: "{fluid.prefs.separatedPanel}.options.lazyLoad",
gradeNames: "fluid.prefs.separatedPanel.lazyLoad"
}
}
}
},
selectors: {
reset: ".flc-prefsEditor-reset",
iframe: ".flc-prefsEditor-iframe"
},
listeners: {
"onReady.bindEvents": {
listener: "fluid.prefs.separatedPanel.bindEvents",
args: ["{separatedPanel}.prefsEditor", "{iframeRenderer}.iframeEnhancer", "{separatedPanel}"]
},
"onCreate.hideReset": {
listener: "fluid.prefs.separatedPanel.hideReset",
args: ["{separatedPanel}"]
}
},
invokers: {
bindReset: {
funcName: "fluid.bind",
args: ["{separatedPanel}.dom.reset", "click", "{arguments}.0"]
}
},
components: {
slidingPanel: {
type: "fluid.slidingPanel",
container: "{separatedPanel}.container",
createOnEvent: "onCreateSlidingPanelReady",
options: {
gradeNames: ["fluid.prefs.msgLookup"],
strings: {
showText: "{that}.msgLookup.slidingPanelShowText",
hideText: "{that}.msgLookup.slidingPanelHideText",
showTextAriaLabel: "{that}.msgLookup.showTextAriaLabel",
hideTextAriaLabel: "{that}.msgLookup.hideTextAriaLabel",
panelLabel: "{that}.msgLookup.slidingPanelPanelLabel"
},
invokers: {
operateShow: {
funcName: "fluid.prefs.separatedPanel.showPanel",
args: ["{that}.dom.panel", "{that}.events.afterPanelShow.fire"],
// override default implementation
"this": null,
"method": null
},
operateHide: {
funcName: "fluid.prefs.separatedPanel.hidePanel",
args: ["{that}.dom.panel", "{iframeRenderer}.iframe", "{that}.events.afterPanelHide.fire"],
// override default implementation
"this": null,
"method": null
}
},
components: {
msgResolver: {
type: "fluid.messageResolver",
options: {
messageBase: "{messageLoader}.resources.prefsEditor.resourceText"
}
}
}
}
},
iframeRenderer: {
type: "fluid.prefs.separatedPanel.renderIframe",
container: "{separatedPanel}.dom.iframe",
options: {
events: {
afterRender: "{separatedPanel}.events.afterRender"
},
components: {
iframeEnhancer: {
type: "fluid.uiEnhancer",
container: "{iframeRenderer}.renderPrefsEditorContainer",
createOnEvent: "afterRender",
options: {
gradeNames: ["{pageEnhancer}.uiEnhancer.options.userGrades"],
jQuery: "{iframeRenderer}.jQuery",
tocTemplate: "{pageEnhancer}.uiEnhancer.options.tocTemplate",
inSeparatedPanel: true
}
}
}
}
},
prefsEditor: {
createOnEvent: "templatesAndIframeReady",
container: "{iframeRenderer}.renderPrefsEditorContainer",
options: {
gradeNames: ["fluid.prefs.uiEnhancerRelay", "fluid.prefs.arrowScrolling"],
// ensure that model and applier are available to users at top level
model: {
preferences: "{separatedPanel}.model.preferences",
panelIndex: "{separatedPanel}.model.panelIndex",
panelMaxIndex: "{separatedPanel}.model.panelMaxIndex",
// The `local` model path is used by the `fluid.remoteModelComponent` grade
// for persisting and synchronizing model values with remotely stored data.
// Below, the panelIndex is being tracked for such persistence and synchronization.
local: {
panelIndex: "{that}.model.panelIndex"
}
},
autoSave: true,
events: {
onSignificantDOMChange: null,
updateEnhancerModel: "{that}.events.modelChanged"
},
modelListeners: {
"panelIndex": [{
listener: "fluid.prefs.prefsEditor.handleAutoSave",
args: ["{that}"],
namespace: "autoSavePanelIndex"
}]
},
listeners: {
"onCreate.bindReset": {
listener: "{separatedPanel}.bindReset",
args: ["{that}.reset"]
},
"afterReset.applyChanges": "{that}.applyChanges",
// Scroll to active panel after opening the separate Panel.
// This is when the panels are all rendered and the actual sizes are available.
"{separatedPanel}.slidingPanel.events.afterPanelShow": {
listener: "fluid.prefs.arrowScrolling.scrollToPanel",
args: ["{that}", "{that}.model.panelIndex"],
priority: "after:updateView",
namespace: "scrollToPanel"
}
}
}
}
},
outerEnhancerOptions: "{originalEnhancerOptions}.options.originalUserOptions",
distributeOptions: {
"separatedPanel.slidingPanel": {
source: "{that}.options.slidingPanel",
removeSource: true,
target: "{that > slidingPanel}.options"
},
"separatedPanel.iframeRenderer": {
source: "{that}.options.iframeRenderer",
removeSource: true,
target: "{that > iframeRenderer}.options"
},
"separatedPanel.iframeRendered.terms": {
source: "{that}.options.terms",
target: "{that > iframeRenderer}.options.terms"
},
"separatedPanel.selectors.iframe": {
source: "{that}.options.iframe",
removeSource: true,
target: "{that}.options.selectors.iframe"
},
"separatedPanel.iframeEnhancer.outerEnhancerOptions": {
source: "{that}.options.outerEnhancerOptions",
removeSource: true,
target: "{that iframeEnhancer}.options"
}
}
});
fluid.prefs.separatedPanel.hideReset = function (separatedPanel) {
separatedPanel.locate("reset").hide();
};
/*****************************************
* fluid.prefs.separatedPanel.renderIframe *
*****************************************/
fluid.defaults("fluid.prefs.separatedPanel.renderIframe", {
gradeNames: ["fluid.viewComponent"],
events: {
afterRender: null
},
styles: {
container: "fl-prefsEditor-separatedPanel-iframe"
},
terms: {
templatePrefix: "."
},
markupProps: {
"class": "flc-iframe",
src: "%templatePrefix/SeparatedPanelPrefsEditorFrame.html"
},
listeners: {
"onCreate.startLoadingIframe": "fluid.prefs.separatedPanel.renderIframe.startLoadingIframe"
}
});
fluid.prefs.separatedPanel.renderIframe.startLoadingIframe = function (that) {
var styles = that.options.styles;
// TODO: get earlier access to templateLoader,
that.options.markupProps.src = fluid.stringTemplate(that.options.markupProps.src, that.options.terms);
that.iframeSrc = that.options.markupProps.src;
// Create iframe and append to container
that.iframe = $("<iframe/>");
that.iframe.on("load", function () {
var iframeWindow = that.iframe[0].contentWindow;
that.iframeDocument = iframeWindow.document;
// The iframe should prefer its own version of jQuery if a separate
// one is loaded
that.jQuery = iframeWindow.jQuery || $;
that.renderPrefsEditorContainer = that.jQuery("body", that.iframeDocument);
that.jQuery(that.iframeDocument).ready(that.events.afterRender.fire);
});
that.iframe.attr(that.options.markupProps);
that.iframe.addClass(styles.container);
that.iframe.hide();
that.iframe.appendTo(that.container);
};
fluid.prefs.separatedPanel.updateView = function (prefsEditor) {
prefsEditor.events.onPrefsEditorRefresh.fire();
prefsEditor.events.onSignificantDOMChange.fire();
};
fluid.prefs.separatedPanel.bindEvents = function (prefsEditor, iframeEnhancer, separatedPanel) {
// FLUID-5740: This binding should be done declaratively - needs ginger world in order to bind onto slidingPanel
// which is a child of this component
var separatedPanelId = separatedPanel.slidingPanel.panelId;
separatedPanel.locate("reset").attr({
"aria-controls": separatedPanelId,
"role": "button"
});
separatedPanel.slidingPanel.events.afterPanelShow.addListener(function () {
fluid.prefs.separatedPanel.updateView(prefsEditor);
}, "updateView", "after:openPanel");
prefsEditor.events.onPrefsEditorRefresh.addListener(function () {
iframeEnhancer.updateModel(prefsEditor.model.preferences);
}, "updateModel");
prefsEditor.events.afterReset.addListener(function (prefsEditor) {
fluid.prefs.separatedPanel.updateView(prefsEditor);
}, "updateView");
prefsEditor.events.onSignificantDOMChange.addListener(function () {
// ensure that the panel is open before trying to adjust its height
if ( fluid.get(separatedPanel, "slidingPanel.model.isShowing") ) {
var dokkument = prefsEditor.container[0].ownerDocument;
var height = fluid.dom.getDocumentHeight(dokkument);
var iframe = separatedPanel.iframeRenderer.iframe;
var attrs = {height: height};
var panel = separatedPanel.slidingPanel.locate("panel");
panel.css({height: ""});
iframe.clearQueue();
iframe.animate(attrs, 400);
}
}, "adjustHeight");
separatedPanel.slidingPanel.events.afterPanelHide.addListener(function () {
separatedPanel.iframeRenderer.iframe.height(0);
// Prevent the hidden Preferences Editorpanel from being keyboard and screen reader accessible
separatedPanel.iframeRenderer.iframe.hide();
}, "collapseFrame");
separatedPanel.slidingPanel.events.afterPanelShow.addListener(function () {
separatedPanel.iframeRenderer.iframe.show();
// FLUID-6183: Required for bug in MS EDGE that clips off the bottom of adjusters
// The height needs to be recalculated in order for the panel to show up completely
separatedPanel.iframeRenderer.iframe.height();
separatedPanel.locate("reset").show();
}, "openPanel");
separatedPanel.slidingPanel.events.onPanelHide.addListener(function () {
separatedPanel.locate("reset").hide();
}, "hideReset");
};
// Replace the standard animator since we don't want the panel to become hidden
// (potential cause of jumping)
fluid.prefs.separatedPanel.hidePanel = function (panel, iframe, callback) {
iframe.clearQueue(); // FLUID-5334: clear the animation queue
$(panel).animate({height: 0}, {duration: 400, complete: callback});
};
// no activity - the kickback to the updateView listener will automatically trigger the
// DOMChangeListener above. This ordering is preferable to avoid causing the animation to
// jump by refreshing the view inside the iframe
fluid.prefs.separatedPanel.showPanel = function (panel, callback) {
// A bizarre race condition has emerged under FF where the iframe held within the panel does not
// react synchronously to being shown
fluid.invokeLater(callback);
};
/**
* FLUID-5926: Some of our users have asked for ways to improve the initial page load
* performance when using the separated panel prefs editor / UI Options. One option,
* provided here, is to implement a scheme for lazy loading the instantiation of the
* prefs editor, only instantiating enough of the workflow to allow display the
* sliding panel tab.
*
* fluid.prefs.separatedPanel.lazyLoad modifies the typical separatedPanel workflow
* by delaying the instantiation and loading of resources for the prefs editor until
* the first time it is opened.
*
* Lazy Load Workflow:
*
* - On instantiation of the prefsEditorLoader only the messageLoader and slidingPanel are instantiated
* - On instantiation, the messageLoader only loads preLoadResources, these are the messages required by
* the slidingPanel. The remaining message bundles will not be loaded until the "onLazyLoad" event is fired.
* - After the preLoadResources have been loaded, the onPrefsEditorMessagesPreloaded event is fired, and triggers the
* sliding panel to instantiate.
* - When a user opens the separated panel prefs editor / UI Options, it checks to see if the prefs editor has been
* instantiated. If it hasn't, a listener is temporarily bound to the onReady event, which gets fired
* after the prefs editor is ready. This is used to continue the process of opening the sliding panel for the first time.
* Additionally the onLazyLoad event is fired, which kicks off the remainder of the instantiation process.
* - onLazyLoad triggers the templateLoader to fetch all of the templates and the messageLoader to fetch the remaining
* message bundles. From here the standard instantiation workflow takes place.
*/
fluid.defaults("fluid.prefs.separatedPanel.lazyLoad", {
events: {
onLazyLoad: null,
onPrefsEditorMessagesPreloaded: null,
onCreateSlidingPanelReady: {
events: {
onPrefsEditorMessagesLoaded: "onPrefsEditorMessagesPreloaded"
}
},
templatesAndIframeReady: {
events: {
onLazyLoad: "onLazyLoad"
}
}
},
components: {
templateLoader: {
createOnEvent: "onLazyLoad"
},
messageLoader: {
options: {
events: {
onResourcesPreloaded: "{separatedPanel}.events.onPrefsEditorMessagesPreloaded"
},
preloadResources: "prefsEditor",
listeners: {
"onCreate.loadResources": {
listener: "fluid.prefs.separatedPanel.lazyLoad.preloadResources",
args: ["{that}", {expander: {func: "{that}.resolveResources"}}, "{that}.options.preloadResources"]
},
"{separatedPanel}.events.onLazyLoad": {
listener: "fluid.resourceLoader.loadResources",
args: ["{messageLoader}", {expander: {func: "{messageLoader}.resolveResources"}}],
namespace: "loadResources"
}
}
}
},
slidingPanel: {
options: {
invokers: {
operateShow: {
funcName: "fluid.prefs.separatedPanel.lazyLoad.showPanel",
args: ["{separatedPanel}", "{that}.events.afterPanelShow.fire"]
}
}
}
}
}
});
fluid.prefs.separatedPanel.lazyLoad.showPanel = function (separatedPanel, callback) {
if (separatedPanel.prefsEditor) {
fluid.invokeLater(callback);
} else {
separatedPanel.events.onReady.addListener(function (that) {
that.events.onReady.removeListener("showPanelCallBack");
fluid.invokeLater(callback);
}, "showPanelCallBack");
separatedPanel.events.onLazyLoad.fire();
}
};
/**
* Used to override the standard "onCreate.loadResources" listener for fluid.resourceLoader component,
* allowing for pre-loading of a subset of resources. This is required for the lazyLoading workflow
* for the "fluid.prefs.separatedPanel.lazyLoad".
*
* @param {Object} that - the component
* @param {Object} resources - all of the resourceSpecs to load, including preload and others.
* see: fluid.fetchResources
* @param {Array|String} toPreload - a String or an String[]s corresponding to the names
* of the resources, supplied in the resource argument, that
* should be loaded. Only these resources will be loaded.
*/
fluid.prefs.separatedPanel.lazyLoad.preloadResources = function (that, resources, toPreload) {
toPreload = fluid.makeArray(toPreload);
var preloadResources = {};
fluid.each(toPreload, function (resourceName) {
preloadResources[resourceName] = resources[resourceName];
});
// This portion of code was copied from fluid.resourceLoader.loadResources
// and will likely need to track any changes made there.
fluid.fetchResources(preloadResources, function () {
that.resources = preloadResources;
that.events.onResourcesPreloaded.fire(preloadResources);
});
};
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
/**************************************
* Full No Preview Preferences Editor *
**************************************/
fluid.defaults("fluid.prefs.fullNoPreview", {
gradeNames: ["fluid.prefs.prefsEditorLoader"],
components: {
prefsEditor: {
container: "{that}.container",
options: {
listeners: {
"afterReset.applyChanges": {
listener: "{that}.applyChanges"
},
"afterReset.save": {
listener: "{that}.save",
priority: "after:applyChanges"
}
}
}
}
},
events: {
onReady: null
}
});
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
/***********************************
* Full Preview Preferences Editor *
***********************************/
fluid.defaults("fluid.prefs.fullPreview", {
gradeNames: ["fluid.prefs.prefsEditorLoader"],
outerUiEnhancerOptions: "{originalEnhancerOptions}.options.originalUserOptions",
outerUiEnhancerGrades: "{originalEnhancerOptions}.uiEnhancer.options.userGrades",
components: {
prefsEditor: {
container: "{that}.container",
options: {
components: {
preview: {
type: "fluid.prefs.preview",
createOnEvent: "onReady",
container: "{prefsEditor}.dom.previewFrame",
options: {
listeners: {
"onReady.boilOnPreviewReady": "{fullPreview}.events.onPreviewReady"
}
}
}
},
listeners: {
"onReady.boil": {
listener: "{prefsEditorLoader}.events.onPrefsEditorReady"
}
},
distributeOptions: {
"fullPreview.prefsEditor.preview": {
source: "{that}.options.preview",
removeSource: true,
target: "{that > preview}.options"
}
}
}
}
},
events: {
onPrefsEditorReady: null,
onPreviewReady: null,
onReady: {
events: {
onPrefsEditorReady: "onPrefsEditorReady",
onPreviewReady: "onPreviewReady"
},
args: "{that}"
}
},
distributeOptions: {
"fullPreview.enhancer.outerUiEnhancerOptions": {
source: "{that}.options.outerUiEnhancerOptions",
target: "{that enhancer}.options"
},
"fullPreview.enhancer.previewEnhancer": {
source: "{that}.options.previewEnhancer",
target: "{that enhancer}.options"
},
"fullPreviw.preview": {
source: "{that}.options.preview",
target: "{that preview}.options"
},
"fullPreview.enhancer.outerUiEnhancerGrades": {
source: "{that}.options.outerUiEnhancerGrades",
target: "{that enhancer}.options.gradeNames"
}
}
});
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
fluid.registerNamespace("fluid.prefs.schemas");
/**
* A custom merge policy that merges primary schema blocks and
* places them in the right location (consistent with the JSON schema
* format).
* @param {JSON} target - A base for merging the options.
* @param {JSON} source - Options being merged.
* @return {JSON} - The updated target.
*/
fluid.prefs.schemas.merge = function (target, source) {
if (!target) {
target = {
type: "object",
properties: {}
};
}
// We can handle both schema blocks in options directly and also inside
// the |properties| field.
source = source.properties || source;
$.extend(true, target.properties, source);
return target;
};
/*******************************************************************************
* Primary builder grade
*******************************************************************************/
fluid.defaults("fluid.prefs.primaryBuilder", {
gradeNames: ["fluid.component", "{that}.buildPrimary"],
// An index of all schema grades registered with the framework.
schemaIndex: {
expander: {
func: "fluid.indexDefaults",
args: ["schemaIndex", {
gradeNames: "fluid.prefs.schemas",
indexFunc: "fluid.prefs.primaryBuilder.defaultSchemaIndexer"
}]
}
},
primarySchema: {},
// A list of all necessarry top level preference names.
typeFilter: [],
invokers: {
// An invoker used to generate a set of grades that comprise a
// final version of the primary schema to be used by the PrefsEditor
// builder.
buildPrimary: {
funcName: "fluid.prefs.primaryBuilder.buildPrimary",
args: [
"{that}.options.schemaIndex",
"{that}.options.typeFilter",
"{that}.options.primarySchema"
]
}
}
});
/**
* An invoker method that builds a list of grades that comprise a final version of the primary schema.
* @param {JSON} schemaIndex - A global index of all schema grades registered with the framework.
* @param {Array} typeFilter - A list of all necessarry top level preference names.
* @param {JSON} primarySchema - Primary schema provided as an option to the primary builder.
* @return {Array} - A list of schema grades.
*/
fluid.prefs.primaryBuilder.buildPrimary = function (schemaIndex, typeFilter, primarySchema) {
var suppliedPrimaryGradeName = "fluid.prefs.schemas.suppliedPrimary" + fluid.allocateGuid();
// Create a grade that has a primary schema passed as an option inclosed.
fluid.defaults(suppliedPrimaryGradeName, {
gradeNames: ["fluid.prefs.schemas"],
schema: fluid.filterKeys(primarySchema.properties || primarySchema,
typeFilter, false)
});
var primary = [];
// Lookup all available schema grades from the index that match the
// top level preference name.
fluid.each(typeFilter, function merge(type) {
var schemaGrades = schemaIndex[type];
if (schemaGrades) {
primary.push.apply(primary, schemaGrades);
}
});
primary.push(suppliedPrimaryGradeName);
return primary;
};
/**
* An index function that indexes all shcema grades based on their
* preference name.
* @param {JSON} defaults - Registered defaults for a schema grade.
* @return {String} A preference name.
*/
fluid.prefs.primaryBuilder.defaultSchemaIndexer = function (defaults) {
if (defaults.schema) {
return fluid.keys(defaults.schema.properties);
}
};
/*******************************************************************************
* Base primary schema grade
*******************************************************************************/
fluid.defaults("fluid.prefs.schemas", {
gradeNames: ["fluid.component"],
mergePolicy: {
schema: fluid.prefs.schemas.merge
}
});
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
fluid.registerNamespace("fluid.prefs");
/*******************************************************************************
* Base auxiliary schema grade
*******************************************************************************/
fluid.defaults("fluid.prefs.auxSchema", {
gradeNames: ["fluid.component"],
auxiliarySchema: {
"loaderGrades": ["fluid.prefs.separatedPanel"]
}
});
/**
* Look up the value on the given source object by using the path.
* Takes a template string containing tokens in the form of "@source-path-to-value".
* Returns a value (any type) or undefined if the path is not found.
*
* Example:
* 1. Parameters:
* source:
* {
* path1: {
* path2: "here"
* }
* }
*
* template: "@path1.path2"
*
* 2. Return: "here"
*
* @param {Object} root - An object to retrieve the returned value from.
* @param {String} pathRef - A string that the path to the requested value is embedded into.
* @return {Any} - Returns a value (any type) or undefined if the path is not found.
*
*/
fluid.prefs.expandSchemaValue = function (root, pathRef) {
if (pathRef.charAt(0) !== "@") {
return pathRef;
}
return fluid.get(root, pathRef.substring(1));
};
fluid.prefs.addAtPath = function (root, path, object) {
var existingObject = fluid.get(root, path);
fluid.set(root, path, $.extend(true, {}, existingObject, object));
return root;
};
// only works with top level elements
fluid.prefs.removeKey = function (root, key) {
var value = root[key];
delete root[key];
return value;
};
fluid.prefs.rearrangeDirect = function (root, toPath, sourcePath) {
var result = {};
var sourceValue = fluid.prefs.removeKey(root, sourcePath);
if (sourceValue) {
fluid.set(result, toPath, sourceValue);
}
return result;
};
fluid.prefs.addCommonOptions = function (root, path, commonOptions, templateValues) {
templateValues = templateValues || {};
var existingValue = fluid.get(root, path);
if (!existingValue) {
return root;
}
var opts = {}, mergePolicy = {};
fluid.each(commonOptions, function (value, key) {
// Adds "container" option only for view and renderer components
if (key === "container") {
var componentType = fluid.get(root, [path, "type"]);
var componentOptions = fluid.defaults(componentType);
// Note that this approach is not completely reliable, although it has been reviewed as "good enough" -
// a grade which modifies the creation signature of its principal type would cause numerous other problems.
// We can review this awkward kind of "anticipatory logic" when the new renderer arrives.
if (fluid.get(componentOptions, ["argumentMap", "container"]) === undefined) {
return false;
}
}
// Merge grade names defined in aux schema and system default grades
if (key.indexOf("gradeNames") !== -1) {
mergePolicy[key] = fluid.arrayConcatPolicy;
}
key = fluid.stringTemplate(key, templateValues);
value = typeof (value) === "string" ? fluid.stringTemplate(value, templateValues) : value;
fluid.set(opts, key, value);
});
fluid.set(root, path, fluid.merge(mergePolicy, existingValue, opts));
return root;
};
fluid.prefs.containerNeeded = function (root, path) {
var componentType = fluid.get(root, [path, "type"]);
var componentOptions = fluid.defaults(componentType);
return (fluid.hasGrade(componentOptions, "fluid.viewComponent") || fluid.hasGrade(componentOptions, "fluid.rendererComponent"));
};
fluid.prefs.checkPrimarySchema = function (primarySchema, prefKey) {
if (!primarySchema) {
fluid.fail("The primary schema for " + prefKey + " is not defined.");
}
return !!primarySchema;
};
fluid.prefs.flattenName = function (name) {
var regexp = new RegExp("\\.", "g");
return name.replace(regexp, "_");
};
fluid.prefs.constructAliases = function (auxSchema, flattenedPrefKey, aliases) {
aliases = fluid.makeArray(aliases);
var prefsEditorModel = {};
var enhancerModel = {};
fluid.each(aliases, function (alias) {
prefsEditorModel[alias] = "{that}.model.preferences." + flattenedPrefKey;
enhancerModel[alias] = "{that}.model." + flattenedPrefKey;
});
fluid.prefs.addAtPath(auxSchema, ["aliases_prefsEditor", "model", "preferences"], prefsEditorModel);
fluid.prefs.addAtPath(auxSchema, ["aliases_enhancer", "model"], enhancerModel);
};
fluid.prefs.expandSchemaComponents = function (auxSchema, type, prefKey, alias, componentConfig, index, commonOptions, modelCommonOptions, mappedDefaults) {
var componentOptions = fluid.copy(componentConfig) || {};
var components = {};
var initialModel = {};
var componentName = fluid.prefs.removeKey(componentOptions, "type");
var memberName = fluid.prefs.flattenName(componentName);
var flattenedPrefKey = fluid.prefs.flattenName(prefKey);
if (componentName) {
components[memberName] = {
type: componentName,
options: componentOptions
};
var selectors = fluid.prefs.rearrangeDirect(componentOptions, memberName, "container");
var templates = fluid.prefs.rearrangeDirect(componentOptions, memberName, "template");
var messages = fluid.prefs.rearrangeDirect(componentOptions, memberName, "message");
var preferenceMap = fluid.defaults(componentName).preferenceMap;
var map = preferenceMap[prefKey];
var prefSchema = mappedDefaults[prefKey];
fluid.each(map, function (primaryPath, internalPath) {
if (fluid.prefs.checkPrimarySchema(prefSchema, prefKey)) {
var opts = {};
if (internalPath.indexOf("model.") === 0 && primaryPath === "value") {
var internalModelName = internalPath.slice(6);
// Set up the binding in "rules" accepted by the modelRelay base grade of every panel
fluid.set(opts, "model", fluid.get(opts, "model") || {});
fluid.prefs.addCommonOptions(opts, "model", modelCommonOptions, {
internalModelName: internalModelName,
externalModelName: flattenedPrefKey
});
fluid.set(initialModel, ["members", "initialModel", "preferences", flattenedPrefKey], prefSchema["default"]);
if (alias) {
fluid.set(initialModel, ["members", "initialModel", "preferences", alias], prefSchema["default"]);
}
} else {
fluid.set(opts, internalPath, prefSchema[primaryPath]);
}
$.extend(true, componentOptions, opts);
}
});
fluid.prefs.addCommonOptions(components, memberName, commonOptions, {
prefKey: memberName
});
fluid.prefs.addAtPath(auxSchema, [type, "components"], components);
fluid.prefs.addAtPath(auxSchema, [type, "selectors"], selectors);
fluid.prefs.addAtPath(auxSchema, ["templateLoader", "resources"], templates);
fluid.prefs.addAtPath(auxSchema, ["messageLoader", "resources"], messages);
fluid.prefs.addAtPath(auxSchema, "initialModel", initialModel);
fluid.prefs.constructAliases(auxSchema, flattenedPrefKey, alias);
}
return auxSchema;
};
/**
* Expands a all "@" path references from an auxiliary schema.
* Note that you cannot chain "@" paths.
*
* @param {Object} schemaToExpand - the schema which will be expanded
* @param {Object} altSource - an alternative look up object. This is primarily used for the internal recursive call.
* @return {Object} an expanded version of the schema.
*/
fluid.prefs.expandSchemaImpl = function (schemaToExpand, altSource) {
var expandedSchema = fluid.copy(schemaToExpand);
altSource = altSource || expandedSchema;
fluid.each(expandedSchema, function (value, key) {
if (typeof value === "object") {
expandedSchema[key] = fluid.prefs.expandSchemaImpl(value, altSource);
} else if (typeof value === "string") {
var expandedVal = fluid.prefs.expandSchemaValue(altSource, value);
if (expandedVal !== undefined) {
expandedSchema[key] = expandedVal;
} else {
delete expandedSchema[key];
}
}
});
return expandedSchema;
};
fluid.prefs.expandCompositePanels = function (auxSchema, compositePanelList, panelIndex, panelCommonOptions, subPanelCommonOptions,
compositePanelBasedOnSubCommonOptions, panelModelCommonOptions, mappedDefaults) {
var panelsToIgnore = [];
fluid.each(compositePanelList, function (compositeDetail, compositeKey) {
var compositePanelOptions = {};
var components = {};
var initialModel = {};
var selectors = {};
var templates = {};
var messages = {};
var selectorsToIgnore = [];
var thisCompositeOptions = fluid.copy(compositeDetail);
fluid.set(compositePanelOptions, "type", thisCompositeOptions.type);
delete thisCompositeOptions.type;
selectors = fluid.prefs.rearrangeDirect(thisCompositeOptions, compositeKey, "container");
templates = fluid.prefs.rearrangeDirect(thisCompositeOptions, compositeKey, "template");
messages = fluid.prefs.rearrangeDirect(thisCompositeOptions, compositeKey, "message");
var subPanelList = []; // list of subpanels to generate options for
var subPanels = {};
var subPanelRenderOn = {};
// thisCompositeOptions.panels can be in two forms:
// 1. an array of names of panels that should always be rendered;
// 2. an object that describes what panels should always be rendered,
// and what panels should be rendered when a preference is turned on
// The loop below is only needed for processing the latter.
if (fluid.isPlainObject(thisCompositeOptions.panels) && !fluid.isArrayable(thisCompositeOptions.panels)) {
fluid.each(thisCompositeOptions.panels, function (subpanelArray, pref) {
subPanelList = subPanelList.concat(subpanelArray);
if (pref !== "always") {
fluid.each(subpanelArray, function (onePanel) {
fluid.set(subPanelRenderOn, onePanel, pref);
});
}
});
} else {
subPanelList = thisCompositeOptions.panels;
}
fluid.each(subPanelList, function (subPanelID) {
panelsToIgnore.push(subPanelID);
var subPanelPrefsKey = fluid.get(auxSchema, [subPanelID, "type"]);
var safeSubPanelPrefsKey = fluid.prefs.subPanel.safePrefKey(subPanelPrefsKey);
selectorsToIgnore.push(safeSubPanelPrefsKey);
var subPanelOptions = fluid.copy(fluid.get(auxSchema, [subPanelID, "panel"]));
var subPanelType = fluid.get(subPanelOptions, "type");
fluid.set(subPanels, [safeSubPanelPrefsKey, "type"], subPanelType);
var renderOn = fluid.get(subPanelRenderOn, subPanelID);
if (renderOn) {
fluid.set(subPanels, [safeSubPanelPrefsKey, "options", "renderOnPreference"], renderOn);
}
// Deal with preferenceMap related options
var map = fluid.defaults(subPanelType).preferenceMap[subPanelPrefsKey];
var prefSchema = mappedDefaults[subPanelPrefsKey];
fluid.each(map, function (primaryPath, internalPath) {
if (fluid.prefs.checkPrimarySchema(prefSchema, subPanelPrefsKey)) {
var opts;
if (internalPath.indexOf("model.") === 0 && primaryPath === "value") {
// Set up the binding in "rules" accepted by the modelRelay base grade of every panel
fluid.set(compositePanelOptions, ["options", "model"], fluid.get(compositePanelOptions, ["options", "model"]) || {});
fluid.prefs.addCommonOptions(compositePanelOptions, ["options", "model"], panelModelCommonOptions, {
internalModelName: safeSubPanelPrefsKey,
externalModelName: safeSubPanelPrefsKey
});
fluid.set(initialModel, ["members", "initialModel", "preferences", safeSubPanelPrefsKey], prefSchema["default"]);
} else {
opts = opts || {options: {}};
fluid.set(opts, "options." + internalPath, prefSchema[primaryPath]);
}
$.extend(true, subPanels[safeSubPanelPrefsKey], opts);
}
});
fluid.set(templates, safeSubPanelPrefsKey, fluid.get(subPanelOptions, "template"));
fluid.set(messages, safeSubPanelPrefsKey, fluid.get(subPanelOptions, "message"));
fluid.set(compositePanelOptions, ["options", "selectors", safeSubPanelPrefsKey], fluid.get(subPanelOptions, "container"));
fluid.set(compositePanelOptions, ["options", "resources"], fluid.get(compositePanelOptions, ["options", "resources"]) || {});
fluid.prefs.addCommonOptions(compositePanelOptions.options, "resources", compositePanelBasedOnSubCommonOptions, {
subPrefKey: safeSubPanelPrefsKey
});
// add additional options from the aux schema for subpanels
delete subPanelOptions.type;
delete subPanelOptions.template;
delete subPanelOptions.message;
delete subPanelOptions.container;
fluid.set(subPanels, [safeSubPanelPrefsKey, "options"], $.extend(true, {}, fluid.get(subPanels, [safeSubPanelPrefsKey, "options"]), subPanelOptions));
fluid.prefs.addCommonOptions(subPanels, safeSubPanelPrefsKey, subPanelCommonOptions, {
compositePanel: compositeKey,
prefKey: safeSubPanelPrefsKey
});
});
delete thisCompositeOptions.panels;
// add additional options from the aux schema for the composite panel
fluid.set(compositePanelOptions, ["options"], $.extend(true, {}, compositePanelOptions.options, thisCompositeOptions));
fluid.set(compositePanelOptions, ["options", "selectorsToIgnore"], selectorsToIgnore);
fluid.set(compositePanelOptions, ["options", "components"], subPanels);
components[compositeKey] = compositePanelOptions;
fluid.prefs.addCommonOptions(components, compositeKey, panelCommonOptions, {
prefKey: compositeKey
});
// Add onto auxSchema
fluid.prefs.addAtPath(auxSchema, ["panels", "components"], components);
fluid.prefs.addAtPath(auxSchema, ["panels", "selectors"], selectors);
fluid.prefs.addAtPath(auxSchema, ["templateLoader", "resources"], templates);
fluid.prefs.addAtPath(auxSchema, ["messageLoader", "resources"], messages);
fluid.prefs.addAtPath(auxSchema, "initialModel", initialModel);
$.extend(true, auxSchema, {panelsToIgnore: panelsToIgnore});
});
return auxSchema;
};
// Processes the auxiliary schema to output an object that contains all grade component definitions
// required for building the preferences editor, uiEnhancer and the settings store. These grade components
// are: panels, enactors, initialModel, messageLoader, templateLoader and terms.
// These grades are consumed and integrated by builder.js
// (https://github.com/fluid-project/infusion/blob/master/src/framework/preferences/js/Builder.js)
fluid.prefs.expandSchema = function (schemaToExpand, indexes, topCommonOptions, elementCommonOptions, mappedDefaults) {
var auxSchema = fluid.prefs.expandSchemaImpl(schemaToExpand);
auxSchema.namespace = auxSchema.namespace || "fluid.prefs.created_" + fluid.allocateGuid();
var terms = fluid.get(auxSchema, "terms");
if (terms) {
delete auxSchema.terms;
fluid.set(auxSchema, ["terms", "terms"], terms);
}
var compositePanelList = fluid.get(auxSchema, "groups");
if (compositePanelList) {
fluid.prefs.expandCompositePanels(auxSchema, compositePanelList, fluid.get(indexes, "panel"),
fluid.get(elementCommonOptions, "panel"), fluid.get(elementCommonOptions, "subPanel"),
fluid.get(elementCommonOptions, "compositePanelBasedOnSub"), fluid.get(elementCommonOptions, "panelModel"),
mappedDefaults);
}
fluid.each(auxSchema, function (category, prefName) {
// TODO: Replace this cumbersome scheme with one based on an extensible lookup to handlers
var type = "panel";
// Ignore the subpanels that are only for composing composite panels
if (category[type] && !fluid.contains(auxSchema.panelsToIgnore, prefName)) {
fluid.prefs.expandSchemaComponents(auxSchema, "panels", category.type, category.alias, category[type], fluid.get(indexes, type),
fluid.get(elementCommonOptions, type), fluid.get(elementCommonOptions, type + "Model"), mappedDefaults);
}
type = "enactor";
if (category[type]) {
fluid.prefs.expandSchemaComponents(auxSchema, "enactors", category.type, category.alias, category[type], fluid.get(indexes, type),
fluid.get(elementCommonOptions, type), fluid.get(elementCommonOptions, type + "Model"), mappedDefaults);
}
fluid.each(["template", "message"], function (type) {
if (prefName === type) {
fluid.set(auxSchema, [type + "Loader", "resources", "prefsEditor"], auxSchema[type]);
delete auxSchema[type];
}
});
});
// Remove subPanels array. It is to keep track of the panels that are only used as sub-components of composite panels.
if (auxSchema.panelsToIgnore) {
delete auxSchema.panelsToIgnore;
}
// Add top common options
fluid.each(topCommonOptions, function (topOptions, type) {
fluid.prefs.addCommonOptions(auxSchema, type, topOptions);
});
return auxSchema;
};
fluid.defaults("fluid.prefs.auxBuilder", {
gradeNames: ["fluid.prefs.auxSchema"],
mergePolicy: {
elementCommonOptions: "noexpand"
},
topCommonOptions: {
panels: {
gradeNames: ["fluid.prefs.prefsEditor"]
},
enactors: {
gradeNames: ["fluid.uiEnhancer"]
},
templateLoader: {
gradeNames: ["fluid.resourceLoader"]
},
messageLoader: {
gradeNames: ["fluid.resourceLoader"]
},
initialModel: {
gradeNames: ["fluid.prefs.initialModel"]
},
terms: {
gradeNames: ["fluid.component"]
},
aliases_prefsEditor: {
gradeNames: ["fluid.modelComponent"]
},
aliases_enhancer: {
gradeNames: ["fluid.modelComponent"]
}
},
elementCommonOptions: {
panel: {
"createOnEvent": "onPrefsEditorMarkupReady",
"container": "{prefsEditor}.dom.%prefKey",
"options.gradeNames": "fluid.prefs.prefsEditorConnections",
"options.resources.template": "{templateLoader}.resources.%prefKey",
"options.messageBase": "{messageLoader}.resources.%prefKey.resourceText"
},
panelModel: {
"%internalModelName": "{prefsEditor}.model.preferences.%externalModelName"
},
compositePanelBasedOnSub: {
"%subPrefKey": "{templateLoader}.resources.%subPrefKey"
},
subPanel: {
"container": "{%compositePanel}.dom.%prefKey",
"options.messageBase": "{messageLoader}.resources.%prefKey.resourceText"
},
enactor: {
"container": "{uiEnhancer}.container"
},
enactorModel: {
"%internalModelName": "{uiEnhancer}.model.%externalModelName"
}
},
indexes: {
panel: {
expander: {
func: "fluid.indexDefaults",
args: ["panelsIndex", {
gradeNames: "fluid.prefs.panel",
indexFunc: "fluid.prefs.auxBuilder.prefMapIndexer"
}]
}
},
enactor: {
expander: {
func: "fluid.indexDefaults",
args: ["enactorsIndex", {
gradeNames: "fluid.prefs.enactor",
indexFunc: "fluid.prefs.auxBuilder.prefMapIndexer"
}]
}
}
},
mappedDefaults: {},
expandedAuxSchema: {
expander: {
func: "fluid.prefs.expandSchema",
args: [
"{that}.options.auxiliarySchema",
"{that}.options.indexes",
"{that}.options.topCommonOptions",
"{that}.options.elementCommonOptions",
"{that}.options.mappedDefaults"
]
}
}
});
fluid.prefs.auxBuilder.prefMapIndexer = function (defaults) {
return fluid.keys(defaults.preferenceMap);
};
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function (fluid) {
"use strict";
/*******************************************************************************
* Starter auxiliary schema grade
*
* Contains the settings for 7 preferences: text size, line space, text font,
* contrast, table of contents, inputs larger and emphasize links
*******************************************************************************/
fluid.defaults("fluid.prefs.auxSchema.starter", {
gradeNames: ["fluid.prefs.auxSchema"],
auxiliarySchema: {
"loaderGrades": ["fluid.prefs.separatedPanel"],
"namespace": "fluid.prefs.constructed", // The author of the auxiliary schema will provide this and will be the component to call to initialize the constructed PrefsEditor.
"terms": {
"templatePrefix": "../../framework/preferences/html", // Must match the keyword used below to identify the common path to settings panel templates.
"messagePrefix": "../../framework/preferences/messages" // Must match the keyword used below to identify the common path to message files.
},
"template": "%templatePrefix/SeparatedPanelPrefsEditor.html",
"message": "%messagePrefix/prefsEditor.json",
"defaultLocale": "en",
"textSize": {
"type": "fluid.prefs.textSize",
"alias": "textSize",
"enactor": {
"type": "fluid.prefs.enactor.textSize"
},
"panel": {
"type": "fluid.prefs.panel.textSize",
"container": ".flc-prefsEditor-text-size", // the css selector in the template where the panel is rendered
"message": "%messagePrefix/textSize.json",
"template": "%templatePrefix/PrefsEditorTemplate-textSize.html"
}
},
"textFont": {
"type": "fluid.prefs.textFont",
"alias": "textFont",
"classes": {
"default": "",
"times": "fl-font-times",
"comic": "fl-font-comic-sans",
"arial": "fl-font-arial",
"verdana": "fl-font-verdana",
"open-dyslexic": "fl-font-open-dyslexic"
},
"enactor": {
"type": "fluid.prefs.enactor.textFont",
"classes": "@textFont.classes"
},
"panel": {
"type": "fluid.prefs.panel.textFont",
"container": ".flc-prefsEditor-text-font", // the css selector in the template where the panel is rendered
"classnameMap": {"textFont": "@textFont.classes"},
"template": "%templatePrefix/PrefsEditorTemplate-textFont.html",
"message": "%messagePrefix/textFont.json"
}
},
"lineSpace": {
"type": "fluid.prefs.lineSpace",
"alias": "lineSpace",
"enactor": {
"type": "fluid.prefs.enactor.lineSpace",
"fontSizeMap": {
"xx-small": "9px",
"x-small": "11px",
"small": "13px",
"medium": "15px",
"large": "18px",
"x-large": "23px",
"xx-large": "30px"
}
},
"panel": {
"type": "fluid.prefs.panel.lineSpace",
"container": ".flc-prefsEditor-line-space", // the css selector in the template where the panel is rendered
"message": "%messagePrefix/lineSpace.json",
"template": "%templatePrefix/PrefsEditorTemplate-lineSpace.html"
}
},
"contrast": {
"type": "fluid.prefs.contrast",
"alias": "theme",
"classes": {
"default": "fl-theme-prefsEditor-default",
"bw": "fl-theme-bw",
"wb": "fl-theme-wb",
"by": "fl-theme-by",
"yb": "fl-theme-yb",
"lgdg": "fl-theme-lgdg",
"gd": "fl-theme-gd",
"gw": "fl-theme-gw",
"bbr": "fl-theme-bbr"
},
"enactor": {
"type": "fluid.prefs.enactor.contrast",
"classes": "@contrast.classes"
},
"panel": {
"type": "fluid.prefs.panel.contrast",
"container": ".flc-prefsEditor-contrast", // the css selector in the template where the panel is rendered
"classnameMap": {"theme": "@contrast.classes"},
"template": "%templatePrefix/PrefsEditorTemplate-contrast.html",
"message": "%messagePrefix/contrast.json"
}
},
"tableOfContents": {
"type": "fluid.prefs.tableOfContents",
"alias": "toc",
"enactor": {
"type": "fluid.prefs.enactor.tableOfContents",
"tocTemplate": "../../components/tableOfContents/html/TableOfContents.html",
"tocMessage": "../../framework/preferences/messages/tableOfContents-enactor.json"
},
"panel": {
"type": "fluid.prefs.panel.layoutControls",
"container": ".flc-prefsEditor-layout-controls", // the css selector in the template where the panel is rendered
"template": "%templatePrefix/PrefsEditorTemplate-layout.html",
"message": "%messagePrefix/tableOfContents.json"
}
},
"enhanceInputs": {
"type": "fluid.prefs.enhanceInputs",
"alias": "inputs",
"enactor": {
"type": "fluid.prefs.enactor.enhanceInputs",
"cssClass": "fl-input-enhanced"
},
"panel": {
"type": "fluid.prefs.panel.enhanceInputs",
"container": ".flc-prefsEditor-enhanceInputs", // the css selector in the template where the panel is rendered
"template": "%templatePrefix/PrefsEditorTemplate-enhanceInputs.html",
"message": "%messagePrefix/enhanceInputs.json"
}
}
}
});
/*******************************************************************************
* Starter primary schema grades
*
* Contains the settings for 7 preferences: text size, line space, text font,
* contrast, table of contents, inputs larger and emphasize links
*******************************************************************************/
fluid.defaults("fluid.prefs.schemas.textSize", {
gradeNames: ["fluid.prefs.schemas"],
schema: {
"fluid.prefs.textSize": {
"type": "number",
"default": 1,
"minimum": 0.5,
"maximum": 2,
"multipleOf": 0.1
}
}
});
fluid.defaults("fluid.prefs.schemas.lineSpace", {
gradeNames: ["fluid.prefs.schemas"],
schema: {
"fluid.prefs.lineSpace": {
"type": "number",
"default": 1,
"minimum": 0.7,
"maximum": 2,
"multipleOf": 0.1
}
}
});
fluid.defaults("fluid.prefs.schemas.textFont", {
gradeNames: ["fluid.prefs.schemas"],
schema: {
"fluid.prefs.textFont": {
"type": "string",
"default": "default",
"enum": ["default", "times", "comic", "arial", "verdana", "open-dyslexic"],
"enumLabels": [
"textFont-default",
"textFont-times",
"textFont-comic",
"textFont-arial",
"textFont-verdana",
"textFont-open-dyslexic"
]
}
}
});
fluid.defaults("fluid.prefs.schemas.contrast", {
gradeNames: ["fluid.prefs.schemas"],
schema: {
"fluid.prefs.contrast": {
"type": "string",
"default": "default",
"enum": ["default", "bw", "wb", "by", "yb", "lgdg", "gw", "gd", "bbr"],
"enumLabels": [
"contrast-default",
"contrast-bw",
"contrast-wb",
"contrast-by",
"contrast-yb",
"contrast-lgdg",
"contrast-gw",
"contrast-gd",
"contrast-bbr"
]
}
}
});
fluid.defaults("fluid.prefs.schemas.tableOfContents", {
gradeNames: ["fluid.prefs.schemas"],
schema: {
"fluid.prefs.tableOfContents": {
"type": "boolean",
"default": false
}
}
});
fluid.defaults("fluid.prefs.schemas.enhanceInputs", {
gradeNames: ["fluid.prefs.schemas"],
schema: {
"fluid.prefs.enhanceInputs": {
"type": "boolean",
"default": false
}
}
});
})(fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function (fluid) {
"use strict";
/*******************************************************************************
* Starter auxiliary schema grade
*
* Contains the settings for captions
*******************************************************************************/
// Fine-tune the starter aux schema and add captions panel
fluid.defaults("fluid.prefs.auxSchema.captions", {
gradeNames: ["fluid.prefs.auxSchema"],
auxiliarySchema: {
"namespace": "fluid.prefs.constructed",
"terms": {
"templatePrefix": "../../framework/preferences/html",
"messagePrefix": "../../framework/preferences/messages"
},
"template": "%templatePrefix/SeparatedPanelPrefsEditor.html",
"message": "%messagePrefix/prefsEditor.json",
captions: {
type: "fluid.prefs.captions",
enactor: {
type: "fluid.prefs.enactor.captions",
container: "body"
},
panel: {
type: "fluid.prefs.panel.captions",
container: ".flc-prefsEditor-captions",
template: "%templatePrefix/PrefsEditorTemplate-captions.html",
message: "%messagePrefix/captions.json"
}
}
}
});
/*******************************************************************************
* Primary Schema
*******************************************************************************/
// add extra prefs to the starter primary schemas
fluid.defaults("fluid.prefs.schemas.captions", {
gradeNames: ["fluid.prefs.schemas"],
schema: {
"fluid.prefs.captions": {
"type": "boolean",
"default": false
}
}
});
})(fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function (fluid) {
"use strict";
/*******************************************************************************
* Starter auxiliary schema grade
*
* Contains the settings for the letter space preference
*******************************************************************************/
// Fine-tune the starter aux schema and add letter space preference
fluid.defaults("fluid.prefs.auxSchema.letterSpace", {
gradeNames: ["fluid.prefs.auxSchema"],
auxiliarySchema: {
"namespace": "fluid.prefs.constructed",
"terms": {
"templatePrefix": "../../framework/preferences/html/",
"messagePrefix": "../../framework/preferences/messages/"
},
"template": "%templatePrefix/SeparatedPanelPrefsEditor.html",
"message": "%messagePrefix/prefsEditor.json",
letterSpace: {
type: "fluid.prefs.letterSpace",
enactor: {
type: "fluid.prefs.enactor.letterSpace",
fontSizeMap: {
"xx-small": "9px",
"x-small": "11px",
"small": "13px",
"medium": "15px",
"large": "18px",
"x-large": "23px",
"xx-large": "30px"
}
},
panel: {
type: "fluid.prefs.panel.letterSpace",
container: ".flc-prefsEditor-letter-space",
template: "%templatePrefix/PrefsEditorTemplate-letterSpace.html",
message: "%messagePrefix/letterSpace.json"
}
}
}
});
/*******************************************************************************
* Primary Schema
*******************************************************************************/
// add extra prefs to the starter primary schemas
fluid.defaults("fluid.prefs.schemas.letterSpace", {
gradeNames: ["fluid.prefs.schemas"],
schema: {
"fluid.prefs.letterSpace": {
"type": "number",
"default": 1,
"minimum": 0.9,
"maximum": 2,
"multipleOf": 0.1
}
}
});
})(fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function (fluid) {
"use strict";
/*******************************************************************************
* Starter auxiliary schema grade
*
* Contains the settings for text-to-speech
*******************************************************************************/
// Fine-tune the starter aux schema and add speak panel
fluid.defaults("fluid.prefs.auxSchema.speak", {
gradeNames: ["fluid.prefs.auxSchema"],
auxiliarySchema: {
"namespace": "fluid.prefs.constructed",
"terms": {
"templatePrefix": "../../framework/preferences/html/",
"messagePrefix": "../../framework/preferences/messages/"
},
"template": "%templatePrefix/SeparatedPanelPrefsEditor.html",
"message": "%messagePrefix/prefsEditor.json",
speak: {
type: "fluid.prefs.speak",
enactor: {
type: "fluid.prefs.enactor.selfVoicing"
},
panel: {
type: "fluid.prefs.panel.speak",
container: ".flc-prefsEditor-speak",
template: "%templatePrefix/PrefsEditorTemplate-speak.html",
message: "%messagePrefix/speak.json"
}
}
}
});
/*******************************************************************************
* Primary Schema
*******************************************************************************/
// add extra prefs to the starter primary schemas
fluid.defaults("fluid.prefs.schemas.speak", {
gradeNames: ["fluid.prefs.schemas"],
schema: {
"fluid.prefs.speak": {
"type": "boolean",
"default": false
}
}
});
})(fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function (fluid) {
"use strict";
/*******************************************************************************
* Starter auxiliary schema grade
*
* Contains the settings for syllabification
*******************************************************************************/
// Fine-tune the starter aux schema and add syllabification panel
fluid.defaults("fluid.prefs.auxSchema.syllabification", {
gradeNames: ["fluid.prefs.auxSchema"],
auxiliarySchema: {
"namespace": "fluid.prefs.constructed",
"terms": {
"templatePrefix": "../../framework/preferences/html",
"messagePrefix": "../../framework/preferences/messages"
},
"template": "%templatePrefix/SeparatedPanelPrefsEditor.html",
"message": "%messagePrefix/prefsEditor.json",
syllabification: {
type: "fluid.prefs.syllabification",
enactor: {
type: "fluid.prefs.enactor.syllabification",
container: "body"
},
panel: {
type: "fluid.prefs.panel.syllabification",
container: ".flc-prefsEditor-syllabification",
template: "%templatePrefix/PrefsEditorTemplate-syllabification.html",
message: "%messagePrefix/syllabification.json"
}
}
}
});
/*******************************************************************************
* Primary Schema
*******************************************************************************/
// add extra prefs to the starter primary schemas
fluid.defaults("fluid.prefs.schemas.syllabification", {
gradeNames: ["fluid.prefs.schemas"],
schema: {
"fluid.prefs.syllabification": {
"type": "boolean",
"default": false
}
}
});
})(fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function (fluid) {
"use strict";
/*******************************************************************************
* Starter auxiliary schema grade
*
* Contains the settings for the localization preference
*******************************************************************************/
// Fine-tune the starter aux schema and add localization preference
fluid.defaults("fluid.prefs.auxSchema.localization", {
gradeNames: ["fluid.prefs.auxSchema"],
auxiliarySchema: {
"terms": {
"templatePrefix": "../../framework/preferences/html/",
"messagePrefix": "../../framework/preferences/messages/"
},
"template": "%templatePrefix/SeparatedPanelPrefsEditor.html",
"message": "%messagePrefix/prefsEditor.json",
localization: {
"type": "fluid.prefs.localization",
"alias": "locale",
"enactor": {
"type": "fluid.prefs.enactor.localization"
},
"panel": {
"type": "fluid.prefs.panel.localization",
"container": ".flc-prefsEditor-localization", // the css selector in the template where the panel is rendered
"template": "%templatePrefix/PrefsEditorTemplate-localization.html",
"message": "%messagePrefix/localization.json"
}
}
}
});
/*******************************************************************************
* Primary Schema
*******************************************************************************/
// add extra prefs to the starter primary schemas
fluid.defaults("fluid.prefs.schemas.localization", {
gradeNames: ["fluid.prefs.schemas"],
schema: {
"fluid.prefs.localization": {
"type": "string",
"default": "",
"enum": ["", "en", "en_CA", "en_US", "fr", "es", "fa"],
"enumLabels": [
"localization-default",
"localization-en",
"localization-fr",
"localization-es",
"localization-fa"
]
}
}
});
})(fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function (fluid) {
"use strict";
/*******************************************************************************
* Starter auxiliary schema grade
*
* Contains the settings for the localization preference
*******************************************************************************/
// Fine-tune the starter aux schema and add localization preference
fluid.defaults("fluid.prefs.constructed.localizationPrefsEditorConfig", {
gradeNames: ["fluid.contextAware"],
contextAwareness: {
localeChange: {
checks: {
urlPath: {
contextValue: "{localizationPrefsEditorConfig}.options.localizationScheme",
equals: "urlPath",
gradeNames: "fluid.prefs.constructed.localizationPrefsEditorConfig.urlPathLocale"
}
}
}
},
distributeOptions: {
"prefsEditor.localization.enactor.localizationScheme": {
source: "{that}.options.localizationScheme",
target: "{that uiEnhancer fluid.prefs.enactor.localization}.options.localizationScheme"
},
"prefsEditor.localization.panel.locales": {
source: "{that}.options.locales",
target: "{that prefsEditor fluid.prefs.panel.localization}.options.controlValues.localization"
},
"prefsEditor.localization.panel.localeNames": {
source: "{that}.options.localeNames",
target: "{that prefsEditor fluid.prefs.panel.localization}.options.stringArrayIndex.localization"
}
}
});
fluid.defaults("fluid.prefs.constructed.localizationPrefsEditorConfig.urlPathLocale", {
distributeOptions: {
"prefsEditor.localization.enactor.langMap": {
source: "{that}.options.langMap",
target: "{that uiEnhancer fluid.prefs.enactor.localization}.options.langMap"
},
"prefsEditor.localization.enactor.langSegIndex": {
source: "{that}.options.langSegIndex",
target: "{that uiEnhancer fluid.prefs.enactor.localization}.options.langSegIndex"
}
}
});
})(fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function (fluid) {
"use strict";
/*******************************************************************************
* Starter auxiliary schema grade
*
* Contains the settings for the word space preference
*******************************************************************************/
// Fine-tune the starter aux schema and add word space preference
fluid.defaults("fluid.prefs.auxSchema.wordSpace", {
gradeNames: ["fluid.prefs.auxSchema"],
auxiliarySchema: {
"namespace": "fluid.prefs.constructed",
"terms": {
"templatePrefix": "../../framework/preferences/html/",
"messagePrefix": "../../framework/preferences/messages/"
},
"template": "%templatePrefix/SeparatedPanelPrefsEditor.html",
"message": "%messagePrefix/prefsEditor.json",
wordSpace: {
type: "fluid.prefs.wordSpace",
enactor: {
type: "fluid.prefs.enactor.wordSpace",
fontSizeMap: {
"xx-small": "9px",
"x-small": "11px",
"small": "13px",
"medium": "15px",
"large": "18px",
"x-large": "23px",
"xx-large": "30px"
}
},
panel: {
type: "fluid.prefs.panel.wordSpace",
container: ".flc-prefsEditor-word-space",
template: "%templatePrefix/PrefsEditorTemplate-wordSpace.html",
message: "%messagePrefix/wordSpace.json"
}
}
}
});
/*******************************************************************************
* Primary Schema
*******************************************************************************/
// add extra prefs to the starter primary schemas
fluid.defaults("fluid.prefs.schemas.wordSpace", {
gradeNames: ["fluid.prefs.schemas"],
schema: {
"fluid.prefs.wordSpace": {
"type": "number",
"default": 1,
"minimum": 0.7,
"maximum": 2,
"multipleOf": 0.1
}
}
});
})(fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
fluid.registerNamespace("fluid.prefs");
fluid.defaults("fluid.prefs.builder", {
gradeNames: ["fluid.component", "fluid.prefs.auxBuilder"],
mergePolicy: {
auxSchema: "expandedAuxSchema"
},
assembledPrefsEditorGrade: {
expander: {
func: "fluid.prefs.builder.generateGrade",
args: ["prefsEditor", "{that}.options.auxSchema.namespace", {
gradeNames: ["fluid.prefs.assembler.prefsEd", "fluid.viewComponent"],
componentGrades: "{that}.options.constructedGrades",
loaderGrades: "{that}.options.auxSchema.loaderGrades",
defaultLocale: "{that}.options.auxSchema.defaultLocale",
enhancer: {
defaultLocale: "{that}.options.auxSchema.defaultLocale"
}
}]
}
},
assembledUIEGrade: {
expander: {
func: "fluid.prefs.builder.generateGrade",
args: ["uie", "{that}.options.auxSchema.namespace", {
gradeNames: ["fluid.viewComponent", "fluid.prefs.assembler.uie"],
componentGrades: "{that}.options.constructedGrades"
}]
}
},
constructedGrades: {
expander: {
func: "fluid.prefs.builder.constructGrades",
args: [
"{that}.options.auxSchema",
[
"enactors",
"messages",
"panels",
"initialModel",
"templateLoader",
"messageLoader",
"terms",
"aliases_prefsEditor",
"aliases_enhancer"
]
]
}
},
mappedDefaults: "{primaryBuilder}.options.schema.properties",
components: {
primaryBuilder: {
type: "fluid.prefs.primaryBuilder",
options: {
typeFilter: {
expander: {
func: "fluid.prefs.builder.parseAuxSchema",
args: "{builder}.options.auxiliarySchema"
}
}
}
}
},
distributeOptions: {
"builder.primaryBuilder.primarySchema": {
source: "{that}.options.primarySchema",
removeSource: true,
target: "{that > primaryBuilder}.options.primarySchema"
}
}
});
fluid.defaults("fluid.prefs.assembler.uie", {
gradeNames: ["fluid.viewComponent"],
components: {
// These two components become global
store: {
type: "fluid.prefs.globalSettingsStore",
options: {
distributeOptions: {
"uie.store.context.checkUser": {
target: "{that fluid.prefs.store}.options.contextAwareness.strategy.checks.user",
record: {
contextValue: "{fluid.prefs.assembler.uie}.options.storeType",
gradeNames: "{fluid.prefs.assembler.uie}.options.storeType"
}
}
}
}
},
enhancer: {
type: "fluid.component",
options: {
gradeNames: "{that}.options.enhancerType",
enhancerType: "fluid.pageEnhancer",
components: {
uiEnhancer: {
options: {
gradeNames: [
"{fluid.prefs.assembler.uie}.options.componentGrades.enactors",
"{fluid.prefs.assembler.prefsEd}.options.componentGrades.aliases_enhancer"
]
}
}
}
}
}
},
distributeOptions: {
"uie.enhancer": {
source: "{that}.options.enhancer",
target: "{that uiEnhancer}.options",
removeSource: true
},
"uie.enhancer.enhancerType": {
source: "{that}.options.enhancerType",
target: "{that > enhancer}.options.enhancerType"
},
"uie.store": { // TODO: not clear that this hits anything since settings store is not a subcomponent
source: "{that}.options.store",
target: "{that fluid.prefs.store}.options"
}
}
});
fluid.defaults("fluid.prefs.assembler.prefsEd", {
gradeNames: ["fluid.viewComponent", "fluid.prefs.assembler.uie"],
components: {
prefsEditorLoader: {
type: "fluid.viewComponent",
container: "{fluid.prefs.assembler.prefsEd}.container",
priority: "last",
options: {
gradeNames: [
"{fluid.prefs.assembler.prefsEd}.options.componentGrades.terms",
"{fluid.prefs.assembler.prefsEd}.options.componentGrades.messages",
"{fluid.prefs.assembler.prefsEd}.options.componentGrades.initialModel",
"{that}.options.loaderGrades"
],
templateLoader: {
gradeNames: ["{fluid.prefs.assembler.prefsEd}.options.componentGrades.templateLoader"]
},
messageLoader: {
gradeNames: ["{fluid.prefs.assembler.prefsEd}.options.componentGrades.messageLoader"]
},
prefsEditor: {
gradeNames: [
"{fluid.prefs.assembler.prefsEd}.options.componentGrades.panels",
"{fluid.prefs.assembler.prefsEd}.options.componentGrades.aliases_prefsEditor",
"fluid.prefs.uiEnhancerRelay"
]
},
events: {
onReady: "{fluid.prefs.assembler.prefsEd}.events.onPrefsEditorReady"
}
}
}
},
events: {
onPrefsEditorReady: null,
onReady: {
events: {
onPrefsEditorReady: "onPrefsEditorReady",
onCreate: "onCreate"
},
args: ["{that}"]
}
},
distributeOptions: {
"prefsEdAssembler.prefsEditorLoader.loaderGrades": {
source: "{that}.options.loaderGrades",
removeSource: true,
target: "{that > prefsEditorLoader}.options.loaderGrades"
},
"prefsEdAssembler.prefsEditorLoader.terms": {
source: "{that}.options.terms",
removeSource: true,
target: "{that prefsEditorLoader}.options.terms"
},
"prefsEdAssembler.prefsEditorLoader.defaultLocale": {
source: "{that}.options.defaultLocale",
target: "{that prefsEditorLoader}.options.defaultLocale"
},
"prefsEdAssembler.uiEnhancer.defaultLocale": {
source: "{that}.options.defaultLocale",
target: "{that uiEnhancer}.options.defaultLocale"
},
"prefsEdAssembler.prefsEditor": {
source: "{that}.options.prefsEditor",
removeSource: true,
target: "{that prefsEditor}.options"
}
}
});
fluid.prefs.builder.generateGrade = function (name, namespace, options) {
var gradeNameTemplate = "%namespace.%name";
var gradeName = fluid.stringTemplate(gradeNameTemplate, {name: name, namespace: namespace});
fluid.defaults(gradeName, options);
return gradeName;
};
fluid.prefs.builder.constructGrades = function (auxSchema, gradeCategories) {
var constructedGrades = {};
fluid.each(gradeCategories, function (category) {
var gradeOpts = auxSchema[category];
if (fluid.get(gradeOpts, "gradeNames")) {
constructedGrades[category] = fluid.prefs.builder.generateGrade(category, auxSchema.namespace, gradeOpts);
}
});
return constructedGrades;
};
fluid.prefs.builder.parseAuxSchema = function (auxSchema) {
var auxTypes = [];
fluid.each(auxSchema, function parse(field) {
var type = field.type;
if (type) {
auxTypes.push(type);
}
});
return auxTypes;
};
/*
* A one-stop-shop function to build and instantiate a prefsEditor from a schema.
*/
fluid.prefs.create = function (container, options) {
options = options || {};
var builder = fluid.prefs.builder(options.build);
return fluid.invokeGlobalFunction(builder.options.assembledPrefsEditorGrade, [container, options.prefsEditor]);
};
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
// Gradename to invoke "fluid.uiOptions.prefsEditor"
fluid.prefs.builder({
gradeNames: ["fluid.prefs.auxSchema.starter"]
});
fluid.defaults("fluid.uiOptions.prefsEditor", {
gradeNames: ["fluid.prefs.constructed.prefsEditor"],
lazyLoad: false,
distributeOptions: {
"uio.separatedPanel.lazyLoad": {
record: "{that}.options.lazyLoad",
target: "{that separatedPanel}.options.lazyLoad"
},
"uio.uiEnhancer.tocTemplate": {
source: "{that}.options.tocTemplate",
target: "{that uiEnhancer > tableOfContents}.options.tocTemplate"
},
"uio.uiEnhancer.tocMessage": {
source: "{that}.options.tocMessage",
target: "{that uiEnhancer > tableOfContents}.options.tocMessage"
},
"uio.uiEnhancer.ignoreForToC": {
source: "{that}.options.ignoreForToC",
target: "{that uiEnhancer > tableOfContents}.options.ignoreForToC"
}
}
});
})(jQuery, fluid_3_0_0);
;
/*!
* jQuery.scrollTo
* Copyright (c) 2007-2015 Ariel Flesler - aflesler<a>gmail<d>com | http://flesler.blogspot.com
* Licensed under MIT
* http://flesler.blogspot.com/2007/10/jqueryscrollto.html
* @projectDescription Lightweight, cross-browser and highly customizable animated scrolling with jQuery
* @author Ariel Flesler
* @version 2.1.2
*/
;(function(factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
// AMD
define(['jquery'], factory);
} else if (typeof module !== 'undefined' && module.exports) {
// CommonJS
module.exports = factory(require('jquery'));
} else {
// Global
factory(jQuery);
}
})(function($) {
'use strict';
var $scrollTo = $.scrollTo = function(target, duration, settings) {
return $(window).scrollTo(target, duration, settings);
};
$scrollTo.defaults = {
axis:'xy',
duration: 0,
limit:true
};
function isWin(elem) {
return !elem.nodeName ||
$.inArray(elem.nodeName.toLowerCase(), ['iframe','#document','html','body']) !== -1;
}
$.fn.scrollTo = function(target, duration, settings) {
if (typeof duration === 'object') {
settings = duration;
duration = 0;
}
if (typeof settings === 'function') {
settings = { onAfter:settings };
}
if (target === 'max') {
target = 9e9;
}
settings = $.extend({}, $scrollTo.defaults, settings);
// Speed is still recognized for backwards compatibility
duration = duration || settings.duration;
// Make sure the settings are given right
var queue = settings.queue && settings.axis.length > 1;
if (queue) {
// Let's keep the overall duration
duration /= 2;
}
settings.offset = both(settings.offset);
settings.over = both(settings.over);
return this.each(function() {
// Null target yields nothing, just like jQuery does
if (target === null) return;
var win = isWin(this),
elem = win ? this.contentWindow || window : this,
$elem = $(elem),
targ = target,
attr = {},
toff;
switch (typeof targ) {
// A number will pass the regex
case 'number':
case 'string':
if (/^([+-]=?)?\d+(\.\d+)?(px|%)?$/.test(targ)) {
targ = both(targ);
// We are done
break;
}
// Relative/Absolute selector
targ = win ? $(targ) : $(targ, elem);
/* falls through */
case 'object':
if (targ.length === 0) return;
// DOMElement / jQuery
if (targ.is || targ.style) {
// Get the real position of the target
toff = (targ = $(targ)).offset();
}
}
var offset = $.isFunction(settings.offset) && settings.offset(elem, targ) || settings.offset;
$.each(settings.axis.split(''), function(i, axis) {
var Pos = axis === 'x' ? 'Left' : 'Top',
pos = Pos.toLowerCase(),
key = 'scroll' + Pos,
prev = $elem[key](),
max = $scrollTo.max(elem, axis);
if (toff) {// jQuery / DOMElement
attr[key] = toff[pos] + (win ? 0 : prev - $elem.offset()[pos]);
// If it's a dom element, reduce the margin
if (settings.margin) {
attr[key] -= parseInt(targ.css('margin'+Pos), 10) || 0;
attr[key] -= parseInt(targ.css('border'+Pos+'Width'), 10) || 0;
}
attr[key] += offset[pos] || 0;
if (settings.over[pos]) {
// Scroll to a fraction of its width/height
attr[key] += targ[axis === 'x'?'width':'height']() * settings.over[pos];
}
} else {
var val = targ[pos];
// Handle percentage values
attr[key] = val.slice && val.slice(-1) === '%' ?
parseFloat(val) / 100 * max
: val;
}
// Number or 'number'
if (settings.limit && /^\d+$/.test(attr[key])) {
// Check the limits
attr[key] = attr[key] <= 0 ? 0 : Math.min(attr[key], max);
}
// Don't waste time animating, if there's no need.
if (!i && settings.axis.length > 1) {
if (prev === attr[key]) {
// No animation needed
attr = {};
} else if (queue) {
// Intermediate animation
animate(settings.onAfterFirst);
// Don't animate this axis again in the next iteration.
attr = {};
}
}
});
animate(settings.onAfter);
function animate(callback) {
var opts = $.extend({}, settings, {
// The queue setting conflicts with animate()
// Force it to always be true
queue: true,
duration: duration,
complete: callback && function() {
callback.call(elem, targ, settings);
}
});
$elem.animate(attr, opts);
}
});
};
// Max scrolling position, works on quirks mode
// It only fails (not too badly) on IE, quirks mode.
$scrollTo.max = function(elem, axis) {
var Dim = axis === 'x' ? 'Width' : 'Height',
scroll = 'scroll'+Dim;
if (!isWin(elem))
return elem[scroll] - $(elem)[Dim.toLowerCase()]();
var size = 'client' + Dim,
doc = elem.ownerDocument || elem.document,
html = doc.documentElement,
body = doc.body;
return Math.max(html[scroll], body[scroll]) - Math.min(html[size], body[size]);
};
function both(val) {
return $.isFunction(val) || $.isPlainObject(val) ? val : { top:val, left:val };
}
// Add special hooks so that window scroll properties can be animated
$.Tween.propHooks.scrollLeft =
$.Tween.propHooks.scrollTop = {
get: function(t) {
return $(t.elem)[t.prop]();
},
set: function(t) {
var curr = this.get(t);
// If interrupt is true and user scrolled, stop animating
if (t.options.interrupt && t._last && t._last !== curr) {
return $(t.elem).stop();
}
var next = Math.round(t.now);
// Don't waste CPU
// Browsers don't render floating point scroll
if (curr !== next) {
$(t.elem)[t.prop](next);
t._last = this.get(t);
}
}
};
// AMD requirement
return $scrollTo;
});
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
/************
* Uploader *
************/
(function ($, fluid) {
"use strict";
fluid.enhance.supportsBinaryXHR = function () {
return window.FormData || (window.XMLHttpRequest && window.XMLHttpRequest.prototype && window.XMLHttpRequest.prototype.sendAsBinary);
};
fluid.enhance.supportsFormData = function () {
return !!window.FormData;
};
fluid.contextAware.makeChecks({
"fluid.browser.supportsBinaryXHR": {
funcName: "fluid.enhance.supportsBinaryXHR"
},
"fluid.browser.supportsFormData": {
funcName: "fluid.enhance.supportsFormData"
}
});
fluid.registerNamespace("fluid.uploader");
fluid.uploader.fileOrFiles = function (that, numFiles) {
return (numFiles === 1) ? that.options.strings.progress.singleFile :
that.options.strings.progress.pluralFiles;
};
// TODO: Use of these four utilities should be replaced by use of the "visibility model" described in FLUID-4928
fluid.uploader.enableElement = function (that, elm) {
elm.prop("disabled", false);
elm.removeClass(that.options.styles.dim);
};
fluid.uploader.disableElement = function (that, elm) {
elm.prop("disabled", true);
elm.addClass(that.options.styles.dim);
};
fluid.uploader.showElement = function (that, elm) {
elm.removeClass(that.options.styles.hidden);
};
fluid.uploader.hideElement = function (that, elm) {
elm.addClass(that.options.styles.hidden);
};
fluid.uploader.maxFilesUploaded = function (that) {
var fileUploadLimit = that.queue.getUploadedFiles().length + that.queue.getReadyFiles().length + that.queue.getErroredFiles().length;
return (fileUploadLimit === that.options.queueSettings.fileUploadLimit);
};
fluid.uploader.setTotalProgressStyle = function (that, didError) {
didError = didError || false;
var indicator = that.totalProgress.indicator;
indicator.toggleClass(that.options.styles.totalProgress, !didError);
indicator.toggleClass(that.options.styles.totalProgressError, didError);
};
fluid.uploader.setStateEmpty = function (that) {
fluid.uploader.disableElement(that, that.locate("uploadButton"));
// If the queue is totally empty, treat it specially.
if (that.queue.files.length === 0) {
that.locate("browseButtonText").text(that.options.strings.buttons.browse);
that.locate("browseButton").removeClass(that.options.styles.browseButton);
fluid.uploader.showElement(that, that.locate("instructions"));
}
};
// Only enable the browse button if the fileUploadLimit
// has not been reached
fluid.uploader.enableBrowseButton = function (that) {
if (!fluid.uploader.maxFilesUploaded(that)) {
fluid.uploader.enableElement(that, that.locate("browseButton"));
that.strategy.local.enableBrowseButton();
}
};
// See above comment: All of this wasted logic should be replaced by a model mapping system
fluid.uploader.setStateDone = function (that) {
fluid.uploader.disableElement(that, that.locate("uploadButton"));
fluid.uploader.hideElement(that, that.locate("pauseButton"));
fluid.uploader.showElement(that, that.locate("uploadButton"));
fluid.uploader.enableBrowseButton(that);
};
fluid.uploader.setStateLoaded = function (that) {
that.locate("browseButtonText").text(that.options.strings.buttons.addMore);
that.locate("browseButton").addClass(that.options.styles.browseButton);
fluid.uploader.hideElement(that, that.locate("pauseButton"));
fluid.uploader.showElement(that, that.locate("uploadButton"));
fluid.uploader.enableElement(that, that.locate("uploadButton"));
fluid.uploader.hideElement(that, that.locate("instructions"));
that.totalProgress.hide();
fluid.uploader.enableBrowseButton(that);
};
fluid.uploader.setStateUploading = function (that) {
that.totalProgress.hide(false, false);
fluid.uploader.setTotalProgressStyle(that);
fluid.uploader.hideElement(that, that.locate("uploadButton"));
fluid.uploader.disableElement(that, that.locate("browseButton"));
that.strategy.local.disableBrowseButton();
fluid.uploader.enableElement(that, that.locate("pauseButton"));
fluid.uploader.showElement(that, that.locate("pauseButton"));
};
fluid.uploader.setStateFull = function (that) {
that.locate("browseButtonText").text(that.options.strings.buttons.addMore);
that.locate("browseButton").addClass(that.options.styles.browseButton);
fluid.uploader.hideElement(that, that.locate("pauseButton"));
fluid.uploader.showElement(that, that.locate("uploadButton"));
fluid.uploader.enableElement(that, that.locate("uploadButton"));
fluid.uploader.disableElement(that, that.locate("browseButton"));
that.strategy.local.disableBrowseButton();
fluid.uploader.hideElement(that, that.locate("instructions"));
that.totalProgress.hide();
};
fluid.uploader.renderUploadTotalMessage = function (that) {
// Preservered for backwards compatibility, should be refactored post v1.5
var numReadyFiles = that.queue.getReadyFiles().length;
var bytesReadyFiles = that.queue.sizeOfReadyFiles();
var fileLabelStr = fluid.uploader.fileOrFiles(that, numReadyFiles);
var totalCount = that.queue.files.length;
var noFilesMsg = that.options.strings.progress.noFiles;
var totalStateStr = fluid.stringTemplate(that.options.strings.progress.toUploadLabel, {
fileCount: numReadyFiles,
fileLabel: fileLabelStr,
totalBytes: fluid.uploader.formatFileSize(bytesReadyFiles),
uploadedCount: that.queue.getUploadedFiles().length,
uploadedSize: fluid.uploader.formatFileSize(that.queue.sizeOfUploadedFiles()),
totalCount: totalCount,
totalSize: fluid.uploader.formatFileSize(that.queue.totalBytes())
});
if (!totalCount && noFilesMsg) {
totalStateStr = noFilesMsg;
}
that.locate("totalFileStatusText").html(totalStateStr);
};
fluid.uploader.renderFileUploadLimit = function (that) {
if (that.options.queueSettings.fileUploadLimit > 0) {
var fileUploadLimitText = fluid.stringTemplate(that.options.strings.progress.fileUploadLimitLabel, {
fileUploadLimit: that.options.queueSettings.fileUploadLimit,
fileLabel: fluid.uploader.fileOrFiles(that, that.options.queueSettings.fileUploadLimit)
});
that.locate("fileUploadLimitText").html(fileUploadLimitText);
}
};
/**
* Pretty prints a file's size, converting from bytes to kilobytes or megabytes.
*
* @param {Number} bytes - The file's size, specified as in number bytes.
* @return {String} - The file size as a string.
*/
fluid.uploader.formatFileSize = function (bytes) {
if (typeof (bytes) === "number") {
if (bytes === 0) {
return "0.0 KB";
} else if (bytes > 0) {
if (bytes < 1048576) {
return (Math.ceil(bytes / 1024 * 10) / 10).toFixed(1) + " KB";
} else {
return (Math.ceil(bytes / 1048576 * 10) / 10).toFixed(1) + " MB";
}
}
}
return "";
};
fluid.uploader.derivePercent = function (num, total) {
return Math.round((num * 100) / total);
};
fluid.uploader.updateTotalProgress = function (that) {
// Preservered for backwards compatibility, should be refactored post v1.5
var batch = that.queue.currentBatch;
var totalPercent = fluid.uploader.derivePercent(batch.totalBytesUploaded, batch.totalBytes);
var numFilesInBatch = batch.files.length;
var fileLabelStr = fluid.uploader.fileOrFiles(that, numFilesInBatch);
var uploadingSize = batch.totalBytesUploaded + that.queue.sizeOfUploadedFiles();
var totalProgressStr = fluid.stringTemplate(that.options.strings.progress.totalProgressLabel, {
curFileN: batch.fileIdx,
totalFilesN: numFilesInBatch,
fileLabel: fileLabelStr,
currBytes: fluid.uploader.formatFileSize(batch.totalBytesUploaded),
totalBytes: fluid.uploader.formatFileSize(batch.totalBytes),
uploadedCount: that.queue.getUploadedFiles().length,
uploadedSize: fluid.uploader.formatFileSize(uploadingSize),
totalCount: that.queue.files.length,
totalSize: fluid.uploader.formatFileSize(that.queue.totalBytes())
});
that.totalProgress.update(totalPercent, totalProgressStr);
};
fluid.uploader.updateTotalAtCompletion = function (that) {
// Preservered for backwards compatibility, should be refactored post v1.5
var numErroredFiles = that.queue.getErroredFiles().length;
var numTotalFiles = that.queue.files.length;
var fileLabelStr = fluid.uploader.fileOrFiles(that, numTotalFiles);
var errorStr = "";
// if there are errors then change the total progress bar
// and set up the errorStr so that we can use it in the totalProgressStr
if (numErroredFiles > 0) {
var errorLabelString = (numErroredFiles === 1) ? that.options.strings.progress.singleError :
that.options.strings.progress.pluralErrors;
fluid.uploader.setTotalProgressStyle(that, true);
errorStr = fluid.stringTemplate(that.options.strings.progress.numberOfErrors, {
errorsN: numErroredFiles,
errorLabel: errorLabelString
});
}
var totalProgressStr = fluid.stringTemplate(that.options.strings.progress.completedLabel, {
curFileN: that.queue.getUploadedFiles().length,
totalFilesN: numTotalFiles,
errorString: errorStr,
fileLabel: fileLabelStr,
totalCurrBytes: fluid.uploader.formatFileSize(that.queue.sizeOfUploadedFiles()),
uploadedCount: that.queue.getUploadedFiles().length,
uploadedSize: fluid.uploader.formatFileSize(that.queue.sizeOfUploadedFiles()),
totalCount: that.queue.files.length,
totalSize: fluid.uploader.formatFileSize(that.queue.totalBytes())
});
that.totalProgress.update(100, totalProgressStr);
};
fluid.uploader.updateStateAfterFileDialog = function (that) {
var queueLength = that.queue.getReadyFiles().length;
if (queueLength > 0) {
fluid.uploader[queueLength === that.options.queueSettings.fileUploadLimit ? "setStateFull" : "setStateLoaded"](that);
fluid.uploader.renderUploadTotalMessage(that);
that.locate(that.options.focusWithEvent.afterFileDialog).focus();
}
};
fluid.uploader.updateStateAfterFileRemoval = function (that) {
fluid.uploader[that.queue.getReadyFiles().length === 0 ? "setStateEmpty" : "setStateLoaded"] (that);
fluid.uploader.renderUploadTotalMessage(that);
};
fluid.uploader.updateStateAfterCompletion = function (that) {
fluid.uploader[that.queue.getReadyFiles().length === 0 ? "setStateDone" : "setStateLoaded"] (that);
fluid.uploader.updateTotalAtCompletion(that);
};
fluid.uploader.uploadNextOrFinish = function (that) {
if (that.queue.shouldUploadNextFile()) {
that.strategy.remote.uploadNextFile();
} else {
that.events.afterUploadComplete.fire(that.queue.currentBatch.files);
that.queue.clearCurrentBatch();
}
};
// Standard event listening functions
fluid.uploader.onFileStart = function (file, queue) {
file.filestatus = fluid.uploader.fileStatusConstants.IN_PROGRESS;
queue.startFile();
};
// TODO: Improve the dependency profile of this listener and "updateTotalProgress"
fluid.uploader.onFileProgress = function (that, currentBytes) {
that.queue.updateBatchStatus(currentBytes);
fluid.uploader.updateTotalProgress(that);
};
fluid.uploader.onFileComplete = function (file, that) {
that.queue.finishFile(file);
that.events.afterFileComplete.fire(file);
fluid.uploader.uploadNextOrFinish(that);
};
// TODO: Avoid reaching directly into the FileQueue and manipulating its state from this and the next two listeners
fluid.uploader.onFileSuccess = function (file, that) {
file.filestatus = fluid.uploader.fileStatusConstants.COMPLETE;
if (that.queue.currentBatch.bytesUploadedForFile === 0) {
that.queue.currentBatch.totalBytesUploaded += file.size;
}
fluid.uploader.updateTotalProgress(that);
};
fluid.uploader.onFileError = function (file, error, that) {
if (error === fluid.uploader.errorConstants.UPLOAD_STOPPED) {
file.filestatus = fluid.uploader.fileStatusConstants.CANCELLED;
} else {
file.filestatus = fluid.uploader.fileStatusConstants.ERROR;
if (that.queue.isUploading) {
that.queue.currentBatch.totalBytesUploaded += file.size;
that.queue.currentBatch.numFilesErrored++;
fluid.uploader.uploadNextOrFinish(that);
}
}
};
fluid.uploader.afterUploadComplete = function (that) {
that.queue.isUploading = false;
fluid.uploader.updateStateAfterCompletion(that);
};
/**
* Instantiates a new Uploader component.
*
* @param container {Object} the DOM element in which the Uploader lives
* @param options {Object} configuration options for the component.
*/
fluid.defaults("fluid.uploader", {
gradeNames: ["fluid.viewComponent", "fluid.contextAware"],
contextAwareness: {
technology: {
defaultGradeNames: "fluid.uploader.singleFile"
},
liveness: {
priority: "before:technology",
checks: {
localDemoOption: {
contextValue: "{uploader}.options.demo",
gradeNames: "fluid.uploader.demo"
}
},
defaultGradeNames: "fluid.uploader.live"
}
}
});
fluid.defaults("fluid.uploader.builtinStrategyDistributor", {
gradeNames: ["fluid.component"],
distributeOptions: {
record: {
contextValue: "{fluid.browser.supportsBinaryXHR}",
gradeNames: "fluid.uploader.html5"
},
target: "{/ fluid.uploader}.options.contextAwareness.technology.checks.supportsBinaryXHR"
}
});
fluid.constructSingle([], "fluid.uploader.builtinStrategyDistributor");
// Implementation of standard public invoker methods
fluid.uploader.browse = function (queue, localStrategy) {
if (!queue.isUploading) {
localStrategy.browse();
}
};
fluid.uploader.removeFile = function (queue, localStrategy, afterFileRemoved, file) {
queue.removeFile(file);
localStrategy.removeFile(file);
afterFileRemoved.fire(file);
};
fluid.uploader.start = function (queue, remoteStrategy, onUploadStart) {
queue.start();
onUploadStart.fire(queue.currentBatch.files);
remoteStrategy.uploadNextFile();
};
fluid.uploader.stop = function (remoteStrategy, onUploadStop) {
onUploadStop.fire();
remoteStrategy.stop();
};
fluid.uploader.defaultQueueSettings = {
uploadURL: "",
postParams: {},
fileSizeLimit: "20480",
fileTypes: null,
fileTypesDescription: null,
fileUploadLimit: 0,
fileQueueLimit: 0
};
// Automatically bind a listener transferring focus to those DOM elements requested for component events
fluid.uploader.bindFocus = function (focusWithEvent, noAutoFocus, events, dom) {
fluid.each(focusWithEvent, function (element, event) {
if (!noAutoFocus[event]) {
events[event].addListener(function () {
dom.locate(element).focus();
});
}
});
};
/**
* Multiple file Uploader implementation. Encapsulates logic which is common across all configurations supporing multiple
* file uploads - HTML5 (and historically Flash)
*/
fluid.defaults("fluid.uploader.multiFileUploader", {
gradeNames: ["fluid.viewComponent"],
members: {
totalFileStatusTextId: {
expander: {
// create an id for that.dom.container, if it does not have one already,
// and set that.totalFileStatusTextIdId to the id value
funcName: "fluid.allocateSimpleId",
args: "{that}.dom.totalFileStatusText"
}
}
},
invokers: {
/**
* Opens the native OS browse file dialog.
*/
browse: {
funcName: "fluid.uploader.browse",
args: ["{that}.queue", "{that}.strategy.local"]
},
/**
* Removes the specified file from the upload queue.
*
* @param file {File} the file to remove
*/
removeFile: {
funcName: "fluid.uploader.removeFile",
args: ["{that}.queue", "{that}.strategy.local", "{that}.events.afterFileRemoved", "{arguments}.0"]
},
/**
* Starts uploading all queued files to the server.
*/
start: {
funcName: "fluid.uploader.start",
args: ["{that}.queue", "{that}.strategy.remote", "{that}.events.onUploadStart"]
},
/**
* Cancels an in-progress upload.
*/
stop: {
funcName: "fluid.uploader.stop",
args: ["{that}.strategy.remote", "{that}.events.onUploadStop"]
}
},
components: {
queue: {
type: "fluid.uploader.fileQueue"
},
strategy: {
type: "fluid.uploader.strategy"
},
errorPanel: {
type: "fluid.uploader.errorPanel",
container: "{uploader}.dom.errorsPanel",
options: {
gradeNames: "fluid.uploader.errorPanel.bindUploader"
}
},
fileQueueView: {
type: "fluid.uploader.fileQueueView",
container: "{uploader}.dom.fileQueue",
options: {
gradeNames: "fluid.uploader.fileQueueView.bindUploader",
members: { // TODO: This amounts to the entire model idiom for fileQueueView
queueFiles: "{uploader}.queue.files"
},
uploaderContainer: "{uploader}.container",
strings: {
buttons: {
remove: "{uploader}.options.strings.buttons.remove"
}
}
}
},
totalProgress: {
type: "fluid.progress",
container: "{uploader}.container",
options: {
selectors: {
progressBar: ".flc-uploader-queue-footer",
displayElement: ".flc-uploader-total-progress",
label: ".flc-uploader-total-progress-text",
indicator: ".flc-uploader-total-progress",
ariaElement: ".flc-uploader-total-progress"
}
}
}
},
queueSettings: fluid.uploader.defaultQueueSettings,
demo: false,
selectors: {
fileQueue: ".flc-uploader-queue",
browseButton: ".flc-uploader-button-browse",
browseButtonText: ".flc-uploader-button-browse-text",
uploadButton: ".flc-uploader-button-upload",
pauseButton: ".flc-uploader-button-pause",
totalFileStatusText: ".flc-uploader-total-progress-text",
fileUploadLimitText: ".flc-uploader-upload-limit-text",
instructions: ".flc-uploader-browse-instructions",
errorsPanel: ".flc-uploader-errorsPanel"
},
noAutoFocus: { // Specifies a member of "focusWithEvent" which the uploader will not attempt to automatically honour
afterFileDialog: true
},
// Specifies a selector name to move keyboard focus to when a particular event fires.
// Event listeners must already be implemented to use these options.
focusWithEvent: {
afterFileDialog: "uploadButton",
onUploadStart: "pauseButton",
onUploadStop: "uploadButton"
},
styles: {
disabled: "fl-uploader-disabled",
hidden: "fl-uploader-hidden",
dim: "fl-uploader-dim",
totalProgress: "fl-uploader-total-progress-okay",
totalProgressError: "fl-uploader-total-progress-errored",
browseButton: "fl-uploader-browseMore"
},
events: {
// TODO: this event "afterReady" was only fired by the Flash Uploader.
// It should either be removed or refactored post v1.5
afterReady: null,
onFileDialog: null,
onFilesSelected: null,
onFileQueued: null, // file
afterFileQueued: null, // file
onFileRemoved: null, // file
afterFileRemoved: null, // file
afterFileDialog: null,
onUploadStart: null,
onUploadStop: null,
onFileStart: null, // file
onFileProgress: null, // file, currentBytes, totalBytes
onFileError: null, // file, error
onQueueError: null,
onFileSuccess: null,
onFileComplete: null,
afterFileComplete: null,
afterUploadComplete: null
},
listeners: {
"onCreate": [{
listener: "fluid.uploader.bindFocus",
args: ["{that}.options.focusWithEvent", "{that}.options.noAutoFocus", "{that}.events", "{that}.dom"]
}, {
funcName: "fluid.uploader.multiFileUploader.setupMarkup",
namespace: "setupMarkup"
},
{ // TODO: These two part of the "new renderer" as "new decorators"
"this": "{that}.dom.uploadButton",
method: "click",
args: "{that}.start"
}, {
"this": "{that}.dom.pauseButton",
method: "click",
args: "{that}.stop"
}, {
"this": "{that}.dom.totalFileStatusText",
method: "attr",
args: [{
"role": "log",
"aria-live": "assertive",
"aria-relevant": "text",
"aria-atomic": "true"
}]
}, {
"this": "{that}.dom.fileQueue",
method: "attr",
args: [{
"aria-controls": "{that}.totalFileStatusTextId",
"aria-labelledby": "{that}.totalFileStatusTextId"
}]
}],
// Namespace all our standard listeners so they are easy to override
"afterFileDialog.uploader": {
listener: "fluid.uploader.updateStateAfterFileDialog",
args: "{that}"
},
"afterFileQueued.uploader": {
listener: "{that}.queue.addFile",
args: "{arguments}.0" // file
},
"onFileRemoved.uploader": {
listener: "{that}.removeFile",
args: "{arguments}.0" // file
},
"afterFileRemoved.uploader": {
listener: "fluid.uploader.updateStateAfterFileRemoval",
args: "{that}"
},
"onUploadStart.uploader": {
listener: "fluid.uploader.setStateUploading",
args: "{that}"
},
"onFileStart.uploader": {
listener: "fluid.uploader.onFileStart",
args: ["{arguments}.0", "{that}.queue"]
},
"onFileProgress.uploader": {
listener: "fluid.uploader.onFileProgress",
args: ["{that}", "{arguments}.1"] // 1: currentBytes
},
"onFileComplete.uploader": {
listener: "fluid.uploader.onFileComplete",
args: ["{arguments}.0", "{that}"]
},
"onFileSuccess.uploader": {
listener: "fluid.uploader.onFileSuccess",
args: ["{arguments}.0", "{that}"]
},
"onFileError.uploader": {
listener: "fluid.uploader.onFileError",
args: ["{arguments}.0", "{arguments}.1", "{that}"]
},
"afterUploadComplete.uploader": {
listener: "fluid.uploader.afterUploadComplete",
args: "{that}"
}
},
strings: {
progress: {
fileUploadLimitLabel: "%fileUploadLimit %fileLabel maximum",
noFiles: "0 files",
toUploadLabel: "%uploadedCount out of %totalCount files uploaded (%uploadedSize of %totalSize)",
totalProgressLabel: "%uploadedCount out of %totalCount files uploaded (%uploadedSize of %totalSize)",
completedLabel: "%uploadedCount out of %totalCount files uploaded (%uploadedSize of %totalSize)%errorString",
numberOfErrors: ", %errorsN %errorLabel",
singleFile: "file",
pluralFiles: "files",
singleError: "error",
pluralErrors: "errors"
},
buttons: {
browse: "Browse Files",
addMore: "Add More",
stopUpload: "Stop Upload",
cancelRemaning: "Cancel remaining Uploads",
resumeUpload: "Resume Upload",
remove: "Remove"
}
}
});
fluid.uploader.multiFileUploader.setupMarkup = function (that) {
// Upload button should not be enabled until there are files to upload
fluid.uploader.disableElement(that, that.locate("uploadButton"));
fluid.uploader.renderFileUploadLimit(that);
// placed here for backwards compatibility, as a noFiles string
// may not be defined.
var noFilesMsg = that.options.strings.progress.noFiles;
if (noFilesMsg) {
that.locate("totalFileStatusText").text(noFilesMsg);
}
};
fluid.defaults("fluid.uploader.strategy", {
gradeNames: ["fluid.component"],
components: {
local: {
type: "fluid.uploader.local"
},
remote: {
type: "fluid.uploader.remote"
}
}
});
fluid.defaults("fluid.uploader.local", {
gradeNames: ["fluid.component"],
queueSettings: "{uploader}.options.queueSettings",
members: {
queue: "{uploader}.queue"
},
events: {
onFileDialog: "{uploader}.events.onFileDialog",
onFilesSelected: "{uploader}.events.onFilesSelected",
afterFileDialog: "{uploader}.events.afterFileDialog",
afterFileQueued: "{uploader}.events.afterFileQueued",
onQueueError: "{uploader}.events.onQueueError"
},
invokers: {
enableBrowseButton: "fluid.uploader.local.enableBrowseButton", // TODO: FLUID-4928 "visibility model"
disableBrowseButton: "fluid.uploader.local.disableBrowseButton"
}
});
fluid.defaults("fluid.uploader.remote", {
gradeNames: ["fluid.component"],
members: {
queue: "{uploader}.queue", // TODO: explosions, see FLUID-4925
queueSettings: "{uploader}.options.queueSettings"
},
events: {
onFileStart: "{uploader}.events.onFileStart",
onFileProgress: "{uploader}.events.onFileProgress",
onFileSuccess: "{uploader}.events.onFileSuccess",
onFileError: "{uploader}.events.onFileError",
onFileComplete: "{uploader}.events.onFileComplete",
onUploadStop: "{uploader}.events.onUploadStop",
afterFileComplete: "{uploader}.events.afterFileComplete",
afterUploadComplete: "{uploader}.events.afterUploadComplete"
},
invokers: {
uploadNextFile: "fluid.uploader.uploadNextFile",
stop: "fluid.uploader.stop"
}
});
/**************************************************
* Error constants for the Uploader *
**************************************************/
// Partial TODO: The values of these keys are now our own - however, the key
// values themselves still align with those from SWFUpload
fluid.uploader.queueErrorConstants = {
QUEUE_LIMIT_EXCEEDED: "queue limit exceeded",
FILE_EXCEEDS_SIZE_LIMIT: "file exceeds size limit",
ZERO_BYTE_FILE: "zero byte file",
INVALID_FILETYPE: "invalid filetype"
};
fluid.uploader.errorConstants = {
HTTP_ERROR: "HTTP error",
MISSING_UPLOAD_URL: "Missing upload URL",
IO_ERROR: "I/O error",
SECURITY_ERROR: "Security error",
UPLOAD_LIMIT_EXCEEDED: "Upload limit exceeded",
UPLOAD_FAILED: "Uploader failed",
SPECIFIED_FILE_ID_NOT_FOUND: "Specified file ID not found",
FILE_VALIDATION_FAILED: "File validation failed",
FILE_CANCELLED: "File cancelled",
UPLOAD_STOPPED: "Upload stopped"
};
fluid.uploader.fileStatusConstants = {
QUEUED: "queued",
IN_PROGRESS: "in progress",
ERROR: "error",
COMPLETE: "complete",
CANCELLED: "cancelled"
};
/**
* Single file Uploader implementation. Use fluid.uploader() for IoC-resolved, progressively
* enhanceable Uploader, or call this directly if you only want a standard single file uploader.
* But why would you want that?
*
* @param container {jQueryable} the component's container
* @param options {Object} configuration options
*/
fluid.defaults("fluid.uploader.singleFile", {
gradeNames: ["fluid.viewComponent"],
selectors: {
basicUpload: ".fl-progEnhance-basic"
},
listeners: {
"onCreate.showMarkup": "fluid.uploader.singleFile.showMarkup"
}
});
fluid.uploader.singleFile.toggleVisibility = function (toShow, toHide) {
// For FLUID-2789: hide() doesn't work in Opera
if (window.opera) {
toShow.show().removeClass("hideUploaderForOpera");
toHide.show().addClass("hideUploaderForOpera");
} else {
toShow.show();
toHide.hide();
}
};
fluid.uploader.singleFile.showMarkup = function (that) {
// TODO: direct DOM fascism that will fail with multiple uploaders on a single page.
fluid.uploader.singleFile.toggleVisibility($(that.options.selectors.basicUpload), that.container);
};
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
fluid.registerNamespace("fluid.uploader");
fluid.defaults("fluid.uploader.fileQueue", {
gradeNames: ["fluid.component"],
members: {
files: [],
isUploading: false
},
invokers: {
/********************
* Queue Operations *
********************/
start: {
funcName: "fluid.uploader.fileQueue.start",
args: "{that}"
},
startFile: {
funcName: "fluid.uploader.fileQueue.startFile",
args: "{that}.currentBatch"
},
finishFile: {
funcName: "fluid.uploader.fileQueue.finishFile",
args: "{that}.currentBatch"
},
shouldUploadNextFile: {
funcName: "fluid.uploader.fileQueue.shouldUploadNextFile",
args: "{that}"
},
/*****************************
* File manipulation methods *
*****************************/
addFile: {
funcName: "fluid.uploader.fileQueue.addFile",
args: ["{that}.files", "{arguments}.0"]
},
removeFile: {
funcName: "fluid.uploader.fileQueue.removeFile",
args: ["{that}.files", "{arguments}.0"]
},
/**********************
* Queue Info Methods *
**********************/
totalBytes: {
funcName: "fluid.uploader.fileQueue.sizeOfFiles",
args: "{that}.files"
},
getReadyFiles: {
funcName: "fluid.uploader.fileQueue.filesByStatus",
args: ["{that}.files", ["QUEUED", "CANCELLED"]]
},
getErroredFiles: {
funcName: "fluid.uploader.fileQueue.filesByStatus",
args: ["{that}.files", "ERROR"]
},
getUploadedFiles: {
funcName: "fluid.uploader.fileQueue.filesByStatus",
args: ["{that}.files", "COMPLETE"]
},
sizeOfReadyFiles: {
funcName: "fluid.uploader.fileQueue.sizeOfFilesByStatus",
args: ["{that}.files", ["QUEUED", "CANCELLED"]]
},
sizeOfUploadedFiles: {
funcName: "fluid.uploader.fileQueue.sizeOfFilesByStatus",
args: ["{that}.files", "COMPLETE"]
},
/*****************
* Batch Methods *
*****************/
setupCurrentBatch: {
funcName: "fluid.uploader.fileQueue.setupCurrentBatch",
args: "{that}"
},
clearCurrentBatch: {
funcName: "fluid.uploader.fileQueue.clearCurrentBatch",
args: "{that}"
},
updateCurrentBatch: {
funcName: "fluid.uploader.fileQueue.updateCurrentBatch",
args: [{expander: {func: "{that}.getReadyFiles"}}, "{that}.currentBatch"]
},
updateBatchStatus: {
funcName: "fluid.uploader.fileQueue.updateBatchStatus",
args: ["{arguments}.0", "{that}.currentBatch"]
}
}
});
fluid.uploader.fileQueue.start = function (that) {
that.setupCurrentBatch();
that.isUploading = true;
that.shouldStop = false;
};
fluid.uploader.fileQueue.startFile = function (currentBatch) {
currentBatch.fileIdx++;
currentBatch.bytesUploadedForFile = 0;
currentBatch.previousBytesUploadedForFile = 0;
};
fluid.uploader.fileQueue.finishFile = function (currentBatch) {
currentBatch.numFilesCompleted++;
};
fluid.uploader.fileQueue.shouldUploadNextFile = function (that) {
return !that.shouldStop &&
that.isUploading &&
(that.currentBatch.numFilesCompleted + that.currentBatch.numFilesErrored) <
that.currentBatch.files.length;
};
fluid.uploader.fileQueue.addFile = function (files, file) {
files.push(file);
};
fluid.uploader.fileQueue.removeFile = function (files, file) {
fluid.remove_if(files, function (thisFile) {
return file === thisFile;
});
};
fluid.uploader.fileQueue.sizeOfFiles = function (files) {
return fluid.accumulate(files, function (file, totalBytes) {
return totalBytes + file.size;
}, 0);
};
fluid.uploader.fileQueue.filterFiles = function (files, filterFn) {
var filteredFiles = []; // filterFn returns TRUE for the files we want
return fluid.remove_if(fluid.makeArray(files), filterFn, filteredFiles);
};
fluid.uploader.fileQueue.filesByStatus = function (files, statuses) {
statuses = fluid.makeArray(statuses);
return fluid.uploader.fileQueue.filterFiles(files, function (file) {
return fluid.find_if(statuses, function (status) {
return file.filestatus === fluid.uploader.fileStatusConstants[status];
});
});
};
fluid.uploader.fileQueue.sizeOfFilesByStatus = function (files, statuses) {
files = fluid.uploader.fileQueue.filesByStatus(files, statuses);
return fluid.uploader.fileQueue.sizeOfFiles(files);
};
fluid.uploader.fileQueue.setupCurrentBatch = function (that) {
that.clearCurrentBatch();
that.updateCurrentBatch();
};
fluid.uploader.fileQueue.clearCurrentBatch = function (that) {
that.currentBatch = {
fileIdx: 0,
files: [],
totalBytes: 0,
numFilesCompleted: 0,
numFilesErrored: 0,
bytesUploadedForFile: 0,
previousBytesUploadedForFile: 0,
totalBytesUploaded: 0
};
};
fluid.uploader.fileQueue.updateCurrentBatch = function (readyFiles, currentBatch) {
currentBatch.files = readyFiles;
currentBatch.totalBytes = fluid.uploader.fileQueue.sizeOfFiles(readyFiles);
};
fluid.uploader.fileQueue.updateBatchStatus = function (currentBytes, currentBatch) {
var byteIncrement = currentBytes - currentBatch.previousBytesUploadedForFile;
currentBatch.totalBytesUploaded += byteIncrement;
currentBatch.bytesUploadedForFile += byteIncrement;
currentBatch.previousBytesUploadedForFile = currentBytes;
};
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
/*******************
* File Queue View *
*******************/
(function ($, fluid) {
"use strict";
fluid.registerNamespace("fluid.uploader.fileQueueView");
// Real data binding would be nice to replace these two pairs.
fluid.uploader.fileQueueView.rowForFile = function (that, file) {
return that.container.find("#" + file.id);
};
fluid.uploader.fileQueueView.errorRowForFile = function (that, file) {
return $("#" + file.id + "_error", that.container);
};
// TODO: None of this hierarchy operates a proper model idiom since it just shares an array instance with fileQueue
fluid.uploader.fileQueueView.fileForRow = function (that, row) {
return fluid.find_if(that.queueFiles, function (file) {
return file.id.toString() === row.prop("id");
});
};
fluid.uploader.fileQueueView.progressorForFile = function (that, file) {
var progressId = file.id + "_progress";
return that.fileProgressors[progressId];
};
fluid.uploader.fileQueueView.startFileProgress = function (that, file) {
var fileRowElm = fluid.uploader.fileQueueView.rowForFile(that, file);
that.scroller.scrollTo(fileRowElm);
// update the progressor and make sure that it's in position
var fileProgressor = fluid.uploader.fileQueueView.progressorForFile(that, file);
fileProgressor.refreshView();
fileProgressor.show();
};
fluid.uploader.fileQueueView.updateFileProgress = function (that, file, fileBytesComplete, fileTotalBytes) {
var filePercent = fluid.uploader.derivePercent(fileBytesComplete, fileTotalBytes);
var filePercentStr = filePercent + "%";
fluid.uploader.fileQueueView.progressorForFile(that, file).update(filePercent, filePercentStr);
};
fluid.uploader.fileQueueView.hideFileProgress = function (that, file) {
var fileRowElm = fluid.uploader.fileQueueView.rowForFile(that, file);
fluid.uploader.fileQueueView.progressorForFile(that, file).hide();
if (file.filestatus === fluid.uploader.fileStatusConstants.COMPLETE) {
that.locate("fileIconBtn", fileRowElm).removeClass(that.options.styles.dim);
}
};
fluid.uploader.fileQueueView.removeFileProgress = function (that, file) {
var fileProgressor = fluid.uploader.fileQueueView.progressorForFile(that, file);
if (!fileProgressor) {
return;
}
var rowProgressor = fileProgressor.displayElement;
rowProgressor.remove();
};
fluid.uploader.fileQueueView.animateRowRemoval = function (that, row) {
row.fadeOut("fast", function () {
row.remove();
that.refreshView();
});
};
fluid.uploader.fileQueueView.removeFileErrorRow = function (that, file) {
if (file.filestatus === fluid.uploader.fileStatusConstants.ERROR) {
fluid.uploader.fileQueueView.animateRowRemoval(that, fluid.uploader.fileQueueView.errorRowForFile(that, file));
}
};
fluid.uploader.fileQueueView.removeFileAndRow = function (that, file, row) {
// Clean up the stuff associated with a file row.
fluid.uploader.fileQueueView.removeFileProgress(that, file);
fluid.uploader.fileQueueView.removeFileErrorRow(that, file);
// Remove the file itself.
that.events.onFileRemoved.fire(file);
fluid.uploader.fileQueueView.animateRowRemoval(that, row);
};
fluid.uploader.fileQueueView.removeFileForRow = function (that, row) {
var file = fluid.uploader.fileQueueView.fileForRow(that, row);
if (!file || file.filestatus === fluid.uploader.fileStatusConstants.COMPLETE) {
return;
}
fluid.uploader.fileQueueView.removeFileAndRow(that, file, row);
};
fluid.uploader.fileQueueView.removeRowForFile = function (that, file) {
var row = fluid.uploader.fileQueueView.rowForFile(that, file);
fluid.uploader.fileQueueView.removeFileAndRow(that, file, row);
};
fluid.uploader.fileQueueView.bindHover = function (row, styles) {
var over = function () {
if (row.hasClass(styles.ready) && !row.hasClass(styles.uploading)) {
row.addClass(styles.hover);
}
};
var out = function () {
if (row.hasClass(styles.ready) && !row.hasClass(styles.uploading)) {
row.removeClass(styles.hover);
}
};
row.hover(over, out);
};
fluid.uploader.fileQueueView.bindDeleteKey = function (that, row) {
var deleteHandler = function () {
fluid.uploader.fileQueueView.removeFileForRow(that, row);
};
fluid.activatable(row, null, {
additionalBindings: [{
key: $.ui.keyCode.DELETE,
activateHandler: deleteHandler
}]
});
};
fluid.uploader.fileQueueView.bindRowHandlers = function (that, row) {
if ($.browser.msie && $.browser.version < 7) {
fluid.uploader.fileQueueView.bindHover(row, that.options.styles);
}
that.locate("fileIconBtn", row).click(function () {
fluid.uploader.fileQueueView.removeFileForRow(that, row);
});
fluid.uploader.fileQueueView.bindDeleteKey(that, row);
};
fluid.uploader.fileQueueView.renderRowFromTemplate = function (that, file) {
var row = that.rowTemplate.clone(),
fileName = file.name,
fileSize = fluid.uploader.formatFileSize(file.size);
row.removeClass(that.options.styles.hiddenTemplate);
that.locate("fileName", row).text(fileName);
that.locate("fileSize", row).text(fileSize);
var fileIconBtn = that.locate("fileIconBtn", row);
fileIconBtn.addClass(that.options.styles.remove);
fluid.updateAriaLabel(fileIconBtn, that.options.strings.buttons.remove);
row.prop("id", file.id);
row.addClass(that.options.styles.ready);
fluid.uploader.fileQueueView.bindRowHandlers(that, row);
fluid.updateAriaLabel(row, fileName + " " + fileSize);
return row;
};
fluid.uploader.fileQueueView.createProgressorFromTemplate = function (that, row) {
// create a new progress bar for the row and position it
var rowProgressor = that.rowProgressorTemplate.clone();
var rowId = row.prop("id");
var progressId = rowId + "_progress";
rowProgressor.prop("id", progressId);
rowProgressor.css("top", row.position().top);
rowProgressor.height(row.height()).width(5);
that.container.after(rowProgressor);
that.fileProgressors[progressId] = fluid.progress(that.options.uploaderContainer, {
selectors: {
progressBar: "#" + rowId,
displayElement: "#" + progressId,
label: "#" + progressId + " .fl-uploader-file-progress-text",
indicator: "#" + progressId
}
});
};
fluid.uploader.fileQueueView.addFile = function (that, file) {
var row = fluid.uploader.fileQueueView.renderRowFromTemplate(that, file);
/* FLUID-2720 - do not hide the row under IE8 */
if (!($.browser.msie && ($.browser.version >= 8))) {
row.hide();
}
that.container.append(row);
row.attr("title", that.options.strings.status.remove);
row.fadeIn("slow");
fluid.uploader.fileQueueView.createProgressorFromTemplate(that, row);
that.refreshView();
that.scroller.scrollTo("max");
};
// Toggle keyboard row handlers on and off depending on the uploader state
fluid.uploader.fileQueueView.enableRows = function (rows, state) {
for (var i = 0; i < rows.length; i++) {
fluid.enabled(rows[i], state);
}
};
fluid.uploader.fileQueueView.prepareForUpload = function (that) {
var rowButtons = that.locate("fileIconBtn", that.locate("fileRows"));
rowButtons.prop("disabled", true);
rowButtons.addClass(that.options.styles.dim);
fluid.uploader.fileQueueView.enableRows(that.locate("fileRows"), false);
};
fluid.uploader.fileQueueView.refreshAfterUpload = function (that) {
var rows = that.locate("fileRows");
var rowButtons = that.locate("fileIconBtn", rows);
// only re-enable rowButtons for files that have not been uploaded.
rowButtons.each(function (index, rowButton) {
// TODO: Improve detection of completed files so as not to rely on row styling.
$(rowButton).prop("disabled", rows.eq(index).hasClass(that.options.styles.uploaded));
});
rowButtons.removeClass(that.options.styles.dim);
fluid.uploader.fileQueueView.enableRows(that.locate("fileRows"), true);
};
fluid.uploader.fileQueueView.changeRowState = function (that, row, newState) {
row.removeClass(that.options.styles.ready).removeClass(that.options.styles.error).addClass(newState);
};
fluid.uploader.fileQueueView.markRowAsComplete = function (that, file) {
// update styles and keyboard bindings for the file row
var row = fluid.uploader.fileQueueView.rowForFile(that, file);
fluid.uploader.fileQueueView.changeRowState(that, row, that.options.styles.uploaded);
row.attr("title", that.options.strings.status.success);
fluid.enabled(row, false);
// update the click event and the styling for the file delete button
var rowButton = that.locate("fileIconBtn", row);
rowButton.off("click");
rowButton.removeClass(that.options.styles.remove);
rowButton.attr("title", that.options.strings.status.success);
};
fluid.uploader.fileQueueView.renderErrorInfoFromTemplate = function (that, fileRow, error) {
// Render the row by cloning the template and binding its id to the file.
var errorRow = that.errorInfoTemplate.clone();
errorRow.prop("id", fileRow.prop("id") + "_error");
// Look up the error message and render it.
var errorType = fluid.keyForValue(fluid.uploader.errorConstants, error);
var errorMsg = that.options.strings.errors[errorType];
that.locate("errorText", errorRow).text(errorMsg);
that.locate("fileName", fileRow).after(errorRow);
that.scroller.scrollTo(errorRow);
};
fluid.uploader.fileQueueView.showErrorForFile = function (that, file, error) {
fluid.uploader.fileQueueView.hideFileProgress(that, file);
if (file.filestatus === fluid.uploader.fileStatusConstants.ERROR) {
var fileRowElm = fluid.uploader.fileQueueView.rowForFile(that, file);
fluid.uploader.fileQueueView.changeRowState(that, fileRowElm, that.options.styles.error);
fluid.uploader.fileQueueView.renderErrorInfoFromTemplate(that, fileRowElm, error);
}
};
fluid.uploader.fileQueueView.addKeyboardNavigation = function (that) {
fluid.tabbable(that.container);
that.selectableContext = fluid.selectable(that.container, {
selectableSelector: that.options.selectors.fileRows,
onSelect: function (itemToSelect) {
$(itemToSelect).addClass(that.options.styles.selected);
},
onUnselect: function (selectedItem) {
$(selectedItem).removeClass(that.options.styles.selected);
}
});
};
fluid.uploader.fileQueueView.prepareTemplateElements = function (that) {
// Grab our template elements out of the DOM.
that.errorInfoTemplate = that.locate("errorInfoTemplate").remove();
that.errorInfoTemplate.removeClass(that.options.styles.hiddenTemplate);
that.rowTemplate = that.locate("rowTemplate").remove();
that.rowProgressorTemplate = that.locate("rowProgressorTemplate", that.options.uploaderContainer).remove();
};
fluid.uploader.fileQueueView.markFileComplete = function (that, file) {
fluid.uploader.fileQueueView.progressorForFile(that, file).update(100, "100%");
fluid.uploader.fileQueueView.markRowAsComplete(that, file);
};
fluid.uploader.fileQueueView.refreshView = function (that) {
that.selectableContext.refresh();
that.scroller.refreshView();
};
/**
* Creates a new File Queue view.
*
* @param container {jQuery|selector} the file queue's container DOM element
* @param queue {fileQueue} a file queue model instance
* @param options {Object} configuration options for the view
*/
fluid.defaults("fluid.uploader.fileQueueView", {
gradeNames: ["fluid.viewComponent"],
mergePolicy: {
// TODO: This mergePolicy was required by some attempts at fixing FLUID-5668
// and may be required again in future if this component is not modelised
// "members.queueFiles": "nomerge"
},
members: {
fileProgressors: {}
// queueFiles: applied in uploader options - TODO: no model idiom
},
invokers: {
addFile: {
funcName: "fluid.uploader.fileQueueView.addFile",
args: ["{that}", "{arguments}.0"] // file
},
removeFile: {
funcName: "fluid.uploader.fileQueueView.removeRowForFile",
args: ["{that}", "{arguments}.0"] // file
},
prepareForUpload: {
funcName: "fluid.uploader.fileQueueView.prepareForUpload",
args: "{that}"
},
refreshAfterUpload: {
funcName: "fluid.uploader.fileQueueView.refreshAfterUpload",
args: "{that}"
},
showFileProgress: {
funcName: "fluid.uploader.fileQueueView.startFileProgress",
args: ["{that}", "{arguments}.0"] // file
},
updateFileProgress: {
funcName: "fluid.uploader.fileQueueView.updateFileProgress",
args: ["{that}", "{arguments}.0", "{arguments}.1", "{arguments}.2"] // file, fileBytesComplete, fileTotalBytes
},
markFileComplete: {
funcName: "fluid.uploader.fileQueueView.markFileComplete",
args: ["{that}", "{arguments}.0"] // file
},
showErrorForFile: {
funcName: "fluid.uploader.fileQueueView.showErrorForFile",
args: ["{that}", "{arguments}.0", "{arguments}.1"] // file, error
},
hideFileProgress: {
funcName: "fluid.uploader.fileQueueView.hideFileProgress",
args: ["{that}", "{arguments}.0"] // file
},
refreshView: {
funcName: "fluid.uploader.fileQueueView.refreshView",
args: "{that}"
}
},
components: {
scroller: {
type: "fluid.scrollableTable",
container: "{fileQueueView}.container"
}
},
selectors: {
fileRows: ".flc-uploader-file",
fileName: ".flc-uploader-file-name",
fileSize: ".flc-uploader-file-size",
fileIconBtn: ".flc-uploader-file-action",
errorText: ".flc-uploader-file-error",
rowTemplate: ".flc-uploader-file-tmplt",
errorInfoTemplate: ".flc-uploader-file-error-tmplt",
rowProgressorTemplate: ".flc-uploader-file-progressor-tmplt"
},
styles: {
hover: "fl-uploader-file-hover",
selected: "fl-uploader-file-focus",
ready: "fl-uploader-file-state-ready",
uploading: "fl-uploader-file-state-uploading",
uploaded: "fl-uploader-file-state-uploaded",
error: "fl-uploader-file-state-error",
remove: "fl-uploader-file-action-remove",
dim: "fl-uploader-dim",
hiddenTemplate: "fl-uploader-hidden-templates"
},
strings: {
progress: {
toUploadLabel: "To upload: %fileCount %fileLabel (%totalBytes)",
singleFile: "file",
pluralFiles: "files"
},
status: {
success: "File Uploaded",
error: "File Upload Error",
remove: "Press Delete key to remove file"
},
errors: {
HTTP_ERROR: "File upload error: a network error occured or the file was rejected (reason unknown).",
IO_ERROR: "File upload error: a network error occured.",
UPLOAD_LIMIT_EXCEEDED: "File upload error: you have uploaded as many files as you are allowed during this session",
UPLOAD_FAILED: "File upload error: the upload failed for an unknown reason.",
QUEUE_LIMIT_EXCEEDED: "You have as many files in the queue as can be added at one time. Removing files from the queue may allow you to add different files.",
FILE_EXCEEDS_SIZE_LIMIT: "One or more of the files that you attempted to add to the queue exceeded the limit of %fileSizeLimit.",
ZERO_BYTE_FILE: "One or more of the files that you attempted to add contained no data.",
INVALID_FILETYPE: "One or more files were not added to the queue because they were of the wrong type."
},
buttons: {
remove: "Remove"
}
},
events: {
onFileRemoved: null
},
listeners: {
"onCreate.prepareTemplateElement": "fluid.uploader.fileQueueView.prepareTemplateElements",
"onCreate.addKeyboardNavigation": "fluid.uploader.fileQueueView.addKeyboardNavigation",
"onCreate.addAriaRole": {
"this": "{that}.container",
method: "attr",
args: {
role: "application"
}
}
}
});
/**
* An interactional mixin for binding a fileQueueView to an Uploader
*/
fluid.defaults("fluid.uploader.fileQueueView.bindUploader", {
events: {
onFileRemoved: "{uploader}.events.onFileRemoved"
},
listeners: {
"{uploader}.events.afterFileQueued": "{fileQueueView}.addFile",
"{uploader}.events.onUploadStart": "{fileQueueView}.prepareForUpload",
"{uploader}.events.onFileStart": "{fileQueueView}.showFileProgress",
"{uploader}.events.onFileProgress": "{fileQueueView}.updateFileProgress",
"{uploader}.events.onFileSuccess": "{fileQueueView}.markFileComplete",
"{uploader}.events.onFileError": "{fileQueueView}.showErrorForFile",
"{uploader}.events.afterFileComplete": "{fileQueueView}.hideFileProgress",
"{uploader}.events.afterUploadComplete": "{fileQueueView}.refreshAfterUpload"
}
});
/**************
* Scrollable *
**************/
fluid.registerNamespace("fluid.scrollable");
fluid.scrollable.makeSimple = function (element) {
return fluid.container(element);
};
fluid.scrollable.makeTable = function (table, wrapperMarkup) {
table.wrap(wrapperMarkup);
return table.closest(".fl-scrollable-scroller");
};
/**
* Simple component cover for the jQuery scrollTo plugin. Provides roughly equivalent
* functionality to Uploader's old Scroller plugin.
*
* @param element {jQueryable} the element to make scrollable
* @param options {Object} for the component
* @return the scrollable component
*/
fluid.defaults("fluid.scrollable", {
gradeNames: ["fluid.viewComponent"],
makeScrollableFn: fluid.scrollable.makeSimple, // NB - a modern style would configure an invoker
members: {
scrollable: {
expander: {
func: "{that}.options.makeScrollableFn",
args: ["{that}.container", "{that}.options.wrapperMarkup"] // TODO: we need to make sure that expander arguments are evaluated fully
}
},
maxHeight: {
expander: {
"this": "{that}.scrollable",
method: "css",
args: "max-height"
}
}
},
invokers: {
/**
* Programmatically scrolls this scrollable element to the region specified.
* This method is directly compatible with the underlying jQuery.scrollTo plugin.
*/
scrollTo: {
"this": "{that}.scrollable",
method: "scrollTo",
args: "{arguments}.0"
},
refreshView: {
funcName: "fluid.scrollable.refreshView",
args: "{that}"
}
},
listeners: {
onCreate: "{that}.refreshView"
}
});
/*
* Updates the view of the scrollable region. This should be called when the content of the scrollable region is changed.
*/
fluid.scrollable.refreshView = function (that) {
if ($.browser.msie && $.browser.version === "6.0") {
that.scrollable.css("height", "");
// Set height, if max-height is reached, to allow scrolling in IE6.
if (that.scrollable.height() >= parseInt(that.maxHeight, 10)) {
that.scrollable.css("height", that.maxHeight);
}
}
};
/**
* Wraps a table in order to make it scrollable with the jQuery.scrollTo plugin.
* Container divs are injected to allow cross-browser support.
*
* @param table {jQueryable} the table to make scrollable
* @param options {Object} configuration options
* @return the scrollable component
*/
fluid.defaults("fluid.scrollableTable", {
gradeNames: ["fluid.scrollable"],
makeScrollableFn: fluid.scrollable.makeTable,
wrapperMarkup: "<div class='fl-scrollable-scroller'><div class='fl-scrollable-inner'></div></div>"
});
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
fluid.defaults("fluid.uploader.errorPanel", {
gradeNames: ["fluid.viewComponent", "fluid.contextAware"],
invokers: {
refreshView: "fluid.uploader.errorPanel.refreshView({that})"
},
events: {
afterRender: null
},
components: {
// TODO: This won't scale nicely with more types of errors.
fileSizeErrorSection: {
type: "fluid.uploader.errorPanel.section",
createOnEvent: "afterRender",
container: "{errorPanel}.dom.fileSizeErrorSection",
options: {
model: {
errorCode: fluid.uploader.queueErrorConstants.FILE_EXCEEDS_SIZE_LIMIT
},
strings: {
header: "{errorPanel}.options.strings.exceedsFileSize"
}
}
},
numFilesErrorSection: {
type: "fluid.uploader.errorPanel.section",
createOnEvent: "afterRender",
container: "{errorPanel}.dom.numFilesErrorSection",
options: {
model: {
errorCode: fluid.uploader.queueErrorConstants.QUEUE_LIMIT_EXCEEDED
},
strings: {
header: "{errorPanel}.options.strings.exceedsNumFilesLimit"
}
}
}
},
selectors: {
header: ".flc-uploader-errorPanel-header",
sectionTemplate: ".flc-uploader-errorPanel-section-tmplt",
fileSizeErrorSection: ".flc-uploader-errorPanel-section-fileSize",
numFilesErrorSection: ".flc-uploader-errorPanel-section-numFiles"
},
strings: {
headerText: "Warning(s)",
exceedsNumFilesLimit: "Too many files were selected. %numFiles were not added to the queue.",
exceedsFileSize: "%numFiles files were too large and were not added to the queue."
},
listeners: {
"onCreate.renderSectionTemplates": {
funcName: "fluid.uploader.errorPanel.renderSectionTemplates",
args: "{that}",
priority: "before:domComplete"
},
"onCreate.domComplete": {
funcName: "fluid.uploader.errorPanel.domComplete",
args: "{that}"
}
},
styles: {
hiddenTemplate: "fl-hidden-templates"
}
});
fluid.uploader.errorPanel.refreshView = function (that) {
for (var i = 0; i < that.sections.length; i++) {
if (that.sections[i].model.files.length > 0) {
// One of the sections has errors. Show them and bail immediately.
that.container.show();
return;
}
}
that.container.hide();
};
fluid.uploader.errorPanel.renderSectionTemplates = function (that) {
var sectionTmpl = that.locate("sectionTemplate").remove().removeClass(that.options.styles.hiddenTemplate);
that.locate("fileSizeErrorSection").append(sectionTmpl.clone());
that.locate("numFilesErrorSection").append(sectionTmpl.clone());
that.events.afterRender.fire(that);
};
fluid.uploader.errorPanel.domComplete = function (that) {
that.sections = [that.fileSizeErrorSection, that.numFilesErrorSection];
that.locate("header").text(that.options.strings.headerText);
that.container.hide();
};
// An "interactional mixin" - a courtesy to dream of a possibility that an "errorPanel" could conceivably be deployed separately
// from an "uploader"
fluid.defaults("fluid.uploader.errorPanel.bindUploader", {
listeners: {
"{uploader}.events.afterFileDialog": "{errorPanel}.refreshView"
},
distributeOptions: {
target: "{that fluid.uploader.errorPanel.section}.options.listeners",
record: {
"{uploader}.events.onQueueError": "{section}.addFile",
"{uploader}.events.onFilesSelected": "{section}.clear",
"{uploader}.events.onUploadStart": "{section}.clear",
"{section}.events.afterErrorsCleared": "{errorPanel}.refreshView"
}
}
});
fluid.defaults("fluid.uploader.errorPanel.section", {
gradeNames: ["fluid.viewComponent"],
model: {
errorCode: undefined,
files: [],
showingDetails: false
},
events: {
afterErrorsCleared: null
},
selectors: {
errorTitle: ".fl-uploader-errorPanel-section-title",
deleteErrorButton: ".flc-uploader-errorPanel-section-removeButton",
errorDetails: ".flc-uploader-errorPanel-section-details",
erroredFiles: ".flc-uploader-errorPanel-section-files",
showHideFilesToggle: ".flc-uploader-errorPanel-section-toggleDetails"
},
strings: {
hideFiles: "Hide files",
showFiles: "Show files",
fileListDelimiter: ", "
},
invokers: {
toggleDetails: "fluid.uploader.errorPanel.section.toggleDetails({that})",
showDetails: "fluid.uploader.errorPanel.section.showDetails({that})",
hideDetails: "fluid.uploader.errorPanel.section.hideDetails({that})",
addFile: "fluid.uploader.errorPanel.section.addFile({that}, {arguments}.0, {arguments}.1)", // file, errorCode
clear: "fluid.uploader.errorPanel.section.clear({that})",
refreshView: "fluid.uploader.errorPanel.section.refreshView({that})"
},
listeners: {
"onCreate.bindHandlers": {
funcName: "fluid.uploader.errorPanel.section.bindHandlers",
priority: "after:refreshView"
},
"onCreate.refreshView": "{that}.refreshView"
}
});
fluid.uploader.errorPanel.section.toggleDetails = function (that) {
var detailsAction = that.model.showingDetails ? that.hideDetails : that.showDetails;
detailsAction();
};
fluid.uploader.errorPanel.section.showDetails = function (that) {
that.locate("errorDetails").show();
that.locate("showHideFilesToggle").text(that.options.strings.hideFiles);
that.model.showingDetails = true; // TODO: model abuse
};
fluid.uploader.errorPanel.section.hideDetails = function (that) {
that.locate("errorDetails").hide();
that.locate("showHideFilesToggle").text(that.options.strings.showFiles);
that.model.showingDetails = false;
};
fluid.uploader.errorPanel.section.addFile = function (that, file, errorCode) {
if (errorCode === that.model.errorCode) {
that.model.files.push(file.name);
that.refreshView();
}
};
fluid.uploader.errorPanel.section.clear = function (that) {
that.model.files = [];
that.refreshView();
that.events.afterErrorsCleared.fire();
};
fluid.uploader.errorPanel.section.refreshView = function (that) {
fluid.uploader.errorPanel.section.renderHeader(that);
fluid.uploader.errorPanel.section.renderErrorDetails(that);
that.hideDetails();
if (that.model.files.length <= 0) { // TODO: use model relay and "visibility model"
that.container.hide();
} else {
that.container.show();
}
};
fluid.uploader.errorPanel.section.bindHandlers = function (that) {
// Bind delete button
that.locate("deleteErrorButton").click(that.clear);
// Bind hide/show error details link
that.locate("showHideFilesToggle").click(that.toggleDetails);
};
fluid.uploader.errorPanel.section.renderHeader = function (that) {
var errorTitle = fluid.stringTemplate(that.options.strings.header, {
numFiles: that.model.files.length
});
that.locate("errorTitle").text(errorTitle);
};
fluid.uploader.errorPanel.section.renderErrorDetails = function (that) {
var files = that.model.files;
var filesList = files.length > 0 ? files.join(that.options.strings.fileListDelimiter) : "";
that.locate("erroredFiles").text(filesList);
};
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
fluid.defaults("fluid.uploader.html5", {
gradeNames: "fluid.uploader.multiFileUploader",
components: {
strategy: {
type: "fluid.uploader.html5Strategy"
}
}
});
fluid.defaults("fluid.uploader.html5Strategy", {
gradeNames: ["fluid.uploader.strategy"],
components: {
local: { // TODO: Would be nice to have some way to express that this is a "natural covariant refinement"
type: "fluid.uploader.html5Strategy.local"
},
remote: {
type: "fluid.uploader.html5Strategy.remote"
}
}
});
// FLUID-6056 ( https://issues.fluidproject.org/browse/FLUID-6056 )
// Using `navigator.msLaunchUri` to browser detect IE10+ and MS Edge, because
// it is exclusive to Microsoft browsers for IE 10 and later.
fluid.registerNamespace("fluid.uploader.html5.browser");
fluid.uploader.html5.browser.isMS = !!navigator.msLaunchUri;
// TODO: The following two or three functions probably ultimately belong on a that responsible for
// coordinating with the XHR. A fileConnection object or something similar.
fluid.uploader.html5Strategy.fileSuccessHandler = function (file, events, xhr) {
events.onFileSuccess.fire(file, xhr.responseText, xhr);
events.onFileComplete.fire(file);
};
fluid.uploader.html5Strategy.fileErrorHandler = function (file, events, xhr) {
events.onFileError.fire(file,
fluid.uploader.errorConstants.UPLOAD_FAILED,
xhr.status,
xhr);
events.onFileComplete.fire(file);
};
fluid.uploader.html5Strategy.fileStopHandler = function (file, events, xhr) {
events.onFileError.fire(file,
fluid.uploader.errorConstants.UPLOAD_STOPPED,
xhr.status,
xhr);
events.onFileComplete.fire(file);
};
fluid.uploader.html5Strategy.monitorFileUploadXHR = function (file, events, xhr) {
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
var status = xhr.status;
if (status >= 200 && status <= 204) {
fluid.uploader.html5Strategy.fileSuccessHandler(file, events, xhr);
} else if (status === 0) {
fluid.uploader.html5Strategy.fileStopHandler(file, events, xhr);
} else {
fluid.uploader.html5Strategy.fileErrorHandler(file, events, xhr);
}
}
};
xhr.upload.onprogress = function (pe) {
events.onFileProgress.fire(file, pe.loaded, pe.total);
};
};
fluid.uploader.html5Strategy.uploadNextFile = function (queue, uploadFile) {
var batch = queue.currentBatch;
var file = batch.files[batch.fileIdx];
uploadFile(file);
};
fluid.uploader.html5Strategy.uploadFile = function (that, file) {
that.events.onFileStart.fire(file);
that.currentXHR = that.createXHR();
fluid.uploader.html5Strategy.monitorFileUploadXHR(file, that.events, that.currentXHR);
that.fileSender.send(file, that.queueSettings, that.currentXHR);
};
fluid.uploader.html5Strategy.stop = function (that) {
that.queue.isUploading = false;
that.currentXHR.abort();
that.events.onUploadStop.fire();
};
fluid.defaults("fluid.uploader.html5Strategy.remote", {
gradeNames: ["fluid.uploader.remote"],
components: {
fileSender: {
type: "fluid.uploader.html5Strategy.fileSender"
}
},
invokers: {
createXHR: "fluid.uploader.html5Strategy.createXHR",
// Upload files in the current batch without exceeding the fileUploadLimit
uploadNextFile: {
funcName: "fluid.uploader.html5Strategy.uploadNextFile",
args: ["{that}.queue", "{that}.uploadFile"]
},
uploadFile: {
funcName: "fluid.uploader.html5Strategy.uploadFile",
args: ["{that}", "{arguments}.0"]
},
stop: {
funcName: "fluid.uploader.html5Strategy.stop",
args: ["{that}"]
}
}
});
fluid.uploader.html5Strategy.createXHR = function () {
return new XMLHttpRequest();
};
fluid.uploader.html5Strategy.createFormData = function () {
return new FormData();
};
// Set additional POST parameters for xhr
fluid.uploader.html5Strategy.setPostParams = function (formData, postParams) {
$.each(postParams, function (key, value) {
formData.append(key, value);
});
};
fluid.defaults("fluid.uploader.html5Strategy.fileSender", {
gradeNames: ["fluid.component", "fluid.contextAware"],
invokers: {
send: {
funcName: "fluid.fail",
args: "Error instantiating HTML5 Uploader - browser does not support FormData feature. Please try version 1.4 or earlier of Uploader which has Firefox 3.x support"
}
},
contextAwareness: {
technology: {
checks: {
formData: {
contextValue: "{fluid.browser.supportsFormData}",
gradeNames: "fluid.uploader.html5Strategy.formDataSender"
}
}
}
}
});
/*******************************************************
* HTML5 FormData Sender, used by most modern browsers *
*******************************************************/
fluid.defaults("fluid.uploader.html5Strategy.formDataSender", {
gradeNames: ["fluid.component"],
invokers: {
createFormData: "fluid.uploader.html5Strategy.createFormData",
send: {
funcName: "fluid.uploader.html5Strategy.sendFormData",
args: ["{that}.createFormData", "{arguments}.0", "{arguments}.1", "{arguments}.2"]
}
}
});
/*
* Uploads the file using the HTML5 FormData object.
*/
fluid.uploader.html5Strategy.sendFormData = function (formCreator, file, queueSettings, xhr) {
var formData = formCreator();
formData.append("file", file);
fluid.uploader.html5Strategy.setPostParams(formData, queueSettings.postParams);
xhr.open("POST", queueSettings.uploadURL, true);
xhr.send(formData);
return formData;
};
/************************************
* HTML5 Strategy's Local Behaviour *
************************************/
fluid.defaults("fluid.uploader.html5Strategy.local", {
gradeNames: ["fluid.uploader.local"],
invokers: {
addFiles: {
funcName: "fluid.uploader.html5Strategy.local.addFiles",
args: ["{that}", "{arguments}.0"] // files
},
removeFile: "fluid.identity", // it appears this was never implemented
enableBrowseButton: "{that}.browseButtonView.enable",
disableBrowseButton: "{that}.browseButtonView.disable"
},
components: {
browseButtonView: {
type: "fluid.uploader.html5Strategy.browseButtonView",
container: "{uploader}.container",
options: {
strings: "{uploader}.options.strings.buttons",
queueSettings: "{uploader}.options.queueSettings",
selectors: {
browseButton: "{uploader}.options.selectors.browseButton"
},
events: {
onBrowse: "{local}.events.onFileDialog"
},
listeners: {
onFilesQueued: "{local}.addFiles"
}
}
}
}
});
fluid.uploader.html5Strategy.local.addFiles = function (that, files) {
// Add files to the file queue without exceeding the fileUploadLimit and the fileSizeLimit
// NOTE: fileSizeLimit set to bytes for HTML5 Uploader.
// TODO: These look like they should be part of a real model.
var queueSettings = that.options.queueSettings;
var sizeLimit = queueSettings.fileSizeLimit * 1024;
var fileLimit = queueSettings.fileUploadLimit;
var uploaded = that.queue.getUploadedFiles().length;
var queued = that.queue.getReadyFiles().length;
var remainingUploadLimit = fileLimit - uploaded - queued;
that.events.onFilesSelected.fire(files.length);
// Provide feedback to the user if the file size is too large and isn't added to the file queue
var numFilesAdded = 0;
for (var i = 0; i < files.length; i++) {
var file = files[i];
if (fileLimit && remainingUploadLimit === 0) {
that.events.onQueueError.fire(file, fluid.uploader.queueErrorConstants.QUEUE_LIMIT_EXCEEDED);
} else if (file.size > sizeLimit) {
file.filestatus = fluid.uploader.fileStatusConstants.ERROR;
that.events.onQueueError.fire(file, fluid.uploader.queueErrorConstants.FILE_EXCEEDS_SIZE_LIMIT);
} else if (!fileLimit || remainingUploadLimit > 0) {
file.id = "file-" + fluid.allocateGuid();
file.filestatus = fluid.uploader.fileStatusConstants.QUEUED;
that.events.afterFileQueued.fire(file);
remainingUploadLimit--;
numFilesAdded++;
}
}
that.events.afterFileDialog.fire(numFilesAdded);
};
/********************
* browseButtonView *
********************/
fluid.uploader.bindEventsToFileInput = function (that, fileInput) {
fileInput.click(function () {
that.events.onBrowse.fire();
});
// FLUID-6056 ( https://issues.fluidproject.org/browse/FLUID-6056 )
// In IE 11 and MS Edge, < input type="file" > creates an element with
// two keyboard focusable parts (textfield and button). When the textfield
// is focused ( this happens first when tabbing through elements ), pressing
// the "Enter" key triggers a form submission. The workaround implemented
// here is to translate the input from the "Enter" key into a click event
// on the fileInput so that it will open the OS's file dialog.
// This hack is only needed for IE 11 and MS Edge. If the it is executed on
// Firefox because Firefox treats the file dialog as a popup, which is
// caught by the popup blocker.
if (fluid.uploader.html5.browser.isMS) {
fileInput.on("keydown", function (event) {
if (event.keyCode === $.ui.keyCode.ENTER) {
event.preventDefault();
fileInput.trigger("click");
}
});
}
fileInput.change(function () {
var files = fileInput[0].files;
that.renderFreshMultiFileInput();
that.events.onFilesQueued.fire(files);
});
fileInput.focus(function () {
that.browseButton.addClass("focus");
that.events.onFocusFileInput.fire(that, fileInput, true);
});
fileInput.blur(function () {
that.browseButton.removeClass("focus");
that.events.onFocusFileInput.fire(that, fileInput, false);
});
};
fluid.uploader.renderMultiFileInput = function (that) {
var multiFileInput = $(that.options.multiFileInputMarkup);
var fileTypes = that.options.queueSettings.fileTypes;
if (fluid.isArrayable(fileTypes)) {
fileTypes = fileTypes.join();
multiFileInput.attr("accept", fileTypes);
}
return multiFileInput;
};
fluid.uploader.renderFreshMultiFileInput = function (that) {
var previousInput = that.locate("fileInputs").last();
previousInput.hide();
previousInput.prop("tabindex", -1);
var newInput = fluid.uploader.renderMultiFileInput(that);
newInput.attr("aria-label", that.options.strings.addMore);
previousInput.after(newInput);
fluid.uploader.bindEventsToFileInput(that, newInput);
};
fluid.uploader.setupBrowseButtonView = function (that) {
var multiFileInput = fluid.uploader.renderMultiFileInput(that);
multiFileInput.attr("aria-label", that.options.strings.browse);
that.browseButton.append(multiFileInput);
fluid.uploader.bindEventsToFileInput(that, multiFileInput);
that.browseButton.prop("tabindex", -1);
};
fluid.uploader.isEnabled = function (element) {
return !element.prop("disabled");
};
fluid.defaults("fluid.uploader.html5Strategy.browseButtonView", {
gradeNames: ["fluid.viewComponent"],
strings: {
browse: "Browse files",
addMore: "Add more"
},
multiFileInputMarkup: "<input type='file' multiple='' class='flc-uploader-html5-input' />",
queueSettings: {},
members: {
browseButton: "{that}.dom.browseButton"
},
invokers: {
enable: { // TODO: FLUID-4928
"this": "{that}.dom.fileInputs",
method: "prop",
args: ["disabled", false]
},
disable: {
"this": "{that}.dom.fileInputs",
method: "prop",
args: ["disabled", true]
},
isEnabled: {
funcName: "fluid.uploader.isEnabled",
args: "{that}.dom.fileInputs"
},
renderFreshMultiFileInput: {
funcName: "fluid.uploader.renderFreshMultiFileInput",
args: "{that}"
}
},
selectors: {
browseButton: ".flc-uploader-button-browse",
fileInputs: ".flc-uploader-html5-input"
},
events: {
onFocusFileInput: null,
onBrowse: null,
onFilesQueued: null
},
listeners: {
onCreate: {
funcName: "fluid.uploader.setupBrowseButtonView",
args: "{that}"
}
}
});
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function ($, fluid) {
"use strict";
fluid.registerNamespace("fluid.uploader.demo");
fluid.defaults("fluid.uploader.demo", {
distributeOptions: {
record: "fluid.uploader.demo.remote",
target: "{that strategy remote}.type"
}
});
fluid.uploader.demo.uploadNextFile = function (that) {
// Reset our upload stats for each new file.
that.demoState.currentFile = that.queue.files[that.demoState.fileIdx];
that.demoState.chunksForCurrentFile = Math.ceil(that.demoState.currentFile / that.demoState.chunkSize);
that.demoState.bytesUploaded = 0;
that.queue.isUploading = true;
that.events.onFileStart.fire(that.demoState.currentFile);
fluid.uploader.demo.simulateUpload(that);
};
fluid.uploader.demo.updateProgress = function (file, events, demoState, isUploading) {
if (!isUploading) {
return;
}
var chunk = Math.min(demoState.chunkSize, file.size);
demoState.bytesUploaded = Math.min(demoState.bytesUploaded + chunk, file.size);
events.onFileProgress.fire(file, demoState.bytesUploaded, file.size);
};
fluid.uploader.demo.finishAndContinueOrCleanup = function (that, file) {
// TODO: it appears that this duplicates handlers in Uploader.js onFileComplete -
// which this component does not fire
that.queue.finishFile(file);
that.events.afterFileComplete.fire(file);
if (that.queue.shouldUploadNextFile()) {
fluid.uploader.demo.uploadNextFile(that);
} else {
that.events.afterUploadComplete.fire(that.queue.currentBatch.files);
if (file.status !== fluid.uploader.fileStatusConstants.CANCELLED) {
that.queue.clearCurrentBatch(); // Only clear the current batch if we're actually done the batch.
}
}
};
fluid.uploader.demo.finishUploading = function (that) {
if (!that.queue.isUploading) {
return;
}
var file = that.demoState.currentFile;
that.events.onFileSuccess.fire(file);
that.demoState.fileIdx++;
fluid.uploader.demo.finishAndContinueOrCleanup(that, file);
};
fluid.uploader.demo.simulateUpload = function (that) {
if (!that.queue.isUploading) {
return;
}
var file = that.demoState.currentFile;
if (that.demoState.bytesUploaded < file.size) {
fluid.invokeAfterRandomDelay(function () {
fluid.uploader.demo.updateProgress(file, that.events, that.demoState, that.queue.isUploading);
fluid.uploader.demo.simulateUpload(that);
});
} else {
fluid.uploader.demo.finishUploading(that);
}
};
fluid.uploader.demo.stop = function (that) {
var file = that.demoState.currentFile;
file.filestatus = fluid.uploader.fileStatusConstants.CANCELLED;
that.queue.shouldStop = true;
// Legacy from the SWFUpload implementation, where pausing is a combination of an UPLOAD_STOPPED error and a complete.
that.events.onFileError.fire(file,
fluid.uploader.errorConstants.UPLOAD_STOPPED,
"The demo upload was paused by the user.");
fluid.uploader.demo.finishAndContinueOrCleanup(that, file);
that.events.onUploadStop.fire();
};
/**
* Invokes a function after a random delay by using setTimeout.
* @param {Function} fn - the function to invoke
*/
fluid.invokeAfterRandomDelay = function (fn) {
var delay = Math.floor(Math.random() * 200 + 100);
setTimeout(fn, delay);
};
/**
* The demo remote pretends to upload files to the server, firing all the appropriate events
* but without sending anything over the network or requiring a server to be running.
*
* @param {Object} configuration options
*/
fluid.defaults("fluid.uploader.demo.remote", {
gradeNames: ["fluid.uploader.remote"],
members: {
demoState: {
fileIdx: 0,
chunkSize: 200000
}
},
invokers: {
uploadNextFile: {
funcName: "fluid.uploader.demo.uploadNextFile",
args: "{that}"
},
stop: {
funcName: "fluid.uploader.demo.stop",
args: "{that}"
}
}
});
})(jQuery, fluid_3_0_0);
;
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/master/AUTHORS.md.
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
*/
var fluid_3_0_0 = fluid_3_0_0 || {};
(function (fluid) {
"use strict";
fluid.registerNamespace("fluid.uploader");
fluid.uploader.mimeTypeRegistry = {
// Images
jpg: "image/jpeg",
jpeg: "image/jpeg",
bmp: "image/bmp",
png: "image/png",
tif: "image/tiff",
tiff: "image/tiff",
// Audio
mp3: "audio/mpeg",
m4a: "audio/mp4a-latm",
ogg: "audio/ogg",
wav: "audio/x-wav",
aiff: "audio/x-aiff",
// Video
mpg: "video/mpeg",
mpeg: "video/mpeg",
m4v: "video/x-m4v",
ogv: "video/ogg",
mov: "video/quicktime",
avi: "video/x-msvideo",
// Text documents
html: "text/html",
htm: "text/html",
text: "text/plain",
// Office Docs.
doc: "application/msword",
docx: "application/msword",
xls: "application/vnd.ms-excel",
xlsx: "application/vnd.ms-excel",
ppt: "application/vnd.ms-powerpoint",
pptx: "application/vnd.ms-powerpoint"
};
})(fluid_3_0_0);
//# sourceMappingURL=infusion-all.js.map