Files larger than 1 MB are truncated. Click
here to display the full file (may cause the browser to become unresponsive) or use the
Open button to view outside of Swarm.
window.EmberENV = {"FEATURES":{},"EXTEND_PROTOTYPES":{"Date":false}};
var runningTests = false;
;var loader, define, requireModule, require, requirejs;
(function (global) {
'use strict';
function dict() {
var obj = Object.create(null);
obj['__'] = undefined;
delete obj['__'];
return obj;
}
// Save off the original values of these globals, so we can restore them if someone asks us to
var oldGlobals = {
loader: loader,
define: define,
requireModule: requireModule,
require: require,
requirejs: requirejs
};
requirejs = require = requireModule = function (id) {
var pending = [];
var mod = findModule(id, '(require)', pending);
for (var i = pending.length - 1; i >= 0; i--) {
pending[i].exports();
}
return mod.module.exports;
};
loader = {
noConflict: function (aliases) {
var oldName, newName;
for (oldName in aliases) {
if (aliases.hasOwnProperty(oldName)) {
if (oldGlobals.hasOwnProperty(oldName)) {
newName = aliases[oldName];
global[newName] = global[oldName];
global[oldName] = oldGlobals[oldName];
}
}
}
},
// Option to enable or disable the generation of default exports
makeDefaultExport: true
};
var registry = dict();
var seen = dict();
var uuid = 0;
function unsupportedModule(length) {
throw new Error('an unsupported module was defined, expected `define(id, deps, module)` instead got: `' + length + '` arguments to define`');
}
var defaultDeps = ['require', 'exports', 'module'];
function Module(id, deps, callback, alias) {
this.uuid = uuid++;
this.id = id;
this.deps = !deps.length && callback.length ? defaultDeps : deps;
this.module = { exports: {} };
this.callback = callback;
this.hasExportsAsDep = false;
this.isAlias = alias;
this.reified = new Array(deps.length);
/*
Each module normally passes through these states, in order:
new : initial state
pending : this module is scheduled to be executed
reifying : this module's dependencies are being executed
reified : this module's dependencies finished executing successfully
errored : this module's dependencies failed to execute
finalized : this module executed successfully
*/
this.state = 'new';
}
Module.prototype.makeDefaultExport = function () {
var exports = this.module.exports;
if (exports !== null && (typeof exports === 'object' || typeof exports === 'function') && exports['default'] === undefined && Object.isExtensible(exports)) {
exports['default'] = exports;
}
};
Module.prototype.exports = function () {
// if finalized, there is no work to do. If reifying, there is a
// circular dependency so we must return our (partial) exports.
if (this.state === 'finalized' || this.state === 'reifying') {
return this.module.exports;
}
if (loader.wrapModules) {
this.callback = loader.wrapModules(this.id, this.callback);
}
this.reify();
var result = this.callback.apply(this, this.reified);
this.reified.length = 0;
this.state = 'finalized';
if (!(this.hasExportsAsDep && result === undefined)) {
this.module.exports = result;
}
if (loader.makeDefaultExport) {
this.makeDefaultExport();
}
return this.module.exports;
};
Module.prototype.unsee = function () {
this.state = 'new';
this.module = { exports: {} };
};
Module.prototype.reify = function () {
if (this.state === 'reified') {
return;
}
this.state = 'reifying';
try {
this.reified = this._reify();
this.state = 'reified';
} finally {
if (this.state === 'reifying') {
this.state = 'errored';
}
}
};
Module.prototype._reify = function () {
var reified = this.reified.slice();
for (var i = 0; i < reified.length; i++) {
var mod = reified[i];
reified[i] = mod.exports ? mod.exports : mod.module.exports();
}
return reified;
};
Module.prototype.findDeps = function (pending) {
if (this.state !== 'new') {
return;
}
this.state = 'pending';
var deps = this.deps;
for (var i = 0; i < deps.length; i++) {
var dep = deps[i];
var entry = this.reified[i] = { exports: undefined, module: undefined };
if (dep === 'exports') {
this.hasExportsAsDep = true;
entry.exports = this.module.exports;
} else if (dep === 'require') {
entry.exports = this.makeRequire();
} else if (dep === 'module') {
entry.exports = this.module;
} else {
entry.module = findModule(resolve(dep, this.id), this.id, pending);
}
}
};
Module.prototype.makeRequire = function () {
var id = this.id;
var r = function (dep) {
return require(resolve(dep, id));
};
r['default'] = r;
r.moduleId = id;
r.has = function (dep) {
return has(resolve(dep, id));
};
return r;
};
define = function (id, deps, callback) {
var module = registry[id];
// If a module for this id has already been defined and is in any state
// other than `new` (meaning it has been or is currently being required),
// then we return early to avoid redefinition.
if (module && module.state !== 'new') {
return;
}
if (arguments.length < 2) {
unsupportedModule(arguments.length);
}
if (!Array.isArray(deps)) {
callback = deps;
deps = [];
}
if (callback instanceof Alias) {
registry[id] = new Module(callback.id, deps, callback, true);
} else {
registry[id] = new Module(id, deps, callback, false);
}
};
define.exports = function (name, defaultExport) {
var module = registry[name];
// If a module for this name has already been defined and is in any state
// other than `new` (meaning it has been or is currently being required),
// then we return early to avoid redefinition.
if (module && module.state !== 'new') {
return;
}
module = new Module(name, [], noop, null);
module.module.exports = defaultExport;
module.state = 'finalized';
registry[name] = module;
return module;
};
function noop() {}
// we don't support all of AMD
// define.amd = {};
function Alias(id) {
this.id = id;
}
define.alias = function (id, target) {
if (arguments.length === 2) {
return define(target, new Alias(id));
}
return new Alias(id);
};
function missingModule(id, referrer) {
throw new Error('Could not find module `' + id + '` imported from `' + referrer + '`');
}
function findModule(id, referrer, pending) {
var mod = registry[id] || registry[id + '/index'];
while (mod && mod.isAlias) {
mod = registry[mod.id];
}
if (!mod) {
missingModule(id, referrer);
}
if (pending && mod.state !== 'pending' && mod.state !== 'finalized') {
mod.findDeps(pending);
pending.push(mod);
}
return mod;
}
function resolve(child, id) {
if (child.charAt(0) !== '.') {
return child;
}
var parts = child.split('/');
var nameParts = id.split('/');
var parentBase = nameParts.slice(0, -1);
for (var i = 0, l = parts.length; i < l; i++) {
var part = parts[i];
if (part === '..') {
if (parentBase.length === 0) {
throw new Error('Cannot access parent module of root');
}
parentBase.pop();
} else if (part === '.') {
continue;
} else {
parentBase.push(part);
}
}
return parentBase.join('/');
}
function has(id) {
return !!(registry[id] || registry[id + '/index']);
}
requirejs.entries = requirejs._eak_seen = registry;
requirejs.has = has;
requirejs.unsee = function (id) {
findModule(id, '(unsee)', false).unsee();
};
requirejs.clear = function () {
requirejs.entries = requirejs._eak_seen = registry = dict();
seen = dict();
};
// This code primes the JS engine for good performance by warming the
// JIT compiler for these functions.
define('foo', function () {});
define('foo/bar', [], function () {});
define('foo/asdf', ['module', 'exports', 'require'], function (module, exports, require) {
if (require.has('foo/bar')) {
require('foo/bar');
}
});
define('foo/baz', [], define.alias('foo'));
define('foo/quz', define.alias('foo'));
define.alias('foo', 'foo/qux');
define('foo/bar', ['foo', './quz', './baz', './asdf', './bar', '../foo'], function () {});
define('foo/main', ['foo/bar'], function () {});
define.exports('foo/exports', {});
require('foo/exports');
require('foo/main');
require.unsee('foo/bar');
requirejs.clear();
if (typeof exports === 'object' && typeof module === 'object' && module.exports) {
module.exports = { require: require, define: define };
}
})(this);
;/*!
* 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() {
/*!
* @overview Ember - JavaScript Application Framework
* @copyright Copyright 2011-2017 Tilde Inc. and contributors
* Portions Copyright 2006-2011 Strobe Inc.
* Portions Copyright 2008-2011 Apple Inc. All rights reserved.
* @license Licensed under MIT license
* See https://raw.github.com/emberjs/ember.js/master/LICENSE
* @version 2.18.0
*/
/*global process */
var enifed, requireModule, Ember;
var mainContext = this; // Used in ember-environment/lib/global.js
(function() {
function missingModule(name, referrerName) {
if (referrerName) {
throw new Error('Could not find module ' + name + ' required by: ' + referrerName);
} else {
throw new Error('Could not find module ' + name);
}
}
function internalRequire(_name, referrerName) {
var name = _name;
var mod = registry[name];
if (!mod) {
name = name + '/index';
mod = registry[name];
}
var exports = seen[name];
if (exports !== undefined) {
return exports;
}
exports = seen[name] = {};
if (!mod) {
missingModule(_name, referrerName);
}
var deps = mod.deps;
var callback = mod.callback;
var reified = new Array(deps.length);
for (var i = 0; i < deps.length; i++) {
if (deps[i] === 'exports') {
reified[i] = exports;
} else if (deps[i] === 'require') {
reified[i] = requireModule;
} else {
reified[i] = internalRequire(deps[i], name);
}
}
callback.apply(this, reified);
return exports;
}
var isNode = typeof window === 'undefined' &&
typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';
if (!isNode) {
Ember = this.Ember = this.Ember || {};
}
if (typeof Ember === 'undefined') { Ember = {}; }
if (typeof Ember.__loader === 'undefined') {
var registry = {};
var seen = {};
enifed = function(name, deps, callback) {
var value = { };
if (!callback) {
value.deps = [];
value.callback = deps;
} else {
value.deps = deps;
value.callback = callback;
}
registry[name] = value;
};
requireModule = function(name) {
return internalRequire(name, null);
};
// setup `require` module
requireModule['default'] = requireModule;
requireModule.has = function registryHas(moduleName) {
return !!registry[moduleName] || !!registry[moduleName + '/index'];
};
requireModule._eak_seen = registry;
Ember.__loader = {
define: enifed,
require: requireModule,
registry: registry
};
} else {
enifed = Ember.__loader.define;
requireModule = Ember.__loader.require;
}
})();
enifed("@glimmer/node", ["exports", "@glimmer/runtime"], function (exports, _runtime) {
"use strict";
exports.NodeDOMTreeConstruction = undefined;
function _defaults(obj, defaults) {
var keys = Object.getOwnPropertyNames(defaults);for (var i = 0; i < keys.length; i++) {
var key = keys[i];var value = Object.getOwnPropertyDescriptor(defaults, key);if (value && value.configurable && obj[key] === undefined) {
Object.defineProperty(obj, key, value);
}
}return obj;
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && (typeof call === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass);
}
var NodeDOMTreeConstruction = function (_DOMTreeConstruction) {
_inherits(NodeDOMTreeConstruction, _DOMTreeConstruction);
function NodeDOMTreeConstruction(doc) {
_classCallCheck(this, NodeDOMTreeConstruction);
return _possibleConstructorReturn(this, _DOMTreeConstruction.call(this, doc));
}
// override to prevent usage of `this.document` until after the constructor
NodeDOMTreeConstruction.prototype.setupUselessElement = function setupUselessElement() {};
NodeDOMTreeConstruction.prototype.insertHTMLBefore = function insertHTMLBefore(parent, reference, html) {
var prev = reference ? reference.previousSibling : parent.lastChild;
var raw = this.document.createRawHTMLSection(html);
parent.insertBefore(raw, reference);
var first = prev ? prev.nextSibling : parent.firstChild;
var last = reference ? reference.previousSibling : parent.lastChild;
return new _runtime.ConcreteBounds(parent, first, last);
};
// override to avoid SVG detection/work when in node (this is not needed in SSR)
NodeDOMTreeConstruction.prototype.createElement = function createElement(tag) {
return this.document.createElement(tag);
};
// override to avoid namespace shenanigans when in node (this is not needed in SSR)
NodeDOMTreeConstruction.prototype.setAttribute = function setAttribute(element, name, value) {
element.setAttribute(name, value);
};
return NodeDOMTreeConstruction;
}(_runtime.DOMTreeConstruction);
exports.NodeDOMTreeConstruction = NodeDOMTreeConstruction;
});
enifed("@glimmer/reference", ["exports", "@glimmer/util"], function (exports, _util) {
"use strict";
exports.isModified = exports.ReferenceCache = exports.map = exports.CachedReference = exports.UpdatableTag = exports.CachedTag = exports.combine = exports.combineSlice = exports.combineTagged = exports.DirtyableTag = exports.CURRENT_TAG = exports.VOLATILE_TAG = exports.CONSTANT_TAG = exports.TagWrapper = exports.RevisionTag = exports.VOLATILE = exports.INITIAL = exports.CONSTANT = exports.IteratorSynchronizer = exports.ReferenceIterator = exports.IterationArtifacts = exports.referenceFromParts = exports.ListItem = exports.isConst = exports.ConstReference = undefined;
function _defaults(obj, defaults) {
var keys = Object.getOwnPropertyNames(defaults);for (var i = 0; i < keys.length; i++) {
var key = keys[i];var value = Object.getOwnPropertyDescriptor(defaults, key);if (value && value.configurable && obj[key] === undefined) {
Object.defineProperty(obj, key, value);
}
}return obj;
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && (typeof call === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass);
}
function _classCallCheck$1(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var CONSTANT = 0;
var INITIAL = 1;
var VOLATILE = NaN;
var RevisionTag = function () {
function RevisionTag() {
_classCallCheck$1(this, RevisionTag);
}
RevisionTag.prototype.validate = function validate(snapshot) {
return this.value() === snapshot;
};
return RevisionTag;
}();
RevisionTag.id = 0;
var VALUE = [];
var VALIDATE = [];
var TagWrapper = function () {
function TagWrapper(type, inner) {
_classCallCheck$1(this, TagWrapper);
this.type = type;
this.inner = inner;
}
TagWrapper.prototype.value = function value() {
var func = VALUE[this.type];
return func(this.inner);
};
TagWrapper.prototype.validate = function validate(snapshot) {
var func = VALIDATE[this.type];
return func(this.inner, snapshot);
};
return TagWrapper;
}();
function register(Type) {
var type = VALUE.length;
VALUE.push(function (tag) {
return tag.value();
});
VALIDATE.push(function (tag, snapshot) {
return tag.validate(snapshot);
});
Type.id = type;
}
///
// CONSTANT: 0
VALUE.push(function () {
return CONSTANT;
});
VALIDATE.push(function (_tag, snapshot) {
return snapshot === CONSTANT;
});
var CONSTANT_TAG = new TagWrapper(0, null);
// VOLATILE: 1
VALUE.push(function () {
return VOLATILE;
});
VALIDATE.push(function (_tag, snapshot) {
return snapshot === VOLATILE;
});
var VOLATILE_TAG = new TagWrapper(1, null);
// CURRENT: 2
VALUE.push(function () {
return $REVISION;
});
VALIDATE.push(function (_tag, snapshot) {
return snapshot === $REVISION;
});
var CURRENT_TAG = new TagWrapper(2, null);
///
var $REVISION = INITIAL;
var DirtyableTag = function (_RevisionTag) {
_inherits(DirtyableTag, _RevisionTag);
DirtyableTag.create = function create() {
var revision = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : $REVISION;
return new TagWrapper(this.id, new DirtyableTag(revision));
};
function DirtyableTag() {
var revision = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : $REVISION;
_classCallCheck$1(this, DirtyableTag);
var _this = _possibleConstructorReturn(this, _RevisionTag.call(this));
_this.revision = revision;
return _this;
}
DirtyableTag.prototype.value = function value() {
return this.revision;
};
DirtyableTag.prototype.dirty = function dirty() {
this.revision = ++$REVISION;
};
return DirtyableTag;
}(RevisionTag);
register(DirtyableTag);
function combineTagged(tagged) {
var optimized = [];
for (var i = 0, l = tagged.length; i < l; i++) {
var tag = tagged[i].tag;
if (tag === VOLATILE_TAG) return VOLATILE_TAG;
if (tag === CONSTANT_TAG) continue;
optimized.push(tag);
}
return _combine(optimized);
}
function combineSlice(slice) {
var optimized = [];
var node = slice.head();
while (node !== null) {
var tag = node.tag;
if (tag === VOLATILE_TAG) return VOLATILE_TAG;
if (tag !== CONSTANT_TAG) optimized.push(tag);
node = slice.nextNode(node);
}
return _combine(optimized);
}
function combine(tags) {
var optimized = [];
for (var i = 0, l = tags.length; i < l; i++) {
var tag = tags[i];
if (tag === VOLATILE_TAG) return VOLATILE_TAG;
if (tag === CONSTANT_TAG) continue;
optimized.push(tag);
}
return _combine(optimized);
}
function _combine(tags) {
switch (tags.length) {
case 0:
return CONSTANT_TAG;
case 1:
return tags[0];
case 2:
return TagsPair.create(tags[0], tags[1]);
default:
return TagsCombinator.create(tags);
}
}
var CachedTag = function (_RevisionTag2) {
_inherits(CachedTag, _RevisionTag2);
function CachedTag() {
_classCallCheck$1(this, CachedTag);
var _this2 = _possibleConstructorReturn(this, _RevisionTag2.apply(this, arguments));
_this2.lastChecked = null;
_this2.lastValue = null;
return _this2;
}
CachedTag.prototype.value = function value() {
var lastChecked = this.lastChecked,
lastValue = this.lastValue;
if (lastChecked !== $REVISION) {
this.lastChecked = $REVISION;
this.lastValue = lastValue = this.compute();
}
return this.lastValue;
};
CachedTag.prototype.invalidate = function invalidate() {
this.lastChecked = null;
};
return CachedTag;
}(RevisionTag);
var TagsPair = function (_CachedTag) {
_inherits(TagsPair, _CachedTag);
TagsPair.create = function create(first, second) {
return new TagWrapper(this.id, new TagsPair(first, second));
};
function TagsPair(first, second) {
_classCallCheck$1(this, TagsPair);
var _this3 = _possibleConstructorReturn(this, _CachedTag.call(this));
_this3.first = first;
_this3.second = second;
return _this3;
}
TagsPair.prototype.compute = function compute() {
return Math.max(this.first.value(), this.second.value());
};
return TagsPair;
}(CachedTag);
register(TagsPair);
var TagsCombinator = function (_CachedTag2) {
_inherits(TagsCombinator, _CachedTag2);
TagsCombinator.create = function create(tags) {
return new TagWrapper(this.id, new TagsCombinator(tags));
};
function TagsCombinator(tags) {
_classCallCheck$1(this, TagsCombinator);
var _this4 = _possibleConstructorReturn(this, _CachedTag2.call(this));
_this4.tags = tags;
return _this4;
}
TagsCombinator.prototype.compute = function compute() {
var tags = this.tags;
var max = -1;
for (var i = 0; i < tags.length; i++) {
var value = tags[i].value();
max = Math.max(value, max);
}
return max;
};
return TagsCombinator;
}(CachedTag);
register(TagsCombinator);
var UpdatableTag = function (_CachedTag3) {
_inherits(UpdatableTag, _CachedTag3);
UpdatableTag.create = function create(tag) {
return new TagWrapper(this.id, new UpdatableTag(tag));
};
function UpdatableTag(tag) {
_classCallCheck$1(this, UpdatableTag);
var _this5 = _possibleConstructorReturn(this, _CachedTag3.call(this));
_this5.tag = tag;
_this5.lastUpdated = INITIAL;
return _this5;
}
UpdatableTag.prototype.compute = function compute() {
return Math.max(this.lastUpdated, this.tag.value());
};
UpdatableTag.prototype.update = function update(tag) {
if (tag !== this.tag) {
this.tag = tag;
this.lastUpdated = $REVISION;
this.invalidate();
}
};
return UpdatableTag;
}(CachedTag);
register(UpdatableTag);
var CachedReference = function () {
function CachedReference() {
_classCallCheck$1(this, CachedReference);
this.lastRevision = null;
this.lastValue = null;
}
CachedReference.prototype.value = function value() {
var tag = this.tag,
lastRevision = this.lastRevision,
lastValue = this.lastValue;
if (!lastRevision || !tag.validate(lastRevision)) {
lastValue = this.lastValue = this.compute();
this.lastRevision = tag.value();
}
return lastValue;
};
CachedReference.prototype.invalidate = function invalidate() {
this.lastRevision = null;
};
return CachedReference;
}();
var MapperReference = function (_CachedReference) {
_inherits(MapperReference, _CachedReference);
function MapperReference(reference, mapper) {
_classCallCheck$1(this, MapperReference);
var _this6 = _possibleConstructorReturn(this, _CachedReference.call(this));
_this6.tag = reference.tag;
_this6.reference = reference;
_this6.mapper = mapper;
return _this6;
}
MapperReference.prototype.compute = function compute() {
var reference = this.reference,
mapper = this.mapper;
return mapper(reference.value());
};
return MapperReference;
}(CachedReference);
function map(reference, mapper) {
return new MapperReference(reference, mapper);
}
//////////
var ReferenceCache = function () {
function ReferenceCache(reference) {
_classCallCheck$1(this, ReferenceCache);
this.lastValue = null;
this.lastRevision = null;
this.initialized = false;
this.tag = reference.tag;
this.reference = reference;
}
ReferenceCache.prototype.peek = function peek() {
if (!this.initialized) {
return this.initialize();
}
return this.lastValue;
};
ReferenceCache.prototype.revalidate = function revalidate() {
if (!this.initialized) {
return this.initialize();
}
var reference = this.reference,
lastRevision = this.lastRevision;
var tag = reference.tag;
if (tag.validate(lastRevision)) return NOT_MODIFIED;
this.lastRevision = tag.value();
var lastValue = this.lastValue;
var value = reference.value();
if (value === lastValue) return NOT_MODIFIED;
this.lastValue = value;
return value;
};
ReferenceCache.prototype.initialize = function initialize() {
var reference = this.reference;
var value = this.lastValue = reference.value();
this.lastRevision = reference.tag.value();
this.initialized = true;
return value;
};
return ReferenceCache;
}();
var NOT_MODIFIED = "adb3b78e-3d22-4e4b-877a-6317c2c5c145";
function isModified(value) {
return value !== NOT_MODIFIED;
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var ConstReference = function () {
function ConstReference(inner) {
_classCallCheck(this, ConstReference);
this.inner = inner;
this.tag = CONSTANT_TAG;
}
ConstReference.prototype.value = function value() {
return this.inner;
};
return ConstReference;
}();
function isConst(reference) {
return reference.tag === CONSTANT_TAG;
}
function _defaults$1(obj, defaults) {
var keys = Object.getOwnPropertyNames(defaults);for (var i = 0; i < keys.length; i++) {
var key = keys[i];var value = Object.getOwnPropertyDescriptor(defaults, key);if (value && value.configurable && obj[key] === undefined) {
Object.defineProperty(obj, key, value);
}
}return obj;
}
function _classCallCheck$2(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn$1(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && (typeof call === "object" || typeof call === "function") ? call : self;
}
function _inherits$1(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults$1(subClass, superClass);
}
var ListItem = function (_ListNode) {
_inherits$1(ListItem, _ListNode);
function ListItem(iterable, result) {
_classCallCheck$2(this, ListItem);
var _this = _possibleConstructorReturn$1(this, _ListNode.call(this, iterable.valueReferenceFor(result)));
_this.retained = false;
_this.seen = false;
_this.key = result.key;
_this.iterable = iterable;
_this.memo = iterable.memoReferenceFor(result);
return _this;
}
ListItem.prototype.update = function update(item) {
this.retained = true;
this.iterable.updateValueReference(this.value, item);
this.iterable.updateMemoReference(this.memo, item);
};
ListItem.prototype.shouldRemove = function shouldRemove() {
return !this.retained;
};
ListItem.prototype.reset = function reset() {
this.retained = false;
this.seen = false;
};
return ListItem;
}(_util.ListNode);
var IterationArtifacts = function () {
function IterationArtifacts(iterable) {
_classCallCheck$2(this, IterationArtifacts);
this.map = (0, _util.dict)();
this.list = new _util.LinkedList();
this.tag = iterable.tag;
this.iterable = iterable;
}
IterationArtifacts.prototype.isEmpty = function isEmpty() {
var iterator = this.iterator = this.iterable.iterate();
return iterator.isEmpty();
};
IterationArtifacts.prototype.iterate = function iterate() {
var iterator = this.iterator || this.iterable.iterate();
this.iterator = null;
return iterator;
};
IterationArtifacts.prototype.has = function has(key) {
return !!this.map[key];
};
IterationArtifacts.prototype.get = function get(key) {
return this.map[key];
};
IterationArtifacts.prototype.wasSeen = function wasSeen(key) {
var node = this.map[key];
return node && node.seen;
};
IterationArtifacts.prototype.append = function append(item) {
var map = this.map,
list = this.list,
iterable = this.iterable;
var node = map[item.key] = new ListItem(iterable, item);
list.append(node);
return node;
};
IterationArtifacts.prototype.insertBefore = function insertBefore(item, reference) {
var map = this.map,
list = this.list,
iterable = this.iterable;
var node = map[item.key] = new ListItem(iterable, item);
node.retained = true;
list.insertBefore(node, reference);
return node;
};
IterationArtifacts.prototype.move = function move(item, reference) {
var list = this.list;
item.retained = true;
list.remove(item);
list.insertBefore(item, reference);
};
IterationArtifacts.prototype.remove = function remove(item) {
var list = this.list;
list.remove(item);
delete this.map[item.key];
};
IterationArtifacts.prototype.nextNode = function nextNode(item) {
return this.list.nextNode(item);
};
IterationArtifacts.prototype.head = function head() {
return this.list.head();
};
return IterationArtifacts;
}();
var ReferenceIterator = function () {
// if anyone needs to construct this object with something other than
// an iterable, let @wycats know.
function ReferenceIterator(iterable) {
_classCallCheck$2(this, ReferenceIterator);
this.iterator = null;
var artifacts = new IterationArtifacts(iterable);
this.artifacts = artifacts;
}
ReferenceIterator.prototype.next = function next() {
var artifacts = this.artifacts;
var iterator = this.iterator = this.iterator || artifacts.iterate();
var item = iterator.next();
if (!item) return null;
return artifacts.append(item);
};
return ReferenceIterator;
}();
var Phase;
(function (Phase) {
Phase[Phase["Append"] = 0] = "Append";
Phase[Phase["Prune"] = 1] = "Prune";
Phase[Phase["Done"] = 2] = "Done";
})(Phase || (Phase = {}));
var IteratorSynchronizer = function () {
function IteratorSynchronizer(_ref) {
var target = _ref.target,
artifacts = _ref.artifacts;
_classCallCheck$2(this, IteratorSynchronizer);
this.target = target;
this.artifacts = artifacts;
this.iterator = artifacts.iterate();
this.current = artifacts.head();
}
IteratorSynchronizer.prototype.sync = function sync() {
var phase = Phase.Append;
while (true) {
switch (phase) {
case Phase.Append:
phase = this.nextAppend();
break;
case Phase.Prune:
phase = this.nextPrune();
break;
case Phase.Done:
this.nextDone();
return;
}
}
};
IteratorSynchronizer.prototype.advanceToKey = function advanceToKey(key) {
var current = this.current,
artifacts = this.artifacts;
var seek = current;
while (seek && seek.key !== key) {
seek.seen = true;
seek = artifacts.nextNode(seek);
}
this.current = seek && artifacts.nextNode(seek);
};
IteratorSynchronizer.prototype.nextAppend = function nextAppend() {
var iterator = this.iterator,
current = this.current,
artifacts = this.artifacts;
var item = iterator.next();
if (item === null) {
return this.startPrune();
}
var key = item.key;
if (current && current.key === key) {
this.nextRetain(item);
} else if (artifacts.has(key)) {
this.nextMove(item);
} else {
this.nextInsert(item);
}
return Phase.Append;
};
IteratorSynchronizer.prototype.nextRetain = function nextRetain(item) {
var artifacts = this.artifacts,
current = this.current;
current = current;
current.update(item);
this.current = artifacts.nextNode(current);
this.target.retain(item.key, current.value, current.memo);
};
IteratorSynchronizer.prototype.nextMove = function nextMove(item) {
var current = this.current,
artifacts = this.artifacts,
target = this.target;
var key = item.key;
var found = artifacts.get(item.key);
found.update(item);
if (artifacts.wasSeen(item.key)) {
artifacts.move(found, current);
target.move(found.key, found.value, found.memo, current ? current.key : null);
} else {
this.advanceToKey(key);
}
};
IteratorSynchronizer.prototype.nextInsert = function nextInsert(item) {
var artifacts = this.artifacts,
target = this.target,
current = this.current;
var node = artifacts.insertBefore(item, current);
target.insert(node.key, node.value, node.memo, current ? current.key : null);
};
IteratorSynchronizer.prototype.startPrune = function startPrune() {
this.current = this.artifacts.head();
return Phase.Prune;
};
IteratorSynchronizer.prototype.nextPrune = function nextPrune() {
var artifacts = this.artifacts,
target = this.target,
current = this.current;
if (current === null) {
return Phase.Done;
}
var node = current;
this.current = artifacts.nextNode(node);
if (node.shouldRemove()) {
artifacts.remove(node);
target.delete(node.key);
} else {
node.reset();
}
return Phase.Prune;
};
IteratorSynchronizer.prototype.nextDone = function nextDone() {
this.target.done();
};
return IteratorSynchronizer;
}();
function referenceFromParts(root, parts) {
var reference = root;
for (var i = 0; i < parts.length; i++) {
reference = reference.get(parts[i]);
}
return reference;
}
exports.ConstReference = ConstReference;
exports.isConst = isConst;
exports.ListItem = ListItem;
exports.referenceFromParts = referenceFromParts;
exports.IterationArtifacts = IterationArtifacts;
exports.ReferenceIterator = ReferenceIterator;
exports.IteratorSynchronizer = IteratorSynchronizer;
exports.CONSTANT = CONSTANT;
exports.INITIAL = INITIAL;
exports.VOLATILE = VOLATILE;
exports.RevisionTag = RevisionTag;
exports.TagWrapper = TagWrapper;
exports.CONSTANT_TAG = CONSTANT_TAG;
exports.VOLATILE_TAG = VOLATILE_TAG;
exports.CURRENT_TAG = CURRENT_TAG;
exports.DirtyableTag = DirtyableTag;
exports.combineTagged = combineTagged;
exports.combineSlice = combineSlice;
exports.combine = combine;
exports.CachedTag = CachedTag;
exports.UpdatableTag = UpdatableTag;
exports.CachedReference = CachedReference;
exports.map = map;
exports.ReferenceCache = ReferenceCache;
exports.isModified = isModified;
});
enifed('@glimmer/runtime', ['exports', '@glimmer/util', '@glimmer/reference', '@glimmer/wire-format'], function (exports, _util, _reference2, _wireFormat) {
'use strict';
exports.ConcreteBounds = exports.ElementStack = exports.insertHTMLBefore = exports.isWhitespace = exports.DOMTreeConstruction = exports.IDOMChanges = exports.DOMChanges = exports.isComponentDefinition = exports.ComponentDefinition = exports.PartialDefinition = exports.Environment = exports.Scope = exports.isSafeString = exports.RenderResult = exports.UpdatingVM = exports.compileExpression = exports.compileList = exports.InlineMacros = exports.BlockMacros = exports.getDynamicVar = exports.resetDebuggerCallback = exports.setDebuggerCallback = exports.normalizeTextValue = exports.debugSlice = exports.Register = exports.readDOMAttr = exports.defaultPropertyManagers = exports.defaultAttributeManagers = exports.defaultManagers = exports.INPUT_VALUE_PROPERTY_MANAGER = exports.PropertyManager = exports.AttributeManager = exports.IAttributeManager = exports.CompiledDynamicTemplate = exports.CompiledStaticTemplate = exports.compileLayout = exports.OpcodeBuilderDSL = exports.ConditionalReference = exports.PrimitiveReference = exports.UNDEFINED_REFERENCE = exports.NULL_REFERENCE = exports.templateFactory = exports.Simple = undefined;
function _defaults(obj, defaults) {
var keys = Object.getOwnPropertyNames(defaults);for (var i = 0; i < keys.length; i++) {
var key = keys[i];var value = Object.getOwnPropertyDescriptor(defaults, key);if (value && value.configurable && obj[key] === undefined) {
Object.defineProperty(obj, key, value);
}
}return obj;
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && (typeof call === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass);
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
/**
* Registers
*
* For the most part, these follows MIPS naming conventions, however the
* register numbers are different.
*/
var Register;
(function (Register) {
// $0 or $pc (program counter): pointer into `program` for the next insturction; -1 means exit
Register[Register["pc"] = 0] = "pc";
// $1 or $ra (return address): pointer into `program` for the return
Register[Register["ra"] = 1] = "ra";
// $2 or $fp (frame pointer): pointer into the `evalStack` for the base of the stack
Register[Register["fp"] = 2] = "fp";
// $3 or $sp (stack pointer): pointer into the `evalStack` for the top of the stack
Register[Register["sp"] = 3] = "sp";
// $4-$5 or $s0-$s1 (saved): callee saved general-purpose registers
Register[Register["s0"] = 4] = "s0";
Register[Register["s1"] = 5] = "s1";
// $6-$7 or $t0-$t1 (temporaries): caller saved general-purpose registers
Register[Register["t0"] = 6] = "t0";
Register[Register["t1"] = 7] = "t1";
})(Register || (exports.Register = Register = {}));
function debugSlice(env, start, end) {}
var AppendOpcodes = function () {
function AppendOpcodes() {
_classCallCheck(this, AppendOpcodes);
this.evaluateOpcode = (0, _util.fillNulls)(72 /* Size */).slice();
}
AppendOpcodes.prototype.add = function add(name, evaluate) {
this.evaluateOpcode[name] = evaluate;
};
AppendOpcodes.prototype.evaluate = function evaluate(vm, opcode, type) {
var func = this.evaluateOpcode[type];
func(vm, opcode);
};
return AppendOpcodes;
}();
var APPEND_OPCODES = new AppendOpcodes();
var AbstractOpcode = function () {
function AbstractOpcode() {
_classCallCheck(this, AbstractOpcode);
(0, _util.initializeGuid)(this);
}
AbstractOpcode.prototype.toJSON = function toJSON() {
return { guid: this._guid, type: this.type };
};
return AbstractOpcode;
}();
var UpdatingOpcode = function (_AbstractOpcode) {
_inherits(UpdatingOpcode, _AbstractOpcode);
function UpdatingOpcode() {
_classCallCheck(this, UpdatingOpcode);
var _this = _possibleConstructorReturn(this, _AbstractOpcode.apply(this, arguments));
_this.next = null;
_this.prev = null;
return _this;
}
return UpdatingOpcode;
}(AbstractOpcode);
function _defaults$1(obj, defaults) {
var keys = Object.getOwnPropertyNames(defaults);for (var i = 0; i < keys.length; i++) {
var key = keys[i];var value = Object.getOwnPropertyDescriptor(defaults, key);if (value && value.configurable && obj[key] === undefined) {
Object.defineProperty(obj, key, value);
}
}return obj;
}
function _classCallCheck$1(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn$1(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && (typeof call === "object" || typeof call === "function") ? call : self;
}
function _inherits$1(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults$1(subClass, superClass);
}
var PrimitiveReference = function (_ConstReference) {
_inherits$1(PrimitiveReference, _ConstReference);
function PrimitiveReference(value) {
_classCallCheck$1(this, PrimitiveReference);
return _possibleConstructorReturn$1(this, _ConstReference.call(this, value));
}
PrimitiveReference.create = function create(value) {
if (value === undefined) {
return UNDEFINED_REFERENCE;
} else if (value === null) {
return NULL_REFERENCE;
} else if (value === true) {
return TRUE_REFERENCE;
} else if (value === false) {
return FALSE_REFERENCE;
} else if (typeof value === 'number') {
return new ValueReference(value);
} else {
return new StringReference(value);
}
};
PrimitiveReference.prototype.get = function get(_key) {
return UNDEFINED_REFERENCE;
};
return PrimitiveReference;
}(_reference2.ConstReference);
var StringReference = function (_PrimitiveReference) {
_inherits$1(StringReference, _PrimitiveReference);
function StringReference() {
_classCallCheck$1(this, StringReference);
var _this2 = _possibleConstructorReturn$1(this, _PrimitiveReference.apply(this, arguments));
_this2.lengthReference = null;
return _this2;
}
StringReference.prototype.get = function get(key) {
if (key === 'length') {
var lengthReference = this.lengthReference;
if (lengthReference === null) {
lengthReference = this.lengthReference = new ValueReference(this.inner.length);
}
return lengthReference;
} else {
return _PrimitiveReference.prototype.get.call(this, key);
}
};
return StringReference;
}(PrimitiveReference);
var ValueReference = function (_PrimitiveReference2) {
_inherits$1(ValueReference, _PrimitiveReference2);
function ValueReference(value) {
_classCallCheck$1(this, ValueReference);
return _possibleConstructorReturn$1(this, _PrimitiveReference2.call(this, value));
}
return ValueReference;
}(PrimitiveReference);
var UNDEFINED_REFERENCE = new ValueReference(undefined);
var NULL_REFERENCE = new ValueReference(null);
var TRUE_REFERENCE = new ValueReference(true);
var FALSE_REFERENCE = new ValueReference(false);
var ConditionalReference = function () {
function ConditionalReference(inner) {
_classCallCheck$1(this, ConditionalReference);
this.inner = inner;
this.tag = inner.tag;
}
ConditionalReference.prototype.value = function value() {
return this.toBool(this.inner.value());
};
ConditionalReference.prototype.toBool = function toBool(value) {
return !!value;
};
return ConditionalReference;
}();
function _defaults$2(obj, defaults) {
var keys = Object.getOwnPropertyNames(defaults);for (var i = 0; i < keys.length; i++) {
var key = keys[i];var value = Object.getOwnPropertyDescriptor(defaults, key);if (value && value.configurable && obj[key] === undefined) {
Object.defineProperty(obj, key, value);
}
}return obj;
}
function _classCallCheck$2(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn$2(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && (typeof call === "object" || typeof call === "function") ? call : self;
}
function _inherits$2(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults$2(subClass, superClass);
}
var ConcatReference = function (_CachedReference) {
_inherits$2(ConcatReference, _CachedReference);
function ConcatReference(parts) {
_classCallCheck$2(this, ConcatReference);
var _this = _possibleConstructorReturn$2(this, _CachedReference.call(this));
_this.parts = parts;
_this.tag = (0, _reference2.combineTagged)(parts);
return _this;
}
ConcatReference.prototype.compute = function compute() {
var parts = new Array();
for (var i = 0; i < this.parts.length; i++) {
var value = this.parts[i].value();
if (value !== null && value !== undefined) {
parts[i] = castToString(value);
}
}
if (parts.length > 0) {
return parts.join('');
}
return null;
};
return ConcatReference;
}(_reference2.CachedReference);
function castToString(value) {
if (typeof value.toString !== 'function') {
return '';
}
return String(value);
}
APPEND_OPCODES.add(1 /* Helper */, function (vm, _ref) {
var _helper = _ref.op1;
var stack = vm.stack;
var helper = vm.constants.getFunction(_helper);
var args = stack.pop();
var value = helper(vm, args);
args.clear();
vm.stack.push(value);
});
APPEND_OPCODES.add(2 /* Function */, function (vm, _ref2) {
var _function = _ref2.op1;
var func = vm.constants.getFunction(_function);
vm.stack.push(func(vm));
});
APPEND_OPCODES.add(5 /* GetVariable */, function (vm, _ref3) {
var symbol = _ref3.op1;
var expr = vm.referenceForSymbol(symbol);
vm.stack.push(expr);
});
APPEND_OPCODES.add(4 /* SetVariable */, function (vm, _ref4) {
var symbol = _ref4.op1;
var expr = vm.stack.pop();
vm.scope().bindSymbol(symbol, expr);
});
APPEND_OPCODES.add(70 /* ResolveMaybeLocal */, function (vm, _ref5) {
var _name = _ref5.op1;
var name = vm.constants.getString(_name);
var locals = vm.scope().getPartialMap();
var ref = locals[name];
if (ref === undefined) {
ref = vm.getSelf().get(name);
}
vm.stack.push(ref);
});
APPEND_OPCODES.add(19 /* RootScope */, function (vm, _ref6) {
var symbols = _ref6.op1,
bindCallerScope = _ref6.op2;
vm.pushRootScope(symbols, !!bindCallerScope);
});
APPEND_OPCODES.add(6 /* GetProperty */, function (vm, _ref7) {
var _key = _ref7.op1;
var key = vm.constants.getString(_key);
var expr = vm.stack.pop();
vm.stack.push(expr.get(key));
});
APPEND_OPCODES.add(7 /* PushBlock */, function (vm, _ref8) {
var _block = _ref8.op1;
var block = _block ? vm.constants.getBlock(_block) : null;
vm.stack.push(block);
});
APPEND_OPCODES.add(8 /* GetBlock */, function (vm, _ref9) {
var _block = _ref9.op1;
vm.stack.push(vm.scope().getBlock(_block));
});
APPEND_OPCODES.add(9 /* HasBlock */, function (vm, _ref10) {
var _block = _ref10.op1;
var hasBlock = !!vm.scope().getBlock(_block);
vm.stack.push(hasBlock ? TRUE_REFERENCE : FALSE_REFERENCE);
});
APPEND_OPCODES.add(10 /* HasBlockParams */, function (vm, _ref11) {
var _block = _ref11.op1;
var block = vm.scope().getBlock(_block);
var hasBlockParams = block && block.symbolTable.parameters.length;
vm.stack.push(hasBlockParams ? TRUE_REFERENCE : FALSE_REFERENCE);
});
APPEND_OPCODES.add(11 /* Concat */, function (vm, _ref12) {
var count = _ref12.op1;
var out = [];
for (var i = count; i > 0; i--) {
out.push(vm.stack.pop());
}
vm.stack.push(new ConcatReference(out.reverse()));
});
var _createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if ("value" in descriptor) descriptor.writable = true;Object.defineProperty(target, descriptor.key, descriptor);
}
}return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);if (staticProps) defineProperties(Constructor, staticProps);return Constructor;
};
}();
function _classCallCheck$4(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var Arguments = function () {
function Arguments() {
_classCallCheck$4(this, Arguments);
this.stack = null;
this.positional = new PositionalArguments();
this.named = new NamedArguments();
}
Arguments.prototype.empty = function empty() {
this.setup(null, true);
return this;
};
Arguments.prototype.setup = function setup(stack, synthetic) {
this.stack = stack;
var names = stack.fromTop(0);
var namedCount = names.length;
var positionalCount = stack.fromTop(namedCount + 1);
var start = positionalCount + namedCount + 2;
var positional = this.positional;
positional.setup(stack, start, positionalCount);
var named = this.named;
named.setup(stack, namedCount, names, synthetic);
};
Arguments.prototype.at = function at(pos) {
return this.positional.at(pos);
};
Arguments.prototype.get = function get(name) {
return this.named.get(name);
};
Arguments.prototype.capture = function capture() {
return {
tag: this.tag,
length: this.length,
positional: this.positional.capture(),
named: this.named.capture()
};
};
Arguments.prototype.clear = function clear() {
var stack = this.stack,
length = this.length;
stack.pop(length + 2);
};
_createClass(Arguments, [{
key: 'tag',
get: function () {
return (0, _reference2.combineTagged)([this.positional, this.named]);
}
}, {
key: 'length',
get: function () {
return this.positional.length + this.named.length;
}
}]);
return Arguments;
}();
var PositionalArguments = function () {
function PositionalArguments() {
_classCallCheck$4(this, PositionalArguments);
this.length = 0;
this.stack = null;
this.start = 0;
this._tag = null;
this._references = null;
}
PositionalArguments.prototype.setup = function setup(stack, start, length) {
this.stack = stack;
this.start = start;
this.length = length;
this._tag = null;
this._references = null;
};
PositionalArguments.prototype.at = function at(position) {
var start = this.start,
length = this.length;
if (position < 0 || position >= length) {
return UNDEFINED_REFERENCE;
}
// stack: pos1, pos2, pos3, named1, named2
// start: 4 (top - 4)
//
// at(0) === pos1 === top - start
// at(1) === pos2 === top - (start - 1)
// at(2) === pos3 === top - (start - 2)
var fromTop = start - position - 1;
return this.stack.fromTop(fromTop);
};
PositionalArguments.prototype.capture = function capture() {
return new CapturedPositionalArguments(this.tag, this.references);
};
_createClass(PositionalArguments, [{
key: 'tag',
get: function () {
var tag = this._tag;
if (!tag) {
tag = this._tag = (0, _reference2.combineTagged)(this.references);
}
return tag;
}
}, {
key: 'references',
get: function () {
var references = this._references;
if (!references) {
var length = this.length;
references = this._references = new Array(length);
for (var i = 0; i < length; i++) {
references[i] = this.at(i);
}
}
return references;
}
}]);
return PositionalArguments;
}();
var CapturedPositionalArguments = function () {
function CapturedPositionalArguments(tag, references) {
var length = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : references.length;
_classCallCheck$4(this, CapturedPositionalArguments);
this.tag = tag;
this.references = references;
this.length = length;
}
CapturedPositionalArguments.prototype.at = function at(position) {
return this.references[position];
};
CapturedPositionalArguments.prototype.value = function value() {
return this.references.map(this.valueOf);
};
CapturedPositionalArguments.prototype.get = function get(name) {
var references = this.references,
length = this.length;
if (name === 'length') {
return PrimitiveReference.create(length);
} else {
var idx = parseInt(name, 10);
if (idx < 0 || idx >= length) {
return UNDEFINED_REFERENCE;
} else {
return references[idx];
}
}
};
CapturedPositionalArguments.prototype.valueOf = function valueOf(reference) {
return reference.value();
};
return CapturedPositionalArguments;
}();
var NamedArguments = function () {
function NamedArguments() {
_classCallCheck$4(this, NamedArguments);
this.length = 0;
this._tag = null;
this._references = null;
this._names = null;
this._realNames = _util.EMPTY_ARRAY;
}
NamedArguments.prototype.setup = function setup(stack, length, names, synthetic) {
this.stack = stack;
this.length = length;
this._tag = null;
this._references = null;
if (synthetic) {
this._names = names;
this._realNames = _util.EMPTY_ARRAY;
} else {
this._names = null;
this._realNames = names;
}
};
NamedArguments.prototype.has = function has(name) {
return this.names.indexOf(name) !== -1;
};
NamedArguments.prototype.get = function get(name) {
var names = this.names,
length = this.length;
var idx = names.indexOf(name);
if (idx === -1) {
return UNDEFINED_REFERENCE;
}
// stack: pos1, pos2, pos3, named1, named2
// start: 4 (top - 4)
// namedDict: { named1: 1, named2: 0 };
//
// get('named1') === named1 === top - (start - 1)
// get('named2') === named2 === top - start
var fromTop = length - idx;
return this.stack.fromTop(fromTop);
};
NamedArguments.prototype.capture = function capture() {
return new CapturedNamedArguments(this.tag, this.names, this.references);
};
NamedArguments.prototype.sliceName = function sliceName(name) {
return name.slice(1);
};
_createClass(NamedArguments, [{
key: 'tag',
get: function () {
return (0, _reference2.combineTagged)(this.references);
}
}, {
key: 'names',
get: function () {
var names = this._names;
if (!names) {
names = this._names = this._realNames.map(this.sliceName);
}
return names;
}
}, {
key: 'references',
get: function () {
var references = this._references;
if (!references) {
var names = this.names,
length = this.length;
references = this._references = [];
for (var i = 0; i < length; i++) {
references[i] = this.get(names[i]);
}
}
return references;
}
}]);
return NamedArguments;
}();
var CapturedNamedArguments = function () {
function CapturedNamedArguments(tag, names, references) {
_classCallCheck$4(this, CapturedNamedArguments);
this.tag = tag;
this.names = names;
this.references = references;
this.length = names.length;
this._map = null;
}
CapturedNamedArguments.prototype.has = function has(name) {
return this.names.indexOf(name) !== -1;
};
CapturedNamedArguments.prototype.get = function get(name) {
var names = this.names,
references = this.references;
var idx = names.indexOf(name);
if (idx === -1) {
return UNDEFINED_REFERENCE;
} else {
return references[idx];
}
};
CapturedNamedArguments.prototype.value = function value() {
var names = this.names,
references = this.references;
var out = (0, _util.dict)();
for (var i = 0; i < names.length; i++) {
var name = names[i];
out[name] = references[i].value();
}
return out;
};
_createClass(CapturedNamedArguments, [{
key: 'map',
get: function () {
var map$$1 = this._map;
if (!map$$1) {
var names = this.names,
references = this.references;
map$$1 = this._map = (0, _util.dict)();
for (var i = 0; i < names.length; i++) {
var name = names[i];
map$$1[name] = references[i];
}
}
return map$$1;
}
}]);
return CapturedNamedArguments;
}();
var ARGS = new Arguments();
function _defaults$5(obj, defaults) {
var keys = Object.getOwnPropertyNames(defaults);for (var i = 0; i < keys.length; i++) {
var key = keys[i];var value = Object.getOwnPropertyDescriptor(defaults, key);if (value && value.configurable && obj[key] === undefined) {
Object.defineProperty(obj, key, value);
}
}return obj;
}
function _classCallCheck$6(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn$5(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && (typeof call === "object" || typeof call === "function") ? call : self;
}
function _inherits$5(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults$5(subClass, superClass);
}
APPEND_OPCODES.add(20 /* ChildScope */, function (vm) {
return vm.pushChildScope();
});
APPEND_OPCODES.add(21 /* PopScope */, function (vm) {
return vm.popScope();
});
APPEND_OPCODES.add(39 /* PushDynamicScope */, function (vm) {
return vm.pushDynamicScope();
});
APPEND_OPCODES.add(40 /* PopDynamicScope */, function (vm) {
return vm.popDynamicScope();
});
APPEND_OPCODES.add(12 /* Immediate */, function (vm, _ref) {
var number = _ref.op1;
vm.stack.push(number);
});
APPEND_OPCODES.add(13 /* Constant */, function (vm, _ref2) {
var other = _ref2.op1;
vm.stack.push(vm.constants.getOther(other));
});
APPEND_OPCODES.add(14 /* PrimitiveReference */, function (vm, _ref3) {
var primitive = _ref3.op1;
var stack = vm.stack;
var flag = (primitive & 3 << 30) >>> 30;
var value = primitive & ~(3 << 30);
switch (flag) {
case 0:
stack.push(PrimitiveReference.create(value));
break;
case 1:
stack.push(PrimitiveReference.create(vm.constants.getFloat(value)));
break;
case 2:
stack.push(PrimitiveReference.create(vm.constants.getString(value)));
break;
case 3:
switch (value) {
case 0:
stack.push(FALSE_REFERENCE);
break;
case 1:
stack.push(TRUE_REFERENCE);
break;
case 2:
stack.push(NULL_REFERENCE);
break;
case 3:
stack.push(UNDEFINED_REFERENCE);
break;
}
break;
}
});
APPEND_OPCODES.add(15 /* Dup */, function (vm, _ref4) {
var register = _ref4.op1,
offset = _ref4.op2;
var position = vm.fetchValue(register) - offset;
vm.stack.dup(position);
});
APPEND_OPCODES.add(16 /* Pop */, function (vm, _ref5) {
var count = _ref5.op1;
return vm.stack.pop(count);
});
APPEND_OPCODES.add(17 /* Load */, function (vm, _ref6) {
var register = _ref6.op1;
return vm.load(register);
});
APPEND_OPCODES.add(18 /* Fetch */, function (vm, _ref7) {
var register = _ref7.op1;
return vm.fetch(register);
});
APPEND_OPCODES.add(38 /* BindDynamicScope */, function (vm, _ref8) {
var _names = _ref8.op1;
var names = vm.constants.getArray(_names);
vm.bindDynamicScope(names);
});
APPEND_OPCODES.add(47 /* PushFrame */, function (vm) {
return vm.pushFrame();
});
APPEND_OPCODES.add(48 /* PopFrame */, function (vm) {
return vm.popFrame();
});
APPEND_OPCODES.add(49 /* Enter */, function (vm, _ref9) {
var args = _ref9.op1;
return vm.enter(args);
});
APPEND_OPCODES.add(50 /* Exit */, function (vm) {
return vm.exit();
});
APPEND_OPCODES.add(41 /* CompileDynamicBlock */, function (vm) {
var stack = vm.stack;
var block = stack.pop();
stack.push(block ? block.compileDynamic(vm.env) : null);
});
APPEND_OPCODES.add(42 /* InvokeStatic */, function (vm, _ref10) {
var _block = _ref10.op1;
var block = vm.constants.getBlock(_block);
var compiled = block.compileStatic(vm.env);
vm.call(compiled.handle);
});
APPEND_OPCODES.add(43 /* InvokeDynamic */, function (vm, _ref11) {
var _invoker = _ref11.op1;
var invoker = vm.constants.getOther(_invoker);
var block = vm.stack.pop();
invoker.invoke(vm, block);
});
APPEND_OPCODES.add(44 /* Jump */, function (vm, _ref12) {
var target = _ref12.op1;
return vm.goto(target);
});
APPEND_OPCODES.add(45 /* JumpIf */, function (vm, _ref13) {
var target = _ref13.op1;
var reference = vm.stack.pop();
if ((0, _reference2.isConst)(reference)) {
if (reference.value()) {
vm.goto(target);
}
} else {
var cache = new _reference2.ReferenceCache(reference);
if (cache.peek()) {
vm.goto(target);
}
vm.updateWith(new Assert(cache));
}
});
APPEND_OPCODES.add(46 /* JumpUnless */, function (vm, _ref14) {
var target = _ref14.op1;
var reference = vm.stack.pop();
if ((0, _reference2.isConst)(reference)) {
if (!reference.value()) {
vm.goto(target);
}
} else {
var cache = new _reference2.ReferenceCache(reference);
if (!cache.peek()) {
vm.goto(target);
}
vm.updateWith(new Assert(cache));
}
});
APPEND_OPCODES.add(22 /* Return */, function (vm) {
return vm.return();
});
APPEND_OPCODES.add(23 /* ReturnTo */, function (vm, _ref15) {
var relative = _ref15.op1;
vm.returnTo(relative);
});
var ConstTest = function (ref, _env) {
return new _reference2.ConstReference(!!ref.value());
};
var SimpleTest = function (ref, _env) {
return ref;
};
var EnvironmentTest = function (ref, env) {
return env.toConditionalReference(ref);
};
APPEND_OPCODES.add(51 /* Test */, function (vm, _ref16) {
var _func = _ref16.op1;
var stack = vm.stack;
var operand = stack.pop();
var func = vm.constants.getFunction(_func);
stack.push(func(operand, vm.env));
});
var Assert = function (_UpdatingOpcode) {
_inherits$5(Assert, _UpdatingOpcode);
function Assert(cache) {
_classCallCheck$6(this, Assert);
var _this = _possibleConstructorReturn$5(this, _UpdatingOpcode.call(this));
_this.type = 'assert';
_this.tag = cache.tag;
_this.cache = cache;
return _this;
}
Assert.prototype.evaluate = function evaluate(vm) {
var cache = this.cache;
if ((0, _reference2.isModified)(cache.revalidate())) {
vm.throw();
}
};
Assert.prototype.toJSON = function toJSON() {
var type = this.type,
_guid = this._guid,
cache = this.cache;
var expected = void 0;
try {
expected = JSON.stringify(cache.peek());
} catch (e) {
expected = String(cache.peek());
}
return {
args: [],
details: { expected: expected },
guid: _guid,
type: type
};
};
return Assert;
}(UpdatingOpcode);
var JumpIfNotModifiedOpcode = function (_UpdatingOpcode2) {
_inherits$5(JumpIfNotModifiedOpcode, _UpdatingOpcode2);
function JumpIfNotModifiedOpcode(tag, target) {
_classCallCheck$6(this, JumpIfNotModifiedOpcode);
var _this2 = _possibleConstructorReturn$5(this, _UpdatingOpcode2.call(this));
_this2.target = target;
_this2.type = 'jump-if-not-modified';
_this2.tag = tag;
_this2.lastRevision = tag.value();
return _this2;
}
JumpIfNotModifiedOpcode.prototype.evaluate = function evaluate(vm) {
var tag = this.tag,
target = this.target,
lastRevision = this.lastRevision;
if (!vm.alwaysRevalidate && tag.validate(lastRevision)) {
vm.goto(target);
}
};
JumpIfNotModifiedOpcode.prototype.didModify = function didModify() {
this.lastRevision = this.tag.value();
};
JumpIfNotModifiedOpcode.prototype.toJSON = function toJSON() {
return {
args: [JSON.stringify(this.target.inspect())],
guid: this._guid,
type: this.type
};
};
return JumpIfNotModifiedOpcode;
}(UpdatingOpcode);
var DidModifyOpcode = function (_UpdatingOpcode3) {
_inherits$5(DidModifyOpcode, _UpdatingOpcode3);
function DidModifyOpcode(target) {
_classCallCheck$6(this, DidModifyOpcode);
var _this3 = _possibleConstructorReturn$5(this, _UpdatingOpcode3.call(this));
_this3.target = target;
_this3.type = 'did-modify';
_this3.tag = _reference2.CONSTANT_TAG;
return _this3;
}
DidModifyOpcode.prototype.evaluate = function evaluate() {
this.target.didModify();
};
return DidModifyOpcode;
}(UpdatingOpcode);
var LabelOpcode = function () {
function LabelOpcode(label) {
_classCallCheck$6(this, LabelOpcode);
this.tag = _reference2.CONSTANT_TAG;
this.type = 'label';
this.label = null;
this.prev = null;
this.next = null;
(0, _util.initializeGuid)(this);
this.label = label;
}
LabelOpcode.prototype.evaluate = function evaluate() {};
LabelOpcode.prototype.inspect = function inspect$$1() {
return this.label + ' [' + this._guid + ']';
};
LabelOpcode.prototype.toJSON = function toJSON() {
return {
args: [JSON.stringify(this.inspect())],
guid: this._guid,
type: this.type
};
};
return LabelOpcode;
}();
function _defaults$4(obj, defaults) {
var keys = Object.getOwnPropertyNames(defaults);for (var i = 0; i < keys.length; i++) {
var key = keys[i];var value = Object.getOwnPropertyDescriptor(defaults, key);if (value && value.configurable && obj[key] === undefined) {
Object.defineProperty(obj, key, value);
}
}return obj;
}
function _possibleConstructorReturn$4(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && (typeof call === "object" || typeof call === "function") ? call : self;
}
function _inherits$4(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults$4(subClass, superClass);
}
function _classCallCheck$5(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
APPEND_OPCODES.add(24 /* Text */, function (vm, _ref) {
var text = _ref.op1;
vm.elements().appendText(vm.constants.getString(text));
});
APPEND_OPCODES.add(25 /* Comment */, function (vm, _ref2) {
var text = _ref2.op1;
vm.elements().appendComment(vm.constants.getString(text));
});
APPEND_OPCODES.add(27 /* OpenElement */, function (vm, _ref3) {
var tag = _ref3.op1;
vm.elements().openElement(vm.constants.getString(tag));
});
APPEND_OPCODES.add(28 /* OpenElementWithOperations */, function (vm, _ref4) {
var tag = _ref4.op1;
var tagName = vm.constants.getString(tag);
var operations = vm.stack.pop();
vm.elements().openElement(tagName, operations);
});
APPEND_OPCODES.add(29 /* OpenDynamicElement */, function (vm) {
var operations = vm.stack.pop();
var tagName = vm.stack.pop().value();
vm.elements().openElement(tagName, operations);
});
APPEND_OPCODES.add(36 /* PushRemoteElement */, function (vm) {
var elementRef = vm.stack.pop();
var nextSiblingRef = vm.stack.pop();
var element = void 0;
var nextSibling = void 0;
if ((0, _reference2.isConst)(elementRef)) {
element = elementRef.value();
} else {
var cache = new _reference2.ReferenceCache(elementRef);
element = cache.peek();
vm.updateWith(new Assert(cache));
}
if ((0, _reference2.isConst)(nextSiblingRef)) {
nextSibling = nextSiblingRef.value();
} else {
var _cache = new _reference2.ReferenceCache(nextSiblingRef);
nextSibling = _cache.peek();
vm.updateWith(new Assert(_cache));
}
vm.elements().pushRemoteElement(element, nextSibling);
});
APPEND_OPCODES.add(37 /* PopRemoteElement */, function (vm) {
return vm.elements().popRemoteElement();
});
var ClassList = function () {
function ClassList() {
_classCallCheck$5(this, ClassList);
this.list = null;
this.isConst = true;
}
ClassList.prototype.append = function append(reference) {
var list = this.list,
isConst$$1 = this.isConst;
if (list === null) list = this.list = [];
list.push(reference);
this.isConst = isConst$$1 && (0, _reference2.isConst)(reference);
};
ClassList.prototype.toReference = function toReference() {
var list = this.list,
isConst$$1 = this.isConst;
if (!list) return NULL_REFERENCE;
if (isConst$$1) return PrimitiveReference.create(toClassName(list));
return new ClassListReference(list);
};
return ClassList;
}();
var ClassListReference = function (_CachedReference) {
_inherits$4(ClassListReference, _CachedReference);
function ClassListReference(list) {
_classCallCheck$5(this, ClassListReference);
var _this = _possibleConstructorReturn$4(this, _CachedReference.call(this));
_this.list = [];
_this.tag = (0, _reference2.combineTagged)(list);
_this.list = list;
return _this;
}
ClassListReference.prototype.compute = function compute() {
return toClassName(this.list);
};
return ClassListReference;
}(_reference2.CachedReference);
function toClassName(list) {
var ret = [];
for (var i = 0; i < list.length; i++) {
var value = list[i].value();
if (value !== false && value !== null && value !== undefined) ret.push(value);
}
return ret.length === 0 ? null : ret.join(' ');
}
var SimpleElementOperations = function () {
function SimpleElementOperations(env) {
_classCallCheck$5(this, SimpleElementOperations);
this.env = env;
this.opcodes = null;
this.classList = null;
}
SimpleElementOperations.prototype.addStaticAttribute = function addStaticAttribute(element, name, value) {
if (name === 'class') {
this.addClass(PrimitiveReference.create(value));
} else {
this.env.getAppendOperations().setAttribute(element, name, value);
}
};
SimpleElementOperations.prototype.addStaticAttributeNS = function addStaticAttributeNS(element, namespace, name, value) {
this.env.getAppendOperations().setAttribute(element, name, value, namespace);
};
SimpleElementOperations.prototype.addDynamicAttribute = function addDynamicAttribute(element, name, reference, isTrusting) {
if (name === 'class') {
this.addClass(reference);
} else {
var attributeManager = this.env.attributeFor(element, name, isTrusting);
var attribute = new DynamicAttribute(element, attributeManager, name, reference);
this.addAttribute(attribute);
}
};
SimpleElementOperations.prototype.addDynamicAttributeNS = function addDynamicAttributeNS(element, namespace, name, reference, isTrusting) {
var attributeManager = this.env.attributeFor(element, name, isTrusting, namespace);
var nsAttribute = new DynamicAttribute(element, attributeManager, name, reference, namespace);
this.addAttribute(nsAttribute);
};
SimpleElementOperations.prototype.flush = function flush(element, vm) {
var env = vm.env;
var opcodes = this.opcodes,
classList = this.classList;
for (var i = 0; opcodes && i < opcodes.length; i++) {
vm.updateWith(opcodes[i]);
}
if (classList) {
var attributeManager = env.attributeFor(element, 'class', false);
var attribute = new DynamicAttribute(element, attributeManager, 'class', classList.toReference());
var opcode = attribute.flush(env);
if (opcode) {
vm.updateWith(opcode);
}
}
this.opcodes = null;
this.classList = null;
};
SimpleElementOperations.prototype.addClass = function addClass(reference) {
var classList = this.classList;
if (!classList) {
classList = this.classList = new ClassList();
}
classList.append(reference);
};
SimpleElementOperations.prototype.addAttribute = function addAttribute(attribute) {
var opcode = attribute.flush(this.env);
if (opcode) {
var opcodes = this.opcodes;
if (!opcodes) {
opcodes = this.opcodes = [];
}
opcodes.push(opcode);
}
};
return SimpleElementOperations;
}();
var ComponentElementOperations = function () {
function ComponentElementOperations(env) {
_classCallCheck$5(this, ComponentElementOperations);
this.env = env;
this.attributeNames = null;
this.attributes = null;
this.classList = null;
}
ComponentElementOperations.prototype.addStaticAttribute = function addStaticAttribute(element, name, value) {
if (name === 'class') {
this.addClass(PrimitiveReference.create(value));
} else if (this.shouldAddAttribute(name)) {
this.addAttribute(name, new StaticAttribute(element, name, value));
}
};
ComponentElementOperations.prototype.addStaticAttributeNS = function addStaticAttributeNS(element, namespace, name, value) {
if (this.shouldAddAttribute(name)) {
this.addAttribute(name, new StaticAttribute(element, name, value, namespace));
}
};
ComponentElementOperations.prototype.addDynamicAttribute = function addDynamicAttribute(element, name, reference, isTrusting) {
if (name === 'class') {
this.addClass(reference);
} else if (this.shouldAddAttribute(name)) {
var attributeManager = this.env.attributeFor(element, name, isTrusting);
var attribute = new DynamicAttribute(element, attributeManager, name, reference);
this.addAttribute(name, attribute);
}
};
ComponentElementOperations.prototype.addDynamicAttributeNS = function addDynamicAttributeNS(element, namespace, name, reference, isTrusting) {
if (this.shouldAddAttribute(name)) {
var attributeManager = this.env.attributeFor(element, name, isTrusting, namespace);
var nsAttribute = new DynamicAttribute(element, attributeManager, name, reference, namespace);
this.addAttribute(name, nsAttribute);
}
};
ComponentElementOperations.prototype.flush = function flush(element, vm) {
var env = this.env;
var attributes = this.attributes,
classList = this.classList;
for (var i = 0; attributes && i < attributes.length; i++) {
var opcode = attributes[i].flush(env);
if (opcode) {
vm.updateWith(opcode);
}
}
if (classList) {
var attributeManager = env.attributeFor(element, 'class', false);
var attribute = new DynamicAttribute(element, attributeManager, 'class', classList.toReference());
var _opcode = attribute.flush(env);
if (_opcode) {
vm.updateWith(_opcode);
}
}
};
ComponentElementOperations.prototype.shouldAddAttribute = function shouldAddAttribute(name) {
return !this.attributeNames || this.attributeNames.indexOf(name) === -1;
};
ComponentElementOperations.prototype.addClass = function addClass(reference) {
var classList = this.classList;
if (!classList) {
classList = this.classList = new ClassList();
}
classList.append(reference);
};
ComponentElementOperations.prototype.addAttribute = function addAttribute(name, attribute) {
var attributeNames = this.attributeNames,
attributes = this.attributes;
if (!attributeNames) {
attributeNames = this.attributeNames = [];
attributes = this.attributes = [];
}
attributeNames.push(name);
attributes.push(attribute);
};
return ComponentElementOperations;
}();
APPEND_OPCODES.add(33 /* FlushElement */, function (vm) {
var stack = vm.elements();
var action = 'FlushElementOpcode#evaluate';
stack.expectOperations(action).flush(stack.expectConstructing(action), vm);
stack.flushElement();
});
APPEND_OPCODES.add(34 /* CloseElement */, function (vm) {
return vm.elements().closeElement();
});
APPEND_OPCODES.add(30 /* StaticAttr */, function (vm, _ref5) {
var _name = _ref5.op1,
_value = _ref5.op2,
_namespace = _ref5.op3;
var name = vm.constants.getString(_name);
var value = vm.constants.getString(_value);
if (_namespace) {
var namespace = vm.constants.getString(_namespace);
vm.elements().setStaticAttributeNS(namespace, name, value);
} else {
vm.elements().setStaticAttribute(name, value);
}
});
APPEND_OPCODES.add(35 /* Modifier */, function (vm, _ref6) {
var _manager = _ref6.op1;
var manager = vm.constants.getOther(_manager);
var stack = vm.stack;
var args = stack.pop();
var tag = args.tag;
var _vm$elements = vm.elements(),
element = _vm$elements.constructing,
updateOperations = _vm$elements.updateOperations;
var dynamicScope = vm.dynamicScope();
var modifier = manager.create(element, args, dynamicScope, updateOperations);
args.clear();
vm.env.scheduleInstallModifier(modifier, manager);
var destructor = manager.getDestructor(modifier);
if (destructor) {
vm.newDestroyable(destructor);
}
vm.updateWith(new UpdateModifierOpcode(tag, manager, modifier));
});
var UpdateModifierOpcode = function (_UpdatingOpcode) {
_inherits$4(UpdateModifierOpcode, _UpdatingOpcode);
function UpdateModifierOpcode(tag, manager, modifier) {
_classCallCheck$5(this, UpdateModifierOpcode);
var _this2 = _possibleConstructorReturn$4(this, _UpdatingOpcode.call(this));
_this2.tag = tag;
_this2.manager = manager;
_this2.modifier = modifier;
_this2.type = 'update-modifier';
_this2.lastUpdated = tag.value();
return _this2;
}
UpdateModifierOpcode.prototype.evaluate = function evaluate(vm) {
var manager = this.manager,
modifier = this.modifier,
tag = this.tag,
lastUpdated = this.lastUpdated;
if (!tag.validate(lastUpdated)) {
vm.env.scheduleUpdateModifier(modifier, manager);
this.lastUpdated = tag.value();
}
};
UpdateModifierOpcode.prototype.toJSON = function toJSON() {
return {
guid: this._guid,
type: this.type
};
};
return UpdateModifierOpcode;
}(UpdatingOpcode);
var StaticAttribute = function () {
function StaticAttribute(element, name, value, namespace) {
_classCallCheck$5(this, StaticAttribute);
this.element = element;
this.name = name;
this.value = value;
this.namespace = namespace;
}
StaticAttribute.prototype.flush = function flush(env) {
env.getAppendOperations().setAttribute(this.element, this.name, this.value, this.namespace);
return null;
};
return StaticAttribute;
}();
var DynamicAttribute = function () {
function DynamicAttribute(element, attributeManager, name, reference, namespace) {
_classCallCheck$5(this, DynamicAttribute);
this.element = element;
this.attributeManager = attributeManager;
this.name = name;
this.reference = reference;
this.namespace = namespace;
this.cache = null;
this.tag = reference.tag;
}
DynamicAttribute.prototype.patch = function patch(env) {
var element = this.element,
cache = this.cache;
var value = cache.revalidate();
if ((0, _reference2.isModified)(value)) {
this.attributeManager.updateAttribute(env, element, value, this.namespace);
}
};
DynamicAttribute.prototype.flush = function flush(env) {
var reference = this.reference,
element = this.element;
if ((0, _reference2.isConst)(reference)) {
var value = reference.value();
this.attributeManager.setAttribute(env, element, value, this.namespace);
return null;
} else {
var cache = this.cache = new _reference2.ReferenceCache(reference);
var _value2 = cache.peek();
this.attributeManager.setAttribute(env, element, _value2, this.namespace);
return new PatchElementOpcode(this);
}
};
DynamicAttribute.prototype.toJSON = function toJSON() {
var element = this.element,
namespace = this.namespace,
name = this.name,
cache = this.cache;
var formattedElement = formatElement(element);
var lastValue = cache.peek();
if (namespace) {
return {
element: formattedElement,
lastValue: lastValue,
name: name,
namespace: namespace,
type: 'attribute'
};
}
return {
element: formattedElement,
lastValue: lastValue,
name: name,
namespace: namespace === undefined ? null : namespace,
type: 'attribute'
};
};
return DynamicAttribute;
}();
function formatElement(element) {
return JSON.stringify('<' + element.tagName.toLowerCase() + ' />');
}
APPEND_OPCODES.add(32 /* DynamicAttrNS */, function (vm, _ref7) {
var _name = _ref7.op1,
_namespace = _ref7.op2,
trusting = _ref7.op3;
var name = vm.constants.getString(_name);
var namespace = vm.constants.getString(_namespace);
var reference = vm.stack.pop();
vm.elements().setDynamicAttributeNS(namespace, name, reference, !!trusting);
});
APPEND_OPCODES.add(31 /* DynamicAttr */, function (vm, _ref8) {
var _name = _ref8.op1,
trusting = _ref8.op2;
var name = vm.constants.getString(_name);
var reference = vm.stack.pop();
vm.elements().setDynamicAttribute(name, reference, !!trusting);
});
var PatchElementOpcode = function (_UpdatingOpcode2) {
_inherits$4(PatchElementOpcode, _UpdatingOpcode2);
function PatchElementOpcode(operation) {
_classCallCheck$5(this, PatchElementOpcode);
var _this3 = _possibleConstructorReturn$4(this, _UpdatingOpcode2.call(this));
_this3.type = 'patch-element';
_this3.tag = operation.tag;
_this3.operation = operation;
return _this3;
}
PatchElementOpcode.prototype.evaluate = function evaluate(vm) {
this.operation.patch(vm.env);
};
PatchElementOpcode.prototype.toJSON = function toJSON() {
var _guid = this._guid,
type = this.type,
operation = this.operation;
return {
details: operation.toJSON(),
guid: _guid,
type: type
};
};
return PatchElementOpcode;
}(UpdatingOpcode);
function _defaults$3(obj, defaults) {
var keys = Object.getOwnPropertyNames(defaults);for (var i = 0; i < keys.length; i++) {
var key = keys[i];var value = Object.getOwnPropertyDescriptor(defaults, key);if (value && value.configurable && obj[key] === undefined) {
Object.defineProperty(obj, key, value);
}
}return obj;
}
function _classCallCheck$3(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn$3(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && (typeof call === "object" || typeof call === "function") ? call : self;
}
function _inherits$3(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults$3(subClass, superClass);
}
APPEND_OPCODES.add(56 /* PushComponentManager */, function (vm, _ref) {
var _definition = _ref.op1;
var definition = vm.constants.getOther(_definition);
var stack = vm.stack;
stack.push({ definition: definition, manager: definition.manager, component: null });
});
APPEND_OPCODES.add(57 /* PushDynamicComponentManager */, function (vm) {
var stack = vm.stack;
var reference = stack.pop();
var cache = (0, _reference2.isConst)(reference) ? undefined : new _reference2.ReferenceCache(reference);
var definition = cache ? cache.peek() : reference.value();
stack.push({ definition: definition, manager: definition.manager, component: null });
if (cache) {
vm.updateWith(new Assert(cache));
}
});
APPEND_OPCODES.add(58 /* PushArgs */, function (vm, _ref2) {
var synthetic = _ref2.op1;
var stack = vm.stack;
ARGS.setup(stack, !!synthetic);
stack.push(ARGS);
});
APPEND_OPCODES.add(59 /* PrepareArgs */, function (vm, _ref3) {
var _state = _ref3.op1;
var stack = vm.stack;
var _vm$fetchValue = vm.fetchValue(_state),
definition = _vm$fetchValue.definition,
manager = _vm$fetchValue.manager;
var args = stack.pop();
var preparedArgs = manager.prepareArgs(definition, args);
if (preparedArgs) {
args.clear();
var positional = preparedArgs.positional,
named = preparedArgs.named;
var positionalCount = positional.length;
for (var i = 0; i < positionalCount; i++) {
stack.push(positional[i]);
}
stack.push(positionalCount);
var names = Object.keys(named);
var namedCount = names.length;
var atNames = [];
for (var _i = 0; _i < namedCount; _i++) {
var value = named[names[_i]];
var atName = '@' + names[_i];
stack.push(value);
atNames.push(atName);
}
stack.push(atNames);
args.setup(stack, false);
}
stack.push(args);
});
APPEND_OPCODES.add(60 /* CreateComponent */, function (vm, _ref4) {
var _vm$fetchValue2;
var flags = _ref4.op1,
_state = _ref4.op2;
var definition = void 0;
var manager = void 0;
var args = vm.stack.pop();
var dynamicScope = vm.dynamicScope();
var state = (_vm$fetchValue2 = vm.fetchValue(_state), definition = _vm$fetchValue2.definition, manager = _vm$fetchValue2.manager, _vm$fetchValue2);
var hasDefaultBlock = flags & 1;
var component = manager.create(vm.env, definition, args, dynamicScope, vm.getSelf(), !!hasDefaultBlock);
state.component = component;
vm.updateWith(new UpdateComponentOpcode(args.tag, definition.name, component, manager, dynamicScope));
});
APPEND_OPCODES.add(61 /* RegisterComponentDestructor */, function (vm, _ref5) {
var _state = _ref5.op1;
var _vm$fetchValue3 = vm.fetchValue(_state),
manager = _vm$fetchValue3.manager,
component = _vm$fetchValue3.component;
var destructor = manager.getDestructor(component);
if (destructor) vm.newDestroyable(destructor);
});
APPEND_OPCODES.add(65 /* BeginComponentTransaction */, function (vm) {
vm.beginCacheGroup();
vm.elements().pushSimpleBlock();
});
APPEND_OPCODES.add(62 /* PushComponentOperations */, function (vm) {
vm.stack.push(new ComponentElementOperations(vm.env));
});
APPEND_OPCODES.add(67 /* DidCreateElement */, function (vm, _ref6) {
var _state = _ref6.op1;
var _vm$fetchValue4 = vm.fetchValue(_state),
manager = _vm$fetchValue4.manager,
component = _vm$fetchValue4.component;
var action = 'DidCreateElementOpcode#evaluate';
manager.didCreateElement(component, vm.elements().expectConstructing(action), vm.elements().expectOperations(action));
});
APPEND_OPCODES.add(63 /* GetComponentSelf */, function (vm, _ref7) {
var _state = _ref7.op1;
var state = vm.fetchValue(_state);
vm.stack.push(state.manager.getSelf(state.component));
});
APPEND_OPCODES.add(64 /* GetComponentLayout */, function (vm, _ref8) {
var _state = _ref8.op1;
var _vm$fetchValue5 = vm.fetchValue(_state),
manager = _vm$fetchValue5.manager,
definition = _vm$fetchValue5.definition,
component = _vm$fetchValue5.component;
vm.stack.push(manager.layoutFor(definition, component, vm.env));
});
APPEND_OPCODES.add(68 /* DidRenderLayout */, function (vm, _ref9) {
var _state = _ref9.op1;
var _vm$fetchValue6 = vm.fetchValue(_state),
manager = _vm$fetchValue6.manager,
component = _vm$fetchValue6.component;
var bounds = vm.elements().popBlock();
manager.didRenderLayout(component, bounds);
vm.env.didCreate(component, manager);
vm.updateWith(new DidUpdateLayoutOpcode(manager, component, bounds));
});
APPEND_OPCODES.add(66 /* CommitComponentTransaction */, function (vm) {
return vm.commitCacheGroup();
});
var UpdateComponentOpcode = function (_UpdatingOpcode) {
_inherits$3(UpdateComponentOpcode, _UpdatingOpcode);
function UpdateComponentOpcode(tag, name, component, manager, dynamicScope) {
_classCallCheck$3(this, UpdateComponentOpcode);
var _this = _possibleConstructorReturn$3(this, _UpdatingOpcode.call(this));
_this.name = name;
_this.component = component;
_this.manager = manager;
_this.dynamicScope = dynamicScope;
_this.type = 'update-component';
var componentTag = manager.getTag(component);
if (componentTag) {
_this.tag = (0, _reference2.combine)([tag, componentTag]);
} else {
_this.tag = tag;
}
return _this;
}
UpdateComponentOpcode.prototype.evaluate = function evaluate(_vm) {
var component = this.component,
manager = this.manager,
dynamicScope = this.dynamicScope;
manager.update(component, dynamicScope);
};
UpdateComponentOpcode.prototype.toJSON = function toJSON() {
return {
args: [JSON.stringify(this.name)],
guid: this._guid,
type: this.type
};
};
return UpdateComponentOpcode;
}(UpdatingOpcode);
var DidUpdateLayoutOpcode = function (_UpdatingOpcode2) {
_inherits$3(DidUpdateLayoutOpcode, _UpdatingOpcode2);
function DidUpdateLayoutOpcode(manager, component, bounds) {
_classCallCheck$3(this, DidUpdateLayoutOpcode);
var _this2 = _possibleConstructorReturn$3(this, _UpdatingOpcode2.call(this));
_this2.manager = manager;
_this2.component = component;
_this2.bounds = bounds;
_this2.type = 'did-update-layout';
_this2.tag = _reference2.CONSTANT_TAG;
return _this2;
}
DidUpdateLayoutOpcode.prototype.evaluate = function evaluate(vm) {
var manager = this.manager,
component = this.component,
bounds = this.bounds;
manager.didUpdateLayout(component, bounds);
vm.env.didUpdate(component, manager);
};
return DidUpdateLayoutOpcode;
}(UpdatingOpcode);
function _classCallCheck$8(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var Cursor = function Cursor(element, nextSibling) {
_classCallCheck$8(this, Cursor);
this.element = element;
this.nextSibling = nextSibling;
};
var ConcreteBounds = function () {
function ConcreteBounds(parentNode, first, last) {
_classCallCheck$8(this, ConcreteBounds);
this.parentNode = parentNode;
this.first = first;
this.last = last;
}
ConcreteBounds.prototype.parentElement = function parentElement() {
return this.parentNode;
};
ConcreteBounds.prototype.firstNode = function firstNode() {
return this.first;
};
ConcreteBounds.prototype.lastNode = function lastNode() {
return this.last;
};
return ConcreteBounds;
}();
var SingleNodeBounds = function () {
function SingleNodeBounds(parentNode, node) {
_classCallCheck$8(this, SingleNodeBounds);
this.parentNode = parentNode;
this.node = node;
}
SingleNodeBounds.prototype.parentElement = function parentElement() {
return this.parentNode;
};
SingleNodeBounds.prototype.firstNode = function firstNode() {
return this.node;
};
SingleNodeBounds.prototype.lastNode = function lastNode() {
return this.node;
};
return SingleNodeBounds;
}();
function single(parent, node) {
return new SingleNodeBounds(parent, node);
}
function move(bounds, reference) {
var parent = bounds.parentElement();
var first = bounds.firstNode();
var last = bounds.lastNode();
var node = first;
while (node) {
var next = node.nextSibling;
parent.insertBefore(node, reference);
if (node === last) return next;
node = next;
}
return null;
}
function clear(bounds) {
var parent = bounds.parentElement();
var first = bounds.firstNode();
var last = bounds.lastNode();
var node = first;
while (node) {
var next = node.nextSibling;
parent.removeChild(node);
if (node === last) return next;
node = next;
}
return null;
}
function _defaults$7(obj, defaults) {
var keys = Object.getOwnPropertyNames(defaults);for (var i = 0; i < keys.length; i++) {
var key = keys[i];var value = Object.getOwnPropertyDescriptor(defaults, key);if (value && value.configurable && obj[key] === undefined) {
Object.defineProperty(obj, key, value);
}
}return obj;
}
function _possibleConstructorReturn$7(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && (typeof call === "object" || typeof call === "function") ? call : self;
}
function _inherits$7(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults$7(subClass, superClass);
}
function _classCallCheck$9(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var First = function () {
function First(node) {
_classCallCheck$9(this, First);
this.node = node;
}
First.prototype.firstNode = function firstNode() {
return this.node;
};
return First;
}();
var Last = function () {
function Last(node) {
_classCallCheck$9(this, Last);
this.node = node;
}
Last.prototype.lastNode = function lastNode() {
return this.node;
};
return Last;
}();
var Fragment = function () {
function Fragment(bounds$$1) {
_classCallCheck$9(this, Fragment);
this.bounds = bounds$$1;
}
Fragment.prototype.parentElement = function parentElement() {
return this.bounds.parentElement();
};
Fragment.prototype.firstNode = function firstNode() {
return this.bounds.firstNode();
};
Fragment.prototype.lastNode = function lastNode() {
return this.bounds.lastNode();
};
Fragment.prototype.update = function update(bounds$$1) {
this.bounds = bounds$$1;
};
return Fragment;
}();
var ElementStack = function () {
function ElementStack(env, parentNode, nextSibling) {
_classCallCheck$9(this, ElementStack);
this.constructing = null;
this.operations = null;
this.elementStack = new _util.Stack();
this.nextSiblingStack = new _util.Stack();
this.blockStack = new _util.Stack();
this.env = env;
this.dom = env.getAppendOperations();
this.updateOperations = env.getDOM();
this.element = parentNode;
this.nextSibling = nextSibling;
this.defaultOperations = new SimpleElementOperations(env);
this.pushSimpleBlock();
this.elementStack.push(this.element);
this.nextSiblingStack.push(this.nextSibling);
}
ElementStack.forInitialRender = function forInitialRender(env, parentNode, nextSibling) {
return new ElementStack(env, parentNode, nextSibling);
};
ElementStack.resume = function resume(env, tracker, nextSibling) {
var parentNode = tracker.parentElement();
var stack = new ElementStack(env, parentNode, nextSibling);
stack.pushBlockTracker(tracker);
return stack;
};
ElementStack.prototype.expectConstructing = function expectConstructing(method) {
return this.constructing;
};
ElementStack.prototype.expectOperations = function expectOperations(method) {
return this.operations;
};
ElementStack.prototype.block = function block() {
return this.blockStack.current;
};
ElementStack.prototype.popElement = function popElement() {
var elementStack = this.elementStack,
nextSiblingStack = this.nextSiblingStack;
var topElement = elementStack.pop();
nextSiblingStack.pop();
// LOGGER.debug(`-> element stack ${this.elementStack.toArray().map(e => e.tagName).join(', ')}`);
this.element = elementStack.current;
this.nextSibling = nextSiblingStack.current;
return topElement;
};
ElementStack.prototype.pushSimpleBlock = function pushSimpleBlock() {
var tracker = new SimpleBlockTracker(this.element);
this.pushBlockTracker(tracker);
return tracker;
};
ElementStack.prototype.pushUpdatableBlock = function pushUpdatableBlock() {
var tracker = new UpdatableBlockTracker(this.element);
this.pushBlockTracker(tracker);
return tracker;
};
ElementStack.prototype.pushBlockTracker = function pushBlockTracker(tracker) {
var isRemote = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
var current = this.blockStack.current;
if (current !== null) {
current.newDestroyable(tracker);
if (!isRemote) {
current.newBounds(tracker);
}
}
this.blockStack.push(tracker);
return tracker;
};
ElementStack.prototype.pushBlockList = function pushBlockList(list) {
var tracker = new BlockListTracker(this.element, list);
var current = this.blockStack.current;
if (current !== null) {
current.newDestroyable(tracker);
current.newBounds(tracker);
}
this.blockStack.push(tracker);
return tracker;
};
ElementStack.prototype.popBlock = function popBlock() {
this.block().finalize(this);
return this.blockStack.pop();
};
ElementStack.prototype.openElement = function openElement(tag, _operations) {
// workaround argument.length transpile of arg initializer
var operations = _operations === undefined ? this.defaultOperations : _operations;
var element = this.dom.createElement(tag, this.element);
this.constructing = element;
this.operations = operations;
return element;
};
ElementStack.prototype.flushElement = function flushElement() {
var parent = this.element;
var element = this.constructing;
this.dom.insertBefore(parent, element, this.nextSibling);
this.constructing = null;
this.operations = null;
this.pushElement(element, null);
this.block().openElement(element);
};
ElementStack.prototype.pushRemoteElement = function pushRemoteElement(element) {
var nextSibling = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
this.pushElement(element, nextSibling);
var tracker = new RemoteBlockTracker(element);
this.pushBlockTracker(tracker, true);
};
ElementStack.prototype.popRemoteElement = function popRemoteElement() {
this.popBlock();
this.popElement();
};
ElementStack.prototype.pushElement = function pushElement(element, nextSibling) {
this.element = element;
this.elementStack.push(element);
// LOGGER.debug(`-> element stack ${this.elementStack.toArray().map(e => e.tagName).join(', ')}`);
this.nextSibling = nextSibling;
this.nextSiblingStack.push(nextSibling);
};
ElementStack.prototype.newDestroyable = function newDestroyable(d) {
this.block().newDestroyable(d);
};
ElementStack.prototype.newBounds = function newBounds(bounds$$1) {
this.block().newBounds(bounds$$1);
};
ElementStack.prototype.appendText = function appendText(string) {
var dom = this.dom;
var text = dom.createTextNode(string);
dom.insertBefore(this.element, text, this.nextSibling);
this.block().newNode(text);
return text;
};
ElementStack.prototype.appendComment = function appendComment(string) {
var dom = this.dom;
var comment = dom.createComment(string);
dom.insertBefore(this.element, comment, this.nextSibling);
this.block().newNode(comment);
return comment;
};
ElementStack.prototype.setStaticAttribute = function setStaticAttribute(name, value) {
this.expectOperations('setStaticAttribute').addStaticAttribute(this.expectConstructing('setStaticAttribute'), name, value);
};
ElementStack.prototype.setStaticAttributeNS = function setStaticAttributeNS(namespace, name, value) {
this.expectOperations('setStaticAttributeNS').addStaticAttributeNS(this.expectConstructing('setStaticAttributeNS'), namespace, name, value);
};
ElementStack.prototype.setDynamicAttribute = function setDynamicAttribute(name, reference, isTrusting) {
this.expectOperations('setDynamicAttribute').addDynamicAttribute(this.expectConstructing('setDynamicAttribute'), name, reference, isTrusting);
};
ElementStack.prototype.setDynamicAttributeNS = function setDynamicAttributeNS(namespace, name, reference, isTrusting) {
this.expectOperations('setDynamicAttributeNS').addDynamicAttributeNS(this.expectConstructing('setDynamicAttributeNS'), namespace, name, reference, isTrusting);
};
ElementStack.prototype.closeElement = function closeElement() {
this.block().closeElement();
this.popElement();
};
return ElementStack;
}();
var SimpleBlockTracker = function () {
function SimpleBlockTracker(parent) {
_classCallCheck$9(this, SimpleBlockTracker);
this.parent = parent;
this.first = null;
this.last = null;
this.destroyables = null;
this.nesting = 0;
}
SimpleBlockTracker.prototype.destroy = function destroy() {
var destroyables = this.destroyables;
if (destroyables && destroyables.length) {
for (var i = 0; i < destroyables.length; i++) {
destroyables[i].destroy();
}
}
};
SimpleBlockTracker.prototype.parentElement = function parentElement() {
return this.parent;
};
SimpleBlockTracker.prototype.firstNode = function firstNode() {
return this.first && this.first.firstNode();
};
SimpleBlockTracker.prototype.lastNode = function lastNode() {
return this.last && this.last.lastNode();
};
SimpleBlockTracker.prototype.openElement = function openElement(element) {
this.newNode(element);
this.nesting++;
};
SimpleBlockTracker.prototype.closeElement = function closeElement() {
this.nesting--;
};
SimpleBlockTracker.prototype.newNode = function newNode(node) {
if (this.nesting !== 0) return;
if (!this.first) {
this.first = new First(node);
}
this.last = new Last(node);
};
SimpleBlockTracker.prototype.newBounds = function newBounds(bounds$$1) {
if (this.nesting !== 0) return;
if (!this.first) {
this.first = bounds$$1;
}
this.last = bounds$$1;
};
SimpleBlockTracker.prototype.newDestroyable = function newDestroyable(d) {
this.destroyables = this.destroyables || [];
this.destroyables.push(d);
};
SimpleBlockTracker.prototype.finalize = function finalize(stack) {
if (!this.first) {
stack.appendComment('');
}
};
return SimpleBlockTracker;
}();
var RemoteBlockTracker = function (_SimpleBlockTracker) {
_inherits$7(RemoteBlockTracker, _SimpleBlockTracker);
function RemoteBlockTracker() {
_classCallCheck$9(this, RemoteBlockTracker);
return _possibleConstructorReturn$7(this, _SimpleBlockTracker.apply(this, arguments));
}
RemoteBlockTracker.prototype.destroy = function destroy() {
_SimpleBlockTracker.prototype.destroy.call(this);
clear(this);
};
return RemoteBlockTracker;
}(SimpleBlockTracker);
var UpdatableBlockTracker = function (_SimpleBlockTracker2) {
_inherits$7(UpdatableBlockTracker, _SimpleBlockTracker2);
function UpdatableBlockTracker() {
_classCallCheck$9(this, UpdatableBlockTracker);
return _possibleConstructorReturn$7(this, _SimpleBlockTracker2.apply(this, arguments));
}
UpdatableBlockTracker.prototype.reset = function reset(env) {
var destroyables = this.destroyables;
if (destroyables && destroyables.length) {
for (var i = 0; i < destroyables.length; i++) {
env.didDestroy(destroyables[i]);
}
}
var nextSibling = clear(this);
this.first = null;
this.last = null;
this.destroyables = null;
this.nesting = 0;
return nextSibling;
};
return UpdatableBlockTracker;
}(SimpleBlockTracker);
var BlockListTracker = function () {
function BlockListTracker(parent, boundList) {
_classCallCheck$9(this, BlockListTracker);
this.parent = parent;
this.boundList = boundList;
this.parent = parent;
this.boundList = boundList;
}
BlockListTracker.prototype.destroy = function destroy() {
this.boundList.forEachNode(function (node) {
return node.destroy();
});
};
BlockListTracker.prototype.parentElement = function parentElement() {
return this.parent;
};
BlockListTracker.prototype.firstNode = function firstNode() {
var head = this.boundList.head();
return head && head.firstNode();
};
BlockListTracker.prototype.lastNode = function lastNode() {
var tail = this.boundList.tail();
return tail && tail.lastNode();
};
BlockListTracker.prototype.openElement = function openElement(_element) {
(0, _util.assert)(false, 'Cannot openElement directly inside a block list');
};
BlockListTracker.prototype.closeElement = function closeElement() {
(0, _util.assert)(false, 'Cannot closeElement directly inside a block list');
};
BlockListTracker.prototype.newNode = function newNode(_node) {
(0, _util.assert)(false, 'Cannot create a new node directly inside a block list');
};
BlockListTracker.prototype.newBounds = function newBounds(_bounds) {};
BlockListTracker.prototype.newDestroyable = function newDestroyable(_d) {};
BlockListTracker.prototype.finalize = function finalize(_stack) {};
return BlockListTracker;
}();
function _classCallCheck$10(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var COMPONENT_DEFINITION_BRAND = 'COMPONENT DEFINITION [id=e59c754e-61eb-4392-8c4a-2c0ac72bfcd4]';
function isComponentDefinition(obj) {
return typeof obj === 'object' && obj !== null && obj[COMPONENT_DEFINITION_BRAND];
}
var ComponentDefinition = function ComponentDefinition(name, manager, ComponentClass) {
_classCallCheck$10(this, ComponentDefinition);
this[COMPONENT_DEFINITION_BRAND] = true;
this.name = name;
this.manager = manager;
this.ComponentClass = ComponentClass;
};
function _defaults$8(obj, defaults) {
var keys = Object.getOwnPropertyNames(defaults);for (var i = 0; i < keys.length; i++) {
var key = keys[i];var value = Object.getOwnPropertyDescriptor(defaults, key);if (value && value.configurable && obj[key] === undefined) {
Object.defineProperty(obj, key, value);
}
}return obj;
}
function _possibleConstructorReturn$8(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && (typeof call === "object" || typeof call === "function") ? call : self;
}
function _inherits$8(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults$8(subClass, superClass);
}
function _classCallCheck$11(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function isSafeString(value) {
return typeof value === 'object' && value !== null && typeof value.toHTML === 'function';
}
function isNode(value) {
return typeof value === 'object' && value !== null && typeof value.nodeType === 'number';
}
function isString(value) {
return typeof value === 'string';
}
var Upsert = function Upsert(bounds$$1) {
_classCallCheck$11(this, Upsert);
this.bounds = bounds$$1;
};
function cautiousInsert(dom, cursor, value) {
if (isString(value)) {
return TextUpsert.insert(dom, cursor, value);
}
if (isSafeString(value)) {
return SafeStringUpsert.insert(dom, cursor, value);
}
if (isNode(value)) {
return NodeUpsert.insert(dom, cursor, value);
}
throw (0, _util.unreachable)();
}
function trustingInsert(dom, cursor, value) {
if (isString(value)) {
return HTMLUpsert.insert(dom, cursor, value);
}
if (isNode(value)) {
return NodeUpsert.insert(dom, cursor, value);
}
throw (0, _util.unreachable)();
}
var TextUpsert = function (_Upsert) {
_inherits$8(TextUpsert, _Upsert);
TextUpsert.insert = function insert(dom, cursor, value) {
var textNode = dom.createTextNode(value);
dom.insertBefore(cursor.element, textNode, cursor.nextSibling);
var bounds$$1 = new SingleNodeBounds(cursor.element, textNode);
return new TextUpsert(bounds$$1, textNode);
};
function TextUpsert(bounds$$1, textNode) {
_classCallCheck$11(this, TextUpsert);
var _this = _possibleConstructorReturn$8(this, _Upsert.call(this, bounds$$1));
_this.textNode = textNode;
return _this;
}
TextUpsert.prototype.update = function update(_dom, value) {
if (isString(value)) {
var textNode = this.textNode;
textNode.nodeValue = value;
return true;
} else {
return false;
}
};
return TextUpsert;
}(Upsert);
var HTMLUpsert = function (_Upsert2) {
_inherits$8(HTMLUpsert, _Upsert2);
function HTMLUpsert() {
_classCallCheck$11(this, HTMLUpsert);
return _possibleConstructorReturn$8(this, _Upsert2.apply(this, arguments));
}
HTMLUpsert.insert = function insert(dom, cursor, value) {
var bounds$$1 = dom.insertHTMLBefore(cursor.element, cursor.nextSibling, value);
return new HTMLUpsert(bounds$$1);
};
HTMLUpsert.prototype.update = function update(dom, value) {
if (isString(value)) {
var bounds$$1 = this.bounds;
var parentElement = bounds$$1.parentElement();
var nextSibling = clear(bounds$$1);
this.bounds = dom.insertHTMLBefore(parentElement, nextSibling, value);
return true;
} else {
return false;
}
};
return HTMLUpsert;
}(Upsert);
var SafeStringUpsert = function (_Upsert3) {
_inherits$8(SafeStringUpsert, _Upsert3);
function SafeStringUpsert(bounds$$1, lastStringValue) {
_classCallCheck$11(this, SafeStringUpsert);
var _this3 = _possibleConstructorReturn$8(this, _Upsert3.call(this, bounds$$1));
_this3.lastStringValue = lastStringValue;
return _this3;
}
SafeStringUpsert.insert = function insert(dom, cursor, value) {
var stringValue = value.toHTML();
var bounds$$1 = dom.insertHTMLBefore(cursor.element, cursor.nextSibling, stringValue);
return new SafeStringUpsert(bounds$$1, stringValue);
};
SafeStringUpsert.prototype.update = function update(dom, value) {
if (isSafeString(value)) {
var stringValue = value.toHTML();
if (stringValue !== this.lastStringValue) {
var bounds$$1 = this.bounds;
var parentElement = bounds$$1.parentElement();
var nextSibling = clear(bounds$$1);
this.bounds = dom.insertHTMLBefore(parentElement, nextSibling, stringValue);
this.lastStringValue = stringValue;
}
return true;
} else {
return false;
}
};
return SafeStringUpsert;
}(Upsert);
var NodeUpsert = function (_Upsert4) {
_inherits$8(NodeUpsert, _Upsert4);
function NodeUpsert() {
_classCallCheck$11(this, NodeUpsert);
return _possibleConstructorReturn$8(this, _Upsert4.apply(this, arguments));
}
NodeUpsert.insert = function insert(dom, cursor, node) {
dom.insertBefore(cursor.element, node, cursor.nextSibling);
return new NodeUpsert(single(cursor.element, node));
};
NodeUpsert.prototype.update = function update(dom, value) {
if (isNode(value)) {
var bounds$$1 = this.bounds;
var parentElement = bounds$$1.parentElement();
var nextSibling = clear(bounds$$1);
this.bounds = dom.insertNodeBefore(parentElement, value, nextSibling);
return true;
} else {
return false;
}
};
return NodeUpsert;
}(Upsert);
function _defaults$6(obj, defaults) {
var keys = Object.getOwnPropertyNames(defaults);for (var i = 0; i < keys.length; i++) {
var key = keys[i];var value = Object.getOwnPropertyDescriptor(defaults, key);if (value && value.configurable && obj[key] === undefined) {
Object.defineProperty(obj, key, value);
}
}return obj;
}
function _possibleConstructorReturn$6(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && (typeof call === "object" || typeof call === "function") ? call : self;
}
function _inherits$6(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults$6(subClass, superClass);
}
function _classCallCheck$7(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
APPEND_OPCODES.add(26 /* DynamicContent */, function (vm, _ref) {
var append = _ref.op1;
var opcode = vm.constants.getOther(append);
opcode.evaluate(vm);
});
function isEmpty(value) {
return value === null || value === undefined || typeof value.toString !== 'function';
}
function normalizeTextValue(value) {
if (isEmpty(value)) {
return '';
}
return String(value);
}
function normalizeTrustedValue(value) {
if (isEmpty(value)) {
return '';
}
if (isString(value)) {
return value;
}
if (isSafeString(value)) {
return value.toHTML();
}
if (isNode(value)) {
return value;
}
return String(value);
}
function normalizeValue(value) {
if (isEmpty(value)) {
return '';
}
if (isString(value)) {
return value;
}
if (isSafeString(value) || isNode(value)) {
return value;
}
return String(value);
}
var AppendDynamicOpcode = function () {
function AppendDynamicOpcode() {
_classCallCheck$7(this, AppendDynamicOpcode);
}
AppendDynamicOpcode.prototype.evaluate = function evaluate(vm) {
var reference = vm.stack.pop();
var normalized = this.normalize(reference);
var value = void 0;
var cache = void 0;
if ((0, _reference2.isConst)(reference)) {
value = normalized.value();
} else {
cache = new _reference2.ReferenceCache(normalized);
value = cache.peek();
}
var stack = vm.elements();
var upsert = this.insert(vm.env.getAppendOperations(), stack, value);
var bounds$$1 = new Fragment(upsert.bounds);
stack.newBounds(bounds$$1);
if (cache /* i.e. !isConst(reference) */) {
vm.updateWith(this.updateWith(vm, reference, cache, bounds$$1, upsert));
}
};
return AppendDynamicOpcode;
}();
var IsComponentDefinitionReference = function (_ConditionalReference) {
_inherits$6(IsComponentDefinitionReference, _ConditionalReference);
function IsComponentDefinitionReference() {
_classCallCheck$7(this, IsComponentDefinitionReference);
return _possibleConstructorReturn$6(this, _ConditionalReference.apply(this, arguments));
}
IsComponentDefinitionReference.create = function create(inner) {
return new IsComponentDefinitionReference(inner);
};
IsComponentDefinitionReference.prototype.toBool = function toBool(value) {
return isComponentDefinition(value);
};
return IsComponentDefinitionReference;
}(ConditionalReference);
var UpdateOpcode = function (_UpdatingOpcode) {
_inherits$6(UpdateOpcode, _UpdatingOpcode);
function UpdateOpcode(cache, bounds$$1, upsert) {
_classCallCheck$7(this, UpdateOpcode);
var _this2 = _possibleConstructorReturn$6(this, _UpdatingOpcode.call(this));
_this2.cache = cache;
_this2.bounds = bounds$$1;
_this2.upsert = upsert;
_this2.tag = cache.tag;
return _this2;
}
UpdateOpcode.prototype.evaluate = function evaluate(vm) {
var value = this.cache.revalidate();
if ((0, _reference2.isModified)(value)) {
var bounds$$1 = this.bounds,
upsert = this.upsert;
var dom = vm.dom;
if (!this.upsert.update(dom, value)) {
var cursor = new Cursor(bounds$$1.parentElement(), clear(bounds$$1));
upsert = this.upsert = this.insert(vm.env.getAppendOperations(), cursor, value);
}
bounds$$1.update(upsert.bounds);
}
};
UpdateOpcode.prototype.toJSON = function toJSON() {
var guid = this._guid,
type = this.type,
cache = this.cache;
return {
details: { lastValue: JSON.stringify(cache.peek()) },
guid: guid,
type: type
};
};
return UpdateOpcode;
}(UpdatingOpcode);
var OptimizedCautiousAppendOpcode = function (_AppendDynamicOpcode) {
_inherits$6(OptimizedCautiousAppendOpcode, _AppendDynamicOpcode);
function OptimizedCautiousAppendOpcode() {
_classCallCheck$7(this, OptimizedCautiousAppendOpcode);
var _this3 = _possibleConstructorReturn$6(this, _AppendDynamicOpcode.apply(this, arguments));
_this3.type = 'optimized-cautious-append';
return _this3;
}
OptimizedCautiousAppendOpcode.prototype.normalize = function normalize(reference) {
return (0, _reference2.map)(reference, normalizeValue);
};
OptimizedCautiousAppendOpcode.prototype.insert = function insert(dom, cursor, value) {
return cautiousInsert(dom, cursor, value);
};
OptimizedCautiousAppendOpcode.prototype.updateWith = function updateWith(_vm, _reference, cache, bounds$$1, upsert) {
return new OptimizedCautiousUpdateOpcode(cache, bounds$$1, upsert);
};
return OptimizedCautiousAppendOpcode;
}(AppendDynamicOpcode);
var OptimizedCautiousUpdateOpcode = function (_UpdateOpcode) {
_inherits$6(OptimizedCautiousUpdateOpcode, _UpdateOpcode);
function OptimizedCautiousUpdateOpcode() {
_classCallCheck$7(this, OptimizedCautiousUpdateOpcode);
var _this4 = _possibleConstructorReturn$6(this, _UpdateOpcode.apply(this, arguments));
_this4.type = 'optimized-cautious-update';
return _this4;
}
OptimizedCautiousUpdateOpcode.prototype.insert = function insert(dom, cursor, value) {
return cautiousInsert(dom, cursor, value);
};
return OptimizedCautiousUpdateOpcode;
}(UpdateOpcode);
var OptimizedTrustingAppendOpcode = function (_AppendDynamicOpcode2) {
_inherits$6(OptimizedTrustingAppendOpcode, _AppendDynamicOpcode2);
function OptimizedTrustingAppendOpcode() {
_classCallCheck$7(this, OptimizedTrustingAppendOpcode);
var _this5 = _possibleConstructorReturn$6(this, _AppendDynamicOpcode2.apply(this, arguments));
_this5.type = 'optimized-trusting-append';
return _this5;
}
OptimizedTrustingAppendOpcode.prototype.normalize = function normalize(reference) {
return (0, _reference2.map)(reference, normalizeTrustedValue);
};
OptimizedTrustingAppendOpcode.prototype.insert = function insert(dom, cursor, value) {
return trustingInsert(dom, cursor, value);
};
OptimizedTrustingAppendOpcode.prototype.updateWith = function updateWith(_vm, _reference, cache, bounds$$1, upsert) {
return new OptimizedTrustingUpdateOpcode(cache, bounds$$1, upsert);
};
return OptimizedTrustingAppendOpcode;
}(AppendDynamicOpcode);
var OptimizedTrustingUpdateOpcode = function (_UpdateOpcode2) {
_inherits$6(OptimizedTrustingUpdateOpcode, _UpdateOpcode2);
function OptimizedTrustingUpdateOpcode() {
_classCallCheck$7(this, OptimizedTrustingUpdateOpcode);
var _this6 = _possibleConstructorReturn$6(this, _UpdateOpcode2.apply(this, arguments));
_this6.type = 'optimized-trusting-update';
return _this6;
}
OptimizedTrustingUpdateOpcode.prototype.insert = function insert(dom, cursor, value) {
return trustingInsert(dom, cursor, value);
};
return OptimizedTrustingUpdateOpcode;
}(UpdateOpcode);
function _classCallCheck$12(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
/* tslint:disable */
function debugCallback(context, get) {
console.info('Use `context`, and `get(<path>)` to debug this template.');
// for example...
context === get('this');
debugger;
}
/* tslint:enable */
var callback = debugCallback;
// For testing purposes
function setDebuggerCallback(cb) {
callback = cb;
}
function resetDebuggerCallback() {
callback = debugCallback;
}
var ScopeInspector = function () {
function ScopeInspector(scope, symbols, evalInfo) {
_classCallCheck$12(this, ScopeInspector);
this.scope = scope;
this.locals = (0, _util.dict)();
for (var i = 0; i < evalInfo.length; i++) {
var slot = evalInfo[i];
var name = symbols[slot - 1];
var ref = scope.getSymbol(slot);
this.locals[name] = ref;
}
}
ScopeInspector.prototype.get = function get(path) {
var scope = this.scope,
locals = this.locals;
var parts = path.split('.');
var _path$split = path.split('.'),
head = _path$split[0],
tail = _path$split.slice(1);
var evalScope = scope.getEvalScope();
var ref = void 0;
if (head === 'this') {
ref = scope.getSelf();
} else if (locals[head]) {
ref = locals[head];
} else if (head.indexOf('@') === 0 && evalScope[head]) {
ref = evalScope[head];
} else {
ref = this.scope.getSelf();
tail = parts;
}
return tail.reduce(function (r, part) {
return r.get(part);
}, ref);
};
return ScopeInspector;
}();
APPEND_OPCODES.add(71 /* Debugger */, function (vm, _ref) {
var _symbols = _ref.op1,
_evalInfo = _ref.op2;
var symbols = vm.constants.getOther(_symbols);
var evalInfo = vm.constants.getArray(_evalInfo);
var inspector = new ScopeInspector(vm.scope(), symbols, evalInfo);
callback(vm.getSelf().value(), function (path) {
return inspector.get(path).value();
});
});
APPEND_OPCODES.add(69 /* GetPartialTemplate */, function (vm) {
var stack = vm.stack;
var definition = stack.pop();
stack.push(definition.value().template.asPartial());
});
function _classCallCheck$13(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var IterablePresenceReference = function () {
function IterablePresenceReference(artifacts) {
_classCallCheck$13(this, IterablePresenceReference);
this.tag = artifacts.tag;
this.artifacts = artifacts;
}
IterablePresenceReference.prototype.value = function value() {
return !this.artifacts.isEmpty();
};
return IterablePresenceReference;
}();
APPEND_OPCODES.add(54 /* PutIterator */, function (vm) {
var stack = vm.stack;
var listRef = stack.pop();
var key = stack.pop();
var iterable = vm.env.iterableFor(listRef, key.value());
var iterator = new _reference2.ReferenceIterator(iterable);
stack.push(iterator);
stack.push(new IterablePresenceReference(iterator.artifacts));
});
APPEND_OPCODES.add(52 /* EnterList */, function (vm, _ref) {
var relativeStart = _ref.op1;
vm.enterList(relativeStart);
});
APPEND_OPCODES.add(53 /* ExitList */, function (vm) {
return vm.exitList();
});
APPEND_OPCODES.add(55 /* Iterate */, function (vm, _ref2) {
var breaks = _ref2.op1;
var stack = vm.stack;
var item = stack.peek().next();
if (item) {
var tryOpcode = vm.iterate(item.memo, item.value);
vm.enterItem(item.key, tryOpcode);
} else {
vm.goto(breaks);
}
});
var Ops$2;
(function (Ops$$1) {
Ops$$1[Ops$$1["OpenComponentElement"] = 0] = "OpenComponentElement";
Ops$$1[Ops$$1["DidCreateElement"] = 1] = "DidCreateElement";
Ops$$1[Ops$$1["DidRenderLayout"] = 2] = "DidRenderLayout";
Ops$$1[Ops$$1["FunctionExpression"] = 3] = "FunctionExpression";
})(Ops$2 || (Ops$2 = {}));
function _classCallCheck$17(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var CompiledStaticTemplate = function CompiledStaticTemplate(handle) {
_classCallCheck$17(this, CompiledStaticTemplate);
this.handle = handle;
};
var CompiledDynamicTemplate = function CompiledDynamicTemplate(handle, symbolTable) {
_classCallCheck$17(this, CompiledDynamicTemplate);
this.handle = handle;
this.symbolTable = symbolTable;
};
var _createClass$2 = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if ("value" in descriptor) descriptor.writable = true;Object.defineProperty(target, descriptor.key, descriptor);
}
}return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);if (staticProps) defineProperties(Constructor, staticProps);return Constructor;
};
}();
function _classCallCheck$20(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function compileLayout(compilable, env) {
var builder = new ComponentLayoutBuilder(env);
compilable.compile(builder);
return builder.compile();
}
var ComponentLayoutBuilder = function () {
function ComponentLayoutBuilder(env) {
_classCallCheck$20(this, ComponentLayoutBuilder);
this.env = env;
}
ComponentLayoutBuilder.prototype.wrapLayout = function wrapLayout(layout) {
this.inner = new WrappedBuilder(this.env, layout);
};
ComponentLayoutBuilder.prototype.fromLayout = function fromLayout(componentName, layout) {
this.inner = new UnwrappedBuilder(this.env, componentName, layout);
};
ComponentLayoutBuilder.prototype.compile = function compile() {
return this.inner.compile();
};
_createClass$2(ComponentLayoutBuilder, [{
key: 'tag',
get: function () {
return this.inner.tag;
}
}, {
key: 'attrs',
get: function () {
return this.inner.attrs;
}
}]);
return ComponentLayoutBuilder;
}();
var WrappedBuilder = function () {
function WrappedBuilder(env, layout) {
_classCallCheck$20(this, WrappedBuilder);
this.env = env;
this.layout = layout;
this.tag = new ComponentTagBuilder();
this.attrs = new ComponentAttrsBuilder();
}
WrappedBuilder.prototype.compile = function compile() {
//========DYNAMIC
// PutValue(TagExpr)
// Test
// JumpUnless(BODY)
// OpenDynamicPrimitiveElement
// DidCreateElement
// ...attr statements...
// FlushElement
// BODY: Noop
// ...body statements...
// PutValue(TagExpr)
// Test
// JumpUnless(END)
// CloseElement
// END: Noop
// DidRenderLayout
// Exit
//
//========STATIC
// OpenPrimitiveElementOpcode
// DidCreateElement
// ...attr statements...
// FlushElement
// ...body statements...
// CloseElement
// DidRenderLayout
// Exit
var env = this.env,
layout = this.layout;
var meta = { templateMeta: layout.meta, symbols: layout.symbols, asPartial: false };
var dynamicTag = this.tag.getDynamic();
var staticTag = this.tag.getStatic();
var b = builder(env, meta);
b.startLabels();
if (dynamicTag) {
b.fetch(Register.s1);
expr(dynamicTag, b);
b.dup();
b.load(Register.s1);
b.test('simple');
b.jumpUnless('BODY');
b.fetch(Register.s1);
b.pushComponentOperations();
b.openDynamicElement();
} else if (staticTag) {
b.pushComponentOperations();
b.openElementWithOperations(staticTag);
}
if (dynamicTag || staticTag) {
b.didCreateElement(Register.s0);
var attrs = this.attrs.buffer;
for (var i = 0; i < attrs.length; i++) {
compileStatement(attrs[i], b);
}
b.flushElement();
}
b.label('BODY');
b.invokeStatic(layout.asBlock());
if (dynamicTag) {
b.fetch(Register.s1);
b.test('simple');
b.jumpUnless('END');
b.closeElement();
} else if (staticTag) {
b.closeElement();
}
b.label('END');
b.didRenderLayout(Register.s0);
if (dynamicTag) {
b.load(Register.s1);
}
b.stopLabels();
var start = b.start;
var end = b.finalize();
return new CompiledDynamicTemplate(start, {
meta: meta,
hasEval: layout.hasEval,
symbols: layout.symbols.concat([ATTRS_BLOCK])
});
};
return WrappedBuilder;
}();
var UnwrappedBuilder = function () {
function UnwrappedBuilder(env, componentName, layout) {
_classCallCheck$20(this, UnwrappedBuilder);
this.env = env;
this.componentName = componentName;
this.layout = layout;
this.attrs = new ComponentAttrsBuilder();
}
UnwrappedBuilder.prototype.compile = function compile() {
var env = this.env,
layout = this.layout;
return layout.asLayout(this.componentName, this.attrs.buffer).compileDynamic(env);
};
_createClass$2(UnwrappedBuilder, [{
key: 'tag',
get: function () {
throw new Error('BUG: Cannot call `tag` on an UnwrappedBuilder');
}
}]);
return UnwrappedBuilder;
}();
var ComponentTagBuilder = function () {
function ComponentTagBuilder() {
_classCallCheck$20(this, ComponentTagBuilder);
this.isDynamic = null;
this.isStatic = null;
this.staticTagName = null;
this.dynamicTagName = null;
}
ComponentTagBuilder.prototype.getDynamic = function getDynamic() {
if (this.isDynamic) {
return this.dynamicTagName;
}
};
ComponentTagBuilder.prototype.getStatic = function getStatic() {
if (this.isStatic) {
return this.staticTagName;
}
};
ComponentTagBuilder.prototype.static = function _static(tagName) {
this.isStatic = true;
this.staticTagName = tagName;
};
ComponentTagBuilder.prototype.dynamic = function dynamic(tagName) {
this.isDynamic = true;
this.dynamicTagName = [_wireFormat.Ops.ClientSideExpression, Ops$2.FunctionExpression, tagName];
};
return ComponentTagBuilder;
}();
var ComponentAttrsBuilder = function () {
function ComponentAttrsBuilder() {
_classCallCheck$20(this, ComponentAttrsBuilder);
this.buffer = [];
}
ComponentAttrsBuilder.prototype.static = function _static(name, value) {
this.buffer.push([_wireFormat.Ops.StaticAttr, name, value, null]);
};
ComponentAttrsBuilder.prototype.dynamic = function dynamic(name, value) {
this.buffer.push([_wireFormat.Ops.DynamicAttr, name, [_wireFormat.Ops.ClientSideExpression, Ops$2.FunctionExpression, value], null]);
};
return ComponentAttrsBuilder;
}();
var ComponentBuilder = function () {
function ComponentBuilder(builder) {
_classCallCheck$20(this, ComponentBuilder);
this.builder = builder;
this.env = builder.env;
}
ComponentBuilder.prototype.static = function _static(definition, args) {
var params = args[0],
hash = args[1],
_default = args[2],
inverse = args[3];
var builder = this.builder;
builder.pushComponentManager(definition);
builder.invokeComponent(null, params, hash, _default, inverse);
};
ComponentBuilder.prototype.dynamic = function dynamic(definitionArgs, getDefinition, args) {
var params = args[0],
hash = args[1],
block = args[2],
inverse = args[3];
var builder = this.builder;
if (!definitionArgs || definitionArgs.length === 0) {
throw new Error("Dynamic syntax without an argument");
}
var meta = this.builder.meta.templateMeta;
function helper(vm, a) {
return getDefinition(vm, a, meta);
}
builder.startLabels();
builder.pushFrame();
builder.returnTo('END');
builder.compileArgs(definitionArgs[0], definitionArgs[1], true);
builder.helper(helper);
builder.dup();
builder.test('simple');
builder.enter(2);
builder.jumpUnless('ELSE');
builder.pushDynamicComponentManager();
builder.invokeComponent(null, params, hash, block, inverse);
builder.label('ELSE');
builder.exit();
builder.return();
builder.label('END');
builder.popFrame();
builder.stopLabels();
};
return ComponentBuilder;
}();
function builder(env, meta) {
return new OpcodeBuilder(env, meta);
}
function _classCallCheck$21(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var RawInlineBlock = function () {
function RawInlineBlock(meta, statements, parameters) {
_classCallCheck$21(this, RawInlineBlock);
this.meta = meta;
this.statements = statements;
this.parameters = parameters;
}
RawInlineBlock.prototype.scan = function scan() {
return new CompilableTemplate(this.statements, { parameters: this.parameters, meta: this.meta });
};
return RawInlineBlock;
}();
var _createClass$1 = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if ("value" in descriptor) descriptor.writable = true;Object.defineProperty(target, descriptor.key, descriptor);
}
}return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);if (staticProps) defineProperties(Constructor, staticProps);return Constructor;
};
}();
function _defaults$9(obj, defaults) {
var keys = Object.getOwnPropertyNames(defaults);for (var i = 0; i < keys.length; i++) {
var key = keys[i];var value = Object.getOwnPropertyDescriptor(defaults, key);if (value && value.configurable && obj[key] === undefined) {
Object.defineProperty(obj, key, value);
}
}return obj;
}
function _possibleConstructorReturn$9(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && (typeof call === "object" || typeof call === "function") ? call : self;
}
function _inherits$9(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults$9(subClass, superClass);
}
function _classCallCheck$19(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var Labels = function () {
function Labels() {
_classCallCheck$19(this, Labels);
this.labels = (0, _util.dict)();
this.targets = [];
}
Labels.prototype.label = function label(name, index) {
this.labels[name] = index;
};
Labels.prototype.target = function target(at, Target, _target) {
this.targets.push({ at: at, Target: Target, target: _target });
};
Labels.prototype.patch = function patch(program) {
var targets = this.targets,
labels = this.labels;
for (var i = 0; i < targets.length; i++) {
var _targets$i = targets[i],
at = _targets$i.at,
target = _targets$i.target;
var goto = labels[target] - at;
program.heap.setbyaddr(at + 1, goto);
}
};
return Labels;
}();
var BasicOpcodeBuilder = function () {
function BasicOpcodeBuilder(env, meta, program) {
_classCallCheck$19(this, BasicOpcodeBuilder);
this.env = env;
this.meta = meta;
this.program = program;
this.labelsStack = new _util.Stack();
this.constants = program.constants;
this.heap = program.heap;
this.start = this.heap.malloc();
}
BasicOpcodeBuilder.prototype.upvars = function upvars(count) {
return (0, _util.fillNulls)(count);
};
BasicOpcodeBuilder.prototype.reserve = function reserve(name) {
this.push(name, 0, 0, 0);
};
BasicOpcodeBuilder.prototype.push = function push(name) {
var op1 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
var op2 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
var op3 = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
this.heap.push(name);
this.heap.push(op1);
this.heap.push(op2);
this.heap.push(op3);
};
BasicOpcodeBuilder.prototype.finalize = function finalize() {
this.push(22 /* Return */);
this.heap.finishMalloc(this.start);
return this.start;
};
// args
BasicOpcodeBuilder.prototype.pushArgs = function pushArgs(synthetic) {
this.push(58 /* PushArgs */, synthetic === true ? 1 : 0);
};
// helpers
BasicOpcodeBuilder.prototype.startLabels = function startLabels() {
this.labelsStack.push(new Labels());
};
BasicOpcodeBuilder.prototype.stopLabels = function stopLabels() {
var label = this.labelsStack.pop();
label.patch(this.program);
};
// components
BasicOpcodeBuilder.prototype.pushComponentManager = function pushComponentManager(definition) {
this.push(56 /* PushComponentManager */, this.other(definition));
};
BasicOpcodeBuilder.prototype.pushDynamicComponentManager = function pushDynamicComponentManager() {
this.push(57 /* PushDynamicComponentManager */);
};
BasicOpcodeBuilder.prototype.prepareArgs = function prepareArgs(state) {
this.push(59 /* PrepareArgs */, state);
};
BasicOpcodeBuilder.prototype.createComponent = function createComponent(state, hasDefault, hasInverse) {
var flag = (hasDefault === true ? 1 : 0) | (hasInverse === true ? 1 : 0) << 1;
this.push(60 /* CreateComponent */, flag, state);
};
BasicOpcodeBuilder.prototype.registerComponentDestructor = function registerComponentDestructor(state) {
this.push(61 /* RegisterComponentDestructor */, state);
};
BasicOpcodeBuilder.prototype.beginComponentTransaction = function beginComponentTransaction() {
this.push(65 /* BeginComponentTransaction */);
};
BasicOpcodeBuilder.prototype.commitComponentTransaction = function commitComponentTransaction() {
this.push(66 /* CommitComponentTransaction */);
};
BasicOpcodeBuilder.prototype.pushComponentOperations = function pushComponentOperations() {
this.push(62 /* PushComponentOperations */);
};
BasicOpcodeBuilder.prototype.getComponentSelf = function getComponentSelf(state) {
this.push(63 /* GetComponentSelf */, state);
};
BasicOpcodeBuilder.prototype.getComponentLayout = function getComponentLayout(state) {
this.push(64 /* GetComponentLayout */, state);
};
BasicOpcodeBuilder.prototype.didCreateElement = function didCreateElement(state) {
this.push(67 /* DidCreateElement */, state);
};
BasicOpcodeBuilder.prototype.didRenderLayout = function didRenderLayout(state) {
this.push(68 /* DidRenderLayout */, state);
};
// partial
BasicOpcodeBuilder.prototype.getPartialTemplate = function getPartialTemplate() {
this.push(69 /* GetPartialTemplate */);
};
BasicOpcodeBuilder.prototype.resolveMaybeLocal = function resolveMaybeLocal(name) {
this.push(70 /* ResolveMaybeLocal */, this.string(name));
};
// debugger
BasicOpcodeBuilder.prototype.debugger = function _debugger(symbols, evalInfo) {
this.push(71 /* Debugger */, this.constants.other(symbols), this.constants.array(evalInfo));
};
// content
BasicOpcodeBuilder.prototype.dynamicContent = function dynamicContent(Opcode) {
this.push(26 /* DynamicContent */, this.other(Opcode));
};
BasicOpcodeBuilder.prototype.cautiousAppend = function cautiousAppend() {
this.dynamicContent(new OptimizedCautiousAppendOpcode());
};
BasicOpcodeBuilder.prototype.trustingAppend = function trustingAppend() {
this.dynamicContent(new OptimizedTrustingAppendOpcode());
};
// dom
BasicOpcodeBuilder.prototype.text = function text(_text) {
this.push(24 /* Text */, this.constants.string(_text));
};
BasicOpcodeBuilder.prototype.openPrimitiveElement = function openPrimitiveElement(tag) {
this.push(27 /* OpenElement */, this.constants.string(tag));
};
BasicOpcodeBuilder.prototype.openElementWithOperations = function openElementWithOperations(tag) {
this.push(28 /* OpenElementWithOperations */, this.constants.string(tag));
};
BasicOpcodeBuilder.prototype.openDynamicElement = function openDynamicElement() {
this.push(29 /* OpenDynamicElement */);
};
BasicOpcodeBuilder.prototype.flushElement = function flushElement() {
this.push(33 /* FlushElement */);
};
BasicOpcodeBuilder.prototype.closeElement = function closeElement() {
this.push(34 /* CloseElement */);
};
BasicOpcodeBuilder.prototype.staticAttr = function staticAttr(_name, _namespace, _value) {
var name = this.constants.string(_name);
var namespace = _namespace ? this.constants.string(_namespace) : 0;
var value = this.constants.string(_value);
this.push(30 /* StaticAttr */, name, value, namespace);
};
BasicOpcodeBuilder.prototype.dynamicAttrNS = function dynamicAttrNS(_name, _namespace, trusting) {
var name = this.constants.string(_name);
var namespace = this.constants.string(_namespace);
this.push(32 /* DynamicAttrNS */, name, namespace, trusting === true ? 1 : 0);
};
BasicOpcodeBuilder.prototype.dynamicAttr = function dynamicAttr(_name, trusting) {
var name = this.constants.string(_name);
this.push(31 /* DynamicAttr */, name, trusting === true ? 1 : 0);
};
BasicOpcodeBuilder.prototype.comment = function comment(_comment) {
var comment = this.constants.string(_comment);
this.push(25 /* Comment */, comment);
};
BasicOpcodeBuilder.prototype.modifier = function modifier(_definition) {
this.push(35 /* Modifier */, this.other(_definition));
};
// lists
BasicOpcodeBuilder.prototype.putIterator = function putIterator() {
this.push(54 /* PutIterator */);
};
BasicOpcodeBuilder.prototype.enterList = function enterList(start) {
this.reserve(52 /* EnterList */);
this.labels.target(this.pos, 52 /* EnterList */, start);
};
BasicOpcodeBuilder.prototype.exitList = function exitList() {
this.push(53 /* ExitList */);
};
BasicOpcodeBuilder.prototype.iterate = function iterate(breaks) {
this.reserve(55 /* Iterate */);
this.labels.target(this.pos, 55 /* Iterate */, breaks);
};
// expressions
BasicOpcodeBuilder.prototype.setVariable = function setVariable(symbol) {
this.push(4 /* SetVariable */, symbol);
};
BasicOpcodeBuilder.prototype.getVariable = function getVariable(symbol) {
this.push(5 /* GetVariable */, symbol);
};
BasicOpcodeBuilder.prototype.getProperty = function getProperty(key) {
this.push(6 /* GetProperty */, this.string(key));
};
BasicOpcodeBuilder.prototype.getBlock = function getBlock(symbol) {
this.push(8 /* GetBlock */, symbol);
};
BasicOpcodeBuilder.prototype.hasBlock = function hasBlock(symbol) {
this.push(9 /* HasBlock */, symbol);
};
BasicOpcodeBuilder.prototype.hasBlockParams = function hasBlockParams(symbol) {
this.push(10 /* HasBlockParams */, symbol);
};
BasicOpcodeBuilder.prototype.concat = function concat(size) {
this.push(11 /* Concat */, size);
};
BasicOpcodeBuilder.prototype.function = function _function(f) {
this.push(2 /* Function */, this.func(f));
};
BasicOpcodeBuilder.prototype.load = function load(register) {
this.push(17 /* Load */, register);
};
BasicOpcodeBuilder.prototype.fetch = function fetch(register) {
this.push(18 /* Fetch */, register);
};
BasicOpcodeBuilder.prototype.dup = function dup() {
var register = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : Register.sp;
var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
return this.push(15 /* Dup */, register, offset);
};
BasicOpcodeBuilder.prototype.pop = function pop() {
var count = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1;
return this.push(16 /* Pop */, count);
};
// vm
BasicOpcodeBuilder.prototype.pushRemoteElement = function pushRemoteElement() {
this.push(36 /* PushRemoteElement */);
};
BasicOpcodeBuilder.prototype.popRemoteElement = function popRemoteElement() {
this.push(37 /* PopRemoteElement */);
};
BasicOpcodeBuilder.prototype.label = function label(name) {
this.labels.label(name, this.nextPos);
};
BasicOpcodeBuilder.prototype.pushRootScope = function pushRootScope(symbols, bindCallerScope) {
this.push(19 /* RootScope */, symbols, bindCallerScope ? 1 : 0);
};
BasicOpcodeBuilder.prototype.pushChildScope = function pushChildScope() {
this.push(20 /* ChildScope */);
};
BasicOpcodeBuilder.prototype.popScope = function popScope() {
this.push(21 /* PopScope */);
};
BasicOpcodeBuilder.prototype.returnTo = function returnTo(label) {
this.reserve(23 /* ReturnTo */);
this.labels.target(this.pos, 23 /* ReturnTo */, label);
};
BasicOpcodeBuilder.prototype.pushDynamicScope = function pushDynamicScope() {
this.push(39 /* PushDynamicScope */);
};
BasicOpcodeBuilder.prototype.popDynamicScope = function popDynamicScope() {
this.push(40 /* PopDynamicScope */);
};
BasicOpcodeBuilder.prototype.pushImmediate = function pushImmediate(value) {
this.push(13 /* Constant */, this.other(value));
};
BasicOpcodeBuilder.prototype.primitive = function primitive(_primitive) {
var flag = 0;
var primitive = void 0;
switch (typeof _primitive) {
case 'number':
if (_primitive % 1 === 0 && _primitive > 0) {
primitive = _primitive;
} else {
primitive = this.float(_primitive);
flag = 1;
}
break;
case 'string':
primitive = this.string(_primitive);
flag = 2;
break;
case 'boolean':
primitive = _primitive | 0;
flag = 3;
break;
case 'object':
// assume null
primitive = 2;
flag = 3;
break;
case 'undefined':
primitive = 3;
flag = 3;
break;
default:
throw new Error('Invalid primitive passed to pushPrimitive');
}
this.push(14 /* PrimitiveReference */, flag << 30 | primitive);
};
BasicOpcodeBuilder.prototype.helper = function helper(func) {
this.push(1 /* Helper */, this.func(func));
};
BasicOpcodeBuilder.prototype.pushBlock = function pushBlock(block) {
this.push(7 /* PushBlock */, this.block(block));
};
BasicOpcodeBuilder.prototype.bindDynamicScope = function bindDynamicScope(_names) {
this.push(38 /* BindDynamicScope */, this.names(_names));
};
BasicOpcodeBuilder.prototype.enter = function enter(args) {
this.push(49 /* Enter */, args);
};
BasicOpcodeBuilder.prototype.exit = function exit() {
this.push(50 /* Exit */);
};
BasicOpcodeBuilder.prototype.return = function _return() {
this.push(22 /* Return */);
};
BasicOpcodeBuilder.prototype.pushFrame = function pushFrame() {
this.push(47 /* PushFrame */);
};
BasicOpcodeBuilder.prototype.popFrame = function popFrame() {
this.push(48 /* PopFrame */);
};
BasicOpcodeBuilder.prototype.compileDynamicBlock = function compileDynamicBlock() {
this.push(41 /* CompileDynamicBlock */);
};
BasicOpcodeBuilder.prototype.invokeDynamic = function invokeDynamic(invoker) {
this.push(43 /* InvokeDynamic */, this.other(invoker));
};
BasicOpcodeBuilder.prototype.invokeStatic = function invokeStatic(block) {
var callerCount = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
var parameters = block.symbolTable.parameters;
var calleeCount = parameters.length;
var count = Math.min(callerCount, calleeCount);
this.pushFrame();
if (count) {
this.pushChildScope();
for (var i = 0; i < count; i++) {
this.dup(Register.fp, callerCount - i);
this.setVariable(parameters[i]);
}
}
var _block = this.constants.block(block);
this.push(42 /* InvokeStatic */, _block);
if (count) {
this.popScope();
}
this.popFrame();
};
BasicOpcodeBuilder.prototype.test = function test(testFunc) {
var _func = void 0;
if (testFunc === 'const') {
_func = ConstTest;
} else if (testFunc === 'simple') {
_func = SimpleTest;
} else if (testFunc === 'environment') {
_func = EnvironmentTest;
} else if (typeof testFunc === 'function') {
_func = testFunc;
} else {
throw new Error('unreachable');
}
var func = this.constants.function(_func);
this.push(51 /* Test */, func);
};
BasicOpcodeBuilder.prototype.jump = function jump(target) {
this.reserve(44 /* Jump */);
this.labels.target(this.pos, 44 /* Jump */, target);
};
BasicOpcodeBuilder.prototype.jumpIf = function jumpIf(target) {
this.reserve(45 /* JumpIf */);
this.labels.target(this.pos, 45 /* JumpIf */, target);
};
BasicOpcodeBuilder.prototype.jumpUnless = function jumpUnless(target) {
this.reserve(46 /* JumpUnless */);
this.labels.target(this.pos, 46 /* JumpUnless */, target);
};
BasicOpcodeBuilder.prototype.string = function string(_string) {
return this.constants.string(_string);
};
BasicOpcodeBuilder.prototype.float = function float(num) {
return this.constants.float(num);
};
BasicOpcodeBuilder.prototype.names = function names(_names) {
var names = [];
for (var i = 0; i < _names.length; i++) {
var n = _names[i];
names[i] = this.constants.string(n);
}
return this.constants.array(names);
};
BasicOpcodeBuilder.prototype.symbols = function symbols(_symbols) {
return this.constants.array(_symbols);
};
BasicOpcodeBuilder.prototype.other = function other(value) {
return this.constants.other(value);
};
BasicOpcodeBuilder.prototype.block = function block(_block2) {
return _block2 ? this.constants.block(_block2) : 0;
};
BasicOpcodeBuilder.prototype.func = function func(_func2) {
return this.constants.function(_func2);
};
_createClass$1(BasicOpcodeBuilder, [{
key: 'pos',
get: function () {
return (0, _util.typePos)(this.heap.size());
}
}, {
key: 'nextPos',
get: function () {
return this.heap.size();
}
}, {
key: 'labels',
get: function () {
return this.labelsStack.current;
}
}]);
return BasicOpcodeBuilder;
}();
function isCompilableExpression(expr$$1) {
return typeof expr$$1 === 'object' && expr$$1 !== null && typeof expr$$1.compile === 'function';
}
var OpcodeBuilder = function (_BasicOpcodeBuilder) {
_inherits$9(OpcodeBuilder, _BasicOpcodeBuilder);
function OpcodeBuilder(env, meta) {
var program = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : env.program;
_classCallCheck$19(this, OpcodeBuilder);
var _this = _possibleConstructorReturn$9(this, _BasicOpcodeBuilder.call(this, env, meta, program));
_this.component = new ComponentBuilder(_this);
return _this;
}
OpcodeBuilder.prototype.compileArgs = function compileArgs(params, hash, synthetic) {
var positional = 0;
if (params) {
for (var i = 0; i < params.length; i++) {
expr(params[i], this);
}
positional = params.length;
}
this.pushImmediate(positional);
var names = _util.EMPTY_ARRAY;
if (hash) {
names = hash[0];
var val = hash[1];
for (var _i = 0; _i < val.length; _i++) {
expr(val[_i], this);
}
}
this.pushImmediate(names);
this.pushArgs(synthetic);
};
OpcodeBuilder.prototype.compile = function compile(expr$$1) {
if (isCompilableExpression(expr$$1)) {
return expr$$1.compile(this);
} else {
return expr$$1;
}
};
OpcodeBuilder.prototype.guardedAppend = function guardedAppend(expression, trusting) {
this.startLabels();
this.pushFrame();
this.returnTo('END');
expr(expression, this);
this.dup();
this.test(function (reference) {
return IsComponentDefinitionReference.create(reference);
});
this.enter(2);
this.jumpUnless('ELSE');
this.pushDynamicComponentManager();
this.invokeComponent(null, null, null, null, null);
this.exit();
this.return();
this.label('ELSE');
if (trusting) {
this.trustingAppend();
} else {
this.cautiousAppend();
}
this.exit();
this.return();
this.label('END');
this.popFrame();
this.stopLabels();
};
OpcodeBuilder.prototype.invokeComponent = function invokeComponent(attrs, params, hash, block) {
var inverse = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : null;
this.fetch(Register.s0);
this.dup(Register.sp, 1);
this.load(Register.s0);
this.pushBlock(block);
this.pushBlock(inverse);
this.compileArgs(params, hash, false);
this.prepareArgs(Register.s0);
this.beginComponentTransaction();
this.pushDynamicScope();
this.createComponent(Register.s0, block !== null, inverse !== null);
this.registerComponentDestructor(Register.s0);
this.getComponentSelf(Register.s0);
this.getComponentLayout(Register.s0);
this.invokeDynamic(new InvokeDynamicLayout(attrs && attrs.scan()));
this.popFrame();
this.popScope();
this.popDynamicScope();
this.commitComponentTransaction();
this.load(Register.s0);
};
OpcodeBuilder.prototype.template = function template(block) {
if (!block) return null;
return new RawInlineBlock(this.meta, block.statements, block.parameters);
};
return OpcodeBuilder;
}(BasicOpcodeBuilder);
function _classCallCheck$18(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var Ops$3 = _wireFormat.Ops;
var ATTRS_BLOCK = '&attrs';
var Compilers = function () {
function Compilers() {
var offset = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
_classCallCheck$18(this, Compilers);
this.offset = offset;
this.names = (0, _util.dict)();
this.funcs = [];
}
Compilers.prototype.add = function add(name, func) {
this.funcs.push(func);
this.names[name] = this.funcs.length - 1;
};
Compilers.prototype.compile = function compile(sexp, builder) {
var name = sexp[this.offset];
var index = this.names[name];
var func = this.funcs[index];
(0, _util.assert)(!!func, 'expected an implementation for ' + (this.offset === 0 ? Ops$3[sexp[0]] : Ops$2[sexp[1]]));
func(sexp, builder);
};
return Compilers;
}();
var STATEMENTS = new Compilers();
var CLIENT_SIDE = new Compilers(1);
STATEMENTS.add(Ops$3.Text, function (sexp, builder) {
builder.text(sexp[1]);
});
STATEMENTS.add(Ops$3.Comment, function (sexp, builder) {
builder.comment(sexp[1]);
});
STATEMENTS.add(Ops$3.CloseElement, function (_sexp, builder) {
builder.closeElement();
});
STATEMENTS.add(Ops$3.FlushElement, function (_sexp, builder) {
builder.flushElement();
});
STATEMENTS.add(Ops$3.Modifier, function (sexp, builder) {
var env = builder.env,
meta = builder.meta;
var name = sexp[1],
params = sexp[2],
hash = sexp[3];
if (env.hasModifier(name, meta.templateMeta)) {
builder.compileArgs(params, hash, true);
builder.modifier(env.lookupModifier(name, meta.templateMeta));
} else {
throw new Error('Compile Error ' + name + ' is not a modifier: Helpers may not be used in the element form.');
}
});
STATEMENTS.add(Ops$3.StaticAttr, function (sexp, builder) {
var name = sexp[1],
value = sexp[2],
namespace = sexp[3];
builder.staticAttr(name, namespace, value);
});
STATEMENTS.add(Ops$3.DynamicAttr, function (sexp, builder) {
dynamicAttr(sexp, false, builder);
});
STATEMENTS.add(Ops$3.TrustingAttr, function (sexp, builder) {
dynamicAttr(sexp, true, builder);
});
function dynamicAttr(sexp, trusting, builder) {
var name = sexp[1],
value = sexp[2],
namespace = sexp[3];
expr(value, builder);
if (namespace) {
builder.dynamicAttrNS(name, namespace, trusting);
} else {
builder.dynamicAttr(name, trusting);
}
}
STATEMENTS.add(Ops$3.OpenElement, function (sexp, builder) {
builder.openPrimitiveElement(sexp[1]);
});
CLIENT_SIDE.add(Ops$2.OpenComponentElement, function (sexp, builder) {
builder.pushComponentOperations();
builder.openElementWithOperations(sexp[2]);
});
CLIENT_SIDE.add(Ops$2.DidCreateElement, function (_sexp, builder) {
builder.didCreateElement(Register.s0);
});
CLIENT_SIDE.add(Ops$2.DidRenderLayout, function (_sexp, builder) {
builder.didRenderLayout(Register.s0);
});
STATEMENTS.add(Ops$3.Append, function (sexp, builder) {
var value = sexp[1],
trusting = sexp[2];
var _builder$env$macros = builder.env.macros(),
inlines = _builder$env$macros.inlines;
var returned = inlines.compile(sexp, builder) || value;
if (returned === true) return;
var isGet = E.isGet(value);
var isMaybeLocal = E.isMaybeLocal(value);
if (trusting) {
builder.guardedAppend(value, true);
} else {
if (isGet || isMaybeLocal) {
builder.guardedAppend(value, false);
} else {
expr(value, builder);
builder.cautiousAppend();
}
}
});
STATEMENTS.add(Ops$3.Block, function (sexp, builder) {
var name = sexp[1],
params = sexp[2],
hash = sexp[3],
_template = sexp[4],
_inverse = sexp[5];
var template = builder.template(_template);
var inverse = builder.template(_inverse);
var templateBlock = template && template.scan();
var inverseBlock = inverse && inverse.scan();
var _builder$env$macros2 = builder.env.macros(),
blocks = _builder$env$macros2.blocks;
blocks.compile(name, params, hash, templateBlock, inverseBlock, builder);
});
var InvokeDynamicLayout = function () {
function InvokeDynamicLayout(attrs) {
_classCallCheck$18(this, InvokeDynamicLayout);
this.attrs = attrs;
}
InvokeDynamicLayout.prototype.invoke = function invoke(vm, layout) {
var _layout$symbolTable = layout.symbolTable,
symbols = _layout$symbolTable.symbols,
hasEval = _layout$symbolTable.hasEval;
var stack = vm.stack;
var scope = vm.pushRootScope(symbols.length + 1, true);
scope.bindSelf(stack.pop());
scope.bindBlock(symbols.indexOf(ATTRS_BLOCK) + 1, this.attrs);
var lookup = null;
var $eval = -1;
if (hasEval) {
$eval = symbols.indexOf('$eval') + 1;
lookup = (0, _util.dict)();
}
var callerNames = stack.pop();
for (var i = callerNames.length - 1; i >= 0; i--) {
var symbol = symbols.indexOf(callerNames[i]);
var value = stack.pop();
if (symbol !== -1) scope.bindSymbol(symbol + 1, value);
if (hasEval) lookup[callerNames[i]] = value;
}
var numPositionalArgs = stack.pop();
(0, _util.assert)(typeof numPositionalArgs === 'number', '[BUG] Incorrect value of positional argument count found during invoke-dynamic-layout.');
// Currently we don't support accessing positional args in templates, so just throw them away
stack.pop(numPositionalArgs);
var inverseSymbol = symbols.indexOf('&inverse');
var inverse = stack.pop();
if (inverseSymbol !== -1) {
scope.bindBlock(inverseSymbol + 1, inverse);
}
if (lookup) lookup['&inverse'] = inverse;
var defaultSymbol = symbols.indexOf('&default');
var defaultBlock = stack.pop();
if (defaultSymbol !== -1) {
scope.bindBlock(defaultSymbol + 1, defaultBlock);
}
if (lookup) lookup['&default'] = defaultBlock;
if (lookup) scope.bindEvalScope(lookup);
vm.pushFrame();
vm.call(layout.handle);
};
InvokeDynamicLayout.prototype.toJSON = function toJSON() {
return { GlimmerDebug: '<invoke-dynamic-layout>' };
};
return InvokeDynamicLayout;
}();
STATEMENTS.add(Ops$3.Component, function (sexp, builder) {
var tag = sexp[1],
attrs = sexp[2],
args = sexp[3],
block = sexp[4];
if (builder.env.hasComponentDefinition(tag, builder.meta.templateMeta)) {
var child = builder.template(block);
var attrsBlock = new RawInlineBlock(builder.meta, attrs, _util.EMPTY_ARRAY);
var definition = builder.env.getComponentDefinition(tag, builder.meta.templateMeta);
builder.pushComponentManager(definition);
builder.invokeComponent(attrsBlock, null, args, child && child.scan());
} else if (block && block.parameters.length) {
throw new Error('Compile Error: Cannot find component ' + tag);
} else {
builder.openPrimitiveElement(tag);
for (var i = 0; i < attrs.length; i++) {
STATEMENTS.compile(attrs[i], builder);
}
builder.flushElement();
if (block) {
var stmts = block.statements;
for (var _i = 0; _i < stmts.length; _i++) {
STATEMENTS.compile(stmts[_i], builder);
}
}
builder.closeElement();
}
});
var PartialInvoker = function () {
function PartialInvoker(outerSymbols, evalInfo) {
_classCallCheck$18(this, PartialInvoker);
this.outerSymbols = outerSymbols;
this.evalInfo = evalInfo;
}
PartialInvoker.prototype.invoke = function invoke(vm, _partial) {
var partial = _partial;
var partialSymbols = partial.symbolTable.symbols;
var outerScope = vm.scope();
var evalScope = outerScope.getEvalScope();
var partialScope = vm.pushRootScope(partialSymbols.length, false);
partialScope.bindCallerScope(outerScope.getCallerScope());
partialScope.bindEvalScope(evalScope);
partialScope.bindSelf(outerScope.getSelf());
var evalInfo = this.evalInfo,
outerSymbols = this.outerSymbols;
var locals = Object.create(outerScope.getPartialMap());
for (var i = 0; i < evalInfo.length; i++) {
var slot = evalInfo[i];
var name = outerSymbols[slot - 1];
var ref = outerScope.getSymbol(slot);
locals[name] = ref;
}
if (evalScope) {
for (var _i2 = 0; _i2 < partialSymbols.length; _i2++) {
var _name = partialSymbols[_i2];
var symbol = _i2 + 1;
var value = evalScope[_name];
if (value !== undefined) partialScope.bind(symbol, value);
}
}
partialScope.bindPartialMap(locals);
vm.pushFrame();
vm.call(partial.handle);
};
return PartialInvoker;
}();
STATEMENTS.add(Ops$3.Partial, function (sexp, builder) {
var name = sexp[1],
evalInfo = sexp[2];
var _builder$meta = builder.meta,
templateMeta = _builder$meta.templateMeta,
symbols = _builder$meta.symbols;
function helper(vm, args) {
var env = vm.env;
var nameRef = args.positional.at(0);
return (0, _reference2.map)(nameRef, function (n) {
if (typeof n === 'string' && n) {
if (!env.hasPartial(n, templateMeta)) {
throw new Error('Could not find a partial named "' + n + '"');
}
return env.lookupPartial(n, templateMeta);
} else if (n) {
throw new Error('Could not find a partial named "' + String(n) + '"');
} else {
return null;
}
});
}
builder.startLabels();
builder.pushFrame();
builder.returnTo('END');
expr(name, builder);
builder.pushImmediate(1);
builder.pushImmediate(_util.EMPTY_ARRAY);
builder.pushArgs(true);
builder.helper(helper);
builder.dup();
builder.test('simple');
builder.enter(2);
builder.jumpUnless('ELSE');
builder.getPartialTemplate();
builder.compileDynamicBlock();
builder.invokeDynamic(new PartialInvoker(symbols, evalInfo));
builder.popScope();
builder.popFrame();
builder.label('ELSE');
builder.exit();
builder.return();
builder.label('END');
builder.popFrame();
builder.stopLabels();
});
var InvokeDynamicYield = function () {
function InvokeDynamicYield(callerCount) {
_classCallCheck$18(this, InvokeDynamicYield);
this.callerCount = callerCount;
}
InvokeDynamicYield.prototype.invoke = function invoke(vm, block) {
var callerCount = this.callerCount;
var stack = vm.stack;
if (!block) {
// To balance the pop{Frame,Scope}
vm.pushFrame();
vm.pushCallerScope();
return;
}
var table = block.symbolTable;
var locals = table.parameters; // always present in inline blocks
var calleeCount = locals ? locals.length : 0;
var count = Math.min(callerCount, calleeCount);
vm.pushFrame();
vm.pushCallerScope(calleeCount > 0);
var scope = vm.scope();
for (var i = 0; i < count; i++) {
scope.bindSymbol(locals[i], stack.fromBase(callerCount - i));
}
vm.call(block.handle);
};
InvokeDynamicYield.prototype.toJSON = function toJSON() {
return { GlimmerDebug: '<invoke-dynamic-yield caller-count=' + this.callerCount + '>' };
};
return InvokeDynamicYield;
}();
STATEMENTS.add(Ops$3.Yield, function (sexp, builder) {
var to = sexp[1],
params = sexp[2];
var count = compileList(params, builder);
builder.getBlock(to);
builder.compileDynamicBlock();
builder.invokeDynamic(new InvokeDynamicYield(count));
builder.popScope();
builder.popFrame();
if (count) {
builder.pop(count);
}
});
STATEMENTS.add(Ops$3.Debugger, function (sexp, builder) {
var evalInfo = sexp[1];
builder.debugger(builder.meta.symbols, evalInfo);
});
STATEMENTS.add(Ops$3.ClientSideStatement, function (sexp, builder) {
CLIENT_SIDE.compile(sexp, builder);
});
var EXPRESSIONS = new Compilers();
var CLIENT_SIDE_EXPRS = new Compilers(1);
var E = _wireFormat.Expressions;
function expr(expression, builder) {
if (Array.isArray(expression)) {
EXPRESSIONS.compile(expression, builder);
} else {
builder.primitive(expression);
}
}
EXPRESSIONS.add(Ops$3.Unknown, function (sexp, builder) {
var name = sexp[1];
if (builder.env.hasHelper(name, builder.meta.templateMeta)) {
EXPRESSIONS.compile([Ops$3.Helper, name, _util.EMPTY_ARRAY, null], builder);
} else if (builder.meta.asPartial) {
builder.resolveMaybeLocal(name);
} else {
builder.getVariable(0);
builder.getProperty(name);
}
});
EXPRESSIONS.add(Ops$3.Concat, function (sexp, builder) {
var parts = sexp[1];
for (var i = 0; i < parts.length; i++) {
expr(parts[i], builder);
}
builder.concat(parts.length);
});
CLIENT_SIDE_EXPRS.add(Ops$2.FunctionExpression, function (sexp, builder) {
builder.function(sexp[2]);
});
EXPRESSIONS.add(Ops$3.Helper, function (sexp, builder) {
var env = builder.env,
meta = builder.meta;
var name = sexp[1],
params = sexp[2],
hash = sexp[3];
if (env.hasHelper(name, meta.templateMeta)) {
builder.compileArgs(params, hash, true);
builder.helper(env.lookupHelper(name, meta.templateMeta));
} else {
throw new Error('Compile Error: ' + name + ' is not a helper');
}
});
EXPRESSIONS.add(Ops$3.Get, function (sexp, builder) {
var head = sexp[1],
path = sexp[2];
builder.getVariable(head);
for (var i = 0; i < path.length; i++) {
builder.getProperty(path[i]);
}
});
EXPRESSIONS.add(Ops$3.MaybeLocal, function (sexp, builder) {
var path = sexp[1];
if (builder.meta.asPartial) {
var head = path[0];
path = path.slice(1);
builder.resolveMaybeLocal(head);
} else {
builder.getVariable(0);
}
for (var i = 0; i < path.length; i++) {
builder.getProperty(path[i]);
}
});
EXPRESSIONS.add(Ops$3.Undefined, function (_sexp, builder) {
return builder.primitive(undefined);
});
EXPRESSIONS.add(Ops$3.HasBlock, function (sexp, builder) {
builder.hasBlock(sexp[1]);
});
EXPRESSIONS.add(Ops$3.HasBlockParams, function (sexp, builder) {
builder.hasBlockParams(sexp[1]);
});
EXPRESSIONS.add(Ops$3.ClientSideExpression, function (sexp, builder) {
CLIENT_SIDE_EXPRS.compile(sexp, builder);
});
function compileList(params, builder) {
if (!params) return 0;
for (var i = 0; i < params.length; i++) {
expr(params[i], builder);
}
return params.length;
}
var Blocks = function () {
function Blocks() {
_classCallCheck$18(this, Blocks);
this.names = (0, _util.dict)();
this.funcs = [];
}
Blocks.prototype.add = function add(name, func) {
this.funcs.push(func);
this.names[name] = this.funcs.length - 1;
};
Blocks.prototype.addMissing = function addMissing(func) {
this.missing = func;
};
Blocks.prototype.compile = function compile(name, params, hash, template, inverse, builder) {
var index = this.names[name];
if (index === undefined) {
(0, _util.assert)(!!this.missing, name + ' not found, and no catch-all block handler was registered');
var func = this.missing;
var handled = func(name, params, hash, template, inverse, builder);
(0, _util.assert)(!!handled, name + ' not found, and the catch-all block handler didn\'t handle it');
} else {
var _func = this.funcs[index];
_func(params, hash, template, inverse, builder);
}
};
return Blocks;
}();
var BLOCKS = new Blocks();
var Inlines = function () {
function Inlines() {
_classCallCheck$18(this, Inlines);
this.names = (0, _util.dict)();
this.funcs = [];
}
Inlines.prototype.add = function add(name, func) {
this.funcs.push(func);
this.names[name] = this.funcs.length - 1;
};
Inlines.prototype.addMissing = function addMissing(func) {
this.missing = func;
};
Inlines.prototype.compile = function compile(sexp, builder) {
var value = sexp[1];
// TODO: Fix this so that expression macros can return
// things like components, so that {{component foo}}
// is the same as {{(component foo)}}
if (!Array.isArray(value)) return ['expr', value];
var name = void 0;
var params = void 0;
var hash = void 0;
if (value[0] === Ops$3.Helper) {
name = value[1];
params = value[2];
hash = value[3];
} else if (value[0] === Ops$3.Unknown) {
name = value[1];
params = hash = null;
} else {
return ['expr', value];
}
var index = this.names[name];
if (index === undefined && this.missing) {
var func = this.missing;
var returned = func(name, params, hash, builder);
return returned === false ? ['expr', value] : returned;
} else if (index !== undefined) {
var _func2 = this.funcs[index];
var _returned = _func2(name, params, hash, builder);
return _returned === false ? ['expr', value] : _returned;
} else {
return ['expr', value];
}
};
return Inlines;
}();
var INLINES = new Inlines();
populateBuiltins(BLOCKS, INLINES);
function populateBuiltins() {
var blocks = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new Blocks();
var inlines = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : new Inlines();
blocks.add('if', function (params, _hash, template, inverse, builder) {
// PutArgs
// Test(Environment)
// Enter(BEGIN, END)
// BEGIN: Noop
// JumpUnless(ELSE)
// Evaluate(default)
// Jump(END)
// ELSE: Noop
// Evalulate(inverse)
// END: Noop
// Exit
if (!params || params.length !== 1) {
throw new Error('SYNTAX ERROR: #if requires a single argument');
}
builder.startLabels();
builder.pushFrame();
builder.returnTo('END');
expr(params[0], builder);
builder.test('environment');
builder.enter(1);
builder.jumpUnless('ELSE');
builder.invokeStatic(template);
if (inverse) {
builder.jump('EXIT');
builder.label('ELSE');
builder.invokeStatic(inverse);
builder.label('EXIT');
builder.exit();
builder.return();
} else {
builder.label('ELSE');
builder.exit();
builder.return();
}
builder.label('END');
builder.popFrame();
builder.stopLabels();
});
blocks.add('unless', function (params, _hash, template, inverse, builder) {
// PutArgs
// Test(Environment)
// Enter(BEGIN, END)
// BEGIN: Noop
// JumpUnless(ELSE)
// Evaluate(default)
// Jump(END)
// ELSE: Noop
// Evalulate(inverse)
// END: Noop
// Exit
if (!params || params.length !== 1) {
throw new Error('SYNTAX ERROR: #unless requires a single argument');
}
builder.startLabels();
builder.pushFrame();
builder.returnTo('END');
expr(params[0], builder);
builder.test('environment');
builder.enter(1);
builder.jumpIf('ELSE');
builder.invokeStatic(template);
if (inverse) {
builder.jump('EXIT');
builder.label('ELSE');
builder.invokeStatic(inverse);
builder.label('EXIT');
builder.exit();
builder.return();
} else {
builder.label('ELSE');
builder.exit();
builder.return();
}
builder.label('END');
builder.popFrame();
builder.stopLabels();
});
blocks.add('with', function (params, _hash, template, inverse, builder) {
// PutArgs
// Test(Environment)
// Enter(BEGIN, END)
// BEGIN: Noop
// JumpUnless(ELSE)
// Evaluate(default)
// Jump(END)
// ELSE: Noop
// Evalulate(inverse)
// END: Noop
// Exit
if (!params || params.length !== 1) {
throw new Error('SYNTAX ERROR: #with requires a single argument');
}
builder.startLabels();
builder.pushFrame();
builder.returnTo('END');
expr(params[0], builder);
builder.dup();
builder.test('environment');
builder.enter(2);
builder.jumpUnless('ELSE');
builder.invokeStatic(template, 1);
if (inverse) {
builder.jump('EXIT');
builder.label('ELSE');
builder.invokeStatic(inverse);
builder.label('EXIT');
builder.exit();
builder.return();
} else {
builder.label('ELSE');
builder.exit();
builder.return();
}
builder.label('END');
builder.popFrame();
builder.stopLabels();
});
blocks.add('each', function (params, hash, template, inverse, builder) {
// Enter(BEGIN, END)
// BEGIN: Noop
// PutArgs
// PutIterable
// JumpUnless(ELSE)
// EnterList(BEGIN2, END2)
// ITER: Noop
// NextIter(BREAK)
// BEGIN2: Noop
// PushChildScope
// Evaluate(default)
// PopScope
// END2: Noop
// Exit
// Jump(ITER)
// BREAK: Noop
// ExitList
// Jump(END)
// ELSE: Noop
// Evalulate(inverse)
// END: Noop
// Exit
builder.startLabels();
builder.pushFrame();
builder.returnTo('END');
if (hash && hash[0][0] === 'key') {
expr(hash[1][0], builder);
} else {
builder.primitive(null);
}
expr(params[0], builder);
builder.enter(2);
builder.putIterator();
builder.jumpUnless('ELSE');
builder.pushFrame();
builder.returnTo('ITER');
builder.dup(Register.fp, 1);
builder.enterList('BODY');
builder.label('ITER');
builder.iterate('BREAK');
builder.label('BODY');
builder.invokeStatic(template, 2);
builder.pop(2);
builder.exit();
builder.return();
builder.label('BREAK');
builder.exitList();
builder.popFrame();
if (inverse) {
builder.jump('EXIT');
builder.label('ELSE');
builder.invokeStatic(inverse);
builder.label('EXIT');
builder.exit();
builder.return();
} else {
builder.label('ELSE');
builder.exit();
builder.return();
}
builder.label('END');
builder.popFrame();
builder.stopLabels();
});
blocks.add('-in-element', function (params, hash, template, _inverse, builder) {
if (!params || params.length !== 1) {
throw new Error('SYNTAX ERROR: #-in-element requires a single argument');
}
builder.startLabels();
builder.pushFrame();
builder.returnTo('END');
if (hash && hash[0].length) {
var keys = hash[0],
values = hash[1];
if (keys.length === 1 && keys[0] === 'nextSibling') {
expr(values[0], builder);
} else {
throw new Error('SYNTAX ERROR: #-in-element does not take a `' + keys[0] + '` option');
}
} else {
expr(null, builder);
}
expr(params[0], builder);
builder.dup();
builder.test('simple');
builder.enter(3);
builder.jumpUnless('ELSE');
builder.pushRemoteElement();
builder.invokeStatic(template);
builder.popRemoteElement();
builder.label('ELSE');
builder.exit();
builder.return();
builder.label('END');
builder.popFrame();
builder.stopLabels();
});
blocks.add('-with-dynamic-vars', function (_params, hash, template, _inverse, builder) {
if (hash) {
var names = hash[0],
expressions = hash[1];
compileList(expressions, builder);
builder.pushDynamicScope();
builder.bindDynamicScope(names);
builder.invokeStatic(template);
builder.popDynamicScope();
} else {
builder.invokeStatic(template);
}
});
return { blocks: blocks, inlines: inlines };
}
function compileStatement(statement, builder) {
STATEMENTS.compile(statement, builder);
}
function compileStatements(statements, meta, env) {
var b = new OpcodeBuilder(env, meta);
for (var i = 0; i < statements.length; i++) {
compileStatement(statements[i], b);
}
return b;
}
function _classCallCheck$16(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var CompilableTemplate = function () {
function CompilableTemplate(statements, symbolTable) {
_classCallCheck$16(this, CompilableTemplate);
this.statements = statements;
this.symbolTable = symbolTable;
this.compiledStatic = null;
this.compiledDynamic = null;
}
CompilableTemplate.prototype.compileStatic = function compileStatic(env) {
var compiledStatic = this.compiledStatic;
if (!compiledStatic) {
var builder = compileStatements(this.statements, this.symbolTable.meta, env);
builder.finalize();
var handle = builder.start;
compiledStatic = this.compiledStatic = new CompiledStaticTemplate(handle);
}
return compiledStatic;
};
CompilableTemplate.prototype.compileDynamic = function compileDynamic(env) {
var compiledDynamic = this.compiledDynamic;
if (!compiledDynamic) {
var staticBlock = this.compileStatic(env);
compiledDynamic = new CompiledDynamicTemplate(staticBlock.handle, this.symbolTable);
}
return compiledDynamic;
};
return CompilableTemplate;
}();
function _classCallCheck$15(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var Ops$1 = _wireFormat.Ops;
var Scanner = function () {
function Scanner(block, env) {
_classCallCheck$15(this, Scanner);
this.block = block;
this.env = env;
}
Scanner.prototype.scanEntryPoint = function scanEntryPoint(meta) {
var block = this.block;
var statements = block.statements,
symbols = block.symbols,
hasEval = block.hasEval;
return new CompilableTemplate(statements, { meta: meta, symbols: symbols, hasEval: hasEval });
};
Scanner.prototype.scanBlock = function scanBlock(meta) {
var block = this.block;
var statements = block.statements;
return new CompilableTemplate(statements, { meta: meta, parameters: _util.EMPTY_ARRAY });
};
Scanner.prototype.scanLayout = function scanLayout(meta, attrs, componentName) {
var block = this.block;
var statements = block.statements,
symbols = block.symbols,
hasEval = block.hasEval;
var symbolTable = { meta: meta, hasEval: hasEval, symbols: symbols };
var newStatements = [];
var toplevel = void 0;
var inTopLevel = false;
for (var i = 0; i < statements.length; i++) {
var statement = statements[i];
if (_wireFormat.Statements.isComponent(statement)) {
var tagName = statement[1];
if (!this.env.hasComponentDefinition(tagName, meta.templateMeta)) {
if (toplevel !== undefined) {
newStatements.push([Ops$1.OpenElement, tagName]);
} else {
toplevel = tagName;
decorateTopLevelElement(tagName, symbols, attrs, newStatements);
}
addFallback(statement, newStatements);
} else {
if (toplevel === undefined && tagName === componentName) {
toplevel = tagName;
decorateTopLevelElement(tagName, symbols, attrs, newStatements);
addFallback(statement, newStatements);
} else {
newStatements.push(statement);
}
}
} else {
if (toplevel === undefined && _wireFormat.Statements.isOpenElement(statement)) {
toplevel = statement[1];
inTopLevel = true;
decorateTopLevelElement(toplevel, symbols, attrs, newStatements);
} else {
if (inTopLevel) {
if (_wireFormat.Statements.isFlushElement(statement)) {
inTopLevel = false;
} else if (_wireFormat.Statements.isModifier(statement)) {
throw Error('Found modifier "' + statement[1] + '" on the top-level element of "' + componentName + '". Modifiers cannot be on the top-level element');
}
}
newStatements.push(statement);
}
}
}
newStatements.push([Ops$1.ClientSideStatement, Ops$2.DidRenderLayout]);
return new CompilableTemplate(newStatements, symbolTable);
};
return Scanner;
}();
function addFallback(statement, buffer) {
var attrs = statement[2],
block = statement[4];
for (var i = 0; i < attrs.length; i++) {
buffer.push(attrs[i]);
}
buffer.push([Ops$1.FlushElement]);
if (block) {
var statements = block.statements;
for (var _i = 0; _i < statements.length; _i++) {
buffer.push(statements[_i]);
}
}
buffer.push([Ops$1.CloseElement]);
}
function decorateTopLevelElement(tagName, symbols, attrs, buffer) {
var attrsSymbol = symbols.push(ATTRS_BLOCK);
buffer.push([Ops$1.ClientSideStatement, Ops$2.OpenComponentElement, tagName]);
buffer.push([Ops$1.ClientSideStatement, Ops$2.DidCreateElement]);
buffer.push([Ops$1.Yield, attrsSymbol, _util.EMPTY_ARRAY]);
buffer.push.apply(buffer, attrs);
}
function _classCallCheck$24(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var Constants = function () {
function Constants() {
_classCallCheck$24(this, Constants);
// `0` means NULL
this.references = [];
this.strings = [];
this.expressions = [];
this.floats = [];
this.arrays = [];
this.blocks = [];
this.functions = [];
this.others = [];
}
Constants.prototype.getReference = function getReference(value) {
return this.references[value - 1];
};
Constants.prototype.reference = function reference(value) {
var index = this.references.length;
this.references.push(value);
return index + 1;
};
Constants.prototype.getString = function getString(value) {
return this.strings[value - 1];
};
Constants.prototype.getFloat = function getFloat(value) {
return this.floats[value - 1];
};
Constants.prototype.float = function float(value) {
return this.floats.push(value);
};
Constants.prototype.string = function string(value) {
var index = this.strings.length;
this.strings.push(value);
return index + 1;
};
Constants.prototype.getExpression = function getExpression(value) {
return this.expressions[value - 1];
};
Constants.prototype.getArray = function getArray(value) {
return this.arrays[value - 1];
};
Constants.prototype.getNames = function getNames(value) {
var _names = [];
var names = this.getArray(value);
for (var i = 0; i < names.length; i++) {
var n = names[i];
_names[i] = this.getString(n);
}
return _names;
};
Constants.prototype.array = function array(values) {
var index = this.arrays.length;
this.arrays.push(values);
return index + 1;
};
Constants.prototype.getBlock = function getBlock(value) {
return this.blocks[value - 1];
};
Constants.prototype.block = function block(_block) {
var index = this.blocks.length;
this.blocks.push(_block);
return index + 1;
};
Constants.prototype.getFunction = function getFunction(value) {
return this.functions[value - 1];
};
Constants.prototype.function = function _function(f) {
var index = this.functions.length;
this.functions.push(f);
return index + 1;
};
Constants.prototype.getOther = function getOther(value) {
return this.others[value - 1];
};
Constants.prototype.other = function other(_other) {
var index = this.others.length;
this.others.push(_other);
return index + 1;
};
return Constants;
}();
var badProtocols = ['javascript:', 'vbscript:'];
var badTags = ['A', 'BODY', 'LINK', 'IMG', 'IFRAME', 'BASE', 'FORM'];
var badTagsForDataURI = ['EMBED'];
var badAttributes = ['href', 'src', 'background', 'action'];
var badAttributesForDataURI = ['src'];
function has(array, item) {
return array.indexOf(item) !== -1;
}
function checkURI(tagName, attribute) {
return (tagName === null || has(badTags, tagName)) && has(badAttributes, attribute);
}
function checkDataURI(tagName, attribute) {
if (tagName === null) return false;
return has(badTagsForDataURI, tagName) && has(badAttributesForDataURI, attribute);
}
function requiresSanitization(tagName, attribute) {
return checkURI(tagName, attribute) || checkDataURI(tagName, attribute);
}
function sanitizeAttributeValue(env, element, attribute, value) {
var tagName = null;
if (value === null || value === undefined) {
return value;
}
if (isSafeString(value)) {
return value.toHTML();
}
if (!element) {
tagName = null;
} else {
tagName = element.tagName.toUpperCase();
}
var str = normalizeTextValue(value);
if (checkURI(tagName, attribute)) {
var protocol = env.protocolForURL(str);
if (has(badProtocols, protocol)) {
return 'unsafe:' + str;
}
}
if (checkDataURI(tagName, attribute)) {
return 'unsafe:' + str;
}
return str;
}
/*
* @method normalizeProperty
* @param element {HTMLElement}
* @param slotName {String}
* @returns {Object} { name, type }
*/
function normalizeProperty(element, slotName) {
var type = void 0,
normalized = void 0;
if (slotName in element) {
normalized = slotName;
type = 'prop';
} else {
var lower = slotName.toLowerCase();
if (lower in element) {
type = 'prop';
normalized = lower;
} else {
type = 'attr';
normalized = slotName;
}
}
if (type === 'prop' && (normalized.toLowerCase() === 'style' || preferAttr(element.tagName, normalized))) {
type = 'attr';
}
return { normalized: normalized, type: type };
}
// properties that MUST be set as attributes, due to:
// * browser bug
// * strange spec outlier
var ATTR_OVERRIDES = {
// phantomjs < 2.0 lets you set it as a prop but won't reflect it
// back to the attribute. button.getAttribute('type') === null
BUTTON: { type: true, form: true },
INPUT: {
// Some version of IE (like IE9) actually throw an exception
// if you set input.type = 'something-unknown'
type: true,
form: true,
// Chrome 46.0.2464.0: 'autocorrect' in document.createElement('input') === false
// Safari 8.0.7: 'autocorrect' in document.createElement('input') === false
// Mobile Safari (iOS 8.4 simulator): 'autocorrect' in document.createElement('input') === true
autocorrect: true,
// Chrome 54.0.2840.98: 'list' in document.createElement('input') === true
// Safari 9.1.3: 'list' in document.createElement('input') === false
list: true
},
// element.form is actually a legitimate readOnly property, that is to be
// mutated, but must be mutated by setAttribute...
SELECT: { form: true },
OPTION: { form: true },
TEXTAREA: { form: true },
LABEL: { form: true },
FIELDSET: { form: true },
LEGEND: { form: true },
OBJECT: { form: true }
};
function preferAttr(tagName, propName) {
var tag = ATTR_OVERRIDES[tagName.toUpperCase()];
return tag && tag[propName.toLowerCase()] || false;
}
function _defaults$12(obj, defaults) {
var keys = Object.getOwnPropertyNames(defaults);for (var i = 0; i < keys.length; i++) {
var key = keys[i];var value = Object.getOwnPropertyDescriptor(defaults, key);if (value && value.configurable && obj[key] === undefined) {
Object.defineProperty(obj, key, value);
}
}return obj;
}
function _classCallCheck$27(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn$12(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && (typeof call === "object" || typeof call === "function") ? call : self;
}
function _inherits$12(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults$12(subClass, superClass);
}
var innerHTMLWrapper = {
colgroup: { depth: 2, before: '<table><colgroup>', after: '</colgroup></table>' },
table: { depth: 1, before: '<table>', after: '</table>' },
tbody: { depth: 2, before: '<table><tbody>', after: '</tbody></table>' },
tfoot: { depth: 2, before: '<table><tfoot>', after: '</tfoot></table>' },
thead: { depth: 2, before: '<table><thead>', after: '</thead></table>' },
tr: { depth: 3, before: '<table><tbody><tr>', after: '</tr></tbody></table>' }
};
// Patch: innerHTML Fix
// Browsers: IE9
// Reason: IE9 don't allow us to set innerHTML on col, colgroup, frameset,
// html, style, table, tbody, tfoot, thead, title, tr.
// Fix: Wrap the innerHTML we are about to set in its parents, apply the
// wrapped innerHTML on a div, then move the unwrapped nodes into the
// target position.
function domChanges(document, DOMChangesClass) {
if (!document) return DOMChangesClass;
if (!shouldApplyFix(document)) {
return DOMChangesClass;
}
var div = document.createElement('div');
return function (_DOMChangesClass) {
_inherits$12(DOMChangesWithInnerHTMLFix, _DOMChangesClass);
function DOMChangesWithInnerHTMLFix() {
_classCallCheck$27(this, DOMChangesWithInnerHTMLFix);
return _possibleConstructorReturn$12(this, _DOMChangesClass.apply(this, arguments));
}
DOMChangesWithInnerHTMLFix.prototype.insertHTMLBefore = function insertHTMLBefore$$1(parent, nextSibling, html) {
if (html === null || html === '') {
return _DOMChangesClass.prototype.insertHTMLBefore.call(this, parent, nextSibling, html);
}
var parentTag = parent.tagName.toLowerCase();
var wrapper = innerHTMLWrapper[parentTag];
if (wrapper === undefined) {
return _DOMChangesClass.prototype.insertHTMLBefore.call(this, parent, nextSibling, html);
}
return fixInnerHTML(parent, wrapper, div, html, nextSibling);
};
return DOMChangesWithInnerHTMLFix;
}(DOMChangesClass);
}
function treeConstruction(document, DOMTreeConstructionClass) {
if (!document) return DOMTreeConstructionClass;
if (!shouldApplyFix(document)) {
return DOMTreeConstructionClass;
}
var div = document.createElement('div');
return function (_DOMTreeConstructionC) {
_inherits$12(DOMTreeConstructionWithInnerHTMLFix, _DOMTreeConstructionC);
function DOMTreeConstructionWithInnerHTMLFix() {
_classCallCheck$27(this, DOMTreeConstructionWithInnerHTMLFix);
return _possibleConstructorReturn$12(this, _DOMTreeConstructionC.apply(this, arguments));
}
DOMTreeConstructionWithInnerHTMLFix.prototype.insertHTMLBefore = function insertHTMLBefore$$1(parent, referenceNode, html) {
if (html === null || html === '') {
return _DOMTreeConstructionC.prototype.insertHTMLBefore.call(this, parent, referenceNode, html);
}
var parentTag = parent.tagName.toLowerCase();
var wrapper = innerHTMLWrapper[parentTag];
if (wrapper === undefined) {
return _DOMTreeConstructionC.prototype.insertHTMLBefore.call(this, parent, referenceNode, html);
}
return fixInnerHTML(parent, wrapper, div, html, referenceNode);
};
return DOMTreeConstructionWithInnerHTMLFix;
}(DOMTreeConstructionClass);
}
function fixInnerHTML(parent, wrapper, div, html, reference) {
var wrappedHtml = wrapper.before + html + wrapper.after;
div.innerHTML = wrappedHtml;
var parentNode = div;
for (var i = 0; i < wrapper.depth; i++) {
parentNode = parentNode.childNodes[0];
}
var _moveNodesBefore = moveNodesBefore(parentNode, parent, reference),
first = _moveNodesBefore[0],
last = _moveNodesBefore[1];
return new ConcreteBounds(parent, first, last);
}
function shouldApplyFix(document) {
var table = document.createElement('table');
try {
table.innerHTML = '<tbody></tbody>';
} catch (e) {} finally {
if (table.childNodes.length !== 0) {
// It worked as expected, no fix required
return false;
}
}
return true;
}
function _defaults$13(obj, defaults) {
var keys = Object.getOwnPropertyNames(defaults);for (var i = 0; i < keys.length; i++) {
var key = keys[i];var value = Object.getOwnPropertyDescriptor(defaults, key);if (value && value.configurable && obj[key] === undefined) {
Object.defineProperty(obj, key, value);
}
}return obj;
}
function _classCallCheck$28(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn$13(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && (typeof call === "object" || typeof call === "function") ? call : self;
}
function _inherits$13(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults$13(subClass, superClass);
}
var SVG_NAMESPACE$1 = 'http://www.w3.org/2000/svg';
// Patch: insertAdjacentHTML on SVG Fix
// Browsers: Safari, IE, Edge, Firefox ~33-34
// Reason: insertAdjacentHTML does not exist on SVG elements in Safari. It is
// present but throws an exception on IE and Edge. Old versions of
// Firefox create nodes in the incorrect namespace.
// Fix: Since IE and Edge silently fail to create SVG nodes using
// innerHTML, and because Firefox may create nodes in the incorrect
// namespace using innerHTML on SVG elements, an HTML-string wrapping
// approach is used. A pre/post SVG tag is added to the string, then
// that whole string is added to a div. The created nodes are plucked
// out and applied to the target location on DOM.
function domChanges$1(document, DOMChangesClass, svgNamespace) {
if (!document) return DOMChangesClass;
if (!shouldApplyFix$1(document, svgNamespace)) {
return DOMChangesClass;
}
var div = document.createElement('div');
return function (_DOMChangesClass) {
_inherits$13(DOMChangesWithSVGInnerHTMLFix, _DOMChangesClass);
function DOMChangesWithSVGInnerHTMLFix() {
_classCallCheck$28(this, DOMChangesWithSVGInnerHTMLFix);
return _possibleConstructorReturn$13(this, _DOMChangesClass.apply(this, arguments));
}
DOMChangesWithSVGInnerHTMLFix.prototype.insertHTMLBefore = function insertHTMLBefore$$1(parent, nextSibling, html) {
if (html === null || html === '') {
return _DOMChangesClass.prototype.insertHTMLBefore.call(this, parent, nextSibling, html);
}
if (parent.namespaceURI !== svgNamespace) {
return _DOMChangesClass.prototype.insertHTMLBefore.call(this, parent, nextSibling, html);
}
return fixSVG(parent, div, html, nextSibling);
};
return DOMChangesWithSVGInnerHTMLFix;
}(DOMChangesClass);
}
function treeConstruction$1(document, TreeConstructionClass, svgNamespace) {
if (!document) return TreeConstructionClass;
if (!shouldApplyFix$1(document, svgNamespace)) {
return TreeConstructionClass;
}
var div = document.createElement('div');
return function (_TreeConstructionClas) {
_inherits$13(TreeConstructionWithSVGInnerHTMLFix, _TreeConstructionClas);
function TreeConstructionWithSVGInnerHTMLFix() {
_classCallCheck$28(this, TreeConstructionWithSVGInnerHTMLFix);
return _possibleConstructorReturn$13(this, _TreeConstructionClas.apply(this, arguments));
}
TreeConstructionWithSVGInnerHTMLFix.prototype.insertHTMLBefore = function insertHTMLBefore$$1(parent, reference, html) {
if (html === null || html === '') {
return _TreeConstructionClas.prototype.insertHTMLBefore.call(this, parent, reference, html);
}
if (parent.namespaceURI !== svgNamespace) {
return _TreeConstructionClas.prototype.insertHTMLBefore.call(this, parent, reference, html);
}
return fixSVG(parent, div, html, reference);
};
return TreeConstructionWithSVGInnerHTMLFix;
}(TreeConstructionClass);
}
function fixSVG(parent, div, html, reference) {
// IE, Edge: also do not correctly support using `innerHTML` on SVG
// namespaced elements. So here a wrapper is used.
var wrappedHtml = '<svg>' + html + '</svg>';
div.innerHTML = wrappedHtml;
var _moveNodesBefore = moveNodesBefore(div.firstChild, parent, reference),
first = _moveNodesBefore[0],
last = _moveNodesBefore[1];
return new ConcreteBounds(parent, first, last);
}
function shouldApplyFix$1(document, svgNamespace) {
var svg = document.createElementNS(svgNamespace, 'svg');
try {
svg['insertAdjacentHTML']('beforeend', '<circle></circle>');
} catch (e) {
// IE, Edge: Will throw, insertAdjacentHTML is unsupported on SVG
// Safari: Will throw, insertAdjacentHTML is not present on SVG
} finally {
// FF: Old versions will create a node in the wrong namespace
if (svg.childNodes.length === 1 && svg.firstChild.namespaceURI === SVG_NAMESPACE$1) {
// The test worked as expected, no fix required
return false;
}
return true;
}
}
function _defaults$14(obj, defaults) {
var keys = Object.getOwnPropertyNames(defaults);for (var i = 0; i < keys.length; i++) {
var key = keys[i];var value = Object.getOwnPropertyDescriptor(defaults, key);if (value && value.configurable && obj[key] === undefined) {
Object.defineProperty(obj, key, value);
}
}return obj;
}
function _classCallCheck$29(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn$14(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && (typeof call === "object" || typeof call === "function") ? call : self;
}
function _inherits$14(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults$14(subClass, superClass);
}
// Patch: Adjacent text node merging fix
// Browsers: IE, Edge, Firefox w/o inspector open
// Reason: These browsers will merge adjacent text nodes. For exmaple given
// <div>Hello</div> with div.insertAdjacentHTML(' world') browsers
// with proper behavior will populate div.childNodes with two items.
// These browsers will populate it with one merged node instead.
// Fix: Add these nodes to a wrapper element, then iterate the childNodes
// of that wrapper and move the nodes to their target location. Note
// that potential SVG bugs will have been handled before this fix.
// Note that this fix must only apply to the previous text node, as
// the base implementation of `insertHTMLBefore` already handles
// following text nodes correctly.
function domChanges$2(document, DOMChangesClass) {
if (!document) return DOMChangesClass;
if (!shouldApplyFix$2(document)) {
return DOMChangesClass;
}
return function (_DOMChangesClass) {
_inherits$14(DOMChangesWithTextNodeMergingFix, _DOMChangesClass);
function DOMChangesWithTextNodeMergingFix(document) {
_classCallCheck$29(this, DOMChangesWithTextNodeMergingFix);
var _this = _possibleConstructorReturn$14(this, _DOMChangesClass.call(this, document));
_this.uselessComment = document.createComment('');
return _this;
}
DOMChangesWithTextNodeMergingFix.prototype.insertHTMLBefore = function insertHTMLBefore(parent, nextSibling, html) {
if (html === null) {
return _DOMChangesClass.prototype.insertHTMLBefore.call(this, parent, nextSibling, html);
}
var didSetUselessComment = false;
var nextPrevious = nextSibling ? nextSibling.previousSibling : parent.lastChild;
if (nextPrevious && nextPrevious instanceof Text) {
didSetUselessComment = true;
parent.insertBefore(this.uselessComment, nextSibling);
}
var bounds = _DOMChangesClass.prototype.insertHTMLBefore.call(this, parent, nextSibling, html);
if (didSetUselessComment) {
parent.removeChild(this.uselessComment);
}
return bounds;
};
return DOMChangesWithTextNodeMergingFix;
}(DOMChangesClass);
}
function treeConstruction$2(document, TreeConstructionClass) {
if (!document) return TreeConstructionClass;
if (!shouldApplyFix$2(document)) {
return TreeConstructionClass;
}
return function (_TreeConstructionClas) {
_inherits$14(TreeConstructionWithTextNodeMergingFix, _TreeConstructionClas);
function TreeConstructionWithTextNodeMergingFix(document) {
_classCallCheck$29(this, TreeConstructionWithTextNodeMergingFix);
var _this2 = _possibleConstructorReturn$14(this, _TreeConstructionClas.call(this, document));
_this2.uselessComment = _this2.createComment('');
return _this2;
}
TreeConstructionWithTextNodeMergingFix.prototype.insertHTMLBefore = function insertHTMLBefore(parent, reference, html) {
if (html === null) {
return _TreeConstructionClas.prototype.insertHTMLBefore.call(this, parent, reference, html);
}
var didSetUselessComment = false;
var nextPrevious = reference ? reference.previousSibling : parent.lastChild;
if (nextPrevious && nextPrevious instanceof Text) {
didSetUselessComment = true;
parent.insertBefore(this.uselessComment, reference);
}
var bounds = _TreeConstructionClas.prototype.insertHTMLBefore.call(this, parent, reference, html);
if (didSetUselessComment) {
parent.removeChild(this.uselessComment);
}
return bounds;
};
return TreeConstructionWithTextNodeMergingFix;
}(TreeConstructionClass);
}
function shouldApplyFix$2(document) {
var mergingTextDiv = document.createElement('div');
mergingTextDiv.innerHTML = 'first';
mergingTextDiv.insertAdjacentHTML('beforeend', 'second');
if (mergingTextDiv.childNodes.length === 2) {
// It worked as expected, no fix required
return false;
}
return true;
}
function _defaults$11(obj, defaults) {
var keys = Object.getOwnPropertyNames(defaults);for (var i = 0; i < keys.length; i++) {
var key = keys[i];var value = Object.getOwnPropertyDescriptor(defaults, key);if (value && value.configurable && obj[key] === undefined) {
Object.defineProperty(obj, key, value);
}
}return obj;
}
function _possibleConstructorReturn$11(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && (typeof call === "object" || typeof call === "function") ? call : self;
}
function _inherits$11(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults$11(subClass, superClass);
}
function _classCallCheck$26(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var SVG_NAMESPACE$$1 = 'http://www.w3.org/2000/svg';
// http://www.w3.org/TR/html/syntax.html#html-integration-point
var SVG_INTEGRATION_POINTS = { foreignObject: 1, desc: 1, title: 1 };
// http://www.w3.org/TR/html/syntax.html#adjust-svg-attributes
// TODO: Adjust SVG attributes
// http://www.w3.org/TR/html/syntax.html#parsing-main-inforeign
// TODO: Adjust SVG elements
// http://www.w3.org/TR/html/syntax.html#parsing-main-inforeign
var BLACKLIST_TABLE = Object.create(null);
["b", "big", "blockquote", "body", "br", "center", "code", "dd", "div", "dl", "dt", "em", "embed", "h1", "h2", "h3", "h4", "h5", "h6", "head", "hr", "i", "img", "li", "listing", "main", "meta", "nobr", "ol", "p", "pre", "ruby", "s", "small", "span", "strong", "strike", "sub", "sup", "table", "tt", "u", "ul", "var"].forEach(function (tag) {
return BLACKLIST_TABLE[tag] = 1;
});
var WHITESPACE = /[\t-\r \xA0\u1680\u180E\u2000-\u200A\u2028\u2029\u202F\u205F\u3000\uFEFF]/;
var doc = typeof document === 'undefined' ? null : document;
function isWhitespace(string) {
return WHITESPACE.test(string);
}
function moveNodesBefore(source, target, nextSibling) {
var first = source.firstChild;
var last = null;
var current = first;
while (current) {
last = current;
current = current.nextSibling;
target.insertBefore(last, nextSibling);
}
return [first, last];
}
var DOMOperations = function () {
function DOMOperations(document) {
_classCallCheck$26(this, DOMOperations);
this.document = document;
this.setupUselessElement();
}
// split into seperate method so that NodeDOMTreeConstruction
// can override it.
DOMOperations.prototype.setupUselessElement = function setupUselessElement() {
this.uselessElement = this.document.createElement('div');
};
DOMOperations.prototype.createElement = function createElement(tag, context) {
var isElementInSVGNamespace = void 0,
isHTMLIntegrationPoint = void 0;
if (context) {
isElementInSVGNamespace = context.namespaceURI === SVG_NAMESPACE$$1 || tag === 'svg';
isHTMLIntegrationPoint = SVG_INTEGRATION_POINTS[context.tagName];
} else {
isElementInSVGNamespace = tag === 'svg';
isHTMLIntegrationPoint = false;
}
if (isElementInSVGNamespace && !isHTMLIntegrationPoint) {
// FIXME: This does not properly handle <font> with color, face, or
// size attributes, which is also disallowed by the spec. We should fix
// this.
if (BLACKLIST_TABLE[tag]) {
throw new Error('Cannot create a ' + tag + ' inside an SVG context');
}
return this.document.createElementNS(SVG_NAMESPACE$$1, tag);
} else {
return this.document.createElement(tag);
}
};
DOMOperations.prototype.insertBefore = function insertBefore(parent, node, reference) {
parent.insertBefore(node, reference);
};
DOMOperations.prototype.insertHTMLBefore = function insertHTMLBefore(_parent, nextSibling, html) {
return _insertHTMLBefore(this.uselessElement, _parent, nextSibling, html);
};
DOMOperations.prototype.createTextNode = function createTextNode(text) {
return this.document.createTextNode(text);
};
DOMOperations.prototype.createComment = function createComment(data) {
return this.document.createComment(data);
};
return DOMOperations;
}();
var DOM;
(function (DOM) {
var TreeConstruction = function (_DOMOperations) {
_inherits$11(TreeConstruction, _DOMOperations);
function TreeConstruction() {
_classCallCheck$26(this, TreeConstruction);
return _possibleConstructorReturn$11(this, _DOMOperations.apply(this, arguments));
}
TreeConstruction.prototype.createElementNS = function createElementNS(namespace, tag) {
return this.document.createElementNS(namespace, tag);
};
TreeConstruction.prototype.setAttribute = function setAttribute(element, name, value, namespace) {
if (namespace) {
element.setAttributeNS(namespace, name, value);
} else {
element.setAttribute(name, value);
}
};
return TreeConstruction;
}(DOMOperations);
DOM.TreeConstruction = TreeConstruction;
var appliedTreeContruction = TreeConstruction;
appliedTreeContruction = treeConstruction$2(doc, appliedTreeContruction);
appliedTreeContruction = treeConstruction(doc, appliedTreeContruction);
appliedTreeContruction = treeConstruction$1(doc, appliedTreeContruction, SVG_NAMESPACE$$1);
DOM.DOMTreeConstruction = appliedTreeContruction;
})(DOM || (DOM = {}));
var DOMChanges = function (_DOMOperations2) {
_inherits$11(DOMChanges, _DOMOperations2);
function DOMChanges(document) {
_classCallCheck$26(this, DOMChanges);
var _this2 = _possibleConstructorReturn$11(this, _DOMOperations2.call(this, document));
_this2.document = document;
_this2.namespace = null;
return _this2;
}
DOMChanges.prototype.setAttribute = function setAttribute(element, name, value) {
element.setAttribute(name, value);
};
DOMChanges.prototype.setAttributeNS = function setAttributeNS(element, namespace, name, value) {
element.setAttributeNS(namespace, name, value);
};
DOMChanges.prototype.removeAttribute = function removeAttribute(element, name) {
element.removeAttribute(name);
};
DOMChanges.prototype.removeAttributeNS = function removeAttributeNS(element, namespace, name) {
element.removeAttributeNS(namespace, name);
};
DOMChanges.prototype.insertNodeBefore = function insertNodeBefore(parent, node, reference) {
if (isDocumentFragment(node)) {
var firstChild = node.firstChild,
lastChild = node.lastChild;
this.insertBefore(parent, node, reference);
return new ConcreteBounds(parent, firstChild, lastChild);
} else {
this.insertBefore(parent, node, reference);
return new SingleNodeBounds(parent, node);
}
};
DOMChanges.prototype.insertTextBefore = function insertTextBefore(parent, nextSibling, text) {
var textNode = this.createTextNode(text);
this.insertBefore(parent, textNode, nextSibling);
return textNode;
};
DOMChanges.prototype.insertBefore = function insertBefore(element, node, reference) {
element.insertBefore(node, reference);
};
DOMChanges.prototype.insertAfter = function insertAfter(element, node, reference) {
this.insertBefore(element, node, reference.nextSibling);
};
return DOMChanges;
}(DOMOperations);
function _insertHTMLBefore(_useless, _parent, _nextSibling, html) {
// TypeScript vendored an old version of the DOM spec where `insertAdjacentHTML`
// only exists on `HTMLElement` but not on `Element`. We actually work with the
// newer version of the DOM API here (and monkey-patch this method in `./compat`
// when we detect older browsers). This is a hack to work around this limitation.
var parent = _parent;
var useless = _useless;
var nextSibling = _nextSibling;
var prev = nextSibling ? nextSibling.previousSibling : parent.lastChild;
var last = void 0;
if (html === null || html === '') {
return new ConcreteBounds(parent, null, null);
}
if (nextSibling === null) {
parent.insertAdjacentHTML('beforeend', html);
last = parent.lastChild;
} else if (nextSibling instanceof HTMLElement) {
nextSibling.insertAdjacentHTML('beforebegin', html);
last = nextSibling.previousSibling;
} else {
// Non-element nodes do not support insertAdjacentHTML, so add an
// element and call it on that element. Then remove the element.
//
// This also protects Edge, IE and Firefox w/o the inspector open
// from merging adjacent text nodes. See ./compat/text-node-merging-fix.ts
parent.insertBefore(useless, nextSibling);
useless.insertAdjacentHTML('beforebegin', html);
last = useless.previousSibling;
parent.removeChild(useless);
}
var first = prev ? prev.nextSibling : parent.firstChild;
return new ConcreteBounds(parent, first, last);
}
function isDocumentFragment(node) {
return node.nodeType === Node.DOCUMENT_FRAGMENT_NODE;
}
var helper = DOMChanges;
helper = domChanges$2(doc, helper);
helper = domChanges(doc, helper);
helper = domChanges$1(doc, helper, SVG_NAMESPACE$$1);
var helper$1 = helper;
var DOMTreeConstruction = DOM.DOMTreeConstruction;
function _defaults$10(obj, defaults) {
var keys = Object.getOwnPropertyNames(defaults);for (var i = 0; i < keys.length; i++) {
var key = keys[i];var value = Object.getOwnPropertyDescriptor(defaults, key);if (value && value.configurable && obj[key] === undefined) {
Object.defineProperty(obj, key, value);
}
}return obj;
}
function _possibleConstructorReturn$10(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && (typeof call === "object" || typeof call === "function") ? call : self;
}
function _inherits$10(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults$10(subClass, superClass);
}
function _classCallCheck$25(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function defaultManagers(element, attr, _isTrusting, _namespace) {
var tagName = element.tagName;
var isSVG = element.namespaceURI === SVG_NAMESPACE$$1;
if (isSVG) {
return defaultAttributeManagers(tagName, attr);
}
var _normalizeProperty = normalizeProperty(element, attr),
type = _normalizeProperty.type,
normalized = _normalizeProperty.normalized;
if (type === 'attr') {
return defaultAttributeManagers(tagName, normalized);
} else {
return defaultPropertyManagers(tagName, normalized);
}
}
function defaultPropertyManagers(tagName, attr) {
if (requiresSanitization(tagName, attr)) {
return new SafePropertyManager(attr);
}
if (isUserInputValue(tagName, attr)) {
return INPUT_VALUE_PROPERTY_MANAGER;
}
if (isOptionSelected(tagName, attr)) {
return OPTION_SELECTED_MANAGER;
}
return new PropertyManager(attr);
}
function defaultAttributeManagers(tagName, attr) {
if (requiresSanitization(tagName, attr)) {
return new SafeAttributeManager(attr);
}
return new AttributeManager(attr);
}
function readDOMAttr(element, attr) {
var isSVG = element.namespaceURI === SVG_NAMESPACE$$1;
var _normalizeProperty2 = normalizeProperty(element, attr),
type = _normalizeProperty2.type,
normalized = _normalizeProperty2.normalized;
if (isSVG) {
return element.getAttribute(normalized);
}
if (type === 'attr') {
return element.getAttribute(normalized);
}
{
return element[normalized];
}
}
var AttributeManager = function () {
function AttributeManager(attr) {
_classCallCheck$25(this, AttributeManager);
this.attr = attr;
}
AttributeManager.prototype.setAttribute = function setAttribute(env, element, value, namespace) {
var dom = env.getAppendOperations();
var normalizedValue = normalizeAttributeValue(value);
if (!isAttrRemovalValue(normalizedValue)) {
dom.setAttribute(element, this.attr, normalizedValue, namespace);
}
};
AttributeManager.prototype.updateAttribute = function updateAttribute(env, element, value, namespace) {
if (value === null || value === undefined || value === false) {
if (namespace) {
env.getDOM().removeAttributeNS(element, namespace, this.attr);
} else {
env.getDOM().removeAttribute(element, this.attr);
}
} else {
this.setAttribute(env, element, value);
}
};
return AttributeManager;
}();
var PropertyManager = function (_AttributeManager) {
_inherits$10(PropertyManager, _AttributeManager);
function PropertyManager() {
_classCallCheck$25(this, PropertyManager);
return _possibleConstructorReturn$10(this, _AttributeManager.apply(this, arguments));
}
PropertyManager.prototype.setAttribute = function setAttribute(_env, element, value, _namespace) {
if (!isAttrRemovalValue(value)) {
element[this.attr] = value;
}
};
PropertyManager.prototype.removeAttribute = function removeAttribute(env, element, namespace) {
// TODO this sucks but to preserve properties first and to meet current
// semantics we must do this.
var attr = this.attr;
if (namespace) {
env.getDOM().removeAttributeNS(element, namespace, attr);
} else {
env.getDOM().removeAttribute(element, attr);
}
};
PropertyManager.prototype.updateAttribute = function updateAttribute(env, element, value, namespace) {
// ensure the property is always updated
element[this.attr] = value;
if (isAttrRemovalValue(value)) {
this.removeAttribute(env, element, namespace);
}
};
return PropertyManager;
}(AttributeManager);
function normalizeAttributeValue(value) {
if (value === false || value === undefined || value === null) {
return null;
}
if (value === true) {
return '';
}
// onclick function etc in SSR
if (typeof value === 'function') {
return null;
}
return String(value);
}
function isAttrRemovalValue(value) {
return value === null || value === undefined;
}
var SafePropertyManager = function (_PropertyManager) {
_inherits$10(SafePropertyManager, _PropertyManager);
function SafePropertyManager() {
_classCallCheck$25(this, SafePropertyManager);
return _possibleConstructorReturn$10(this, _PropertyManager.apply(this, arguments));
}
SafePropertyManager.prototype.setAttribute = function setAttribute(env, element, value) {
_PropertyManager.prototype.setAttribute.call(this, env, element, sanitizeAttributeValue(env, element, this.attr, value));
};
SafePropertyManager.prototype.updateAttribute = function updateAttribute(env, element, value) {
_PropertyManager.prototype.updateAttribute.call(this, env, element, sanitizeAttributeValue(env, element, this.attr, value));
};
return SafePropertyManager;
}(PropertyManager);
function isUserInputValue(tagName, attribute) {
return (tagName === 'INPUT' || tagName === 'TEXTAREA') && attribute === 'value';
}
var InputValuePropertyManager = function (_AttributeManager2) {
_inherits$10(InputValuePropertyManager, _AttributeManager2);
function InputValuePropertyManager() {
_classCallCheck$25(this, InputValuePropertyManager);
return _possibleConstructorReturn$10(this, _AttributeManager2.apply(this, arguments));
}
InputValuePropertyManager.prototype.setAttribute = function setAttribute(_env, element, value) {
var input = element;
input.value = normalizeTextValue(value);
};
InputValuePropertyManager.prototype.updateAttribute = function updateAttribute(_env, element, value) {
var input = element;
var currentValue = input.value;
var normalizedValue = normalizeTextValue(value);
if (currentValue !== normalizedValue) {
input.value = normalizedValue;
}
};
return InputValuePropertyManager;
}(AttributeManager);
var INPUT_VALUE_PROPERTY_MANAGER = new InputValuePropertyManager('value');
function isOptionSelected(tagName, attribute) {
return tagName === 'OPTION' && attribute === 'selected';
}
var OptionSelectedManager = function (_PropertyManager2) {
_inherits$10(OptionSelectedManager, _PropertyManager2);
function OptionSelectedManager() {
_classCallCheck$25(this, OptionSelectedManager);
return _possibleConstructorReturn$10(this, _PropertyManager2.apply(this, arguments));
}
OptionSelectedManager.prototype.setAttribute = function setAttribute(_env, element, value) {
if (value !== null && value !== undefined && value !== false) {
var option = element;
option.selected = true;
}
};
OptionSelectedManager.prototype.updateAttribute = function updateAttribute(_env, element, value) {
var option = element;
if (value) {
option.selected = true;
} else {
option.selected = false;
}
};
return OptionSelectedManager;
}(PropertyManager);
var OPTION_SELECTED_MANAGER = new OptionSelectedManager('selected');
var SafeAttributeManager = function (_AttributeManager3) {
_inherits$10(SafeAttributeManager, _AttributeManager3);
function SafeAttributeManager() {
_classCallCheck$25(this, SafeAttributeManager);
return _possibleConstructorReturn$10(this, _AttributeManager3.apply(this, arguments));
}
SafeAttributeManager.prototype.setAttribute = function setAttribute(env, element, value) {
_AttributeManager3.prototype.setAttribute.call(this, env, element, sanitizeAttributeValue(env, element, this.attr, value));
};
SafeAttributeManager.prototype.updateAttribute = function updateAttribute(env, element, value, _namespace) {
_AttributeManager3.prototype.updateAttribute.call(this, env, element, sanitizeAttributeValue(env, element, this.attr, value));
};
return SafeAttributeManager;
}(AttributeManager);
var _createClass$4 = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if ("value" in descriptor) descriptor.writable = true;Object.defineProperty(target, descriptor.key, descriptor);
}
}return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);if (staticProps) defineProperties(Constructor, staticProps);return Constructor;
};
}();
function _classCallCheck$23(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var Scope = function () {
function Scope(
// the 0th slot is `self`
slots, callerScope,
// named arguments and blocks passed to a layout that uses eval
evalScope,
// locals in scope when the partial was invoked
partialMap) {
_classCallCheck$23(this, Scope);
this.slots = slots;
this.callerScope = callerScope;
this.evalScope = evalScope;
this.partialMap = partialMap;
}
Scope.root = function root(self) {
var size = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
var refs = new Array(size + 1);
for (var i = 0; i <= size; i++) {
refs[i] = UNDEFINED_REFERENCE;
}
return new Scope(refs, null, null, null).init({ self: self });
};
Scope.sized = function sized() {
var size = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
var refs = new Array(size + 1);
for (var i = 0; i <= size; i++) {
refs[i] = UNDEFINED_REFERENCE;
}
return new Scope(refs, null, null, null);
};
Scope.prototype.init = function init(_ref) {
var self = _ref.self;
this.slots[0] = self;
return this;
};
Scope.prototype.getSelf = function getSelf() {
return this.get(0);
};
Scope.prototype.getSymbol = function getSymbol(symbol) {
return this.get(symbol);
};
Scope.prototype.getBlock = function getBlock(symbol) {
return this.get(symbol);
};
Scope.prototype.getEvalScope = function getEvalScope() {
return this.evalScope;
};
Scope.prototype.getPartialMap = function getPartialMap() {
return this.partialMap;
};
Scope.prototype.bind = function bind(symbol, value) {
this.set(symbol, value);
};
Scope.prototype.bindSelf = function bindSelf(self) {
this.set(0, self);
};
Scope.prototype.bindSymbol = function bindSymbol(symbol, value) {
this.set(symbol, value);
};
Scope.prototype.bindBlock = function bindBlock(symbol, value) {
this.set(symbol, value);
};
Scope.prototype.bindEvalScope = function bindEvalScope(map$$1) {
this.evalScope = map$$1;
};
Scope.prototype.bindPartialMap = function bindPartialMap(map$$1) {
this.partialMap = map$$1;
};
Scope.prototype.bindCallerScope = function bindCallerScope(scope) {
this.callerScope = scope;
};
Scope.prototype.getCallerScope = function getCallerScope() {
return this.callerScope;
};
Scope.prototype.child = function child() {
return new Scope(this.slots.slice(), this.callerScope, this.evalScope, this.partialMap);
};
Scope.prototype.get = function get(index) {
if (index >= this.slots.length) {
throw new RangeError('BUG: cannot get $' + index + ' from scope; length=' + this.slots.length);
}
return this.slots[index];
};
Scope.prototype.set = function set(index, value) {
if (index >= this.slots.length) {
throw new RangeError('BUG: cannot get $' + index + ' from scope; length=' + this.slots.length);
}
this.slots[index] = value;
};
return Scope;
}();
var Transaction = function () {
function Transaction() {
_classCallCheck$23(this, Transaction);
this.scheduledInstallManagers = [];
this.scheduledInstallModifiers = [];
this.scheduledUpdateModifierManagers = [];
this.scheduledUpdateModifiers = [];
this.createdComponents = [];
this.createdManagers = [];
this.updatedComponents = [];
this.updatedManagers = [];
this.destructors = [];
}
Transaction.prototype.didCreate = function didCreate(component, manager) {
this.createdComponents.push(component);
this.createdManagers.push(manager);
};
Transaction.prototype.didUpdate = function didUpdate(component, manager) {
this.updatedComponents.push(component);
this.updatedManagers.push(manager);
};
Transaction.prototype.scheduleInstallModifier = function scheduleInstallModifier(modifier, manager) {
this.scheduledInstallManagers.push(manager);
this.scheduledInstallModifiers.push(modifier);
};
Transaction.prototype.scheduleUpdateModifier = function scheduleUpdateModifier(modifier, manager) {
this.scheduledUpdateModifierManagers.push(manager);
this.scheduledUpdateModifiers.push(modifier);
};
Transaction.prototype.didDestroy = function didDestroy(d) {
this.destructors.push(d);
};
Transaction.prototype.commit = function commit() {
var createdComponents = this.createdComponents,
createdManagers = this.createdManagers;
for (var i = 0; i < createdComponents.length; i++) {
var component = createdComponents[i];
var manager = createdManagers[i];
manager.didCreate(component);
}
var updatedComponents = this.updatedComponents,
updatedManagers = this.updatedManagers;
for (var _i = 0; _i < updatedComponents.length; _i++) {
var _component = updatedComponents[_i];
var _manager = updatedManagers[_i];
_manager.didUpdate(_component);
}
var destructors = this.destructors;
for (var _i2 = 0; _i2 < destructors.length; _i2++) {
destructors[_i2].destroy();
}
var scheduledInstallManagers = this.scheduledInstallManagers,
scheduledInstallModifiers = this.scheduledInstallModifiers;
for (var _i3 = 0; _i3 < scheduledInstallManagers.length; _i3++) {
var _manager2 = scheduledInstallManagers[_i3];
var modifier = scheduledInstallModifiers[_i3];
_manager2.install(modifier);
}
var scheduledUpdateModifierManagers = this.scheduledUpdateModifierManagers,
scheduledUpdateModifiers = this.scheduledUpdateModifiers;
for (var _i4 = 0; _i4 < scheduledUpdateModifierManagers.length; _i4++) {
var _manager3 = scheduledUpdateModifierManagers[_i4];
var _modifier = scheduledUpdateModifiers[_i4];
_manager3.update(_modifier);
}
};
return Transaction;
}();
var Opcode = function () {
function Opcode(heap) {
_classCallCheck$23(this, Opcode);
this.heap = heap;
this.offset = 0;
}
_createClass$4(Opcode, [{
key: 'type',
get: function () {
return this.heap.getbyaddr(this.offset);
}
}, {
key: 'op1',
get: function () {
return this.heap.getbyaddr(this.offset + 1);
}
}, {
key: 'op2',
get: function () {
return this.heap.getbyaddr(this.offset + 2);
}
}, {
key: 'op3',
get: function () {
return this.heap.getbyaddr(this.offset + 3);
}
}]);
return Opcode;
}();
var TableSlotState;
(function (TableSlotState) {
TableSlotState[TableSlotState["Allocated"] = 0] = "Allocated";
TableSlotState[TableSlotState["Freed"] = 1] = "Freed";
TableSlotState[TableSlotState["Purged"] = 2] = "Purged";
TableSlotState[TableSlotState["Pointer"] = 3] = "Pointer";
})(TableSlotState || (TableSlotState = {}));
var Heap = function () {
function Heap() {
_classCallCheck$23(this, Heap);
this.heap = [];
this.offset = 0;
this.handle = 0;
/**
* layout:
*
* - pointer into heap
* - size
* - freed (0 or 1)
*/
this.table = [];
}
Heap.prototype.push = function push(item) {
this.heap[this.offset++] = item;
};
Heap.prototype.getbyaddr = function getbyaddr(address) {
return this.heap[address];
};
Heap.prototype.setbyaddr = function setbyaddr(address, value) {
this.heap[address] = value;
};
Heap.prototype.malloc = function malloc() {
this.table.push(this.offset, 0, 0);
var handle = this.handle;
this.handle += 3;
return handle;
};
Heap.prototype.finishMalloc = function finishMalloc(handle) {
var start = this.table[handle];
var finish = this.offset;
this.table[handle + 1] = finish - start;
};
Heap.prototype.size = function size() {
return this.offset;
};
// It is illegal to close over this address, as compaction
// may move it. However, it is legal to use this address
// multiple times between compactions.
Heap.prototype.getaddr = function getaddr(handle) {
return this.table[handle];
};
Heap.prototype.gethandle = function gethandle(address) {
this.table.push(address, 0, TableSlotState.Pointer);
var handle = this.handle;
this.handle += 3;
return handle;
};
Heap.prototype.sizeof = function sizeof(handle) {
return -1;
};
Heap.prototype.free = function free(handle) {
this.table[handle + 2] = 1;
};
Heap.prototype.compact = function compact() {
var compactedSize = 0;
var table = this.table,
length = this.table.length,
heap = this.heap;
for (var i = 0; i < length; i += 3) {
var offset = table[i];
var size = table[i + 1];
var state = table[i + 2];
if (state === TableSlotState.Purged) {
continue;
} else if (state === TableSlotState.Freed) {
// transition to "already freed"
// a good improvement would be to reuse
// these slots
table[i + 2] = 2;
compactedSize += size;
} else if (state === TableSlotState.Allocated) {
for (var j = offset; j <= i + size; j++) {
heap[j - compactedSize] = heap[j];
}
table[i] = offset - compactedSize;
} else if (state === TableSlotState.Pointer) {
table[i] = offset - compactedSize;
}
}
this.offset = this.offset - compactedSize;
};
return Heap;
}();
var Program = function () {
function Program() {
_classCallCheck$23(this, Program);
this.heap = new Heap();
this._opcode = new Opcode(this.heap);
this.constants = new Constants();
}
Program.prototype.opcode = function opcode(offset) {
this._opcode.offset = offset;
return this._opcode;
};
return Program;
}();
var Environment = function () {
function Environment(_ref2) {
var appendOperations = _ref2.appendOperations,
updateOperations = _ref2.updateOperations;
_classCallCheck$23(this, Environment);
this._macros = null;
this._transaction = null;
this.program = new Program();
this.appendOperations = appendOperations;
this.updateOperations = updateOperations;
}
Environment.prototype.toConditionalReference = function toConditionalReference(reference) {
return new ConditionalReference(reference);
};
Environment.prototype.getAppendOperations = function getAppendOperations() {
return this.appendOperations;
};
Environment.prototype.getDOM = function getDOM() {
return this.updateOperations;
};
Environment.prototype.getIdentity = function getIdentity(object) {
return (0, _util.ensureGuid)(object) + '';
};
Environment.prototype.begin = function begin() {
(0, _util.assert)(!this._transaction, 'a glimmer transaction was begun, but one already exists. You may have a nested transaction');
this._transaction = new Transaction();
};
Environment.prototype.didCreate = function didCreate(component, manager) {
this.transaction.didCreate(component, manager);
};
Environment.prototype.didUpdate = function didUpdate(component, manager) {
this.transaction.didUpdate(component, manager);
};
Environment.prototype.scheduleInstallModifier = function scheduleInstallModifier(modifier, manager) {
this.transaction.scheduleInstallModifier(modifier, manager);
};
Environment.prototype.scheduleUpdateModifier = function scheduleUpdateModifier(modifier, manager) {
this.transaction.scheduleUpdateModifier(modifier, manager);
};
Environment.prototype.didDestroy = function didDestroy(d) {
this.transaction.didDestroy(d);
};
Environment.prototype.commit = function commit() {
var transaction = this.transaction;
this._transaction = null;
transaction.commit();
};
Environment.prototype.attributeFor = function attributeFor(element, attr, isTrusting, namespace) {
return defaultManagers(element, attr, isTrusting, namespace === undefined ? null : namespace);
};
Environment.prototype.macros = function macros() {
var macros = this._macros;
if (!macros) {
this._macros = macros = this.populateBuiltins();
}
return macros;
};
Environment.prototype.populateBuiltins = function populateBuiltins$$1() {
return populateBuiltins();
};
_createClass$4(Environment, [{
key: 'transaction',
get: function () {
return this._transaction;
}
}]);
return Environment;
}();
function _defaults$15(obj, defaults) {
var keys = Object.getOwnPropertyNames(defaults);for (var i = 0; i < keys.length; i++) {
var key = keys[i];var value = Object.getOwnPropertyDescriptor(defaults, key);if (value && value.configurable && obj[key] === undefined) {
Object.defineProperty(obj, key, value);
}
}return obj;
}
var _createClass$5 = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if ("value" in descriptor) descriptor.writable = true;Object.defineProperty(target, descriptor.key, descriptor);
}
}return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);if (staticProps) defineProperties(Constructor, staticProps);return Constructor;
};
}();
function _possibleConstructorReturn$15(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && (typeof call === "object" || typeof call === "function") ? call : self;
}
function _inherits$15(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults$15(subClass, superClass);
}
function _classCallCheck$30(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var UpdatingVM = function () {
function UpdatingVM(env, _ref) {
var _ref$alwaysRevalidate = _ref.alwaysRevalidate,
alwaysRevalidate = _ref$alwaysRevalidate === undefined ? false : _ref$alwaysRevalidate;
_classCallCheck$30(this, UpdatingVM);
this.frameStack = new _util.Stack();
this.env = env;
this.constants = env.program.constants;
this.dom = env.getDOM();
this.alwaysRevalidate = alwaysRevalidate;
}
UpdatingVM.prototype.execute = function execute(opcodes, handler) {
var frameStack = this.frameStack;
this.try(opcodes, handler);
while (true) {
if (frameStack.isEmpty()) break;
var opcode = this.frame.nextStatement();
if (opcode === null) {
this.frameStack.pop();
continue;
}
opcode.evaluate(this);
}
};
UpdatingVM.prototype.goto = function goto(op) {
this.frame.goto(op);
};
UpdatingVM.prototype.try = function _try(ops, handler) {
this.frameStack.push(new UpdatingVMFrame(this, ops, handler));
};
UpdatingVM.prototype.throw = function _throw() {
this.frame.handleException();
this.frameStack.pop();
};
UpdatingVM.prototype.evaluateOpcode = function evaluateOpcode(opcode) {
opcode.evaluate(this);
};
_createClass$5(UpdatingVM, [{
key: 'frame',
get: function () {
return this.frameStack.current;
}
}]);
return UpdatingVM;
}();
var BlockOpcode = function (_UpdatingOpcode) {
_inherits$15(BlockOpcode, _UpdatingOpcode);
function BlockOpcode(start, state, bounds$$1, children) {
_classCallCheck$30(this, BlockOpcode);
var _this = _possibleConstructorReturn$15(this, _UpdatingOpcode.call(this));
_this.start = start;
_this.type = "block";
_this.next = null;
_this.prev = null;
var env = state.env,
scope = state.scope,
dynamicScope = state.dynamicScope,
stack = state.stack;
_this.children = children;
_this.env = env;
_this.scope = scope;
_this.dynamicScope = dynamicScope;
_this.stack = stack;
_this.bounds = bounds$$1;
return _this;
}
BlockOpcode.prototype.parentElement = function parentElement() {
return this.bounds.parentElement();
};
BlockOpcode.prototype.firstNode = function firstNode() {
return this.bounds.firstNode();
};
BlockOpcode.prototype.lastNode = function lastNode() {
return this.bounds.lastNode();
};
BlockOpcode.prototype.evaluate = function evaluate(vm) {
vm.try(this.children, null);
};
BlockOpcode.prototype.destroy = function destroy() {
this.bounds.destroy();
};
BlockOpcode.prototype.didDestroy = function didDestroy() {
this.env.didDestroy(this.bounds);
};
BlockOpcode.prototype.toJSON = function toJSON() {
var details = (0, _util.dict)();
details["guid"] = '' + this._guid;
return {
guid: this._guid,
type: this.type,
details: details,
children: this.children.toArray().map(function (op) {
return op.toJSON();
})
};
};
return BlockOpcode;
}(UpdatingOpcode);
var TryOpcode = function (_BlockOpcode) {
_inherits$15(TryOpcode, _BlockOpcode);
function TryOpcode(start, state, bounds$$1, children) {
_classCallCheck$30(this, TryOpcode);
var _this2 = _possibleConstructorReturn$15(this, _BlockOpcode.call(this, start, state, bounds$$1, children));
_this2.type = "try";
_this2.tag = _this2._tag = _reference2.UpdatableTag.create(_reference2.CONSTANT_TAG);
return _this2;
}
TryOpcode.prototype.didInitializeChildren = function didInitializeChildren() {
this._tag.inner.update((0, _reference2.combineSlice)(this.children));
};
TryOpcode.prototype.evaluate = function evaluate(vm) {
vm.try(this.children, this);
};
TryOpcode.prototype.handleException = function handleException() {
var _this3 = this;
var env = this.env,
bounds$$1 = this.bounds,
children = this.children,
scope = this.scope,
dynamicScope = this.dynamicScope,
start = this.start,
stack = this.stack,
prev = this.prev,
next = this.next;
children.clear();
var elementStack = ElementStack.resume(env, bounds$$1, bounds$$1.reset(env));
var vm = new VM(env, scope, dynamicScope, elementStack);
var updating = new _util.LinkedList();
vm.execute(start, function (vm) {
vm.stack = EvaluationStack.restore(stack);
vm.updatingOpcodeStack.push(updating);
vm.updateWith(_this3);
vm.updatingOpcodeStack.push(children);
});
this.prev = prev;
this.next = next;
};
TryOpcode.prototype.toJSON = function toJSON() {
var json = _BlockOpcode.prototype.toJSON.call(this);
var details = json["details"];
if (!details) {
details = json["details"] = {};
}
return _BlockOpcode.prototype.toJSON.call(this);
};
return TryOpcode;
}(BlockOpcode);
var ListRevalidationDelegate = function () {
function ListRevalidationDelegate(opcode, marker) {
_classCallCheck$30(this, ListRevalidationDelegate);
this.opcode = opcode;
this.marker = marker;
this.didInsert = false;
this.didDelete = false;
this.map = opcode.map;
this.updating = opcode['children'];
}
ListRevalidationDelegate.prototype.insert = function insert(key, item, memo, before) {
var map$$1 = this.map,
opcode = this.opcode,
updating = this.updating;
var nextSibling = null;
var reference = null;
if (before) {
reference = map$$1[before];
nextSibling = reference['bounds'].firstNode();
} else {
nextSibling = this.marker;
}
var vm = opcode.vmForInsertion(nextSibling);
var tryOpcode = null;
var start = opcode.start;
vm.execute(start, function (vm) {
map$$1[key] = tryOpcode = vm.iterate(memo, item);
vm.updatingOpcodeStack.push(new _util.LinkedList());
vm.updateWith(tryOpcode);
vm.updatingOpcodeStack.push(tryOpcode.children);
});
updating.insertBefore(tryOpcode, reference);
this.didInsert = true;
};
ListRevalidationDelegate.prototype.retain = function retain(_key, _item, _memo) {};
ListRevalidationDelegate.prototype.move = function move$$1(key, _item, _memo, before) {
var map$$1 = this.map,
updating = this.updating;
var entry = map$$1[key];
var reference = map$$1[before] || null;
if (before) {
move(entry, reference.firstNode());
} else {
move(entry, this.marker);
}
updating.remove(entry);
updating.insertBefore(entry, reference);
};
ListRevalidationDelegate.prototype.delete = function _delete(key) {
var map$$1 = this.map;
var opcode = map$$1[key];
opcode.didDestroy();
clear(opcode);
this.updating.remove(opcode);
delete map$$1[key];
this.didDelete = true;
};
ListRevalidationDelegate.prototype.done = function done() {
this.opcode.didInitializeChildren(this.didInsert || this.didDelete);
};
return ListRevalidationDelegate;
}();
var ListBlockOpcode = function (_BlockOpcode2) {
_inherits$15(ListBlockOpcode, _BlockOpcode2);
function ListBlockOpcode(start, state, bounds$$1, children, artifacts) {
_classCallCheck$30(this, ListBlockOpcode);
var _this4 = _possibleConstructorReturn$15(this, _BlockOpcode2.call(this, start, state, bounds$$1, children));
_this4.type = "list-block";
_this4.map = (0, _util.dict)();
_this4.lastIterated = _reference2.INITIAL;
_this4.artifacts = artifacts;
var _tag = _this4._tag = _reference2.UpdatableTag.create(_reference2.CONSTANT_TAG);
_this4.tag = (0, _reference2.combine)([artifacts.tag, _tag]);
return _this4;
}
ListBlockOpcode.prototype.didInitializeChildren = function didInitializeChildren() {
var listDidChange = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
this.lastIterated = this.artifacts.tag.value();
if (listDidChange) {
this._tag.inner.update((0, _reference2.combineSlice)(this.children));
}
};
ListBlockOpcode.prototype.evaluate = function evaluate(vm) {
var artifacts = this.artifacts,
lastIterated = this.lastIterated;
if (!artifacts.tag.validate(lastIterated)) {
var bounds$$1 = this.bounds;
var dom = vm.dom;
var marker = dom.createComment('');
dom.insertAfter(bounds$$1.parentElement(), marker, bounds$$1.lastNode());
var target = new ListRevalidationDelegate(this, marker);
var synchronizer = new _reference2.IteratorSynchronizer({ target: target, artifacts: artifacts });
synchronizer.sync();
this.parentElement().removeChild(marker);
}
// Run now-updated updating opcodes
_BlockOpcode2.prototype.evaluate.call(this, vm);
};
ListBlockOpcode.prototype.vmForInsertion = function vmForInsertion(nextSibling) {
var env = this.env,
scope = this.scope,
dynamicScope = this.dynamicScope;
var elementStack = ElementStack.forInitialRender(this.env, this.bounds.parentElement(), nextSibling);
return new VM(env, scope, dynamicScope, elementStack);
};
ListBlockOpcode.prototype.toJSON = function toJSON() {
var json = _BlockOpcode2.prototype.toJSON.call(this);
var map$$1 = this.map;
var inner = Object.keys(map$$1).map(function (key) {
return JSON.stringify(key) + ': ' + map$$1[key]._guid;
}).join(", ");
var details = json["details"];
if (!details) {
details = json["details"] = {};
}
details["map"] = '{' + inner + '}';
return json;
};
return ListBlockOpcode;
}(BlockOpcode);
var UpdatingVMFrame = function () {
function UpdatingVMFrame(vm, ops, exceptionHandler) {
_classCallCheck$30(this, UpdatingVMFrame);
this.vm = vm;
this.ops = ops;
this.exceptionHandler = exceptionHandler;
this.vm = vm;
this.ops = ops;
this.current = ops.head();
}
UpdatingVMFrame.prototype.goto = function goto(op) {
this.current = op;
};
UpdatingVMFrame.prototype.nextStatement = function nextStatement() {
var current = this.current,
ops = this.ops;
if (current) this.current = ops.nextNode(current);
return current;
};
UpdatingVMFrame.prototype.handleException = function handleException() {
if (this.exceptionHandler) {
this.exceptionHandler.handleException();
}
};
return UpdatingVMFrame;
}();
function _classCallCheck$31(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var RenderResult = function () {
function RenderResult(env, updating, bounds$$1) {
_classCallCheck$31(this, RenderResult);
this.env = env;
this.updating = updating;
this.bounds = bounds$$1;
}
RenderResult.prototype.rerender = function rerender() {
var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : { alwaysRevalidate: false },
_ref$alwaysRevalidate = _ref.alwaysRevalidate,
alwaysRevalidate = _ref$alwaysRevalidate === undefined ? false : _ref$alwaysRevalidate;
var env = this.env,
updating = this.updating;
var vm = new UpdatingVM(env, { alwaysRevalidate: alwaysRevalidate });
vm.execute(updating, this);
};
RenderResult.prototype.parentElement = function parentElement() {
return this.bounds.parentElement();
};
RenderResult.prototype.firstNode = function firstNode() {
return this.bounds.firstNode();
};
RenderResult.prototype.lastNode = function lastNode() {
return this.bounds.lastNode();
};
RenderResult.prototype.opcodes = function opcodes() {
return this.updating;
};
RenderResult.prototype.handleException = function handleException() {
throw "this should never happen";
};
RenderResult.prototype.destroy = function destroy() {
this.bounds.destroy();
clear(this.bounds);
};
return RenderResult;
}();
var _createClass$3 = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if ("value" in descriptor) descriptor.writable = true;Object.defineProperty(target, descriptor.key, descriptor);
}
}return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);if (staticProps) defineProperties(Constructor, staticProps);return Constructor;
};
}();
function _classCallCheck$22(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var EvaluationStack = function () {
function EvaluationStack(stack, fp, sp) {
_classCallCheck$22(this, EvaluationStack);
this.stack = stack;
this.fp = fp;
this.sp = sp;
}
EvaluationStack.empty = function empty() {
return new this([], 0, -1);
};
EvaluationStack.restore = function restore(snapshot) {
return new this(snapshot.slice(), 0, snapshot.length - 1);
};
EvaluationStack.prototype.isEmpty = function isEmpty() {
return this.sp === -1;
};
EvaluationStack.prototype.push = function push(value) {
this.stack[++this.sp] = value;
};
EvaluationStack.prototype.dup = function dup() {
var position = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.sp;
this.push(this.stack[position]);
};
EvaluationStack.prototype.pop = function pop() {
var n = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1;
var top = this.stack[this.sp];
this.sp -= n;
return top;
};
EvaluationStack.prototype.peek = function peek() {
return this.stack[this.sp];
};
EvaluationStack.prototype.fromBase = function fromBase(offset) {
return this.stack[this.fp - offset];
};
EvaluationStack.prototype.fromTop = function fromTop(offset) {
return this.stack[this.sp - offset];
};
EvaluationStack.prototype.capture = function capture(items) {
var end = this.sp + 1;
var start = end - items;
return this.stack.slice(start, end);
};
EvaluationStack.prototype.reset = function reset() {
this.stack.length = 0;
};
EvaluationStack.prototype.toArray = function toArray() {
return this.stack.slice(this.fp, this.sp + 1);
};
return EvaluationStack;
}();
var VM = function () {
function VM(env, scope, dynamicScope, elementStack) {
_classCallCheck$22(this, VM);
this.env = env;
this.elementStack = elementStack;
this.dynamicScopeStack = new _util.Stack();
this.scopeStack = new _util.Stack();
this.updatingOpcodeStack = new _util.Stack();
this.cacheGroups = new _util.Stack();
this.listBlockStack = new _util.Stack();
this.stack = EvaluationStack.empty();
/* Registers */
this.pc = -1;
this.ra = -1;
this.s0 = null;
this.s1 = null;
this.t0 = null;
this.t1 = null;
this.env = env;
this.heap = env.program.heap;
this.constants = env.program.constants;
this.elementStack = elementStack;
this.scopeStack.push(scope);
this.dynamicScopeStack.push(dynamicScope);
}
// Fetch a value from a register onto the stack
VM.prototype.fetch = function fetch(register) {
this.stack.push(this[Register[register]]);
};
// Load a value from the stack into a register
VM.prototype.load = function load(register) {
this[Register[register]] = this.stack.pop();
};
// Fetch a value from a register
VM.prototype.fetchValue = function fetchValue(register) {
return this[Register[register]];
};
// Load a value into a register
VM.prototype.loadValue = function loadValue(register, value) {
this[Register[register]] = value;
};
// Start a new frame and save $ra and $fp on the stack
VM.prototype.pushFrame = function pushFrame() {
this.stack.push(this.ra);
this.stack.push(this.fp);
this.fp = this.sp - 1;
};
// Restore $ra, $sp and $fp
VM.prototype.popFrame = function popFrame() {
this.sp = this.fp - 1;
this.ra = this.stack.fromBase(0);
this.fp = this.stack.fromBase(-1);
};
// Jump to an address in `program`
VM.prototype.goto = function goto(offset) {
this.pc = (0, _util.typePos)(this.pc + offset);
};
// Save $pc into $ra, then jump to a new address in `program` (jal in MIPS)
VM.prototype.call = function call(handle) {
var pc = this.heap.getaddr(handle);
this.ra = this.pc;
this.pc = pc;
};
// Put a specific `program` address in $ra
VM.prototype.returnTo = function returnTo(offset) {
this.ra = (0, _util.typePos)(this.pc + offset);
};
// Return to the `program` address stored in $ra
VM.prototype.return = function _return() {
this.pc = this.ra;
};
VM.initial = function initial(env, self, dynamicScope, elementStack, program) {
var scope = Scope.root(self, program.symbolTable.symbols.length);
var vm = new VM(env, scope, dynamicScope, elementStack);
vm.pc = vm.heap.getaddr(program.handle);
vm.updatingOpcodeStack.push(new _util.LinkedList());
return vm;
};
VM.prototype.capture = function capture(args) {
return {
dynamicScope: this.dynamicScope(),
env: this.env,
scope: this.scope(),
stack: this.stack.capture(args)
};
};
VM.prototype.beginCacheGroup = function beginCacheGroup() {
this.cacheGroups.push(this.updating().tail());
};
VM.prototype.commitCacheGroup = function commitCacheGroup() {
// JumpIfNotModified(END)
// (head)
// (....)
// (tail)
// DidModify
// END: Noop
var END = new LabelOpcode("END");
var opcodes = this.updating();
var marker = this.cacheGroups.pop();
var head = marker ? opcodes.nextNode(marker) : opcodes.head();
var tail = opcodes.tail();
var tag = (0, _reference2.combineSlice)(new _util.ListSlice(head, tail));
var guard = new JumpIfNotModifiedOpcode(tag, END);
opcodes.insertBefore(guard, head);
opcodes.append(new DidModifyOpcode(guard));
opcodes.append(END);
};
VM.prototype.enter = function enter(args) {
var updating = new _util.LinkedList();
var state = this.capture(args);
var tracker = this.elements().pushUpdatableBlock();
var tryOpcode = new TryOpcode(this.heap.gethandle(this.pc), state, tracker, updating);
this.didEnter(tryOpcode);
};
VM.prototype.iterate = function iterate(memo, value) {
var stack = this.stack;
stack.push(value);
stack.push(memo);
var state = this.capture(2);
var tracker = this.elements().pushUpdatableBlock();
// let ip = this.ip;
// this.ip = end + 4;
// this.frames.push(ip);
return new TryOpcode(this.heap.gethandle(this.pc), state, tracker, new _util.LinkedList());
};
VM.prototype.enterItem = function enterItem(key, opcode) {
this.listBlock().map[key] = opcode;
this.didEnter(opcode);
};
VM.prototype.enterList = function enterList(relativeStart) {
var updating = new _util.LinkedList();
var state = this.capture(0);
var tracker = this.elements().pushBlockList(updating);
var artifacts = this.stack.peek().artifacts;
var start = this.heap.gethandle((0, _util.typePos)(this.pc + relativeStart));
var opcode = new ListBlockOpcode(start, state, tracker, updating, artifacts);
this.listBlockStack.push(opcode);
this.didEnter(opcode);
};
VM.prototype.didEnter = function didEnter(opcode) {
this.updateWith(opcode);
this.updatingOpcodeStack.push(opcode.children);
};
VM.prototype.exit = function exit() {
this.elements().popBlock();
this.updatingOpcodeStack.pop();
var parent = this.updating().tail();
parent.didInitializeChildren();
};
VM.prototype.exitList = function exitList() {
this.exit();
this.listBlockStack.pop();
};
VM.prototype.updateWith = function updateWith(opcode) {
this.updating().append(opcode);
};
VM.prototype.listBlock = function listBlock() {
return this.listBlockStack.current;
};
VM.prototype.updating = function updating() {
return this.updatingOpcodeStack.current;
};
VM.prototype.elements = function elements() {
return this.elementStack;
};
VM.prototype.scope = function scope() {
return this.scopeStack.current;
};
VM.prototype.dynamicScope = function dynamicScope() {
return this.dynamicScopeStack.current;
};
VM.prototype.pushChildScope = function pushChildScope() {
this.scopeStack.push(this.scope().child());
};
VM.prototype.pushCallerScope = function pushCallerScope() {
var childScope = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
var callerScope = this.scope().getCallerScope();
this.scopeStack.push(childScope ? callerScope.child() : callerScope);
};
VM.prototype.pushDynamicScope = function pushDynamicScope() {
var child = this.dynamicScope().child();
this.dynamicScopeStack.push(child);
return child;
};
VM.prototype.pushRootScope = function pushRootScope(size, bindCaller) {
var scope = Scope.sized(size);
if (bindCaller) scope.bindCallerScope(this.scope());
this.scopeStack.push(scope);
return scope;
};
VM.prototype.popScope = function popScope() {
this.scopeStack.pop();
};
VM.prototype.popDynamicScope = function popDynamicScope() {
this.dynamicScopeStack.pop();
};
VM.prototype.newDestroyable = function newDestroyable(d) {
this.elements().newDestroyable(d);
};
/// SCOPE HELPERS
VM.prototype.getSelf = function getSelf() {
return this.scope().getSelf();
};
VM.prototype.referenceForSymbol = function referenceForSymbol(symbol) {
return this.scope().getSymbol(symbol);
};
/// EXECUTION
VM.prototype.execute = function execute(start, initialize) {
this.pc = this.heap.getaddr(start);
if (initialize) initialize(this);
var result = void 0;
while (true) {
result = this.next();
if (result.done) break;
}
return result.value;
};
VM.prototype.next = function next() {
var env = this.env,
updatingOpcodeStack = this.updatingOpcodeStack,
elementStack = this.elementStack;
var opcode = this.nextStatement(env);
var result = void 0;
if (opcode !== null) {
APPEND_OPCODES.evaluate(this, opcode, opcode.type);
result = { done: false, value: null };
} else {
// Unload the stack
this.stack.reset();
result = {
done: true,
value: new RenderResult(env, updatingOpcodeStack.pop(), elementStack.popBlock())
};
}
return result;
};
VM.prototype.nextStatement = function nextStatement(env) {
var pc = this.pc;
if (pc === -1) {
return null;
}
var program = env.program;
this.pc += 4;
return program.opcode(pc);
};
VM.prototype.evaluateOpcode = function evaluateOpcode(opcode) {
APPEND_OPCODES.evaluate(this, opcode, opcode.type);
};
VM.prototype.bindDynamicScope = function bindDynamicScope(names) {
var scope = this.dynamicScope();
for (var i = names.length - 1; i >= 0; i--) {
var name = this.constants.getString(names[i]);
scope.set(name, this.stack.pop());
}
};
_createClass$3(VM, [{
key: 'fp',
get: function () {
return this.stack.fp;
},
set: function (fp) {
this.stack.fp = fp;
}
}, {
key: 'sp',
get: function () {
return this.stack.sp;
},
set: function (sp) {
this.stack.sp = sp;
}
}]);
return VM;
}();
function _classCallCheck$14(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var TemplateIterator = function () {
function TemplateIterator(vm) {
_classCallCheck$14(this, TemplateIterator);
this.vm = vm;
}
TemplateIterator.prototype.next = function next() {
return this.vm.next();
};
return TemplateIterator;
}();
var clientId = 0;
function templateFactory(_ref) {
var templateId = _ref.id,
meta = _ref.meta,
block = _ref.block;
var parsedBlock = void 0;
var id = templateId || 'client-' + clientId++;
var create = function (env, envMeta) {
var newMeta = envMeta ? (0, _util.assign)({}, envMeta, meta) : meta;
if (!parsedBlock) {
parsedBlock = JSON.parse(block);
}
return new ScannableTemplate(id, newMeta, env, parsedBlock);
};
return { id: id, meta: meta, create: create };
}
var ScannableTemplate = function () {
function ScannableTemplate(id, meta, env, rawBlock) {
_classCallCheck$14(this, ScannableTemplate);
this.id = id;
this.meta = meta;
this.env = env;
this.entryPoint = null;
this.layout = null;
this.partial = null;
this.block = null;
this.scanner = new Scanner(rawBlock, env);
this.symbols = rawBlock.symbols;
this.hasEval = rawBlock.hasEval;
}
ScannableTemplate.prototype.render = function render(self, appendTo, dynamicScope) {
var env = this.env;
var elementStack = ElementStack.forInitialRender(env, appendTo, null);
var compiled = this.asEntryPoint().compileDynamic(env);
var vm = VM.initial(env, self, dynamicScope, elementStack, compiled);
return new TemplateIterator(vm);
};
ScannableTemplate.prototype.asEntryPoint = function asEntryPoint() {
if (!this.entryPoint) this.entryPoint = this.scanner.scanEntryPoint(this.compilationMeta());
return this.entryPoint;
};
ScannableTemplate.prototype.asLayout = function asLayout(componentName, attrs) {
if (!this.layout) this.layout = this.scanner.scanLayout(this.compilationMeta(), attrs || _util.EMPTY_ARRAY, componentName);
return this.layout;
};
ScannableTemplate.prototype.asPartial = function asPartial() {
if (!this.partial) this.partial = this.scanner.scanEntryPoint(this.compilationMeta(true));
return this.partial;
};
ScannableTemplate.prototype.asBlock = function asBlock() {
if (!this.block) this.block = this.scanner.scanBlock(this.compilationMeta());
return this.block;
};
ScannableTemplate.prototype.compilationMeta = function compilationMeta() {
var asPartial = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
return { templateMeta: this.meta, symbols: this.symbols, asPartial: asPartial };
};
return ScannableTemplate;
}();
function _classCallCheck$32(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var DynamicVarReference = function () {
function DynamicVarReference(scope, nameRef) {
_classCallCheck$32(this, DynamicVarReference);
this.scope = scope;
this.nameRef = nameRef;
var varTag = this.varTag = _reference2.UpdatableTag.create(_reference2.CONSTANT_TAG);
this.tag = (0, _reference2.combine)([nameRef.tag, varTag]);
}
DynamicVarReference.prototype.value = function value() {
return this.getVar().value();
};
DynamicVarReference.prototype.get = function get(key) {
return this.getVar().get(key);
};
DynamicVarReference.prototype.getVar = function getVar() {
var name = String(this.nameRef.value());
var ref = this.scope.get(name);
this.varTag.inner.update(ref.tag);
return ref;
};
return DynamicVarReference;
}();
function getDynamicVar(vm, args) {
var scope = vm.dynamicScope();
var nameRef = args.positional.at(0);
return new DynamicVarReference(scope, nameRef);
}
function _classCallCheck$33(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var PartialDefinition = function PartialDefinition(name, // for debugging
template) {
_classCallCheck$33(this, PartialDefinition);
this.name = name;
this.template = template;
};
var NodeType;
(function (NodeType) {
NodeType[NodeType["Element"] = 0] = "Element";
NodeType[NodeType["Attribute"] = 1] = "Attribute";
NodeType[NodeType["Text"] = 2] = "Text";
NodeType[NodeType["CdataSection"] = 3] = "CdataSection";
NodeType[NodeType["EntityReference"] = 4] = "EntityReference";
NodeType[NodeType["Entity"] = 5] = "Entity";
NodeType[NodeType["ProcessingInstruction"] = 6] = "ProcessingInstruction";
NodeType[NodeType["Comment"] = 7] = "Comment";
NodeType[NodeType["Document"] = 8] = "Document";
NodeType[NodeType["DocumentType"] = 9] = "DocumentType";
NodeType[NodeType["DocumentFragment"] = 10] = "DocumentFragment";
NodeType[NodeType["Notation"] = 11] = "Notation";
})(NodeType || (NodeType = {}));
var interfaces = Object.freeze({
get NodeType() {
return NodeType;
}
});
exports.Simple = interfaces;
exports.templateFactory = templateFactory;
exports.NULL_REFERENCE = NULL_REFERENCE;
exports.UNDEFINED_REFERENCE = UNDEFINED_REFERENCE;
exports.PrimitiveReference = PrimitiveReference;
exports.ConditionalReference = ConditionalReference;
exports.OpcodeBuilderDSL = OpcodeBuilder;
exports.compileLayout = compileLayout;
exports.CompiledStaticTemplate = CompiledStaticTemplate;
exports.CompiledDynamicTemplate = CompiledDynamicTemplate;
exports.IAttributeManager = AttributeManager;
exports.AttributeManager = AttributeManager;
exports.PropertyManager = PropertyManager;
exports.INPUT_VALUE_PROPERTY_MANAGER = INPUT_VALUE_PROPERTY_MANAGER;
exports.defaultManagers = defaultManagers;
exports.defaultAttributeManagers = defaultAttributeManagers;
exports.defaultPropertyManagers = defaultPropertyManagers;
exports.readDOMAttr = readDOMAttr;
exports.Register = Register;
exports.debugSlice = debugSlice;
exports.normalizeTextValue = normalizeTextValue;
exports.setDebuggerCallback = setDebuggerCallback;
exports.resetDebuggerCallback = resetDebuggerCallback;
exports.getDynamicVar = getDynamicVar;
exports.BlockMacros = Blocks;
exports.InlineMacros = Inlines;
exports.compileList = compileList;
exports.compileExpression = expr;
exports.UpdatingVM = UpdatingVM;
exports.RenderResult = RenderResult;
exports.isSafeString = isSafeString;
exports.Scope = Scope;
exports.Environment = Environment;
exports.PartialDefinition = PartialDefinition;
exports.ComponentDefinition = ComponentDefinition;
exports.isComponentDefinition = isComponentDefinition;
exports.DOMChanges = helper$1;
exports.IDOMChanges = DOMChanges;
exports.DOMTreeConstruction = DOMTreeConstruction;
exports.isWhitespace = isWhitespace;
exports.insertHTMLBefore = _insertHTMLBefore;
exports.ElementStack = ElementStack;
exports.ConcreteBounds = ConcreteBounds;
});
enifed('@glimmer/util', ['exports'], function (exports) {
'use strict';
// There is a small whitelist of namespaced attributes specially
// enumerated in
// https://www.w3.org/TR/html/syntax.html#attributes-0
//
// > When a foreign element has one of the namespaced attributes given by
// > the local name and namespace of the first and second cells of a row
// > from the following table, it must be written using the name given by
// > the third cell from the same row.
//
// In all other cases, colons are interpreted as a regular character
// with no special meaning:
//
// > No other namespaced attribute can be expressed in the HTML syntax.
var XLINK = 'http://www.w3.org/1999/xlink';
var XML = 'http://www.w3.org/XML/1998/namespace';
var XMLNS = 'http://www.w3.org/2000/xmlns/';
var WHITELIST = {
'xlink:actuate': XLINK,
'xlink:arcrole': XLINK,
'xlink:href': XLINK,
'xlink:role': XLINK,
'xlink:show': XLINK,
'xlink:title': XLINK,
'xlink:type': XLINK,
'xml:base': XML,
'xml:lang': XML,
'xml:space': XML,
'xmlns': XMLNS,
'xmlns:xlink': XMLNS
};
function getAttrNamespace(attrName) {
return WHITELIST[attrName] || null;
}
function unwrap(val) {
if (val === null || val === undefined) throw new Error('Expected value to be present');
return val;
}
function expect(val, message) {
if (val === null || val === undefined) throw new Error(message);
return val;
}
function unreachable() {
return new Error('unreachable');
}
function typePos(lastOperand) {
return lastOperand - 4;
}
// import Logger from './logger';
// let alreadyWarned = false;
// import Logger from './logger';
function debugAssert(test, msg) {
// if (!alreadyWarned) {
// alreadyWarned = true;
// Logger.warn("Don't leave debug assertions on in public builds");
// }
if (!test) {
throw new Error(msg || "assertion failure");
}
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var LogLevel;
(function (LogLevel) {
LogLevel[LogLevel["Trace"] = 0] = "Trace";
LogLevel[LogLevel["Debug"] = 1] = "Debug";
LogLevel[LogLevel["Warn"] = 2] = "Warn";
LogLevel[LogLevel["Error"] = 3] = "Error";
})(LogLevel || (exports.LogLevel = LogLevel = {}));
var NullConsole = function () {
function NullConsole() {
_classCallCheck(this, NullConsole);
}
NullConsole.prototype.log = function log(_message) {};
NullConsole.prototype.warn = function warn(_message) {};
NullConsole.prototype.error = function error(_message) {};
NullConsole.prototype.trace = function trace() {};
return NullConsole;
}();
var ALWAYS = void 0;
var Logger = function () {
function Logger(_ref) {
var console = _ref.console,
level = _ref.level;
_classCallCheck(this, Logger);
this.f = ALWAYS;
this.force = ALWAYS;
this.console = console;
this.level = level;
}
Logger.prototype.skipped = function skipped(level) {
return level < this.level;
};
Logger.prototype.trace = function trace(message) {
var _ref2 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
_ref2$stackTrace = _ref2.stackTrace,
stackTrace = _ref2$stackTrace === undefined ? false : _ref2$stackTrace;
if (this.skipped(LogLevel.Trace)) return;
this.console.log(message);
if (stackTrace) this.console.trace();
};
Logger.prototype.debug = function debug(message) {
var _ref3 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
_ref3$stackTrace = _ref3.stackTrace,
stackTrace = _ref3$stackTrace === undefined ? false : _ref3$stackTrace;
if (this.skipped(LogLevel.Debug)) return;
this.console.log(message);
if (stackTrace) this.console.trace();
};
Logger.prototype.warn = function warn(message) {
var _ref4 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
_ref4$stackTrace = _ref4.stackTrace,
stackTrace = _ref4$stackTrace === undefined ? false : _ref4$stackTrace;
if (this.skipped(LogLevel.Warn)) return;
this.console.warn(message);
if (stackTrace) this.console.trace();
};
Logger.prototype.error = function error(message) {
if (this.skipped(LogLevel.Error)) return;
this.console.error(message);
};
return Logger;
}();
var _console = typeof console === 'undefined' ? new NullConsole() : console;
ALWAYS = new Logger({ console: _console, level: LogLevel.Trace });
var LOG_LEVEL = LogLevel.Debug;
var logger = new Logger({ console: _console, level: LOG_LEVEL });
var objKeys = Object.keys;
function assign(obj) {
for (var i = 1; i < arguments.length; i++) {
var assignment = arguments[i];
if (assignment === null || typeof assignment !== 'object') continue;
var keys = objKeys(assignment);
for (var j = 0; j < keys.length; j++) {
var key = keys[j];
obj[key] = assignment[key];
}
}
return obj;
}
function fillNulls(count) {
var arr = new Array(count);
for (var i = 0; i < count; i++) {
arr[i] = null;
}
return arr;
}
var GUID = 0;
function initializeGuid(object) {
return object._guid = ++GUID;
}
function ensureGuid(object) {
return object._guid || initializeGuid(object);
}
function _classCallCheck$1(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var proto = Object.create(null, {
// without this, we will always still end up with (new
// EmptyObject()).constructor === Object
constructor: {
value: undefined,
enumerable: false,
writable: true
}
});
function EmptyObject() {}
EmptyObject.prototype = proto;
function dict() {
// let d = Object.create(null);
// d.x = 1;
// delete d.x;
// return d;
return new EmptyObject();
}
var DictSet = function () {
function DictSet() {
_classCallCheck$1(this, DictSet);
this.dict = dict();
}
DictSet.prototype.add = function add(obj) {
if (typeof obj === 'string') this.dict[obj] = obj;else this.dict[ensureGuid(obj)] = obj;
return this;
};
DictSet.prototype.delete = function _delete(obj) {
if (typeof obj === 'string') delete this.dict[obj];else if (obj._guid) delete this.dict[obj._guid];
};
DictSet.prototype.forEach = function forEach(callback) {
var dict = this.dict;
var dictKeys = Object.keys(dict);
for (var i = 0; dictKeys.length; i++) {
callback(dict[dictKeys[i]]);
}
};
DictSet.prototype.toArray = function toArray() {
return Object.keys(this.dict);
};
return DictSet;
}();
var Stack = function () {
function Stack() {
_classCallCheck$1(this, Stack);
this.stack = [];
this.current = null;
}
Stack.prototype.toArray = function toArray() {
return this.stack;
};
Stack.prototype.push = function push(item) {
this.current = item;
this.stack.push(item);
};
Stack.prototype.pop = function pop() {
var item = this.stack.pop();
var len = this.stack.length;
this.current = len === 0 ? null : this.stack[len - 1];
return item === undefined ? null : item;
};
Stack.prototype.isEmpty = function isEmpty() {
return this.stack.length === 0;
};
return Stack;
}();
function _classCallCheck$2(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var ListNode = function ListNode(value) {
_classCallCheck$2(this, ListNode);
this.next = null;
this.prev = null;
this.value = value;
};
var LinkedList = function () {
function LinkedList() {
_classCallCheck$2(this, LinkedList);
this.clear();
}
LinkedList.fromSlice = function fromSlice(slice) {
var list = new LinkedList();
slice.forEachNode(function (n) {
return list.append(n.clone());
});
return list;
};
LinkedList.prototype.head = function head() {
return this._head;
};
LinkedList.prototype.tail = function tail() {
return this._tail;
};
LinkedList.prototype.clear = function clear() {
this._head = this._tail = null;
};
LinkedList.prototype.isEmpty = function isEmpty() {
return this._head === null;
};
LinkedList.prototype.toArray = function toArray() {
var out = [];
this.forEachNode(function (n) {
return out.push(n);
});
return out;
};
LinkedList.prototype.splice = function splice(start, end, reference) {
var before = void 0;
if (reference === null) {
before = this._tail;
this._tail = end;
} else {
before = reference.prev;
end.next = reference;
reference.prev = end;
}
if (before) {
before.next = start;
start.prev = before;
}
};
LinkedList.prototype.nextNode = function nextNode(node) {
return node.next;
};
LinkedList.prototype.prevNode = function prevNode(node) {
return node.prev;
};
LinkedList.prototype.forEachNode = function forEachNode(callback) {
var node = this._head;
while (node !== null) {
callback(node);
node = node.next;
}
};
LinkedList.prototype.contains = function contains(needle) {
var node = this._head;
while (node !== null) {
if (node === needle) return true;
node = node.next;
}
return false;
};
LinkedList.prototype.insertBefore = function insertBefore(node) {
var reference = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
if (reference === null) return this.append(node);
if (reference.prev) reference.prev.next = node;else this._head = node;
node.prev = reference.prev;
node.next = reference;
reference.prev = node;
return node;
};
LinkedList.prototype.append = function append(node) {
var tail = this._tail;
if (tail) {
tail.next = node;
node.prev = tail;
node.next = null;
} else {
this._head = node;
}
return this._tail = node;
};
LinkedList.prototype.pop = function pop() {
if (this._tail) return this.remove(this._tail);
return null;
};
LinkedList.prototype.prepend = function prepend(node) {
if (this._head) return this.insertBefore(node, this._head);
return this._head = this._tail = node;
};
LinkedList.prototype.remove = function remove(node) {
if (node.prev) node.prev.next = node.next;else this._head = node.next;
if (node.next) node.next.prev = node.prev;else this._tail = node.prev;
return node;
};
return LinkedList;
}();
var ListSlice = function () {
function ListSlice(head, tail) {
_classCallCheck$2(this, ListSlice);
this._head = head;
this._tail = tail;
}
ListSlice.toList = function toList(slice) {
var list = new LinkedList();
slice.forEachNode(function (n) {
return list.append(n.clone());
});
return list;
};
ListSlice.prototype.forEachNode = function forEachNode(callback) {
var node = this._head;
while (node !== null) {
callback(node);
node = this.nextNode(node);
}
};
ListSlice.prototype.contains = function contains(needle) {
var node = this._head;
while (node !== null) {
if (node === needle) return true;
node = node.next;
}
return false;
};
ListSlice.prototype.head = function head() {
return this._head;
};
ListSlice.prototype.tail = function tail() {
return this._tail;
};
ListSlice.prototype.toArray = function toArray() {
var out = [];
this.forEachNode(function (n) {
return out.push(n);
});
return out;
};
ListSlice.prototype.nextNode = function nextNode(node) {
if (node === this._tail) return null;
return node.next;
};
ListSlice.prototype.prevNode = function prevNode(node) {
if (node === this._head) return null;
return node.prev;
};
ListSlice.prototype.isEmpty = function isEmpty() {
return false;
};
return ListSlice;
}();
var EMPTY_SLICE = new ListSlice(null, null);
var HAS_NATIVE_WEAKMAP = function () {
// detect if `WeakMap` is even present
var hasWeakMap = typeof WeakMap === 'function';
if (!hasWeakMap) {
return false;
}
var instance = new WeakMap();
// use `Object`'s `.toString` directly to prevent us from detecting
// polyfills as native weakmaps
return Object.prototype.toString.call(instance) === '[object WeakMap]';
}();
var HAS_TYPED_ARRAYS = typeof Uint32Array !== 'undefined';
var A = void 0;
if (HAS_TYPED_ARRAYS) {
A = Uint32Array;
} else {
A = Array;
}
var A$1 = A;
var EMPTY_ARRAY = HAS_NATIVE_WEAKMAP ? Object.freeze([]) : [];
exports.getAttrNamespace = getAttrNamespace;
exports.assert = debugAssert;
exports.LOGGER = logger;
exports.Logger = Logger;
exports.LogLevel = LogLevel;
exports.assign = assign;
exports.fillNulls = fillNulls;
exports.ensureGuid = ensureGuid;
exports.initializeGuid = initializeGuid;
exports.Stack = Stack;
exports.DictSet = DictSet;
exports.dict = dict;
exports.EMPTY_SLICE = EMPTY_SLICE;
exports.LinkedList = LinkedList;
exports.ListNode = ListNode;
exports.ListSlice = ListSlice;
exports.A = A$1;
exports.EMPTY_ARRAY = EMPTY_ARRAY;
exports.HAS_NATIVE_WEAKMAP = HAS_NATIVE_WEAKMAP;
exports.unwrap = unwrap;
exports.expect = expect;
exports.unreachable = unreachable;
exports.typePos = typePos;
});
enifed("@glimmer/wire-format", ["exports"], function (exports) {
"use strict";
var Opcodes;
(function (Opcodes) {
// Statements
Opcodes[Opcodes["Text"] = 0] = "Text";
Opcodes[Opcodes["Append"] = 1] = "Append";
Opcodes[Opcodes["Comment"] = 2] = "Comment";
Opcodes[Opcodes["Modifier"] = 3] = "Modifier";
Opcodes[Opcodes["Block"] = 4] = "Block";
Opcodes[Opcodes["Component"] = 5] = "Component";
Opcodes[Opcodes["OpenElement"] = 6] = "OpenElement";
Opcodes[Opcodes["FlushElement"] = 7] = "FlushElement";
Opcodes[Opcodes["CloseElement"] = 8] = "CloseElement";
Opcodes[Opcodes["StaticAttr"] = 9] = "StaticAttr";
Opcodes[Opcodes["DynamicAttr"] = 10] = "DynamicAttr";
Opcodes[Opcodes["Yield"] = 11] = "Yield";
Opcodes[Opcodes["Partial"] = 12] = "Partial";
Opcodes[Opcodes["DynamicArg"] = 13] = "DynamicArg";
Opcodes[Opcodes["StaticArg"] = 14] = "StaticArg";
Opcodes[Opcodes["TrustingAttr"] = 15] = "TrustingAttr";
Opcodes[Opcodes["Debugger"] = 16] = "Debugger";
Opcodes[Opcodes["ClientSideStatement"] = 17] = "ClientSideStatement";
// Expressions
Opcodes[Opcodes["Unknown"] = 18] = "Unknown";
Opcodes[Opcodes["Get"] = 19] = "Get";
Opcodes[Opcodes["MaybeLocal"] = 20] = "MaybeLocal";
Opcodes[Opcodes["FixThisBeforeWeMerge"] = 21] = "FixThisBeforeWeMerge";
Opcodes[Opcodes["HasBlock"] = 22] = "HasBlock";
Opcodes[Opcodes["HasBlockParams"] = 23] = "HasBlockParams";
Opcodes[Opcodes["Undefined"] = 24] = "Undefined";
Opcodes[Opcodes["Helper"] = 25] = "Helper";
Opcodes[Opcodes["Concat"] = 26] = "Concat";
Opcodes[Opcodes["ClientSideExpression"] = 27] = "ClientSideExpression";
})(Opcodes || (exports.Ops = Opcodes = {}));
function is(variant) {
return function (value) {
return Array.isArray(value) && value[0] === variant;
};
}
var Expressions;
(function (Expressions) {
Expressions.isUnknown = is(Opcodes.Unknown);
Expressions.isGet = is(Opcodes.Get);
Expressions.isConcat = is(Opcodes.Concat);
Expressions.isHelper = is(Opcodes.Helper);
Expressions.isHasBlock = is(Opcodes.HasBlock);
Expressions.isHasBlockParams = is(Opcodes.HasBlockParams);
Expressions.isUndefined = is(Opcodes.Undefined);
Expressions.isClientSide = is(Opcodes.ClientSideExpression);
Expressions.isMaybeLocal = is(Opcodes.MaybeLocal);
function isPrimitiveValue(value) {
if (value === null) {
return true;
}
return typeof value !== 'object';
}
Expressions.isPrimitiveValue = isPrimitiveValue;
})(Expressions || (exports.Expressions = Expressions = {}));
var Statements;
(function (Statements) {
Statements.isText = is(Opcodes.Text);
Statements.isAppend = is(Opcodes.Append);
Statements.isComment = is(Opcodes.Comment);
Statements.isModifier = is(Opcodes.Modifier);
Statements.isBlock = is(Opcodes.Block);
Statements.isComponent = is(Opcodes.Component);
Statements.isOpenElement = is(Opcodes.OpenElement);
Statements.isFlushElement = is(Opcodes.FlushElement);
Statements.isCloseElement = is(Opcodes.CloseElement);
Statements.isStaticAttr = is(Opcodes.StaticAttr);
Statements.isDynamicAttr = is(Opcodes.DynamicAttr);
Statements.isYield = is(Opcodes.Yield);
Statements.isPartial = is(Opcodes.Partial);
Statements.isDynamicArg = is(Opcodes.DynamicArg);
Statements.isStaticArg = is(Opcodes.StaticArg);
Statements.isTrustingAttr = is(Opcodes.TrustingAttr);
Statements.isDebugger = is(Opcodes.Debugger);
Statements.isClientSide = is(Opcodes.ClientSideStatement);
function isAttribute(val) {
return val[0] === Opcodes.StaticAttr || val[0] === Opcodes.DynamicAttr || val[0] === Opcodes.TrustingAttr;
}
Statements.isAttribute = isAttribute;
function isArgument(val) {
return val[0] === Opcodes.StaticArg || val[0] === Opcodes.DynamicArg;
}
Statements.isArgument = isArgument;
function isParameter(val) {
return isAttribute(val) || isArgument(val);
}
Statements.isParameter = isParameter;
function getParameterName(s) {
return s[1];
}
Statements.getParameterName = getParameterName;
})(Statements || (exports.Statements = Statements = {}));
exports.is = is;
exports.Expressions = Expressions;
exports.Statements = Statements;
exports.Ops = Opcodes;
});
enifed('backburner', ['exports', 'ember-babel'], function (exports, _emberBabel) {
'use strict';
var NUMBER = /\d+/;
function isString(suspect) {
return typeof suspect === 'string';
}
function isFunction(suspect) {
return typeof suspect === 'function';
}
function isNumber(suspect) {
return typeof suspect === 'number';
}
function isCoercableNumber(suspect) {
return isNumber(suspect) && suspect === suspect || NUMBER.test(suspect);
}
function noSuchQueue(name) {
throw new Error('You attempted to schedule an action in a queue (' + name + ') that doesn\'t exist');
}
function noSuchMethod(name) {
throw new Error('You attempted to schedule an action in a queue (' + name + ') for a method that doesn\'t exist');
}
function getOnError(options) {
return options.onError || options.onErrorTarget && options.onErrorTarget[options.onErrorMethod];
}
function findItem(target, method, collection) {
var index = -1;
for (var i = 0, l = collection.length; i < l; i += 4) {
if (collection[i] === target && collection[i + 1] === method) {
index = i;
break;
}
}
return index;
}
function findTimer(timer, collection) {
var index = -1;
for (var i = 3; i < collection.length; i += 4) {
if (collection[i] === timer) {
index = i - 3;
break;
}
}
return index;
}
function binarySearch(time, timers) {
var start = 0;
var end = timers.length - 2;
var middle = void 0;
var l = void 0;
while (start < end) {
// since timers is an array of pairs 'l' will always
// be an integer
l = (end - start) / 2;
// compensate for the index in case even number
// of pairs inside timers
middle = start + l - l % 2;
if (time >= timers[middle]) {
start = middle + 2;
} else {
end = middle;
}
}
return time >= timers[start] ? start + 2 : start;
}
var Queue = function () {
function Queue(name) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var globalOptions = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
(0, _emberBabel.classCallCheck)(this, Queue);
this._queueBeingFlushed = [];
this.targetQueues = Object.create(null);
this.index = 0;
this._queue = [];
this.name = name;
this.options = options;
this.globalOptions = globalOptions;
}
Queue.prototype.push = function push(target, method, args, stack) {
this._queue.push(target, method, args, stack);
return {
queue: this,
target: target,
method: method
};
};
Queue.prototype.pushUnique = function pushUnique(target, method, args, stack) {
var guid = this.guidForTarget(target);
if (guid) {
this.pushUniqueWithGuid(guid, target, method, args, stack);
} else {
this.pushUniqueWithoutGuid(target, method, args, stack);
}
return {
queue: this,
target: target,
method: method
};
};
Queue.prototype.flush = function flush(sync) {
var _options = this.options,
before = _options.before,
after = _options.after;
var target = void 0;
var method = void 0;
var args = void 0;
var errorRecordedForStack = void 0;
this.targetQueues = Object.create(null);
if (this._queueBeingFlushed.length === 0) {
this._queueBeingFlushed = this._queue;
this._queue = [];
}
if (before !== undefined) {
before();
}
var invoke = void 0;
var queueItems = this._queueBeingFlushed;
if (queueItems.length > 0) {
var onError = getOnError(this.globalOptions);
invoke = onError ? this.invokeWithOnError : this.invoke;
for (var i = this.index; i < queueItems.length; i += 4) {
this.index += 4;
method = queueItems[i + 1];
// method could have been nullified / canceled during flush
if (method !== null) {
//
// ** Attention intrepid developer **
//
// To find out the stack of this task when it was scheduled onto
// the run loop, add the following to your app.js:
//
// Ember.run.backburner.DEBUG = true; // NOTE: This slows your app, don't leave it on in production.
//
// Once that is in place, when you are at a breakpoint and navigate
// here in the stack explorer, you can look at `errorRecordedForStack.stack`,
// which will be the captured stack when this job was scheduled.
//
// One possible long-term solution is the following Chrome issue:
// https://bugs.chromium.org/p/chromium/issues/detail?id=332624
//
target = queueItems[i];
args = queueItems[i + 2];
errorRecordedForStack = queueItems[i + 3]; // Debugging assistance
invoke(target, method, args, onError, errorRecordedForStack);
}
if (this.index !== this._queueBeingFlushed.length && this.globalOptions.mustYield && this.globalOptions.mustYield()) {
return 1 /* Pause */;
}
}
}
if (after !== undefined) {
after();
}
this._queueBeingFlushed.length = 0;
this.index = 0;
if (sync !== false && this._queue.length > 0) {
// check if new items have been added
this.flush(true);
}
};
Queue.prototype.hasWork = function hasWork() {
return this._queueBeingFlushed.length > 0 || this._queue.length > 0;
};
Queue.prototype.cancel = function cancel(_ref) {
var target = _ref.target,
method = _ref.method;
var queue = this._queue;
var guid = this.guidForTarget(target);
var targetQueue = guid ? this.targetQueues[guid] : undefined;
if (targetQueue !== undefined) {
var t = void 0;
for (var i = 0, l = targetQueue.length; i < l; i += 2) {
t = targetQueue[i];
if (t === method) {
targetQueue.splice(i, 2);
break;
}
}
}
var index = findItem(target, method, queue);
if (index > -1) {
queue.splice(index, 4);
return true;
}
// if not found in current queue
// could be in the queue that is being flushed
queue = this._queueBeingFlushed;
index = findItem(target, method, queue);
if (index > -1) {
queue[index + 1] = null;
return true;
}
return false;
};
Queue.prototype.guidForTarget = function guidForTarget(target) {
if (!target) {
return;
}
var peekGuid = this.globalOptions.peekGuid;
if (peekGuid) {
return peekGuid(target);
}
var KEY = this.globalOptions.GUID_KEY;
if (KEY) {
return target[KEY];
}
};
Queue.prototype.pushUniqueWithoutGuid = function pushUniqueWithoutGuid(target, method, args, stack) {
var queue = this._queue;
var index = findItem(target, method, queue);
if (index > -1) {
queue[index + 2] = args; // replace args
queue[index + 3] = stack; // replace stack
} else {
queue.push(target, method, args, stack);
}
};
Queue.prototype.targetQueue = function targetQueue(_targetQueue, target, method, args, stack) {
var queue = this._queue;
for (var i = 0, l = _targetQueue.length; i < l; i += 2) {
var currentMethod = _targetQueue[i];
if (currentMethod === method) {
var currentIndex = _targetQueue[i + 1];
queue[currentIndex + 2] = args; // replace args
queue[currentIndex + 3] = stack; // replace stack
return;
}
}
_targetQueue.push(method, queue.push(target, method, args, stack) - 4);
};
Queue.prototype.pushUniqueWithGuid = function pushUniqueWithGuid(guid, target, method, args, stack) {
var localQueue = this.targetQueues[guid];
if (localQueue !== undefined) {
this.targetQueue(localQueue, target, method, args, stack);
} else {
this.targetQueues[guid] = [method, this._queue.push(target, method, args, stack) - 4];
}
};
Queue.prototype.invoke = function invoke(target, method, args /*, onError, errorRecordedForStack */) {
if (args !== undefined) {
method.apply(target, args);
} else {
method.call(target);
}
};
Queue.prototype.invokeWithOnError = function invokeWithOnError(target, method, args, onError, errorRecordedForStack) {
try {
if (args !== undefined) {
method.apply(target, args);
} else {
method.call(target);
}
} catch (error) {
onError(error, errorRecordedForStack);
}
};
return Queue;
}();
var DeferredActionQueues = function () {
function DeferredActionQueues() {
var queueNames = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
var options = arguments[1];
(0, _emberBabel.classCallCheck)(this, DeferredActionQueues);
this.queues = {};
this.queueNameIndex = 0;
this.queueNames = queueNames;
queueNames.reduce(function (queues, queueName) {
queues[queueName] = new Queue(queueName, options[queueName], options);
return queues;
}, this.queues);
}
/*
@method schedule
@param {String} queueName
@param {Any} target
@param {Any} method
@param {Any} args
@param {Boolean} onceFlag
@param {Any} stack
@return queue
*/
DeferredActionQueues.prototype.schedule = function schedule(queueName, target, method, args, onceFlag, stack) {
var queues = this.queues;
var queue = queues[queueName];
if (!queue) {
noSuchQueue(queueName);
}
if (!method) {
noSuchMethod(queueName);
}
if (onceFlag) {
return queue.pushUnique(target, method, args, stack);
} else {
return queue.push(target, method, args, stack);
}
};
DeferredActionQueues.prototype.flush = function flush() {
var queue = void 0;
var queueName = void 0;
var numberOfQueues = this.queueNames.length;
while (this.queueNameIndex < numberOfQueues) {
queueName = this.queueNames[this.queueNameIndex];
queue = this.queues[queueName];
if (queue.hasWork() === false) {
this.queueNameIndex++;
} else {
if (queue.flush(false /* async */) === 1 /* Pause */) {
return 1 /* Pause */;
}
this.queueNameIndex = 0; // only reset to first queue if non-pause break
}
}
};
return DeferredActionQueues;
}();
// accepts a function that when invoked will return an iterator
// iterator will drain until completion
var iteratorDrain = function (fn) {
var iterator = fn();
var result = iterator.next();
while (result.done === false) {
result.value();
result = iterator.next();
}
};
var noop = function () {};
var SET_TIMEOUT = setTimeout;
function parseArgs() {
var length = arguments.length;
var method = void 0;
var target = void 0;
var args = void 0;
if (length === 1) {
method = arguments[0];
target = null;
} else {
target = arguments[0];
method = arguments[1];
if (isString(method)) {
method = target[method];
}
if (length > 2) {
args = new Array(length - 2);
for (var i = 0, l = length - 2; i < l; i++) {
args[i] = arguments[i + 2];
}
}
}
return [target, method, args];
}
var Backburner = function () {
function Backburner(queueNames) {
var _this = this;
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
(0, _emberBabel.classCallCheck)(this, Backburner);
this.DEBUG = false;
this.currentInstance = null;
this._timerTimeoutId = null;
this._autorun = null;
this.queueNames = queueNames;
this.options = options;
if (!this.options.defaultQueue) {
this.options.defaultQueue = queueNames[0];
}
this.instanceStack = [];
this._timers = [];
this._debouncees = [];
this._throttlers = [];
this._eventCallbacks = {
end: [],
begin: []
};
this._onBegin = this.options.onBegin || noop;
this._onEnd = this.options.onEnd || noop;
var _platform = this.options._platform || {};
var platform = Object.create(null);
platform.setTimeout = _platform.setTimeout || function (fn, ms) {
return setTimeout(fn, ms);
};
platform.clearTimeout = _platform.clearTimeout || function (id) {
return clearTimeout(id);
};
platform.next = _platform.next || function (fn) {
return SET_TIMEOUT(fn, 0);
};
platform.clearNext = _platform.clearNext || platform.clearTimeout;
platform.now = _platform.now || function () {
return Date.now();
};
this._platform = platform;
this._boundRunExpiredTimers = function () {
_this._runExpiredTimers();
};
this._boundAutorunEnd = function () {
_this._autorun = null;
_this.end();
};
}
/*
@method begin
@return instantiated class DeferredActionQueues
*/
Backburner.prototype.begin = function begin() {
var options = this.options;
var previousInstance = this.currentInstance;
var current = void 0;
if (this._autorun !== null) {
current = previousInstance;
this._cancelAutorun();
} else {
if (previousInstance !== null) {
this.instanceStack.push(previousInstance);
}
current = this.currentInstance = new DeferredActionQueues(this.queueNames, options);
this._trigger('begin', current, previousInstance);
}
this._onBegin(current, previousInstance);
return current;
};
Backburner.prototype.end = function end() {
var currentInstance = this.currentInstance;
var nextInstance = null;
if (currentInstance === null) {
throw new Error('end called without begin');
}
// Prevent double-finally bug in Safari 6.0.2 and iOS 6
// This bug appears to be resolved in Safari 6.0.5 and iOS 7
var finallyAlreadyCalled = false;
var result = void 0;
try {
result = currentInstance.flush();
} finally {
if (!finallyAlreadyCalled) {
finallyAlreadyCalled = true;
if (result === 1 /* Pause */) {
var next = this._platform.next;
this._autorun = next(this._boundAutorunEnd);
} else {
this.currentInstance = null;
if (this.instanceStack.length > 0) {
nextInstance = this.instanceStack.pop();
this.currentInstance = nextInstance;
}
this._trigger('end', currentInstance, nextInstance);
this._onEnd(currentInstance, nextInstance);
}
}
}
};
Backburner.prototype.on = function on(eventName, callback) {
if (typeof callback !== 'function') {
throw new TypeError('Callback must be a function');
}
var callbacks = this._eventCallbacks[eventName];
if (callbacks !== undefined) {
callbacks.push(callback);
} else {
throw new TypeError('Cannot on() event ' + eventName + ' because it does not exist');
}
};
Backburner.prototype.off = function off(eventName, callback) {
var callbacks = this._eventCallbacks[eventName];
if (!eventName || callbacks === undefined) {
throw new TypeError('Cannot off() event ' + eventName + ' because it does not exist');
}
var callbackFound = false;
if (callback) {
for (var i = 0; i < callbacks.length; i++) {
if (callbacks[i] === callback) {
callbackFound = true;
callbacks.splice(i, 1);
i--;
}
}
}
if (!callbackFound) {
throw new TypeError('Cannot off() callback that does not exist');
}
};
Backburner.prototype.run = function run() {
var _parseArgs = parseArgs.apply(undefined, arguments),
target = _parseArgs[0],
method = _parseArgs[1],
args = _parseArgs[2];
return this._run(target, method, args);
};
Backburner.prototype.join = function join() {
var _parseArgs2 = parseArgs.apply(undefined, arguments),
target = _parseArgs2[0],
method = _parseArgs2[1],
args = _parseArgs2[2];
return this._join(target, method, args);
};
Backburner.prototype.defer = function defer() {
return this.schedule.apply(this, arguments);
};
Backburner.prototype.schedule = function schedule(queueName) {
for (var _len = arguments.length, _args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
_args[_key - 1] = arguments[_key];
}
var _parseArgs3 = parseArgs.apply(undefined, _args),
target = _parseArgs3[0],
method = _parseArgs3[1],
args = _parseArgs3[2];
var stack = this.DEBUG ? new Error() : undefined;
return this._ensureInstance().schedule(queueName, target, method, args, false, stack);
};
Backburner.prototype.scheduleIterable = function scheduleIterable(queueName, iterable) {
var stack = this.DEBUG ? new Error() : undefined;
return this._ensureInstance().schedule(queueName, null, iteratorDrain, [iterable], false, stack);
};
Backburner.prototype.deferOnce = function deferOnce() {
return this.scheduleOnce.apply(this, arguments);
};
Backburner.prototype.scheduleOnce = function scheduleOnce(queueName) {
for (var _len2 = arguments.length, _args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
_args[_key2 - 1] = arguments[_key2];
}
var _parseArgs4 = parseArgs.apply(undefined, _args),
target = _parseArgs4[0],
method = _parseArgs4[1],
args = _parseArgs4[2];
var stack = this.DEBUG ? new Error() : undefined;
return this._ensureInstance().schedule(queueName, target, method, args, true, stack);
};
Backburner.prototype.setTimeout = function setTimeout() {
return this.later.apply(this, arguments);
};
Backburner.prototype.later = function later() {
for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
args[_key3] = arguments[_key3];
}
var length = args.length;
var wait = 0;
var method = void 0;
var target = void 0;
var methodOrTarget = void 0;
var methodOrWait = void 0;
var methodOrArgs = void 0;
if (length === 0) {
return;
} else if (length === 1) {
method = args.shift();
} else if (length === 2) {
methodOrTarget = args[0];
methodOrWait = args[1];
if (isFunction(methodOrWait)) {
target = args.shift();
method = args.shift();
} else if (methodOrTarget !== null && isString(methodOrWait) && methodOrWait in methodOrTarget) {
target = args.shift();
method = target[args.shift()];
} else if (isCoercableNumber(methodOrWait)) {
method = args.shift();
wait = parseInt(args.shift(), 10);
} else {
method = args.shift();
}
} else {
var last = args[args.length - 1];
if (isCoercableNumber(last)) {
wait = parseInt(args.pop(), 10);
}
methodOrTarget = args[0];
methodOrArgs = args[1];
if (isFunction(methodOrArgs)) {
target = args.shift();
method = args.shift();
} else if (methodOrTarget !== null && isString(methodOrArgs) && methodOrArgs in methodOrTarget) {
target = args.shift();
method = target[args.shift()];
} else {
method = args.shift();
}
}
var onError = getOnError(this.options);
var executeAt = this._platform.now() + wait;
var fn = void 0;
if (onError) {
fn = function () {
try {
method.apply(target, args);
} catch (e) {
onError(e);
}
};
} else {
fn = function () {
method.apply(target, args);
};
}
return this._setTimeout(fn, executeAt);
};
Backburner.prototype.throttle = function throttle(target, method) /*, ...args, wait, [immediate] */{
var _this2 = this;
for (var _len4 = arguments.length, args = Array(_len4 > 2 ? _len4 - 2 : 0), _key4 = 2; _key4 < _len4; _key4++) {
args[_key4 - 2] = arguments[_key4];
}
var immediate = args.pop();
var isImmediate = void 0;
var wait = void 0;
if (isCoercableNumber(immediate)) {
wait = immediate;
isImmediate = true;
} else {
wait = args.pop();
isImmediate = immediate === true;
}
if (isString(method)) {
method = target[method];
}
var index = findItem(target, method, this._throttlers);
if (index > -1) {
this._throttlers[index + 2] = args;
return this._throttlers[index + 3];
} // throttled
wait = parseInt(wait, 10);
var timer = this._platform.setTimeout(function () {
var i = findTimer(timer, _this2._throttlers);
var _throttlers$splice = _this2._throttlers.splice(i, 4),
context = _throttlers$splice[0],
func = _throttlers$splice[1],
params = _throttlers$splice[2];
if (isImmediate === false) {
_this2._run(context, func, params);
}
}, wait);
if (isImmediate) {
this._join(target, method, args);
}
this._throttlers.push(target, method, args, timer);
return timer;
};
Backburner.prototype.debounce = function debounce(target, method) /* , wait, [immediate] */{
var _this3 = this;
for (var _len5 = arguments.length, args = Array(_len5 > 2 ? _len5 - 2 : 0), _key5 = 2; _key5 < _len5; _key5++) {
args[_key5 - 2] = arguments[_key5];
}
var immediate = args.pop();
var isImmediate = void 0;
var wait = void 0;
if (isCoercableNumber(immediate)) {
wait = immediate;
isImmediate = false;
} else {
wait = args.pop();
isImmediate = immediate === true;
}
if (isString(method)) {
method = target[method];
}
wait = parseInt(wait, 10);
// Remove debouncee
var index = findItem(target, method, this._debouncees);
if (index > -1) {
var timerId = this._debouncees[index + 3];
this._platform.clearTimeout(timerId);
this._debouncees.splice(index, 4);
}
var timer = this._platform.setTimeout(function () {
var i = findTimer(timer, _this3._debouncees);
var _debouncees$splice = _this3._debouncees.splice(i, 4),
context = _debouncees$splice[0],
func = _debouncees$splice[1],
params = _debouncees$splice[2];
if (isImmediate === false) {
_this3._run(context, func, params);
}
}, wait);
if (isImmediate && index === -1) {
this._join(target, method, args);
}
this._debouncees.push(target, method, args, timer);
return timer;
};
Backburner.prototype.cancelTimers = function cancelTimers() {
for (var i = 3; i < this._throttlers.length; i += 4) {
this._platform.clearTimeout(this._throttlers[i]);
}
this._throttlers = [];
for (var t = 3; t < this._debouncees.length; t += 4) {
this._platform.clearTimeout(this._debouncees[t]);
}
this._debouncees = [];
this._clearTimerTimeout();
this._timers = [];
this._cancelAutorun();
};
Backburner.prototype.hasTimers = function hasTimers() {
return this._timers.length > 0 || this._debouncees.length > 0 || this._throttlers.length > 0 || this._autorun !== null;
};
Backburner.prototype.cancel = function cancel(timer) {
if (!timer) {
return false;
}
var timerType = typeof timer;
if (timerType === 'number' || timerType === 'string') {
return this._cancelItem(timer, this._throttlers) || this._cancelItem(timer, this._debouncees);
} else if (timerType === 'function') {
return this._cancelLaterTimer(timer);
} else if (timerType === 'object' && timer.queue && timer.method) {
return timer.queue.cancel(timer);
}
return false;
};
Backburner.prototype.ensureInstance = function ensureInstance() {
this._ensureInstance();
};
Backburner.prototype._join = function _join(target, method, args) {
if (this.currentInstance === null) {
return this._run(target, method, args);
}
if (target === undefined && args === undefined) {
return method();
} else {
return method.apply(target, args);
}
};
Backburner.prototype._run = function _run(target, method, args) {
var onError = getOnError(this.options);
this.begin();
if (onError) {
try {
return method.apply(target, args);
} catch (error) {
onError(error);
} finally {
this.end();
}
} else {
try {
return method.apply(target, args);
} finally {
this.end();
}
}
};
Backburner.prototype._cancelAutorun = function _cancelAutorun() {
if (this._autorun !== null) {
this._platform.clearNext(this._autorun);
this._autorun = null;
}
};
Backburner.prototype._setTimeout = function _setTimeout(fn, executeAt) {
if (this._timers.length === 0) {
this._timers.push(executeAt, fn);
this._installTimerTimeout();
return fn;
}
// find position to insert
var i = binarySearch(executeAt, this._timers);
this._timers.splice(i, 0, executeAt, fn);
// we should be the new earliest timer if i == 0
if (i === 0) {
this._reinstallTimerTimeout();
}
return fn;
};
Backburner.prototype._cancelLaterTimer = function _cancelLaterTimer(timer) {
for (var i = 1; i < this._timers.length; i += 2) {
if (this._timers[i] === timer) {
i = i - 1;
this._timers.splice(i, 2); // remove the two elements
if (i === 0) {
this._reinstallTimerTimeout();
}
return true;
}
}
return false;
};
Backburner.prototype._cancelItem = function _cancelItem(timer, array) {
var index = findTimer(timer, array);
if (index > -1) {
this._platform.clearTimeout(timer);
array.splice(index, 4);
return true;
}
return false;
};
Backburner.prototype._trigger = function _trigger(eventName, arg1, arg2) {
var callbacks = this._eventCallbacks[eventName];
if (callbacks !== undefined) {
for (var i = 0; i < callbacks.length; i++) {
callbacks[i](arg1, arg2);
}
}
};
Backburner.prototype._runExpiredTimers = function _runExpiredTimers() {
this._timerTimeoutId = null;
if (this._timers.length === 0) {
return;
}
this.begin();
this._scheduleExpiredTimers();
this.end();
};
Backburner.prototype._scheduleExpiredTimers = function _scheduleExpiredTimers() {
var timers = this._timers;
var l = timers.length;
var i = 0;
var defaultQueue = this.options.defaultQueue;
var n = this._platform.now();
for (; i < l; i += 2) {
var executeAt = timers[i];
if (executeAt <= n) {
var fn = timers[i + 1];
this.schedule(defaultQueue, null, fn);
} else {
break;
}
}
timers.splice(0, i);
this._installTimerTimeout();
};
Backburner.prototype._reinstallTimerTimeout = function _reinstallTimerTimeout() {
this._clearTimerTimeout();
this._installTimerTimeout();
};
Backburner.prototype._clearTimerTimeout = function _clearTimerTimeout() {
if (this._timerTimeoutId === null) {
return;
}
this._platform.clearTimeout(this._timerTimeoutId);
this._timerTimeoutId = null;
};
Backburner.prototype._installTimerTimeout = function _installTimerTimeout() {
if (this._timers.length === 0) {
return;
}
var minExpiresAt = this._timers[0];
var n = this._platform.now();
var wait = Math.max(0, minExpiresAt - n);
this._timerTimeoutId = this._platform.setTimeout(this._boundRunExpiredTimers, wait);
};
Backburner.prototype._ensureInstance = function _ensureInstance() {
var currentInstance = this.currentInstance;
if (currentInstance === null) {
currentInstance = this.begin();
var next = this._platform.next;
this._autorun = next(this._boundAutorunEnd);
}
return currentInstance;
};
return Backburner;
}();
Backburner.Queue = Queue;
exports.default = Backburner;
});
enifed('container', ['exports', 'ember-babel', 'ember-utils', 'ember-debug', 'ember/features'], function (exports, _emberBabel, _emberUtils, _emberDebug, _features) {
'use strict';
exports.Container = exports.privatize = exports.Registry = undefined;
/* globals Proxy */
var CONTAINER_OVERRIDE = (0, _emberUtils.symbol)('CONTAINER_OVERRIDE');
/**
A container used to instantiate and cache objects.
Every `Container` must be associated with a `Registry`, which is referenced
to determine the factory and options that should be used to instantiate
objects.
The public API for `Container` is still in flux and should not be considered
stable.
@private
@class Container
*/
var Container = function () {
function Container(registry) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
(0, _emberBabel.classCallCheck)(this, Container);
this.registry = registry;
this.owner = options.owner || null;
this.cache = (0, _emberUtils.dictionary)(options.cache || null);
this.factoryManagerCache = (0, _emberUtils.dictionary)(options.factoryManagerCache || null);
this[CONTAINER_OVERRIDE] = undefined;
this.isDestroyed = false;
if (true) {
this.validationCache = (0, _emberUtils.dictionary)(options.validationCache || null);
}
}
/**
@private
@property registry
@type Registry
@since 1.11.0
*/
/**
@private
@property cache
@type InheritingDict
*/
/**
@private
@property validationCache
@type InheritingDict
*/
/**
Given a fullName return a corresponding instance.
The default behavior is for lookup to return a singleton instance.
The singleton is scoped to the container, allowing multiple containers
to all have their own locally scoped singletons.
```javascript
let registry = new Registry();
let container = registry.container();
registry.register('api:twitter', Twitter);
let twitter = container.lookup('api:twitter');
twitter instanceof Twitter; // => true
// by default the container will return singletons
let twitter2 = container.lookup('api:twitter');
twitter2 instanceof Twitter; // => true
twitter === twitter2; //=> true
```
If singletons are not wanted, an optional flag can be provided at lookup.
```javascript
let registry = new Registry();
let container = registry.container();
registry.register('api:twitter', Twitter);
let twitter = container.lookup('api:twitter', { singleton: false });
let twitter2 = container.lookup('api:twitter', { singleton: false });
twitter === twitter2; //=> false
```
@private
@method lookup
@param {String} fullName
@param {Object} [options]
@param {String} [options.source] The fullname of the request source (used for local lookup)
@return {any}
*/
Container.prototype.lookup = function lookup(fullName, options) {
(true && !(this.registry.isValidFullName(fullName)) && (0, _emberDebug.assert)('fullName must be a proper full name', this.registry.isValidFullName(fullName)));
return _lookup(this, this.registry.normalize(fullName), options);
};
Container.prototype.destroy = function destroy() {
destroyDestroyables(this);
this.isDestroyed = true;
};
Container.prototype.reset = function reset(fullName) {
if (fullName === undefined) {
resetCache(this);
} else {
resetMember(this, this.registry.normalize(fullName));
}
};
Container.prototype.ownerInjection = function ownerInjection() {
var _ref;
return _ref = {}, _ref[_emberUtils.OWNER] = this.owner, _ref;
};
Container.prototype._resolverCacheKey = function _resolverCacheKey(name, options) {
return this.registry.resolverCacheKey(name, options);
};
Container.prototype.factoryFor = function factoryFor(fullName) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var normalizedName = this.registry.normalize(fullName);
(true && !(this.registry.isValidFullName(normalizedName)) && (0, _emberDebug.assert)('fullName must be a proper full name', this.registry.isValidFullName(normalizedName)));
if (options.source) {
var expandedFullName = this.registry.expandLocalLookup(fullName, options);
// if expandLocalLookup returns falsey, we do not support local lookup
if (!_features.EMBER_MODULE_UNIFICATION) {
if (!expandedFullName) {
return;
}
normalizedName = expandedFullName;
} else if (expandedFullName) {
// with ember-module-unification, if expandLocalLookup returns something,
// pass it to the resolve without the source
normalizedName = expandedFullName;
options = {};
}
}
var cacheKey = this._resolverCacheKey(normalizedName, options);
var cached = this.factoryManagerCache[cacheKey];
if (cached !== undefined) {
return cached;
}
var factory = _features.EMBER_MODULE_UNIFICATION ? this.registry.resolve(normalizedName, options) : this.registry.resolve(normalizedName);
if (factory === undefined) {
return;
}
if (true && factory && typeof factory._onLookup === 'function') {
factory._onLookup(fullName);
}
var manager = new FactoryManager(this, factory, fullName, normalizedName);
if (true) {
manager = wrapManagerInDeprecationProxy(manager);
}
this.factoryManagerCache[cacheKey] = manager;
return manager;
};
return Container;
}();
/*
* Wrap a factory manager in a proxy which will not permit properties to be
* set on the manager.
*/
function wrapManagerInDeprecationProxy(manager) {
if (_emberUtils.HAS_NATIVE_PROXY) {
var validator = {
set: function (obj, prop, value) {
throw new Error('You attempted to set "' + prop + '" on a factory manager created by container#factoryFor. A factory manager is a read-only construct.');
}
};
// Note:
// We have to proxy access to the manager here so that private property
// access doesn't cause the above errors to occur.
var m = manager;
var proxiedManager = {
class: m.class,
create: function (props) {
return m.create(props);
}
};
return new Proxy(proxiedManager, validator);
}
return manager;
}
function isSingleton(container, fullName) {
return container.registry.getOption(fullName, 'singleton') !== false;
}
function isInstantiatable(container, fullName) {
return container.registry.getOption(fullName, 'instantiate') !== false;
}
function _lookup(container, fullName) {
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
if (options.source) {
var expandedFullName = container.registry.expandLocalLookup(fullName, options);
if (!_features.EMBER_MODULE_UNIFICATION) {
// if expandLocalLookup returns falsey, we do not support local lookup
if (!expandedFullName) {
return;
}
fullName = expandedFullName;
} else if (expandedFullName) {
// with ember-module-unification, if expandLocalLookup returns something,
// pass it to the resolve without the source
fullName = expandedFullName;
options = {};
}
}
if (options.singleton !== false) {
var cacheKey = container._resolverCacheKey(fullName, options);
var cached = container.cache[cacheKey];
if (cached !== undefined) {
return cached;
}
}
return instantiateFactory(container, fullName, options);
}
function isSingletonClass(container, fullName, _ref2) {
var instantiate = _ref2.instantiate,
singleton = _ref2.singleton;
return singleton !== false && !instantiate && isSingleton(container, fullName) && !isInstantiatable(container, fullName);
}
function isSingletonInstance(container, fullName, _ref3) {
var instantiate = _ref3.instantiate,
singleton = _ref3.singleton;
return singleton !== false && instantiate !== false && isSingleton(container, fullName) && isInstantiatable(container, fullName);
}
function isFactoryClass(container, fullname, _ref4) {
var instantiate = _ref4.instantiate,
singleton = _ref4.singleton;
return instantiate === false && (singleton === false || !isSingleton(container, fullname)) && !isInstantiatable(container, fullname);
}
function isFactoryInstance(container, fullName, _ref5) {
var instantiate = _ref5.instantiate,
singleton = _ref5.singleton;
return instantiate !== false && (singleton !== false || isSingleton(container, fullName)) && isInstantiatable(container, fullName);
}
function instantiateFactory(container, fullName, options) {
var factoryManager = _features.EMBER_MODULE_UNIFICATION && options && options.source ? container.factoryFor(fullName, options) : container.factoryFor(fullName);
if (factoryManager === undefined) {
return;
}
// SomeClass { singleton: true, instantiate: true } | { singleton: true } | { instantiate: true } | {}
// By default majority of objects fall into this case
if (isSingletonInstance(container, fullName, options)) {
var cacheKey = container._resolverCacheKey(fullName, options);
return container.cache[cacheKey] = factoryManager.create();
}
// SomeClass { singleton: false, instantiate: true }
if (isFactoryInstance(container, fullName, options)) {
return factoryManager.create();
}
// SomeClass { singleton: true, instantiate: false } | { instantiate: false } | { singleton: false, instantiation: false }
if (isSingletonClass(container, fullName, options) || isFactoryClass(container, fullName, options)) {
return factoryManager.class;
}
throw new Error('Could not create factory');
}
function buildInjections(container, injections) {
var hash = {};
var isDynamic = false;
if (injections.length > 0) {
if (true) {
container.registry.validateInjections(injections);
}
var injection = void 0;
for (var i = 0; i < injections.length; i++) {
injection = injections[i];
hash[injection.property] = _lookup(container, injection.fullName);
if (!isDynamic) {
isDynamic = !isSingleton(container, injection.fullName);
}
}
}
return { injections: hash, isDynamic: isDynamic };
}
function injectionsFor(container, fullName) {
var registry = container.registry;
var _fullName$split = fullName.split(':'),
type = _fullName$split[0];
var injections = registry.getTypeInjections(type).concat(registry.getInjections(fullName));
return buildInjections(container, injections);
}
function destroyDestroyables(container) {
var cache = container.cache;
var keys = Object.keys(cache);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var value = cache[key];
if (value.destroy) {
value.destroy();
}
}
}
function resetCache(container) {
destroyDestroyables(container);
container.cache = (0, _emberUtils.dictionary)(null);
container.factoryManagerCache = (0, _emberUtils.dictionary)(null);
}
function resetMember(container, fullName) {
var member = container.cache[fullName];
delete container.factoryManagerCache[fullName];
if (member) {
delete container.cache[fullName];
if (member.destroy) {
member.destroy();
}
}
}
var FactoryManager = function () {
function FactoryManager(container, factory, fullName, normalizedName) {
(0, _emberBabel.classCallCheck)(this, FactoryManager);
this.container = container;
this.owner = container.owner;
this.class = factory;
this.fullName = fullName;
this.normalizedName = normalizedName;
this.madeToString = undefined;
this.injections = undefined;
}
FactoryManager.prototype.toString = function toString() {
if (this.madeToString === undefined) {
this.madeToString = this.container.registry.makeToString(this.class, this.fullName);
}
return this.madeToString;
};
FactoryManager.prototype.create = function create() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var injectionsCache = this.injections;
if (injectionsCache === undefined) {
var _injectionsFor = injectionsFor(this.container, this.normalizedName),
injections = _injectionsFor.injections,
isDynamic = _injectionsFor.isDynamic;
injectionsCache = injections;
if (!isDynamic) {
this.injections = injections;
}
}
var props = (0, _emberUtils.assign)({}, injectionsCache, options);
if (true) {
var lazyInjections = void 0;
var validationCache = this.container.validationCache;
// Ensure that all lazy injections are valid at instantiation time
if (!validationCache[this.fullName] && this.class && typeof this.class._lazyInjections === 'function') {
lazyInjections = this.class._lazyInjections();
lazyInjections = this.container.registry.normalizeInjectionsHash(lazyInjections);
this.container.registry.validateInjections(lazyInjections);
}
validationCache[this.fullName] = true;
}
if (!this.class.create) {
throw new Error('Failed to create an instance of \'' + this.normalizedName + '\'. Most likely an improperly defined class or' + ' an invalid module export.');
}
// required to allow access to things like
// the customized toString, _debugContainerKey,
// owner, etc. without a double extend and without
// modifying the objects properties
if (typeof this.class._initFactory === 'function') {
this.class._initFactory(this);
} else {
// in the non-EmberObject case we need to still setOwner
// this is required for supporting glimmer environment and
// template instantiation which rely heavily on
// `options[OWNER]` being passed into `create`
// TODO: clean this up, and remove in future versions
(0, _emberUtils.setOwner)(props, this.owner);
}
return this.class.create(props);
};
return FactoryManager;
}();
var VALID_FULL_NAME_REGEXP = /^[^:]+:[^:]+$/;
/**
A registry used to store factory and option information keyed
by type.
A `Registry` stores the factory and option information needed by a
`Container` to instantiate and cache objects.
The API for `Registry` is still in flux and should not be considered stable.
@private
@class Registry
@since 1.11.0
*/
var Registry = function () {
function Registry() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
(0, _emberBabel.classCallCheck)(this, Registry);
this.fallback = options.fallback || null;
this.resolver = options.resolver || null;
if (typeof this.resolver === 'function') {
deprecateResolverFunction(this);
}
this.registrations = (0, _emberUtils.dictionary)(options.registrations || null);
this._typeInjections = (0, _emberUtils.dictionary)(null);
this._injections = (0, _emberUtils.dictionary)(null);
this._localLookupCache = Object.create(null);
this._normalizeCache = (0, _emberUtils.dictionary)(null);
this._resolveCache = (0, _emberUtils.dictionary)(null);
this._failCache = (0, _emberUtils.dictionary)(null);
this._options = (0, _emberUtils.dictionary)(null);
this._typeOptions = (0, _emberUtils.dictionary)(null);
}
/**
A backup registry for resolving registrations when no matches can be found.
@private
@property fallback
@type Registry
*/
/**
An object that has a `resolve` method that resolves a name.
@private
@property resolver
@type Resolver
*/
/**
@private
@property registrations
@type InheritingDict
*/
/**
@private
@property _typeInjections
@type InheritingDict
*/
/**
@private
@property _injections
@type InheritingDict
*/
/**
@private
@property _normalizeCache
@type InheritingDict
*/
/**
@private
@property _resolveCache
@type InheritingDict
*/
/**
@private
@property _options
@type InheritingDict
*/
/**
@private
@property _typeOptions
@type InheritingDict
*/
/**
Creates a container based on this registry.
@private
@method container
@param {Object} options
@return {Container} created container
*/
Registry.prototype.container = function container(options) {
return new Container(this, options);
};
Registry.prototype.register = function register(fullName, factory) {
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
(true && !(this.isValidFullName(fullName)) && (0, _emberDebug.assert)('fullName must be a proper full name', this.isValidFullName(fullName)));
(true && !(factory !== undefined) && (0, _emberDebug.assert)('Attempting to register an unknown factory: \'' + fullName + '\'', factory !== undefined));
var normalizedName = this.normalize(fullName);
(true && !(!this._resolveCache[normalizedName]) && (0, _emberDebug.assert)('Cannot re-register: \'' + fullName + '\', as it has already been resolved.', !this._resolveCache[normalizedName]));
delete this._failCache[normalizedName];
this.registrations[normalizedName] = factory;
this._options[normalizedName] = options;
};
Registry.prototype.unregister = function unregister(fullName) {
(true && !(this.isValidFullName(fullName)) && (0, _emberDebug.assert)('fullName must be a proper full name', this.isValidFullName(fullName)));
var normalizedName = this.normalize(fullName);
this._localLookupCache = Object.create(null);
delete this.registrations[normalizedName];
delete this._resolveCache[normalizedName];
delete this._failCache[normalizedName];
delete this._options[normalizedName];
};
Registry.prototype.resolve = function resolve(fullName, options) {
(true && !(this.isValidFullName(fullName)) && (0, _emberDebug.assert)('fullName must be a proper full name', this.isValidFullName(fullName)));
var factory = _resolve(this, this.normalize(fullName), options);
if (factory === undefined && this.fallback !== null) {
var _fallback;
factory = (_fallback = this.fallback).resolve.apply(_fallback, arguments);
}
return factory;
};
Registry.prototype.describe = function describe(fullName) {
if (this.resolver !== null && this.resolver.lookupDescription) {
return this.resolver.lookupDescription(fullName);
} else if (this.fallback !== null) {
return this.fallback.describe(fullName);
} else {
return fullName;
}
};
Registry.prototype.normalizeFullName = function normalizeFullName(fullName) {
if (this.resolver !== null && this.resolver.normalize) {
return this.resolver.normalize(fullName);
} else if (this.fallback !== null) {
return this.fallback.normalizeFullName(fullName);
} else {
return fullName;
}
};
Registry.prototype.normalize = function normalize(fullName) {
return this._normalizeCache[fullName] || (this._normalizeCache[fullName] = this.normalizeFullName(fullName));
};
Registry.prototype.makeToString = function makeToString(factory, fullName) {
if (this.resolver !== null && this.resolver.makeToString) {
return this.resolver.makeToString(factory, fullName);
} else if (this.fallback !== null) {
return this.fallback.makeToString(factory, fullName);
} else {
return factory.toString();
}
};
Registry.prototype.has = function has(fullName, options) {
if (!this.isValidFullName(fullName)) {
return false;
}
var source = options && options.source && this.normalize(options.source);
return _has(this, this.normalize(fullName), source);
};
Registry.prototype.optionsForType = function optionsForType(type, options) {
this._typeOptions[type] = options;
};
Registry.prototype.getOptionsForType = function getOptionsForType(type) {
var optionsForType = this._typeOptions[type];
if (optionsForType === undefined && this.fallback !== null) {
optionsForType = this.fallback.getOptionsForType(type);
}
return optionsForType;
};
Registry.prototype.options = function options(fullName) {
var _options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var normalizedName = this.normalize(fullName);
this._options[normalizedName] = _options;
};
Registry.prototype.getOptions = function getOptions(fullName) {
var normalizedName = this.normalize(fullName);
var options = this._options[normalizedName];
if (options === undefined && this.fallback !== null) {
options = this.fallback.getOptions(fullName);
}
return options;
};
Registry.prototype.getOption = function getOption(fullName, optionName) {
var options = this._options[fullName];
if (options && options[optionName] !== undefined) {
return options[optionName];
}
var type = fullName.split(':')[0];
options = this._typeOptions[type];
if (options && options[optionName] !== undefined) {
return options[optionName];
} else if (this.fallback !== null) {
return this.fallback.getOption(fullName, optionName);
}
};
Registry.prototype.typeInjection = function typeInjection(type, property, fullName) {
(true && !(this.isValidFullName(fullName)) && (0, _emberDebug.assert)('fullName must be a proper full name', this.isValidFullName(fullName)));
var fullNameType = fullName.split(':')[0];
(true && !(fullNameType !== type) && (0, _emberDebug.assert)('Cannot inject a \'' + fullName + '\' on other ' + type + '(s).', fullNameType !== type));
var injections = this._typeInjections[type] || (this._typeInjections[type] = []);
injections.push({ property: property, fullName: fullName });
};
Registry.prototype.injection = function injection(fullName, property, injectionName) {
(true && !(this.isValidFullName(injectionName)) && (0, _emberDebug.assert)('Invalid injectionName, expected: \'type:name\' got: ' + injectionName, this.isValidFullName(injectionName)));
var normalizedInjectionName = this.normalize(injectionName);
if (fullName.indexOf(':') === -1) {
return this.typeInjection(fullName, property, normalizedInjectionName);
}
(true && !(this.isValidFullName(fullName)) && (0, _emberDebug.assert)('fullName must be a proper full name', this.isValidFullName(fullName)));
var normalizedName = this.normalize(fullName);
var injections = this._injections[normalizedName] || (this._injections[normalizedName] = []);
injections.push({ property: property, fullName: normalizedInjectionName });
};
Registry.prototype.knownForType = function knownForType(type) {
var fallbackKnown = void 0,
resolverKnown = void 0;
var localKnown = (0, _emberUtils.dictionary)(null);
var registeredNames = Object.keys(this.registrations);
for (var index = 0; index < registeredNames.length; index++) {
var fullName = registeredNames[index];
var itemType = fullName.split(':')[0];
if (itemType === type) {
localKnown[fullName] = true;
}
}
if (this.fallback !== null) {
fallbackKnown = this.fallback.knownForType(type);
}
if (this.resolver !== null && this.resolver.knownForType) {
resolverKnown = this.resolver.knownForType(type);
}
return (0, _emberUtils.assign)({}, fallbackKnown, localKnown, resolverKnown);
};
Registry.prototype.isValidFullName = function isValidFullName(fullName) {
return VALID_FULL_NAME_REGEXP.test(fullName);
};
Registry.prototype.getInjections = function getInjections(fullName) {
var injections = this._injections[fullName] || [];
if (this.fallback !== null) {
injections = injections.concat(this.fallback.getInjections(fullName));
}
return injections;
};
Registry.prototype.getTypeInjections = function getTypeInjections(type) {
var injections = this._typeInjections[type] || [];
if (this.fallback !== null) {
injections = injections.concat(this.fallback.getTypeInjections(type));
}
return injections;
};
Registry.prototype.resolverCacheKey = function resolverCacheKey(name, options) {
if (!_features.EMBER_MODULE_UNIFICATION) {
return name;
}
return options && options.source ? options.source + ':' + name : name;
};
Registry.prototype.expandLocalLookup = function expandLocalLookup(fullName, options) {
if (this.resolver !== null && this.resolver.expandLocalLookup) {
(true && !(this.isValidFullName(fullName)) && (0, _emberDebug.assert)('fullName must be a proper full name', this.isValidFullName(fullName)));
(true && !(options && options.source) && (0, _emberDebug.assert)('options.source must be provided to expandLocalLookup', options && options.source));
(true && !(this.isValidFullName(options.source)) && (0, _emberDebug.assert)('options.source must be a proper full name', this.isValidFullName(options.source)));
var normalizedFullName = this.normalize(fullName);
var normalizedSource = this.normalize(options.source);
return _expandLocalLookup(this, normalizedFullName, normalizedSource);
} else if (this.fallback !== null) {
return this.fallback.expandLocalLookup(fullName, options);
} else {
return null;
}
};
return Registry;
}();
function deprecateResolverFunction(registry) {
(true && !(false) && (0, _emberDebug.deprecate)('Passing a `resolver` function into a Registry is deprecated. Please pass in a Resolver object with a `resolve` method.', false, { id: 'ember-application.registry-resolver-as-function', until: '3.0.0', url: 'https://emberjs.com/deprecations/v2.x#toc_registry-resolver-as-function' }));
registry.resolver = { resolve: registry.resolver };
}
if (true) {
Registry.prototype.normalizeInjectionsHash = function (hash) {
var injections = [];
for (var key in hash) {
if (hash.hasOwnProperty(key)) {
(true && !(this.isValidFullName(hash[key])) && (0, _emberDebug.assert)('Expected a proper full name, given \'' + hash[key] + '\'', this.isValidFullName(hash[key])));
injections.push({
property: key,
fullName: hash[key]
});
}
}
return injections;
};
Registry.prototype.validateInjections = function (injections) {
if (!injections) {
return;
}
var fullName = void 0;
for (var i = 0; i < injections.length; i++) {
fullName = injections[i].fullName;
(true && !(this.has(fullName)) && (0, _emberDebug.assert)('Attempting to inject an unknown injection: \'' + fullName + '\'', this.has(fullName)));
}
};
}
function _expandLocalLookup(registry, normalizedName, normalizedSource) {
var cache = registry._localLookupCache;
var normalizedNameCache = cache[normalizedName];
if (!normalizedNameCache) {
normalizedNameCache = cache[normalizedName] = Object.create(null);
}
var cached = normalizedNameCache[normalizedSource];
if (cached !== undefined) {
return cached;
}
var expanded = registry.resolver.expandLocalLookup(normalizedName, normalizedSource);
return normalizedNameCache[normalizedSource] = expanded;
}
function _resolve(registry, normalizedName, options) {
if (options && options.source) {
// when `source` is provided expand normalizedName
// and source into the full normalizedName
var expandedNormalizedName = registry.expandLocalLookup(normalizedName, options);
// if expandLocalLookup returns falsey, we do not support local lookup
if (!_features.EMBER_MODULE_UNIFICATION) {
if (!expandedNormalizedName) {
return;
}
normalizedName = expandedNormalizedName;
} else if (expandedNormalizedName) {
// with ember-module-unification, if expandLocalLookup returns something,
// pass it to the resolve without the source
normalizedName = expandedNormalizedName;
options = {};
}
}
var cacheKey = registry.resolverCacheKey(normalizedName, options);
var cached = registry._resolveCache[cacheKey];
if (cached !== undefined) {
return cached;
}
if (registry._failCache[cacheKey]) {
return;
}
var resolved = void 0;
if (registry.resolver) {
resolved = registry.resolver.resolve(normalizedName, options && options.source);
}
if (resolved === undefined) {
resolved = registry.registrations[normalizedName];
}
if (resolved === undefined) {
registry._failCache[cacheKey] = true;
} else {
registry._resolveCache[cacheKey] = resolved;
}
return resolved;
}
function _has(registry, fullName, source) {
return registry.resolve(fullName, { source: source }) !== undefined;
}
var privateNames = (0, _emberUtils.dictionary)(null);
var privateSuffix = ('' + Math.random() + Date.now()).replace('.', '');
function privatize(_ref6) {
var fullName = _ref6[0];
var name = privateNames[fullName];
if (name) {
return name;
}
var _fullName$split2 = fullName.split(':'),
type = _fullName$split2[0],
rawName = _fullName$split2[1];
return privateNames[fullName] = (0, _emberUtils.intern)(type + ':' + rawName + '-' + privateSuffix);
}
/*
Public API for the container is still in flux.
The public API, specified on the application namespace should be considered the stable API.
// @module container
@private
*/
exports.Registry = Registry;
exports.privatize = privatize;
exports.Container = Container;
});
enifed("dag-map", ["exports"], function (exports) {
"use strict";
/**
* A topologically ordered map of key/value pairs with a simple API for adding constraints.
*
* Edges can forward reference keys that have not been added yet (the forward reference will
* map the key to undefined).
*/
var DAG = function () {
function DAG() {
this._vertices = new Vertices();
}
/**
* Adds a key/value pair with dependencies on other key/value pairs.
*
* @public
* @param key The key of the vertex to be added.
* @param value The value of that vertex.
* @param before A key or array of keys of the vertices that must
* be visited before this vertex.
* @param after An string or array of strings with the keys of the
* vertices that must be after this vertex is visited.
*/
DAG.prototype.add = function (key, value, before, after) {
if (!key) throw new Error('argument `key` is required');
var vertices = this._vertices;
var v = vertices.add(key);
v.val = value;
if (before) {
if (typeof before === "string") {
vertices.addEdge(v, vertices.add(before));
} else {
for (var i = 0; i < before.length; i++) {
vertices.addEdge(v, vertices.add(before[i]));
}
}
}
if (after) {
if (typeof after === "string") {
vertices.addEdge(vertices.add(after), v);
} else {
for (var i = 0; i < after.length; i++) {
vertices.addEdge(vertices.add(after[i]), v);
}
}
}
};
/**
* @deprecated please use add.
*/
DAG.prototype.addEdges = function (key, value, before, after) {
this.add(key, value, before, after);
};
/**
* Visits key/value pairs in topological order.
*
* @public
* @param callback The function to be invoked with each key/value.
*/
DAG.prototype.each = function (callback) {
this._vertices.walk(callback);
};
/**
* @deprecated please use each.
*/
DAG.prototype.topsort = function (callback) {
this.each(callback);
};
return DAG;
}();
exports.default = DAG;
/** @private */
var Vertices = function () {
function Vertices() {
this.length = 0;
this.stack = new IntStack();
this.path = new IntStack();
this.result = new IntStack();
}
Vertices.prototype.add = function (key) {
if (!key) throw new Error("missing key");
var l = this.length | 0;
var vertex;
for (var i = 0; i < l; i++) {
vertex = this[i];
if (vertex.key === key) return vertex;
}
this.length = l + 1;
return this[l] = {
idx: l,
key: key,
val: undefined,
out: false,
flag: false,
length: 0
};
};
Vertices.prototype.addEdge = function (v, w) {
this.check(v, w.key);
var l = w.length | 0;
for (var i = 0; i < l; i++) {
if (w[i] === v.idx) return;
}
w.length = l + 1;
w[l] = v.idx;
v.out = true;
};
Vertices.prototype.walk = function (cb) {
this.reset();
for (var i = 0; i < this.length; i++) {
var vertex = this[i];
if (vertex.out) continue;
this.visit(vertex, "");
}
this.each(this.result, cb);
};
Vertices.prototype.check = function (v, w) {
if (v.key === w) {
throw new Error("cycle detected: " + w + " <- " + w);
}
// quick check
if (v.length === 0) return;
// shallow check
for (var i = 0; i < v.length; i++) {
var key = this[v[i]].key;
if (key === w) {
throw new Error("cycle detected: " + w + " <- " + v.key + " <- " + w);
}
}
// deep check
this.reset();
this.visit(v, w);
if (this.path.length > 0) {
var msg_1 = "cycle detected: " + w;
this.each(this.path, function (key) {
msg_1 += " <- " + key;
});
throw new Error(msg_1);
}
};
Vertices.prototype.reset = function () {
this.stack.length = 0;
this.path.length = 0;
this.result.length = 0;
for (var i = 0, l = this.length; i < l; i++) {
this[i].flag = false;
}
};
Vertices.prototype.visit = function (start, search) {
var _a = this,
stack = _a.stack,
path = _a.path,
result = _a.result;
stack.push(start.idx);
while (stack.length) {
var index = stack.pop() | 0;
if (index >= 0) {
// enter
var vertex = this[index];
if (vertex.flag) continue;
vertex.flag = true;
path.push(index);
if (search === vertex.key) break;
// push exit
stack.push(~index);
this.pushIncoming(vertex);
} else {
// exit
path.pop();
result.push(~index);
}
}
};
Vertices.prototype.pushIncoming = function (incomming) {
var stack = this.stack;
for (var i = incomming.length - 1; i >= 0; i--) {
var index = incomming[i];
if (!this[index].flag) {
stack.push(index);
}
}
};
Vertices.prototype.each = function (indices, cb) {
for (var i = 0, l = indices.length; i < l; i++) {
var vertex = this[indices[i]];
cb(vertex.key, vertex.val);
}
};
return Vertices;
}();
/** @private */
var IntStack = function () {
function IntStack() {
this.length = 0;
}
IntStack.prototype.push = function (n) {
this[this.length++] = n | 0;
};
IntStack.prototype.pop = function () {
return this[--this.length] | 0;
};
return IntStack;
}();
});
enifed('ember-application/index', ['exports', 'ember-application/system/application', 'ember-application/system/application-instance', 'ember-application/system/resolver', 'ember-application/system/engine', 'ember-application/system/engine-instance', 'ember-application/system/engine-parent', 'ember-application/initializers/dom-templates'], function (exports, _application, _applicationInstance, _resolver, _engine, _engineInstance, _engineParent) {
'use strict';
exports.setEngineParent = exports.getEngineParent = exports.EngineInstance = exports.Engine = exports.Resolver = exports.ApplicationInstance = exports.Application = undefined;
Object.defineProperty(exports, 'Application', {
enumerable: true,
get: function () {
return _application.default;
}
});
Object.defineProperty(exports, 'ApplicationInstance', {
enumerable: true,
get: function () {
return _applicationInstance.default;
}
});
Object.defineProperty(exports, 'Resolver', {
enumerable: true,
get: function () {
return _resolver.default;
}
});
Object.defineProperty(exports, 'Engine', {
enumerable: true,
get: function () {
return _engine.default;
}
});
Object.defineProperty(exports, 'EngineInstance', {
enumerable: true,
get: function () {
return _engineInstance.default;
}
});
Object.defineProperty(exports, 'getEngineParent', {
enumerable: true,
get: function () {
return _engineParent.getEngineParent;
}
});
Object.defineProperty(exports, 'setEngineParent', {
enumerable: true,
get: function () {
return _engineParent.setEngineParent;
}
});
});
enifed('ember-application/initializers/dom-templates', ['require', 'ember-glimmer', 'ember-environment', 'ember-application/system/application'], function (_require2, _emberGlimmer, _emberEnvironment, _application) {
'use strict';
var bootstrap = function () {};
_application.default.initializer({
name: 'domTemplates',
initialize: function () {
var bootstrapModuleId = 'ember-template-compiler/system/bootstrap';
var context = void 0;
if (_emberEnvironment.environment.hasDOM && (0, _require2.has)(bootstrapModuleId)) {
bootstrap = (0, _require2.default)(bootstrapModuleId).default;
context = document;
}
bootstrap({ context: context, hasTemplate: _emberGlimmer.hasTemplate, setTemplate: _emberGlimmer.setTemplate });
}
});
});
enifed('ember-application/system/application-instance', ['exports', 'ember-utils', 'ember-metal', 'ember-runtime', 'ember-environment', 'ember-views', 'ember-application/system/engine-instance'], function (exports, _emberUtils, _emberMetal, _emberRuntime, _emberEnvironment, _emberViews, _engineInstance) {
'use strict';
/**
The `ApplicationInstance` encapsulates all of the stateful aspects of a
running `Application`.
At a high-level, we break application boot into two distinct phases:
* Definition time, where all of the classes, templates, and other
dependencies are loaded (typically in the browser).
* Run time, where we begin executing the application once everything
has loaded.
Definition time can be expensive and only needs to happen once since it is
an idempotent operation. For example, between test runs and FastBoot
requests, the application stays the same. It is only the state that we want
to reset.
That state is what the `ApplicationInstance` manages: it is responsible for
creating the container that contains all application state, and disposing of
it once the particular test run or FastBoot request has finished.
@public
@class ApplicationInstance
@extends EngineInstance
*/
/**
@module @ember/application
*/
var ApplicationInstance = _engineInstance.default.extend({
/**
The `Application` for which this is an instance.
@property {Application} application
@private
*/
application: null,
/**
The DOM events for which the event dispatcher should listen.
By default, the application's `Ember.EventDispatcher` listens
for a set of standard DOM events, such as `mousedown` and
`keyup`, and delegates them to your application's `Ember.View`
instances.
@private
@property {Object} customEvents
*/
customEvents: null,
/**
The root DOM element of the Application as an element or a
[jQuery-compatible selector
string](http://api.jquery.com/category/selectors/).
@private
@property {String|DOMElement} rootElement
*/
rootElement: null,
init: function () {
this._super.apply(this, arguments);
// Register this instance in the per-instance registry.
//
// Why do we need to register the instance in the first place?
// Because we need a good way for the root route (a.k.a ApplicationRoute)
// to notify us when it has created the root-most view. That view is then
// appended to the rootElement, in the case of apps, to the fixture harness
// in tests, or rendered to a string in the case of FastBoot.
this.register('-application-instance:main', this, { instantiate: false });
},
_bootSync: function (options) {
if (this._booted) {
return this;
}
options = new BootOptions(options);
this.setupRegistry(options);
if (options.rootElement) {
this.rootElement = options.rootElement;
} else {
this.rootElement = this.application.rootElement;
}
if (options.location) {
var router = (0, _emberMetal.get)(this, 'router');
(0, _emberMetal.set)(router, 'location', options.location);
}
this.application.runInstanceInitializers(this);
if (options.isInteractive) {
this.setupEventDispatcher();
}
this._booted = true;
return this;
},
setupRegistry: function (options) {
this.constructor.setupRegistry(this.__registry__, options);
},
router: (0, _emberMetal.computed)(function () {
return this.lookup('router:main');
}).readOnly(),
didCreateRootView: function (view) {
view.appendTo(this.rootElement);
},
startRouting: function () {
var router = (0, _emberMetal.get)(this, 'router');
router.startRouting();
this._didSetupRouter = true;
},
setupRouter: function () {
if (this._didSetupRouter) {
return;
}
this._didSetupRouter = true;
var router = (0, _emberMetal.get)(this, 'router');
router.setupRouter();
},
handleURL: function (url) {
var router = (0, _emberMetal.get)(this, 'router');
this.setupRouter();
return router.handleURL(url);
},
setupEventDispatcher: function () {
var dispatcher = this.lookup('event_dispatcher:main');
var applicationCustomEvents = (0, _emberMetal.get)(this.application, 'customEvents');
var instanceCustomEvents = (0, _emberMetal.get)(this, 'customEvents');
var customEvents = (0, _emberUtils.assign)({}, applicationCustomEvents, instanceCustomEvents);
dispatcher.setup(customEvents, this.rootElement);
return dispatcher;
},
getURL: function () {
return (0, _emberMetal.get)(this, 'router.url');
},
visit: function (url) {
var _this = this;
this.setupRouter();
var bootOptions = this.__container__.lookup('-environment:main');
var router = (0, _emberMetal.get)(this, 'router');
var handleTransitionResolve = function () {
if (!bootOptions.options.shouldRender) {
// No rendering is needed, and routing has completed, simply return.
return _this;
} else {
return new _emberRuntime.RSVP.Promise(function (resolve) {
// Resolve once rendering is completed. `router.handleURL` returns the transition (as a thennable)
// which resolves once the transition is completed, but the transition completion only queues up
// a scheduled revalidation (into the `render` queue) in the Renderer.
//
// This uses `run.schedule('afterRender', ....)` to resolve after that rendering has completed.
_emberMetal.run.schedule('afterRender', null, resolve, _this);
});
}
};
var handleTransitionReject = function (error) {
if (error.error) {
throw error.error;
} else if (error.name === 'TransitionAborted' && router._routerMicrolib.activeTransition) {
return router._routerMicrolib.activeTransition.then(handleTransitionResolve, handleTransitionReject);
} else if (error.name === 'TransitionAborted') {
throw new Error(error.message);
} else {
throw error;
}
};
var location = (0, _emberMetal.get)(router, 'location');
// Keeps the location adapter's internal URL in-sync
location.setURL(url);
// getURL returns the set url with the rootURL stripped off
return router.handleURL(location.getURL()).then(handleTransitionResolve, handleTransitionReject);
}
});
ApplicationInstance.reopenClass({
setupRegistry: function (registry) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
if (!options.toEnvironment) {
options = new BootOptions(options);
}
registry.register('-environment:main', options.toEnvironment(), { instantiate: false });
registry.register('service:-document', options.document, { instantiate: false });
this._super(registry, options);
}
});
/**
A list of boot-time configuration options for customizing the behavior of
an `Ember.ApplicationInstance`.
This is an interface class that exists purely to document the available
options; you do not need to construct it manually. Simply pass a regular
JavaScript object containing the desired options into methods that require
one of these options object:
```javascript
MyApp.visit("/", { location: "none", rootElement: "#container" });
```
Not all combinations of the supported options are valid. See the documentation
on `Ember.Application#visit` for the supported configurations.
Internal, experimental or otherwise unstable flags are marked as private.
@class BootOptions
@namespace ApplicationInstance
@public
*/
function BootOptions() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
/**
Provide a specific instance of jQuery. This is useful in conjunction with
the `document` option, as it allows you to use a copy of `jQuery` that is
appropriately bound to the foreign `document` (e.g. a jsdom).
This is highly experimental and support very incomplete at the moment.
@property jQuery
@type Object
@default auto-detected
@private
*/
this.jQuery = _emberViews.jQuery; // This default is overridable below
/**
Interactive mode: whether we need to set up event delegation and invoke
lifecycle callbacks on Components.
@property isInteractive
@type boolean
@default auto-detected
@private
*/
this.isInteractive = _emberEnvironment.environment.hasDOM; // This default is overridable below
/**
Run in a full browser environment.
When this flag is set to `false`, it will disable most browser-specific
and interactive features. Specifically:
* It does not use `jQuery` to append the root view; the `rootElement`
(either specified as a subsequent option or on the application itself)
must already be an `Element` in the given `document` (as opposed to a
string selector).
* It does not set up an `EventDispatcher`.
* It does not run any `Component` lifecycle hooks (such as `didInsertElement`).
* It sets the `location` option to `"none"`. (If you would like to use
the location adapter specified in the app's router instead, you can also
specify `{ location: null }` to specifically opt-out.)
@property isBrowser
@type boolean
@default auto-detected
@public
*/
if (options.isBrowser !== undefined) {
this.isBrowser = !!options.isBrowser;
} else {
this.isBrowser = _emberEnvironment.environment.hasDOM;
}
if (!this.isBrowser) {
this.jQuery = null;
this.isInteractive = false;
this.location = 'none';
}
/**
Disable rendering completely.
When this flag is set to `true`, it will disable the entire rendering
pipeline. Essentially, this puts the app into "routing-only" mode. No
templates will be rendered, and no Components will be created.
@property shouldRender
@type boolean
@default true
@public
*/
if (options.shouldRender !== undefined) {
this.shouldRender = !!options.shouldRender;
} else {
this.shouldRender = true;
}
if (!this.shouldRender) {
this.jQuery = null;
this.isInteractive = false;
}
/**
If present, render into the given `Document` object instead of the
global `window.document` object.
In practice, this is only useful in non-browser environment or in
non-interactive mode, because Ember's `jQuery` dependency is
implicitly bound to the current document, causing event delegation
to not work properly when the app is rendered into a foreign
document object (such as an iframe's `contentDocument`).
In non-browser mode, this could be a "`Document`-like" object as
Ember only interact with a small subset of the DOM API in non-
interactive mode. While the exact requirements have not yet been
formalized, the `SimpleDOM` library's implementation is known to
work.
@property document
@type Document
@default the global `document` object
@public
*/
if (options.document) {
this.document = options.document;
} else {
this.document = typeof document !== 'undefined' ? document : null;
}
/**
If present, overrides the application's `rootElement` property on
the instance. This is useful for testing environment, where you
might want to append the root view to a fixture area.
In non-browser mode, because Ember does not have access to jQuery,
this options must be specified as a DOM `Element` object instead of
a selector string.
See the documentation on `Ember.Applications`'s `rootElement` for
details.
@property rootElement
@type String|Element
@default null
@public
*/
if (options.rootElement) {
this.rootElement = options.rootElement;
}
// Set these options last to give the user a chance to override the
// defaults from the "combo" options like `isBrowser` (although in
// practice, the resulting combination is probably invalid)
/**
If present, overrides the router's `location` property with this
value. This is useful for environments where trying to modify the
URL would be inappropriate.
@property location
@type string
@default null
@public
*/
if (options.location !== undefined) {
this.location = options.location;
}
if (options.jQuery !== undefined) {
this.jQuery = options.jQuery;
}
if (options.isInteractive !== undefined) {
this.isInteractive = !!options.isInteractive;
}
}
BootOptions.prototype.toEnvironment = function () {
var env = (0, _emberUtils.assign)({}, _emberEnvironment.environment);
// For compatibility with existing code
env.hasDOM = this.isBrowser;
env.isInteractive = this.isInteractive;
env.options = this;
return env;
};
Object.defineProperty(ApplicationInstance.prototype, 'registry', {
configurable: true,
enumerable: false,
get: function () {
return (0, _emberRuntime.buildFakeRegistryWithDeprecations)(this, 'ApplicationInstance');
}
});
exports.default = ApplicationInstance;
});
enifed('ember-application/system/application', ['exports', 'ember-babel', 'ember-utils', 'ember-environment', 'ember-debug', 'ember-metal', 'ember-runtime', 'ember-views', 'ember-routing', 'ember-application/system/application-instance', 'container', 'ember-application/system/engine', 'ember-glimmer', 'ember/features'], function (exports, _emberBabel, _emberUtils, _emberEnvironment, _emberDebug, _emberMetal, _emberRuntime, _emberViews, _emberRouting, _applicationInstance, _container, _engine, _emberGlimmer, _features) {
'use strict';
var _templateObject = (0, _emberBabel.taggedTemplateLiteralLoose)(['-bucket-cache:main'], ['-bucket-cache:main']);
var librariesRegistered = false;
/**
An instance of `Ember.Application` is the starting point for every Ember
application. It helps to instantiate, initialize and coordinate the many
objects that make up your app.
Each Ember app has one and only one `Ember.Application` object. In fact, the
very first thing you should do in your application is create the instance:
```javascript
window.App = Ember.Application.create();
```
Typically, the application object is the only global variable. All other
classes in your app should be properties on the `Ember.Application` instance,
which highlights its first role: a global namespace.
For example, if you define a view class, it might look like this:
```javascript
App.MyView = Ember.View.extend();
```
By default, calling `Ember.Application.create()` will automatically initialize
your application by calling the `Ember.Application.initialize()` method. If
you need to delay initialization, you can call your app's `deferReadiness()`
method. When you are ready for your app to be initialized, call its
`advanceReadiness()` method.
You can define a `ready` method on the `Ember.Application` instance, which
will be run by Ember when the application is initialized.
Because `Ember.Application` inherits from `Ember.Namespace`, any classes
you create will have useful string representations when calling `toString()`.
See the `Ember.Namespace` documentation for more information.
While you can think of your `Ember.Application` as a container that holds the
other classes in your application, there are several other responsibilities
going on under-the-hood that you may want to understand.
### Event Delegation
Ember uses a technique called _event delegation_. This allows the framework
to set up a global, shared event listener instead of requiring each view to
do it manually. For example, instead of each view registering its own
`mousedown` listener on its associated element, Ember sets up a `mousedown`
listener on the `body`.
If a `mousedown` event occurs, Ember will look at the target of the event and
start walking up the DOM node tree, finding corresponding views and invoking
their `mouseDown` method as it goes.
`Ember.Application` has a number of default events that it listens for, as
well as a mapping from lowercase events to camel-cased view method names. For
example, the `keypress` event causes the `keyPress` method on the view to be
called, the `dblclick` event causes `doubleClick` to be called, and so on.
If there is a bubbling browser event that Ember does not listen for by
default, you can specify custom events and their corresponding view method
names by setting the application's `customEvents` property:
```javascript
let App = Ember.Application.create({
customEvents: {
// add support for the paste event
paste: 'paste'
}
});
```
To prevent Ember from setting up a listener for a default event,
specify the event name with a `null` value in the `customEvents`
property:
```javascript
let App = Ember.Application.create({
customEvents: {
// prevent listeners for mouseenter/mouseleave events
mouseenter: null,
mouseleave: null
}
});
```
By default, the application sets up these event listeners on the document
body. However, in cases where you are embedding an Ember application inside
an existing page, you may want it to set up the listeners on an element
inside the body.
For example, if only events inside a DOM element with the ID of `ember-app`
should be delegated, set your application's `rootElement` property:
```javascript
let App = Ember.Application.create({
rootElement: '#ember-app'
});
```
The `rootElement` can be either a DOM element or a jQuery-compatible selector
string. Note that *views appended to the DOM outside the root element will
not receive events.* If you specify a custom root element, make sure you only
append views inside it!
To learn more about the events Ember components use, see
[components/handling-events](https://guides.emberjs.com/v2.6.0/components/handling-events/#toc_event-names).
### Initializers
Libraries on top of Ember can add initializers, like so:
```javascript
Ember.Application.initializer({
name: 'api-adapter',
initialize: function(application) {
application.register('api-adapter:main', ApiAdapter);
}
});
```
Initializers provide an opportunity to access the internal registry, which
organizes the different components of an Ember application. Additionally
they provide a chance to access the instantiated application. Beyond
being used for libraries, initializers are also a great way to organize
dependency injection or setup in your own application.
### Routing
In addition to creating your application's router, `Ember.Application` is
also responsible for telling the router when to start routing. Transitions
between routes can be logged with the `LOG_TRANSITIONS` flag, and more
detailed intra-transition logging can be logged with
the `LOG_TRANSITIONS_INTERNAL` flag:
```javascript
let App = Ember.Application.create({
LOG_TRANSITIONS: true, // basic logging of successful transitions
LOG_TRANSITIONS_INTERNAL: true // detailed logging of all routing steps
});
```
By default, the router will begin trying to translate the current URL into
application state once the browser emits the `DOMContentReady` event. If you
need to defer routing, you can call the application's `deferReadiness()`
method. Once routing can begin, call the `advanceReadiness()` method.
If there is any setup required before routing begins, you can implement a
`ready()` method on your app that will be invoked immediately before routing
begins.
@class Application
@extends Engine
@uses RegistryProxyMixin
@public
*/
var Application = _engine.default.extend({
/**
The root DOM element of the Application. This can be specified as an
element or a
[jQuery-compatible selector string](http://api.jquery.com/category/selectors/).
This is the element that will be passed to the Application's,
`eventDispatcher`, which sets up the listeners for event delegation. Every
view in your application should be a child of the element you specify here.
@property rootElement
@type DOMElement
@default 'body'
@public
*/
rootElement: 'body',
/**
The `Ember.EventDispatcher` responsible for delegating events to this
application's views.
The event dispatcher is created by the application at initialization time
and sets up event listeners on the DOM element described by the
application's `rootElement` property.
See the documentation for `Ember.EventDispatcher` for more information.
@property eventDispatcher
@type Ember.EventDispatcher
@default null
@public
*/
eventDispatcher: null,
/**
The DOM events for which the event dispatcher should listen.
By default, the application's `Ember.EventDispatcher` listens
for a set of standard DOM events, such as `mousedown` and
`keyup`, and delegates them to your application's `Ember.View`
instances.
If you would like additional bubbling events to be delegated to your
views, set your `Ember.Application`'s `customEvents` property
to a hash containing the DOM event name as the key and the
corresponding view method name as the value. Setting an event to
a value of `null` will prevent a default event listener from being
added for that event.
To add new events to be listened to:
```javascript
let App = Ember.Application.create({
customEvents: {
// add support for the paste event
paste: 'paste'
}
});
```
To prevent default events from being listened to:
```javascript
let App = Ember.Application.create({
customEvents: {
// remove support for mouseenter / mouseleave events
mouseenter: null,
mouseleave: null
}
});
```
@property customEvents
@type Object
@default null
@public
*/
customEvents: null,
/**
Whether the application should automatically start routing and render
templates to the `rootElement` on DOM ready. While default by true,
other environments such as FastBoot or a testing harness can set this
property to `false` and control the precise timing and behavior of the boot
process.
@property autoboot
@type Boolean
@default true
@private
*/
autoboot: true,
/**
Whether the application should be configured for the legacy "globals mode".
Under this mode, the Application object serves as a global namespace for all
classes.
```javascript
let App = Ember.Application.create({
...
});
App.Router.reopen({
location: 'none'
});
App.Router.map({
...
});
App.MyComponent = Ember.Component.extend({
...
});
```
This flag also exposes other internal APIs that assumes the existence of
a special "default instance", like `App.__container__.lookup(...)`.
This option is currently not configurable, its value is derived from
the `autoboot` flag – disabling `autoboot` also implies opting-out of
globals mode support, although they are ultimately orthogonal concerns.
Some of the global modes features are already deprecated in 1.x. The
existence of this flag is to untangle the globals mode code paths from
the autoboot code paths, so that these legacy features can be reviewed
for deprecation/removal separately.
Forcing the (autoboot=true, _globalsMode=false) here and running the tests
would reveal all the places where we are still relying on these legacy
behavior internally (mostly just tests).
@property _globalsMode
@type Boolean
@default true
@private
*/
_globalsMode: true,
init: function (options) {
this._super.apply(this, arguments);
if (!this.$) {
this.$ = _emberViews.jQuery;
}
registerLibraries();
if (true) {
logLibraryVersions();
}
// Start off the number of deferrals at 1. This will be decremented by
// the Application's own `boot` method.
this._readinessDeferrals = 1;
this._booted = false;
this.autoboot = this._globalsMode = !!this.autoboot;
if (this._globalsMode) {
this._prepareForGlobalsMode();
}
if (this.autoboot) {
this.waitForDOMReady();
}
},
buildInstance: function () {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
options.base = this;
options.application = this;
return _applicationInstance.default.create(options);
},
_prepareForGlobalsMode: function () {
// Create subclass of Ember.Router for this Application instance.
// This is to ensure that someone reopening `App.Router` does not
// tamper with the default `Ember.Router`.
this.Router = (this.Router || _emberRouting.Router).extend();
this._buildDeprecatedInstance();
},
_buildDeprecatedInstance: function () {
// Build a default instance
var instance = this.buildInstance();
// Legacy support for App.__container__ and other global methods
// on App that rely on a single, default instance.
this.__deprecatedInstance__ = instance;
this.__container__ = instance.__container__;
},
waitForDOMReady: function () {
if (!this.$ || this.$.isReady) {
_emberMetal.run.schedule('actions', this, 'domReady');
} else {
this.$().ready(_emberMetal.run.bind(this, 'domReady'));
}
},
domReady: function () {
if (this.isDestroyed) {
return;
}
this._bootSync();
// Continues to `didBecomeReady`
},
deferReadiness: function () {
(true && !(this instanceof Application) && (0, _emberDebug.assert)('You must call deferReadiness on an instance of Ember.Application', this instanceof Application));
(true && !(this._readinessDeferrals > 0) && (0, _emberDebug.assert)('You cannot defer readiness since the `ready()` hook has already been called.', this._readinessDeferrals > 0));
this._readinessDeferrals++;
},
advanceReadiness: function () {
(true && !(this instanceof Application) && (0, _emberDebug.assert)('You must call advanceReadiness on an instance of Ember.Application', this instanceof Application));
this._readinessDeferrals--;
if (this._readinessDeferrals === 0) {
_emberMetal.run.once(this, this.didBecomeReady);
}
},
boot: function () {
if (this._bootPromise) {
return this._bootPromise;
}
try {
this._bootSync();
} catch (_) {
// Ignore th error: in the asynchronous boot path, the error is already reflected
// in the promise rejection
}
return this._bootPromise;
},
_bootSync: function () {
if (this._booted) {
return;
}
// Even though this returns synchronously, we still need to make sure the
// boot promise exists for book-keeping purposes: if anything went wrong in
// the boot process, we need to store the error as a rejection on the boot
// promise so that a future caller of `boot()` can tell what failed.
var defer = this._bootResolver = _emberRuntime.RSVP.defer();
this._bootPromise = defer.promise;
try {
this.runInitializers();
(0, _emberRuntime.runLoadHooks)('application', this);
this.advanceReadiness();
// Continues to `didBecomeReady`
} catch (error) {
// For the asynchronous boot path
defer.reject(error);
// For the synchronous boot path
throw error;
}
},
reset: function () {
(true && !(this._globalsMode && this.autoboot) && (0, _emberDebug.assert)('Calling reset() on instances of `Ember.Application` is not\n supported when globals mode is disabled; call `visit()` to\n create new `Ember.ApplicationInstance`s and dispose them\n via their `destroy()` method instead.', this._globalsMode && this.autoboot));
var instance = this.__deprecatedInstance__;
this._readinessDeferrals = 1;
this._bootPromise = null;
this._bootResolver = null;
this._booted = false;
function handleReset() {
(0, _emberMetal.run)(instance, 'destroy');
this._buildDeprecatedInstance();
_emberMetal.run.schedule('actions', this, '_bootSync');
}
_emberMetal.run.join(this, handleReset);
},
didBecomeReady: function () {
try {
// TODO: Is this still needed for _globalsMode = false?
if (!(0, _emberDebug.isTesting)()) {
// Eagerly name all classes that are already loaded
_emberRuntime.Namespace.processAll();
(0, _emberRuntime.setNamespaceSearchDisabled)(true);
}
// See documentation on `_autoboot()` for details
if (this.autoboot) {
var instance = void 0;
if (this._globalsMode) {
// If we already have the __deprecatedInstance__ lying around, boot it to
// avoid unnecessary work
instance = this.__deprecatedInstance__;
} else {
// Otherwise, build an instance and boot it. This is currently unreachable,
// because we forced _globalsMode to === autoboot; but having this branch
// allows us to locally toggle that flag for weeding out legacy globals mode
// dependencies independently
instance = this.buildInstance();
}
instance._bootSync();
// TODO: App.ready() is not called when autoboot is disabled, is this correct?
this.ready();
instance.startRouting();
}
// For the asynchronous boot path
this._bootResolver.resolve(this);
// For the synchronous boot path
this._booted = true;
} catch (error) {
// For the asynchronous boot path
this._bootResolver.reject(error);
// For the synchronous boot path
throw error;
}
},
ready: function () {
return this;
},
willDestroy: function () {
this._super.apply(this, arguments);
(0, _emberRuntime.setNamespaceSearchDisabled)(false);
this._booted = false;
this._bootPromise = null;
this._bootResolver = null;
if (_emberRuntime._loaded.application === this) {
_emberRuntime._loaded.application = undefined;
}
if (this._globalsMode && this.__deprecatedInstance__) {
this.__deprecatedInstance__.destroy();
}
},
visit: function (url, options) {
var _this = this;
return this.boot().then(function () {
var instance = _this.buildInstance();
return instance.boot(options).then(function () {
return instance.visit(url);
}).catch(function (error) {
(0, _emberMetal.run)(instance, 'destroy');
throw error;
});
});
}
});
Object.defineProperty(Application.prototype, 'registry', {
configurable: true,
enumerable: false,
get: function () {
return (0, _emberRuntime.buildFakeRegistryWithDeprecations)(this, 'Application');
}
});
Application.reopenClass({
buildRegistry: function (application) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var registry = this._super.apply(this, arguments);
commonSetupRegistry(registry);
(0, _emberGlimmer.setupApplicationRegistry)(registry);
return registry;
}
});
function commonSetupRegistry(registry) {
registry.register('router:main', _emberRouting.Router.extend());
registry.register('-view-registry:main', {
create: function () {
return (0, _emberUtils.dictionary)(null);
}
});
registry.register('route:basic', _emberRouting.Route);
registry.register('event_dispatcher:main', _emberViews.EventDispatcher);
registry.injection('router:main', 'namespace', 'application:main');
registry.register('location:auto', _emberRouting.AutoLocation);
registry.register('location:hash', _emberRouting.HashLocation);
registry.register('location:history', _emberRouting.HistoryLocation);
registry.register('location:none', _emberRouting.NoneLocation);
registry.register((0, _container.privatize)(_templateObject), _emberRouting.BucketCache);
if (_features.EMBER_ROUTING_ROUTER_SERVICE) {
registry.register('service:router', _emberRouting.RouterService);
registry.injection('service:router', '_router', 'router:main');
}
}
function registerLibraries() {
if (!librariesRegistered) {
librariesRegistered = true;
if (_emberEnvironment.environment.hasDOM && typeof _emberViews.jQuery === 'function') {
_emberMetal.libraries.registerCoreLibrary('jQuery', (0, _emberViews.jQuery)().jquery);
}
}
}
function logLibraryVersions() {
if (true) {
if (_emberEnvironment.ENV.LOG_VERSION) {
// we only need to see this once per Application#init
_emberEnvironment.ENV.LOG_VERSION = false;
var libs = _emberMetal.libraries._registry;
var nameLengths = libs.map(function (item) {
return (0, _emberMetal.get)(item, 'name.length');
});
var maxNameLength = Math.max.apply(this, nameLengths);
(0, _emberDebug.debug)('-------------------------------');
for (var i = 0; i < libs.length; i++) {
var lib = libs[i];
var spaces = new Array(maxNameLength - lib.name.length + 1).join(' ');
(0, _emberDebug.debug)([lib.name, spaces, ' : ', lib.version].join(''));
}
(0, _emberDebug.debug)('-------------------------------');
}
}
}
exports.default = Application;
});
enifed('ember-application/system/engine-instance', ['exports', 'ember-babel', 'ember-utils', 'ember-runtime', 'ember-debug', 'ember-metal', 'container', 'ember-application/system/engine-parent'], function (exports, _emberBabel, _emberUtils, _emberRuntime, _emberDebug, _emberMetal, _container, _engineParent) {
'use strict';
var _templateObject = (0, _emberBabel.taggedTemplateLiteralLoose)(['-bucket-cache:main'], ['-bucket-cache:main']);
/**
The `EngineInstance` encapsulates all of the stateful aspects of a
running `Engine`.
@public
@class EngineInstance
@extends EmberObject
@uses RegistryProxyMixin
@uses ContainerProxyMixin
*/
var EngineInstance = _emberRuntime.Object.extend(_emberRuntime.RegistryProxyMixin, _emberRuntime.ContainerProxyMixin, {
/**
The base `Engine` for which this is an instance.
@property {Ember.Engine} engine
@private
*/
base: null,
init: function () {
this._super.apply(this, arguments);
(0, _emberUtils.guidFor)(this);
var base = this.base;
if (!base) {
base = this.application;
this.base = base;
}
// Create a per-instance registry that will use the application's registry
// as a fallback for resolving registrations.
var registry = this.__registry__ = new _container.Registry({
fallback: base.__registry__
});
// Create a per-instance container from the instance's registry
this.__container__ = registry.container({ owner: this });
this._booted = false;
},
boot: function (options) {
var _this = this;
if (this._bootPromise) {
return this._bootPromise;
}
this._bootPromise = new _emberRuntime.RSVP.Promise(function (resolve) {
return resolve(_this._bootSync(options));
});
return this._bootPromise;
},
_bootSync: function (options) {
if (this._booted) {
return this;
}
(true && !((0, _engineParent.getEngineParent)(this)) && (0, _emberDebug.assert)('An engine instance\'s parent must be set via `setEngineParent(engine, parent)` prior to calling `engine.boot()`.', (0, _engineParent.getEngineParent)(this)));
this.cloneParentDependencies();
this.setupRegistry(options);
this.base.runInstanceInitializers(this);
this._booted = true;
return this;
},
setupRegistry: function () {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.__container__.lookup('-environment:main');
this.constructor.setupRegistry(this.__registry__, options);
},
unregister: function (fullName) {
this.__container__.reset(fullName);
this._super.apply(this, arguments);
},
buildChildEngineInstance: function (name) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var Engine = this.lookup('engine:' + name);
if (!Engine) {
throw new _emberDebug.Error('You attempted to mount the engine \'' + name + '\', but it is not registered with its parent.');
}
var engineInstance = Engine.buildInstance(options);
(0, _engineParent.setEngineParent)(engineInstance, this);
return engineInstance;
},
cloneParentDependencies: function () {
var _this2 = this;
var parent = (0, _engineParent.getEngineParent)(this);
var registrations = ['route:basic', 'service:-routing', 'service:-glimmer-environment'];
registrations.forEach(function (key) {
return _this2.register(key, parent.resolveRegistration(key));
});
var env = parent.lookup('-environment:main');
this.register('-environment:main', env, { instantiate: false });
var singletons = ['router:main', (0, _container.privatize)(_templateObject), '-view-registry:main', 'renderer:-' + (env.isInteractive ? 'dom' : 'inert'), 'service:-document'];
if (env.isInteractive) {
singletons.push('event_dispatcher:main');
}
singletons.forEach(function (key) {
return _this2.register(key, parent.lookup(key), { instantiate: false });
});
this.inject('view', '_environment', '-environment:main');
this.inject('route', '_environment', '-environment:main');
}
});
EngineInstance.reopenClass({
setupRegistry: function (registry, options) {
// when no options/environment is present, do nothing
if (!options) {
return;
}
registry.injection('view', '_environment', '-environment:main');
registry.injection('route', '_environment', '-environment:main');
if (options.isInteractive) {
registry.injection('view', 'renderer', 'renderer:-dom');
registry.injection('component', 'renderer', 'renderer:-dom');
} else {
registry.injection('view', 'renderer', 'renderer:-inert');
registry.injection('component', 'renderer', 'renderer:-inert');
}
}
});
exports.default = EngineInstance;
});
enifed('ember-application/system/engine-parent', ['exports', 'ember-utils'], function (exports, _emberUtils) {
'use strict';
exports.ENGINE_PARENT = undefined;
exports.getEngineParent = getEngineParent;
exports.setEngineParent = setEngineParent;
var ENGINE_PARENT = exports.ENGINE_PARENT = (0, _emberUtils.symbol)('ENGINE_PARENT');
/**
`getEngineParent` retrieves an engine instance's parent instance.
@method getEngineParent
@param {EngineInstance} engine An engine instance.
@return {EngineInstance} The parent engine instance.
@for @ember/engine
@static
@private
*/
function getEngineParent(engine) {
return engine[ENGINE_PARENT];
}
/**
`setEngineParent` sets an engine instance's parent instance.
@method setEngineParent
@param {EngineInstance} engine An engine instance.
@param {EngineInstance} parent The parent engine instance.
@private
*/
function setEngineParent(engine, parent) {
engine[ENGINE_PARENT] = parent;
}
});
enifed('ember-application/system/engine', ['exports', 'ember-babel', 'ember-utils', 'ember-runtime', 'container', 'dag-map', 'ember-debug', 'ember-metal', 'ember-application/system/resolver', 'ember-application/system/engine-instance', 'ember-routing', 'ember-extension-support', 'ember-views', 'ember-glimmer'], function (exports, _emberBabel, _emberUtils, _emberRuntime, _container, _dagMap, _emberDebug, _emberMetal, _resolver, _engineInstance, _emberRouting, _emberExtensionSupport, _emberViews, _emberGlimmer) {
'use strict';
var _templateObject = (0, _emberBabel.taggedTemplateLiteralLoose)(['-bucket-cache:main'], ['-bucket-cache:main']);
function props(obj) {
var properties = [];
for (var key in obj) {
properties.push(key);
}
return properties;
}
/**
The `Engine` class contains core functionality for both applications and
engines.
Each engine manages a registry that's used for dependency injection and
exposed through `RegistryProxy`.
Engines also manage initializers and instance initializers.
Engines can spawn `EngineInstance` instances via `buildInstance()`.
@class Engine
@extends Ember.Namespace
@uses RegistryProxy
@public
*/
var Engine = _emberRuntime.Namespace.extend(_emberRuntime.RegistryProxyMixin, {
init: function () {
this._super.apply(this, arguments);
this.buildRegistry();
},
/**
A private flag indicating whether an engine's initializers have run yet.
@private
@property _initializersRan
*/
_initializersRan: false,
ensureInitializers: function () {
if (!this._initializersRan) {
this.runInitializers();
this._initializersRan = true;
}
},
buildInstance: function () {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
this.ensureInitializers();
options.base = this;
return _engineInstance.default.create(options);
},
buildRegistry: function () {
var registry = this.__registry__ = this.constructor.buildRegistry(this);
return registry;
},
initializer: function (options) {
this.constructor.initializer(options);
},
instanceInitializer: function (options) {
this.constructor.instanceInitializer(options);
},
runInitializers: function () {
var _this = this;
this._runInitializer('initializers', function (name, initializer) {
(true && !(!!initializer) && (0, _emberDebug.assert)('No application initializer named \'' + name + '\'', !!initializer));
if (initializer.initialize.length === 2) {
(true && !(false) && (0, _emberDebug.deprecate)('The `initialize` method for Application initializer \'' + name + '\' should take only one argument - `App`, an instance of an `Application`.', false, {
id: 'ember-application.app-initializer-initialize-arguments',
until: '3.0.0',
url: 'https://emberjs.com/deprecations/v2.x/#toc_initializer-arity'
}));
initializer.initialize(_this.__registry__, _this);
} else {
initializer.initialize(_this);
}
});
},
runInstanceInitializers: function (instance) {
this._runInitializer('instanceInitializers', function (name, initializer) {
(true && !(!!initializer) && (0, _emberDebug.assert)('No instance initializer named \'' + name + '\'', !!initializer));
initializer.initialize(instance);
});
},
_runInitializer: function (bucketName, cb) {
var initializersByName = (0, _emberMetal.get)(this.constructor, bucketName);
var initializers = props(initializersByName);
var graph = new _dagMap.default();
var initializer = void 0;
for (var i = 0; i < initializers.length; i++) {
initializer = initializersByName[initializers[i]];
graph.add(initializer.name, initializer, initializer.before, initializer.after);
}
graph.topsort(cb);
}
});
Engine.reopenClass({
initializers: Object.create(null),
instanceInitializers: Object.create(null),
/**
The goal of initializers should be to register dependencies and injections.
This phase runs once. Because these initializers may load code, they are
allowed to defer application readiness and advance it. If you need to access
the container or store you should use an InstanceInitializer that will be run
after all initializers and therefore after all code is loaded and the app is
ready.
Initializer receives an object which has the following attributes:
`name`, `before`, `after`, `initialize`. The only required attribute is
`initialize`, all others are optional.
* `name` allows you to specify under which name the initializer is registered.
This must be a unique name, as trying to register two initializers with the
same name will result in an error.
```app/initializer/named-initializer.js
import { debug } from '@ember/debug';
export function initialize() {
debug('Running namedInitializer!');
}
export default {
name: 'named-initializer',
initialize
};
```
* `before` and `after` are used to ensure that this initializer is ran prior
or after the one identified by the value. This value can be a single string
or an array of strings, referencing the `name` of other initializers.
An example of ordering initializers, we create an initializer named `first`:
```app/initializer/first.js
import { debug } from '@ember/debug';
export function initialize() {
debug('First initializer!');
}
export default {
name: 'first',
initialize
};
```
```bash
// DEBUG: First initializer!
```
We add another initializer named `second`, specifying that it should run
after the initializer named `first`:
```app/initializer/second.js
import { debug } from '@ember/debug';
export function initialize() {
debug('Second initializer!');
}
export default {
name: 'second',
after: 'first',
initialize
};
```
```
// DEBUG: First initializer!
// DEBUG: Second initializer!
```
Afterwards we add a further initializer named `pre`, this time specifying
that it should run before the initializer named `first`:
```app/initializer/pre.js
import { debug } from '@ember/debug';
export function initialize() {
debug('Pre initializer!');
}
export default {
name: 'pre',
before: 'first',
initialize
};
```
```bash
// DEBUG: Pre initializer!
// DEBUG: First initializer!
// DEBUG: Second initializer!
```
Finally we add an initializer named `post`, specifying it should run after
both the `first` and the `second` initializers:
```app/initializer/post.js
import { debug } from '@ember/debug';
export function initialize() {
debug('Post initializer!');
}
export default {
name: 'post',
after: ['first', 'second'],
initialize
};
```
```bash
// DEBUG: Pre initializer!
// DEBUG: First initializer!
// DEBUG: Second initializer!
// DEBUG: Post initializer!
```
* `initialize` is a callback function that receives one argument,
`application`, on which you can operate.
Example of using `application` to register an adapter:
```app/initializer/api-adapter.js
import ApiAdapter from '../utils/api-adapter';
export function initialize(application) {
application.register('api-adapter:main', ApiAdapter);
}
export default {
name: 'post',
after: ['first', 'second'],
initialize
};
```
@method initializer
@param initializer {Object}
@public
*/
initializer: buildInitializerMethod('initializers', 'initializer'),
/**
Instance initializers run after all initializers have run. Because
instance initializers run after the app is fully set up. We have access
to the store, container, and other items. However, these initializers run
after code has loaded and are not allowed to defer readiness.
Instance initializer receives an object which has the following attributes:
`name`, `before`, `after`, `initialize`. The only required attribute is
`initialize`, all others are optional.
* `name` allows you to specify under which name the instanceInitializer is
registered. This must be a unique name, as trying to register two
instanceInitializer with the same name will result in an error.
```app/initializer/named-instance-initializer.js
import { debug } from '@ember/debug';
export function initialize() {
debug('Running named-instance-initializer!');
}
export default {
name: 'named-instance-initializer',
initialize
};
```
* `before` and `after` are used to ensure that this initializer is ran prior
or after the one identified by the value. This value can be a single string
or an array of strings, referencing the `name` of other initializers.
* See Ember.Application.initializer for discussion on the usage of before
and after.
Example instanceInitializer to preload data into the store.
```app/initializer/preload-data.js
import $ from 'jquery';
export function initialize(application) {
var userConfig, userConfigEncoded, store;
// We have a HTML escaped JSON representation of the user's basic
// configuration generated server side and stored in the DOM of the main
// index.html file. This allows the app to have access to a set of data
// without making any additional remote calls. Good for basic data that is
// needed for immediate rendering of the page. Keep in mind, this data,
// like all local models and data can be manipulated by the user, so it
// should not be relied upon for security or authorization.
// Grab the encoded data from the meta tag
userConfigEncoded = $('head meta[name=app-user-config]').attr('content');
// Unescape the text, then parse the resulting JSON into a real object
userConfig = JSON.parse(unescape(userConfigEncoded));
// Lookup the store
store = application.lookup('service:store');
// Push the encoded JSON into the store
store.pushPayload(userConfig);
}
export default {
name: 'named-instance-initializer',
initialize
};
```
@method instanceInitializer
@param instanceInitializer
@public
*/
instanceInitializer: buildInitializerMethod('instanceInitializers', 'instance initializer'),
buildRegistry: function (namespace) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var registry = new _container.Registry({
resolver: resolverFor(namespace)
});
registry.set = _emberMetal.set;
registry.register('application:main', namespace, { instantiate: false });
commonSetupRegistry(registry);
(0, _emberGlimmer.setupEngineRegistry)(registry);
return registry;
},
/**
Set this to provide an alternate class to `Ember.DefaultResolver`
@deprecated Use 'Resolver' instead
@property resolver
@public
*/
resolver: null,
/**
Set this to provide an alternate class to `Ember.DefaultResolver`
@property resolver
@public
*/
Resolver: null
});
/**
This function defines the default lookup rules for container lookups:
* templates are looked up on `Ember.TEMPLATES`
* other names are looked up on the application after classifying the name.
For example, `controller:post` looks up `App.PostController` by default.
* if the default lookup fails, look for registered classes on the container
This allows the application to register default injections in the container
that could be overridden by the normal naming convention.
@private
@method resolverFor
@param {Ember.Namespace} namespace the namespace to look for classes
@return {*} the resolved value for a given lookup
*/
function resolverFor(namespace) {
var ResolverClass = namespace.get('Resolver') || _resolver.default;
return ResolverClass.create({
namespace: namespace
});
}
function buildInitializerMethod(bucketName, humanName) {
return function (initializer) {
// If this is the first initializer being added to a subclass, we are going to reopen the class
// to make sure we have a new `initializers` object, which extends from the parent class' using
// prototypal inheritance. Without this, attempting to add initializers to the subclass would
// pollute the parent class as well as other subclasses.
if (this.superclass[bucketName] !== undefined && this.superclass[bucketName] === this[bucketName]) {
var attrs = {};
attrs[bucketName] = Object.create(this[bucketName]);
this.reopenClass(attrs);
}
(true && !(!this[bucketName][initializer.name]) && (0, _emberDebug.assert)('The ' + humanName + ' \'' + initializer.name + '\' has already been registered', !this[bucketName][initializer.name]));
(true && !((0, _emberUtils.canInvoke)(initializer, 'initialize')) && (0, _emberDebug.assert)('An ' + humanName + ' cannot be registered without an initialize function', (0, _emberUtils.canInvoke)(initializer, 'initialize')));
(true && !(initializer.name !== undefined) && (0, _emberDebug.assert)('An ' + humanName + ' cannot be registered without a name property', initializer.name !== undefined));
this[bucketName][initializer.name] = initializer;
};
}
function commonSetupRegistry(registry) {
registry.optionsForType('component', { singleton: false });
registry.optionsForType('view', { singleton: false });
registry.register('controller:basic', _emberRuntime.Controller, { instantiate: false });
registry.injection('view', '_viewRegistry', '-view-registry:main');
registry.injection('renderer', '_viewRegistry', '-view-registry:main');
registry.injection('event_dispatcher:main', '_viewRegistry', '-view-registry:main');
registry.injection('route', '_topLevelViewTemplate', 'template:-outlet');
registry.injection('view:-outlet', 'namespace', 'application:main');
registry.injection('controller', 'target', 'router:main');
registry.injection('controller', 'namespace', 'application:main');
registry.injection('router', '_bucketCache', (0, _container.privatize)(_templateObject));
registry.injection('route', '_bucketCache', (0, _container.privatize)(_templateObject));
registry.injection('route', 'router', 'router:main');
// Register the routing service...
registry.register('service:-routing', _emberRouting.RoutingService);
// Then inject the app router into it
registry.injection('service:-routing', 'router', 'router:main');
// DEBUGGING
registry.register('resolver-for-debugging:main', registry.resolver, { instantiate: false });
registry.injection('container-debug-adapter:main', 'resolver', 'resolver-for-debugging:main');
registry.injection('data-adapter:main', 'containerDebugAdapter', 'container-debug-adapter:main');
// Custom resolver authors may want to register their own ContainerDebugAdapter with this key
registry.register('container-debug-adapter:main', _emberExtensionSupport.ContainerDebugAdapter);
registry.register('component-lookup:main', _emberViews.ComponentLookup);
}
exports.default = Engine;
});
enifed('ember-application/system/resolver', ['exports', 'ember-utils', 'ember-metal', 'ember-debug', 'ember-runtime', 'ember-application/utils/validate-type', 'ember-glimmer'], function (exports, _emberUtils, _emberMetal, _emberDebug, _emberRuntime, _validateType, _emberGlimmer) {
'use strict';
exports.Resolver = undefined;
/**
@module @ember/application
*/
var Resolver = exports.Resolver = _emberRuntime.Object.extend({
/*
This will be set to the Application instance when it is
created.
@property namespace
*/
namespace: null,
normalize: null, // required
resolve: null, // required
parseName: null, // required
lookupDescription: null, // required
makeToString: null, // required
resolveOther: null, // required
_logLookup: null // required
});
/**
The DefaultResolver defines the default lookup rules to resolve
container lookups before consulting the container for registered
items:
* templates are looked up on `Ember.TEMPLATES`
* other names are looked up on the application after converting
the name. For example, `controller:post` looks up
`App.PostController` by default.
* there are some nuances (see examples below)
### How Resolving Works
The container calls this object's `resolve` method with the
`fullName` argument.
It first parses the fullName into an object using `parseName`.
Then it checks for the presence of a type-specific instance
method of the form `resolve[Type]` and calls it if it exists.
For example if it was resolving 'template:post', it would call
the `resolveTemplate` method.
Its last resort is to call the `resolveOther` method.
The methods of this object are designed to be easy to override
in a subclass. For example, you could enhance how a template
is resolved like so:
```app/app.js
import Application from '@ember/application';
import GlobalsResolver from '@ember/application/globals-resolver';
App = Application.create({
Resolver: GlobalsResolver.extend({
resolveTemplate(parsedName) {
let resolvedTemplate = this._super(parsedName);
if (resolvedTemplate) { return resolvedTemplate; }
return Ember.TEMPLATES['not_found'];
}
})
});
```
Some examples of how names are resolved:
```text
'template:post' //=> Ember.TEMPLATES['post']
'template:posts/byline' //=> Ember.TEMPLATES['posts/byline']
'template:posts.byline' //=> Ember.TEMPLATES['posts/byline']
'template:blogPost' //=> Ember.TEMPLATES['blog-post']
'controller:post' //=> App.PostController
'controller:posts.index' //=> App.PostsIndexController
'controller:blog/post' //=> Blog.PostController
'controller:basic' //=> Controller
'route:post' //=> App.PostRoute
'route:posts.index' //=> App.PostsIndexRoute
'route:blog/post' //=> Blog.PostRoute
'route:basic' //=> Route
'foo:post' //=> App.PostFoo
'model:post' //=> App.Post
```
@class GlobalsResolver
@extends EmberObject
@public
*/
var DefaultResolver = _emberRuntime.Object.extend({
/**
This will be set to the Application instance when it is
created.
@property namespace
@public
*/
namespace: null,
init: function () {
this._parseNameCache = (0, _emberUtils.dictionary)(null);
},
normalize: function (fullName) {
var _fullName$split = fullName.split(':'),
type = _fullName$split[0],
name = _fullName$split[1];
(true && !(fullName.split(':').length === 2) && (0, _emberDebug.assert)('Tried to normalize a container name without a colon (:) in it. ' + 'You probably tried to lookup a name that did not contain a type, ' + 'a colon, and a name. A proper lookup name would be `view:post`.', fullName.split(':').length === 2));
if (type !== 'template') {
var result = name.replace(/(\.|_|-)./g, function (m) {
return m.charAt(1).toUpperCase();
});
return type + ':' + result;
} else {
return fullName;
}
},
resolve: function (fullName) {
var parsedName = this.parseName(fullName);
var resolveMethodName = parsedName.resolveMethodName;
var resolved = void 0;
if (this[resolveMethodName]) {
resolved = this[resolveMethodName](parsedName);
}
resolved = resolved || this.resolveOther(parsedName);
if (true) {
if (parsedName.root && parsedName.root.LOG_RESOLVER) {
this._logLookup(resolved, parsedName);
}
}
if (resolved) {
(0, _validateType.default)(resolved, parsedName);
}
return resolved;
},
parseName: function (fullName) {
return this._parseNameCache[fullName] || (this._parseNameCache[fullName] = this._parseName(fullName));
},
_parseName: function (fullName) {
var _fullName$split2 = fullName.split(':'),
type = _fullName$split2[0],
fullNameWithoutType = _fullName$split2[1];
var name = fullNameWithoutType;
var namespace = (0, _emberMetal.get)(this, 'namespace');
var root = namespace;
var lastSlashIndex = name.lastIndexOf('/');
var dirname = lastSlashIndex !== -1 ? name.slice(0, lastSlashIndex) : null;
if (type !== 'template' && lastSlashIndex !== -1) {
var parts = name.split('/');
name = parts[parts.length - 1];
var namespaceName = _emberRuntime.String.capitalize(parts.slice(0, -1).join('.'));
root = _emberRuntime.Namespace.byName(namespaceName);
(true && !(root) && (0, _emberDebug.assert)('You are looking for a ' + name + ' ' + type + ' in the ' + namespaceName + ' namespace, but the namespace could not be found', root));
}
var resolveMethodName = fullNameWithoutType === 'main' ? 'Main' : _emberRuntime.String.classify(type);
if (!(name && type)) {
throw new TypeError('Invalid fullName: `' + fullName + '`, must be of the form `type:name` ');
}
return {
fullName: fullName,
type: type,
fullNameWithoutType: fullNameWithoutType,
dirname: dirname,
name: name,
root: root,
resolveMethodName: 'resolve' + resolveMethodName
};
},
lookupDescription: function (fullName) {
var parsedName = this.parseName(fullName);
var description = void 0;
if (parsedName.type === 'template') {
return 'template at ' + parsedName.fullNameWithoutType.replace(/\./g, '/');
}
description = parsedName.root + '.' + _emberRuntime.String.classify(parsedName.name).replace(/\./g, '');
if (parsedName.type !== 'model') {
description += _emberRuntime.String.classify(parsedName.type);
}
return description;
},
makeToString: function (factory, fullName) {
return factory.toString();
},
useRouterNaming: function (parsedName) {
if (parsedName.name === 'basic') {
parsedName.name = '';
} else {
parsedName.name = parsedName.name.replace(/\./g, '_');
}
},
resolveTemplate: function (parsedName) {
var templateName = parsedName.fullNameWithoutType.replace(/\./g, '/');
return (0, _emberGlimmer.getTemplate)(templateName) || (0, _emberGlimmer.getTemplate)(_emberRuntime.String.decamelize(templateName));
},
resolveView: function (parsedName) {
this.useRouterNaming(parsedName);
return this.resolveOther(parsedName);
},
resolveController: function (parsedName) {
this.useRouterNaming(parsedName);
return this.resolveOther(parsedName);
},
resolveRoute: function (parsedName) {
this.useRouterNaming(parsedName);
return this.resolveOther(parsedName);
},
resolveModel: function (parsedName) {
var className = _emberRuntime.String.classify(parsedName.name);
var factory = (0, _emberMetal.get)(parsedName.root, className);
return factory;
},
resolveHelper: function (parsedName) {
return this.resolveOther(parsedName);
},
resolveOther: function (parsedName) {
var className = _emberRuntime.String.classify(parsedName.name) + _emberRuntime.String.classify(parsedName.type);
var factory = (0, _emberMetal.get)(parsedName.root, className);
return factory;
},
resolveMain: function (parsedName) {
var className = _emberRuntime.String.classify(parsedName.type);
return (0, _emberMetal.get)(parsedName.root, className);
},
knownForType: function (type) {
var namespace = (0, _emberMetal.get)(this, 'namespace');
var suffix = _emberRuntime.String.classify(type);
var typeRegexp = new RegExp(suffix + '$');
var known = (0, _emberUtils.dictionary)(null);
var knownKeys = Object.keys(namespace);
for (var index = 0; index < knownKeys.length; index++) {
var name = knownKeys[index];
if (typeRegexp.test(name)) {
var containerName = this.translateToContainerFullname(type, name);
known[containerName] = true;
}
}
return known;
},
translateToContainerFullname: function (type, name) {
var suffix = _emberRuntime.String.classify(type);
var namePrefix = name.slice(0, suffix.length * -1);
var dasherizedName = _emberRuntime.String.dasherize(namePrefix);
return type + ':' + dasherizedName;
}
});
exports.default = DefaultResolver;
if (true) {
DefaultResolver.reopen({
_logLookup: function (found, parsedName) {
var symbol = found ? '[✓]' : '[ ]';
var padding = void 0;
if (parsedName.fullName.length > 60) {
padding = '.';
} else {
padding = new Array(60 - parsedName.fullName.length).join('.');
}
(0, _emberDebug.info)(symbol, parsedName.fullName, padding, this.lookupDescription(parsedName.fullName));
}
});
}
});
enifed('ember-application/utils/validate-type', ['exports', 'ember-debug'], function (exports, _emberDebug) {
'use strict';
exports.default = validateType;
var VALIDATED_TYPES = {
route: ['assert', 'isRouteFactory', 'Ember.Route'],
component: ['deprecate', 'isComponentFactory', 'Ember.Component'],
view: ['deprecate', 'isViewFactory', 'Ember.View'],
service: ['deprecate', 'isServiceFactory', 'Ember.Service']
};
function validateType(resolvedType, parsedName) {
var validationAttributes = VALIDATED_TYPES[parsedName.type];
if (!validationAttributes) {
return;
}
var action = validationAttributes[0],
factoryFlag = validationAttributes[1],
expectedType = validationAttributes[2];
(true && !(!!resolvedType[factoryFlag]) && (0, _emberDebug.assert)('Expected ' + parsedName.fullName + ' to resolve to an ' + expectedType + ' but ' + ('instead it was ' + resolvedType + '.'), !!resolvedType[factoryFlag]));
}
});
enifed('ember-babel', ['exports'], function (exports) {
'use strict';
exports.classCallCheck = classCallCheck;
exports.inherits = inherits;
exports.taggedTemplateLiteralLoose = taggedTemplateLiteralLoose;
exports.createClass = createClass;
exports.defaults = defaults;
function classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError('Cannot call a class as a function');
}
}
function inherits(subClass, superClass) {
if (typeof superClass !== 'function' && superClass !== null) {
throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass);
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : defaults(subClass, superClass);
}
function taggedTemplateLiteralLoose(strings, raw) {
strings.raw = raw;
return strings;
}
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ('value' in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function createClass(Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
}
function defaults(obj, defaults) {
var keys = Object.getOwnPropertyNames(defaults);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var value = Object.getOwnPropertyDescriptor(defaults, key);
if (value && value.configurable && obj[key] === undefined) {
Object.defineProperty(obj, key, value);
}
}
return obj;
}
var possibleConstructorReturn = exports.possibleConstructorReturn = function (self, call) {
if (!self) {
throw new ReferenceError('this hasn\'t been initialized - super() hasn\'t been called');
}
return call && (typeof call === 'object' || typeof call === 'function') ? call : self;
};
var slice = exports.slice = Array.prototype.slice;
});
enifed('ember-console', ['exports', 'ember-environment'], function (exports, _emberEnvironment) {
'use strict';
function K() {}
function consoleMethod(name) {
var consoleObj = void 0;
if (_emberEnvironment.context.imports.console) {
consoleObj = _emberEnvironment.context.imports.console;
} else if (typeof console !== 'undefined') {
// eslint-disable-line no-undef
consoleObj = console; // eslint-disable-line no-undef
}
var method = typeof consoleObj === 'object' ? consoleObj[name] : null;
if (typeof method !== 'function') {
return;
}
return method.bind(consoleObj);
}
function assertPolyfill(test, message) {
if (!test) {
try {
// attempt to preserve the stack
throw new Error('assertion failed: ' + message);
} catch (error) {
setTimeout(function () {
throw error;
}, 0);
}
}
}
/**
Inside Ember-Metal, simply uses the methods from `imports.console`.
Override this to provide more robust logging functionality.
@class Logger
@namespace Ember
@public
*/
var index = {
/**
Logs the arguments to the console.
You can pass as many arguments as you want and they will be joined together with a space.
```javascript
var foo = 1;
Ember.Logger.log('log value of foo:', foo);
// "log value of foo: 1" will be printed to the console
```
@method log
@for Ember.Logger
@param {*} arguments
@public
*/
log: consoleMethod('log') || K,
/**
Prints the arguments to the console with a warning icon.
You can pass as many arguments as you want and they will be joined together with a space.
```javascript
Ember.Logger.warn('Something happened!');
// "Something happened!" will be printed to the console with a warning icon.
```
@method warn
@for Ember.Logger
@param {*} arguments
@public
*/
warn: consoleMethod('warn') || K,
/**
Prints the arguments to the console with an error icon, red text and a stack trace.
You can pass as many arguments as you want and they will be joined together with a space.
```javascript
Ember.Logger.error('Danger! Danger!');
// "Danger! Danger!" will be printed to the console in red text.
```
@method error
@for Ember.Logger
@param {*} arguments
@public
*/
error: consoleMethod('error') || K,
/**
Logs the arguments to the console.
You can pass as many arguments as you want and they will be joined together with a space.
```javascript
var foo = 1;
Ember.Logger.info('log value of foo:', foo);
// "log value of foo: 1" will be printed to the console
```
@method info
@for Ember.Logger
@param {*} arguments
@public
*/
info: consoleMethod('info') || K,
/**
Logs the arguments to the console in blue text.
You can pass as many arguments as you want and they will be joined together with a space.
```javascript
var foo = 1;
Ember.Logger.debug('log value of foo:', foo);
// "log value of foo: 1" will be printed to the console
```
@method debug
@for Ember.Logger
@param {*} arguments
@public
*/
debug: consoleMethod('debug') || consoleMethod('info') || K,
/**
If the value passed into `Ember.Logger.assert` is not truthy it will throw an error with a stack trace.
```javascript
Ember.Logger.assert(true); // undefined
Ember.Logger.assert(true === false); // Throws an Assertion failed error.
Ember.Logger.assert(true === false, 'Something invalid'); // Throws an Assertion failed error with message.
```
@method assert
@for Ember.Logger
@param {Boolean} bool Value to test
@param {String} message Assertion message on failed
@public
*/
assert: consoleMethod('assert') || assertPolyfill
};
exports.default = index;
});
enifed('ember-debug/deprecate', ['exports', 'ember-debug/error', 'ember-console', 'ember-environment', 'ember-debug/handlers'], function (exports, _error, _emberConsole, _emberEnvironment, _handlers) {
'use strict';
exports.missingOptionsUntilDeprecation = exports.missingOptionsIdDeprecation = exports.missingOptionsDeprecation = exports.registerHandler = undefined;
/**
@module @ember/debug
@public
*/
/**
Allows for runtime registration of handler functions that override the default deprecation behavior.
Deprecations are invoked by calls to [Ember.deprecate](https://emberjs.com/api/classes/Ember.html#method_deprecate).
The following example demonstrates its usage by registering a handler that throws an error if the
message contains the word "should", otherwise defers to the default handler.
```javascript
Ember.Debug.registerDeprecationHandler((message, options, next) => {
if (message.indexOf('should') !== -1) {
throw new Error(`Deprecation message with should: ${message}`);
} else {
// defer to whatever handler was registered before this one
next(message, options);
}
});
```
The handler function takes the following arguments:
<ul>
<li> <code>message</code> - The message received from the deprecation call.</li>
<li> <code>options</code> - An object passed in with the deprecation call containing additional information including:</li>
<ul>
<li> <code>id</code> - An id of the deprecation in the form of <code>package-name.specific-deprecation</code>.</li>
<li> <code>until</code> - The Ember version number the feature and deprecation will be removed in.</li>
</ul>
<li> <code>next</code> - A function that calls into the previously registered handler.</li>
</ul>
@public
@static
@method registerDeprecationHandler
@for @ember/debug
@param handler {Function} A function to handle deprecation calls.
@since 2.1.0
*/
var registerHandler = function () {}; /*global __fail__*/
var missingOptionsDeprecation = void 0,
missingOptionsIdDeprecation = void 0,
missingOptionsUntilDeprecation = void 0,
deprecate = void 0;
if (true) {
exports.registerHandler = registerHandler = function registerHandler(handler) {
(0, _handlers.registerHandler)('deprecate', handler);
};
var formatMessage = function formatMessage(_message, options) {
var message = _message;
if (options && options.id) {
message = message + (' [deprecation id: ' + options.id + ']');
}
if (options && options.url) {
message += ' See ' + options.url + ' for more details.';
}
return message;
};
registerHandler(function logDeprecationToConsole(message, options) {
var updatedMessage = formatMessage(message, options);
_emberConsole.default.warn('DEPRECATION: ' + updatedMessage);
});
var captureErrorForStack = void 0;
if (new Error().stack) {
captureErrorForStack = function () {
return new Error();
};
} else {
captureErrorForStack = function () {
try {
__fail__.fail();
} catch (e) {
return e;
}
};
}
registerHandler(function logDeprecationStackTrace(message, options, next) {
if (_emberEnvironment.ENV.LOG_STACKTRACE_ON_DEPRECATION) {
var stackStr = '';
var error = captureErrorForStack();
var stack = void 0;
if (error.stack) {
if (error['arguments']) {
// Chrome
stack = error.stack.replace(/^\s+at\s+/gm, '').replace(/^([^\(]+?)([\n$])/gm, '{anonymous}($1)$2').replace(/^Object.<anonymous>\s*\(([^\)]+)\)/gm, '{anonymous}($1)').split('\n');
stack.shift();
} else {
// Firefox
stack = error.stack.replace(/(?:\n@:0)?\s+$/m, '').replace(/^\(/gm, '{anonymous}(').split('\n');
}
stackStr = '\n ' + stack.slice(2).join('\n ');
}
var updatedMessage = formatMessage(message, options);
_emberConsole.default.warn('DEPRECATION: ' + updatedMessage + stackStr);
} else {
next.apply(undefined, arguments);
}
});
registerHandler(function raiseOnDeprecation(message, options, next) {
if (_emberEnvironment.ENV.RAISE_ON_DEPRECATION) {
var updatedMessage = formatMessage(message);
throw new _error.default(updatedMessage);
} else {
next.apply(undefined, arguments);
}
});
exports.missingOptionsDeprecation = missingOptionsDeprecation = 'When calling `Ember.deprecate` you ' + 'must provide an `options` hash as the third parameter. ' + '`options` should include `id` and `until` properties.';
exports.missingOptionsIdDeprecation = missingOptionsIdDeprecation = 'When calling `Ember.deprecate` you must provide `id` in options.';
exports.missingOptionsUntilDeprecation = missingOptionsUntilDeprecation = 'When calling `Ember.deprecate` you must provide `until` in options.';
/**
@module @ember/application
@public
*/
/**
Display a deprecation warning with the provided message and a stack trace
(Chrome and Firefox only).
* In a production build, this method is defined as an empty function (NOP).
Uses of this method in Ember itself are stripped from the ember.prod.js build.
@method deprecate
@for @ember/application/deprecations
@param {String} message A description of the deprecation.
@param {Boolean} test A boolean. If falsy, the deprecation will be displayed.
@param {Object} options
@param {String} options.id A unique id for this deprecation. The id can be
used by Ember debugging tools to change the behavior (raise, log or silence)
for that specific deprecation. The id should be namespaced by dots, e.g.
"view.helper.select".
@param {string} options.until The version of Ember when this deprecation
warning will be removed.
@param {String} [options.url] An optional url to the transition guide on the
emberjs.com website.
@static
@public
@since 1.0.0
*/
deprecate = function deprecate(message, test, options) {
if (!options || !options.id && !options.until) {
deprecate(missingOptionsDeprecation, false, {
id: 'ember-debug.deprecate-options-missing',
until: '3.0.0',
url: 'https://emberjs.com/deprecations/v2.x/#toc_ember-debug-function-options'
});
}
if (options && !options.id) {
deprecate(missingOptionsIdDeprecation, false, {
id: 'ember-debug.deprecate-id-missing',
until: '3.0.0',
url: 'https://emberjs.com/deprecations/v2.x/#toc_ember-debug-function-options'
});
}
if (options && !options.until) {
deprecate(missingOptionsUntilDeprecation, options && options.until, {
id: 'ember-debug.deprecate-until-missing',
until: '3.0.0',
url: 'https://emberjs.com/deprecations/v2.x/#toc_ember-debug-function-options'
});
}
_handlers.invoke.apply(undefined, ['deprecate'].concat(Array.prototype.slice.call(arguments)));
};
}
exports.default = deprecate;
exports.registerHandler = registerHandler;
exports.missingOptionsDeprecation = missingOptionsDeprecation;
exports.missingOptionsIdDeprecation = missingOptionsIdDeprecation;
exports.missingOptionsUntilDeprecation = missingOptionsUntilDeprecation;
});
enifed("ember-debug/error", ["exports", "ember-babel"], function (exports, _emberBabel) {
"use strict";
/**
@module @ember/error
*/
function ExtendBuiltin(klass) {
function ExtendableBuiltin() {
klass.apply(this, arguments);
}
ExtendableBuiltin.prototype = Object.create(klass.prototype);
ExtendableBuiltin.prototype.constructor = ExtendableBuiltin;
return ExtendableBuiltin;
}
/**
A subclass of the JavaScript Error object for use in Ember.
@class EmberError
@extends Error
@constructor
@public
*/
var EmberError = function (_ExtendBuiltin) {
(0, _emberBabel.inherits)(EmberError, _ExtendBuiltin);
function EmberError(message) {
(0, _emberBabel.classCallCheck)(this, EmberError);
var _this = (0, _emberBabel.possibleConstructorReturn)(this, _ExtendBuiltin.call(this));
if (!(_this instanceof EmberError)) {
var _ret;
return _ret = new EmberError(message), (0, _emberBabel.possibleConstructorReturn)(_this, _ret);
}
var error = Error.call(_this, message);
_this.stack = error.stack;
_this.description = error.description;
_this.fileName = error.fileName;
_this.lineNumber = error.lineNumber;
_this.message = error.message;
_this.name = error.name;
_this.number = error.number;
_this.code = error.code;
return _this;
}
return EmberError;
}(ExtendBuiltin(Error));
exports.default = EmberError;
});
enifed('ember-debug/features', ['exports', 'ember-environment', 'ember/features'], function (exports, _emberEnvironment, _features) {
'use strict';
exports.default = isEnabled;
var FEATURES = _features.FEATURES;
/**
@module ember
*/
/**
The hash of enabled Canary features. Add to this, any canary features
before creating your application.
Alternatively (and recommended), you can also define `EmberENV.FEATURES`
if you need to enable features flagged at runtime.
@class FEATURES
@namespace Ember
@static
@since 1.1.0
@public
*/
// Auto-generated
/**
Determine whether the specified `feature` is enabled. Used by Ember's
build tools to exclude experimental features from beta/stable builds.
You can define the following configuration options:
* `EmberENV.ENABLE_OPTIONAL_FEATURES` - enable any features that have not been explicitly
enabled/disabled.
@method isEnabled
@param {String} feature The feature to check
@return {Boolean}
@for Ember.FEATURES
@since 1.1.0
@public
*/
function isEnabled(feature) {
var featureValue = FEATURES[feature];
if (featureValue === true || featureValue === false || featureValue === undefined) {
return featureValue;
} else if (_emberEnvironment.ENV.ENABLE_OPTIONAL_FEATURES) {
return true;
} else {
return false;
}
}
});
enifed('ember-debug/handlers', ['exports'], function (exports) {
'use strict';
var HANDLERS = exports.HANDLERS = {};
var registerHandler = function () {};
var invoke = function () {};
if (true) {
exports.registerHandler = registerHandler = function registerHandler(type, callback) {
var nextHandler = HANDLERS[type] || function () {};
HANDLERS[type] = function (message, options) {
callback(message, options, nextHandler);
};
};
exports.invoke = invoke = function invoke(type, message, test, options) {
if (test) {
return;
}
var handlerForType = HANDLERS[type];
if (handlerForType) {
handlerForType(message, options);
}
};
}
exports.registerHandler = registerHandler;
exports.invoke = invoke;
});
enifed('ember-debug/index', ['exports', 'ember-debug/warn', 'ember-debug/deprecate', 'ember-debug/features', 'ember-debug/error', 'ember-debug/testing', 'ember-environment', 'ember-console', 'ember/features'], function (exports, _warn2, _deprecate2, _features, _error, _testing, _emberEnvironment, _emberConsole, _features2) {
'use strict';
exports._warnIfUsingStrippedFeatureFlags = exports.getDebugFunction = exports.setDebugFunction = exports.deprecateFunc = exports.runInDebug = exports.debugFreeze = exports.debugSeal = exports.deprecate = exports.debug = exports.warn = exports.info = exports.assert = exports.setTesting = exports.isTesting = exports.Error = exports.isFeatureEnabled = exports.registerDeprecationHandler = exports.registerWarnHandler = undefined;
Object.defineProperty(exports, 'registerWarnHandler', {
enumerable: true,
get: function () {
return _warn2.registerHandler;
}
});
Object.defineProperty(exports, 'registerDeprecationHandler', {
enumerable: true,
get: function () {
return _deprecate2.registerHandler;
}
});
Object.defineProperty(exports, 'isFeatureEnabled', {
enumerable: true,
get: function () {
return _features.default;
}
});
Object.defineProperty(exports, 'Error', {
enumerable: true,
get: function () {
return _error.default;
}
});
Object.defineProperty(exports, 'isTesting', {
enumerable: true,
get: function () {
return _testing.isTesting;
}
});
Object.defineProperty(exports, 'setTesting', {
enumerable: true,
get: function () {
return _testing.setTesting;
}
});
var DEFAULT_FEATURES = _features2.DEFAULT_FEATURES,
FEATURES = _features2.FEATURES;
// These are the default production build versions:
var noop = function () {};
var assert = noop;
var info = noop;
var warn = noop;
var debug = noop;
var deprecate = noop;
var debugSeal = noop;
var debugFreeze = noop;
var runInDebug = noop;
var setDebugFunction = noop;
var getDebugFunction = noop;
var deprecateFunc = function () {
return arguments[arguments.length - 1];
};
if (true) {
exports.setDebugFunction = setDebugFunction = function (type, callback) {
switch (type) {
case 'assert':
return exports.assert = assert = callback;
case 'info':
return exports.info = info = callback;
case 'warn':
return exports.warn = warn = callback;
case 'debug':
return exports.debug = debug = callback;
case 'deprecate':
return exports.deprecate = deprecate = callback;
case 'debugSeal':
return exports.debugSeal = debugSeal = callback;
case 'debugFreeze':
return exports.debugFreeze = debugFreeze = callback;
case 'runInDebug':
return exports.runInDebug = runInDebug = callback;
case 'deprecateFunc':
return exports.deprecateFunc = deprecateFunc = callback;
}
};
exports.getDebugFunction = getDebugFunction = function (type) {
switch (type) {
case 'assert':
return assert;
case 'info':
return info;
case 'warn':
return warn;
case 'debug':
return debug;
case 'deprecate':
return deprecate;
case 'debugSeal':
return debugSeal;
case 'debugFreeze':
return debugFreeze;
case 'runInDebug':
return runInDebug;
case 'deprecateFunc':
return deprecateFunc;
}
};
}
/**
@module @ember/debug
*/
if (true) {
/**
Define an assertion that will throw an exception if the condition is not met.
* In a production build, this method is defined as an empty function (NOP).
Uses of this method in Ember itself are stripped from the ember.prod.js build.
```javascript
import { assert } from '@ember/debug';
// Test for truthiness
assert('Must pass a valid object', obj);
// Fail unconditionally
assert('This code path should never be run');
```
@method assert
@static
@for @ember/debug
@param {String} desc A description of the assertion. This will become
the text of the Error thrown if the assertion fails.
@param {Boolean} test Must be truthy for the assertion to pass. If
falsy, an exception will be thrown.
@public
@since 1.0.0
*/
setDebugFunction('assert', function assert(desc, test) {
if (!test) {
throw new _error.default('Assertion Failed: ' + desc);
}
});
/**
Display a debug notice.
* In a production build, this method is defined as an empty function (NOP).
Uses of this method in Ember itself are stripped from the ember.prod.js build.
```javascript
import { debug } from '@ember/debug';
debug('I\'m a debug notice!');
```
@method debug
@for @ember/debug
@static
@param {String} message A debug message to display.
@public
*/
setDebugFunction('debug', function debug(message) {
_emberConsole.default.debug('DEBUG: ' + message);
});
/**
Display an info notice.
* In a production build, this method is defined as an empty function (NOP).
Uses of this method in Ember itself are stripped from the ember.prod.js build.
@method info
@private
*/
setDebugFunction('info', function info() {
_emberConsole.default.info.apply(undefined, arguments);
});
/**
@module @ember/application
@public
*/
/**
Alias an old, deprecated method with its new counterpart.
Display a deprecation warning with the provided message and a stack trace
(Chrome and Firefox only) when the assigned method is called.
* In a production build, this method is defined as an empty function (NOP).
```javascript
Ember.oldMethod = Ember.deprecateFunc('Please use the new, updated method', Ember.newMethod);
```
@method deprecateFunc
@static
@for @ember/application/deprecations
@param {String} message A description of the deprecation.
@param {Object} [options] The options object for Ember.deprecate.
@param {Function} func The new function called to replace its deprecated counterpart.
@return {Function} A new function that wraps the original function with a deprecation warning
@private
*/
setDebugFunction('deprecateFunc', function deprecateFunc() {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
if (args.length === 3) {
var message = args[0],
options = args[1],
func = args[2];
return function () {
deprecate(message, false, options);
return func.apply(this, arguments);
};
} else {
var _message = args[0],
_func = args[1];
return function () {
deprecate(_message);
return _func.apply(this, arguments);
};
}
});
/**
@module @ember/debug
@public
*/
/**
Run a function meant for debugging.
* In a production build, this method is defined as an empty function (NOP).
Uses of this method in Ember itself are stripped from the ember.prod.js build.
```javascript
import Component from '@ember/component';
import { runInDebug } from '@ember/debug';
runInDebug(() => {
Component.reopen({
didInsertElement() {
console.log("I'm happy");
}
});
});
```
@method runInDebug
@for @ember/debug
@static
@param {Function} func The function to be executed.
@since 1.5.0
@public
*/
setDebugFunction('runInDebug', function runInDebug(func) {
func();
});
setDebugFunction('debugSeal', function debugSeal(obj) {
Object.seal(obj);
});
setDebugFunction('debugFreeze', function debugFreeze(obj) {
Object.freeze(obj);
});
setDebugFunction('deprecate', _deprecate2.default);
setDebugFunction('warn', _warn2.default);
}
var _warnIfUsingStrippedFeatureFlags = void 0;
if (true && !(0, _testing.isTesting)()) {
/**
Will call `warn()` if ENABLE_OPTIONAL_FEATURES or
any specific FEATURES flag is truthy.
This method is called automatically in debug canary builds.
@private
@method _warnIfUsingStrippedFeatureFlags
@return {void}
*/
exports._warnIfUsingStrippedFeatureFlags = _warnIfUsingStrippedFeatureFlags = function _warnIfUsingStrippedFeatureFlags(FEATURES, knownFeatures, featuresWereStripped) {
if (featuresWereStripped) {
warn('Ember.ENV.ENABLE_OPTIONAL_FEATURES is only available in canary builds.', !_emberEnvironment.ENV.ENABLE_OPTIONAL_FEATURES, { id: 'ember-debug.feature-flag-with-features-stripped' });
var keys = Object.keys(FEATURES || {});
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (key === 'isEnabled' || !(key in knownFeatures)) {
continue;
}
warn('FEATURE["' + key + '"] is set as enabled, but FEATURE flags are only available in canary builds.', !FEATURES[key], { id: 'ember-debug.feature-flag-with-features-stripped' });
}
}
};
// Complain if they're using FEATURE flags in builds other than canary
FEATURES['features-stripped-test'] = true;
var featuresWereStripped = true;
if ((0, _features.default)('features-stripped-test')) {
featuresWereStripped = false;
}
delete FEATURES['features-stripped-test'];
_warnIfUsingStrippedFeatureFlags(_emberEnvironment.ENV.FEATURES, DEFAULT_FEATURES, featuresWereStripped);
// Inform the developer about the Ember Inspector if not installed.
var isFirefox = _emberEnvironment.environment.isFirefox;
var isChrome = _emberEnvironment.environment.isChrome;
if (typeof window !== 'undefined' && (isFirefox || isChrome) && window.addEventListener) {
window.addEventListener('load', function () {
if (document.documentElement && document.documentElement.dataset && !document.documentElement.dataset.emberExtension) {
var downloadURL = void 0;
if (isChrome) {
downloadURL = 'https://chrome.google.com/webstore/detail/ember-inspector/bmdblncegkenkacieihfhpjfppoconhi';
} else if (isFirefox) {
downloadURL = 'https://addons.mozilla.org/en-US/firefox/addon/ember-inspector/';
}
debug('For more advanced debugging, install the Ember Inspector from ' + downloadURL);
}
}, false);
}
}
exports.assert = assert;
exports.info = info;
exports.warn = warn;
exports.debug = debug;
exports.deprecate = deprecate;
exports.debugSeal = debugSeal;
exports.debugFreeze = debugFreeze;
exports.runInDebug = runInDebug;
exports.deprecateFunc = deprecateFunc;
exports.setDebugFunction = setDebugFunction;
exports.getDebugFunction = getDebugFunction;
exports._warnIfUsingStrippedFeatureFlags = _warnIfUsingStrippedFeatureFlags;
});
enifed("ember-debug/testing", ["exports"], function (exports) {
"use strict";
exports.isTesting = isTesting;
exports.setTesting = setTesting;
var testing = false;
function isTesting() {
return testing;
}
function setTesting(value) {
testing = !!value;
}
});
enifed('ember-debug/warn', ['exports', 'ember-console', 'ember-debug/deprecate', 'ember-debug/handlers'], function (exports, _emberConsole, _deprecate, _handlers) {
'use strict';
exports.missingOptionsDeprecation = exports.missingOptionsIdDeprecation = exports.registerHandler = undefined;
var registerHandler = function () {};
var warn = function () {};
var missingOptionsDeprecation = void 0,
missingOptionsIdDeprecation = void 0;
/**
@module @ember/debug
*/
if (true) {
/**
Allows for runtime registration of handler functions that override the default warning behavior.
Warnings are invoked by calls made to [warn](https://emberjs.com/api/classes/Ember.html#method_warn).
The following example demonstrates its usage by registering a handler that does nothing overriding Ember's
default warning behavior.
```javascript
import { registerWarnHandler } from '@ember/debug';
// next is not called, so no warnings get the default behavior
registerWarnHandler(() => {});
```
The handler function takes the following arguments:
<ul>
<li> <code>message</code> - The message received from the warn call. </li>
<li> <code>options</code> - An object passed in with the warn call containing additional information including:</li>
<ul>
<li> <code>id</code> - An id of the warning in the form of <code>package-name.specific-warning</code>.</li>
</ul>
<li> <code>next</code> - A function that calls into the previously registered handler.</li>
</ul>
@public
@static
@method registerWarnHandler
@for @ember/debug
@param handler {Function} A function to handle warnings.
@since 2.1.0
*/
exports.registerHandler = registerHandler = function registerHandler(handler) {
(0, _handlers.registerHandler)('warn', handler);
};
registerHandler(function logWarning(message, options) {
_emberConsole.default.warn('WARNING: ' + message);
if ('trace' in _emberConsole.default) {
_emberConsole.default.trace();
}
});
exports.missingOptionsDeprecation = missingOptionsDeprecation = 'When calling `warn` you ' + 'must provide an `options` hash as the third parameter. ' + '`options` should include an `id` property.';
exports.missingOptionsIdDeprecation = missingOptionsIdDeprecation = 'When calling `warn` you must provide `id` in options.';
/**
Display a warning with the provided message.
* In a production build, this method is defined as an empty function (NOP).
Uses of this method in Ember itself are stripped from the ember.prod.js build.
@method warn
@for @ember/debug
@static
@param {String} message A warning to display.
@param {Boolean} test An optional boolean. If falsy, the warning
will be displayed.
@param {Object} options An object that can be used to pass a unique
`id` for this warning. The `id` can be used by Ember debugging tools
to change the behavior (raise, log, or silence) for that specific warning.
The `id` should be namespaced by dots, e.g. "ember-debug.feature-flag-with-features-stripped"
@public
@since 1.0.0
*/
warn = function warn(message, test, options) {
if (arguments.length === 2 && typeof test === 'object') {
options = test;
test = false;
}
if (!options) {
(0, _deprecate.default)(missingOptionsDeprecation, false, {
id: 'ember-debug.warn-options-missing',
until: '3.0.0',
url: 'https://emberjs.com/deprecations/v2.x/#toc_ember-debug-function-options'
});
}
if (options && !options.id) {
(0, _deprecate.default)(missingOptionsIdDeprecation, false, {
id: 'ember-debug.warn-id-missing',
until: '3.0.0',
url: 'https://emberjs.com/deprecations/v2.x/#toc_ember-debug-function-options'
});
}
(0, _handlers.invoke)('warn', message, test, options);
};
}
exports.default = warn;
exports.registerHandler = registerHandler;
exports.missingOptionsIdDeprecation = missingOptionsIdDeprecation;
exports.missingOptionsDeprecation = missingOptionsDeprecation;
});
enifed('ember-environment', ['exports'], function (exports) {
'use strict';
/* globals global, window, self, mainContext */
// from lodash to catch fake globals
function checkGlobal(value) {
return value && value.Object === Object ? value : undefined;
}
// element ids can ruin global miss checks
function checkElementIdShadowing(value) {
return value && value.nodeType === undefined ? value : undefined;
}
// export real global
var global$1 = checkGlobal(checkElementIdShadowing(typeof global === 'object' && global)) || checkGlobal(typeof self === 'object' && self) || checkGlobal(typeof window === 'object' && window) || mainContext || // set before strict mode in Ember loader/wrapper
new Function('return this')(); // eval outside of strict mode
function defaultTrue(v) {
return v === false ? false : true;
}
function defaultFalse(v) {
return v === true ? true : false;
}
function normalizeExtendPrototypes(obj) {
if (obj === false) {
return { String: false, Array: false, Function: false };
} else if (!obj || obj === true) {
return { String: true, Array: true, Function: true };
} else {
return {
String: defaultTrue(obj.String),
Array: defaultTrue(obj.Array),
Function: defaultTrue(obj.Function)
};
}
}
/* globals module */
/**
The hash of environment variables used to control various configuration
settings. To specify your own or override default settings, add the
desired properties to a global hash named `EmberENV` (or `ENV` for
backwards compatibility with earlier versions of Ember). The `EmberENV`
hash must be created before loading Ember.
@class EmberENV
@type Object
@public
*/
var ENV = typeof global$1.EmberENV === 'object' && global$1.EmberENV || typeof global$1.ENV === 'object' && global$1.ENV || {};
// ENABLE_ALL_FEATURES was documented, but you can't actually enable non optional features.
if (ENV.ENABLE_ALL_FEATURES) {
ENV.ENABLE_OPTIONAL_FEATURES = true;
}
/**
Determines whether Ember should add to `Array`, `Function`, and `String`
native object prototypes, a few extra methods in order to provide a more
friendly API.
We generally recommend leaving this option set to true however, if you need
to turn it off, you can add the configuration property
`EXTEND_PROTOTYPES` to `EmberENV` and set it to `false`.
Note, when disabled (the default configuration for Ember Addons), you will
instead have to access all methods and functions from the Ember
namespace.
@property EXTEND_PROTOTYPES
@type Boolean
@default true
@for EmberENV
@public
*/
ENV.EXTEND_PROTOTYPES = normalizeExtendPrototypes(ENV.EXTEND_PROTOTYPES);
/**
The `LOG_STACKTRACE_ON_DEPRECATION` property, when true, tells Ember to log
a full stack trace during deprecation warnings.
@property LOG_STACKTRACE_ON_DEPRECATION
@type Boolean
@default true
@for EmberENV
@public
*/
ENV.LOG_STACKTRACE_ON_DEPRECATION = defaultTrue(ENV.LOG_STACKTRACE_ON_DEPRECATION);
/**
The `LOG_VERSION` property, when true, tells Ember to log versions of all
dependent libraries in use.
@property LOG_VERSION
@type Boolean
@default true
@for EmberENV
@public
*/
ENV.LOG_VERSION = defaultTrue(ENV.LOG_VERSION);
/**
Debug parameter you can turn on. This will log all bindings that fire to
the console. This should be disabled in production code. Note that you
can also enable this from the console or temporarily.
@property LOG_BINDINGS
@for EmberENV
@type Boolean
@default false
@public
*/
ENV.LOG_BINDINGS = defaultFalse(ENV.LOG_BINDINGS);
ENV.RAISE_ON_DEPRECATION = defaultFalse(ENV.RAISE_ON_DEPRECATION);
// check if window exists and actually is the global
var hasDOM = typeof window !== 'undefined' && window === global$1 && window.document && window.document.createElement && !ENV.disableBrowserEnvironment; // is this a public thing?
// legacy imports/exports/lookup stuff (should we keep this??)
var originalContext = global$1.Ember || {};
var context = {
// import jQuery
imports: originalContext.imports || global$1,
// export Ember
exports: originalContext.exports || global$1,
// search for Namespaces
lookup: originalContext.lookup || global$1
};
// TODO: cleanup single source of truth issues with this stuff
var environment = hasDOM ? {
hasDOM: true,
isChrome: !!window.chrome && !window.opera,
isFirefox: typeof InstallTrigger !== 'undefined',
isPhantom: !!window.callPhantom,
location: window.location,
history: window.history,
userAgent: window.navigator.userAgent,
window: window
} : {
hasDOM: false,
isChrome: false,
isFirefox: false,
isPhantom: false,
location: null,
history: null,
userAgent: 'Lynx (textmode)',
window: null
};
exports.ENV = ENV;
exports.context = context;
exports.environment = environment;
});
enifed('ember-extension-support/container_debug_adapter', ['exports', 'ember-metal', 'ember-runtime'], function (exports, _emberMetal, _emberRuntime) {
'use strict';
exports.default = _emberRuntime.Object.extend({
/**
The resolver instance of the application
being debugged. This property will be injected
on creation.
@property resolver
@default null
@public
*/
resolver: null,
/**
Returns true if it is possible to catalog a list of available
classes in the resolver for a given type.
@method canCatalogEntriesByType
@param {String} type The type. e.g. "model", "controller", "route".
@return {boolean} whether a list is available for this type.
@public
*/
canCatalogEntriesByType: function (type) {
if (type === 'model' || type === 'template') {
return false;
}
return true;
},
/**
Returns the available classes a given type.
@method catalogEntriesByType
@param {String} type The type. e.g. "model", "controller", "route".
@return {Array} An array of strings.
@public
*/
catalogEntriesByType: function (type) {
var namespaces = (0, _emberRuntime.A)(_emberRuntime.Namespace.NAMESPACES);
var types = (0, _emberRuntime.A)();
var typeSuffixRegex = new RegExp(_emberRuntime.String.classify(type) + '$');
namespaces.forEach(function (namespace) {
if (namespace !== _emberMetal.default) {
for (var key in namespace) {
if (!namespace.hasOwnProperty(key)) {
continue;
}
if (typeSuffixRegex.test(key)) {
var klass = namespace[key];
if ((0, _emberRuntime.typeOf)(klass) === 'class') {
types.push(_emberRuntime.String.dasherize(key.replace(typeSuffixRegex, '')));
}
}
}
}
});
return types;
}
});
});
enifed('ember-extension-support/data_adapter', ['exports', 'ember-utils', 'ember-metal', 'ember-runtime'], function (exports, _emberUtils, _emberMetal, _emberRuntime) {
'use strict';
exports.default = _emberRuntime.Object.extend({
init: function () {
this._super.apply(this, arguments);
this.releaseMethods = (0, _emberRuntime.A)();
},
/**
The container-debug-adapter which is used
to list all models.
@property containerDebugAdapter
@default undefined
@since 1.5.0
@public
**/
containerDebugAdapter: undefined,
/**
The number of attributes to send
as columns. (Enough to make the record
identifiable).
@private
@property attributeLimit
@default 3
@since 1.3.0
*/
attributeLimit: 3,
/**
Ember Data > v1.0.0-beta.18
requires string model names to be passed
around instead of the actual factories.
This is a stamp for the Ember Inspector
to differentiate between the versions
to be able to support older versions too.
@public
@property acceptsModelName
*/
acceptsModelName: true,
/**
Stores all methods that clear observers.
These methods will be called on destruction.
@private
@property releaseMethods
@since 1.3.0
*/
releaseMethods: (0, _emberRuntime.A)(),
/**
Specifies how records can be filtered.
Records returned will need to have a `filterValues`
property with a key for every name in the returned array.
@public
@method getFilters
@return {Array} List of objects defining filters.
The object should have a `name` and `desc` property.
*/
getFilters: function () {
return (0, _emberRuntime.A)();
},
/**
Fetch the model types and observe them for changes.
@public
@method watchModelTypes
@param {Function} typesAdded Callback to call to add types.
Takes an array of objects containing wrapped types (returned from `wrapModelType`).
@param {Function} typesUpdated Callback to call when a type has changed.
Takes an array of objects containing wrapped types.
@return {Function} Method to call to remove all observers
*/
watchModelTypes: function (typesAdded, typesUpdated) {
var _this = this;
var modelTypes = this.getModelTypes();
var releaseMethods = (0, _emberRuntime.A)();
var typesToSend = void 0;
typesToSend = modelTypes.map(function (type) {
var klass = type.klass;
var wrapped = _this.wrapModelType(klass, type.name);
releaseMethods.push(_this.observeModelType(type.name, typesUpdated));
return wrapped;
});
typesAdded(typesToSend);
var release = function () {
releaseMethods.forEach(function (fn) {
return fn();
});
_this.releaseMethods.removeObject(release);
};
this.releaseMethods.pushObject(release);
return release;
},
_nameToClass: function (type) {
if (typeof type === 'string') {
var owner = (0, _emberUtils.getOwner)(this);
var Factory = owner.factoryFor('model:' + type);
type = Factory && Factory.class;
}
return type;
},
/**
Fetch the records of a given type and observe them for changes.
@public
@method watchRecords
@param {String} modelName The model name.
@param {Function} recordsAdded Callback to call to add records.
Takes an array of objects containing wrapped records.
The object should have the following properties:
columnValues: {Object} The key and value of a table cell.
object: {Object} The actual record object.
@param {Function} recordsUpdated Callback to call when a record has changed.
Takes an array of objects containing wrapped records.
@param {Function} recordsRemoved Callback to call when a record has removed.
Takes the following parameters:
index: The array index where the records were removed.
count: The number of records removed.
@return {Function} Method to call to remove all observers.
*/
watchRecords: function (modelName, recordsAdded, recordsUpdated, recordsRemoved) {
var _this2 = this;
var releaseMethods = (0, _emberRuntime.A)();
var klass = this._nameToClass(modelName);
var records = this.getRecords(klass, modelName);
var release = void 0;
function recordUpdated(updatedRecord) {
recordsUpdated([updatedRecord]);
}
var recordsToSend = records.map(function (record) {
releaseMethods.push(_this2.observeRecord(record, recordUpdated));
return _this2.wrapRecord(record);
});
var contentDidChange = function (array, idx, removedCount, addedCount) {
for (var i = idx; i < idx + addedCount; i++) {
var record = (0, _emberRuntime.objectAt)(array, i);
var wrapped = _this2.wrapRecord(record);
releaseMethods.push(_this2.observeRecord(record, recordUpdated));
recordsAdded([wrapped]);
}
if (removedCount) {
recordsRemoved(idx, removedCount);
}
};
var observer = { didChange: contentDidChange, willChange: function () {
return this;
}
};
(0, _emberRuntime.addArrayObserver)(records, this, observer);
release = function () {
releaseMethods.forEach(function (fn) {
return fn();
});
(0, _emberRuntime.removeArrayObserver)(records, _this2, observer);
_this2.releaseMethods.removeObject(release);
};
recordsAdded(recordsToSend);
this.releaseMethods.pushObject(release);
return release;
},
/**
Clear all observers before destruction
@private
@method willDestroy
*/
willDestroy: function () {
this._super.apply(this, arguments);
this.releaseMethods.forEach(function (fn) {
return fn();
});
},
/**
Detect whether a class is a model.
Test that against the model class
of your persistence library.
@private
@method detect
@param {Class} klass The class to test.
@return boolean Whether the class is a model class or not.
*/
detect: function (klass) {
return false;
},
/**
Get the columns for a given model type.
@private
@method columnsForType
@param {Class} type The model type.
@return {Array} An array of columns of the following format:
name: {String} The name of the column.
desc: {String} Humanized description (what would show in a table column name).
*/
columnsForType: function (type) {
return (0, _emberRuntime.A)();
},
/**
Adds observers to a model type class.
@private
@method observeModelType
@param {String} modelName The model type name.
@param {Function} typesUpdated Called when a type is modified.
@return {Function} The function to call to remove observers.
*/
observeModelType: function (modelName, typesUpdated) {
var _this3 = this;
var klass = this._nameToClass(modelName);
var records = this.getRecords(klass, modelName);
function onChange() {
typesUpdated([this.wrapModelType(klass, modelName)]);
}
var observer = {
didChange: function (array, idx, removedCount, addedCount) {
// Only re-fetch records if the record count changed
// (which is all we care about as far as model types are concerned).
if (removedCount > 0 || addedCount > 0) {
_emberMetal.run.scheduleOnce('actions', this, onChange);
}
},
willChange: function () {
return this;
}
};
(0, _emberRuntime.addArrayObserver)(records, this, observer);
var release = function () {
return (0, _emberRuntime.removeArrayObserver)(records, _this3, observer);
};
return release;
},
/**
Wraps a given model type and observes changes to it.
@private
@method wrapModelType
@param {Class} klass A model class.
@param {String} modelName Name of the class.
@return {Object} Contains the wrapped type and the function to remove observers
Format:
type: {Object} The wrapped type.
The wrapped type has the following format:
name: {String} The name of the type.
count: {Integer} The number of records available.
columns: {Columns} An array of columns to describe the record.
object: {Class} The actual Model type class.
release: {Function} The function to remove observers.
*/
wrapModelType: function (klass, name) {
var records = this.getRecords(klass, name);
var typeToSend = void 0;
typeToSend = {
name: name,
count: (0, _emberMetal.get)(records, 'length'),
columns: this.columnsForType(klass),
object: klass
};
return typeToSend;
},
/**
Fetches all models defined in the application.
@private
@method getModelTypes
@return {Array} Array of model types.
*/
getModelTypes: function () {
var _this4 = this;
var containerDebugAdapter = this.get('containerDebugAdapter');
var types = void 0;
if (containerDebugAdapter.canCatalogEntriesByType('model')) {
types = containerDebugAdapter.catalogEntriesByType('model');
} else {
types = this._getObjectsOnNamespaces();
}
// New adapters return strings instead of classes.
types = (0, _emberRuntime.A)(types).map(function (name) {
return {
klass: _this4._nameToClass(name),
name: name
};
});
types = (0, _emberRuntime.A)(types).filter(function (type) {
return _this4.detect(type.klass);
});
return (0, _emberRuntime.A)(types);
},
/**
Loops over all namespaces and all objects
attached to them.
@private
@method _getObjectsOnNamespaces
@return {Array} Array of model type strings.
*/
_getObjectsOnNamespaces: function () {
var _this5 = this;
var namespaces = (0, _emberRuntime.A)(_emberRuntime.Namespace.NAMESPACES);
var types = (0, _emberRuntime.A)();
namespaces.forEach(function (namespace) {
for (var key in namespace) {
if (!namespace.hasOwnProperty(key)) {
continue;
}
// Even though we will filter again in `getModelTypes`,
// we should not call `lookupFactory` on non-models
if (!_this5.detect(namespace[key])) {
continue;
}
var name = _emberRuntime.String.dasherize(key);
types.push(name);
}
});
return types;
},
/**
Fetches all loaded records for a given type.
@private
@method getRecords
@return {Array} An array of records.
This array will be observed for changes,
so it should update when new records are added/removed.
*/
getRecords: function (type) {
return (0, _emberRuntime.A)();
},
/**
Wraps a record and observers changes to it.
@private
@method wrapRecord
@param {Object} record The record instance.
@return {Object} The wrapped record. Format:
columnValues: {Array}
searchKeywords: {Array}
*/
wrapRecord: function (record) {
var recordToSend = { object: record };
recordToSend.columnValues = this.getRecordColumnValues(record);
recordToSend.searchKeywords = this.getRecordKeywords(record);
recordToSend.filterValues = this.getRecordFilterValues(record);
recordToSend.color = this.getRecordColor(record);
return recordToSend;
},
/**
Gets the values for each column.
@private
@method getRecordColumnValues
@return {Object} Keys should match column names defined
by the model type.
*/
getRecordColumnValues: function (record) {
return {};
},
/**
Returns keywords to match when searching records.
@private
@method getRecordKeywords
@return {Array} Relevant keywords for search.
*/
getRecordKeywords: function (record) {
return (0, _emberRuntime.A)();
},
/**
Returns the values of filters defined by `getFilters`.
@private
@method getRecordFilterValues
@param {Object} record The record instance.
@return {Object} The filter values.
*/
getRecordFilterValues: function (record) {
return {};
},
/**
Each record can have a color that represents its state.
@private
@method getRecordColor
@param {Object} record The record instance
@return {String} The records color.
Possible options: black, red, blue, green.
*/
getRecordColor: function (record) {
return null;
},
/**
Observes all relevant properties and re-sends the wrapped record
when a change occurs.
@private
@method observerRecord
@param {Object} record The record instance.
@param {Function} recordUpdated The callback to call when a record is updated.
@return {Function} The function to call to remove all observers.
*/
observeRecord: function (record, recordUpdated) {
return function () {};
}
});
});
enifed('ember-extension-support/index', ['exports', 'ember-extension-support/data_adapter', 'ember-extension-support/container_debug_adapter'], function (exports, _data_adapter, _container_debug_adapter) {
'use strict';
Object.defineProperty(exports, 'DataAdapter', {
enumerable: true,
get: function () {
return _data_adapter.default;
}
});
Object.defineProperty(exports, 'ContainerDebugAdapter', {
enumerable: true,
get: function () {
return _container_debug_adapter.default;
}
});
});
enifed('ember-glimmer/component-managers/abstract', ['exports', 'ember-babel'], function (exports, _emberBabel) {
'use strict';
var AbstractManager = function () {
function AbstractManager() {
(0, _emberBabel.classCallCheck)(this, AbstractManager);
this.debugStack = undefined;
}
AbstractManager.prototype.prepareArgs = function prepareArgs(_definition, _args) {
return null;
};
AbstractManager.prototype.didCreateElement = function didCreateElement(_component, _element, _operations) {}
// noop
// inheritors should also call `this.debugStack.pop()` to
// ensure the rerendering assertion messages are properly
// maintained
;
AbstractManager.prototype.didRenderLayout = function didRenderLayout(_component, _bounds) {
// noop
};
AbstractManager.prototype.didCreate = function didCreate(_bucket) {
// noop
};
AbstractManager.prototype.getTag = function getTag(_bucket) {
return null;
};
AbstractManager.prototype.update = function update(_bucket, _dynamicScope) {}
// noop
// inheritors should also call `this.debugStack.pop()` to
// ensure the rerendering assertion messages are properly
// maintained
;
AbstractManager.prototype.didUpdateLayout = function didUpdateLayout(_bucket, _bounds) {
// noop
};
AbstractManager.prototype.didUpdate = function didUpdate(_bucket) {
// noop
};
return AbstractManager;
}();
exports.default = AbstractManager;
if (true) {
AbstractManager.prototype._pushToDebugStack = function (name, environment) {
this.debugStack = environment.debugStack;
this.debugStack.push(name);
};
AbstractManager.prototype._pushEngineToDebugStack = function (name, environment) {
this.debugStack = environment.debugStack;
this.debugStack.pushEngine(name);
};
}
});
enifed('ember-glimmer/component-managers/curly', ['exports', 'ember-babel', '@glimmer/reference', '@glimmer/runtime', 'container', 'ember-debug', 'ember-metal', 'ember-utils', 'ember-views', 'ember-glimmer/component', 'ember-glimmer/utils/bindings', 'ember-glimmer/utils/curly-component-state-bucket', 'ember-glimmer/utils/process-args', 'ember-glimmer/utils/references', 'ember-glimmer/component-managers/abstract'], function (exports, _emberBabel, _reference, _runtime, _container, _emberDebug, _emberMetal, _emberUtils, _emberViews, _component, _bindings, _curlyComponentStateBucket, _processArgs, _references, _abstract) {
'use strict';
exports.CurlyComponentDefinition = exports.PositionalArgumentReference = undefined;
exports.validatePositionalParameters = validatePositionalParameters;
exports.processComponentInitializationAssertions = processComponentInitializationAssertions;
exports.initialRenderInstrumentDetails = initialRenderInstrumentDetails;
exports.rerenderInstrumentDetails = rerenderInstrumentDetails;
var _templateObject = (0, _emberBabel.taggedTemplateLiteralLoose)(['template:components/-default'], ['template:components/-default']);
var DEFAULT_LAYOUT = (0, _container.privatize)(_templateObject);
function aliasIdToElementId(args, props) {
if (args.named.has('id')) {
(true && !(!args.named.has('elementId')) && (0, _emberDebug.assert)('You cannot invoke a component with both \'id\' and \'elementId\' at the same time.', !args.named.has('elementId')));
props.elementId = props.id;
}
}
// We must traverse the attributeBindings in reverse keeping track of
// what has already been applied. This is essentially refining the concatenated
// properties applying right to left.
function applyAttributeBindings(element, attributeBindings, component, operations) {
var seen = [];
var i = attributeBindings.length - 1;
while (i !== -1) {
var binding = attributeBindings[i];
var parsed = _bindings.AttributeBinding.parse(binding);
var attribute = parsed[1];
if (seen.indexOf(attribute) === -1) {
seen.push(attribute);
_bindings.AttributeBinding.install(element, component, parsed, operations);
}
i--;
}
if (seen.indexOf('id') === -1) {
operations.addStaticAttribute(element, 'id', component.elementId);
}
if (seen.indexOf('style') === -1) {
_bindings.IsVisibleBinding.install(element, component, operations);
}
}
function tagName(vm) {
var dynamicScope = vm.dynamicScope();
// tslint:disable-next-line:no-shadowed-variable
var tagName = dynamicScope.view.tagName;
return _runtime.PrimitiveReference.create(tagName === '' ? null : tagName || 'div');
}
function ariaRole(vm) {
return vm.getSelf().get('ariaRole');
}
var CurlyComponentLayoutCompiler = function () {
function CurlyComponentLayoutCompiler(template) {
(0, _emberBabel.classCallCheck)(this, CurlyComponentLayoutCompiler);
this.template = template;
}
CurlyComponentLayoutCompiler.prototype.compile = function compile(builder) {
builder.wrapLayout(this.template);
builder.tag.dynamic(tagName);
builder.attrs.dynamic('role', ariaRole);
builder.attrs.static('class', 'ember-view');
};
return CurlyComponentLayoutCompiler;
}();
CurlyComponentLayoutCompiler.id = 'curly';
var PositionalArgumentReference = exports.PositionalArgumentReference = function () {
function PositionalArgumentReference(references) {
(0, _emberBabel.classCallCheck)(this, PositionalArgumentReference);
this.tag = (0, _reference.combineTagged)(references);
this._references = references;
}
PositionalArgumentReference.prototype.value = function value() {
return this._references.map(function (reference) {
return reference.value();
});
};
PositionalArgumentReference.prototype.get = function get(key) {
return _references.PropertyReference.create(this, key);
};
return PositionalArgumentReference;
}();
var CurlyComponentManager = function (_AbstractManager) {
(0, _emberBabel.inherits)(CurlyComponentManager, _AbstractManager);
function CurlyComponentManager() {
(0, _emberBabel.classCallCheck)(this, CurlyComponentManager);
return (0, _emberBabel.possibleConstructorReturn)(this, _AbstractManager.apply(this, arguments));
}
CurlyComponentManager.prototype.prepareArgs = function prepareArgs(definition, args) {
var componentPositionalParamsDefinition = definition.ComponentClass.class.positionalParams;
if (true && componentPositionalParamsDefinition) {
validatePositionalParameters(args.named, args.positional, componentPositionalParamsDefinition);
}
var componentHasRestStylePositionalParams = typeof componentPositionalParamsDefinition === 'string';
var componentHasPositionalParams = componentHasRestStylePositionalParams || componentPositionalParamsDefinition.length > 0;
var needsPositionalParamMunging = componentHasPositionalParams && args.positional.length !== 0;
var isClosureComponent = definition.args;
if (!needsPositionalParamMunging && !isClosureComponent) {
return null;
}
var capturedArgs = args.capture();
// grab raw positional references array
var positional = capturedArgs.positional.references;
// handle prep for closure component with positional params
var curriedNamed = void 0;
if (definition.args) {
var remainingDefinitionPositionals = definition.args.positional.slice(positional.length);
positional = positional.concat(remainingDefinitionPositionals);
curriedNamed = definition.args.named;
}
// handle positionalParams
var positionalParamsToNamed = void 0;
if (componentHasRestStylePositionalParams) {
var _positionalParamsToNa;
positionalParamsToNamed = (_positionalParamsToNa = {}, _positionalParamsToNa[componentPositionalParamsDefinition] = new PositionalArgumentReference(positional), _positionalParamsToNa);
positional = [];
} else if (componentHasPositionalParams) {
positionalParamsToNamed = {};
var length = Math.min(positional.length, componentPositionalParamsDefinition.length);
for (var i = 0; i < length; i++) {
var name = componentPositionalParamsDefinition[i];
positionalParamsToNamed[name] = positional[i];
}
}
var named = (0, _emberUtils.assign)({}, curriedNamed, positionalParamsToNamed, capturedArgs.named.map);
return { positional: positional, named: named };
};
CurlyComponentManager.prototype.create = function create(environment, definition, args, dynamicScope, callerSelfRef, hasBlock) {
if (true) {
this._pushToDebugStack('component:' + definition.name, environment);
}
var parentView = dynamicScope.view;
var factory = definition.ComponentClass;
var capturedArgs = args.named.capture();
var props = (0, _processArgs.processComponentArgs)(capturedArgs);
aliasIdToElementId(args, props);
props.parentView = parentView;
props[_component.HAS_BLOCK] = hasBlock;
props._targetObject = callerSelfRef.value();
var component = factory.create(props);
var finalizer = (0, _emberMetal._instrumentStart)('render.component', initialRenderInstrumentDetails, component);
dynamicScope.view = component;
if (parentView !== null && parentView !== undefined) {
parentView.appendChild(component);
}
// We usually do this in the `didCreateElement`, but that hook doesn't fire for tagless components
if (component.tagName === '') {
if (environment.isInteractive) {
component.trigger('willRender');
}
component._transitionTo('hasElement');
if (environment.isInteractive) {
component.trigger('willInsertElement');
}
}
var bucket = new _curlyComponentStateBucket.default(environment, component, capturedArgs, finalizer);
if (args.named.has('class')) {
bucket.classRef = args.named.get('class');
}
if (true) {
processComponentInitializationAssertions(component, props);
}
if (environment.isInteractive && component.tagName !== '') {
component.trigger('willRender');
}
return bucket;
};
CurlyComponentManager.prototype.layoutFor = function layoutFor(definition, bucket, env) {
var template = definition.template;
if (!template) {
template = this.templateFor(bucket.component, env);
}
return env.getCompiledBlock(CurlyComponentLayoutCompiler, template);
};
CurlyComponentManager.prototype.templateFor = function templateFor(component, env) {
var Template = (0, _emberMetal.get)(component, 'layout');
var owner = component[_emberUtils.OWNER];
if (Template) {
return env.getTemplate(Template, owner);
}
var layoutName = (0, _emberMetal.get)(component, 'layoutName');
if (layoutName) {
var template = owner.lookup('template:' + layoutName);
if (template) {
return template;
}
}
return owner.lookup(DEFAULT_LAYOUT);
};
CurlyComponentManager.prototype.getSelf = function getSelf(_ref) {
var component = _ref.component;
return component[_component.ROOT_REF];
};
CurlyComponentManager.prototype.didCreateElement = function didCreateElement(_ref2, element, operations) {
var component = _ref2.component,
classRef = _ref2.classRef,
environment = _ref2.environment;
(0, _emberViews.setViewElement)(component, element);
var attributeBindings = component.attributeBindings,
classNames = component.classNames,
classNameBindings = component.classNameBindings;
if (attributeBindings && attributeBindings.length) {
applyAttributeBindings(element, attributeBindings, component, operations);
} else {
operations.addStaticAttribute(element, 'id', component.elementId);
_bindings.IsVisibleBinding.install(element, component, operations);
}
if (classRef) {
// TODO should make addDynamicAttribute accept an opaque
operations.addDynamicAttribute(element, 'class', classRef, false);
}
if (classNames && classNames.length) {
classNames.forEach(function (name) {
operations.addStaticAttribute(element, 'class', name);
});
}
if (classNameBindings && classNameBindings.length) {
classNameBindings.forEach(function (binding) {
_bindings.ClassNameBinding.install(element, component, binding, operations);
});
}
component._transitionTo('hasElement');
if (environment.isInteractive) {
component.trigger('willInsertElement');
}
};
CurlyComponentManager.prototype.didRenderLayout = function didRenderLayout(bucket, bounds) {
bucket.component[_component.BOUNDS] = bounds;
bucket.finalize();
if (true) {
this.debugStack.pop();
}
};
CurlyComponentManager.prototype.getTag = function getTag(_ref3) {
var component = _ref3.component;
return component[_component.DIRTY_TAG];
};
CurlyComponentManager.prototype.didCreate = function didCreate(_ref4) {
var component = _ref4.component,
environment = _ref4.environment;
if (environment.isInteractive) {
component._transitionTo('inDOM');
component.trigger('didInsertElement');
component.trigger('didRender');
}
};
CurlyComponentManager.prototype.update = function update(bucket) {
var component = bucket.component,
args = bucket.args,
argsRevision = bucket.argsRevision,
environment = bucket.environment;
if (true) {
this._pushToDebugStack(component._debugContainerKey, environment);
}
bucket.finalizer = (0, _emberMetal._instrumentStart)('render.component', rerenderInstrumentDetails, component);
if (!args.tag.validate(argsRevision)) {
var props = (0, _processArgs.processComponentArgs)(args);
bucket.argsRevision = args.tag.value();
component[_component.IS_DISPATCHING_ATTRS] = true;
component.setProperties(props);
component[_component.IS_DISPATCHING_ATTRS] = false;
component.trigger('didUpdateAttrs');
component.trigger('didReceiveAttrs');
}
if (environment.isInteractive) {
component.trigger('willUpdate');
component.trigger('willRender');
}
};
CurlyComponentManager.prototype.didUpdateLayout = function didUpdateLayout(bucket) {
bucket.finalize();
if (true) {
this.debugStack.pop();
}
};
CurlyComponentManager.prototype.didUpdate = function didUpdate(_ref5) {
var component = _ref5.component,
environment = _ref5.environment;
if (environment.isInteractive) {
component.trigger('didUpdate');
component.trigger('didRender');
}
};
CurlyComponentManager.prototype.getDestructor = function getDestructor(stateBucket) {
return stateBucket;
};
return CurlyComponentManager;
}(_abstract.default);
exports.default = CurlyComponentManager;
function validatePositionalParameters(named, positional, positionalParamsDefinition) {
if (true) {
if (!named || !positional || !positional.length) {
return;
}
var paramType = typeof positionalParamsDefinition;
if (paramType === 'string') {
(true && !(!named.has(positionalParamsDefinition)) && (0, _emberDebug.assert)('You cannot specify positional parameters and the hash argument `' + positionalParamsDefinition + '`.', !named.has(positionalParamsDefinition)));
} else {
if (positional.length < positionalParamsDefinition.length) {
positionalParamsDefinition = positionalParamsDefinition.slice(0, positional.length);
}
for (var i = 0; i < positionalParamsDefinition.length; i++) {
var name = positionalParamsDefinition[i];
(true && !(!named.has(name)) && (0, _emberDebug.assert)('You cannot specify both a positional param (at position ' + i + ') and the hash argument `' + name + '`.', !named.has(name)));
}
}
}
}
function processComponentInitializationAssertions(component, props) {
(true && !(function () {
var classNameBindings = component.classNameBindings;
for (var i = 0; i < classNameBindings.length; i++) {
var binding = classNameBindings[i];
if (typeof binding !== 'string' || binding.length === 0) {
return false;
}
}
return true;
}()) && (0, _emberDebug.assert)('classNameBindings must be non-empty strings: ' + component, function () {
var classNameBindings = component.classNameBindings;
for (var i = 0; i < classNameBindings.length; i++) {
var binding = classNameBindings[i];if (typeof binding !== 'string' || binding.length === 0) {
return false;
}
}return true;
}()));
(true && !(function () {
var classNameBindings = component.classNameBindings;
for (var i = 0; i < classNameBindings.length; i++) {
var binding = classNameBindings[i];
if (binding.split(' ').length > 1) {
return false;
}
}
return true;
}()) && (0, _emberDebug.assert)('classNameBindings must not have spaces in them: ' + component, function () {
var classNameBindings = component.classNameBindings;
for (var i = 0; i < classNameBindings.length; i++) {
var binding = classNameBindings[i];if (binding.split(' ').length > 1) {
return false;
}
}return true;
}()));
(true && !(component.tagName !== '' || !component.classNameBindings || component.classNameBindings.length === 0) && (0, _emberDebug.assert)('You cannot use `classNameBindings` on a tag-less component: ' + component, component.tagName !== '' || !component.classNameBindings || component.classNameBindings.length === 0));
(true && !(component.tagName !== '' || props.id === component.elementId || !component.elementId && component.elementId !== '') && (0, _emberDebug.assert)('You cannot use `elementId` on a tag-less component: ' + component, component.tagName !== '' || props.id === component.elementId || !component.elementId && component.elementId !== ''));
(true && !(component.tagName !== '' || !component.attributeBindings || component.attributeBindings.length === 0) && (0, _emberDebug.assert)('You cannot use `attributeBindings` on a tag-less component: ' + component, component.tagName !== '' || !component.attributeBindings || component.attributeBindings.length === 0));
}
function initialRenderInstrumentDetails(component) {
return component.instrumentDetails({ initialRender: true });
}
function rerenderInstrumentDetails(component) {
return component.instrumentDetails({ initialRender: false });
}
var MANAGER = new CurlyComponentManager();
var CurlyComponentDefinition = exports.CurlyComponentDefinition = function (_ComponentDefinition) {
(0, _emberBabel.inherits)(CurlyComponentDefinition, _ComponentDefinition);
// tslint:disable-next-line:no-shadowed-variable
function CurlyComponentDefinition(name, ComponentClass, template, args, customManager) {
(0, _emberBabel.classCallCheck)(this, CurlyComponentDefinition);
var _this2 = (0, _emberBabel.possibleConstructorReturn)(this, _ComponentDefinition.call(this, name, customManager || MANAGER, ComponentClass));
_this2.template = template;
_this2.args = args;
return _this2;
}
return CurlyComponentDefinition;
}(_runtime.ComponentDefinition);
});
enifed('ember-glimmer/component-managers/mount', ['exports', 'ember-babel', '@glimmer/runtime', 'ember-routing', 'ember/features', 'ember-glimmer/utils/references', 'ember-glimmer/component-managers/abstract', 'ember-glimmer/component-managers/outlet'], function (exports, _emberBabel, _runtime, _emberRouting, _features, _references, _abstract, _outlet) {
'use strict';
exports.MountDefinition = undefined;
var MountManager = function (_AbstractManager) {
(0, _emberBabel.inherits)(MountManager, _AbstractManager);
function MountManager() {
(0, _emberBabel.classCallCheck)(this, MountManager);
return (0, _emberBabel.possibleConstructorReturn)(this, _AbstractManager.apply(this, arguments));
}
MountManager.prototype.create = function create(environment, _ref, args) {
var name = _ref.name;
if (true) {
this._pushEngineToDebugStack('engine:' + name, environment);
}
var engine = environment.owner.buildChildEngineInstance(name);
engine.boot();
var bucket = { engine: engine };
if (_features.EMBER_ENGINES_MOUNT_PARAMS) {
bucket.modelReference = args.named.get('model');
}
return bucket;
};
MountManager.prototype.layoutFor = function layoutFor(_definition, _ref2, env) {
var engine = _ref2.engine;
var template = engine.lookup('template:application');
return env.getCompiledBlock(_outlet.OutletLayoutCompiler, template);
};
MountManager.prototype.getSelf = function getSelf(bucket) {
var engine = bucket.engine,
modelReference = bucket.modelReference;
var applicationFactory = engine.factoryFor('controller:application');
var controllerFactory = applicationFactory || (0, _emberRouting.generateControllerFactory)(engine, 'application');
var controller = bucket.controller = controllerFactory.create();
if (_features.EMBER_ENGINES_MOUNT_PARAMS) {
var model = modelReference.value();
bucket.modelRevision = modelReference.tag.value();
controller.set('model', model);
}
return new _references.RootReference(controller);
};
MountManager.prototype.getDestructor = function getDestructor(_ref3) {
var engine = _ref3.engine;
return engine;
};
MountManager.prototype.didRenderLayout = function didRenderLayout() {
if (true) {
this.debugStack.pop();
}
};
MountManager.prototype.update = function update(bucket) {
if (_features.EMBER_ENGINES_MOUNT_PARAMS) {
var controller = bucket.controller,
modelReference = bucket.modelReference,
modelRevision = bucket.modelRevision;
if (!modelReference.tag.validate(modelRevision)) {
var model = modelReference.value();
bucket.modelRevision = modelReference.tag.value();
controller.set('model', model);
}
}
};
return MountManager;
}(_abstract.default);
var MOUNT_MANAGER = new MountManager();
var MountDefinition = exports.MountDefinition = function (_ComponentDefinition) {
(0, _emberBabel.inherits)(MountDefinition, _ComponentDefinition);
function MountDefinition(name) {
(0, _emberBabel.classCallCheck)(this, MountDefinition);
return (0, _emberBabel.possibleConstructorReturn)(this, _ComponentDefinition.call(this, name, MOUNT_MANAGER, null));
}
return MountDefinition;
}(_runtime.ComponentDefinition);
});
enifed('ember-glimmer/component-managers/outlet', ['exports', 'ember-babel', '@glimmer/runtime', 'ember-metal', 'ember-utils', 'ember-glimmer/utils/references', 'ember-glimmer/component-managers/abstract'], function (exports, _emberBabel, _runtime, _emberMetal, _emberUtils, _references, _abstract) {
'use strict';
exports.OutletLayoutCompiler = exports.OutletComponentDefinition = exports.TopLevelOutletComponentDefinition = undefined;
function instrumentationPayload(_ref) {
var _ref$render = _ref.render,
name = _ref$render.name,
outlet = _ref$render.outlet;
return { object: name + ':' + outlet };
}
function NOOP() {}
var StateBucket = function () {
function StateBucket(outletState) {
(0, _emberBabel.classCallCheck)(this, StateBucket);
this.outletState = outletState;
this.instrument();
}
StateBucket.prototype.instrument = function instrument() {
this.finalizer = (0, _emberMetal._instrumentStart)('render.outlet', instrumentationPayload, this.outletState);
};
StateBucket.prototype.finalize = function finalize() {
var finalizer = this.finalizer;
finalizer();
this.finalizer = NOOP;
};
return StateBucket;
}();
var OutletComponentManager = function (_AbstractManager) {
(0, _emberBabel.inherits)(OutletComponentManager, _AbstractManager);
function OutletComponentManager() {
(0, _emberBabel.classCallCheck)(this, OutletComponentManager);
return (0, _emberBabel.possibleConstructorReturn)(this, _AbstractManager.apply(this, arguments));
}
OutletComponentManager.prototype.create = function create(environment, definition, _args, dynamicScope) {
if (true) {
this._pushToDebugStack('template:' + definition.template.meta.moduleName, environment);
}
var outletStateReference = dynamicScope.outletState = dynamicScope.outletState.get('outlets').get(definition.outletName);
var outletState = outletStateReference.value();
return new StateBucket(outletState);
};
OutletComponentManager.prototype.layoutFor = function layoutFor(definition, _bucket, env) {
return env.getCompiledBlock(OutletLayoutCompiler, definition.template);
};
OutletComponentManager.prototype.getSelf = function getSelf(_ref2) {
var outletState = _ref2.outletState;
return new _references.RootReference(outletState.render.controller);
};
OutletComponentManager.prototype.didRenderLayout = function didRenderLayout(bucket) {
bucket.finalize();
if (true) {
this.debugStack.pop();
}
};
OutletComponentManager.prototype.getDestructor = function getDestructor() {
return null;
};
return OutletComponentManager;
}(_abstract.default);
var MANAGER = new OutletComponentManager();
var TopLevelOutletComponentManager = function (_OutletComponentManag) {
(0, _emberBabel.inherits)(TopLevelOutletComponentManager, _OutletComponentManag);
function TopLevelOutletComponentManager() {
(0, _emberBabel.classCallCheck)(this, TopLevelOutletComponentManager);
return (0, _emberBabel.possibleConstructorReturn)(this, _OutletComponentManag.apply(this, arguments));
}
TopLevelOutletComponentManager.prototype.create = function create(environment, definition, _args, dynamicScope) {
if (true) {
this._pushToDebugStack('template:' + definition.template.meta.moduleName, environment);
}
return new StateBucket(dynamicScope.outletState.value());
};
TopLevelOutletComponentManager.prototype.layoutFor = function layoutFor(definition, _bucket, env) {
return env.getCompiledBlock(TopLevelOutletLayoutCompiler, definition.template);
};
return TopLevelOutletComponentManager;
}(OutletComponentManager);
var TOP_LEVEL_MANAGER = new TopLevelOutletComponentManager();
var TopLevelOutletComponentDefinition = exports.TopLevelOutletComponentDefinition = function (_ComponentDefinition) {
(0, _emberBabel.inherits)(TopLevelOutletComponentDefinition, _ComponentDefinition);
function TopLevelOutletComponentDefinition(instance) {
(0, _emberBabel.classCallCheck)(this, TopLevelOutletComponentDefinition);
var _this3 = (0, _emberBabel.possibleConstructorReturn)(this, _ComponentDefinition.call(this, 'outlet', TOP_LEVEL_MANAGER, instance));
_this3.template = instance.template;
(0, _emberUtils.generateGuid)(_this3);
return _this3;
}
return TopLevelOutletComponentDefinition;
}(_runtime.ComponentDefinition);
var TopLevelOutletLayoutCompiler = function () {
function TopLevelOutletLayoutCompiler(template) {
(0, _emberBabel.classCallCheck)(this, TopLevelOutletLayoutCompiler);
this.template = template;
}
TopLevelOutletLayoutCompiler.prototype.compile = function compile(builder) {
builder.wrapLayout(this.template);
builder.tag.static('div');
builder.attrs.static('id', (0, _emberUtils.guidFor)(this));
builder.attrs.static('class', 'ember-view');
};
return TopLevelOutletLayoutCompiler;
}();
TopLevelOutletLayoutCompiler.id = 'top-level-outlet';
var OutletComponentDefinition = exports.OutletComponentDefinition = function (_ComponentDefinition2) {
(0, _emberBabel.inherits)(OutletComponentDefinition, _ComponentDefinition2);
function OutletComponentDefinition(outletName, template) {
(0, _emberBabel.classCallCheck)(this, OutletComponentDefinition);
var _this4 = (0, _emberBabel.possibleConstructorReturn)(this, _ComponentDefinition2.call(this, 'outlet', MANAGER, null));
_this4.outletName = outletName;
_this4.template = template;
(0, _emberUtils.generateGuid)(_this4);
return _this4;
}
return OutletComponentDefinition;
}(_runtime.ComponentDefinition);
var OutletLayoutCompiler = exports.OutletLayoutCompiler = function () {
function OutletLayoutCompiler(template) {
(0, _emberBabel.classCallCheck)(this, OutletLayoutCompiler);
this.template = template;
}
OutletLayoutCompiler.prototype.compile = function compile(builder) {
builder.wrapLayout(this.template);
};
return OutletLayoutCompiler;
}();
OutletLayoutCompiler.id = 'outlet';
});
enifed('ember-glimmer/component-managers/render', ['exports', 'ember-babel', '@glimmer/runtime', 'ember-debug', 'ember-routing', 'ember-glimmer/utils/references', 'ember-glimmer/component-managers/abstract', 'ember-glimmer/component-managers/outlet'], function (exports, _emberBabel, _runtime, _emberDebug, _emberRouting, _references, _abstract, _outlet) {
'use strict';
exports.RenderDefinition = exports.NON_SINGLETON_RENDER_MANAGER = exports.SINGLETON_RENDER_MANAGER = exports.AbstractRenderManager = undefined;
var AbstractRenderManager = exports.AbstractRenderManager = function (_AbstractManager) {
(0, _emberBabel.inherits)(AbstractRenderManager, _AbstractManager);
function AbstractRenderManager() {
(0, _emberBabel.classCallCheck)(this, AbstractRenderManager);
return (0, _emberBabel.possibleConstructorReturn)(this, _AbstractManager.apply(this, arguments));
}
AbstractRenderManager.prototype.layoutFor = function layoutFor(definition, _bucket, env) {
// only curly components can have lazy layout
(true && !(!!definition.template) && (0, _emberDebug.assert)('definition is missing a template', !!definition.template));
return env.getCompiledBlock(_outlet.OutletLayoutCompiler, definition.template);
};
AbstractRenderManager.prototype.getSelf = function getSelf(_ref) {
var controller = _ref.controller;
return new _references.RootReference(controller);
};
return AbstractRenderManager;
}(_abstract.default);
if (true) {
AbstractRenderManager.prototype.didRenderLayout = function () {
this.debugStack.pop();
};
}
var SingletonRenderManager = function (_AbstractRenderManage) {
(0, _emberBabel.inherits)(SingletonRenderManager, _AbstractRenderManage);
function SingletonRenderManager() {
(0, _emberBabel.classCallCheck)(this, SingletonRenderManager);
return (0, _emberBabel.possibleConstructorReturn)(this, _AbstractRenderManage.apply(this, arguments));
}
SingletonRenderManager.prototype.create = function create(env, definition, _args, dynamicScope) {
var name = definition.name;
var controller = env.owner.lookup('controller:' + name) || (0, _emberRouting.generateController)(env.owner, name);
if (true) {
this._pushToDebugStack('controller:' + name + ' (with the render helper)', env);
}
if (dynamicScope.rootOutletState) {
dynamicScope.outletState = dynamicScope.rootOutletState.getOrphan(name);
}
return { controller: controller };
};
SingletonRenderManager.prototype.getDestructor = function getDestructor() {
return null;
};
return SingletonRenderManager;
}(AbstractRenderManager);
var SINGLETON_RENDER_MANAGER = exports.SINGLETON_RENDER_MANAGER = new SingletonRenderManager();
var NonSingletonRenderManager = function (_AbstractRenderManage2) {
(0, _emberBabel.inherits)(NonSingletonRenderManager, _AbstractRenderManage2);
function NonSingletonRenderManager() {
(0, _emberBabel.classCallCheck)(this, NonSingletonRenderManager);
return (0, _emberBabel.possibleConstructorReturn)(this, _AbstractRenderManage2.apply(this, arguments));
}
NonSingletonRenderManager.prototype.create = function create(environment, definition, args, dynamicScope) {
var name = definition.name,
env = definition.env;
var modelRef = args.positional.at(0);
var controllerFactory = env.owner.factoryFor('controller:' + name);
var factory = controllerFactory || (0, _emberRouting.generateControllerFactory)(env.owner, name);
var controller = factory.create({ model: modelRef.value() });
if (true) {
this._pushToDebugStack('controller:' + name + ' (with the render helper)', environment);
}
if (dynamicScope.rootOutletState) {
dynamicScope.outletState = dynamicScope.rootOutletState.getOrphan(name);
}
return { controller: controller, model: modelRef };
};
NonSingletonRenderManager.prototype.update = function update(_ref2) {
var controller = _ref2.controller,
model = _ref2.model;
controller.set('model', model.value());
};
NonSingletonRenderManager.prototype.getDestructor = function getDestructor(_ref3) {
var controller = _ref3.controller;
return controller;
};
return NonSingletonRenderManager;
}(AbstractRenderManager);
var NON_SINGLETON_RENDER_MANAGER = exports.NON_SINGLETON_RENDER_MANAGER = new NonSingletonRenderManager();
var RenderDefinition = exports.RenderDefinition = function (_ComponentDefinition) {
(0, _emberBabel.inherits)(RenderDefinition, _ComponentDefinition);
function RenderDefinition(name, template, env, manager) {
(0, _emberBabel.classCallCheck)(this, RenderDefinition);
var _this4 = (0, _emberBabel.possibleConstructorReturn)(this, _ComponentDefinition.call(this, 'render', manager, null));
_this4.name = name;
_this4.template = template;
_this4.env = env;
return _this4;
}
return RenderDefinition;
}(_runtime.ComponentDefinition);
});
enifed('ember-glimmer/component-managers/root', ['exports', 'ember-babel', '@glimmer/runtime', 'ember-metal', 'ember-glimmer/utils/curly-component-state-bucket', 'ember-glimmer/component-managers/curly'], function (exports, _emberBabel, _runtime, _emberMetal, _curlyComponentStateBucket, _curly) {
'use strict';
exports.RootComponentDefinition = undefined;
var RootComponentManager = function (_CurlyComponentManage) {
(0, _emberBabel.inherits)(RootComponentManager, _CurlyComponentManage);
function RootComponentManager() {
(0, _emberBabel.classCallCheck)(this, RootComponentManager);
return (0, _emberBabel.possibleConstructorReturn)(this, _CurlyComponentManage.apply(this, arguments));
}
RootComponentManager.prototype.create = function create(environment, definition, args, dynamicScope) {
var component = definition.ComponentClass.create();
if (true) {
this._pushToDebugStack(component._debugContainerKey, environment);
}
var finalizer = (0, _emberMetal._instrumentStart)('render.component', _curly.initialRenderInstrumentDetails, component);
dynamicScope.view = component;
// We usually do this in the `didCreateElement`, but that hook doesn't fire for tagless components
if (component.tagName === '') {
if (environment.isInteractive) {
component.trigger('willRender');
}
component._transitionTo('hasElement');
if (environment.isInteractive) {
component.trigger('willInsertElement');
}
}
if (true) {
(0, _curly.processComponentInitializationAssertions)(component, {});
}
return new _curlyComponentStateBucket.default(environment, component, args.named.capture(), finalizer);
};
return RootComponentManager;
}(_curly.default);
var ROOT_MANAGER = new RootComponentManager();
var RootComponentDefinition = exports.RootComponentDefinition = function (_ComponentDefinition) {
(0, _emberBabel.inherits)(RootComponentDefinition, _ComponentDefinition);
function RootComponentDefinition(instance) {
(0, _emberBabel.classCallCheck)(this, RootComponentDefinition);
var _this2 = (0, _emberBabel.possibleConstructorReturn)(this, _ComponentDefinition.call(this, '-root', ROOT_MANAGER, {
class: instance.constructor,
create: function () {
return instance;
}
}));
_this2.template = undefined;
_this2.args = undefined;
return _this2;
}
return RootComponentDefinition;
}(_runtime.ComponentDefinition);
});
enifed('ember-glimmer/component', ['exports', '@glimmer/reference', '@glimmer/runtime', 'ember-debug', 'ember-metal', 'ember-runtime', 'ember-utils', 'ember-views', 'ember-glimmer/utils/references'], function (exports, _reference, _runtime, _emberDebug, _emberMetal, _emberRuntime, _emberUtils, _emberViews, _references) {
'use strict';
exports.BOUNDS = exports.HAS_BLOCK = exports.IS_DISPATCHING_ATTRS = exports.ROOT_REF = exports.ARGS = exports.DIRTY_TAG = undefined;
var _CoreView$extend;
var DIRTY_TAG = exports.DIRTY_TAG = (0, _emberUtils.symbol)('DIRTY_TAG');
var ARGS = exports.ARGS = (0, _emberUtils.symbol)('ARGS');
var ROOT_REF = exports.ROOT_REF = (0, _emberUtils.symbol)('ROOT_REF');
var IS_DISPATCHING_ATTRS = exports.IS_DISPATCHING_ATTRS = (0, _emberUtils.symbol)('IS_DISPATCHING_ATTRS');
var HAS_BLOCK = exports.HAS_BLOCK = (0, _emberUtils.symbol)('HAS_BLOCK');
var BOUNDS = exports.BOUNDS = (0, _emberUtils.symbol)('BOUNDS');
/**
@module @ember/component
*/
/**
A `Component` is a view that is completely
isolated. Properties accessed in its templates go
to the view object and actions are targeted at
the view object. There is no access to the
surrounding context or outer controller; all
contextual information must be passed in.
The easiest way to create a `Component` is via
a template. If you name a template
`app/components/my-foo.hbs`, you will be able to use
`{{my-foo}}` in other templates, which will make
an instance of the isolated component.
```app/components/my-foo.hbs
{{person-profile person=currentUser}}
```
```app/components/person-profile.hbs
<h1>{{person.title}}</h1>
<img src={{person.avatar}}>
<p class='signature'>{{person.signature}}</p>
```
You can use `yield` inside a template to
include the **contents** of any block attached to
the component. The block will be executed in the
context of the surrounding context or outer controller:
```handlebars
{{#person-profile person=currentUser}}
<p>Admin mode</p>
{{! Executed in the controller's context. }}
{{/person-profile}}
```
```app/components/person-profile.hbs
<h1>{{person.title}}</h1>
{{! Executed in the component's context. }}
{{yield}} {{! block contents }}
```
If you want to customize the component, in order to
handle events or actions, you implement a subclass
of `Component` named after the name of the
component.
For example, you could implement the action
`hello` for the `person-profile` component:
```app/components/person-profile.js
import Component from '@ember/component';
export default Component.extend({
actions: {
hello(name) {
console.log("Hello", name);
}
}
});
```
And then use it in the component's template:
```app/templates/components/person-profile.hbs
<h1>{{person.title}}</h1>
{{yield}} <!-- block contents -->
<button {{action 'hello' person.name}}>
Say Hello to {{person.name}}
</button>
```
Components must have a `-` in their name to avoid
conflicts with built-in controls that wrap HTML
elements. This is consistent with the same
requirement in web components.
## HTML Tag
The default HTML tag name used for a component's DOM representation is `div`.
This can be customized by setting the `tagName` property.
The following component class:
```app/components/emphasized-paragraph.js
import Component from '@ember/component';
export default Component.extend({
tagName: 'em'
});
```
Would result in instances with the following HTML:
```html
<em id="ember1" class="ember-view"></em>
```
## HTML `class` Attribute
The HTML `class` attribute of a component's tag can be set by providing a
`classNames` property that is set to an array of strings:
```app/components/my-widget.js
import Component from '@ember/component';
export default Component.extend({
classNames: ['my-class', 'my-other-class']
});
```
Will result in component instances with an HTML representation of:
```html
<div id="ember1" class="ember-view my-class my-other-class"></div>
```
`class` attribute values can also be set by providing a `classNameBindings`
property set to an array of properties names for the component. The return value
of these properties will be added as part of the value for the components's `class`
attribute. These properties can be computed properties:
```app/components/my-widget.js
import Component from '@ember/component';
import { computed } from '@ember/object';
export default Component.extend({
classNameBindings: ['propertyA', 'propertyB'],
propertyA: 'from-a',
propertyB: computed(function() {
if (someLogic) { return 'from-b'; }
})
});
```
Will result in component instances with an HTML representation of:
```html
<div id="ember1" class="ember-view from-a from-b"></div>
```
If the value of a class name binding returns a boolean the property name
itself will be used as the class name if the property is true.
The class name will not be added if the value is `false` or `undefined`.
```app/components/my-widget.js
import Component from '@ember/component';
export default Component.extend({
classNameBindings: ['hovered'],
hovered: true
});
```
Will result in component instances with an HTML representation of:
```html
<div id="ember1" class="ember-view hovered"></div>
```
When using boolean class name bindings you can supply a string value other
than the property name for use as the `class` HTML attribute by appending the
preferred value after a ":" character when defining the binding:
```app/components/my-widget.js
import Component from '@ember/component';
export default Component.extend({
classNameBindings: ['awesome:so-very-cool'],
awesome: true
});
```
Will result in component instances with an HTML representation of:
```html
<div id="ember1" class="ember-view so-very-cool"></div>
```
Boolean value class name bindings whose property names are in a
camelCase-style format will be converted to a dasherized format:
```app/components/my-widget.js
import Component from '@ember/component';
export default Component.extend({
classNameBindings: ['isUrgent'],
isUrgent: true
});
```
Will result in component instances with an HTML representation of:
```html
<div id="ember1" class="ember-view is-urgent"></div>
```
Class name bindings can also refer to object values that are found by
traversing a path relative to the component itself:
```app/components/my-widget.js
import Component from '@ember/component';
import EmberObject from '@ember/object';
export default Component.extend({
classNameBindings: ['messages.empty'],
messages: EmberObject.create({
empty: true
})
});
```
Will result in component instances with an HTML representation of:
```html
<div id="ember1" class="ember-view empty"></div>
```
If you want to add a class name for a property which evaluates to true and
and a different class name if it evaluates to false, you can pass a binding
like this:
```app/components/my-widget.js
import Component from '@ember/component';
export default Component.extend({
classNameBindings: ['isEnabled:enabled:disabled'],
isEnabled: true
});
```
Will result in component instances with an HTML representation of:
```html
<div id="ember1" class="ember-view enabled"></div>
```
When isEnabled is `false`, the resulting HTML representation looks like
this:
```html
<div id="ember1" class="ember-view disabled"></div>
```
This syntax offers the convenience to add a class if a property is `false`:
```app/components/my-widget.js
import Component from '@ember/component';
// Applies no class when isEnabled is true and class 'disabled' when isEnabled is false
export default Component.extend({
classNameBindings: ['isEnabled::disabled'],
isEnabled: true
});
```
Will result in component instances with an HTML representation of:
```html
<div id="ember1" class="ember-view"></div>
```
When the `isEnabled` property on the component is set to `false`, it will result
in component instances with an HTML representation of:
```html
<div id="ember1" class="ember-view disabled"></div>
```
Updates to the value of a class name binding will result in automatic
update of the HTML `class` attribute in the component's rendered HTML
representation. If the value becomes `false` or `undefined` the class name
will be removed.
Both `classNames` and `classNameBindings` are concatenated properties. See
[EmberObject](/api/classes/Ember.Object.html) documentation for more
information about concatenated properties.
## HTML Attributes
The HTML attribute section of a component's tag can be set by providing an
`attributeBindings` property set to an array of property names on the component.
The return value of these properties will be used as the value of the component's
HTML associated attribute:
```app/components/my-anchor.js
import Component from '@ember/component';
export default Component.extend({
tagName: 'a',
attributeBindings: ['href'],
href: 'http://google.com'
});
```
Will result in component instances with an HTML representation of:
```html
<a id="ember1" class="ember-view" href="http://google.com"></a>
```
One property can be mapped on to another by placing a ":" between
the source property and the destination property:
```app/components/my-anchor.js
import Component from '@ember/component';
export default Component.extend({
tagName: 'a',
attributeBindings: ['url:href'],
url: 'http://google.com'
});
```
Will result in component instances with an HTML representation of:
```html
<a id="ember1" class="ember-view" href="http://google.com"></a>
```
Namespaced attributes (e.g. `xlink:href`) are supported, but have to be
mapped, since `:` is not a valid character for properties in Javascript:
```app/components/my-use.js
import Component from '@ember/component';
export default Component.extend({
tagName: 'use',
attributeBindings: ['xlinkHref:xlink:href'],
xlinkHref: '#triangle'
});
```
Will result in component instances with an HTML representation of:
```html
<use xlink:href="#triangle"></use>
```
If the return value of an `attributeBindings` monitored property is a boolean
the attribute will be present or absent depending on the value:
```app/components/my-text-input.js
import Component from '@ember/component';
export default Component.extend({
tagName: 'input',
attributeBindings: ['disabled'],
disabled: false
});
```
Will result in a component instance with an HTML representation of:
```html
<input id="ember1" class="ember-view" />
```
`attributeBindings` can refer to computed properties:
```app/components/my-text-input.js
import Component from '@ember/component';
import { computed } from '@ember/object';
export default Component.extend({
tagName: 'input',
attributeBindings: ['disabled'],
disabled: computed(function() {
if (someLogic) {
return true;
} else {
return false;
}
})
});
```
To prevent setting an attribute altogether, use `null` or `undefined` as the
return value of the `attributeBindings` monitored property:
```app/components/my-text-input.js
import Component from '@ember/component';
export default Component.extend({
tagName: 'form',
attributeBindings: ['novalidate'],
novalidate: null
});
```
Updates to the property of an attribute binding will result in automatic
update of the HTML attribute in the component's rendered HTML representation.
`attributeBindings` is a concatenated property. See [EmberObject](/api/classes/Ember.Object.html)
documentation for more information about concatenated properties.
## Layouts
See [Ember.Templates.helpers.yield](/api/classes/Ember.Templates.helpers.html#method_yield)
for more information.
Layout can be used to wrap content in a component. In addition
to wrapping content in a Component's template, you can also use
the public layout API in your Component JavaScript.
```app/templates/components/person-profile.hbs
<h1>Person's Title</h1>
<div class='details'>{{yield}}</div>
```
```app/components/person-profile.js
import Component from '@ember/component';
import layout from '../templates/components/person-profile';
export default Component.extend({
layout
});
```
The above will result in the following HTML output:
```html
<h1>Person's Title</h1>
<div class="details">
<h2>Chief Basket Weaver</h2>
<h3>Fisherman Industries</h3>
</div>
```
## Responding to Browser Events
Components can respond to user-initiated events in one of three ways: method
implementation, through an event manager, and through `{{action}}` helper use
in their template or layout.
### Method Implementation
Components can respond to user-initiated events by implementing a method that
matches the event name. A `jQuery.Event` object will be passed as the
argument to this method.
```app/components/my-widget.js
import Component from '@ember/component';
export default Component.extend({
click(event) {
// will be called when an instance's
// rendered element is clicked
}
});
```
### `{{action}}` Helper
See [Ember.Templates.helpers.action](/api/classes/Ember.Templates.helpers.html#method_action).
### Event Names
All of the event handling approaches described above respond to the same set
of events. The names of the built-in events are listed below. (The hash of
built-in events exists in `Ember.EventDispatcher`.) Additional, custom events
can be registered by using `Ember.Application.customEvents`.
Touch events:
* `touchStart`
* `touchMove`
* `touchEnd`
* `touchCancel`
Keyboard events:
* `keyDown`
* `keyUp`
* `keyPress`
Mouse events:
* `mouseDown`
* `mouseUp`
* `contextMenu`
* `click`
* `doubleClick`
* `mouseMove`
* `focusIn`
* `focusOut`
* `mouseEnter`
* `mouseLeave`
Form events:
* `submit`
* `change`
* `focusIn`
* `focusOut`
* `input`
HTML5 drag and drop events:
* `dragStart`
* `drag`
* `dragEnter`
* `dragLeave`
* `dragOver`
* `dragEnd`
* `drop`
@class Component
@extends Ember.CoreView
@uses Ember.TargetActionSupport
@uses Ember.ClassNamesSupport
@uses Ember.ActionSupport
@uses Ember.ViewMixin
@uses Ember.ViewStateSupport
@public
*/
var Component = _emberViews.CoreView.extend(_emberViews.ChildViewsSupport, _emberViews.ViewStateSupport, _emberViews.ClassNamesSupport, _emberRuntime.TargetActionSupport, _emberViews.ActionSupport, _emberViews.ViewMixin, (_CoreView$extend = {
isComponent: true,
init: function () {
var _this = this;
this._super.apply(this, arguments);
this[IS_DISPATCHING_ATTRS] = false;
this[DIRTY_TAG] = new _reference.DirtyableTag();
this[ROOT_REF] = new _references.RootReference(this);
this[BOUNDS] = null;
// If a `defaultLayout` was specified move it to the `layout` prop.
// `layout` is no longer a CP, so this just ensures that the `defaultLayout`
// logic is supported with a deprecation
if (this.defaultLayout && !this.layout) {
(true && !(false) && (0, _emberDebug.deprecate)('Specifying `defaultLayout` to ' + this + ' is deprecated. Please use `layout` instead.', false, {
id: 'ember-views.component.defaultLayout',
until: '3.0.0',
url: 'https://emberjs.com/deprecations/v2.x/#toc_ember-component-defaultlayout'
}));
this.layout = this.defaultLayout;
}
// If in a tagless component, assert that no event handlers are defined
(true && !(this.tagName !== '' || !this.renderer._destinedForDOM || !function () {
var eventDispatcher = (0, _emberUtils.getOwner)(_this).lookup('event_dispatcher:main');
var events = eventDispatcher && eventDispatcher._finalEvents || {};
// tslint:disable-next-line:forin
for (var key in events) {
var methodName = events[key];
if (typeof _this[methodName] === 'function') {
return true; // indicate that the assertion should be triggered
}
}
return false;
}()) && (0, _emberDebug.assert)('You can not define a function that handles DOM events in the `' + this + '` tagless component since it doesn\'t have any DOM element.', this.tagName !== '' || !this.renderer._destinedForDOM || !function () {
var eventDispatcher = (0, _emberUtils.getOwner)(_this).lookup('event_dispatcher:main');var events = eventDispatcher && eventDispatcher._finalEvents || {};for (var key in events) {
var methodName = events[key];if (typeof _this[methodName] === 'function') {
return true;
}
}return false;
}()));
(true && !(!(this.tagName && this.tagName.isDescriptor)) && (0, _emberDebug.assert)('You cannot use a computed property for the component\'s `tagName` (' + this + ').', !(this.tagName && this.tagName.isDescriptor)));
},
rerender: function () {
this[DIRTY_TAG].dirty();
this._super();
},
__defineNonEnumerable: function (property) {
this[property.name] = property.descriptor.value;
}
}, _CoreView$extend[_emberMetal.PROPERTY_DID_CHANGE] = function (key) {
if (this[IS_DISPATCHING_ATTRS]) {
return;
}
var args = this[ARGS];
var reference = args && args[key];
if (reference) {
if (reference[_references.UPDATE]) {
reference[_references.UPDATE]((0, _emberMetal.get)(this, key));
}
}
}, _CoreView$extend.getAttr = function (key) {
// TODO Intimate API should be deprecated
return this.get(key);
}, _CoreView$extend.readDOMAttr = function (name) {
var element = (0, _emberViews.getViewElement)(this);
return (0, _runtime.readDOMAttr)(element, name);
}, _CoreView$extend));
Component[_emberUtils.NAME_KEY] = 'Ember.Component';
Component.reopenClass({
isComponentFactory: true,
positionalParams: []
});
exports.default = Component;
});
enifed('ember-glimmer/components/checkbox', ['exports', 'ember-metal', 'ember-glimmer/component', 'ember-glimmer/templates/empty'], function (exports, _emberMetal, _component, _empty) {
'use strict';
exports.default = _component.default.extend({
layout: _empty.default,
classNames: ['ember-checkbox'],
tagName: 'input',
attributeBindings: ['type', 'checked', 'indeterminate', 'disabled', 'tabindex', 'name', 'autofocus', 'required', 'form'],
type: 'checkbox',
disabled: false,
indeterminate: false,
didInsertElement: function () {
this._super.apply(this, arguments);
(0, _emberMetal.get)(this, 'element').indeterminate = !!(0, _emberMetal.get)(this, 'indeterminate');
},
change: function () {
(0, _emberMetal.set)(this, 'checked', this.$().prop('checked'));
}
});
});
enifed('ember-glimmer/components/link-to', ['exports', 'ember-debug', 'ember-metal', 'ember-runtime', 'ember-views', 'ember-glimmer/component', 'ember-glimmer/templates/link-to'], function (exports, _emberDebug, _emberMetal, _emberRuntime, _emberViews, _component, _linkTo) {
'use strict';
/**
@module @ember/routing
*/
/**
`LinkComponent` renders an element whose `click` event triggers a
transition of the application's instance of `Router` to
a supplied route by name.
`LinkComponent` components are invoked with {{#link-to}}. Properties
of this class can be overridden with `reopen` to customize application-wide
behavior.
@class LinkComponent
@extends Component
@see {Ember.Templates.helpers.link-to}
@public
**/
var LinkComponent = _component.default.extend({
layout: _linkTo.default,
tagName: 'a',
/**
@deprecated Use current-when instead.
@property currentWhen
@private
*/
currentWhen: (0, _emberRuntime.deprecatingAlias)('current-when', { id: 'ember-routing-view.deprecated-current-when', until: '3.0.0' }),
/**
Used to determine when this `LinkComponent` is active.
@property current-when
@public
*/
'current-when': null,
/**
Sets the `title` attribute of the `LinkComponent`'s HTML element.
@property title
@default null
@public
**/
title: null,
/**
Sets the `rel` attribute of the `LinkComponent`'s HTML element.
@property rel
@default null
@public
**/
rel: null,
/**
Sets the `tabindex` attribute of the `LinkComponent`'s HTML element.
@property tabindex
@default null
@public
**/
tabindex: null,
/**
Sets the `target` attribute of the `LinkComponent`'s HTML element.
@since 1.8.0
@property target
@default null
@public
**/
target: null,
/**
The CSS class to apply to `LinkComponent`'s element when its `active`
property is `true`.
@property activeClass
@type String
@default active
@public
**/
activeClass: 'active',
/**
The CSS class to apply to `LinkComponent`'s element when its `loading`
property is `true`.
@property loadingClass
@type String
@default loading
@private
**/
loadingClass: 'loading',
/**
The CSS class to apply to a `LinkComponent`'s element when its `disabled`
property is `true`.
@property disabledClass
@type String
@default disabled
@private
**/
disabledClass: 'disabled',
/**
Determines whether the `LinkComponent` will trigger routing via
the `replaceWith` routing strategy.
@property replace
@type Boolean
@default false
@public
**/
replace: false,
/**
By default the `{{link-to}}` component will bind to the `href` and
`title` attributes. It's discouraged that you override these defaults,
however you can push onto the array if needed.
@property attributeBindings
@type Array | String
@default ['title', 'rel', 'tabindex', 'target']
@public
*/
attributeBindings: ['href', 'title', 'rel', 'tabindex', 'target'],
/**
By default the `{{link-to}}` component will bind to the `active`, `loading`,
and `disabled` classes. It is discouraged to override these directly.
@property classNameBindings
@type Array
@default ['active', 'loading', 'disabled', 'ember-transitioning-in', 'ember-transitioning-out']
@public
*/
classNameBindings: ['active', 'loading', 'disabled', 'transitioningIn', 'transitioningOut'],
/**
By default the `{{link-to}}` component responds to the `click` event. You
can override this globally by setting this property to your custom
event name.
This is particularly useful on mobile when one wants to avoid the 300ms
click delay using some sort of custom `tap` event.
@property eventName
@type String
@default click
@private
*/
eventName: 'click',
init: function () {
this._super.apply(this, arguments);
// Map desired event name to invoke function
var eventName = (0, _emberMetal.get)(this, 'eventName');
this.on(eventName, this, this._invoke);
},
_routing: _emberRuntime.inject.service('-routing'),
/**
Accessed as a classname binding to apply the `LinkComponent`'s `disabledClass`
CSS `class` to the element when the link is disabled.
When `true` interactions with the element will not trigger route changes.
@property disabled
@private
*/
disabled: (0, _emberMetal.computed)({
get: function (_key) {
// always returns false for `get` because (due to the `set` just below)
// the cached return value from the set will prevent this getter from _ever_
// being called after a set has occured
return false;
},
set: function (_key, value) {
this._isDisabled = value;
return value ? (0, _emberMetal.get)(this, 'disabledClass') : false;
}
}),
_isActive: function (routerState) {
if ((0, _emberMetal.get)(this, 'loading')) {
return false;
}
var currentWhen = (0, _emberMetal.get)(this, 'current-when');
if (typeof currentWhen === 'boolean') {
return currentWhen;
}
var isCurrentWhenSpecified = !!currentWhen;
currentWhen = currentWhen || (0, _emberMetal.get)(this, 'qualifiedRouteName');
currentWhen = currentWhen.split(' ');
var routing = (0, _emberMetal.get)(this, '_routing');
var models = (0, _emberMetal.get)(this, 'models');
var resolvedQueryParams = (0, _emberMetal.get)(this, 'resolvedQueryParams');
for (var i = 0; i < currentWhen.length; i++) {
if (routing.isActiveForRoute(models, resolvedQueryParams, currentWhen[i], routerState, isCurrentWhenSpecified)) {
return true;
}
}
return false;
},
/**
Accessed as a classname binding to apply the `LinkComponent`'s `activeClass`
CSS `class` to the element when the link is active.
A `LinkComponent` is considered active when its `currentWhen` property is `true`
or the application's current route is the route the `LinkComponent` would trigger
transitions into.
The `currentWhen` property can match against multiple routes by separating
route names using the ` ` (space) character.
@property active
@private
*/
active: (0, _emberMetal.computed)('activeClass', '_active', function computeLinkToComponentActiveClass() {
return this.get('_active') ? (0, _emberMetal.get)(this, 'activeClass') : false;
}),
_active: (0, _emberMetal.computed)('_routing.currentState', function computeLinkToComponentActive() {
var currentState = (0, _emberMetal.get)(this, '_routing.currentState');
if (!currentState) {
return false;
}
return this._isActive(currentState);
}),
willBeActive: (0, _emberMetal.computed)('_routing.targetState', function computeLinkToComponentWillBeActive() {
var routing = (0, _emberMetal.get)(this, '_routing');
var targetState = (0, _emberMetal.get)(routing, 'targetState');
if ((0, _emberMetal.get)(routing, 'currentState') === targetState) {
return;
}
return this._isActive(targetState);
}),
transitioningIn: (0, _emberMetal.computed)('active', 'willBeActive', function computeLinkToComponentTransitioningIn() {
if ((0, _emberMetal.get)(this, 'willBeActive') === true && !(0, _emberMetal.get)(this, '_active')) {
return 'ember-transitioning-in';
} else {
return false;
}
}),
transitioningOut: (0, _emberMetal.computed)('active', 'willBeActive', function computeLinkToComponentTransitioningOut() {
if ((0, _emberMetal.get)(this, 'willBeActive') === false && (0, _emberMetal.get)(this, '_active')) {
return 'ember-transitioning-out';
} else {
return false;
}
}),
_invoke: function (event) {
if (!(0, _emberViews.isSimpleClick)(event)) {
return true;
}
var preventDefault = (0, _emberMetal.get)(this, 'preventDefault');
var targetAttribute = (0, _emberMetal.get)(this, 'target');
if (preventDefault !== false) {
if (!targetAttribute || targetAttribute === '_self') {
event.preventDefault();
}
}
if ((0, _emberMetal.get)(this, 'bubbles') === false) {
event.stopPropagation();
}
if (this._isDisabled) {
return false;
}
if ((0, _emberMetal.get)(this, 'loading')) {
(true && (0, _emberDebug.warn)('This link-to is in an inactive loading state because at least one of its parameters presently has a null/undefined value, or the provided route name is invalid.', false));
return false;
}
if (targetAttribute && targetAttribute !== '_self') {
return false;
}
var qualifiedRouteName = (0, _emberMetal.get)(this, 'qualifiedRouteName');
var models = (0, _emberMetal.get)(this, 'models');
var queryParams = (0, _emberMetal.get)(this, 'queryParams.values');
var shouldReplace = (0, _emberMetal.get)(this, 'replace');
var payload = {
queryParams: queryParams,
routeName: qualifiedRouteName
};
// tslint:disable-next-line:max-line-length
(0, _emberMetal.flaggedInstrument)('interaction.link-to', payload, this._generateTransition(payload, qualifiedRouteName, models, queryParams, shouldReplace));
return false;
},
_generateTransition: function (payload, qualifiedRouteName, models, queryParams, shouldReplace) {
var routing = (0, _emberMetal.get)(this, '_routing');
return function () {
payload.transition = routing.transitionTo(qualifiedRouteName, models, queryParams, shouldReplace);
};
},
queryParams: null,
qualifiedRouteName: (0, _emberMetal.computed)('targetRouteName', '_routing.currentState', function computeLinkToComponentQualifiedRouteName() {
var params = (0, _emberMetal.get)(this, 'params');
var paramsLength = params.length;
var lastParam = params[paramsLength - 1];
if (lastParam && lastParam.isQueryParams) {
paramsLength--;
}
var onlyQueryParamsSupplied = this[_component.HAS_BLOCK] ? paramsLength === 0 : paramsLength === 1;
if (onlyQueryParamsSupplied) {
return (0, _emberMetal.get)(this, '_routing.currentRouteName');
}
return (0, _emberMetal.get)(this, 'targetRouteName');
}),
resolvedQueryParams: (0, _emberMetal.computed)('queryParams', function computeLinkToComponentResolvedQueryParams() {
var resolvedQueryParams = {};
var queryParams = (0, _emberMetal.get)(this, 'queryParams');
if (!queryParams) {
return resolvedQueryParams;
}
var values = queryParams.values;
for (var key in values) {
if (!values.hasOwnProperty(key)) {
continue;
}
resolvedQueryParams[key] = values[key];
}
return resolvedQueryParams;
}),
/**
Sets the element's `href` attribute to the url for
the `LinkComponent`'s targeted route.
If the `LinkComponent`'s `tagName` is changed to a value other
than `a`, this property will be ignored.
@property href
@private
*/
href: (0, _emberMetal.computed)('models', 'qualifiedRouteName', function computeLinkToComponentHref() {
if ((0, _emberMetal.get)(this, 'tagName') !== 'a') {
return;
}
var qualifiedRouteName = (0, _emberMetal.get)(this, 'qualifiedRouteName');
var models = (0, _emberMetal.get)(this, 'models');
if ((0, _emberMetal.get)(this, 'loading')) {
return (0, _emberMetal.get)(this, 'loadingHref');
}
var routing = (0, _emberMetal.get)(this, '_routing');
var queryParams = (0, _emberMetal.get)(this, 'queryParams.values');
if (true) {
/*
* Unfortunately, to get decent error messages, we need to do this.
* In some future state we should be able to use a "feature flag"
* which allows us to strip this without needing to call it twice.
*
* if (isDebugBuild()) {
* // Do the useful debug thing, probably including try/catch.
* } else {
* // Do the performant thing.
* }
*/
try {
routing.generateURL(qualifiedRouteName, models, queryParams);
} catch (e) {
(true && !(false) && (0, _emberDebug.assert)('You attempted to define a `{{link-to "' + qualifiedRouteName + '"}}` but did not pass the parameters required for generating its dynamic segments. ' + e.message));
}
}
return routing.generateURL(qualifiedRouteName, models, queryParams);
}),
loading: (0, _emberMetal.computed)('_modelsAreLoaded', 'qualifiedRouteName', function computeLinkToComponentLoading() {
var qualifiedRouteName = (0, _emberMetal.get)(this, 'qualifiedRouteName');
var modelsAreLoaded = (0, _emberMetal.get)(this, '_modelsAreLoaded');
if (!modelsAreLoaded || qualifiedRouteName === null || qualifiedRouteName === undefined) {
return (0, _emberMetal.get)(this, 'loadingClass');
}
}),
_modelsAreLoaded: (0, _emberMetal.computed)('models', function computeLinkToComponentModelsAreLoaded() {
var models = (0, _emberMetal.get)(this, 'models');
for (var i = 0; i < models.length; i++) {
var model = models[i];
if (model === null || model === undefined) {
return false;
}
}
return true;
}),
_getModels: function (params) {
var modelCount = params.length - 1;
var models = new Array(modelCount);
for (var i = 0; i < modelCount; i++) {
var value = params[i + 1];
while (_emberRuntime.ControllerMixin.detect(value)) {
(true && !(false) && (0, _emberDebug.deprecate)('Providing `{{link-to}}` with a param that is wrapped in a controller is deprecated. ' + (this.parentView ? 'Please update `' + this.parentView + '` to use `{{link-to "post" someController.model}}` instead.' : ''), false, { id: 'ember-routing-views.controller-wrapped-param', until: '3.0.0' }));
value = value.get('model');
}
models[i] = value;
}
return models;
},
/**
The default href value to use while a link-to is loading.
Only applies when tagName is 'a'
@property loadingHref
@type String
@default #
@private
*/
loadingHref: '#',
didReceiveAttrs: function () {
var queryParams = void 0;
var params = (0, _emberMetal.get)(this, 'params');
if (params) {
// Do not mutate params in place
params = params.slice();
}
(true && !(params && params.length) && (0, _emberDebug.assert)('You must provide one or more parameters to the link-to component.', params && params.length));
var disabledWhen = (0, _emberMetal.get)(this, 'disabledWhen');
if (disabledWhen !== undefined) {
this.set('disabled', disabledWhen);
}
// Process the positional arguments, in order.
// 1. Inline link title comes first, if present.
if (!this[_component.HAS_BLOCK]) {
this.set('linkTitle', params.shift());
}
// 2. `targetRouteName` is now always at index 0.
this.set('targetRouteName', params[0]);
// 3. The last argument (if still remaining) is the `queryParams` object.
var lastParam = params[params.length - 1];
if (lastParam && lastParam.isQueryParams) {
queryParams = params.pop();
} else {
queryParams = { values: {} };
}
this.set('queryParams', queryParams);
// 4. Any remaining indices (excepting `targetRouteName` at 0) are `models`.
if (params.length > 1) {
this.set('models', this._getModels(params));
} else {
this.set('models', []);
}
}
}); /**
@module ember
*/
/**
The `{{link-to}}` component renders a link to the supplied
`routeName` passing an optionally supplied model to the
route as its `model` context of the route. The block
for `{{link-to}}` becomes the innerHTML of the rendered
element:
```handlebars
{{#link-to 'photoGallery'}}
Great Hamster Photos
{{/link-to}}
```
You can also use an inline form of `{{link-to}}` component by
passing the link text as the first argument
to the component:
```handlebars
{{link-to 'Great Hamster Photos' 'photoGallery'}}
```
Both will result in:
```html
<a href="/hamster-photos">
Great Hamster Photos
</a>
```
### Supplying a tagName
By default `{{link-to}}` renders an `<a>` element. This can
be overridden for a single use of `{{link-to}}` by supplying
a `tagName` option:
```handlebars
{{#link-to 'photoGallery' tagName="li"}}
Great Hamster Photos
{{/link-to}}
```
```html
<li>
Great Hamster Photos
</li>
```
To override this option for your entire application, see
"Overriding Application-wide Defaults".
### Disabling the `link-to` component
By default `{{link-to}}` is enabled.
any passed value to the `disabled` component property will disable
the `link-to` component.
static use: the `disabled` option:
```handlebars
{{#link-to 'photoGallery' disabled=true}}
Great Hamster Photos
{{/link-to}}
```
dynamic use: the `disabledWhen` option:
```handlebars
{{#link-to 'photoGallery' disabledWhen=controller.someProperty}}
Great Hamster Photos
{{/link-to}}
```
any truthy value passed to `disabled` will disable it except `undefined`.
See "Overriding Application-wide Defaults" for more.
### Handling `href`
`{{link-to}}` will use your application's Router to
fill the element's `href` property with a url that
matches the path to the supplied `routeName` for your
router's configured `Location` scheme, which defaults
to HashLocation.
### Handling current route
`{{link-to}}` will apply a CSS class name of 'active'
when the application's current route matches
the supplied routeName. For example, if the application's
current route is 'photoGallery.recent' the following
use of `{{link-to}}`:
```handlebars
{{#link-to 'photoGallery.recent'}}
Great Hamster Photos
{{/link-to}}
```
will result in
```html
<a href="/hamster-photos/this-week" class="active">
Great Hamster Photos
</a>
```
The CSS class name used for active classes can be customized
for a single use of `{{link-to}}` by passing an `activeClass`
option:
```handlebars
{{#link-to 'photoGallery.recent' activeClass="current-url"}}
Great Hamster Photos
{{/link-to}}
```
```html
<a href="/hamster-photos/this-week" class="current-url">
Great Hamster Photos
</a>
```
To override this option for your entire application, see
"Overriding Application-wide Defaults".
### Keeping a link active for other routes
If you need a link to be 'active' even when it doesn't match
the current route, you can use the `current-when` argument.
```handlebars
{{#link-to 'photoGallery' current-when='photos'}}
Photo Gallery
{{/link-to}}
```
This may be helpful for keeping links active for:
* non-nested routes that are logically related
* some secondary menu approaches
* 'top navigation' with 'sub navigation' scenarios
A link will be active if `current-when` is `true` or the current
route is the route this link would transition to.
To match multiple routes 'space-separate' the routes:
```handlebars
{{#link-to 'gallery' current-when='photos drawings paintings'}}
Art Gallery
{{/link-to}}
```
### Supplying a model
An optional model argument can be used for routes whose
paths contain dynamic segments. This argument will become
the model context of the linked route:
```javascript
Router.map(function() {
this.route("photoGallery", {path: "hamster-photos/:photo_id"});
});
```
```handlebars
{{#link-to 'photoGallery' aPhoto}}
{{aPhoto.title}}
{{/link-to}}
```
```html
<a href="/hamster-photos/42">
Tomster
</a>
```
### Supplying multiple models
For deep-linking to route paths that contain multiple
dynamic segments, multiple model arguments can be used.
As the router transitions through the route path, each
supplied model argument will become the context for the
route with the dynamic segments:
```javascript
Router.map(function() {
this.route("photoGallery", { path: "hamster-photos/:photo_id" }, function() {
this.route("comment", {path: "comments/:comment_id"});
});
});
```
This argument will become the model context of the linked route:
```handlebars
{{#link-to 'photoGallery.comment' aPhoto comment}}
{{comment.body}}
{{/link-to}}
```
```html
<a href="/hamster-photos/42/comments/718">
A+++ would snuggle again.
</a>
```
### Supplying an explicit dynamic segment value
If you don't have a model object available to pass to `{{link-to}}`,
an optional string or integer argument can be passed for routes whose
paths contain dynamic segments. This argument will become the value
of the dynamic segment:
```javascript
Router.map(function() {
this.route("photoGallery", { path: "hamster-photos/:photo_id" });
});
```
```handlebars
{{#link-to 'photoGallery' aPhotoId}}
{{aPhoto.title}}
{{/link-to}}
```
```html
<a href="/hamster-photos/42">
Tomster
</a>
```
When transitioning into the linked route, the `model` hook will
be triggered with parameters including this passed identifier.
### Allowing Default Action
By default the `{{link-to}}` component prevents the default browser action
by calling `preventDefault()` as this sort of action bubbling is normally
handled internally and we do not want to take the browser to a new URL (for
example).
If you need to override this behavior specify `preventDefault=false` in
your template:
```handlebars
{{#link-to 'photoGallery' aPhotoId preventDefault=false}}
{{aPhotoId.title}}
{{/link-to}}
```
### Overriding attributes
You can override any given property of the `LinkComponent`
that is generated by the `{{link-to}}` component by passing
key/value pairs, like so:
```handlebars
{{#link-to aPhoto tagName='li' title='Following this link will change your life' classNames='pic sweet'}}
Uh-mazing!
{{/link-to}}
```
See [LinkComponent](/api/classes/Ember.LinkComponent.html) for a
complete list of overrideable properties. Be sure to also
check out inherited properties of `LinkComponent`.
### Overriding Application-wide Defaults
``{{link-to}}`` creates an instance of `LinkComponent` for rendering. To
override options for your entire application, export your customized
`LinkComponent` from `app/components/link-to.js` with the desired overrides:
```javascript
// app/components/link-to.js
import LinkComponent from '@ember/routing/link-component';
export default LinkComponent.extend({
activeClass: "is-active",
tagName: 'li'
})
```
It is also possible to override the default event in this manner:
```javascript
import LinkCompoennt from '@ember/routing/link-component';
export default LinkComponent.extend({
eventName: 'customEventName'
});
```
@method link-to
@for Ember.Templates.helpers
@param {String} routeName
@param {Object} [context]*
@param [options] {Object} Handlebars key/value pairs of options, you can override any property of Ember.LinkComponent
@return {String} HTML string
@see {LinkComponent}
@public
*/
LinkComponent.toString = function () {
return 'LinkComponent';
};
LinkComponent.reopenClass({
positionalParams: 'params'
});
exports.default = LinkComponent;
});
enifed('ember-glimmer/components/text_area', ['exports', 'ember-views', 'ember-glimmer/component', 'ember-glimmer/templates/empty'], function (exports, _emberViews, _component, _empty) {
'use strict';
exports.default = _component.default.extend(_emberViews.TextSupport, {
classNames: ['ember-text-area'],
layout: _empty.default,
tagName: 'textarea',
attributeBindings: ['rows', 'cols', 'name', 'selectionEnd', 'selectionStart', 'wrap', 'lang', 'dir', 'value'],
rows: null,
cols: null
});
});
enifed('ember-glimmer/components/text_field', ['exports', 'ember-environment', 'ember-metal', 'ember-views', 'ember-glimmer/component', 'ember-glimmer/templates/empty'], function (exports, _emberEnvironment, _emberMetal, _emberViews, _component, _empty) {
'use strict';
var inputTypes = Object.create(null); /**
@module @ember/component
*/
function canSetTypeOfInput(type) {
if (type in inputTypes) {
return inputTypes[type];
}
// if running in outside of a browser always return the
// original type
if (!_emberEnvironment.environment.hasDOM) {
inputTypes[type] = type;
return type;
}
var inputTypeTestElement = document.createElement('input');
try {
inputTypeTestElement.type = type;
} catch (e) {
// ignored
}
return inputTypes[type] = inputTypeTestElement.type === type;
}
/**
The internal class used to create text inputs when the `{{input}}`
helper is used with `type` of `text`.
See [Ember.Templates.helpers.input](/api/classes/Ember.Templates.helpers.html#method_input) for usage details.
## Layout and LayoutName properties
Because HTML `input` elements are self closing `layout` and `layoutName`
properties will not be applied.
@class TextField
@extends Component
@uses Ember.TextSupport
@public
*/
exports.default = _component.default.extend(_emberViews.TextSupport, {
layout: _empty.default,
classNames: ['ember-text-field'],
tagName: 'input',
attributeBindings: ['accept', 'autocomplete', 'autosave', 'dir', 'formaction', 'formenctype', 'formmethod', 'formnovalidate', 'formtarget', 'height', 'inputmode', 'lang', 'list', 'type', 'max', 'min', 'multiple', 'name', 'pattern', 'size', 'step', 'value', 'width'],
/**
The `value` attribute of the input element. As the user inputs text, this
property is updated live.
@property value
@type String
@default ""
@public
*/
value: '',
/**
The `type` attribute of the input element.
@property type
@type String
@default "text"
@public
*/
type: (0, _emberMetal.computed)({
get: function () {
return 'text';
},
set: function (_key, value) {
var type = 'text';
if (canSetTypeOfInput(value)) {
type = value;
}
return type;
}
}),
/**
The `size` of the text field in characters.
@property size
@type String
@default null
@public
*/
size: null,
/**
The `pattern` attribute of input element.
@property pattern
@type String
@default null
@public
*/
pattern: null,
/**
The `min` attribute of input element used with `type="number"` or `type="range"`.
@property min
@type String
@default null
@since 1.4.0
@public
*/
min: null,
/**
The `max` attribute of input element used with `type="number"` or `type="range"`.
@property max
@type String
@default null
@since 1.4.0
@public
*/
max: null
});
});
enifed('ember-glimmer/dom', ['exports', '@glimmer/runtime', '@glimmer/node'], function (exports, _runtime, _node) {
'use strict';
Object.defineProperty(exports, 'DOMChanges', {
enumerable: true,
get: function () {
return _runtime.DOMChanges;
}
});
Object.defineProperty(exports, 'DOMTreeConstruction', {
enumerable: true,
get: function () {
return _runtime.DOMTreeConstruction;
}
});
Object.defineProperty(exports, 'NodeDOMTreeConstruction', {
enumerable: true,
get: function () {
return _node.NodeDOMTreeConstruction;
}
});
});
enifed('ember-glimmer/environment', ['exports', 'ember-babel', '@glimmer/runtime', 'ember-debug', 'ember-metal', 'ember-utils', 'ember-views', 'ember-glimmer/component-managers/curly', 'ember-glimmer/syntax', 'ember-glimmer/utils/debug-stack', 'ember-glimmer/utils/iterable', 'ember-glimmer/utils/references', 'ember-glimmer/helpers/-class', 'ember-glimmer/helpers/-html-safe', 'ember-glimmer/helpers/-input-type', 'ember-glimmer/helpers/-normalize-class', 'ember-glimmer/helpers/action', 'ember-glimmer/helpers/component', 'ember-glimmer/helpers/concat', 'ember-glimmer/helpers/each-in', 'ember-glimmer/helpers/get', 'ember-glimmer/helpers/hash', 'ember-glimmer/helpers/if-unless', 'ember-glimmer/helpers/log', 'ember-glimmer/helpers/mut', 'ember-glimmer/helpers/query-param', 'ember-glimmer/helpers/readonly', 'ember-glimmer/helpers/unbound', 'ember-glimmer/modifiers/action', 'ember-glimmer/protocol-for-url', 'ember/features'], function (exports, _emberBabel, _runtime, _emberDebug, _emberMetal, _emberUtils, _emberViews, _curly, _syntax, _debugStack, _iterable, _references, _class, _htmlSafe, _inputType, _normalizeClass, _action, _component, _concat, _eachIn, _get, _hash, _ifUnless, _log, _mut, _queryParam, _readonly, _unbound, _action2, _protocolForUrl, _features) {
'use strict';
function instrumentationPayload(name) {
return { object: 'component:' + name };
}
function isTemplateFactory(template) {
return typeof template.create === 'function';
}
var Environment = function (_GlimmerEnvironment) {
(0, _emberBabel.inherits)(Environment, _GlimmerEnvironment);
Environment.create = function create(options) {
return new this(options);
};
function Environment(injections) {
(0, _emberBabel.classCallCheck)(this, Environment);
var _this = (0, _emberBabel.possibleConstructorReturn)(this, _GlimmerEnvironment.call(this, injections));
_this.owner = injections[_emberUtils.OWNER];
_this.isInteractive = _this.owner.lookup('-environment:main').isInteractive;
// can be removed once https://github.com/tildeio/glimmer/pull/305 lands
_this.destroyedComponents = [];
(0, _protocolForUrl.default)(_this);
_this._definitionCache = new _emberMetal.Cache(2000, function (_ref) {
var name = _ref.name,
source = _ref.source,
owner = _ref.owner;
var _lookupComponent = (0, _emberViews.lookupComponent)(owner, name, { source: source }),
componentFactory = _lookupComponent.component,
layout = _lookupComponent.layout;
var customManager = void 0;
if (componentFactory || layout) {
if (_features.GLIMMER_CUSTOM_COMPONENT_MANAGER) {
var managerId = layout && layout.meta.managerId;
if (managerId) {
customManager = owner.factoryFor('component-manager:' + managerId).class;
}
}
return new _curly.CurlyComponentDefinition(name, componentFactory, layout, undefined, customManager);
}
return undefined;
}, function (_ref2) {
var name = _ref2.name,
source = _ref2.source,
owner = _ref2.owner;
var expandedName = source && _this._resolveLocalLookupName(name, source, owner) || name;
var ownerGuid = (0, _emberUtils.guidFor)(owner);
return ownerGuid + '|' + expandedName;
});
_this._templateCache = new _emberMetal.Cache(1000, function (_ref3) {
var Template = _ref3.Template,
owner = _ref3.owner;
if (isTemplateFactory(Template)) {
var _Template$create;
// we received a factory
return Template.create((_Template$create = { env: _this }, _Template$create[_emberUtils.OWNER] = owner, _Template$create));
} else {
// we were provided an instance already
return Template;
}
}, function (_ref4) {
var Template = _ref4.Template,
owner = _ref4.owner;
return (0, _emberUtils.guidFor)(owner) + '|' + Template.id;
});
_this._compilerCache = new _emberMetal.Cache(10, function (Compiler) {
return new _emberMetal.Cache(2000, function (template) {
var compilable = new Compiler(template);
return (0, _runtime.compileLayout)(compilable, _this);
}, function (template) {
var owner = template.meta.owner;
return (0, _emberUtils.guidFor)(owner) + '|' + template.id;
});
}, function (Compiler) {
return Compiler.id;
});
_this.builtInModifiers = {
action: new _action2.default()
};
_this.builtInHelpers = {
'if': _ifUnless.inlineIf,
action: _action.default,
concat: _concat.default,
get: _get.default,
hash: _hash.default,
log: _log.default,
mut: _mut.default,
'query-params': _queryParam.default,
readonly: _readonly.default,
unbound: _unbound.default,
'unless': _ifUnless.inlineUnless,
'-class': _class.default,
'-each-in': _eachIn.default,
'-input-type': _inputType.default,
'-normalize-class': _normalizeClass.default,
'-html-safe': _htmlSafe.default,
'-get-dynamic-var': _runtime.getDynamicVar
};
if (true) {
_this.debugStack = new _debugStack.default();
}
return _this;
}
// this gets clobbered by installPlatformSpecificProtocolForURL
// it really should just delegate to a platform specific injection
Environment.prototype.protocolForURL = function protocolForURL(s) {
return s;
};
Environment.prototype._resolveLocalLookupName = function _resolveLocalLookupName(name, source, owner) {
return _features.EMBER_MODULE_UNIFICATION ? source + ':' + name : owner._resolveLocalLookupName(name, source);
};
Environment.prototype.macros = function macros() {
var macros = _GlimmerEnvironment.prototype.macros.call(this);
(0, _syntax.populateMacros)(macros.blocks, macros.inlines);
return macros;
};
Environment.prototype.hasComponentDefinition = function hasComponentDefinition() {
return false;
};
Environment.prototype.getComponentDefinition = function getComponentDefinition(name, _ref5) {
var owner = _ref5.owner,
moduleName = _ref5.moduleName;
var finalizer = (0, _emberMetal._instrumentStart)('render.getComponentDefinition', instrumentationPayload, name);
var source = moduleName && 'template:' + moduleName;
var definition = this._definitionCache.get({ name: name, source: source, owner: owner });
finalizer();
// TODO the glimmer-vm wants this to always have a def
// but internally we need it to sometimes be undefined
return definition;
};
Environment.prototype.getTemplate = function getTemplate(Template, owner) {
return this._templateCache.get({ Template: Template, owner: owner });
};
Environment.prototype.getCompiledBlock = function getCompiledBlock(Compiler, template) {
var compilerCache = this._compilerCache.get(Compiler);
return compilerCache.get(template);
};
Environment.prototype.hasPartial = function hasPartial(name, meta) {
return (0, _emberViews.hasPartial)(name, meta.owner);
};
Environment.prototype.lookupPartial = function lookupPartial(name, meta) {
var partial = {
name: name,
template: (0, _emberViews.lookupPartial)(name, meta.owner)
};
if (partial.template) {
return partial;
} else {
throw new Error(name + ' is not a partial');
}
};
Environment.prototype.hasHelper = function hasHelper(name, _ref6) {
var owner = _ref6.owner,
moduleName = _ref6.moduleName;
if (name === 'component' || this.builtInHelpers[name]) {
return true;
}
var options = { source: 'template:' + moduleName };
return owner.hasRegistration('helper:' + name, options) || owner.hasRegistration('helper:' + name);
};
Environment.prototype.lookupHelper = function lookupHelper(name, meta) {
if (name === 'component') {
return function (vm, args) {
return (0, _component.default)(vm, args, meta);
};
}
var owner = meta.owner,
moduleName = meta.moduleName;
var helper = this.builtInHelpers[name];
if (helper) {
return helper;
}
var options = moduleName && { source: 'template:' + moduleName } || {};
var helperFactory = owner.factoryFor('helper:' + name, options) || owner.factoryFor('helper:' + name);
// TODO: try to unify this into a consistent protocol to avoid wasteful closure allocations
var HelperReference = void 0;
if (helperFactory.class.isSimpleHelperFactory) {
HelperReference = _references.SimpleHelperReference;
} else if (helperFactory.class.isHelperFactory) {
HelperReference = _references.ClassBasedHelperReference;
} else {
throw new Error(name + ' is not a helper');
}
return function (vm, args) {
return HelperReference.create(helperFactory, vm, args.capture());
};
};
Environment.prototype.hasModifier = function hasModifier(name) {
return !!this.builtInModifiers[name];
};
Environment.prototype.lookupModifier = function lookupModifier(name) {
var modifier = this.builtInModifiers[name];
if (modifier) {
return modifier;
} else {
throw new Error(name + ' is not a modifier');
}
};
Environment.prototype.toConditionalReference = function toConditionalReference(reference) {
return _references.ConditionalReference.create(reference);
};
Environment.prototype.iterableFor = function iterableFor(ref, key) {
return (0, _iterable.default)(ref, key);
};
Environment.prototype.scheduleInstallModifier = function scheduleInstallModifier(modifier, manager) {
if (this.isInteractive) {
_GlimmerEnvironment.prototype.scheduleInstallModifier.call(this, modifier, manager);
}
};
Environment.prototype.scheduleUpdateModifier = function scheduleUpdateModifier(modifier, manager) {
if (this.isInteractive) {
_GlimmerEnvironment.prototype.scheduleUpdateModifier.call(this, modifier, manager);
}
};
Environment.prototype.didDestroy = function didDestroy(destroyable) {
destroyable.destroy();
};
Environment.prototype.begin = function begin() {
this.inTransaction = true;
_GlimmerEnvironment.prototype.begin.call(this);
};
Environment.prototype.commit = function commit() {
var destroyedComponents = this.destroyedComponents;
this.destroyedComponents = [];
// components queued for destruction must be destroyed before firing
// `didCreate` to prevent errors when removing and adding a component
// with the same name (would throw an error when added to view registry)
for (var i = 0; i < destroyedComponents.length; i++) {
destroyedComponents[i].destroy();
}
_GlimmerEnvironment.prototype.commit.call(this);
this.inTransaction = false;
};
return Environment;
}(_runtime.Environment);
exports.default = Environment;
if (true) {
var StyleAttributeManager = function (_AttributeManager) {
(0, _emberBabel.inherits)(StyleAttributeManager, _AttributeManager);
function StyleAttributeManager() {
(0, _emberBabel.classCallCheck)(this, StyleAttributeManager);
return (0, _emberBabel.possibleConstructorReturn)(this, _AttributeManager.apply(this, arguments));
}
StyleAttributeManager.prototype.setAttribute = function setAttribute(dom, element, value) {
(true && (0, _emberDebug.warn)((0, _emberViews.constructStyleDeprecationMessage)(value), function () {
if (value === null || value === undefined || (0, _runtime.isSafeString)(value)) {
return true;
}
return false;
}(), { id: 'ember-htmlbars.style-xss-warning' }));
_AttributeManager.prototype.setAttribute.call(this, dom, element, value);
};
StyleAttributeManager.prototype.updateAttribute = function updateAttribute(dom, element, value) {
(true && (0, _emberDebug.warn)((0, _emberViews.constructStyleDeprecationMessage)(value), function () {
if (value === null || value === undefined || (0, _runtime.isSafeString)(value)) {
return true;
}
return false;
}(), { id: 'ember-htmlbars.style-xss-warning' }));
_AttributeManager.prototype.updateAttribute.call(this, dom, element, value);
};
return StyleAttributeManager;
}(_runtime.AttributeManager);
var STYLE_ATTRIBUTE_MANANGER = new StyleAttributeManager('style');
Environment.prototype.attributeFor = function (element, attribute, isTrusting) {
if (attribute === 'style' && !isTrusting) {
return STYLE_ATTRIBUTE_MANANGER;
}
return _runtime.Environment.prototype.attributeFor.call(this, element, attribute, isTrusting);
};
}
});
enifed('ember-glimmer/helper', ['exports', 'ember-babel', '@glimmer/reference', 'ember-runtime', 'ember-utils'], function (exports, _emberBabel, _reference, _emberRuntime, _emberUtils) {
'use strict';
exports.SimpleHelper = exports.RECOMPUTE_TAG = undefined;
exports.helper = helper;
var RECOMPUTE_TAG = exports.RECOMPUTE_TAG = (0, _emberUtils.symbol)('RECOMPUTE_TAG');
/**
Ember Helpers are functions that can compute values, and are used in templates.
For example, this code calls a helper named `format-currency`:
```handlebars
<div>{{format-currency cents currency="$"}}</div>
```
Additionally a helper can be called as a nested helper (sometimes called a
subexpression). In this example, the computed value of a helper is passed
to a component named `show-money`:
```handlebars
{{show-money amount=(format-currency cents currency="$")}}
```
Helpers defined using a class must provide a `compute` function. For example:
```app/helpers/format-currency.js
import Helper from '@ember/component/helper';
export default Helper.extend({
compute(params, hash) {
let cents = params[0];
let currency = hash.currency;
return `${currency}${cents * 0.01}`;
}
});
```
Each time the input to a helper changes, the `compute` function will be
called again.
As instances, these helpers also have access to the container an will accept
injected dependencies.
Additionally, class helpers can call `recompute` to force a new computation.
@class Helper
@public
@since 1.13.0
*/
/**
@module @ember/component
*/
var Helper = _emberRuntime.FrameworkObject.extend({
isHelperInstance: true,
init: function () {
this._super.apply(this, arguments);
this[RECOMPUTE_TAG] = new _reference.DirtyableTag();
},
recompute: function () {
this[RECOMPUTE_TAG].dirty();
}
});
Helper.reopenClass({
isHelperFactory: true
});
var SimpleHelper = exports.SimpleHelper = function () {
function SimpleHelper(compute) {
(0, _emberBabel.classCallCheck)(this, SimpleHelper);
this.compute = compute;
this.isHelperFactory = true;
this.isHelperInstance = true;
this.isSimpleHelperFactory = true;
}
SimpleHelper.prototype.create = function create() {
return this;
};
return SimpleHelper;
}();
/**
In many cases, the ceremony of a full `Helper` class is not required.
The `helper` method create pure-function helpers without instances. For
example:
```app/helpers/format-currency.js
import { helper } from '@ember/component/helper';
export default helper(function(params, hash) {
let cents = params[0];
let currency = hash.currency;
return `${currency}${cents * 0.01}`;
});
```
@static
@param {Function} helper The helper function
@method helper
@for @ember/component/helper
@public
@since 1.13.0
*/
function helper(helperFn) {
return new SimpleHelper(helperFn);
}
exports.default = Helper;
});
enifed('ember-glimmer/helpers/-class', ['exports', 'ember-runtime', 'ember-glimmer/utils/references'], function (exports, _emberRuntime, _references) {
'use strict';
exports.default = function (_vm, args) {
return new _references.InternalHelperReference(classHelper, args.capture());
};
function classHelper(_ref) {
var positional = _ref.positional;
var path = positional.at(0);
var args = positional.length;
var value = path.value();
if (value === true) {
if (args > 1) {
return _emberRuntime.String.dasherize(positional.at(1).value());
}
return null;
}
if (value === false) {
if (args > 2) {
return _emberRuntime.String.dasherize(positional.at(2).value());
}
return null;
}
return value;
}
});
enifed('ember-glimmer/helpers/-html-safe', ['exports', 'ember-glimmer/utils/references', 'ember-glimmer/utils/string'], function (exports, _references, _string) {
'use strict';
exports.default = function (_vm, args) {
return new _references.InternalHelperReference(htmlSafe, args.capture());
};
function htmlSafe(_ref) {
var positional = _ref.positional;
var path = positional.at(0);
return new _string.SafeString(path.value());
}
});
enifed('ember-glimmer/helpers/-input-type', ['exports', 'ember-glimmer/utils/references'], function (exports, _references) {
'use strict';
exports.default = function (_vm, args) {
return new _references.InternalHelperReference(inputTypeHelper, args.capture());
};
function inputTypeHelper(_ref) {
var positional = _ref.positional;
var type = positional.at(0).value();
if (type === 'checkbox') {
return '-checkbox';
}
return '-text-field';
}
});
enifed('ember-glimmer/helpers/-normalize-class', ['exports', 'ember-runtime', 'ember-glimmer/utils/references'], function (exports, _emberRuntime, _references) {
'use strict';
exports.default = function (_vm, args) {
return new _references.InternalHelperReference(normalizeClass, args.capture());
};
function normalizeClass(_ref) {
var positional = _ref.positional;
var classNameParts = positional.at(0).value().split('.');
var className = classNameParts[classNameParts.length - 1];
var value = positional.at(1).value();
if (value === true) {
return _emberRuntime.String.dasherize(className);
} else if (!value && value !== 0) {
return '';
} else {
return String(value);
}
}
});
enifed('ember-glimmer/helpers/action', ['exports', '@glimmer/reference', 'ember-debug', 'ember-metal', 'ember-utils', 'ember-glimmer/utils/references'], function (exports, _reference, _emberDebug, _emberMetal, _emberUtils, _references) {
'use strict';
exports.ACTION = exports.INVOKE = undefined;
exports.default = function (_vm, args) {
var named = args.named,
positional = args.positional;
var capturedArgs = positional.capture();
// The first two argument slots are reserved.
// pos[0] is the context (or `this`)
// pos[1] is the action name or function
// Anything else is an action argument.
var _capturedArgs$referen = capturedArgs.references,
context = _capturedArgs$referen[0],
action = _capturedArgs$referen[1],
restArgs = _capturedArgs$referen.slice(2);
// TODO: Is there a better way of doing this?
var debugKey = action._propertyKey;
var target = named.has('target') ? named.get('target') : context;
var processArgs = makeArgsProcessor(named.has('value') && named.get('value'), restArgs);
var fn = void 0;
if (typeof action[INVOKE] === 'function') {
fn = makeClosureAction(action, action, action[INVOKE], processArgs, debugKey);
} else if ((0, _reference.isConst)(target) && (0, _reference.isConst)(action)) {
fn = makeClosureAction(context.value(), target.value(), action.value(), processArgs, debugKey);
} else {
fn = makeDynamicClosureAction(context.value(), target, action, processArgs, debugKey);
}
fn[ACTION] = true;
return new _references.UnboundReference(fn);
};
var INVOKE = exports.INVOKE = (0, _emberUtils.symbol)('INVOKE'); /**
@module ember
*/
var ACTION = exports.ACTION = (0, _emberUtils.symbol)('ACTION');
/**
The `{{action}}` helper provides a way to pass triggers for behavior (usually
just a function) between components, and into components from controllers.
### Passing functions with the action helper
There are three contexts an action helper can be used in. The first two
contexts to discuss are attribute context, and Handlebars value context.
```handlebars
{{! An example of attribute context }}
<div onclick={{action "save"}}></div>
{{! Examples of Handlebars value context }}
{{input on-input=(action "save")}}
{{yield (action "refreshData") andAnotherParam}}
```
In these contexts,
the helper is called a "closure action" helper. Its behavior is simple:
If passed a function name, read that function off the `actions` property
of the current context. Once that function is read (or if a function was
passed), create a closure over that function and any arguments.
The resulting value of an action helper used this way is simply a function.
For example, in the attribute context:
```handlebars
{{! An example of attribute context }}
<div onclick={{action "save"}}></div>
```
The resulting template render logic would be:
```js
var div = document.createElement('div');
var actionFunction = (function(context){
return function() {
return context.actions.save.apply(context, arguments);
};
})(context);
div.onclick = actionFunction;
```
Thus when the div is clicked, the action on that context is called.
Because the `actionFunction` is just a function, closure actions can be
passed between components and still execute in the correct context.
Here is an example action handler on a component:
```app/components/my-component.js
import Component from '@ember/component';
export default Component.extend({
actions: {
save() {
this.get('model').save();
}
}
});
```
Actions are always looked up on the `actions` property of the current context.
This avoids collisions in the naming of common actions, such as `destroy`.
Two options can be passed to the `action` helper when it is used in this way.
* `target=someProperty` will look to `someProperty` instead of the current
context for the `actions` hash. This can be useful when targeting a
service for actions.
* `value="target.value"` will read the path `target.value` off the first
argument to the action when it is called and rewrite the first argument
to be that value. This is useful when attaching actions to event listeners.
### Invoking an action
Closure actions curry both their scope and any arguments. When invoked, any
additional arguments are added to the already curried list.
Actions should be invoked using the [sendAction](/api/classes/Ember.Component.html#method_sendAction)
method. The first argument to `sendAction` is the action to be called, and
additional arguments are passed to the action function. This has interesting
properties combined with currying of arguments. For example:
```app/components/my-component.js
import Component from '@ember/component';
export default Component.extend({
actions: {
// Usage {{input on-input=(action (action 'setName' model) value="target.value")}}
setName(model, name) {
model.set('name', name);
}
}
});
```
The first argument (`model`) was curried over, and the run-time argument (`event`)
becomes a second argument. Action calls can be nested this way because each simply
returns a function. Any function can be passed to the `{{action}}` helper, including
other actions.
Actions invoked with `sendAction` have the same currying behavior as demonstrated
with `on-input` above. For example:
```app/components/my-input.js
import Component from '@ember/component';
export default Component.extend({
actions: {
setName(model, name) {
model.set('name', name);
}
}
});
```
```handlebars
{{my-input submit=(action 'setName' model)}}
```
```app/components/my-component.js
import Component from '@ember/component';
export default Component.extend({
click() {
// Note that model is not passed, it was curried in the template
this.sendAction('submit', 'bob');
}
});
```
### Attaching actions to DOM elements
The third context of the `{{action}}` helper can be called "element space".
For example:
```handlebars
{{! An example of element space }}
<div {{action "save"}}></div>
```
Used this way, the `{{action}}` helper provides a useful shortcut for
registering an HTML element in a template for a single DOM event and
forwarding that interaction to the template's context (controller or component).
If the context of a template is a controller, actions used this way will
bubble to routes when the controller does not implement the specified action.
Once an action hits a route, it will bubble through the route hierarchy.
### Event Propagation
`{{action}}` helpers called in element space can control event bubbling. Note
that the closure style actions cannot.
Events triggered through the action helper will automatically have
`.preventDefault()` called on them. You do not need to do so in your event
handlers. If you need to allow event propagation (to handle file inputs for
example) you can supply the `preventDefault=false` option to the `{{action}}` helper:
```handlebars
<div {{action "sayHello" preventDefault=false}}>
<input type="file" />
<input type="checkbox" />
</div>
```
To disable bubbling, pass `bubbles=false` to the helper:
```handlebars
<button {{action 'edit' post bubbles=false}}>Edit</button>
```
To disable bubbling with closure style actions you must create your own
wrapper helper that makes use of `event.stopPropagation()`:
```handlebars
<div onclick={{disable-bubbling (action "sayHello")}}>Hello</div>
```
```app/helpers/disable-bubbling.js
import { helper } from '@ember/component/helper';
export function disableBubbling([action]) {
return function(event) {
event.stopPropagation();
return action(event);
};
}
export default helper(disableBubbling);
```
If you need the default handler to trigger you should either register your
own event handler, or use event methods on your view class. See
["Responding to Browser Events"](/api/classes/Ember.Component#responding-to-browser-events)
in the documentation for `Component` for more information.
### Specifying DOM event type
`{{action}}` helpers called in element space can specify an event type.
By default the `{{action}}` helper registers for DOM `click` events. You can
supply an `on` option to the helper to specify a different DOM event name:
```handlebars
<div {{action "anActionName" on="doubleClick"}}>
click me
</div>
```
See ["Event Names"](/api/classes/Ember.Component#event-names) for a list of
acceptable DOM event names.
### Specifying whitelisted modifier keys
`{{action}}` helpers called in element space can specify modifier keys.
By default the `{{action}}` helper will ignore click events with pressed modifier
keys. You can supply an `allowedKeys` option to specify which keys should not be ignored.
```handlebars
<div {{action "anActionName" allowedKeys="alt"}}>
click me
</div>
```
This way the action will fire when clicking with the alt key pressed down.
Alternatively, supply "any" to the `allowedKeys` option to accept any combination of modifier keys.
```handlebars
<div {{action "anActionName" allowedKeys="any"}}>
click me with any key pressed
</div>
```
### Specifying a Target
A `target` option can be provided to the helper to change
which object will receive the method call. This option must be a path
to an object, accessible in the current context:
```app/templates/application.hbs
<div {{action "anActionName" target=someService}}>
click me
</div>
```
```app/controllers/application.js
import Controller from '@ember/controller';
import { inject as service } from '@ember/service';
export default Controller.extend({
someService: service()
});
```
@method action
@for Ember.Templates.helpers
@public
*/
function NOOP(args) {
return args;
}
function makeArgsProcessor(valuePathRef, actionArgsRef) {
var mergeArgs = void 0;
if (actionArgsRef.length > 0) {
mergeArgs = function (args) {
return actionArgsRef.map(function (ref) {
return ref.value();
}).concat(args);
};
}
var readValue = void 0;
if (valuePathRef) {
readValue = function (args) {
var valuePath = valuePathRef.value();
if (valuePath && args.length > 0) {
args[0] = (0, _emberMetal.get)(args[0], valuePath);
}
return args;
};
}
if (mergeArgs && readValue) {
return function (args) {
return readValue(mergeArgs(args));
};
} else {
return mergeArgs || readValue || NOOP;
}
}
function makeDynamicClosureAction(context, targetRef, actionRef, processArgs, debugKey) {
// We don't allow undefined/null values, so this creates a throw-away action to trigger the assertions
if (true) {
makeClosureAction(context, targetRef.value(), actionRef.value(), processArgs, debugKey);
}
return function () {
return makeClosureAction(context, targetRef.value(), actionRef.value(), processArgs, debugKey).apply(undefined, arguments);
};
}
function makeClosureAction(context, target, action, processArgs, debugKey) {
var self = void 0;
var fn = void 0;
(true && !(!(0, _emberMetal.isNone)(action)) && (0, _emberDebug.assert)('Action passed is null or undefined in (action) from ' + target + '.', !(0, _emberMetal.isNone)(action)));
if (typeof action[INVOKE] === 'function') {
self = action;
fn = action[INVOKE];
} else {
var typeofAction = typeof action;
if (typeofAction === 'string') {
self = target;
fn = target.actions && target.actions[action];
(true && !(fn) && (0, _emberDebug.assert)('An action named \'' + action + '\' was not found in ' + target, fn));
} else if (typeofAction === 'function') {
self = context;
fn = action;
} else {
(true && !(false) && (0, _emberDebug.assert)('An action could not be made for `' + (debugKey || action) + '` in ' + target + '. Please confirm that you are using either a quoted action name (i.e. `(action \'' + (debugKey || 'myAction') + '\')`) or a function available in ' + target + '.', false));
}
}
return function () {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var payload = { target: self, args: args, label: '@glimmer/closure-action' };
return (0, _emberMetal.flaggedInstrument)('interaction.ember-action', payload, function () {
return _emberMetal.run.join.apply(_emberMetal.run, [self, fn].concat(processArgs(args)));
});
};
}
});
enifed('ember-glimmer/helpers/component', ['exports', 'ember-babel', '@glimmer/runtime', 'ember-debug', 'ember-utils', 'ember-glimmer/component-managers/curly', 'ember-glimmer/utils/references'], function (exports, _emberBabel, _runtime, _emberDebug, _emberUtils, _curly, _references) {
'use strict';
exports.ClosureComponentReference = undefined;
exports.default = function (vm, args, meta) {
return ClosureComponentReference.create(args.capture(), meta, vm.env);
};
var ClosureComponentReference = exports.ClosureComponentReference = function (_CachedReference) {
(0, _emberBabel.inherits)(ClosureComponentReference, _CachedReference);
ClosureComponentReference.create = function create(args, meta, env) {
return new ClosureComponentReference(args, meta, env);
};
function ClosureComponentReference(args, meta, env) {
(0, _emberBabel.classCallCheck)(this, ClosureComponentReference);
var _this = (0, _emberBabel.possibleConstructorReturn)(this, _CachedReference.call(this));
var firstArg = args.positional.at(0);
_this.defRef = firstArg;
_this.tag = firstArg.tag;
_this.args = args;
_this.meta = meta;
_this.env = env;
_this.lastDefinition = undefined;
_this.lastName = undefined;
return _this;
}
ClosureComponentReference.prototype.compute = function compute() {
// TODO: Figure out how to extract this because it's nearly identical to
// DynamicComponentReference::compute(). The only differences besides
// currying are in the assertion messages.
var args = this.args,
defRef = this.defRef,
env = this.env,
meta = this.meta,
lastDefinition = this.lastDefinition,
lastName = this.lastName;
var nameOrDef = defRef.value();
var definition = void 0;
if (nameOrDef && nameOrDef === lastName) {
return lastDefinition;
}
this.lastName = nameOrDef;
if (typeof nameOrDef === 'string') {
// tslint:disable-next-line:max-line-length
(true && !(nameOrDef !== 'input') && (0, _emberDebug.assert)('You cannot use the input helper as a contextual helper. Please extend TextField or Checkbox to use it as a contextual component.', nameOrDef !== 'input'));
// tslint:disable-next-line:max-line-length
(true && !(nameOrDef !== 'textarea') && (0, _emberDebug.assert)('You cannot use the textarea helper as a contextual helper. Please extend TextArea to use it as a contextual component.', nameOrDef !== 'textarea'));
definition = env.getComponentDefinition(nameOrDef, meta);
// tslint:disable-next-line:max-line-length
(true && !(!!definition) && (0, _emberDebug.assert)('The component helper cannot be used without a valid component name. You used "' + nameOrDef + '" via (component "' + nameOrDef + '")', !!definition));
} else if ((0, _runtime.isComponentDefinition)(nameOrDef)) {
definition = nameOrDef;
} else {
(true && !(nameOrDef) && (0, _emberDebug.assert)('You cannot create a component from ' + nameOrDef + ' using the {{component}} helper', nameOrDef));
return null;
}
var newDef = createCurriedDefinition(definition, args);
this.lastDefinition = newDef;
return newDef;
};
return ClosureComponentReference;
}(_references.CachedReference);
function createCurriedDefinition(definition, args) {
var curriedArgs = curryArgs(definition, args);
return new _curly.CurlyComponentDefinition(definition.name, definition.ComponentClass, definition.template, curriedArgs);
}
function curryArgs(definition, newArgs) {
var args = definition.args,
ComponentClass = definition.ComponentClass;
var positionalParams = ComponentClass.class.positionalParams;
// The args being passed in are from the (component ...) invocation,
// so the first positional argument is actually the name or component
// definition. It needs to be dropped in order for any actual positional
// args to coincide with the ComponentClass's positionParams.
// For "normal" curly components this slicing is done at the syntax layer,
// but we don't have that luxury here.
var _newArgs$positional$r = newArgs.positional.references,
slicedPositionalArgs = _newArgs$positional$r.slice(1);
if (positionalParams && slicedPositionalArgs.length) {
(0, _curly.validatePositionalParameters)(newArgs.named, slicedPositionalArgs, positionalParams);
}
var isRest = typeof positionalParams === 'string';
// For non-rest position params, we need to perform the position -> name mapping
// at each layer to avoid a collision later when the args are used to construct
// the component instance (inside of processArgs(), inside of create()).
var positionalToNamedParams = {};
if (!isRest && positionalParams.length > 0) {
var limit = Math.min(positionalParams.length, slicedPositionalArgs.length);
for (var i = 0; i < limit; i++) {
var name = positionalParams[i];
positionalToNamedParams[name] = slicedPositionalArgs[i];
}
slicedPositionalArgs.length = 0; // Throw them away since you're merged in.
}
// args (aka 'oldArgs') may be undefined or simply be empty args, so
// we need to fall back to an empty array or object.
var oldNamed = args && args.named || {};
var oldPositional = args && args.positional || [];
// Merge positional arrays
var positional = new Array(Math.max(oldPositional.length, slicedPositionalArgs.length));
positional.splice.apply(positional, [0, oldPositional.length].concat(oldPositional));
positional.splice.apply(positional, [0, slicedPositionalArgs.length].concat(slicedPositionalArgs));
// Merge named maps
var named = (0, _emberUtils.assign)({}, oldNamed, positionalToNamedParams, newArgs.named.map);
return { positional: positional, named: named };
}
});
enifed('ember-glimmer/helpers/concat', ['exports', '@glimmer/runtime', 'ember-glimmer/utils/references'], function (exports, _runtime, _references) {
'use strict';
exports.default = function (_vm, args) {
return new _references.InternalHelperReference(concat, args.capture());
};
/**
@module ember
*/
/**
Concatenates the given arguments into a string.
Example:
```handlebars
{{some-component name=(concat firstName " " lastName)}}
{{! would pass name="<first name value> <last name value>" to the component}}
```
@public
@method concat
@for Ember.Templates.helpers
@since 1.13.0
*/
function concat(_ref) {
var positional = _ref.positional;
return positional.value().map(_runtime.normalizeTextValue).join('');
}
});
enifed('ember-glimmer/helpers/each-in', ['exports', 'ember-utils'], function (exports, _emberUtils) {
'use strict';
exports.isEachIn = isEachIn;
exports.default = function (_vm, args) {
var ref = Object.create(args.positional.at(0));
ref[EACH_IN_REFERENCE] = true;
return ref;
};
/**
The `{{#each}}` helper loops over elements in a collection. It is an extension
of the base Handlebars `{{#each}}` helper.
The default behavior of `{{#each}}` is to yield its inner block once for every
item in an array passing the item as the first block parameter.
```javascript
var developers = [{ name: 'Yehuda' },{ name: 'Tom' }, { name: 'Paul' }];
```
```handlebars
{{#each developers key="name" as |person|}}
{{person.name}}
{{! `this` is whatever it was outside the #each }}
{{/each}}
```
The same rules apply to arrays of primitives.
```javascript
var developerNames = ['Yehuda', 'Tom', 'Paul']
```
```handlebars
{{#each developerNames key="@index" as |name|}}
{{name}}
{{/each}}
```
During iteration, the index of each item in the array is provided as a second block parameter.
```handlebars
<ul>
{{#each people as |person index|}}
<li>Hello, {{person.name}}! You're number {{index}} in line</li>
{{/each}}
</ul>
```
### Specifying Keys
The `key` option is used to tell Ember how to determine if the array being
iterated over with `{{#each}}` has changed between renders. By helping Ember
detect that some elements in the array are the same, DOM elements can be
re-used, significantly improving rendering speed.
For example, here's the `{{#each}}` helper with its `key` set to `id`:
```handlebars
{{#each model key="id" as |item|}}
{{/each}}
```
When this `{{#each}}` re-renders, Ember will match up the previously rendered
items (and reorder the generated DOM elements) based on each item's `id`
property.
By default the item's own reference is used.
### {{else}} condition
`{{#each}}` can have a matching `{{else}}`. The contents of this block will render
if the collection is empty.
```handlebars
{{#each developers as |person|}}
{{person.name}}
{{else}}
<p>Sorry, nobody is available for this task.</p>
{{/each}}
```
@method each
@for Ember.Templates.helpers
@public
*/
/**
The `{{each-in}}` helper loops over properties on an object.
For example, given a `user` object that looks like:
```javascript
{
"name": "Shelly Sails",
"age": 42
}
```
This template would display all properties on the `user`
object in a list:
```handlebars
<ul>
{{#each-in user as |key value|}}
<li>{{key}}: {{value}}</li>
{{/each-in}}
</ul>
```
Outputting their name and age.
@method each-in
@for Ember.Templates.helpers
@public
@since 2.1.0
*/
var EACH_IN_REFERENCE = (0, _emberUtils.symbol)('EACH_IN');
function isEachIn(ref) {
return ref && ref[EACH_IN_REFERENCE];
}
});
enifed('ember-glimmer/helpers/get', ['exports', 'ember-babel', '@glimmer/reference', '@glimmer/runtime', 'ember-metal', 'ember-glimmer/utils/references'], function (exports, _emberBabel, _reference, _runtime, _emberMetal, _references) {
'use strict';
exports.default = function (_vm, args) {
return GetHelperReference.create(args.positional.at(0), args.positional.at(1));
};
var GetHelperReference = function (_CachedReference) {
(0, _emberBabel.inherits)(GetHelperReference, _CachedReference);
GetHelperReference.create = function create(sourceReference, pathReference) {
if ((0, _reference.isConst)(pathReference)) {
var parts = pathReference.value().split('.');
return (0, _reference.referenceFromParts)(sourceReference, parts);
} else {
return new GetHelperReference(sourceReference, pathReference);
}
};
function GetHelperReference(sourceReference, pathReference) {
(0, _emberBabel.classCallCheck)(this, GetHelperReference);
var _this = (0, _emberBabel.possibleConstructorReturn)(this, _CachedReference.call(this));
_this.sourceReference = sourceReference;
_this.pathReference = pathReference;
_this.lastPath = null;
_this.innerReference = _runtime.NULL_REFERENCE;
var innerTag = _this.innerTag = _reference.UpdatableTag.create(_reference.CONSTANT_TAG);
_this.tag = (0, _reference.combine)([sourceReference.tag, pathReference.tag, innerTag]);
return _this;
}
GetHelperReference.prototype.compute = function compute() {
var lastPath = this.lastPath,
innerReference = this.innerReference,
innerTag = this.innerTag;
var path = this.lastPath = this.pathReference.value();
if (path !== lastPath) {
if (path !== undefined && path !== null && path !== '') {
var pathType = typeof path;
if (pathType === 'string') {
innerReference = (0, _reference.referenceFromParts)(this.sourceReference, path.split('.'));
} else if (pathType === 'number') {
innerReference = this.sourceReference.get('' + path);
}
innerTag.inner.update(innerReference.tag);
} else {
innerReference = _runtime.NULL_REFERENCE;
innerTag.inner.update(_reference.CONSTANT_TAG);
}
this.innerReference = innerReference;
}
return innerReference.value();
};
GetHelperReference.prototype[_references.UPDATE] = function (value) {
(0, _emberMetal.set)(this.sourceReference.value(), this.pathReference.value(), value);
};
return GetHelperReference;
}(_references.CachedReference);
});
enifed("ember-glimmer/helpers/hash", ["exports"], function (exports) {
"use strict";
exports.default = function (_vm, args) {
return args.named.capture();
};
});
enifed('ember-glimmer/helpers/if-unless', ['exports', 'ember-babel', '@glimmer/reference', 'ember-debug', 'ember-glimmer/utils/references'], function (exports, _emberBabel, _reference, _emberDebug, _references) {
'use strict';
exports.inlineIf = inlineIf;
exports.inlineUnless = inlineUnless;
var ConditionalHelperReference = function (_CachedReference) {
(0, _emberBabel.inherits)(ConditionalHelperReference, _CachedReference);
ConditionalHelperReference.create = function create(_condRef, truthyRef, falsyRef) {
var condRef = _references.ConditionalReference.create(_condRef);
if ((0, _reference.isConst)(condRef)) {
return condRef.value() ? truthyRef : falsyRef;
} else {
return new ConditionalHelperReference(condRef, truthyRef, falsyRef);
}
};
function ConditionalHelperReference(cond, truthy, falsy) {
(0, _emberBabel.classCallCheck)(this, ConditionalHelperReference);
var _this = (0, _emberBabel.possibleConstructorReturn)(this, _CachedReference.call(this));
_this.branchTag = _reference.UpdatableTag.create(_reference.CONSTANT_TAG);
_this.tag = (0, _reference.combine)([cond.tag, _this.branchTag]);
_this.cond = cond;
_this.truthy = truthy;
_this.falsy = falsy;
return _this;
}
ConditionalHelperReference.prototype.compute = function compute() {
var branch = this.cond.value() ? this.truthy : this.falsy;
this.branchTag.inner.update(branch.tag);
return branch.value();
};
return ConditionalHelperReference;
}(_references.CachedReference);
/**
The `if` helper allows you to conditionally render one of two branches,
depending on the "truthiness" of a property.
For example the following values are all falsey: `false`, `undefined`, `null`, `""`, `0`, `NaN` or an empty array.
This helper has two forms, block and inline.
## Block form
You can use the block form of `if` to conditionally render a section of the template.
To use it, pass the conditional value to the `if` helper,
using the block form to wrap the section of template you want to conditionally render.
Like so:
```handlebars
{{! will not render if foo is falsey}}
{{#if foo}}
Welcome to the {{foo.bar}}
{{/if}}
```
You can also specify a template to show if the property is falsey by using
the `else` helper.
```handlebars
{{! is it raining outside?}}
{{#if isRaining}}
Yes, grab an umbrella!
{{else}}
No, it's lovely outside!
{{/if}}
```
You are also able to combine `else` and `if` helpers to create more complex
conditional logic.
```handlebars
{{#if isMorning}}
Good morning
{{else if isAfternoon}}
Good afternoon
{{else}}
Good night
{{/if}}
```
## Inline form
The inline `if` helper conditionally renders a single property or string.
In this form, the `if` helper receives three arguments, the conditional value,
the value to render when truthy, and the value to render when falsey.
For example, if `useLongGreeting` is truthy, the following:
```handlebars
{{if useLongGreeting "Hello" "Hi"}} Alex
```
Will render:
```html
Hello Alex
```
### Nested `if`
You can use the `if` helper inside another helper as a nested helper:
```handlebars
{{some-component height=(if isBig "100" "10")}}
```
One detail to keep in mind is that both branches of the `if` helper will be evaluated,
so if you have `{{if condition "foo" (expensive-operation "bar")`,
`expensive-operation` will always calculate.
@method if
@for Ember.Templates.helpers
@public
*/
function inlineIf(_vm, _ref) {
var positional = _ref.positional;
(true && !(positional.length === 3 || positional.length === 2) && (0, _emberDebug.assert)('The inline form of the `if` helper expects two or three arguments, e.g. ' + '`{{if trialExpired "Expired" expiryDate}}`.', positional.length === 3 || positional.length === 2));
return ConditionalHelperReference.create(positional.at(0), positional.at(1), positional.at(2));
}
/**
The inline `unless` helper conditionally renders a single property or string.
This helper acts like a ternary operator. If the first property is falsy,
the second argument will be displayed, otherwise, the third argument will be
displayed
```handlebars
{{unless useLongGreeting "Hi" "Hello"}} Ben
```
You can use the `unless` helper inside another helper as a subexpression.
```handlebars
{{some-component height=(unless isBig "10" "100")}}
```
@method unless
@for Ember.Templates.helpers
@public
*/
function inlineUnless(_vm, _ref2) {
var positional = _ref2.positional;
(true && !(positional.length === 3 || positional.length === 2) && (0, _emberDebug.assert)('The inline form of the `unless` helper expects two or three arguments, e.g. ' + '`{{unless isFirstLogin "Welcome back!"}}`.', positional.length === 3 || positional.length === 2));
return ConditionalHelperReference.create(positional.at(0), positional.at(2), positional.at(1));
}
});
enifed('ember-glimmer/helpers/loc', ['exports', 'ember-glimmer/helper', 'ember-runtime'], function (exports, _helper, _emberRuntime) {
'use strict';
exports.default = (0, _helper.helper)(function (params) {
return _emberRuntime.String.loc.apply(null, params);
});
});
enifed('ember-glimmer/helpers/log', ['exports', 'ember-glimmer/utils/references', 'ember-console'], function (exports, _references, _emberConsole) {
'use strict';
exports.default = function (_vm, args) {
return new _references.InternalHelperReference(log, args.capture());
};
/**
`log` allows you to output the value of variables in the current rendering
context. `log` also accepts primitive types such as strings or numbers.
```handlebars
{{log "myVariable:" myVariable }}
```
@method log
@for Ember.Templates.helpers
@param {Array} params
@public
*/
function log(_ref) {
var positional = _ref.positional;
_emberConsole.default.log.apply(null, positional.value());
}
/**
@module ember
*/
});
enifed('ember-glimmer/helpers/mut', ['exports', 'ember-debug', 'ember-utils', 'ember-glimmer/utils/references', 'ember-glimmer/helpers/action'], function (exports, _emberDebug, _emberUtils, _references, _action) {
'use strict';
exports.isMut = isMut;
exports.unMut = unMut;
exports.default = function (_vm, args) {
var rawRef = args.positional.at(0);
if (isMut(rawRef)) {
return rawRef;
}
// TODO: Improve this error message. This covers at least two distinct
// cases:
//
// 1. (mut "not a path") – passing a literal, result from a helper
// invocation, etc
//
// 2. (mut receivedValue) – passing a value received from the caller
// that was originally derived from a literal, result from a helper
// invocation, etc
//
// This message is alright for the first case, but could be quite
// confusing for the second case.
(true && !(rawRef[_references.UPDATE]) && (0, _emberDebug.assert)('You can only pass a path to mut', rawRef[_references.UPDATE]));
var wrappedRef = Object.create(rawRef);
wrappedRef[SOURCE] = rawRef;
wrappedRef[_action.INVOKE] = rawRef[_references.UPDATE];
wrappedRef[MUT_REFERENCE] = true;
return wrappedRef;
};
/**
The `mut` helper lets you __clearly specify__ that a child `Component` can update the
(mutable) value passed to it, which will __change the value of the parent component__.
To specify that a parameter is mutable, when invoking the child `Component`:
```handlebars
{{my-child childClickCount=(mut totalClicks)}}
```
The child `Component` can then modify the parent's value just by modifying its own
property:
```javascript
// my-child.js
export default Component.extend({
click() {
this.incrementProperty('childClickCount');
}
});
```
Note that for curly components (`{{my-component}}`) the bindings are already mutable,
making the `mut` unnecessary.
Additionally, the `mut` helper can be combined with the `action` helper to
mutate a value. For example:
```handlebars
{{my-child childClickCount=totalClicks click-count-change=(action (mut totalClicks))}}
```
The child `Component` would invoke the action with the new click value:
```javascript
// my-child.js
export default Component.extend({
click() {
this.get('click-count-change')(this.get('childClickCount') + 1);
}
});
```
The `mut` helper changes the `totalClicks` value to what was provided as the action argument.
The `mut` helper, when used with `action`, will return a function that
sets the value passed to `mut` to its first argument. This works like any other
closure action and interacts with the other features `action` provides.
As an example, we can create a button that increments a value passing the value
directly to the `action`:
```handlebars
{{! inc helper is not provided by Ember }}
<button onclick={{action (mut count) (inc count)}}>
Increment count
</button>
```
You can also use the `value` option:
```handlebars
<input value={{name}} oninput={{action (mut name) value="target.value"}}>
```
@method mut
@param {Object} [attr] the "two-way" attribute that can be modified.
@for Ember.Templates.helpers
@public
*/
var MUT_REFERENCE = (0, _emberUtils.symbol)('MUT');
var SOURCE = (0, _emberUtils.symbol)('SOURCE');
function isMut(ref) {
return ref && ref[MUT_REFERENCE];
}
function unMut(ref) {
return ref[SOURCE] || ref;
}
});
enifed('ember-glimmer/helpers/query-param', ['exports', 'ember-debug', 'ember-routing', 'ember-utils', 'ember-glimmer/utils/references'], function (exports, _emberDebug, _emberRouting, _emberUtils, _references) {
'use strict';
exports.default = function (_vm, args) {
return new _references.InternalHelperReference(queryParams, args.capture());
};
/**
This is a helper to be used in conjunction with the link-to helper.
It will supply url query parameters to the target route.
Example
```handlebars
{{#link-to 'posts' (query-params direction="asc")}}Sort{{/link-to}}
```
@method query-params
@for Ember.Templates.helpers
@param {Object} hash takes a hash of query parameters
@return {Object} A `QueryParams` object for `{{link-to}}`
@public
*/
function queryParams(_ref) {
var positional = _ref.positional,
named = _ref.named;
(true && !(positional.value().length === 0) && (0, _emberDebug.assert)('The `query-params` helper only accepts hash parameters, e.g. (query-params queryParamPropertyName=\'foo\') as opposed to just (query-params \'foo\')', positional.value().length === 0));
return _emberRouting.QueryParams.create({
values: (0, _emberUtils.assign)({}, named.value())
});
}
});
enifed('ember-glimmer/helpers/readonly', ['exports', 'ember-glimmer/utils/references', 'ember-glimmer/helpers/mut'], function (exports, _references, _mut) {
'use strict';
exports.default = function (_vm, args) {
var ref = (0, _mut.unMut)(args.positional.at(0));
var wrapped = Object.create(ref);
wrapped[_references.UPDATE] = undefined;
return wrapped;
};
});
enifed('ember-glimmer/helpers/unbound', ['exports', 'ember-debug', 'ember-glimmer/utils/references'], function (exports, _emberDebug, _references) {
'use strict';
exports.default = function (_vm, args) {
(true && !(args.positional.length === 1 && args.named.length === 0) && (0, _emberDebug.assert)('unbound helper cannot be called with multiple params or hash params', args.positional.length === 1 && args.named.length === 0));
return _references.UnboundReference.create(args.positional.at(0).value());
};
});
enifed('ember-glimmer/index', ['exports', 'ember-glimmer/helpers/action', 'ember-glimmer/templates/root', 'ember-glimmer/template', 'ember-glimmer/components/checkbox', 'ember-glimmer/components/text_field', 'ember-glimmer/components/text_area', 'ember-glimmer/components/link-to', 'ember-glimmer/component', 'ember-glimmer/helper', 'ember-glimmer/environment', 'ember-glimmer/utils/string', 'ember-glimmer/renderer', 'ember-glimmer/template_registry', 'ember-glimmer/setup-registry', 'ember-glimmer/dom', 'ember-glimmer/syntax', 'ember-glimmer/component-managers/abstract'], function (exports, _action, _root, _template, _checkbox, _text_field, _text_area, _linkTo, _component, _helper, _environment, _string, _renderer, _template_registry, _setupRegistry, _dom, _syntax, _abstract) {
'use strict';
Object.defineProperty(exports, 'INVOKE', {
enumerable: true,
get: function () {
return _action.INVOKE;
}
});
Object.defineProperty(exports, 'RootTemplate', {
enumerable: true,
get: function () {
return _root.default;
}
});
Object.defineProperty(exports, 'template', {
enumerable: true,
get: function () {
return _template.default;
}
});
Object.defineProperty(exports, 'Checkbox', {
enumerable: true,
get: function () {
return _checkbox.default;
}
});
Object.defineProperty(exports, 'TextField', {
enumerable: true,
get: function () {
return _text_field.default;
}
});
Object.defineProperty(exports, 'TextArea', {
enumerable: true,
get: function () {
return _text_area.default;
}
});
Object.defineProperty(exports, 'LinkComponent', {
enumerable: true,
get: function () {
return _linkTo.default;
}
});
Object.defineProperty(exports, 'Component', {
enumerable: true,
get: function () {
return _component.default;
}
});
Object.defineProperty(exports, 'Helper', {
enumerable: true,
get: function () {
return _helper.default;
}
});
Object.defineProperty(exports, 'helper', {
enumerable: true,
get: function () {
return _helper.helper;
}
});
Object.defineProperty(exports, 'Environment', {
enumerable: true,
get: function () {
return _environment.default;
}
});
Object.defineProperty(exports, 'SafeString', {
enumerable: true,
get: function () {
return _string.SafeString;
}
});
Object.defineProperty(exports, 'escapeExpression', {
enumerable: true,
get: function () {
return _string.escapeExpression;
}
});
Object.defineProperty(exports, 'htmlSafe', {
enumerable: true,
get: function () {
return _string.htmlSafe;
}
});
Object.defineProperty(exports, 'isHTMLSafe', {
enumerable: true,
get: function () {
return _string.isHTMLSafe;
}
});
Object.defineProperty(exports, '_getSafeString', {
enumerable: true,
get: function () {
return _string.getSafeString;
}
});
Object.defineProperty(exports, 'Renderer', {
enumerable: true,
get: function () {
return _renderer.Renderer;
}
});
Object.defineProperty(exports, 'InertRenderer', {
enumerable: true,
get: function () {
return _renderer.InertRenderer;
}
});
Object.defineProperty(exports, 'InteractiveRenderer', {
enumerable: true,
get: function () {
return _renderer.InteractiveRenderer;
}
});
Object.defineProperty(exports, '_resetRenderers', {
enumerable: true,
get: function () {
return _renderer._resetRenderers;
}
});
Object.defineProperty(exports, 'getTemplate', {
enumerable: true,
get: function () {
return _template_registry.getTemplate;
}
});
Object.defineProperty(exports, 'setTemplate', {
enumerable: true,
get: function () {
return _template_registry.setTemplate;
}
});
Object.defineProperty(exports, 'hasTemplate', {
enumerable: true,
get: function () {
return _template_registry.hasTemplate;
}
});
Object.defineProperty(exports, 'getTemplates', {
enumerable: true,
get: function () {
return _template_registry.getTemplates;
}
});
Object.defineProperty(exports, 'setTemplates', {
enumerable: true,
get: function () {
return _template_registry.setTemplates;
}
});
Object.defineProperty(exports, 'setupEngineRegistry', {
enumerable: true,
get: function () {
return _setupRegistry.setupEngineRegistry;
}
});
Object.defineProperty(exports, 'setupApplicationRegistry', {
enumerable: true,
get: function () {
return _setupRegistry.setupApplicationRegistry;
}
});
Object.defineProperty(exports, 'DOMChanges', {
enumerable: true,
get: function () {
return _dom.DOMChanges;
}
});
Object.defineProperty(exports, 'NodeDOMTreeConstruction', {
enumerable: true,
get: function () {
return _dom.NodeDOMTreeConstruction;
}
});
Object.defineProperty(exports, 'DOMTreeConstruction', {
enumerable: true,
get: function () {
return _dom.DOMTreeConstruction;
}
});
Object.defineProperty(exports, '_registerMacros', {
enumerable: true,
get: function () {
return _syntax.registerMacros;
}
});
Object.defineProperty(exports, '_experimentalMacros', {
enumerable: true,
get: function () {
return _syntax.experimentalMacros;
}
});
Object.defineProperty(exports, 'AbstractComponentManager', {
enumerable: true,
get: function () {
return _abstract.default;
}
});
});
enifed('ember-glimmer/modifiers/action', ['exports', 'ember-babel', 'ember-debug', 'ember-metal', 'ember-utils', 'ember-views', 'ember-glimmer/helpers/action'], function (exports, _emberBabel, _emberDebug, _emberMetal, _emberUtils, _emberViews, _action) {
'use strict';
exports.ActionState = exports.ActionHelper = undefined;
var MODIFIERS = ['alt', 'shift', 'meta', 'ctrl'];
var POINTER_EVENT_TYPE_REGEX = /^click|mouse|touch/;
function isAllowedEvent(event, allowedKeys) {
if (allowedKeys === null || allowedKeys === undefined) {
if (POINTER_EVENT_TYPE_REGEX.test(event.type)) {
return (0, _emberViews.isSimpleClick)(event);
} else {
allowedKeys = '';
}
}
if (allowedKeys.indexOf('any') >= 0) {
return true;
}
for (var i = 0; i < MODIFIERS.length; i++) {
if (event[MODIFIERS[i] + 'Key'] && allowedKeys.indexOf(MODIFIERS[i]) === -1) {
return false;
}
}
return true;
}
var ActionHelper = exports.ActionHelper = {
// registeredActions is re-exported for compatibility with older plugins
// that were using this undocumented API.
registeredActions: _emberViews.ActionManager.registeredActions,
registerAction: function (actionState) {
var actionId = actionState.actionId;
_emberViews.ActionManager.registeredActions[actionId] = actionState;
return actionId;
},
unregisterAction: function (actionState) {
var actionId = actionState.actionId;
delete _emberViews.ActionManager.registeredActions[actionId];
}
};
var ActionState = exports.ActionState = function () {
function ActionState(element, actionId, actionName, actionArgs, namedArgs, positionalArgs, implicitTarget, dom) {
(0, _emberBabel.classCallCheck)(this, ActionState);
this.element = element;
this.actionId = actionId;
this.actionName = actionName;
this.actionArgs = actionArgs;
this.namedArgs = namedArgs;
this.positional = positionalArgs;
this.implicitTarget = implicitTarget;
this.dom = dom;
this.eventName = this.getEventName();
}
ActionState.prototype.getEventName = function getEventName() {
return this.namedArgs.get('on').value() || 'click';
};
ActionState.prototype.getActionArgs = function getActionArgs() {
var result = new Array(this.actionArgs.length);
for (var i = 0; i < this.actionArgs.length; i++) {
result[i] = this.actionArgs[i].value();
}
return result;
};
ActionState.prototype.getTarget = function getTarget() {
var implicitTarget = this.implicitTarget,
namedArgs = this.namedArgs;
var target = void 0;
if (namedArgs.has('target')) {
target = namedArgs.get('target').value();
} else {
target = implicitTarget.value();
}
return target;
};
ActionState.prototype.handler = function handler(event) {
var _this = this;
var actionName = this.actionName,
namedArgs = this.namedArgs;
var bubbles = namedArgs.get('bubbles');
var preventDefault = namedArgs.get('preventDefault');
var allowedKeys = namedArgs.get('allowedKeys');
var target = this.getTarget();
if (!isAllowedEvent(event, allowedKeys.value())) {
return true;
}
if (preventDefault.value() !== false) {
event.preventDefault();
}
if (bubbles.value() === false) {
event.stopPropagation();
}
(0, _emberMetal.run)(function () {
var args = _this.getActionArgs();
var payload = {
args: args,
target: target,
name: null
};
if (typeof actionName[_action.INVOKE] === 'function') {
(0, _emberMetal.flaggedInstrument)('interaction.ember-action', payload, function () {
actionName[_action.INVOKE].apply(actionName, args);
});
return;
}
if (typeof actionName === 'function') {
(0, _emberMetal.flaggedInstrument)('interaction.ember-action', payload, function () {
actionName.apply(target, args);
});
return;
}
payload.name = actionName;
if (target.send) {
(0, _emberMetal.flaggedInstrument)('interaction.ember-action', payload, function () {
target.send.apply(target, [actionName].concat(args));
});
} else {
(true && !(typeof target[actionName] === 'function') && (0, _emberDebug.assert)('The action \'' + actionName + '\' did not exist on ' + target, typeof target[actionName] === 'function'));
(0, _emberMetal.flaggedInstrument)('interaction.ember-action', payload, function () {
target[actionName].apply(target, args);
});
}
});
return false;
};
ActionState.prototype.destroy = function destroy() {
ActionHelper.unregisterAction(this);
};
return ActionState;
}();
var ActionModifierManager = function () {
function ActionModifierManager() {
(0, _emberBabel.classCallCheck)(this, ActionModifierManager);
}
ActionModifierManager.prototype.create = function create(element, args, _dynamicScope, dom) {
var _args$capture = args.capture(),
named = _args$capture.named,
positional = _args$capture.positional;
var implicitTarget = void 0;
var actionName = void 0;
var actionNameRef = void 0;
if (positional.length > 1) {
implicitTarget = positional.at(0);
actionNameRef = positional.at(1);
if (actionNameRef[_action.INVOKE]) {
actionName = actionNameRef;
} else {
var actionLabel = actionNameRef._propertyKey;
actionName = actionNameRef.value();
(true && !(typeof actionName === 'string' || typeof actionName === 'function') && (0, _emberDebug.assert)('You specified a quoteless path, `' + actionLabel + '`, to the ' + '{{action}} helper which did not resolve to an action name (a ' + 'string). Perhaps you meant to use a quoted actionName? (e.g. ' + '{{action "' + actionLabel + '"}}).', typeof actionName === 'string' || typeof actionName === 'function'));
}
}
var actionArgs = [];
// The first two arguments are (1) `this` and (2) the action name.
// Everything else is a param.
for (var i = 2; i < positional.length; i++) {
actionArgs.push(positional.at(i));
}
var actionId = (0, _emberUtils.uuid)();
return new ActionState(element, actionId, actionName, actionArgs, named, positional, implicitTarget, dom);
};
ActionModifierManager.prototype.install = function install(actionState) {
var dom = actionState.dom,
element = actionState.element,
actionId = actionState.actionId;
ActionHelper.registerAction(actionState);
dom.setAttribute(element, 'data-ember-action', '');
dom.setAttribute(element, 'data-ember-action-' + actionId, actionId);
};
ActionModifierManager.prototype.update = function update(actionState) {
var positional = actionState.positional;
var actionNameRef = positional.at(1);
if (!actionNameRef[_action.INVOKE]) {
actionState.actionName = actionNameRef.value();
}
actionState.eventName = actionState.getEventName();
};
ActionModifierManager.prototype.getDestructor = function getDestructor(modifier) {
return modifier;
};
return ActionModifierManager;
}();
exports.default = ActionModifierManager;
});
enifed('ember-glimmer/protocol-for-url', ['exports', 'ember-environment', 'node-module'], function (exports, _emberEnvironment, _nodeModule) {
'use strict';
exports.default = installProtocolForURL;
/* globals module, URL */
var nodeURL = void 0;
var parsingNode = void 0;
function installProtocolForURL(environment) {
var protocol = void 0;
if (_emberEnvironment.environment.hasDOM) {
protocol = browserProtocolForURL.call(environment, 'foobar:baz');
}
// Test to see if our DOM implementation parses
// and normalizes URLs.
if (protocol === 'foobar:') {
// Swap in the method that doesn't do this test now that
// we know it works.
environment.protocolForURL = browserProtocolForURL;
} else if (typeof URL === 'object') {
// URL globally provided, likely from FastBoot's sandbox
nodeURL = URL;
environment.protocolForURL = nodeProtocolForURL;
} else if (_nodeModule.IS_NODE) {
// Otherwise, we need to fall back to our own URL parsing.
// Global `require` is shadowed by Ember's loader so we have to use the fully
// qualified `module.require`.
// tslint:disable-next-line:no-require-imports
nodeURL = (0, _nodeModule.require)('url');
environment.protocolForURL = nodeProtocolForURL;
} else {
throw new Error('Could not find valid URL parsing mechanism for URL Sanitization');
}
}
function browserProtocolForURL(url) {
if (!parsingNode) {
parsingNode = document.createElement('a');
}
parsingNode.href = url;
return parsingNode.protocol;
}
function nodeProtocolForURL(url) {
var protocol = null;
if (typeof url === 'string') {
protocol = nodeURL.parse(url).protocol;
}
return protocol === null ? ':' : protocol;
}
});
enifed('ember-glimmer/renderer', ['exports', 'ember-babel', '@glimmer/reference', 'ember-debug', 'ember-metal', 'ember-views', 'ember-glimmer/component', 'ember-glimmer/component-managers/outlet', 'ember-glimmer/component-managers/root', 'ember-glimmer/utils/references', '@glimmer/runtime'], function (exports, _emberBabel, _reference, _emberDebug, _emberMetal, _emberViews, _component, _outlet, _root2, _references, _runtime) {
'use strict';
exports.InteractiveRenderer = exports.InertRenderer = exports.Renderer = exports.DynamicScope = undefined;
exports._resetRenderers = _resetRenderers;
var backburner = _emberMetal.run.backburner;
var DynamicScope = exports.DynamicScope = function () {
function DynamicScope(view, outletState, rootOutletState) {
(0, _emberBabel.classCallCheck)(this, DynamicScope);
this.view = view;
this.outletState = outletState;
this.rootOutletState = rootOutletState;
}
DynamicScope.prototype.child = function child() {
return new DynamicScope(this.view, this.outletState, this.rootOutletState);
};
DynamicScope.prototype.get = function get(key) {
// tslint:disable-next-line:max-line-length
(true && !(key === 'outletState') && (0, _emberDebug.assert)('Using `-get-dynamic-scope` is only supported for `outletState` (you used `' + key + '`).', key === 'outletState'));
return this.outletState;
};
DynamicScope.prototype.set = function set(key, value) {
// tslint:disable-next-line:max-line-length
(true && !(key === 'outletState') && (0, _emberDebug.assert)('Using `-with-dynamic-scope` is only supported for `outletState` (you used `' + key + '`).', key === 'outletState'));
this.outletState = value;
return value;
};
return DynamicScope;
}();
var RootState = function () {
function RootState(root, env, template, self, parentElement, dynamicScope) {
var _this = this;
(0, _emberBabel.classCallCheck)(this, RootState);
(true && !(template !== undefined) && (0, _emberDebug.assert)('You cannot render `' + self.value() + '` without a template.', template !== undefined));
this.id = (0, _emberViews.getViewId)(root);
this.env = env;
this.root = root;
this.result = undefined;
this.shouldReflush = false;
this.destroyed = false;
this._removing = false;
var options = this.options = {
alwaysRevalidate: false
};
this.render = function () {
var iterator = template.render(self, parentElement, dynamicScope);
var iteratorResult = void 0;
do {
iteratorResult = iterator.next();
} while (!iteratorResult.done);
var result = _this.result = iteratorResult.value;
// override .render function after initial render
_this.render = function () {
return result.rerender(options);
};
};
}
RootState.prototype.isFor = function isFor(possibleRoot) {
return this.root === possibleRoot;
};
RootState.prototype.destroy = function destroy() {
var result = this.result,
env = this.env;
this.destroyed = true;
this.env = undefined;
this.root = null;
this.result = undefined;
this.render = undefined;
if (result) {
/*
Handles these scenarios:
* When roots are removed during standard rendering process, a transaction exists already
`.begin()` / `.commit()` are not needed.
* When roots are being destroyed manually (`component.append(); component.destroy() case), no
transaction exists already.
* When roots are being destroyed during `Renderer#destroy`, no transaction exists
*/
var needsTransaction = !env.inTransaction;
if (needsTransaction) {
env.begin();
}
result.destroy();
if (needsTransaction) {
env.commit();
}
}
};
return RootState;
}();
var renderers = [];
function _resetRenderers() {
renderers.length = 0;
}
(0, _emberMetal.setHasViews)(function () {
return renderers.length > 0;
});
function register(renderer) {
(true && !(renderers.indexOf(renderer) === -1) && (0, _emberDebug.assert)('Cannot register the same renderer twice', renderers.indexOf(renderer) === -1));
renderers.push(renderer);
}
function deregister(renderer) {
var index = renderers.indexOf(renderer);
(true && !(index !== -1) && (0, _emberDebug.assert)('Cannot deregister unknown unregistered renderer', index !== -1));
renderers.splice(index, 1);
}
function loopBegin() {
for (var i = 0; i < renderers.length; i++) {
renderers[i]._scheduleRevalidate();
}
}
function K() {}
var loops = 0;
function loopEnd() {
for (var i = 0; i < renderers.length; i++) {
if (!renderers[i]._isValid()) {
if (loops > 10) {
loops = 0;
// TODO: do something better
renderers[i].destroy();
throw new Error('infinite rendering invalidation detected');
}
loops++;
return backburner.join(null, K);
}
}
loops = 0;
}
backburner.on('begin', loopBegin);
backburner.on('end', loopEnd);
var Renderer = exports.Renderer = function () {
function Renderer(env, rootTemplate) {
var _viewRegistry = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _emberViews.fallbackViewRegistry;
var destinedForDOM = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
(0, _emberBabel.classCallCheck)(this, Renderer);
this._env = env;
this._rootTemplate = rootTemplate;
this._viewRegistry = _viewRegistry;
this._destinedForDOM = destinedForDOM;
this._destroyed = false;
this._roots = [];
this._lastRevision = -1;
this._isRenderingRoots = false;
this._removedRoots = [];
}
// renderer HOOKS
Renderer.prototype.appendOutletView = function appendOutletView(view, target) {
var definition = new _outlet.TopLevelOutletComponentDefinition(view);
var outletStateReference = view.toReference();
this._appendDefinition(view, definition, target, outletStateReference);
};
Renderer.prototype.appendTo = function appendTo(view, target) {
var rootDef = new _root2.RootComponentDefinition(view);
this._appendDefinition(view, rootDef, target);
};
Renderer.prototype._appendDefinition = function _appendDefinition(root, definition, target, outletStateReference) {
var self = new _references.RootReference(definition);
var dynamicScope = new DynamicScope(null, outletStateReference || _runtime.NULL_REFERENCE, outletStateReference);
var rootState = new RootState(root, this._env, this._rootTemplate, self, target, dynamicScope);
this._renderRoot(rootState);
};
Renderer.prototype.rerender = function rerender() {
this._scheduleRevalidate();
};
Renderer.prototype.register = function register(view) {
var id = (0, _emberViews.getViewId)(view);
(true && !(!this._viewRegistry[id]) && (0, _emberDebug.assert)('Attempted to register a view with an id already in use: ' + id, !this._viewRegistry[id]));
this._viewRegistry[id] = view;
};
Renderer.prototype.unregister = function unregister(view) {
delete this._viewRegistry[(0, _emberViews.getViewId)(view)];
};
Renderer.prototype.remove = function remove(view) {
view._transitionTo('destroying');
this.cleanupRootFor(view);
(0, _emberViews.setViewElement)(view, null);
if (this._destinedForDOM) {
view.trigger('didDestroyElement');
}
if (!view.isDestroying) {
view.destroy();
}
};
Renderer.prototype.cleanupRootFor = function cleanupRootFor(view) {
// no need to cleanup roots if we have already been destroyed
if (this._destroyed) {
return;
}
var roots = this._roots;
// traverse in reverse so we can remove items
// without mucking up the index
var i = this._roots.length;
while (i--) {
var root = roots[i];
if (root.isFor(view)) {
root.destroy();
roots.splice(i, 1);
}
}
};
Renderer.prototype.destroy = function destroy() {
if (this._destroyed) {
return;
}
this._destroyed = true;
this._clearAllRoots();
};
Renderer.prototype.getBounds = function getBounds(view) {
var bounds = view[_component.BOUNDS];
var parentElement = bounds.parentElement();
var firstNode = bounds.firstNode();
var lastNode = bounds.lastNode();
return { parentElement: parentElement, firstNode: firstNode, lastNode: lastNode };
};
Renderer.prototype.createElement = function createElement(tagName) {
return this._env.getAppendOperations().createElement(tagName);
};
Renderer.prototype._renderRoot = function _renderRoot(root) {
var roots = this._roots;
roots.push(root);
if (roots.length === 1) {
register(this);
}
this._renderRootsTransaction();
};
Renderer.prototype._renderRoots = function _renderRoots() {
var roots = this._roots,
env = this._env,
removedRoots = this._removedRoots;
var globalShouldReflush = void 0;
var initialRootsLength = void 0;
do {
env.begin();
// ensure that for the first iteration of the loop
// each root is processed
initialRootsLength = roots.length;
globalShouldReflush = false;
for (var i = 0; i < roots.length; i++) {
var root = roots[i];
if (root.destroyed) {
// add to the list of roots to be removed
// they will be removed from `this._roots` later
removedRoots.push(root);
// skip over roots that have been marked as destroyed
continue;
}
var shouldReflush = root.shouldReflush;
// when processing non-initial reflush loops,
// do not process more roots than needed
if (i >= initialRootsLength && !shouldReflush) {
continue;
}
root.options.alwaysRevalidate = shouldReflush;
// track shouldReflush based on this roots render result
shouldReflush = root.shouldReflush = (0, _emberMetal.runInTransaction)(root, 'render');
// globalShouldReflush should be `true` if *any* of
// the roots need to reflush
globalShouldReflush = globalShouldReflush || shouldReflush;
}
this._lastRevision = _reference.CURRENT_TAG.value();
env.commit();
} while (globalShouldReflush || roots.length > initialRootsLength);
// remove any roots that were destroyed during this transaction
while (removedRoots.length) {
var _root = removedRoots.pop();
var rootIndex = roots.indexOf(_root);
roots.splice(rootIndex, 1);
}
if (this._roots.length === 0) {
deregister(this);
}
};
Renderer.prototype._renderRootsTransaction = function _renderRootsTransaction() {
if (this._isRenderingRoots) {
// currently rendering roots, a new root was added and will
// be processed by the existing _renderRoots invocation
return;
}
// used to prevent calling _renderRoots again (see above)
// while we are actively rendering roots
this._isRenderingRoots = true;
var completedWithoutError = false;
try {
this._renderRoots();
completedWithoutError = true;
} finally {
if (!completedWithoutError) {
this._lastRevision = _reference.CURRENT_TAG.value();
}
this._isRenderingRoots = false;
}
};
Renderer.prototype._clearAllRoots = function _clearAllRoots() {
var roots = this._roots;
for (var i = 0; i < roots.length; i++) {
var root = roots[i];
root.destroy();
}
this._removedRoots.length = 0;
this._roots = [];
// if roots were present before destroying
// deregister this renderer instance
if (roots.length) {
deregister(this);
}
};
Renderer.prototype._scheduleRevalidate = function _scheduleRevalidate() {
backburner.scheduleOnce('render', this, this._revalidate);
};
Renderer.prototype._isValid = function _isValid() {
return this._destroyed || this._roots.length === 0 || _reference.CURRENT_TAG.validate(this._lastRevision);
};
Renderer.prototype._revalidate = function _revalidate() {
if (this._isValid()) {
return;
}
this._renderRootsTransaction();
};
return Renderer;
}();
var InertRenderer = exports.InertRenderer = function (_Renderer) {
(0, _emberBabel.inherits)(InertRenderer, _Renderer);
function InertRenderer() {
(0, _emberBabel.classCallCheck)(this, InertRenderer);
return (0, _emberBabel.possibleConstructorReturn)(this, _Renderer.apply(this, arguments));
}
InertRenderer.create = function create(_ref) {
var env = _ref.env,
rootTemplate = _ref.rootTemplate,
_viewRegistry = _ref._viewRegistry;
return new this(env, rootTemplate, _viewRegistry, false);
};
InertRenderer.prototype.getElement = function getElement(_view) {
throw new Error('Accessing `this.element` is not allowed in non-interactive environments (such as FastBoot).');
};
return InertRenderer;
}(Renderer);
var InteractiveRenderer = exports.InteractiveRenderer = function (_Renderer2) {
(0, _emberBabel.inherits)(InteractiveRenderer, _Renderer2);
function InteractiveRenderer() {
(0, _emberBabel.classCallCheck)(this, InteractiveRenderer);
return (0, _emberBabel.possibleConstructorReturn)(this, _Renderer2.apply(this, arguments));
}
InteractiveRenderer.create = function create(_ref2) {
var env = _ref2.env,
rootTemplate = _ref2.rootTemplate,
_viewRegistry = _ref2._viewRegistry;
return new this(env, rootTemplate, _viewRegistry, true);
};
InteractiveRenderer.prototype.getElement = function getElement(view) {
return (0, _emberViews.getViewElement)(view);
};
return InteractiveRenderer;
}(Renderer);
});
enifed('ember-glimmer/setup-registry', ['exports', 'ember-babel', 'container', 'ember-environment', 'ember-glimmer/component', 'ember-glimmer/components/checkbox', 'ember-glimmer/components/link-to', 'ember-glimmer/components/text_area', 'ember-glimmer/components/text_field', 'ember-glimmer/dom', 'ember-glimmer/environment', 'ember-glimmer/renderer', 'ember-glimmer/templates/component', 'ember-glimmer/templates/outlet', 'ember-glimmer/templates/root', 'ember-glimmer/views/outlet', 'ember-glimmer/helpers/loc'], function (exports, _emberBabel, _container, _emberEnvironment, _component, _checkbox, _linkTo, _text_area, _text_field, _dom, _environment, _renderer, _component2, _outlet, _root, _outlet2, _loc) {
'use strict';
exports.setupApplicationRegistry = setupApplicationRegistry;
exports.setupEngineRegistry = setupEngineRegistry;
var _templateObject = (0, _emberBabel.taggedTemplateLiteralLoose)(['template:-root'], ['template:-root']),
_templateObject2 = (0, _emberBabel.taggedTemplateLiteralLoose)(['template:components/-default'], ['template:components/-default']),
_templateObject3 = (0, _emberBabel.taggedTemplateLiteralLoose)(['component:-default'], ['component:-default']);
function setupApplicationRegistry(registry) {
registry.injection('service:-glimmer-environment', 'appendOperations', 'service:-dom-tree-construction');
registry.injection('renderer', 'env', 'service:-glimmer-environment');
registry.register((0, _container.privatize)(_templateObject), _root.default);
registry.injection('renderer', 'rootTemplate', (0, _container.privatize)(_templateObject));
registry.register('renderer:-dom', _renderer.InteractiveRenderer);
registry.register('renderer:-inert', _renderer.InertRenderer);
if (_emberEnvironment.environment.hasDOM) {
registry.injection('service:-glimmer-environment', 'updateOperations', 'service:-dom-changes');
}
registry.register('service:-dom-changes', {
create: function (_ref) {
var document = _ref.document;
return new _dom.DOMChanges(document);
}
});
registry.register('service:-dom-tree-construction', {
create: function (_ref2) {
var document = _ref2.document;
var Implementation = _emberEnvironment.environment.hasDOM ? _dom.DOMTreeConstruction : _dom.NodeDOMTreeConstruction;
return new Implementation(document);
}
});
}
function setupEngineRegistry(registry) {
registry.register('view:-outlet', _outlet2.default);
registry.register('template:-outlet', _outlet.default);
registry.injection('view:-outlet', 'template', 'template:-outlet');
registry.injection('service:-dom-changes', 'document', 'service:-document');
registry.injection('service:-dom-tree-construction', 'document', 'service:-document');
registry.register((0, _container.privatize)(_templateObject2), _component2.default);
registry.register('service:-glimmer-environment', _environment.default);
registry.injection('template', 'env', 'service:-glimmer-environment');
registry.optionsForType('helper', { instantiate: false });
registry.register('helper:loc', _loc.default);
registry.register('component:-text-field', _text_field.default);
registry.register('component:-text-area', _text_area.default);
registry.register('component:-checkbox', _checkbox.default);
registry.register('component:link-to', _linkTo.default);
registry.register((0, _container.privatize)(_templateObject3), _component.default);
}
});
enifed('ember-glimmer/syntax', ['exports', 'ember-debug', 'ember-glimmer/syntax/-text-area', 'ember-glimmer/syntax/dynamic-component', 'ember-glimmer/syntax/input', 'ember-glimmer/syntax/mount', 'ember-glimmer/syntax/outlet', 'ember-glimmer/syntax/render', 'ember-glimmer/syntax/utils', 'ember-glimmer/utils/bindings'], function (exports, _emberDebug, _textArea, _dynamicComponent, _input, _mount, _outlet, _render, _utils, _bindings) {
'use strict';
exports.experimentalMacros = undefined;
exports.registerMacros = registerMacros;
exports.populateMacros = populateMacros;
function refineInlineSyntax(name, params, hash, builder) {
(true && !(!(builder.env.builtInHelpers[name] && builder.env.owner.hasRegistration('helper:' + name))) && (0, _emberDebug.assert)('You attempted to overwrite the built-in helper "' + name + '" which is not allowed. Please rename the helper.', !(builder.env.builtInHelpers[name] && builder.env.owner.hasRegistration('helper:' + name))));
var definition = void 0;
if (name.indexOf('-') > -1) {
definition = builder.env.getComponentDefinition(name, builder.meta.templateMeta);
}
if (definition) {
(0, _bindings.wrapComponentClassAttribute)(hash);
builder.component.static(definition, [params, (0, _utils.hashToArgs)(hash), null, null]);
return true;
}
return false;
}
function refineBlockSyntax(name, params, hash, _default, inverse, builder) {
if (name.indexOf('-') === -1) {
return false;
}
var meta = builder.meta.templateMeta;
var definition = void 0;
if (name.indexOf('-') > -1) {
definition = builder.env.getComponentDefinition(name, meta);
}
if (definition) {
(0, _bindings.wrapComponentClassAttribute)(hash);
builder.component.static(definition, [params, (0, _utils.hashToArgs)(hash), _default, inverse]);
return true;
}
(true && !(builder.env.hasHelper(name, meta)) && (0, _emberDebug.assert)('A component or helper named "' + name + '" could not be found', builder.env.hasHelper(name, meta)));
(true && !(!builder.env.hasHelper(name, meta)) && (0, _emberDebug.assert)('Helpers may not be used in the block form, for example {{#' + name + '}}{{/' + name + '}}. Please use a component, or alternatively use the helper in combination with a built-in Ember helper, for example {{#if (' + name + ')}}{{/if}}.', !builder.env.hasHelper(name, meta)));
return false;
}
var experimentalMacros = exports.experimentalMacros = [];
// This is a private API to allow for experimental macros
// to be created in user space. Registering a macro should
// should be done in an initializer.
function registerMacros(macro) {
experimentalMacros.push(macro);
}
function populateMacros(blocks, inlines) {
inlines.add('outlet', _outlet.outletMacro);
inlines.add('component', _dynamicComponent.inlineComponentMacro);
inlines.add('render', _render.renderMacro);
inlines.add('mount', _mount.mountMacro);
inlines.add('input', _input.inputMacro);
inlines.add('textarea', _textArea.textAreaMacro);
inlines.addMissing(refineInlineSyntax);
blocks.add('component', _dynamicComponent.blockComponentMacro);
blocks.addMissing(refineBlockSyntax);
for (var i = 0; i < experimentalMacros.length; i++) {
var macro = experimentalMacros[i];
macro(blocks, inlines);
}
return { blocks: blocks, inlines: inlines };
}
});
enifed('ember-glimmer/syntax/-text-area', ['exports', 'ember-glimmer/utils/bindings', 'ember-glimmer/syntax/utils'], function (exports, _bindings, _utils) {
'use strict';
exports.textAreaMacro = textAreaMacro;
function textAreaMacro(_name, params, hash, builder) {
var definition = builder.env.getComponentDefinition('-text-area', builder.meta.templateMeta);
(0, _bindings.wrapComponentClassAttribute)(hash);
builder.component.static(definition, [params, (0, _utils.hashToArgs)(hash), null, null]);
return true;
}
});
enifed('ember-glimmer/syntax/dynamic-component', ['exports', 'ember-babel', '@glimmer/runtime', 'ember-debug', 'ember-glimmer/syntax/utils'], function (exports, _emberBabel, _runtime, _emberDebug, _utils) {
'use strict';
exports.dynamicComponentMacro = dynamicComponentMacro;
exports.blockComponentMacro = blockComponentMacro;
exports.inlineComponentMacro = inlineComponentMacro;
function dynamicComponentFor(vm, args, meta) {
var env = vm.env;
var nameRef = args.positional.at(0);
return new DynamicComponentReference({ nameRef: nameRef, env: env, meta: meta, args: null });
}
function dynamicComponentMacro(params, hash, _default, _inverse, builder) {
var definitionArgs = [params.slice(0, 1), null, null, null];
var args = [params.slice(1), (0, _utils.hashToArgs)(hash), null, null];
builder.component.dynamic(definitionArgs, dynamicComponentFor, args);
return true;
}
function blockComponentMacro(params, hash, _default, inverse, builder) {
var definitionArgs = [params.slice(0, 1), null, null, null];
var args = [params.slice(1), (0, _utils.hashToArgs)(hash), _default, inverse];
builder.component.dynamic(definitionArgs, dynamicComponentFor, args);
return true;
}
function inlineComponentMacro(_name, params, hash, builder) {
var definitionArgs = [params.slice(0, 1), null, null, null];
var args = [params.slice(1), (0, _utils.hashToArgs)(hash), null, null];
builder.component.dynamic(definitionArgs, dynamicComponentFor, args);
return true;
}
var DynamicComponentReference = function () {
function DynamicComponentReference(_ref) {
var nameRef = _ref.nameRef,
env = _ref.env,
meta = _ref.meta,
args = _ref.args;
(0, _emberBabel.classCallCheck)(this, DynamicComponentReference);
this.tag = nameRef.tag;
this.nameRef = nameRef;
this.env = env;
this.meta = meta;
this.args = args;
}
DynamicComponentReference.prototype.value = function value() {
var env = this.env,
nameRef = this.nameRef,
meta = this.meta;
var nameOrDef = nameRef.value();
if (typeof nameOrDef === 'string') {
var definition = env.getComponentDefinition(nameOrDef, meta);
// tslint:disable-next-line:max-line-length
(true && !(!!definition) && (0, _emberDebug.assert)('Could not find component named "' + nameOrDef + '" (no component or template with that name was found)', !!definition));
return definition;
} else if ((0, _runtime.isComponentDefinition)(nameOrDef)) {
return nameOrDef;
} else {
return null;
}
};
DynamicComponentReference.prototype.get = function get() {};
return DynamicComponentReference;
}();
});
enifed('ember-glimmer/syntax/input', ['exports', 'ember-debug', 'ember-glimmer/utils/bindings', 'ember-glimmer/syntax/dynamic-component', 'ember-glimmer/syntax/utils'], function (exports, _emberDebug, _bindings, _dynamicComponent, _utils) {
'use strict';
exports.inputMacro = inputMacro;
/**
@module ember
*/
function buildSyntax(type, params, hash, builder) {
var definition = builder.env.getComponentDefinition(type, builder.meta.templateMeta);
builder.component.static(definition, [params, (0, _utils.hashToArgs)(hash), null, null]);
return true;
}
/**
The `{{input}}` helper lets you create an HTML `<input />` component.
It causes an `TextField` component to be rendered. For more info,
see the [TextField](/api/classes/Ember.TextField.html) docs and
the [templates guide](https://emberjs.com/guides/templates/input-helpers/).
```handlebars
{{input value="987"}}
```
renders as:
```HTML
<input type="text" value="987" />
```
### Text field
If no `type` option is specified, a default of type 'text' is used.
Many of the standard HTML attributes may be passed to this helper.
<table>
<tr><td>`readonly`</td><td>`required`</td><td>`autofocus`</td></tr>
<tr><td>`value`</td><td>`placeholder`</td><td>`disabled`</td></tr>
<tr><td>`size`</td><td>`tabindex`</td><td>`maxlength`</td></tr>
<tr><td>`name`</td><td>`min`</td><td>`max`</td></tr>
<tr><td>`pattern`</td><td>`accept`</td><td>`autocomplete`</td></tr>
<tr><td>`autosave`</td><td>`formaction`</td><td>`formenctype`</td></tr>
<tr><td>`formmethod`</td><td>`formnovalidate`</td><td>`formtarget`</td></tr>
<tr><td>`height`</td><td>`inputmode`</td><td>`multiple`</td></tr>
<tr><td>`step`</td><td>`width`</td><td>`form`</td></tr>
<tr><td>`selectionDirection`</td><td>`spellcheck`</td><td> </td></tr>
</table>
When set to a quoted string, these values will be directly applied to the HTML
element. When left unquoted, these values will be bound to a property on the
template's current rendering context (most typically a controller instance).
A very common use of this helper is to bind the `value` of an input to an Object's attribute:
```handlebars
Search:
{{input value=searchWord}}
```
In this example, the initial value in the `<input />` will be set to the value of `searchWord`.
If the user changes the text, the value of `searchWord` will also be updated.
### Actions
The helper can send multiple actions based on user events.
The action property defines the action which is sent when
the user presses the return key.
```handlebars
{{input action="submit"}}
```
The helper allows some user events to send actions.
* `enter`
* `insert-newline`
* `escape-press`
* `focus-in`
* `focus-out`
* `key-press`
* `key-up`
For example, if you desire an action to be sent when the input is blurred,
you only need to setup the action name to the event name property.
```handlebars
{{input focus-out="alertMessage"}}
```
See more about [Text Support Actions](/api/classes/Ember.TextField.html)
### Extending `TextField`
Internally, `{{input type="text"}}` creates an instance of `TextField`, passing
arguments from the helper to `TextField`'s `create` method. You can extend the
capabilities of text inputs in your applications by reopening this class. For example,
if you are building a Bootstrap project where `data-*` attributes are used, you
can add one to the `TextField`'s `attributeBindings` property:
```javascript
import TextField from '@ember/component/text-field';
TextField.reopen({
attributeBindings: ['data-error']
});
```
Keep in mind when writing `TextField` subclasses that `TextField`
itself extends `Component`. Expect isolated component semantics, not
legacy 1.x view semantics (like `controller` being present).
See more about [Ember components](/api/classes/Ember.Component.html)
### Checkbox
Checkboxes are special forms of the `{{input}}` helper. To create a `<checkbox />`:
```handlebars
Emberize Everything:
{{input type="checkbox" name="isEmberized" checked=isEmberized}}
```
This will bind checked state of this checkbox to the value of `isEmberized` -- if either one changes,
it will be reflected in the other.
The following HTML attributes can be set via the helper:
* `checked`
* `disabled`
* `tabindex`
* `indeterminate`
* `name`
* `autofocus`
* `form`
### Extending `Checkbox`
Internally, `{{input type="checkbox"}}` creates an instance of `Checkbox`, passing
arguments from the helper to `Checkbox`'s `create` method. You can extend the
capablilties of checkbox inputs in your applications by reopening this class. For example,
if you wanted to add a css class to all checkboxes in your application:
```javascript
import Checkbox from '@ember/component/checkbox';
Checkbox.reopen({
classNames: ['my-app-checkbox']
});
```
@method input
@for Ember.Templates.helpers
@param {Hash} options
@public
*/
function inputMacro(_name, params, hash, builder) {
var keys = void 0;
var values = void 0;
var typeIndex = -1;
var valueIndex = -1;
if (hash) {
keys = hash[0];
values = hash[1];
typeIndex = keys.indexOf('type');
valueIndex = keys.indexOf('value');
}
if (!params) {
params = [];
}
if (typeIndex > -1) {
var typeArg = values[typeIndex];
if (Array.isArray(typeArg)) {
return (0, _dynamicComponent.dynamicComponentMacro)(params, hash, null, null, builder);
} else if (typeArg === 'checkbox') {
(true && !(valueIndex === -1) && (0, _emberDebug.assert)('{{input type=\'checkbox\'}} does not support setting `value=someBooleanValue`; ' + 'you must use `checked=someBooleanValue` instead.', valueIndex === -1));
(0, _bindings.wrapComponentClassAttribute)(hash);
return buildSyntax('-checkbox', params, hash, builder);
}
}
return buildSyntax('-text-field', params, hash, builder);
}
});
enifed('ember-glimmer/syntax/mount', ['exports', 'ember-babel', 'ember-debug', 'ember/features', 'ember-glimmer/component-managers/mount', 'ember-glimmer/syntax/utils'], function (exports, _emberBabel, _emberDebug, _features, _mount, _utils) {
'use strict';
exports.mountMacro = mountMacro;
function dynamicEngineFor(vm, args, meta) {
var env = vm.env;
var nameRef = args.positional.at(0);
return new DynamicEngineReference({ nameRef: nameRef, env: env, meta: meta });
}
/**
The `{{mount}}` helper lets you embed a routeless engine in a template.
Mounting an engine will cause an instance to be booted and its `application`
template to be rendered.
For example, the following template mounts the `ember-chat` engine:
```handlebars
{{! application.hbs }}
{{mount "ember-chat"}}
```
Additionally, you can also pass in a `model` argument that will be
set as the engines model. This can be an existing object:
```
<div>
{{mount 'admin' model=userSettings}}
</div>
```
Or an inline `hash`, and you can even pass components:
```
<div>
<h1>Application template!</h1>
{{mount 'admin' model=(hash
title='Secret Admin'
signInButton=(component 'sign-in-button')
)}}
</div>
```
@method mount
@param {String} name Name of the engine to mount.
@param {Object} [model] Object that will be set as
the model of the engine.
@for Ember.Templates.helpers
@category ember-application-engines
@public
*/
function mountMacro(_name, params, hash, builder) {
if (_features.EMBER_ENGINES_MOUNT_PARAMS) {
(true && !(params.length === 1) && (0, _emberDebug.assert)('You can only pass a single positional argument to the {{mount}} helper, e.g. {{mount "chat-engine"}}.', params.length === 1));
} else {
(true && !(params.length === 1 && hash === null) && (0, _emberDebug.assert)('You can only pass a single argument to the {{mount}} helper, e.g. {{mount "chat-engine"}}.', params.length === 1 && hash === null));
}
var definitionArgs = [params.slice(0, 1), null, null, null];
var args = [null, (0, _utils.hashToArgs)(hash), null, null];
builder.component.dynamic(definitionArgs, dynamicEngineFor, args);
return true;
}
var DynamicEngineReference = function () {
function DynamicEngineReference(_ref) {
var nameRef = _ref.nameRef,
env = _ref.env,
meta = _ref.meta;
(0, _emberBabel.classCallCheck)(this, DynamicEngineReference);
this.tag = nameRef.tag;
this.nameRef = nameRef;
this.env = env;
this.meta = meta;
this._lastName = undefined;
this._lastDef = undefined;
}
DynamicEngineReference.prototype.value = function value() {
var env = this.env,
nameRef = this.nameRef;
var nameOrDef = nameRef.value();
if (typeof nameOrDef === 'string') {
if (this._lastName === nameOrDef) {
return this._lastDef;
}
(true && !(env.owner.hasRegistration('engine:' + nameOrDef)) && (0, _emberDebug.assert)('You used `{{mount \'' + nameOrDef + '\'}}`, but the engine \'' + nameOrDef + '\' can not be found.', env.owner.hasRegistration('engine:' + nameOrDef)));
if (!env.owner.hasRegistration('engine:' + nameOrDef)) {
return null;
}
this._lastName = nameOrDef;
this._lastDef = new _mount.MountDefinition(nameOrDef);
return this._lastDef;
} else {
(true && !(nameOrDef === null || nameOrDef === undefined) && (0, _emberDebug.assert)('Invalid engine name \'' + nameOrDef + '\' specified, engine name must be either a string, null or undefined.', nameOrDef === null || nameOrDef === undefined));
return null;
}
};
return DynamicEngineReference;
}();
});
enifed('ember-glimmer/syntax/outlet', ['exports', 'ember-babel', '@glimmer/reference', 'ember-glimmer/component-managers/outlet'], function (exports, _emberBabel, _reference, _outlet) {
'use strict';
exports.outletMacro = outletMacro;
var OutletComponentReference = function () {
function OutletComponentReference(outletNameRef, parentOutletStateRef) {
(0, _emberBabel.classCallCheck)(this, OutletComponentReference);
this.outletNameRef = outletNameRef;
this.parentOutletStateRef = parentOutletStateRef;
this.definition = null;
this.lastState = null;
var outletStateTag = this.outletStateTag = _reference.UpdatableTag.create(parentOutletStateRef.tag);
this.tag = (0, _reference.combine)([outletStateTag.inner, outletNameRef.tag]);
}
OutletComponentReference.prototype.value = function value() {
var outletNameRef = this.outletNameRef,
parentOutletStateRef = this.parentOutletStateRef,
definition = this.definition,
lastState = this.lastState;
var outletName = outletNameRef.value();
var outletStateRef = parentOutletStateRef.get('outlets').get(outletName);
var newState = this.lastState = outletStateRef.value();
this.outletStateTag.inner.update(outletStateRef.tag);
definition = revalidate(definition, lastState, newState);
var hasTemplate = newState && newState.render.template;
if (definition) {
return definition;
} else if (hasTemplate) {
return this.definition = new _outlet.OutletComponentDefinition(outletName, newState.render.template);
} else {
return this.definition = null;
}
};
return OutletComponentReference;
}();
function revalidate(definition, lastState, newState) {
if (!lastState && !newState) {
return definition;
}
if (!lastState && newState || lastState && !newState) {
return null;
}
if (newState.render.template === lastState.render.template && newState.render.controller === lastState.render.controller) {
return definition;
}
return null;
}
function outletComponentFor(vm, args) {
var _vm$dynamicScope = vm.dynamicScope(),
outletState = _vm$dynamicScope.outletState;
var outletNameRef = void 0;
if (args.positional.length === 0) {
outletNameRef = new _reference.ConstReference('main');
} else {
outletNameRef = args.positional.at(0);
}
return new OutletComponentReference(outletNameRef, outletState);
}
/**
The `{{outlet}}` helper lets you specify where a child route will render in
your template. An important use of the `{{outlet}}` helper is in your
application's `application.hbs` file:
```handlebars
{{! app/templates/application.hbs }}
<!-- header content goes here, and will always display -->
{{my-header}}
<div class="my-dynamic-content">
<!-- this content will change based on the current route, which depends on the current URL -->
{{outlet}}
</div>
<!-- footer content goes here, and will always display -->
{{my-footer}}
```
See [templates guide](https://emberjs.com/guides/templates/the-application-template/) for
additional information on using `{{outlet}}` in `application.hbs`.
You may also specify a name for the `{{outlet}}`, which is useful when using more than one
`{{outlet}}` in a template:
```handlebars
{{outlet "menu"}}
{{outlet "sidebar"}}
{{outlet "main"}}
```
Your routes can then render into a specific one of these `outlet`s by specifying the `outlet`
attribute in your `renderTemplate` function:
```app/routes/menu.js
import Route from '@ember/routing/route';
export default Route.extend({
renderTemplate() {
this.render({ outlet: 'menu' });
}
});
```
See the [routing guide](https://emberjs.com/guides/routing/rendering-a-template/) for more
information on how your `route` interacts with the `{{outlet}}` helper.
Note: Your content __will not render__ if there isn't an `{{outlet}}` for it.
@method outlet
@param {String} [name]
@for Ember.Templates.helpers
@public
*/
function outletMacro(_name, params, _hash, builder) {
if (!params) {
params = [];
}
var definitionArgs = [params.slice(0, 1), null, null, null];
var emptyArgs = [[], null, null, null]; // FIXME
builder.component.dynamic(definitionArgs, outletComponentFor, emptyArgs);
return true;
}
});
enifed('ember-glimmer/syntax/render', ['exports', '@glimmer/reference', 'ember-debug', 'ember-glimmer/component-managers/render', 'ember-glimmer/syntax/utils'], function (exports, _reference, _emberDebug, _render, _utils) {
'use strict';
exports.renderMacro = renderMacro;
/**
@module ember
*/
function makeComponentDefinition(vm, args) {
var env = vm.env;
var nameRef = args.positional.at(0);
(true && !((0, _reference.isConst)(nameRef)) && (0, _emberDebug.assert)('The first argument of {{render}} must be quoted, e.g. {{render "sidebar"}}.', (0, _reference.isConst)(nameRef)));
(true && !(args.positional.length === 1 || !(0, _reference.isConst)(args.positional.at(1))) && (0, _emberDebug.assert)('The second argument of {{render}} must be a path, e.g. {{render "post" post}}.', args.positional.length === 1 || !(0, _reference.isConst)(args.positional.at(1))));
var templateName = nameRef.value();
// tslint:disable-next-line:max-line-length
(true && !(env.owner.hasRegistration('template:' + templateName)) && (0, _emberDebug.assert)('You used `{{render \'' + templateName + '\'}}`, but \'' + templateName + '\' can not be found as a template.', env.owner.hasRegistration('template:' + templateName)));
var template = env.owner.lookup('template:' + templateName);
var controllerName = void 0;
if (args.named.has('controller')) {
var controllerNameRef = args.named.get('controller');
// tslint:disable-next-line:max-line-length
(true && !((0, _reference.isConst)(controllerNameRef)) && (0, _emberDebug.assert)('The controller argument for {{render}} must be quoted, e.g. {{render "sidebar" controller="foo"}}.', (0, _reference.isConst)(controllerNameRef)));
// TODO should be ensuring this to string here
controllerName = controllerNameRef.value();
// tslint:disable-next-line:max-line-length
(true && !(env.owner.hasRegistration('controller:' + controllerName)) && (0, _emberDebug.assert)('The controller name you supplied \'' + controllerName + '\' did not resolve to a controller.', env.owner.hasRegistration('controller:' + controllerName)));
} else {
controllerName = templateName;
}
if (args.positional.length === 1) {
return new _reference.ConstReference(new _render.RenderDefinition(controllerName, template, env, _render.SINGLETON_RENDER_MANAGER));
} else {
return new _reference.ConstReference(new _render.RenderDefinition(controllerName, template, env, _render.NON_SINGLETON_RENDER_MANAGER));
}
}
/**
Calling ``{{render}}`` from within a template will insert another
template that matches the provided name. The inserted template will
access its properties on its own controller (rather than the controller
of the parent template).
If a view class with the same name exists, the view class also will be used.
Note: A given controller may only be used *once* in your app in this manner.
A singleton instance of the controller will be created for you.
Example:
```app/controllers/navigation.js
import Controller from '@ember/controller';
export default Controller.extend({
who: "world"
});
```
```handlebars
<!-- navigation.hbs -->
Hello, {{who}}.
```
```handlebars
<!-- application.hbs -->
<h1>My great app</h1>
{{render "navigation"}}
```
```html
<h1>My great app</h1>
<div class='ember-view'>
Hello, world.
</div>
```
Optionally you may provide a second argument: a property path
that will be bound to the `model` property of the controller.
If a `model` property path is specified, then a new instance of the
controller will be created and `{{render}}` can be used multiple times
with the same name.
For example if you had this `author` template.
```handlebars
<div class="author">
Written by {{firstName}} {{lastName}}.
Total Posts: {{postCount}}
</div>
```
You could render it inside the `post` template using the `render` helper.
```handlebars
<div class="post">
<h1>{{title}}</h1>
<div>{{body}}</div>
{{render "author" author}}
</div>
```
@method render
@for Ember.Templates.helpers
@param {String} name
@param {Object?} context
@param {Hash} options
@return {String} HTML string
@public
@deprecated Use a component instead
*/
function renderMacro(_name, params, hash, builder) {
if (!params) {
params = [];
}
var definitionArgs = [params.slice(0), hash, null, null];
var args = [params.slice(1), (0, _utils.hashToArgs)(hash), null, null];
builder.component.dynamic(definitionArgs, makeComponentDefinition, args);
return true;
}
});
enifed("ember-glimmer/syntax/utils", ["exports"], function (exports) {
"use strict";
exports.hashToArgs = hashToArgs;
function hashToArgs(hash) {
if (hash === null) {
return null;
}
var names = hash[0].map(function (key) {
return "@" + key;
});
return [names, hash[1]];
}
});
enifed('ember-glimmer/template', ['exports', 'ember-babel', '@glimmer/runtime', 'ember-utils'], function (exports, _emberBabel, _runtime, _emberUtils) {
'use strict';
exports.WrappedTemplateFactory = undefined;
exports.default = template;
var WrappedTemplateFactory = exports.WrappedTemplateFactory = function () {
function WrappedTemplateFactory(factory) {
(0, _emberBabel.classCallCheck)(this, WrappedTemplateFactory);
this.factory = factory;
this.id = factory.id;
this.meta = factory.meta;
}
WrappedTemplateFactory.prototype.create = function create(props) {
var owner = props[_emberUtils.OWNER];
return this.factory.create(props.env, { owner: owner });
};
return WrappedTemplateFactory;
}();
function template(json) {
var factory = (0, _runtime.templateFactory)(json);
return new WrappedTemplateFactory(factory);
}
});
enifed("ember-glimmer/template_registry", ["exports"], function (exports) {
"use strict";
exports.setTemplates = setTemplates;
exports.getTemplates = getTemplates;
exports.getTemplate = getTemplate;
exports.hasTemplate = hasTemplate;
exports.setTemplate = setTemplate;
var TEMPLATES = {};
function setTemplates(templates) {
TEMPLATES = templates;
}
function getTemplates() {
return TEMPLATES;
}
function getTemplate(name) {
if (TEMPLATES.hasOwnProperty(name)) {
return TEMPLATES[name];
}
}
function hasTemplate(name) {
return TEMPLATES.hasOwnProperty(name);
}
function setTemplate(name, template) {
return TEMPLATES[name] = template;
}
});
enifed("ember-glimmer/templates/component", ["exports", "ember-glimmer/template"], function (exports, _template) {
"use strict";
exports.default = (0, _template.default)({ "id": "RxHsBKwy", "block": "{\"symbols\":[\"&default\"],\"statements\":[[11,1]],\"hasEval\":false}", "meta": { "moduleName": "packages/ember-glimmer/lib/templates/component.hbs" } });
});
enifed("ember-glimmer/templates/empty", ["exports", "ember-glimmer/template"], function (exports, _template) {
"use strict";
exports.default = (0, _template.default)({ "id": "5jp2oO+o", "block": "{\"symbols\":[],\"statements\":[],\"hasEval\":false}", "meta": { "moduleName": "packages/ember-glimmer/lib/templates/empty.hbs" } });
});
enifed("ember-glimmer/templates/link-to", ["exports", "ember-glimmer/template"], function (exports, _template) {
"use strict";
exports.default = (0, _template.default)({ "id": "VZn3uSPL", "block": "{\"symbols\":[\"&default\"],\"statements\":[[4,\"if\",[[20,[\"linkTitle\"]]],null,{\"statements\":[[1,[18,\"linkTitle\"],false]],\"parameters\":[]},{\"statements\":[[11,1]],\"parameters\":[]}]],\"hasEval\":false}", "meta": { "moduleName": "packages/ember-glimmer/lib/templates/link-to.hbs" } });
});
enifed("ember-glimmer/templates/outlet", ["exports", "ember-glimmer/template"], function (exports, _template) {
"use strict";
exports.default = (0, _template.default)({ "id": "/7rqcQ85", "block": "{\"symbols\":[],\"statements\":[[1,[18,\"outlet\"],false]],\"hasEval\":false}", "meta": { "moduleName": "packages/ember-glimmer/lib/templates/outlet.hbs" } });
});
enifed("ember-glimmer/templates/root", ["exports", "ember-glimmer/template"], function (exports, _template) {
"use strict";
exports.default = (0, _template.default)({ "id": "AdIsk/cm", "block": "{\"symbols\":[],\"statements\":[[1,[25,\"component\",[[19,0,[]]],null],false]],\"hasEval\":false}", "meta": { "moduleName": "packages/ember-glimmer/lib/templates/root.hbs" } });
});
enifed('ember-glimmer/utils/bindings', ['exports', 'ember-babel', '@glimmer/reference', '@glimmer/wire-format', 'ember-debug', 'ember-metal', 'ember-runtime', 'ember-glimmer/component', 'ember-glimmer/utils/string'], function (exports, _emberBabel, _reference, _wireFormat, _emberDebug, _emberMetal, _emberRuntime, _component, _string) {
'use strict';
exports.ClassNameBinding = exports.IsVisibleBinding = exports.AttributeBinding = undefined;
exports.wrapComponentClassAttribute = wrapComponentClassAttribute;
function referenceForKey(component, key) {
return component[_component.ROOT_REF].get(key);
}
function referenceForParts(component, parts) {
var isAttrs = parts[0] === 'attrs';
// TODO deprecate this
if (isAttrs) {
parts.shift();
if (parts.length === 1) {
return referenceForKey(component, parts[0]);
}
}
return (0, _reference.referenceFromParts)(component[_component.ROOT_REF], parts);
}
// TODO we should probably do this transform at build time
function wrapComponentClassAttribute(hash) {
if (!hash) {
return hash;
}
var keys = hash[0],
values = hash[1];
var index = keys.indexOf('class');
if (index !== -1) {
var _values$index = values[index],
type = _values$index[0];
if (type === _wireFormat.Ops.Get || type === _wireFormat.Ops.MaybeLocal) {
var getExp = values[index];
var path = getExp[getExp.length - 1];
var propName = path[path.length - 1];
hash[1][index] = [_wireFormat.Ops.Helper, ['-class'], [getExp, propName]];
}
}
return hash;
}
var AttributeBinding = exports.AttributeBinding = {
parse: function (microsyntax) {
var colonIndex = microsyntax.indexOf(':');
if (colonIndex === -1) {
(true && !(microsyntax !== 'class') && (0, _emberDebug.assert)('You cannot use class as an attributeBinding, use classNameBindings instead.', microsyntax !== 'class'));
return [microsyntax, microsyntax, true];
} else {
var prop = microsyntax.substring(0, colonIndex);
var attribute = microsyntax.substring(colonIndex + 1);
(true && !(attribute !== 'class') && (0, _emberDebug.assert)('You cannot use class as an attributeBinding, use classNameBindings instead.', attribute !== 'class'));
return [prop, attribute, false];
}
},
install: function (element, component, parsed, operations) {
var prop = parsed[0],
attribute = parsed[1],
isSimple = parsed[2];
if (attribute === 'id') {
var elementId = (0, _emberMetal.get)(component, prop);
if (elementId === undefined || elementId === null) {
elementId = component.elementId;
}
operations.addStaticAttribute(element, 'id', elementId);
return;
}
var isPath = prop.indexOf('.') > -1;
var reference = isPath ? referenceForParts(component, prop.split('.')) : referenceForKey(component, prop);
(true && !(!(isSimple && isPath)) && (0, _emberDebug.assert)('Illegal attributeBinding: \'' + prop + '\' is not a valid attribute name.', !(isSimple && isPath)));
if (attribute === 'style') {
reference = new StyleBindingReference(reference, referenceForKey(component, 'isVisible'));
}
operations.addDynamicAttribute(element, attribute, reference, false);
}
};
var DISPLAY_NONE = 'display: none;';
var SAFE_DISPLAY_NONE = (0, _string.htmlSafe)(DISPLAY_NONE);
var StyleBindingReference = function (_CachedReference) {
(0, _emberBabel.inherits)(StyleBindingReference, _CachedReference);
function StyleBindingReference(inner, isVisible) {
(0, _emberBabel.classCallCheck)(this, StyleBindingReference);
var _this = (0, _emberBabel.possibleConstructorReturn)(this, _CachedReference.call(this));
_this.inner = inner;
_this.isVisible = isVisible;
_this.tag = (0, _reference.combine)([inner.tag, isVisible.tag]);
return _this;
}
StyleBindingReference.prototype.compute = function compute() {
var value = this.inner.value();
var isVisible = this.isVisible.value();
if (isVisible !== false) {
return value;
} else if (!value) {
return SAFE_DISPLAY_NONE;
} else {
var style = value + ' ' + DISPLAY_NONE;
return (0, _string.isHTMLSafe)(value) ? (0, _string.htmlSafe)(style) : style;
}
};
return StyleBindingReference;
}(_reference.CachedReference);
var IsVisibleBinding = exports.IsVisibleBinding = {
install: function (element, component, operations) {
operations.addDynamicAttribute(element, 'style', (0, _reference.map)(referenceForKey(component, 'isVisible'), this.mapStyleValue), false);
},
mapStyleValue: function (isVisible) {
return isVisible === false ? SAFE_DISPLAY_NONE : null;
}
};
var ClassNameBinding = exports.ClassNameBinding = {
install: function (element, component, microsyntax, operations) {
var _microsyntax$split = microsyntax.split(':'),
prop = _microsyntax$split[0],
truthy = _microsyntax$split[1],
falsy = _microsyntax$split[2];
var isStatic = prop === '';
if (isStatic) {
operations.addStaticAttribute(element, 'class', truthy);
} else {
var isPath = prop.indexOf('.') > -1;
var parts = isPath ? prop.split('.') : [];
var value = isPath ? referenceForParts(component, parts) : referenceForKey(component, prop);
var ref = void 0;
if (truthy === undefined) {
ref = new SimpleClassNameBindingReference(value, isPath ? parts[parts.length - 1] : prop);
} else {
ref = new ColonClassNameBindingReference(value, truthy, falsy);
}
operations.addDynamicAttribute(element, 'class', ref, false);
}
}
};
var SimpleClassNameBindingReference = function (_CachedReference2) {
(0, _emberBabel.inherits)(SimpleClassNameBindingReference, _CachedReference2);
function SimpleClassNameBindingReference(inner, path) {
(0, _emberBabel.classCallCheck)(this, SimpleClassNameBindingReference);
var _this2 = (0, _emberBabel.possibleConstructorReturn)(this, _CachedReference2.call(this));
_this2.inner = inner;
_this2.path = path;
_this2.tag = inner.tag;
_this2.inner = inner;
_this2.path = path;
_this2.dasherizedPath = null;
return _this2;
}
SimpleClassNameBindingReference.prototype.compute = function compute() {
var value = this.inner.value();
if (value === true) {
var path = this.path,
dasherizedPath = this.dasherizedPath;
return dasherizedPath || (this.dasherizedPath = _emberRuntime.String.dasherize(path));
} else if (value || value === 0) {
return String(value);
} else {
return null;
}
};
return SimpleClassNameBindingReference;
}(_reference.CachedReference);
var ColonClassNameBindingReference = function (_CachedReference3) {
(0, _emberBabel.inherits)(ColonClassNameBindingReference, _CachedReference3);
function ColonClassNameBindingReference(inner) {
var truthy = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
var falsy = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
(0, _emberBabel.classCallCheck)(this, ColonClassNameBindingReference);
var _this3 = (0, _emberBabel.possibleConstructorReturn)(this, _CachedReference3.call(this));
_this3.inner = inner;
_this3.truthy = truthy;
_this3.falsy = falsy;
_this3.tag = inner.tag;
return _this3;
}
ColonClassNameBindingReference.prototype.compute = function compute() {
var inner = this.inner,
truthy = this.truthy,
falsy = this.falsy;
return inner.value() ? truthy : falsy;
};
return ColonClassNameBindingReference;
}(_reference.CachedReference);
});
enifed('ember-glimmer/utils/curly-component-state-bucket', ['exports', 'ember-babel'], function (exports, _emberBabel) {
'use strict';
// tslint:disable-next-line:no-empty
function NOOP() {}
/**
@module ember
*/
/**
Represents the internal state of the component.
@class ComponentStateBucket
@private
*/
var ComponentStateBucket = function () {
function ComponentStateBucket(environment, component, args, finalizer) {
(0, _emberBabel.classCallCheck)(this, ComponentStateBucket);
this.environment = environment;
this.component = component;
this.args = args;
this.finalizer = finalizer;
this.classRef = null;
this.classRef = null;
this.argsRevision = args.tag.value();
}
ComponentStateBucket.prototype.destroy = function destroy() {
var component = this.component,
environment = this.environment;
if (environment.isInteractive) {
component.trigger('willDestroyElement');
component.trigger('willClearRender');
}
environment.destroyedComponents.push(component);
};
ComponentStateBucket.prototype.finalize = function finalize() {
var finalizer = this.finalizer;
finalizer();
this.finalizer = NOOP;
};
return ComponentStateBucket;
}();
exports.default = ComponentStateBucket;
});
enifed('ember-glimmer/utils/debug-stack', ['exports', 'ember-babel'], function (exports, _emberBabel) {
'use strict';
// @ts-check
var DebugStack = void 0;
if (true) {
var Element = function Element(name) {
(0, _emberBabel.classCallCheck)(this, Element);
this.name = name;
};
var TemplateElement = function (_Element) {
(0, _emberBabel.inherits)(TemplateElement, _Element);
function TemplateElement() {
(0, _emberBabel.classCallCheck)(this, TemplateElement);
return (0, _emberBabel.possibleConstructorReturn)(this, _Element.apply(this, arguments));
}
return TemplateElement;
}(Element);
var EngineElement = function (_Element2) {
(0, _emberBabel.inherits)(EngineElement, _Element2);
function EngineElement() {
(0, _emberBabel.classCallCheck)(this, EngineElement);
return (0, _emberBabel.possibleConstructorReturn)(this, _Element2.apply(this, arguments));
}
return EngineElement;
}(Element);
// tslint:disable-next-line:no-shadowed-variable
DebugStack = function () {
function DebugStack() {
(0, _emberBabel.classCallCheck)(this, DebugStack);
this._stack = [];
}
DebugStack.prototype.push = function push(name) {
this._stack.push(new TemplateElement(name));
};
DebugStack.prototype.pushEngine = function pushEngine(name) {
this._stack.push(new EngineElement(name));
};
DebugStack.prototype.pop = function pop() {
var element = this._stack.pop();
if (element) {
return element.name;
}
};
DebugStack.prototype.peek = function peek() {
var template = this._currentTemplate();
var engine = this._currentEngine();
if (engine) {
return '"' + template + '" (in "' + engine + '")';
} else if (template) {
return '"' + template + '"';
}
};
DebugStack.prototype._currentTemplate = function _currentTemplate() {
return this._getCurrentByType(TemplateElement);
};
DebugStack.prototype._currentEngine = function _currentEngine() {