Last active
May 15, 2017 12:34
-
-
Save buschtoens/20a8a96b9c5ac07b73db0ef96abf08e3 to your computer and use it in GitHub Desktop.
This file has been truncated, but you can view the full file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
window.EmberENV = {"FEATURES":{},"EXTEND_PROTOTYPES":{"Date":false}}; | |
var runningTests = false; | |
;var loader, define, requireModule, require, requirejs; | |
(function (global) { | |
'use strict'; | |
var heimdall = global.heimdall; | |
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 (name) { | |
var pending = []; | |
var mod = findModule(name, '(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]; | |
} | |
} | |
} | |
} | |
}; | |
var _isArray; | |
if (!Array.isArray) { | |
_isArray = function (x) { | |
return Object.prototype.toString.call(x) === '[object Array]'; | |
}; | |
} else { | |
_isArray = Array.isArray; | |
} | |
var registry = dict(); | |
var seen = dict(); | |
var uuid = 0; | |
function unsupportedModule(length) { | |
throw new Error('an unsupported module was defined, expected `define(name, deps, module)` instead got: `' + length + '` arguments to define`'); | |
} | |
var defaultDeps = ['require', 'exports', 'module']; | |
function Module(name, deps, callback, alias) { | |
this.id = uuid++; | |
this.name = name; | |
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.name, this.callback); | |
} | |
this.reify(); | |
var result = this.callback.apply(this, this.reified); | |
this.state = 'finalized'; | |
if (!(this.hasExportsAsDep && result === undefined)) { | |
this.module.exports = result; | |
} | |
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.name), this.name, pending); | |
} | |
} | |
}; | |
Module.prototype.makeRequire = function () { | |
var name = this.name; | |
var r = function (dep) { | |
return require(resolve(dep, name)); | |
}; | |
r['default'] = r; | |
r.has = function (dep) { | |
return has(resolve(dep, name)); | |
}; | |
return r; | |
}; | |
define = function (name, deps, callback) { | |
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; | |
} | |
if (arguments.length < 2) { | |
unsupportedModule(arguments.length); | |
} | |
if (!_isArray(deps)) { | |
callback = deps; | |
deps = []; | |
} | |
if (callback instanceof Alias) { | |
registry[name] = new Module(callback.name, deps, callback, true); | |
} else { | |
registry[name] = new Module(name, deps, callback, false); | |
} | |
}; | |
// we don't support all of AMD | |
// define.amd = {}; | |
function Alias(path) { | |
this.name = path; | |
} | |
define.alias = function (path, target) { | |
if (arguments.length === 2) { | |
return define(target, new Alias(path)); | |
} | |
return new Alias(path); | |
}; | |
function missingModule(name, referrer) { | |
throw new Error('Could not find module `' + name + '` imported from `' + referrer + '`'); | |
} | |
function findModule(name, referrer, pending) { | |
var mod = registry[name] || registry[name + '/index']; | |
while (mod && mod.isAlias) { | |
mod = registry[mod.name]; | |
} | |
if (!mod) { | |
missingModule(name, referrer); | |
} | |
if (pending && mod.state !== 'pending' && mod.state !== 'finalized') { | |
mod.findDeps(pending); | |
pending.push(mod); | |
} | |
return mod; | |
} | |
function resolve(child, name) { | |
if (child.charAt(0) !== '.') { | |
return child; | |
} | |
var parts = child.split('/'); | |
var nameParts = name.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(name) { | |
return !!(registry[name] || registry[name + '/index']); | |
} | |
requirejs.entries = requirejs._eak_seen = registry; | |
requirejs.has = has; | |
requirejs.unsee = function (moduleName) { | |
findModule(moduleName, '(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 () {}); | |
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.2.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: 2017-03-20T18:59Z | |
*/ | |
( 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 = {}; | |
function DOMEval( code, doc ) { | |
doc = doc || document; | |
var script = doc.createElement( "script" ); | |
script.text = code; | |
doc.head.appendChild( script ).parentNode.removeChild( script ); | |
} | |
/* 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.2.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, | |
// Matches dashed string for camelizing | |
rmsPrefix = /^-ms-/, | |
rdashAlpha = /-([a-z])/g, | |
// Used by jQuery.camelCase as callback to replace() | |
fcamelCase = function( all, letter ) { | |
return letter.toUpperCase(); | |
}; | |
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" && !jQuery.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() {}, | |
isFunction: function( obj ) { | |
return jQuery.type( obj ) === "function"; | |
}, | |
isWindow: function( obj ) { | |
return obj != null && obj === obj.window; | |
}, | |
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 ) ); | |
}, | |
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; | |
}, | |
type: function( 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; | |
}, | |
// Evaluates a script in a global context | |
globalEval: function( code ) { | |
DOMEval( code ); | |
}, | |
// Convert dashed to camelCase; used by the css and data modules | |
// Support: IE <=9 - 11, Edge 12 - 13 | |
// Microsoft forgot to hump their vendor prefix (#9572) | |
camelCase: function( string ) { | |
return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); | |
}, | |
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, | |
// Bind a function to a context, optionally partially applying any | |
// arguments. | |
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 ( !jQuery.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; | |
}, | |
now: Date.now, | |
// 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 = jQuery.type( obj ); | |
if ( type === "function" || jQuery.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 ); | |
var risSimple = /^.[^:#\[\.,]*$/; | |
// Implement the identical functionality for filter and not | |
function winnow( elements, qualifier, not ) { | |
if ( jQuery.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; | |
} ); | |
} | |
// Simple selector that can be filtered directly, removing non-Elements | |
if ( risSimple.test( qualifier ) ) { | |
return jQuery.filter( qualifier, elements, not ); | |
} | |
// Complex selector, compare the two sets, removing non-Elements | |
qualifier = jQuery.filter( qualifier, elements ); | |
return jQuery.grep( elements, function( elem ) { | |
return ( indexOf.call( qualifier, elem ) > -1 ) !== not && elem.nodeType === 1; | |
} ); | |
} | |
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 ( jQuery.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 ( jQuery.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 ( jQuery.isFunction( arg ) ) { | |
if ( !options.unique || !self.has( arg ) ) { | |
list.push( arg ); | |
} | |
} else if ( arg && arg.length && jQuery.type( 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 && jQuery.isFunction( ( method = value.promise ) ) ) { | |
method.call( value ).done( resolve ).fail( reject ); | |
// Other thenables | |
} else if ( value && jQuery.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 = jQuery.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 && jQuery.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 ( jQuery.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, | |
jQuery.isFunction( onProgress ) ? | |
onProgress : | |
Identity, | |
newDefer.notifyWith | |
) | |
); | |
// fulfilled_handlers.add( ... ) | |
tuples[ 1 ][ 3 ].add( | |
resolve( | |
0, | |
newDefer, | |
jQuery.isFunction( onFulfilled ) ? | |
onFulfilled : | |
Identity | |
) | |
); | |
// rejected_handlers.add( ... ) | |
tuples[ 2 ][ 3 ].add( | |
resolve( | |
0, | |
newDefer, | |
jQuery.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, | |
// progress_callbacks.lock | |
tuples[ 0 ][ 2 ].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" || | |
jQuery.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 ( jQuery.type( 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 ( !jQuery.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; | |
}; | |
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[ jQuery.camelCase( data ) ] = value; | |
// Handle: [ owner, { properties } ] args | |
} else { | |
// Copy the properties one-by-one to the cache object | |
for ( prop in data ) { | |
cache[ jQuery.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 ][ jQuery.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( jQuery.camelCase ); | |
} else { | |
key = jQuery.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 = jQuery.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 = 1, | |
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 ) { | |
// Trust units reported by jQuery.css | |
unit = unit || initialInUnit[ 3 ]; | |
// Make sure we update the tween properties later on | |
valueParts = valueParts || []; | |
// Iteratively approximate from a nonzero starting point | |
initialInUnit = +initial || 1; | |
do { | |
// If previous iteration zeroed out, double until we get *something*. | |
// Use string for doubling so we don't accidentally see scale as unchanged below | |
scale = scale || ".5"; | |
// Adjust and apply | |
initialInUnit = initialInUnit / scale; | |
jQuery.style( elem, prop, initialInUnit + unit ); | |
// Update scale, tolerating zero or NaN from tween.cur() | |
// Break the loop if scale is unchanged or perfect, or if we've just had enough. | |
} while ( | |
scale !== ( scale = currentValue() / initial ) && scale !== 1 && --maxIterations | |
); | |
} | |
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 = ( /^$|\/(?: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 ( jQuery.type( 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: jQuery.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 || jQuery.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 | |
// 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, | |
rscriptTypeMasked = /^true\/(.*)/, | |
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( ">tbody", elem )[ 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 ) { | |
var match = rscriptTypeMasked.exec( elem.type ); | |
if ( match ) { | |
elem.type = match[ 1 ]; | |
} 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 ], | |
isFunction = jQuery.isFunction( value ); | |
// We can't cloneNode fragments that contain checked, in WebKit | |
if ( isFunction || | |
( l > 1 && typeof value === "string" && | |
!support.checkClone && rchecked.test( value ) ) ) { | |
return collection.each( function( index ) { | |
var self = collection.eq( index ); | |
if ( isFunction ) { | |
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 ) { | |
// 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 ); | |
} | |
} | |
} | |
} | |
} | |
} | |
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 rmargin = ( /^margin/ ); | |
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 ); | |
}; | |
( 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; | |
} | |
div.style.cssText = | |
"box-sizing:border-box;" + | |
"position:relative;display:block;" + | |
"margin:auto;border:1px;padding:1px;" + | |
"top:1%;width:50%"; | |
div.innerHTML = ""; | |
documentElement.appendChild( container ); | |
var divStyle = window.getComputedStyle( div ); | |
pixelPositionVal = divStyle.top !== "1%"; | |
// Support: Android 4.0 - 4.3 only, Firefox <=3 - 44 | |
reliableMarginLeftVal = divStyle.marginLeft === "2px"; | |
boxSizingReliableVal = divStyle.width === "4px"; | |
// Support: Android 4.0 - 4.3 only | |
// Some styles come back with percentage values, even though they shouldn't | |
div.style.marginRight = "50%"; | |
pixelMarginRightVal = divStyle.marginRight === "4px"; | |
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; | |
} | |
var pixelPositionVal, boxSizingReliableVal, pixelMarginRightVal, 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"; | |
container.style.cssText = "border:0;width:8px;height:0;top:0;left:-9999px;" + | |
"padding:0;margin-top:1px;position:absolute"; | |
container.appendChild( div ); | |
jQuery.extend( support, { | |
pixelPosition: function() { | |
computeStyleTests(); | |
return pixelPositionVal; | |
}, | |
boxSizingReliable: function() { | |
computeStyleTests(); | |
return boxSizingReliableVal; | |
}, | |
pixelMarginRight: function() { | |
computeStyleTests(); | |
return pixelMarginRightVal; | |
}, | |
reliableMarginLeft: function() { | |
computeStyleTests(); | |
return reliableMarginLeftVal; | |
} | |
} ); | |
} )(); | |
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.pixelMarginRight() && rnumnonpx.test( ret ) && rmargin.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 augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) { | |
var i, | |
val = 0; | |
// If we already have the right measurement, avoid augmentation | |
if ( extra === ( isBorderBox ? "border" : "content" ) ) { | |
i = 4; | |
// Otherwise initialize for horizontal or vertical properties | |
} else { | |
i = name === "width" ? 1 : 0; | |
} | |
for ( ; i < 4; i += 2 ) { | |
// Both box models exclude margin, so add it if we want it | |
if ( extra === "margin" ) { | |
val += jQuery.css( elem, extra + cssExpand[ i ], true, styles ); | |
} | |
if ( isBorderBox ) { | |
// border-box includes padding, so remove it if we want content | |
if ( extra === "content" ) { | |
val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); | |
} | |
// At this point, extra isn't border nor margin, so remove border | |
if ( extra !== "margin" ) { | |
val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); | |
} | |
} else { | |
// At this point, extra isn't content, so add padding | |
val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); | |
// At this point, extra isn't content nor padding, so add border | |
if ( extra !== "padding" ) { | |
val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); | |
} | |
} | |
} | |
return val; | |
} | |
function getWidthOrHeight( elem, name, extra ) { | |
// Start with computed style | |
var valueIsBorderBox, | |
styles = getStyles( elem ), | |
val = curCSS( elem, name, styles ), | |
isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; | |
// Computed unit is not pixels. Stop here and return. | |
if ( rnumnonpx.test( val ) ) { | |
return val; | |
} | |
// Check for style in case a browser which returns unreliable values | |
// for getComputedStyle silently falls back to the reliable elem.style | |
valueIsBorderBox = isBorderBox && | |
( support.boxSizingReliable() || val === elem.style[ name ] ); | |
// Fall back to offsetWidth/Height when value is "auto" | |
// This happens for inline elements with no explicit setting (gh-3571) | |
if ( val === "auto" ) { | |
val = elem[ "offset" + name[ 0 ].toUpperCase() + name.slice( 1 ) ]; | |
} | |
// Normalize "", auto, and prepare for extra | |
val = parseFloat( val ) || 0; | |
// Use the active box-sizing model to add/subtract irrelevant styles | |
return ( val + | |
augmentWidthOrHeight( | |
elem, | |
name, | |
extra || ( isBorderBox ? "border" : "content" ), | |
valueIsBorderBox, | |
styles | |
) | |
) + "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: { | |
"float": "cssFloat" | |
}, | |
// 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 = jQuery.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 = jQuery.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, name ) { | |
jQuery.cssHooks[ name ] = { | |
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, name, extra ); | |
} ) : | |
getWidthOrHeight( elem, name, extra ); | |
} | |
}, | |
set: function( elem, value, extra ) { | |
var matches, | |
styles = extra && getStyles( elem ), | |
subtract = extra && augmentWidthOrHeight( | |
elem, | |
name, | |
extra, | |
jQuery.css( elem, "boxSizing", false, styles ) === "border-box", | |
styles | |
); | |
// Convert to pixels if value adjustment is needed | |
if ( subtract && ( matches = rcssNum.exec( value ) ) && | |
( matches[ 3 ] || "px" ) !== "px" ) { | |
elem.style[ name ] = value; | |
value = jQuery.css( elem, name ); | |
} | |
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 ( !rmargin.test( prefix ) ) { | |
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 = jQuery.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 - 13 | |
// Record all 3 overflow attributes because IE does not infer the shorthand | |
// from identically-valued overflowX and overflowY | |
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 = jQuery.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 ( jQuery.isFunction( result.stop ) ) { | |
jQuery._queueHooks( animation.elem, animation.opts.queue ).stop = | |
jQuery.proxy( result.stop, result ); | |
} | |
return result; | |
} | |
} | |
jQuery.map( props, createTween, animation ); | |
if ( jQuery.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 ( jQuery.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 || | |
jQuery.isFunction( speed ) && speed, | |
duration: speed, | |
easing: fn && easing || easing && !jQuery.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 ( jQuery.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 = jQuery.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://html.spec.whatwg.org/multipage/infrastructure.html#strip-and-collapse-whitespace | |
function stripAndCollapse( value ) { | |
var tokens = value.match( rnothtmlwhite ) || []; | |
return tokens.join( " " ); | |
} | |
function getClass( elem ) { | |
return elem.getAttribute && elem.getAttribute( "class" ) || ""; | |
} | |
jQuery.fn.extend( { | |
addClass: function( value ) { | |
var classes, elem, cur, curValue, clazz, j, finalValue, | |
i = 0; | |
if ( jQuery.isFunction( value ) ) { | |
return this.each( function( j ) { | |
jQuery( this ).addClass( value.call( this, j, getClass( this ) ) ); | |
} ); | |
} | |
if ( typeof value === "string" && value ) { | |
classes = value.match( rnothtmlwhite ) || []; | |
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 ( jQuery.isFunction( value ) ) { | |
return this.each( function( j ) { | |
jQuery( this ).removeClass( value.call( this, j, getClass( this ) ) ); | |
} ); | |
} | |
if ( !arguments.length ) { | |
return this.attr( "class", "" ); | |
} | |
if ( typeof value === "string" && value ) { | |
classes = value.match( rnothtmlwhite ) || []; | |
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; | |
if ( typeof stateVal === "boolean" && type === "string" ) { | |
return stateVal ? this.addClass( value ) : this.removeClass( value ); | |
} | |
if ( jQuery.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 ( type === "string" ) { | |
// Toggle individual class names | |
i = 0; | |
self = jQuery( this ); | |
classNames = value.match( rnothtmlwhite ) || []; | |
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, isFunction, | |
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; | |
} | |
isFunction = jQuery.isFunction( value ); | |
return this.each( function( i ) { | |
var val; | |
if ( this.nodeType !== 1 ) { | |
return; | |
} | |
if ( isFunction ) { | |
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 | |
var rfocusMorph = /^(?:focusinfocus|focusoutblur)$/; | |
jQuery.extend( jQuery.event, { | |
trigger: function( event, data, elem, onlyHandlers ) { | |
var i, cur, tmp, bubbleType, ontype, handle, special, | |
eventPath = [ elem || document ], | |
type = hasOwn.call( event, "type" ) ? event.type : event, | |
namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split( "." ) : []; | |
cur = 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 && !jQuery.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() ) { | |
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 && jQuery.isFunction( elem[ type ] ) && !jQuery.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; | |
elem[ type ](); | |
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 ); | |
} | |
} | |
} ); | |
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 ); | |
} | |
} ); | |
support.focusin = "onfocusin" in window; | |
// 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 = jQuery.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 && jQuery.type( 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 = jQuery.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 ( jQuery.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 - 13 | |
// 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, append data to url | |
if ( s.data ) { | |
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 ( jQuery.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 ( jQuery.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 ( jQuery.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 isFunction = jQuery.isFunction( html ); | |
return this.each( function( i ) { | |
jQuery( this ).wrapAll( isFunction ? 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.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 = 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 = jQuery.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 && jQuery.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 ( jQuery.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 ( jQuery.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: function( options ) { | |
// Preserve chaining for setter | |
if ( arguments.length ) { | |
return options === undefined ? | |
this : | |
this.each( function( i ) { | |
jQuery.offset.setOffset( this, options, i ); | |
} ); | |
} | |
var doc, docElem, 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 }; | |
} | |
rect = elem.getBoundingClientRect(); | |
doc = elem.ownerDocument; | |
docElem = doc.documentElement; | |
win = doc.defaultView; | |
return { | |
top: rect.top + win.pageYOffset - docElem.clientTop, | |
left: rect.left + win.pageXOffset - docElem.clientLeft | |
}; | |
}, | |
position: function() { | |
if ( !this[ 0 ] ) { | |
return; | |
} | |
var offsetParent, offset, | |
elem = this[ 0 ], | |
parentOffset = { top: 0, left: 0 }; | |
// Fixed elements are offset from window (parentOffset = {top:0, left: 0}, | |
// because it is its only offset parent | |
if ( jQuery.css( elem, "position" ) === "fixed" ) { | |
// Assume getBoundingClientRect is there when computed position is fixed | |
offset = elem.getBoundingClientRect(); | |
} else { | |
// Get *real* offsetParent | |
offsetParent = this.offsetParent(); | |
// Get correct offsets | |
offset = this.offset(); | |
if ( !nodeName( offsetParent[ 0 ], "html" ) ) { | |
parentOffset = offsetParent.offset(); | |
} | |
// Add offsetParent borders | |
parentOffset = { | |
top: parentOffset.top + jQuery.css( offsetParent[ 0 ], "borderTopWidth", true ), | |
left: parentOffset.left + jQuery.css( offsetParent[ 0 ], "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 ( jQuery.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 ( jQuery.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.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 ); | |
} | |
} ); | |
jQuery.holdReady = function( hold ) { | |
if ( hold ) { | |
jQuery.readyWait++; | |
} else { | |
jQuery.ready( true ); | |
} | |
}; | |
jQuery.isArray = Array.isArray; | |
jQuery.parseJSON = JSON.parse; | |
jQuery.nodeName = nodeName; | |
// 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.13.0 | |
*/ | |
var enifed, requireModule, Ember; | |
var mainContext = this; // Used in ember-environment/lib/global.js | |
(function() { | |
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']; | |
}; | |
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; | |
} | |
requireModule._eak_seen = registry; | |
Ember.__loader = { | |
define: enifed, | |
require: requireModule, | |
registry: registry | |
}; | |
} else { | |
enifed = Ember.__loader.define; | |
requireModule = Ember.__loader.require; | |
} | |
})(); | |
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 interopExportWildcard(obj, defaults) { | |
var newObj = defaults({}, obj); | |
delete newObj['default']; | |
return newObj; | |
} | |
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 babelHelpers = { | |
classCallCheck: classCallCheck, | |
inherits: inherits, | |
taggedTemplateLiteralLoose: taggedTemplateLiteralLoose, | |
slice: Array.prototype.slice, | |
createClass: createClass, | |
interopExportWildcard: interopExportWildcard, | |
defaults: defaults | |
}; | |
enifed('@glimmer/di', ['exports', '@glimmer/util'], function (exports, _glimmerUtil) { | |
'use strict'; | |
var Container = (function () { | |
function Container(registry) { | |
var resolver = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1]; | |
this._registry = registry; | |
this._resolver = resolver; | |
this._lookups = _glimmerUtil.dict(); | |
this._factoryLookups = _glimmerUtil.dict(); | |
} | |
Container.prototype.factoryFor = function factoryFor(specifier) { | |
var factory = this._factoryLookups[specifier]; | |
if (!factory) { | |
if (this._resolver) { | |
factory = this._resolver.retrieve(specifier); | |
} | |
if (!factory) { | |
factory = this._registry.registration(specifier); | |
} | |
if (factory) { | |
this._factoryLookups[specifier] = factory; | |
} | |
} | |
return factory; | |
}; | |
Container.prototype.lookup = function lookup(specifier) { | |
var singleton = this._registry.registeredOption(specifier, 'singleton') !== false; | |
if (singleton && this._lookups[specifier]) { | |
return this._lookups[specifier]; | |
} | |
var factory = this.factoryFor(specifier); | |
if (!factory) { | |
return; | |
} | |
if (this._registry.registeredOption(specifier, 'instantiate') === false) { | |
return factory; | |
} | |
var injections = this.buildInjections(specifier); | |
var object = factory.create(injections); | |
if (singleton && object) { | |
this._lookups[specifier] = object; | |
} | |
return object; | |
}; | |
Container.prototype.defaultInjections = function defaultInjections(specifier) { | |
return {}; | |
}; | |
Container.prototype.buildInjections = function buildInjections(specifier) { | |
var hash = this.defaultInjections(specifier); | |
var injections = this._registry.registeredInjections(specifier); | |
var injection = undefined; | |
for (var i = 0; i < injections.length; i++) { | |
injection = injections[i]; | |
hash[injection.property] = this.lookup(injection.source); | |
} | |
return hash; | |
}; | |
return Container; | |
})(); | |
var Registry = (function () { | |
function Registry() { | |
this._registrations = _glimmerUtil.dict(); | |
this._registeredOptions = _glimmerUtil.dict(); | |
this._registeredInjections = _glimmerUtil.dict(); | |
} | |
// TODO - use symbol | |
Registry.prototype.register = function register(specifier, factory, options) { | |
this._registrations[specifier] = factory; | |
if (options) { | |
this._registeredOptions[specifier] = options; | |
} | |
}; | |
Registry.prototype.registration = function registration(specifier) { | |
return this._registrations[specifier]; | |
}; | |
Registry.prototype.unregister = function unregister(specifier) { | |
delete this._registrations[specifier]; | |
delete this._registeredOptions[specifier]; | |
delete this._registeredInjections[specifier]; | |
}; | |
Registry.prototype.registerOption = function registerOption(specifier, option, value) { | |
var options = this._registeredOptions[specifier]; | |
if (!options) { | |
options = {}; | |
this._registeredOptions[specifier] = options; | |
} | |
options[option] = value; | |
}; | |
Registry.prototype.registeredOption = function registeredOption(specifier, option) { | |
var options = this.registeredOptions(specifier); | |
if (options) { | |
return options[option]; | |
} | |
}; | |
Registry.prototype.registeredOptions = function registeredOptions(specifier) { | |
var options = this._registeredOptions[specifier]; | |
if (options === undefined) { | |
var _specifier$split = specifier.split(':'); | |
var type = _specifier$split[0]; | |
options = this._registeredOptions[type]; | |
} | |
return options; | |
}; | |
Registry.prototype.unregisterOption = function unregisterOption(specifier, option) { | |
var options = this._registeredOptions[specifier]; | |
if (options) { | |
delete options[option]; | |
} | |
}; | |
Registry.prototype.registerInjection = function registerInjection(specifier, property, source) { | |
var injections = this._registeredInjections[specifier]; | |
if (injections === undefined) { | |
this._registeredInjections[specifier] = injections = []; | |
} | |
injections.push({ | |
property: property, | |
source: source | |
}); | |
}; | |
Registry.prototype.registeredInjections = function registeredInjections(specifier) { | |
var _specifier$split2 = specifier.split(':'); | |
var type = _specifier$split2[0]; | |
var injections = []; | |
Array.prototype.push.apply(injections, this._registeredInjections[type]); | |
Array.prototype.push.apply(injections, this._registeredInjections[specifier]); | |
return injections; | |
}; | |
return Registry; | |
})(); | |
var OWNER = '__owner__'; | |
function getOwner(object) { | |
return object[OWNER]; | |
} | |
function setOwner(object, owner) { | |
object[OWNER] = owner; | |
} | |
function isSpecifierStringAbsolute(specifier) { | |
var _specifier$split3 = specifier.split(':'); | |
var type = _specifier$split3[0]; | |
var path = _specifier$split3[1]; | |
return !!(type && path && path.indexOf('/') === 0 && path.split('/').length > 3); | |
} | |
function isSpecifierObjectAbsolute(specifier) { | |
return specifier.rootName !== undefined && specifier.collection !== undefined && specifier.name !== undefined && specifier.type !== undefined; | |
} | |
function serializeSpecifier(specifier) { | |
var type = specifier.type; | |
var path = serializeSpecifierPath(specifier); | |
if (path) { | |
return type + ':' + path; | |
} else { | |
return type; | |
} | |
} | |
function serializeSpecifierPath(specifier) { | |
var path = []; | |
if (specifier.rootName) { | |
path.push(specifier.rootName); | |
} | |
if (specifier.collection) { | |
path.push(specifier.collection); | |
} | |
if (specifier.namespace) { | |
path.push(specifier.namespace); | |
} | |
if (specifier.name) { | |
path.push(specifier.name); | |
} | |
if (path.length > 0) { | |
var fullPath = path.join('/'); | |
if (isSpecifierObjectAbsolute(specifier)) { | |
fullPath = '/' + fullPath; | |
} | |
return fullPath; | |
} | |
} | |
function deserializeSpecifier(specifier) { | |
var obj = {}; | |
if (specifier.indexOf(':') > -1) { | |
var _specifier$split4 = specifier.split(':'); | |
var type = _specifier$split4[0]; | |
var path = _specifier$split4[1]; | |
obj.type = type; | |
var pathSegments = undefined; | |
if (path.indexOf('/') === 0) { | |
pathSegments = path.substr(1).split('/'); | |
obj.rootName = pathSegments.shift(); | |
obj.collection = pathSegments.shift(); | |
} else { | |
pathSegments = path.split('/'); | |
} | |
if (pathSegments.length > 0) { | |
obj.name = pathSegments.pop(); | |
if (pathSegments.length > 0) { | |
obj.namespace = pathSegments.join('/'); | |
} | |
} | |
} else { | |
obj.type = specifier; | |
} | |
return obj; | |
} | |
exports.Container = Container; | |
exports.Registry = Registry; | |
exports.getOwner = getOwner; | |
exports.setOwner = setOwner; | |
exports.OWNER = OWNER; | |
exports.isSpecifierStringAbsolute = isSpecifierStringAbsolute; | |
exports.isSpecifierObjectAbsolute = isSpecifierObjectAbsolute; | |
exports.serializeSpecifier = serializeSpecifier; | |
exports.deserializeSpecifier = deserializeSpecifier; | |
}); | |
enifed('@glimmer/node', ['exports', '@glimmer/runtime'], function (exports, _glimmerRuntime) { | |
'use strict'; | |
var NodeDOMTreeConstruction = (function (_DOMTreeConstruction) { | |
babelHelpers.inherits(NodeDOMTreeConstruction, _DOMTreeConstruction); | |
function NodeDOMTreeConstruction(doc) { | |
_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, html, reference) { | |
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 _glimmerRuntime.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; | |
})(_glimmerRuntime.DOMTreeConstruction); | |
exports.NodeDOMTreeConstruction = NodeDOMTreeConstruction; | |
}); | |
enifed("@glimmer/reference", ["exports", "@glimmer/util"], function (exports, _glimmerUtil) { | |
"use strict"; | |
var CONSTANT = 0; | |
var INITIAL = 1; | |
var VOLATILE = NaN; | |
var RevisionTag = (function () { | |
function RevisionTag() {} | |
RevisionTag.prototype.validate = function validate(snapshot) { | |
return this.value() === snapshot; | |
}; | |
return RevisionTag; | |
})(); | |
var $REVISION = INITIAL; | |
var DirtyableTag = (function (_RevisionTag) { | |
babelHelpers.inherits(DirtyableTag, _RevisionTag); | |
function DirtyableTag() { | |
var revision = arguments.length <= 0 || arguments[0] === undefined ? $REVISION : arguments[0]; | |
_RevisionTag.call(this); | |
this.revision = revision; | |
} | |
DirtyableTag.prototype.value = function value() { | |
return this.revision; | |
}; | |
DirtyableTag.prototype.dirty = function dirty() { | |
this.revision = ++$REVISION; | |
}; | |
return DirtyableTag; | |
})(RevisionTag); | |
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 new TagsPair(tags[0], tags[1]); | |
default: | |
return new TagsCombinator(tags); | |
} | |
; | |
} | |
var CachedTag = (function (_RevisionTag2) { | |
babelHelpers.inherits(CachedTag, _RevisionTag2); | |
function CachedTag() { | |
_RevisionTag2.apply(this, arguments); | |
this.lastChecked = null; | |
this.lastValue = null; | |
} | |
CachedTag.prototype.value = function value() { | |
var lastChecked = this.lastChecked; | |
var 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) { | |
babelHelpers.inherits(TagsPair, _CachedTag); | |
function TagsPair(first, second) { | |
_CachedTag.call(this); | |
this.first = first; | |
this.second = second; | |
} | |
TagsPair.prototype.compute = function compute() { | |
return Math.max(this.first.value(), this.second.value()); | |
}; | |
return TagsPair; | |
})(CachedTag); | |
var TagsCombinator = (function (_CachedTag2) { | |
babelHelpers.inherits(TagsCombinator, _CachedTag2); | |
function TagsCombinator(tags) { | |
_CachedTag2.call(this); | |
this.tags = tags; | |
} | |
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); | |
var UpdatableTag = (function (_CachedTag3) { | |
babelHelpers.inherits(UpdatableTag, _CachedTag3); | |
function UpdatableTag(tag) { | |
_CachedTag3.call(this); | |
this.tag = tag; | |
this.lastUpdated = INITIAL; | |
} | |
////////// | |
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); | |
var CONSTANT_TAG = new ((function (_RevisionTag3) { | |
babelHelpers.inherits(ConstantTag, _RevisionTag3); | |
function ConstantTag() { | |
_RevisionTag3.apply(this, arguments); | |
} | |
ConstantTag.prototype.value = function value() { | |
return CONSTANT; | |
}; | |
return ConstantTag; | |
})(RevisionTag))(); | |
var VOLATILE_TAG = new ((function (_RevisionTag4) { | |
babelHelpers.inherits(VolatileTag, _RevisionTag4); | |
function VolatileTag() { | |
_RevisionTag4.apply(this, arguments); | |
} | |
VolatileTag.prototype.value = function value() { | |
return VOLATILE; | |
}; | |
return VolatileTag; | |
})(RevisionTag))(); | |
var CURRENT_TAG = new ((function (_DirtyableTag) { | |
babelHelpers.inherits(CurrentTag, _DirtyableTag); | |
function CurrentTag() { | |
_DirtyableTag.apply(this, arguments); | |
} | |
CurrentTag.prototype.value = function value() { | |
return $REVISION; | |
}; | |
return CurrentTag; | |
})(DirtyableTag))(); | |
var CachedReference = (function () { | |
function CachedReference() { | |
this.lastRevision = null; | |
this.lastValue = null; | |
} | |
CachedReference.prototype.value = function value() { | |
var tag = this.tag; | |
var lastRevision = this.lastRevision; | |
var 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) { | |
babelHelpers.inherits(MapperReference, _CachedReference); | |
function MapperReference(reference, mapper) { | |
_CachedReference.call(this); | |
this.tag = reference.tag; | |
this.reference = reference; | |
this.mapper = mapper; | |
} | |
MapperReference.prototype.compute = function compute() { | |
var reference = this.reference; | |
var 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) { | |
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; | |
var 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; | |
} | |
var ConstReference = (function () { | |
function ConstReference(inner) { | |
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; | |
} | |
var ListItem = (function (_ListNode) { | |
babelHelpers.inherits(ListItem, _ListNode); | |
function ListItem(iterable, result) { | |
_ListNode.call(this, iterable.valueReferenceFor(result)); | |
this.retained = false; | |
this.seen = false; | |
this.key = result.key; | |
this.iterable = iterable; | |
this.memo = iterable.memoReferenceFor(result); | |
} | |
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; | |
})(_glimmerUtil.ListNode); | |
var IterationArtifacts = (function () { | |
function IterationArtifacts(iterable) { | |
this.map = _glimmerUtil.dict(); | |
this.list = new _glimmerUtil.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; | |
var list = this.list; | |
var 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; | |
var list = this.list; | |
var 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) { | |
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; | |
var artifacts = _ref.artifacts; | |
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; | |
var 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; | |
var current = this.current; | |
var 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; | |
var current = this.current; | |
current = _glimmerUtil.expect(current, 'BUG: current is empty'); | |
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; | |
var artifacts = this.artifacts; | |
var 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; | |
var target = this.target; | |
var 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; | |
var target = this.target; | |
var 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.DirtyableTag = DirtyableTag; | |
exports.combineTagged = combineTagged; | |
exports.combineSlice = combineSlice; | |
exports.combine = combine; | |
exports.CachedTag = CachedTag; | |
exports.UpdatableTag = UpdatableTag; | |
exports.CONSTANT_TAG = CONSTANT_TAG; | |
exports.VOLATILE_TAG = VOLATILE_TAG; | |
exports.CURRENT_TAG = CURRENT_TAG; | |
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,_glimmerUtil,_glimmerReference,_glimmerWireFormat){'use strict';var PrimitiveReference=(function(_ConstReference){babelHelpers.inherits(PrimitiveReference,_ConstReference);function PrimitiveReference(value){_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;})(_glimmerReference.ConstReference);var StringReference=(function(_PrimitiveReference){babelHelpers.inherits(StringReference,_PrimitiveReference);function StringReference(){_PrimitiveReference.apply(this,arguments);this.lengthReference = null;}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){babelHelpers.inherits(ValueReference,_PrimitiveReference2);function ValueReference(value){_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){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;})();var Constants=(function(){function Constants(){ // `0` means NULL | |
this.references = [];this.strings = [];this.expressions = [];this.arrays = [];this.blocks = [];this.functions = [];this.others = [];this.NULL_REFERENCE = this.reference(NULL_REFERENCE);this.UNDEFINED_REFERENCE = this.reference(UNDEFINED_REFERENCE);}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.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.expression = function expression(value){var index=this.expressions.length;this.expressions.push(value);return index + 1;};Constants.prototype.getArray = function getArray(value){return this.arrays[value - 1];};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(_block2){var index=this.blocks.length;this.blocks.push(_block2);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 AppendOpcodes=(function(){function AppendOpcodes(){this.evaluateOpcode = _glimmerUtil.fillNulls(51 /* EvaluatePartial */ + 1);}AppendOpcodes.prototype.add = function add(name,evaluate){this.evaluateOpcode[name] = evaluate;};AppendOpcodes.prototype.evaluate = function evaluate(vm,opcode){var func=this.evaluateOpcode[opcode.type];func(vm,opcode);};return AppendOpcodes;})();var APPEND_OPCODES=new AppendOpcodes();var AbstractOpcode=(function(){function AbstractOpcode(){_glimmerUtil.initializeGuid(this);}AbstractOpcode.prototype.toJSON = function toJSON(){return {guid:this._guid,type:this.type};};return AbstractOpcode;})();var UpdatingOpcode=(function(_AbstractOpcode){babelHelpers.inherits(UpdatingOpcode,_AbstractOpcode);function UpdatingOpcode(){_AbstractOpcode.apply(this,arguments);this.next = null;this.prev = null;}return UpdatingOpcode;})(AbstractOpcode);APPEND_OPCODES.add(20, /* OpenBlock */function(vm,_ref){var _getBlock=_ref.op1;var _args=_ref.op2;var inner=vm.constants.getOther(_getBlock);var rawArgs=vm.constants.getExpression(_args);var args=null;var block=inner.evaluate(vm);if(block){args = rawArgs.evaluate(vm);} // FIXME: can we avoid doing this when we don't have a block? | |
vm.pushCallerScope();if(block){vm.invokeBlock(block,args || null);}});APPEND_OPCODES.add(21, /* CloseBlock */function(vm){return vm.popScope();});APPEND_OPCODES.add(0, /* PushChildScope */function(vm){return vm.pushChildScope();});APPEND_OPCODES.add(1, /* PopScope */function(vm){return vm.popScope();});APPEND_OPCODES.add(2, /* PushDynamicScope */function(vm){return vm.pushDynamicScope();});APPEND_OPCODES.add(3, /* PopDynamicScope */function(vm){return vm.popDynamicScope();});APPEND_OPCODES.add(4, /* Put */function(vm,_ref2){var reference=_ref2.op1;vm.frame.setOperand(vm.constants.getReference(reference));});APPEND_OPCODES.add(5, /* EvaluatePut */function(vm,_ref3){var expression=_ref3.op1;var expr=vm.constants.getExpression(expression);vm.evaluateOperand(expr);});APPEND_OPCODES.add(6, /* PutArgs */function(vm,_ref4){var args=_ref4.op1;vm.evaluateArgs(vm.constants.getExpression(args));});APPEND_OPCODES.add(7, /* BindPositionalArgs */function(vm,_ref5){var _symbols=_ref5.op1;var symbols=vm.constants.getArray(_symbols);vm.bindPositionalArgs(symbols);});APPEND_OPCODES.add(8, /* BindNamedArgs */function(vm,_ref6){var _names=_ref6.op1;var _symbols=_ref6.op2;var names=vm.constants.getArray(_names);var symbols=vm.constants.getArray(_symbols);vm.bindNamedArgs(names,symbols);});APPEND_OPCODES.add(9, /* BindBlocks */function(vm,_ref7){var _names=_ref7.op1;var _symbols=_ref7.op2;var names=vm.constants.getArray(_names);var symbols=vm.constants.getArray(_symbols);vm.bindBlocks(names,symbols);});APPEND_OPCODES.add(10, /* BindPartialArgs */function(vm,_ref8){var symbol=_ref8.op1;vm.bindPartialArgs(symbol);});APPEND_OPCODES.add(11, /* BindCallerScope */function(vm){return vm.bindCallerScope();});APPEND_OPCODES.add(12, /* BindDynamicScope */function(vm,_ref9){var _names=_ref9.op1;var names=vm.constants.getArray(_names);vm.bindDynamicScope(names);});APPEND_OPCODES.add(13, /* Enter */function(vm,_ref10){var start=_ref10.op1;var end=_ref10.op2;return vm.enter(start,end);});APPEND_OPCODES.add(14, /* Exit */function(vm){return vm.exit();});APPEND_OPCODES.add(15, /* Evaluate */function(vm,_ref11){var _block=_ref11.op1;var block=vm.constants.getBlock(_block);var args=vm.frame.getArgs();vm.invokeBlock(block,args);});APPEND_OPCODES.add(16, /* Jump */function(vm,_ref12){var target=_ref12.op1;return vm.goto(target);});APPEND_OPCODES.add(17, /* JumpIf */function(vm,_ref13){var target=_ref13.op1;var reference=vm.frame.getCondition();if(_glimmerReference.isConst(reference)){if(reference.value()){vm.goto(target);}}else {var cache=new _glimmerReference.ReferenceCache(reference);if(cache.peek()){vm.goto(target);}vm.updateWith(new Assert(cache));}});APPEND_OPCODES.add(18, /* JumpUnless */function(vm,_ref14){var target=_ref14.op1;var reference=vm.frame.getCondition();if(_glimmerReference.isConst(reference)){if(!reference.value()){vm.goto(target);}}else {var cache=new _glimmerReference.ReferenceCache(reference);if(!cache.peek()){vm.goto(target);}vm.updateWith(new Assert(cache));}});var ConstTest=function(ref,_env){return new _glimmerReference.ConstReference(!!ref.value());};var SimpleTest=function(ref,_env){return ref;};var EnvironmentTest=function(ref,env){return env.toConditionalReference(ref);};APPEND_OPCODES.add(19, /* Test */function(vm,_ref15){var _func=_ref15.op1;var operand=vm.frame.getOperand();var func=vm.constants.getFunction(_func);vm.frame.setCondition(func(operand,vm.env));});var Assert=(function(_UpdatingOpcode){babelHelpers.inherits(Assert,_UpdatingOpcode);function Assert(cache){_UpdatingOpcode.call(this);this.type = "assert";this.tag = cache.tag;this.cache = cache;}Assert.prototype.evaluate = function evaluate(vm){var cache=this.cache;if(_glimmerReference.isModified(cache.revalidate())){vm.throw();}};Assert.prototype.toJSON = function toJSON(){var type=this.type;var _guid=this._guid;var cache=this.cache;var expected=undefined;try{expected = JSON.stringify(cache.peek());}catch(e) {expected = String(cache.peek());}return {guid:_guid,type:type,args:[],details:{expected:expected}};};return Assert;})(UpdatingOpcode);var JumpIfNotModifiedOpcode=(function(_UpdatingOpcode2){babelHelpers.inherits(JumpIfNotModifiedOpcode,_UpdatingOpcode2);function JumpIfNotModifiedOpcode(tag,target){_UpdatingOpcode2.call(this);this.target = target;this.type = "jump-if-not-modified";this.tag = tag;this.lastRevision = tag.value();}JumpIfNotModifiedOpcode.prototype.evaluate = function evaluate(vm){var tag=this.tag;var target=this.target;var 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 {guid:this._guid,type:this.type,args:[JSON.stringify(this.target.inspect())]};};return JumpIfNotModifiedOpcode;})(UpdatingOpcode);var DidModifyOpcode=(function(_UpdatingOpcode3){babelHelpers.inherits(DidModifyOpcode,_UpdatingOpcode3);function DidModifyOpcode(target){_UpdatingOpcode3.call(this);this.target = target;this.type = "did-modify";this.tag = _glimmerReference.CONSTANT_TAG;}DidModifyOpcode.prototype.evaluate = function evaluate(){this.target.didModify();};return DidModifyOpcode;})(UpdatingOpcode);var LabelOpcode=(function(){function LabelOpcode(label){this.tag = _glimmerReference.CONSTANT_TAG;this.type = "label";this.label = null;this.prev = null;this.next = null;_glimmerUtil.initializeGuid(this);if(label)this.label = label;}LabelOpcode.prototype.evaluate = function evaluate(){};LabelOpcode.prototype.inspect = function inspect(){return this.label + ' [' + this._guid + ']';};LabelOpcode.prototype.toJSON = function toJSON(){return {guid:this._guid,type:this.type,args:[JSON.stringify(this.inspect())]};};return LabelOpcode;})();var EMPTY_ARRAY=_glimmerUtil.HAS_NATIVE_WEAKMAP?Object.freeze([]):[];var EMPTY_DICT=_glimmerUtil.HAS_NATIVE_WEAKMAP?Object.freeze(_glimmerUtil.dict()):_glimmerUtil.dict();var CompiledPositionalArgs=(function(){function CompiledPositionalArgs(values){this.values = values;this.length = values.length;}CompiledPositionalArgs.create = function create(values){if(values.length){return new this(values);}else {return COMPILED_EMPTY_POSITIONAL_ARGS;}};CompiledPositionalArgs.empty = function empty(){return COMPILED_EMPTY_POSITIONAL_ARGS;};CompiledPositionalArgs.prototype.evaluate = function evaluate(vm){var values=this.values;var length=this.length;var references=new Array(length);for(var i=0;i < length;i++) {references[i] = values[i].evaluate(vm);}return EvaluatedPositionalArgs.create(references);};CompiledPositionalArgs.prototype.toJSON = function toJSON(){return '[' + this.values.map(function(value){return value.toJSON();}).join(", ") + ']';};return CompiledPositionalArgs;})();var COMPILED_EMPTY_POSITIONAL_ARGS=new ((function(_CompiledPositionalArgs){babelHelpers.inherits(_class,_CompiledPositionalArgs);function _class(){_CompiledPositionalArgs.call(this,EMPTY_ARRAY);}_class.prototype.evaluate = function evaluate(_vm){return EVALUATED_EMPTY_POSITIONAL_ARGS;};_class.prototype.toJSON = function toJSON(){return '<EMPTY>';};return _class;})(CompiledPositionalArgs))();var EvaluatedPositionalArgs=(function(){function EvaluatedPositionalArgs(values){this.values = values;this.tag = _glimmerReference.combineTagged(values);this.length = values.length;}EvaluatedPositionalArgs.create = function create(values){return new this(values);};EvaluatedPositionalArgs.empty = function empty(){return EVALUATED_EMPTY_POSITIONAL_ARGS;};EvaluatedPositionalArgs.prototype.at = function at(index){var values=this.values;var length=this.length;return index < length?values[index]:UNDEFINED_REFERENCE;};EvaluatedPositionalArgs.prototype.value = function value(){var values=this.values;var length=this.length;var ret=new Array(length);for(var i=0;i < length;i++) {ret[i] = values[i].value();}return ret;};return EvaluatedPositionalArgs;})();var EVALUATED_EMPTY_POSITIONAL_ARGS=new ((function(_EvaluatedPositionalArgs){babelHelpers.inherits(_class2,_EvaluatedPositionalArgs);function _class2(){_EvaluatedPositionalArgs.call(this,EMPTY_ARRAY);}_class2.prototype.at = function at(){return UNDEFINED_REFERENCE;};_class2.prototype.value = function value(){return this.values;};return _class2;})(EvaluatedPositionalArgs))();var CompiledNamedArgs=(function(){function CompiledNamedArgs(keys,values){this.keys = keys;this.values = values;this.length = keys.length;_glimmerUtil.assert(keys.length === values.length,'Keys and values do not have the same length');}CompiledNamedArgs.empty = function empty(){return COMPILED_EMPTY_NAMED_ARGS;};CompiledNamedArgs.create = function create(map){var keys=Object.keys(map);var length=keys.length;if(length > 0){var values=[];for(var i=0;i < length;i++) {values[i] = map[keys[i]];}return new this(keys,values);}else {return COMPILED_EMPTY_NAMED_ARGS;}};CompiledNamedArgs.prototype.evaluate = function evaluate(vm){var keys=this.keys;var values=this.values;var length=this.length;var evaluated=new Array(length);for(var i=0;i < length;i++) {evaluated[i] = values[i].evaluate(vm);}return new EvaluatedNamedArgs(keys,evaluated);};CompiledNamedArgs.prototype.toJSON = function toJSON(){var keys=this.keys;var values=this.values;var inner=keys.map(function(key,i){return key + ': ' + values[i].toJSON();}).join(", ");return '{' + inner + '}';};return CompiledNamedArgs;})();var COMPILED_EMPTY_NAMED_ARGS=new ((function(_CompiledNamedArgs){babelHelpers.inherits(_class3,_CompiledNamedArgs);function _class3(){_CompiledNamedArgs.call(this,EMPTY_ARRAY,EMPTY_ARRAY);}_class3.prototype.evaluate = function evaluate(_vm){return EVALUATED_EMPTY_NAMED_ARGS;};_class3.prototype.toJSON = function toJSON(){return '<EMPTY>';};return _class3;})(CompiledNamedArgs))();var EvaluatedNamedArgs=(function(){function EvaluatedNamedArgs(keys,values){var _map=arguments.length <= 2 || arguments[2] === undefined?null:arguments[2];this.keys = keys;this.values = values;this._map = _map;this.tag = _glimmerReference.combineTagged(values);this.length = keys.length;_glimmerUtil.assert(keys.length === values.length,'Keys and values do not have the same length');}EvaluatedNamedArgs.create = function create(map){var keys=Object.keys(map);var length=keys.length;if(length > 0){var values=new Array(length);for(var i=0;i < length;i++) {values[i] = map[keys[i]];}return new this(keys,values,map);}else {return EVALUATED_EMPTY_NAMED_ARGS;}};EvaluatedNamedArgs.empty = function empty(){return EVALUATED_EMPTY_NAMED_ARGS;};EvaluatedNamedArgs.prototype.get = function get(key){var keys=this.keys;var values=this.values;var index=keys.indexOf(key);return index === -1?UNDEFINED_REFERENCE:values[index];};EvaluatedNamedArgs.prototype.has = function has(key){return this.keys.indexOf(key) !== -1;};EvaluatedNamedArgs.prototype.value = function value(){var keys=this.keys;var values=this.values;var out=_glimmerUtil.dict();for(var i=0;i < keys.length;i++) {var key=keys[i];var ref=values[i];out[key] = ref.value();}return out;};babelHelpers.createClass(EvaluatedNamedArgs,[{key:'map',get:function(){var map=this._map;if(map){return map;}map = this._map = _glimmerUtil.dict();var keys=this.keys;var values=this.values;var length=this.length;for(var i=0;i < length;i++) {map[keys[i]] = values[i];}return map;}}]);return EvaluatedNamedArgs;})();var EVALUATED_EMPTY_NAMED_ARGS=new ((function(_EvaluatedNamedArgs){babelHelpers.inherits(_class4,_EvaluatedNamedArgs);function _class4(){_EvaluatedNamedArgs.call(this,EMPTY_ARRAY,EMPTY_ARRAY,EMPTY_DICT);}_class4.prototype.get = function get(){return UNDEFINED_REFERENCE;};_class4.prototype.has = function has(_key){return false;};_class4.prototype.value = function value(){return EMPTY_DICT;};return _class4;})(EvaluatedNamedArgs))();var EMPTY_BLOCKS={default:null,inverse:null};var CompiledArgs=(function(){function CompiledArgs(positional,named,blocks){this.positional = positional;this.named = named;this.blocks = blocks;this.type = "compiled-args";}CompiledArgs.create = function create(positional,named,blocks){if(positional === COMPILED_EMPTY_POSITIONAL_ARGS && named === COMPILED_EMPTY_NAMED_ARGS && blocks === EMPTY_BLOCKS){return this.empty();}else {return new this(positional,named,blocks);}};CompiledArgs.empty = function empty(){return COMPILED_EMPTY_ARGS;};CompiledArgs.prototype.evaluate = function evaluate(vm){var positional=this.positional;var named=this.named;var blocks=this.blocks;return EvaluatedArgs.create(positional.evaluate(vm),named.evaluate(vm),blocks);};return CompiledArgs;})();var COMPILED_EMPTY_ARGS=new ((function(_CompiledArgs){babelHelpers.inherits(_class5,_CompiledArgs);function _class5(){_CompiledArgs.call(this,COMPILED_EMPTY_POSITIONAL_ARGS,COMPILED_EMPTY_NAMED_ARGS,EMPTY_BLOCKS);}_class5.prototype.evaluate = function evaluate(_vm){return EMPTY_EVALUATED_ARGS;};return _class5;})(CompiledArgs))();var EvaluatedArgs=(function(){function EvaluatedArgs(positional,named,blocks){this.positional = positional;this.named = named;this.blocks = blocks;this.tag = _glimmerReference.combineTagged([positional,named]);}EvaluatedArgs.empty = function empty(){return EMPTY_EVALUATED_ARGS;};EvaluatedArgs.create = function create(positional,named,blocks){return new this(positional,named,blocks);};EvaluatedArgs.positional = function positional(values){var blocks=arguments.length <= 1 || arguments[1] === undefined?EMPTY_BLOCKS:arguments[1];return new this(EvaluatedPositionalArgs.create(values),EVALUATED_EMPTY_NAMED_ARGS,blocks);};EvaluatedArgs.named = function named(map){var blocks=arguments.length <= 1 || arguments[1] === undefined?EMPTY_BLOCKS:arguments[1];return new this(EVALUATED_EMPTY_POSITIONAL_ARGS,EvaluatedNamedArgs.create(map),blocks);};return EvaluatedArgs;})();var EMPTY_EVALUATED_ARGS=new EvaluatedArgs(EVALUATED_EMPTY_POSITIONAL_ARGS,EVALUATED_EMPTY_NAMED_ARGS,EMPTY_BLOCKS);APPEND_OPCODES.add(22, /* PutDynamicComponent */function(vm){var reference=vm.frame.getOperand();var cache=_glimmerReference.isConst(reference)?undefined:new _glimmerReference.ReferenceCache(reference);var definition=cache?cache.peek():reference.value();vm.frame.setImmediate(definition);if(cache){vm.updateWith(new Assert(cache));}});APPEND_OPCODES.add(23, /* PutComponent */function(vm,_ref16){var _component=_ref16.op1;var definition=vm.constants.getOther(_component);vm.frame.setImmediate(definition);});APPEND_OPCODES.add(24, /* OpenComponent */function(vm,_ref17){var _args=_ref17.op1;var _shadow=_ref17.op2;var rawArgs=vm.constants.getExpression(_args);var shadow=vm.constants.getBlock(_shadow);var definition=vm.frame.getImmediate();var dynamicScope=vm.pushDynamicScope();var callerScope=vm.scope();var manager=definition.manager;var args=manager.prepareArgs(definition,rawArgs.evaluate(vm),dynamicScope);var hasDefaultBlock=!!args.blocks.default; // TODO Cleanup? | |
var component=manager.create(vm.env,definition,args,dynamicScope,vm.getSelf(),hasDefaultBlock);var destructor=manager.getDestructor(component);if(destructor)vm.newDestroyable(destructor);var layout=manager.layoutFor(definition,component,vm.env);var selfRef=manager.getSelf(component);vm.beginCacheGroup();vm.stack().pushSimpleBlock();vm.pushRootScope(selfRef,layout.symbols);vm.invokeLayout(args,layout,callerScope,component,manager,shadow);vm.updateWith(new UpdateComponentOpcode(definition.name,component,manager,args,dynamicScope));}); // export class DidCreateElementOpcode extends Opcode { | |
// public type = "did-create-element"; | |
// evaluate(vm: VM) { | |
// let manager = vm.frame.getManager(); | |
// let component = vm.frame.getComponent(); | |
// let action = 'DidCreateElementOpcode#evaluate'; | |
// manager.didCreateElement(component, vm.stack().expectConstructing(action), vm.stack().expectOperations(action)); | |
// } | |
// toJSON(): OpcodeJSON { | |
// return { | |
// guid: this._guid, | |
// type: this.type, | |
// args: ["$ARGS"] | |
// }; | |
// } | |
// } | |
APPEND_OPCODES.add(25, /* DidCreateElement */function(vm){var manager=vm.frame.getManager();var component=vm.frame.getComponent();var action='DidCreateElementOpcode#evaluate';manager.didCreateElement(component,vm.stack().expectConstructing(action),vm.stack().expectOperations(action));}); // export class ShadowAttributesOpcode extends Opcode { | |
// public type = "shadow-attributes"; | |
// evaluate(vm: VM) { | |
// let shadow = vm.frame.getShadow(); | |
// vm.pushCallerScope(); | |
// if (!shadow) return; | |
// vm.invokeBlock(shadow, EvaluatedArgs.empty()); | |
// } | |
// toJSON(): OpcodeJSON { | |
// return { | |
// guid: this._guid, | |
// type: this.type, | |
// args: ["$ARGS"] | |
// }; | |
// } | |
// } | |
// Slow path for non-specialized component invocations. Uses an internal | |
// named lookup on the args. | |
APPEND_OPCODES.add(26, /* ShadowAttributes */function(vm){var shadow=vm.frame.getShadow();vm.pushCallerScope();if(!shadow)return;vm.invokeBlock(shadow,EvaluatedArgs.empty());}); // export class DidRenderLayoutOpcode extends Opcode { | |
// public type = "did-render-layout"; | |
// evaluate(vm: VM) { | |
// let manager = vm.frame.getManager(); | |
// let component = vm.frame.getComponent(); | |
// let bounds = vm.stack().popBlock(); | |
// manager.didRenderLayout(component, bounds); | |
// vm.env.didCreate(component, manager); | |
// vm.updateWith(new DidUpdateLayoutOpcode(manager, component, bounds)); | |
// } | |
// } | |
APPEND_OPCODES.add(27, /* DidRenderLayout */function(vm){var manager=vm.frame.getManager();var component=vm.frame.getComponent();var bounds=vm.stack().popBlock();manager.didRenderLayout(component,bounds);vm.env.didCreate(component,manager);vm.updateWith(new DidUpdateLayoutOpcode(manager,component,bounds));}); // export class CloseComponentOpcode extends Opcode { | |
// public type = "close-component"; | |
// evaluate(vm: VM) { | |
// vm.popScope(); | |
// vm.popDynamicScope(); | |
// vm.commitCacheGroup(); | |
// } | |
// } | |
APPEND_OPCODES.add(28, /* CloseComponent */function(vm){vm.popScope();vm.popDynamicScope();vm.commitCacheGroup();});var UpdateComponentOpcode=(function(_UpdatingOpcode4){babelHelpers.inherits(UpdateComponentOpcode,_UpdatingOpcode4);function UpdateComponentOpcode(name,component,manager,args,dynamicScope){_UpdatingOpcode4.call(this);this.name = name;this.component = component;this.manager = manager;this.args = args;this.dynamicScope = dynamicScope;this.type = "update-component";var componentTag=manager.getTag(component);if(componentTag){this.tag = _glimmerReference.combine([args.tag,componentTag]);}else {this.tag = args.tag;}}UpdateComponentOpcode.prototype.evaluate = function evaluate(_vm){var component=this.component;var manager=this.manager;var args=this.args;var dynamicScope=this.dynamicScope;manager.update(component,args,dynamicScope);};UpdateComponentOpcode.prototype.toJSON = function toJSON(){return {guid:this._guid,type:this.type,args:[JSON.stringify(this.name)]};};return UpdateComponentOpcode;})(UpdatingOpcode);var DidUpdateLayoutOpcode=(function(_UpdatingOpcode5){babelHelpers.inherits(DidUpdateLayoutOpcode,_UpdatingOpcode5);function DidUpdateLayoutOpcode(manager,component,bounds){_UpdatingOpcode5.call(this);this.manager = manager;this.component = component;this.bounds = bounds;this.type = "did-update-layout";this.tag = _glimmerReference.CONSTANT_TAG;}DidUpdateLayoutOpcode.prototype.evaluate = function evaluate(vm){var manager=this.manager;var component=this.component;var bounds=this.bounds;manager.didUpdateLayout(component,bounds);vm.env.didUpdate(component,manager);};return DidUpdateLayoutOpcode;})(UpdatingOpcode);var Cursor=function Cursor(element,nextSibling){this.element = element;this.nextSibling = nextSibling;};var ConcreteBounds=(function(){function ConcreteBounds(parentNode,first,last){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){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 moveBounds(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 isSafeString(value){return !!value && typeof value['toHTML'] === 'function';}function isNode(value){return value !== null && typeof value === 'object' && typeof value['nodeType'] === 'number';}function isString(value){return typeof value === 'string';}var Upsert=function Upsert(bounds){this.bounds = bounds;};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 _glimmerUtil.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 _glimmerUtil.unreachable();}var TextUpsert=(function(_Upsert){babelHelpers.inherits(TextUpsert,_Upsert);TextUpsert.insert = function insert(dom,cursor,value){var textNode=dom.createTextNode(value);dom.insertBefore(cursor.element,textNode,cursor.nextSibling);var bounds=new SingleNodeBounds(cursor.element,textNode);return new TextUpsert(bounds,textNode);};function TextUpsert(bounds,textNode){_Upsert.call(this,bounds);this.textNode = textNode;}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){babelHelpers.inherits(HTMLUpsert,_Upsert2);function HTMLUpsert(){_Upsert2.apply(this,arguments);}HTMLUpsert.insert = function insert(dom,cursor,value){var bounds=dom.insertHTMLBefore(cursor.element,value,cursor.nextSibling);return new HTMLUpsert(bounds);};HTMLUpsert.prototype.update = function update(dom,value){if(isString(value)){var bounds=this.bounds;var parentElement=bounds.parentElement();var nextSibling=clear(bounds);this.bounds = dom.insertHTMLBefore(parentElement,nextSibling,value);return true;}else {return false;}};return HTMLUpsert;})(Upsert);var SafeStringUpsert=(function(_Upsert3){babelHelpers.inherits(SafeStringUpsert,_Upsert3);function SafeStringUpsert(bounds,lastStringValue){_Upsert3.call(this,bounds);this.lastStringValue = lastStringValue;}SafeStringUpsert.insert = function insert(dom,cursor,value){var stringValue=value.toHTML();var bounds=dom.insertHTMLBefore(cursor.element,stringValue,cursor.nextSibling);return new SafeStringUpsert(bounds,stringValue);};SafeStringUpsert.prototype.update = function update(dom,value){if(isSafeString(value)){var stringValue=value.toHTML();if(stringValue !== this.lastStringValue){var bounds=this.bounds;var parentElement=bounds.parentElement();var nextSibling=clear(bounds);this.bounds = dom.insertHTMLBefore(parentElement,nextSibling,stringValue);this.lastStringValue = stringValue;}return true;}else {return false;}};return SafeStringUpsert;})(Upsert);var NodeUpsert=(function(_Upsert4){babelHelpers.inherits(NodeUpsert,_Upsert4);function NodeUpsert(){_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=this.bounds;var parentElement=bounds.parentElement();var nextSibling=clear(bounds);this.bounds = dom.insertNodeBefore(parentElement,value,nextSibling);return true;}else {return false;}};return NodeUpsert;})(Upsert);var COMPONENT_DEFINITION_BRAND='COMPONENT DEFINITION [id=e59c754e-61eb-4392-8c4a-2c0ac72bfcd4]';function isComponentDefinition(obj){return typeof obj === 'object' && obj && obj[COMPONENT_DEFINITION_BRAND];}var ComponentDefinition=function ComponentDefinition(name,manager,ComponentClass){this[COMPONENT_DEFINITION_BRAND] = true;this.name = name;this.manager = manager;this.ComponentClass = ComponentClass;};var CompiledExpression=(function(){function CompiledExpression(){}CompiledExpression.prototype.toJSON = function toJSON(){return 'UNIMPL: ' + this.type.toUpperCase();};return CompiledExpression;})();APPEND_OPCODES.add(29, /* Text */function(vm,_ref18){var text=_ref18.op1;vm.stack().appendText(vm.constants.getString(text));});APPEND_OPCODES.add(30, /* Comment */function(vm,_ref19){var text=_ref19.op1;vm.stack().appendComment(vm.constants.getString(text));});APPEND_OPCODES.add(32, /* OpenElement */function(vm,_ref20){var tag=_ref20.op1;vm.stack().openElement(vm.constants.getString(tag));});APPEND_OPCODES.add(33, /* PushRemoteElement */function(vm){var reference=vm.frame.getOperand();var cache=_glimmerReference.isConst(reference)?undefined:new _glimmerReference.ReferenceCache(reference);var element=cache?cache.peek():reference.value();vm.stack().pushRemoteElement(element);if(cache){vm.updateWith(new Assert(cache));}});APPEND_OPCODES.add(34, /* PopRemoteElement */function(vm){return vm.stack().popRemoteElement();});APPEND_OPCODES.add(35, /* OpenComponentElement */function(vm,_ref21){var _tag=_ref21.op1;var tag=vm.constants.getString(_tag);vm.stack().openElement(tag,new ComponentElementOperations(vm.env));});APPEND_OPCODES.add(36, /* OpenDynamicElement */function(vm){var tagName=vm.frame.getOperand().value();vm.stack().openElement(tagName);});var ClassList=(function(){function ClassList(){this.list = null;this.isConst = true;}ClassList.prototype.append = function append(reference){var list=this.list;var isConst$$=this.isConst;if(list === null)list = this.list = [];list.push(reference);this.isConst = isConst$$ && _glimmerReference.isConst(reference);};ClassList.prototype.toReference = function toReference(){var list=this.list;var isConst$$=this.isConst;if(!list)return NULL_REFERENCE;if(isConst$$)return PrimitiveReference.create(toClassName(list));return new ClassListReference(list);};return ClassList;})();var ClassListReference=(function(_CachedReference){babelHelpers.inherits(ClassListReference,_CachedReference);function ClassListReference(list){_CachedReference.call(this);this.list = [];this.tag = _glimmerReference.combineTagged(list);this.list = list;}ClassListReference.prototype.compute = function compute(){return toClassName(this.list);};return ClassListReference;})(_glimmerReference.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){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;var 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){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;var 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;var attributes=this.attributes;if(!attributeNames){attributeNames = this.attributeNames = [];attributes = this.attributes = [];}attributeNames.push(name);_glimmerUtil.unwrap(attributes).push(attribute);};return ComponentElementOperations;})();APPEND_OPCODES.add(37, /* FlushElement */function(vm){var stack=vm.stack();var action='FlushElementOpcode#evaluate';stack.expectOperations(action).flush(stack.expectConstructing(action),vm);stack.flushElement();});APPEND_OPCODES.add(38, /* CloseElement */function(vm){return vm.stack().closeElement();});APPEND_OPCODES.add(39, /* PopElement */function(vm){return vm.stack().popElement();});APPEND_OPCODES.add(40, /* StaticAttr */function(vm,_ref22){var _name=_ref22.op1;var _value=_ref22.op2;var _namespace=_ref22.op3;var name=vm.constants.getString(_name);var value=vm.constants.getString(_value);if(_namespace){var namespace=vm.constants.getString(_namespace);vm.stack().setStaticAttributeNS(namespace,name,value);}else {vm.stack().setStaticAttribute(name,value);}});APPEND_OPCODES.add(41, /* Modifier */function(vm,_ref23){var _name=_ref23.op1;var _manager=_ref23.op2;var _args=_ref23.op3;var manager=vm.constants.getOther(_manager);var rawArgs=vm.constants.getExpression(_args);var stack=vm.stack();var element=stack.constructing;var updateOperations=stack.updateOperations;var args=rawArgs.evaluate(vm);var dynamicScope=vm.dynamicScope();var modifier=manager.create(element,args,dynamicScope,updateOperations);vm.env.scheduleInstallModifier(modifier,manager);var destructor=manager.getDestructor(modifier);if(destructor){vm.newDestroyable(destructor);}vm.updateWith(new UpdateModifierOpcode(manager,modifier,args));});var UpdateModifierOpcode=(function(_UpdatingOpcode6){babelHelpers.inherits(UpdateModifierOpcode,_UpdatingOpcode6);function UpdateModifierOpcode(manager,modifier,args){_UpdatingOpcode6.call(this);this.manager = manager;this.modifier = modifier;this.args = args;this.type = "update-modifier";this.tag = args.tag;this.lastUpdated = args.tag.value();}UpdateModifierOpcode.prototype.evaluate = function evaluate(vm){var manager=this.manager;var modifier=this.modifier;var tag=this.tag;var 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,args:[JSON.stringify(this.args)]};};return UpdateModifierOpcode;})(UpdatingOpcode);var StaticAttribute=(function(){function StaticAttribute(element,name,value,namespace){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){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;var cache=this.cache;var value=_glimmerUtil.expect(cache,'must patch after flush').revalidate();if(_glimmerReference.isModified(value)){this.attributeManager.updateAttribute(env,element,value,this.namespace);}};DynamicAttribute.prototype.flush = function flush(env){var reference=this.reference;var element=this.element;if(_glimmerReference.isConst(reference)){var value=reference.value();this.attributeManager.setAttribute(env,element,value,this.namespace);return null;}else {var cache=this.cache = new _glimmerReference.ReferenceCache(reference);var value=cache.peek();this.attributeManager.setAttribute(env,element,value,this.namespace);return new PatchElementOpcode(this);}};DynamicAttribute.prototype.toJSON = function toJSON(){var element=this.element;var namespace=this.namespace;var name=this.name;var cache=this.cache;var formattedElement=formatElement(element);var lastValue=_glimmerUtil.expect(cache,'must serialize after flush').peek();if(namespace){return {element:formattedElement,type:'attribute',namespace:namespace,name:name,lastValue:lastValue};}return {element:formattedElement,type:'attribute',namespace:namespace === undefined?null:namespace,name:name,lastValue:lastValue};};return DynamicAttribute;})();function formatElement(element){return JSON.stringify('<' + element.tagName.toLowerCase() + ' />');}APPEND_OPCODES.add(42, /* DynamicAttrNS */function(vm,_ref24){var _name=_ref24.op1;var _namespace=_ref24.op2;var trusting=_ref24.op3;var name=vm.constants.getString(_name);var namespace=vm.constants.getString(_namespace);var reference=vm.frame.getOperand();vm.stack().setDynamicAttributeNS(namespace,name,reference,!!trusting);});APPEND_OPCODES.add(43, /* DynamicAttr */function(vm,_ref25){var _name=_ref25.op1;var trusting=_ref25.op2;var name=vm.constants.getString(_name);var reference=vm.frame.getOperand();vm.stack().setDynamicAttribute(name,reference,!!trusting);});var PatchElementOpcode=(function(_UpdatingOpcode7){babelHelpers.inherits(PatchElementOpcode,_UpdatingOpcode7);function PatchElementOpcode(operation){_UpdatingOpcode7.call(this);this.type = "patch-element";this.tag = operation.tag;this.operation = operation;}PatchElementOpcode.prototype.evaluate = function evaluate(vm){this.operation.patch(vm.env);};PatchElementOpcode.prototype.toJSON = function toJSON(){var _guid=this._guid;var type=this.type;var operation=this.operation;return {guid:_guid,type:type,details:operation.toJSON()};};return PatchElementOpcode;})(UpdatingOpcode);var First=(function(){function First(node){this.node = node;}First.prototype.firstNode = function firstNode(){return this.node;};return First;})();var Last=(function(){function Last(node){this.node = node;}Last.prototype.lastNode = function lastNode(){return this.node;};return Last;})();var Fragment=(function(){function Fragment(bounds){this.bounds = bounds;}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){this.bounds = bounds;};return Fragment;})();var ElementStack=(function(){function ElementStack(env,parentNode,nextSibling){this.constructing = null;this.operations = null;this.elementStack = new _glimmerUtil.Stack();this.nextSiblingStack = new _glimmerUtil.Stack();this.blockStack = new _glimmerUtil.Stack();this.env = env;this.dom = env.getAppendOperations();this.updateOperations = env.getDOM();this.element = parentNode;this.nextSibling = nextSibling;this.defaultOperations = new SimpleElementOperations(env);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 _glimmerUtil.expect(this.constructing,method + ' should only be called while constructing an element');};ElementStack.prototype.expectOperations = function expectOperations(method){return _glimmerUtil.expect(this.operations,method + ' should only be called while constructing an element');};ElementStack.prototype.block = function block(){return _glimmerUtil.expect(this.blockStack.current,"Expected a current block tracker");};ElementStack.prototype.popElement = function popElement(){var elementStack=this.elementStack;var nextSiblingStack=this.nextSiblingStack;var topElement=elementStack.pop();nextSiblingStack.pop(); // LOGGER.debug(`-> element stack ${this.elementStack.toArray().map(e => e.tagName).join(', ')}`); | |
this.element = _glimmerUtil.expect(elementStack.current,"can't pop past the last element");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?false:arguments[1];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 _glimmerUtil.expect(this.blockStack.pop(),"Expected popBlock to return a block");};ElementStack.prototype.openElement = function openElement(tag){var operations=arguments.length <= 1 || arguments[1] === undefined?this.defaultOperations:arguments[1];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=_glimmerUtil.expect(this.constructing,'flushElement should only be called when constructing an element');this.dom.insertBefore(parent,element,this.nextSibling);this.constructing = null;this.operations = null;this.pushElement(element);this.block().openElement(element);};ElementStack.prototype.pushRemoteElement = function pushRemoteElement(element){this.pushElement(element);var tracker=new RemoteBlockTracker(element);this.pushBlockTracker(tracker,true);};ElementStack.prototype.popRemoteElement = function popRemoteElement(){this.popBlock();this.popElement();};ElementStack.prototype.pushElement = function pushElement(element){this.element = element;this.elementStack.push(element); // LOGGER.debug(`-> element stack ${this.elementStack.toArray().map(e => e.tagName).join(', ')}`); | |
this.nextSibling = null;this.nextSiblingStack.push(null);};ElementStack.prototype.newDestroyable = function newDestroyable(d){this.block().newDestroyable(d);};ElementStack.prototype.newBounds = function newBounds(bounds){this.block().newBounds(bounds);};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){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){if(this.nesting !== 0)return;if(!this.first){this.first = bounds;}this.last = bounds;};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){babelHelpers.inherits(RemoteBlockTracker,_SimpleBlockTracker);function RemoteBlockTracker(){_SimpleBlockTracker.apply(this,arguments);}RemoteBlockTracker.prototype.destroy = function destroy(){_SimpleBlockTracker.prototype.destroy.call(this);clear(this);};return RemoteBlockTracker;})(SimpleBlockTracker);var UpdatableBlockTracker=(function(_SimpleBlockTracker2){babelHelpers.inherits(UpdatableBlockTracker,_SimpleBlockTracker2);function UpdatableBlockTracker(){_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.destroyables = null;this.first = null;this.last = null;return nextSibling;};return UpdatableBlockTracker;})(SimpleBlockTracker);var BlockListTracker=(function(){function BlockListTracker(parent,boundList){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){_glimmerUtil.assert(false,'Cannot openElement directly inside a block list');};BlockListTracker.prototype.closeElement = function closeElement(){_glimmerUtil.assert(false,'Cannot closeElement directly inside a block list');};BlockListTracker.prototype.newNode = function newNode(_node){_glimmerUtil.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;})();var CompiledValue=(function(_CompiledExpression){babelHelpers.inherits(CompiledValue,_CompiledExpression);function CompiledValue(value){_CompiledExpression.call(this);this.type = "value";this.reference = PrimitiveReference.create(value);}CompiledValue.prototype.evaluate = function evaluate(_vm){return this.reference;};CompiledValue.prototype.toJSON = function toJSON(){return JSON.stringify(this.reference.value());};return CompiledValue;})(CompiledExpression);var CompiledHasBlock=(function(_CompiledExpression2){babelHelpers.inherits(CompiledHasBlock,_CompiledExpression2);function CompiledHasBlock(inner){_CompiledExpression2.call(this);this.inner = inner;this.type = "has-block";}CompiledHasBlock.prototype.evaluate = function evaluate(vm){var block=this.inner.evaluate(vm);return PrimitiveReference.create(!!block);};CompiledHasBlock.prototype.toJSON = function toJSON(){return 'has-block(' + this.inner.toJSON() + ')';};return CompiledHasBlock;})(CompiledExpression);var CompiledHasBlockParams=(function(_CompiledExpression3){babelHelpers.inherits(CompiledHasBlockParams,_CompiledExpression3);function CompiledHasBlockParams(inner){_CompiledExpression3.call(this);this.inner = inner;this.type = "has-block-params";}CompiledHasBlockParams.prototype.evaluate = function evaluate(vm){var block=this.inner.evaluate(vm);var hasLocals=block && block.symbolTable.getSymbols().locals;return PrimitiveReference.create(!!hasLocals);};CompiledHasBlockParams.prototype.toJSON = function toJSON(){return 'has-block-params(' + this.inner.toJSON() + ')';};return CompiledHasBlockParams;})(CompiledExpression);var CompiledGetBlockBySymbol=(function(){function CompiledGetBlockBySymbol(symbol,debug){this.symbol = symbol;this.debug = debug;}CompiledGetBlockBySymbol.prototype.evaluate = function evaluate(vm){return vm.scope().getBlock(this.symbol);};CompiledGetBlockBySymbol.prototype.toJSON = function toJSON(){return 'get-block($' + this.symbol + '(' + this.debug + '))';};return CompiledGetBlockBySymbol;})();var CompiledInPartialGetBlock=(function(){function CompiledInPartialGetBlock(symbol,name){this.symbol = symbol;this.name = name;}CompiledInPartialGetBlock.prototype.evaluate = function evaluate(vm){var symbol=this.symbol;var name=this.name;var args=vm.scope().getPartialArgs(symbol);return args.blocks[name];};CompiledInPartialGetBlock.prototype.toJSON = function toJSON(){return 'get-block($' + this.symbol + '($ARGS).' + this.name + '))';};return CompiledInPartialGetBlock;})();var CompiledBlock=function CompiledBlock(start,end){this.start = start;this.end = end;};var CompiledProgram=(function(_CompiledBlock){babelHelpers.inherits(CompiledProgram,_CompiledBlock);function CompiledProgram(start,end,symbols){_CompiledBlock.call(this,start,end);this.symbols = symbols;}return CompiledProgram;})(CompiledBlock);var Labels=(function(){function Labels(){this.labels = _glimmerUtil.dict();this.jumps = [];this.ranges = [];}Labels.prototype.label = function label(name,index){this.labels[name] = index;};Labels.prototype.jump = function jump(at,Target,target){this.jumps.push({at:at,target:target,Target:Target});};Labels.prototype.range = function range(at,Range,start,end){this.ranges.push({at:at,start:start,end:end,Range:Range});};Labels.prototype.patch = function patch(opcodes){for(var i=0;i < this.jumps.length;i++) {var _jumps$i=this.jumps[i];var at=_jumps$i.at;var target=_jumps$i.target;var Target=_jumps$i.Target;opcodes.set(at,Target,this.labels[target]);}for(var i=0;i < this.ranges.length;i++) {var _ranges$i=this.ranges[i];var at=_ranges$i.at;var start=_ranges$i.start;var end=_ranges$i.end;var _Range=_ranges$i.Range;opcodes.set(at,_Range,this.labels[start],this.labels[end] - 1);}};return Labels;})();var BasicOpcodeBuilder=(function(){function BasicOpcodeBuilder(symbolTable,env,program){this.symbolTable = symbolTable;this.env = env;this.program = program;this.labelsStack = new _glimmerUtil.Stack();this.constants = env.constants;this.start = program.next;}BasicOpcodeBuilder.prototype.opcode = function opcode(name,op1,op2,op3){this.push(name,op1,op2,op3);};BasicOpcodeBuilder.prototype.push = function push(type){var op1=arguments.length <= 1 || arguments[1] === undefined?0:arguments[1];var op2=arguments.length <= 2 || arguments[2] === undefined?0:arguments[2];var op3=arguments.length <= 3 || arguments[3] === undefined?0:arguments[3];this.program.push(type,op1,op2,op3);}; // helpers | |
BasicOpcodeBuilder.prototype.startLabels = function startLabels(){this.labelsStack.push(new Labels());};BasicOpcodeBuilder.prototype.stopLabels = function stopLabels(){var label=_glimmerUtil.expect(this.labelsStack.pop(),'unbalanced push and pop labels');label.patch(this.program);}; // partials | |
BasicOpcodeBuilder.prototype.putPartialDefinition = function putPartialDefinition(_definition){var definition=this.constants.other(_definition);this.opcode(50, /* PutPartial */definition);};BasicOpcodeBuilder.prototype.putDynamicPartialDefinition = function putDynamicPartialDefinition(){this.opcode(49, /* PutDynamicPartial */this.constants.other(this.symbolTable));};BasicOpcodeBuilder.prototype.evaluatePartial = function evaluatePartial(){this.opcode(51, /* EvaluatePartial */this.constants.other(this.symbolTable),this.constants.other(_glimmerUtil.dict()));}; // components | |
BasicOpcodeBuilder.prototype.putComponentDefinition = function putComponentDefinition(definition){this.opcode(23, /* PutComponent */this.other(definition));};BasicOpcodeBuilder.prototype.putDynamicComponentDefinition = function putDynamicComponentDefinition(){this.opcode(22 /* PutDynamicComponent */);};BasicOpcodeBuilder.prototype.openComponent = function openComponent(args,shadow){this.opcode(24, /* OpenComponent */this.args(args),shadow?this.block(shadow):0);};BasicOpcodeBuilder.prototype.didCreateElement = function didCreateElement(){this.opcode(25 /* DidCreateElement */);};BasicOpcodeBuilder.prototype.shadowAttributes = function shadowAttributes(){this.opcode(26 /* ShadowAttributes */);this.opcode(21 /* CloseBlock */);};BasicOpcodeBuilder.prototype.didRenderLayout = function didRenderLayout(){this.opcode(27 /* DidRenderLayout */);};BasicOpcodeBuilder.prototype.closeComponent = function closeComponent(){this.opcode(28 /* CloseComponent */);}; // content | |
BasicOpcodeBuilder.prototype.dynamicContent = function dynamicContent(Opcode){this.opcode(31, /* DynamicContent */this.other(Opcode));};BasicOpcodeBuilder.prototype.cautiousAppend = function cautiousAppend(){this.dynamicContent(new OptimizedCautiousAppendOpcode());};BasicOpcodeBuilder.prototype.trustingAppend = function trustingAppend(){this.dynamicContent(new OptimizedTrustingAppendOpcode());};BasicOpcodeBuilder.prototype.guardedCautiousAppend = function guardedCautiousAppend(expression){this.dynamicContent(new GuardedCautiousAppendOpcode(this.compileExpression(expression),this.symbolTable));};BasicOpcodeBuilder.prototype.guardedTrustingAppend = function guardedTrustingAppend(expression){this.dynamicContent(new GuardedTrustingAppendOpcode(this.compileExpression(expression),this.symbolTable));}; // dom | |
BasicOpcodeBuilder.prototype.text = function text(_text){this.opcode(29, /* Text */this.constants.string(_text));};BasicOpcodeBuilder.prototype.openPrimitiveElement = function openPrimitiveElement(tag){this.opcode(32, /* OpenElement */this.constants.string(tag));};BasicOpcodeBuilder.prototype.openComponentElement = function openComponentElement(tag){this.opcode(35, /* OpenComponentElement */this.constants.string(tag));};BasicOpcodeBuilder.prototype.openDynamicPrimitiveElement = function openDynamicPrimitiveElement(){this.opcode(36 /* OpenDynamicElement */);};BasicOpcodeBuilder.prototype.flushElement = function flushElement(){this.opcode(37 /* FlushElement */);};BasicOpcodeBuilder.prototype.closeElement = function closeElement(){this.opcode(38 /* 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.opcode(40, /* 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.opcode(42, /* DynamicAttrNS */name,namespace,trusting | 0);};BasicOpcodeBuilder.prototype.dynamicAttr = function dynamicAttr(_name,trusting){var name=this.constants.string(_name);this.opcode(43, /* DynamicAttr */name,trusting | 0);};BasicOpcodeBuilder.prototype.comment = function comment(_comment){var comment=this.constants.string(_comment);this.opcode(30, /* Comment */comment);};BasicOpcodeBuilder.prototype.modifier = function modifier(_name,_args){var args=this.constants.expression(this.compile(_args));var _modifierManager=this.env.lookupModifier(_name,this.symbolTable);var modifierManager=this.constants.other(_modifierManager);var name=this.constants.string(_name);this.opcode(41, /* Modifier */name,modifierManager,args);}; // lists | |
BasicOpcodeBuilder.prototype.putIterator = function putIterator(){this.opcode(44 /* PutIterator */);};BasicOpcodeBuilder.prototype.enterList = function enterList(start,end){this.push(45 /* EnterList */);this.labels.range(this.pos,45, /* EnterList */start,end);};BasicOpcodeBuilder.prototype.exitList = function exitList(){this.opcode(46 /* ExitList */);};BasicOpcodeBuilder.prototype.enterWithKey = function enterWithKey(start,end){this.push(47 /* EnterWithKey */);this.labels.range(this.pos,47, /* EnterWithKey */start,end);};BasicOpcodeBuilder.prototype.nextIter = function nextIter(end){this.push(48 /* NextIter */);this.labels.jump(this.pos,48, /* NextIter */end);}; // vm | |
BasicOpcodeBuilder.prototype.openBlock = function openBlock(_args,_inner){var args=this.constants.expression(this.compile(_args));var inner=this.constants.other(_inner);this.opcode(20, /* OpenBlock */inner,args);};BasicOpcodeBuilder.prototype.closeBlock = function closeBlock(){this.opcode(21 /* CloseBlock */);};BasicOpcodeBuilder.prototype.pushRemoteElement = function pushRemoteElement(){this.opcode(33 /* PushRemoteElement */);};BasicOpcodeBuilder.prototype.popRemoteElement = function popRemoteElement(){this.opcode(34 /* PopRemoteElement */);};BasicOpcodeBuilder.prototype.popElement = function popElement(){this.opcode(39 /* PopElement */);};BasicOpcodeBuilder.prototype.label = function label(name){this.labels.label(name,this.nextPos);};BasicOpcodeBuilder.prototype.pushChildScope = function pushChildScope(){this.opcode(0 /* PushChildScope */);};BasicOpcodeBuilder.prototype.popScope = function popScope(){this.opcode(1 /* PopScope */);};BasicOpcodeBuilder.prototype.pushDynamicScope = function pushDynamicScope(){this.opcode(2 /* PushDynamicScope */);};BasicOpcodeBuilder.prototype.popDynamicScope = function popDynamicScope(){this.opcode(3 /* PopDynamicScope */);};BasicOpcodeBuilder.prototype.putNull = function putNull(){this.opcode(4, /* Put */this.constants.NULL_REFERENCE);};BasicOpcodeBuilder.prototype.putValue = function putValue(_expression){var expr=this.constants.expression(this.compileExpression(_expression));this.opcode(5, /* EvaluatePut */expr);};BasicOpcodeBuilder.prototype.putArgs = function putArgs(_args){var args=this.constants.expression(this.compile(_args));this.opcode(6, /* PutArgs */args);};BasicOpcodeBuilder.prototype.bindDynamicScope = function bindDynamicScope(_names){this.opcode(12, /* BindDynamicScope */this.names(_names));};BasicOpcodeBuilder.prototype.bindPositionalArgs = function bindPositionalArgs(_names,_symbols){this.opcode(7, /* BindPositionalArgs */this.names(_names),this.symbols(_symbols));};BasicOpcodeBuilder.prototype.bindNamedArgs = function bindNamedArgs(_names,_symbols){this.opcode(8, /* BindNamedArgs */this.names(_names),this.symbols(_symbols));};BasicOpcodeBuilder.prototype.bindBlocks = function bindBlocks(_names,_symbols){this.opcode(9, /* BindBlocks */this.names(_names),this.symbols(_symbols));};BasicOpcodeBuilder.prototype.enter = function enter(_enter,exit){this.push(13 /* Enter */);this.labels.range(this.pos,13, /* Enter */_enter,exit);};BasicOpcodeBuilder.prototype.exit = function exit(){this.opcode(14 /* Exit */);};BasicOpcodeBuilder.prototype.evaluate = function evaluate(_block){var block=this.constants.block(_block);this.opcode(15, /* Evaluate */block);};BasicOpcodeBuilder.prototype.test = function test(testFunc){var _func=undefined;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.opcode(19, /* Test */func);};BasicOpcodeBuilder.prototype.jump = function jump(target){this.push(16 /* Jump */);this.labels.jump(this.pos,16, /* Jump */target);};BasicOpcodeBuilder.prototype.jumpIf = function jumpIf(target){this.push(17 /* JumpIf */);this.labels.jump(this.pos,17, /* JumpIf */target);};BasicOpcodeBuilder.prototype.jumpUnless = function jumpUnless(target){this.push(18 /* JumpUnless */);this.labels.jump(this.pos,18, /* JumpUnless */target);};BasicOpcodeBuilder.prototype.names = function names(_names){var _this=this;var names=_names.map(function(n){return _this.constants.string(n);});return this.constants.array(names);};BasicOpcodeBuilder.prototype.symbols = function symbols(_symbols2){return this.constants.array(_symbols2);};BasicOpcodeBuilder.prototype.other = function other(value){return this.constants.other(value);};BasicOpcodeBuilder.prototype.args = function args(_args2){return this.constants.expression(this.compile(_args2));};BasicOpcodeBuilder.prototype.block = function block(_block3){return this.constants.block(_block3);};babelHelpers.createClass(BasicOpcodeBuilder,[{key:'end',get:function(){return this.program.next;}},{key:'pos',get:function(){return this.program.current;}},{key:'nextPos',get:function(){return this.program.next;}},{key:'labels',get:function(){return _glimmerUtil.expect(this.labelsStack.current,'bug: not in a label stack');}}]);return BasicOpcodeBuilder;})();function isCompilableExpression(expr){return expr && typeof expr['compile'] === 'function';}var OpcodeBuilder=(function(_BasicOpcodeBuilder){babelHelpers.inherits(OpcodeBuilder,_BasicOpcodeBuilder);function OpcodeBuilder(symbolTable,env){var program=arguments.length <= 2 || arguments[2] === undefined?env.program:arguments[2];return (function(){_BasicOpcodeBuilder.call(this,symbolTable,env,program);this.component = new ComponentBuilder(this);}).apply(this,arguments);}OpcodeBuilder.prototype.compile = function compile(expr){if(isCompilableExpression(expr)){return expr.compile(this);}else {return expr;}};OpcodeBuilder.prototype.compileExpression = function compileExpression(expression){if(expression instanceof CompiledExpression){return expression;}else {return expr(expression,this);}};OpcodeBuilder.prototype.bindPositionalArgsForLocals = function bindPositionalArgsForLocals(locals){var names=Object.keys(locals);var symbols=new Array(names.length); //Object.keys(locals).map(name => locals[name]); | |
for(var i=0;i < names.length;i++) {symbols[i] = locals[names[i]];}this.opcode(7, /* BindPositionalArgs */this.symbols(symbols));};OpcodeBuilder.prototype.preludeForLayout = function preludeForLayout(layout){var _this2=this;var symbols=layout.symbolTable.getSymbols();if(symbols.named){(function(){var named=symbols.named;var namedNames=Object.keys(named);var namedSymbols=namedNames.map(function(n){return named[n];});_this2.opcode(8, /* BindNamedArgs */_this2.names(namedNames),_this2.symbols(namedSymbols));})();}this.opcode(11 /* BindCallerScope */);if(symbols.yields){(function(){var yields=symbols.yields;var yieldNames=Object.keys(yields);var yieldSymbols=yieldNames.map(function(n){return yields[n];});_this2.opcode(9, /* BindBlocks */_this2.names(yieldNames),_this2.symbols(yieldSymbols));})();}if(symbols.partialArgs){this.opcode(10, /* BindPartialArgs */symbols.partialArgs);}};OpcodeBuilder.prototype.yield = function _yield(args,to){var yields=undefined,partial=undefined;var inner=undefined;if(yields = this.symbolTable.getSymbol('yields',to)){inner = new CompiledGetBlockBySymbol(yields,to);}else if(partial = this.symbolTable.getPartialArgs()){inner = new CompiledInPartialGetBlock(partial,to);}else {throw new Error('[BUG] ${to} is not a valid block name.');}this.openBlock(args,inner);this.closeBlock();}; // TODO | |
// come back to this | |
OpcodeBuilder.prototype.labelled = function labelled(args,callback){if(args)this.putArgs(args);this.startLabels();this.enter('BEGIN','END');this.label('BEGIN');callback(this,'BEGIN','END');this.label('END');this.exit();this.stopLabels();}; // TODO | |
// come back to this | |
OpcodeBuilder.prototype.iter = function iter(callback){this.startLabels();this.enterList('BEGIN','END');this.label('ITER');this.nextIter('BREAK');this.enterWithKey('BEGIN','END');this.label('BEGIN');callback(this,'BEGIN','END');this.label('END');this.exit();this.jump('ITER');this.label('BREAK');this.exitList();this.stopLabels();}; // TODO | |
// come back to this | |
OpcodeBuilder.prototype.unit = function unit(callback){this.startLabels();callback(this);this.stopLabels();};return OpcodeBuilder;})(BasicOpcodeBuilder);function compileLayout(compilable,env){var builder=new ComponentLayoutBuilder(env);compilable.compile(builder);return builder.compile();}var ComponentLayoutBuilder=(function(){function ComponentLayoutBuilder(env){this.env = env;}ComponentLayoutBuilder.prototype.wrapLayout = function wrapLayout(layout){this.inner = new WrappedBuilder(this.env,layout);};ComponentLayoutBuilder.prototype.fromLayout = function fromLayout(layout){this.inner = new UnwrappedBuilder(this.env,layout);};ComponentLayoutBuilder.prototype.compile = function compile(){return this.inner.compile();};babelHelpers.createClass(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){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;var layout=this.layout;var symbolTable=layout.symbolTable;var b=builder(env,layout.symbolTable);b.startLabels();var dynamicTag=this.tag.getDynamic();var staticTag=undefined;if(dynamicTag){b.putValue(dynamicTag);b.test('simple');b.jumpUnless('BODY');b.openDynamicPrimitiveElement();b.didCreateElement();this.attrs['buffer'].forEach(function(statement){return compileStatement(statement,b);});b.flushElement();b.label('BODY');}else if(staticTag = this.tag.getStatic()){b.openPrimitiveElement(staticTag);b.didCreateElement();this.attrs['buffer'].forEach(function(statement){return compileStatement(statement,b);});b.flushElement();}b.preludeForLayout(layout);layout.statements.forEach(function(statement){return compileStatement(statement,b);});if(dynamicTag){b.putValue(dynamicTag);b.test('simple');b.jumpUnless('END');b.closeElement();b.label('END');}else if(staticTag){b.closeElement();}b.didRenderLayout();b.stopLabels();return new CompiledProgram(b.start,b.end,symbolTable.size);};return WrappedBuilder;})();function isOpenElement(value){var type=value[0];return type === _glimmerWireFormat.Ops.OpenElement || type === _glimmerWireFormat.Ops.OpenPrimitiveElement;}var UnwrappedBuilder=(function(){function UnwrappedBuilder(env,layout){this.env = env;this.layout = layout;this.attrs = new ComponentAttrsBuilder();}UnwrappedBuilder.prototype.compile = function compile(){var env=this.env;var layout=this.layout;var b=builder(env,layout.symbolTable);b.startLabels();b.preludeForLayout(layout);var attrs=this.attrs['buffer'];var attrsInserted=false;for(var i=0;i < layout.statements.length;i++) {var statement=layout.statements[i];if(!attrsInserted && isOpenElement(statement)){b.openComponentElement(statement[1]);b.didCreateElement();b.shadowAttributes();attrs.forEach(function(statement){return compileStatement(statement,b);});attrsInserted = true;}else {compileStatement(statement,b);}}b.didRenderLayout();b.stopLabels();return new CompiledProgram(b.start,b.end,layout.symbolTable.size);};babelHelpers.createClass(UnwrappedBuilder,[{key:'tag',get:function(){throw new Error('BUG: Cannot call `tag` on an UnwrappedBuilder');}}]);return UnwrappedBuilder;})();var ComponentTagBuilder=(function(){function 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 = [_glimmerWireFormat.Ops.Function,tagName];};return ComponentTagBuilder;})();var ComponentAttrsBuilder=(function(){function ComponentAttrsBuilder(){this.buffer = [];}ComponentAttrsBuilder.prototype.static = function _static(name,value){this.buffer.push([_glimmerWireFormat.Ops.StaticAttr,name,value,null]);};ComponentAttrsBuilder.prototype.dynamic = function dynamic(name,value){this.buffer.push([_glimmerWireFormat.Ops.DynamicAttr,name,[_glimmerWireFormat.Ops.Function,value],null]);};return ComponentAttrsBuilder;})();var ComponentBuilder=(function(){function ComponentBuilder(builder){this.builder = builder;this.env = builder.env;}ComponentBuilder.prototype.static = function _static(definition,args,_symbolTable,shadow){this.builder.unit(function(b){b.putComponentDefinition(definition);b.openComponent(compileBaselineArgs(args,b),shadow);b.closeComponent();});};ComponentBuilder.prototype.dynamic = function dynamic(definitionArgs,definition,args,_symbolTable,shadow){this.builder.unit(function(b){b.putArgs(compileArgs(definitionArgs[0],definitionArgs[1],b));b.putValue([_glimmerWireFormat.Ops.Function,definition]);b.test('simple');b.enter('BEGIN','END');b.label('BEGIN');b.jumpUnless('END');b.putDynamicComponentDefinition();b.openComponent(compileBaselineArgs(args,b),shadow);b.closeComponent();b.label('END');b.exit();});};return ComponentBuilder;})();function builder(env,symbolTable){return new OpcodeBuilder(symbolTable,env);}function entryPoint(meta){return new ProgramSymbolTable(meta);}function layout(meta,wireNamed,wireYields,hasPartials){var _symbols3=symbols(wireNamed,wireYields,hasPartials);var named=_symbols3.named;var yields=_symbols3.yields;var partialSymbol=_symbols3.partialSymbol;var size=_symbols3.size;return new ProgramSymbolTable(meta,named,yields,partialSymbol,size);}function block(parent,locals){var localsMap=null;var program=parent['program'];if(locals.length !== 0){(function(){var map=localsMap = _glimmerUtil.dict();locals.forEach(function(l){return map[l] = program.size++;});})();}return new BlockSymbolTable(parent,program,localsMap);}function symbols(named,yields,hasPartials){var yieldsMap=null;var namedMap=null;var size=1;if(yields.length !== 0){(function(){var map=yieldsMap = _glimmerUtil.dict();yields.forEach(function(y){return map[y] = size++;});})();}if(named.length !== 0){(function(){var map=namedMap = _glimmerUtil.dict();named.forEach(function(y){return map[y] = size++;});})();}var partialSymbol=hasPartials?size++:null;return {named:namedMap,yields:yieldsMap,partialSymbol:partialSymbol,size:size};}var ProgramSymbolTable=(function(){function ProgramSymbolTable(meta){var named=arguments.length <= 1 || arguments[1] === undefined?null:arguments[1];var yields=arguments.length <= 2 || arguments[2] === undefined?null:arguments[2];var partialArgs=arguments.length <= 3 || arguments[3] === undefined?null:arguments[3];var size=arguments.length <= 4 || arguments[4] === undefined?1:arguments[4];this.meta = meta;this.named = named;this.yields = yields;this.partialArgs = partialArgs;this.size = size;this.program = this;}ProgramSymbolTable.prototype.getMeta = function getMeta(){return this.meta;};ProgramSymbolTable.prototype.getSymbols = function getSymbols(){return {named:this.named,yields:this.yields,locals:null,partialArgs:this.partialArgs};};ProgramSymbolTable.prototype.getSymbol = function getSymbol(kind,name){if(kind === 'local')return null;return this[kind] && this[kind][name];};ProgramSymbolTable.prototype.getPartialArgs = function getPartialArgs(){return this.partialArgs || 0;};return ProgramSymbolTable;})();var BlockSymbolTable=(function(){function BlockSymbolTable(parent,program,locals){this.parent = parent;this.program = program;this.locals = locals;}BlockSymbolTable.prototype.getMeta = function getMeta(){return this.program.getMeta();};BlockSymbolTable.prototype.getSymbols = function getSymbols(){return {named:null,yields:null,locals:this.locals,partialArgs:null};};BlockSymbolTable.prototype.getSymbol = function getSymbol(kind,name){if(kind === 'local'){return this.getLocal(name);}else {return this.program.getSymbol(kind,name);}};BlockSymbolTable.prototype.getLocal = function getLocal(name){var locals=this.locals;var parent=this.parent;var symbol=locals && locals[name];if(!symbol && parent){symbol = parent.getSymbol('local',name);}return symbol;};BlockSymbolTable.prototype.getPartialArgs = function getPartialArgs(){return this.program.getPartialArgs();};return BlockSymbolTable;})();var Specialize=(function(){function Specialize(){this.names = _glimmerUtil.dict();this.funcs = [];}Specialize.prototype.add = function add(name,func){this.funcs.push(func);this.names[name] = this.funcs.length - 1;};Specialize.prototype.specialize = function specialize(sexp,table){var name=sexp[0];var index=this.names[name];if(index === undefined)return sexp;var func=this.funcs[index];_glimmerUtil.assert(!!func,'expected a specialization for ' + sexp[0]);return func(sexp,table);};return Specialize;})();var SPECIALIZE=new Specialize();var E=_glimmerWireFormat.Expressions;var Ops$3=_glimmerWireFormat.Ops;SPECIALIZE.add(Ops$3.Append,function(sexp,_symbolTable){var expression=sexp[1];if(Array.isArray(expression) && E.isGet(expression)){var path=expression[1];if(path.length !== 1){return [Ops$3.UnoptimizedAppend,sexp[1],sexp[2]];}}return [Ops$3.OptimizedAppend,sexp[1],sexp[2]];});SPECIALIZE.add(Ops$3.DynamicAttr,function(sexp,_symbolTable){return [Ops$3.AnyDynamicAttr,sexp[1],sexp[2],sexp[3],false];});SPECIALIZE.add(Ops$3.TrustingAttr,function(sexp,_symbolTable){return [Ops$3.AnyDynamicAttr,sexp[1],sexp[2],sexp[3],true];});SPECIALIZE.add(Ops$3.Partial,function(sexp,_table){var expression=sexp[1];if(typeof expression === 'string'){return [Ops$3.StaticPartial,expression];}else {return [Ops$3.DynamicPartial,expression];}});function compileStatement(statement,builder){var refined=SPECIALIZE.specialize(statement,builder.symbolTable);STATEMENTS.compile(refined,builder);}var Template=function Template(statements,symbolTable){this.statements = statements;this.symbolTable = symbolTable;};var Layout=(function(_Template){babelHelpers.inherits(Layout,_Template);function Layout(){_Template.apply(this,arguments);}return Layout;})(Template);var EntryPoint=(function(_Template2){babelHelpers.inherits(EntryPoint,_Template2);function EntryPoint(){_Template2.apply(this,arguments);this.compiled = null;}EntryPoint.prototype.compile = function compile(env){var compiled=this.compiled;if(!compiled){var table=this.symbolTable;var b=builder(env,table);for(var i=0;i < this.statements.length;i++) {var statement=this.statements[i];var refined=SPECIALIZE.specialize(statement,table);STATEMENTS.compile(refined,b);}compiled = this.compiled = new CompiledProgram(b.start,b.end,this.symbolTable.size);}return compiled;};return EntryPoint;})(Template);var InlineBlock=(function(_Template3){babelHelpers.inherits(InlineBlock,_Template3);function InlineBlock(){_Template3.apply(this,arguments);this.compiled = null;}InlineBlock.prototype.splat = function splat(builder){var table=builder.symbolTable;var locals=table.getSymbols().locals;if(locals){builder.pushChildScope();builder.bindPositionalArgsForLocals(locals);}for(var i=0;i < this.statements.length;i++) {var statement=this.statements[i];var refined=SPECIALIZE.specialize(statement,table);STATEMENTS.compile(refined,builder);}if(locals){builder.popScope();}};InlineBlock.prototype.compile = function compile(env){var compiled=this.compiled;if(!compiled){var table=this.symbolTable;var b=builder(env,table);this.splat(b);compiled = this.compiled = new CompiledBlock(b.start,b.end);}return compiled;};return InlineBlock;})(Template);var PartialBlock=(function(_Template4){babelHelpers.inherits(PartialBlock,_Template4);function PartialBlock(){_Template4.apply(this,arguments);this.compiled = null;}PartialBlock.prototype.compile = function compile(env){var compiled=this.compiled;if(!compiled){var table=this.symbolTable;var b=builder(env,table);for(var i=0;i < this.statements.length;i++) {var statement=this.statements[i];var refined=SPECIALIZE.specialize(statement,table);STATEMENTS.compile(refined,b);}compiled = this.compiled = new CompiledProgram(b.start,b.end,table.size);}return compiled;};return PartialBlock;})(Template);var Scanner=(function(){function Scanner(block,meta,env){this.block = block;this.meta = meta;this.env = env;}Scanner.prototype.scanEntryPoint = function scanEntryPoint(){var block=this.block;var meta=this.meta;var symbolTable=entryPoint(meta);var child=scanBlock(block,symbolTable,this.env);return new EntryPoint(child.statements,symbolTable);};Scanner.prototype.scanLayout = function scanLayout(){var block=this.block;var meta=this.meta;var named=block.named;var yields=block.yields;var hasPartials=block.hasPartials;var symbolTable=layout(meta,named,yields,hasPartials);var child=scanBlock(block,symbolTable,this.env);return new Layout(child.statements,symbolTable);};Scanner.prototype.scanPartial = function scanPartial(symbolTable){var block=this.block;var child=scanBlock(block,symbolTable,this.env);return new PartialBlock(child.statements,symbolTable);};return Scanner;})();function scanBlock(_ref26,symbolTable,env){var statements=_ref26.statements;return new RawInlineBlock(env,symbolTable,statements).scan();}var BaselineSyntax;(function(BaselineSyntax){var Ops=_glimmerWireFormat.Ops;BaselineSyntax.isScannedComponent = _glimmerWireFormat.is(Ops.ScannedComponent);BaselineSyntax.isPrimitiveElement = _glimmerWireFormat.is(Ops.OpenPrimitiveElement);BaselineSyntax.isOptimizedAppend = _glimmerWireFormat.is(Ops.OptimizedAppend);BaselineSyntax.isUnoptimizedAppend = _glimmerWireFormat.is(Ops.UnoptimizedAppend);BaselineSyntax.isAnyAttr = _glimmerWireFormat.is(Ops.AnyDynamicAttr);BaselineSyntax.isStaticPartial = _glimmerWireFormat.is(Ops.StaticPartial);BaselineSyntax.isDynamicPartial = _glimmerWireFormat.is(Ops.DynamicPartial);BaselineSyntax.isFunctionExpression = _glimmerWireFormat.is(Ops.Function);BaselineSyntax.isNestedBlock = _glimmerWireFormat.is(Ops.NestedBlock);BaselineSyntax.isScannedBlock = _glimmerWireFormat.is(Ops.ScannedBlock);BaselineSyntax.isDebugger = _glimmerWireFormat.is(Ops.Debugger);var NestedBlock;(function(NestedBlock){function defaultBlock(sexp){return sexp[4];}NestedBlock.defaultBlock = defaultBlock;function inverseBlock(sexp){return sexp[5];}NestedBlock.inverseBlock = inverseBlock;function params(sexp){return sexp[2];}NestedBlock.params = params;function hash(sexp){return sexp[3];}NestedBlock.hash = hash;})(NestedBlock = BaselineSyntax.NestedBlock || (BaselineSyntax.NestedBlock = {}));})(BaselineSyntax || (exports.BaselineSyntax = BaselineSyntax = {}));var Ops$2=_glimmerWireFormat.Ops;var RawInlineBlock=(function(){function RawInlineBlock(env,table,statements){this.env = env;this.table = table;this.statements = statements;}RawInlineBlock.prototype.scan = function scan(){var buffer=[];for(var i=0;i < this.statements.length;i++) {var statement=this.statements[i];if(_glimmerWireFormat.Statements.isBlock(statement)){buffer.push(this.specializeBlock(statement));}else if(_glimmerWireFormat.Statements.isComponent(statement)){buffer.push.apply(buffer,this.specializeComponent(statement));}else {buffer.push(statement);}}return new InlineBlock(buffer,this.table);};RawInlineBlock.prototype.specializeBlock = function specializeBlock(block$$){var path=block$$[1];var params=block$$[2];var hash=block$$[3];var template=block$$[4];var inverse=block$$[5];return [Ops$2.ScannedBlock,path,params,hash,this.child(template),this.child(inverse)];};RawInlineBlock.prototype.specializeComponent = function specializeComponent(sexp){var tag=sexp[1];var component=sexp[2];if(this.env.hasComponentDefinition(tag,this.table)){var child=this.child(component);var attrs=new RawInlineBlock(this.env,this.table,component.attrs);return [[Ops$2.ScannedComponent,tag,attrs,component.args,child]];}else {var buf=[];buf.push([Ops$2.OpenElement,tag,[]]);buf.push.apply(buf,component.attrs);buf.push([Ops$2.FlushElement]);buf.push.apply(buf,component.statements);buf.push([Ops$2.CloseElement]);return buf;}};RawInlineBlock.prototype.child = function child(block$$){if(!block$$)return null;var table=block(this.table,block$$.locals);return new RawInlineBlock(this.env,table,block$$.statements);};return RawInlineBlock;})();var CompiledLookup=(function(_CompiledExpression4){babelHelpers.inherits(CompiledLookup,_CompiledExpression4);function CompiledLookup(base,path){_CompiledExpression4.call(this);this.base = base;this.path = path;this.type = "lookup";}CompiledLookup.create = function create(base,path){if(path.length === 0){return base;}else {return new this(base,path);}};CompiledLookup.prototype.evaluate = function evaluate(vm){var base=this.base;var path=this.path;return _glimmerReference.referenceFromParts(base.evaluate(vm),path);};CompiledLookup.prototype.toJSON = function toJSON(){return this.base.toJSON() + '.' + this.path.join('.');};return CompiledLookup;})(CompiledExpression);var CompiledSelf=(function(_CompiledExpression5){babelHelpers.inherits(CompiledSelf,_CompiledExpression5);function CompiledSelf(){_CompiledExpression5.apply(this,arguments);}CompiledSelf.prototype.evaluate = function evaluate(vm){return vm.getSelf();};CompiledSelf.prototype.toJSON = function toJSON(){return 'self';};return CompiledSelf;})(CompiledExpression);var CompiledSymbol=(function(_CompiledExpression6){babelHelpers.inherits(CompiledSymbol,_CompiledExpression6);function CompiledSymbol(symbol,debug){_CompiledExpression6.call(this);this.symbol = symbol;this.debug = debug;}CompiledSymbol.prototype.evaluate = function evaluate(vm){return vm.referenceForSymbol(this.symbol);};CompiledSymbol.prototype.toJSON = function toJSON(){return '$' + this.symbol + '(' + this.debug + ')';};return CompiledSymbol;})(CompiledExpression);var CompiledInPartialName=(function(_CompiledExpression7){babelHelpers.inherits(CompiledInPartialName,_CompiledExpression7);function CompiledInPartialName(symbol,name){_CompiledExpression7.call(this);this.symbol = symbol;this.name = name;}CompiledInPartialName.prototype.evaluate = function evaluate(vm){var symbol=this.symbol;var name=this.name;var args=vm.scope().getPartialArgs(symbol);return args.named.get(name);};CompiledInPartialName.prototype.toJSON = function toJSON(){return '$' + this.symbol + '($ARGS).' + this.name;};return CompiledInPartialName;})(CompiledExpression);var CompiledHelper=(function(_CompiledExpression8){babelHelpers.inherits(CompiledHelper,_CompiledExpression8);function CompiledHelper(name,helper,args,symbolTable){_CompiledExpression8.call(this);this.name = name;this.helper = helper;this.args = args;this.symbolTable = symbolTable;this.type = "helper";}CompiledHelper.prototype.evaluate = function evaluate(vm){var helper=this.helper;return helper(vm,this.args.evaluate(vm),this.symbolTable);};CompiledHelper.prototype.toJSON = function toJSON(){return '`' + this.name + '($ARGS)`';};return CompiledHelper;})(CompiledExpression);var CompiledConcat=(function(){function CompiledConcat(parts){this.parts = parts;this.type = "concat";}CompiledConcat.prototype.evaluate = function evaluate(vm){var parts=new Array(this.parts.length);for(var i=0;i < this.parts.length;i++) {parts[i] = this.parts[i].evaluate(vm);}return new ConcatReference(parts);};CompiledConcat.prototype.toJSON = function toJSON(){return 'concat(' + this.parts.map(function(expr){return expr.toJSON();}).join(", ") + ')';};return CompiledConcat;})();var ConcatReference=(function(_CachedReference2){babelHelpers.inherits(ConcatReference,_CachedReference2);function ConcatReference(parts){_CachedReference2.call(this);this.parts = parts;this.tag = _glimmerReference.combineTagged(parts);}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;})(_glimmerReference.CachedReference);function castToString(value){if(typeof value['toString'] !== 'function'){return '';}return String(value);}var CompiledFunctionExpression=(function(_CompiledExpression9){babelHelpers.inherits(CompiledFunctionExpression,_CompiledExpression9);function CompiledFunctionExpression(func,symbolTable){_CompiledExpression9.call(this);this.func = func;this.symbolTable = symbolTable;this.type = "function";this.func = func;}CompiledFunctionExpression.prototype.evaluate = function evaluate(vm){var func=this.func;var symbolTable=this.symbolTable;return func(vm,symbolTable);};CompiledFunctionExpression.prototype.toJSON = function toJSON(){var func=this.func;if(func.name){return '`' + func.name + '(...)`';}else {return "`func(...)`";}};return CompiledFunctionExpression;})(CompiledExpression);var _BaselineSyntax$NestedBlock=BaselineSyntax.NestedBlock;var defaultBlock=_BaselineSyntax$NestedBlock.defaultBlock;var params=_BaselineSyntax$NestedBlock.params;var hash=_BaselineSyntax$NestedBlock.hash;function debugCallback(context,get){console.info('Use `context`, and `get(<path>)` to debug this template.'); /* tslint:disable */debugger; /* tslint:enable */return {context:context,get:get};}function getter(vm,builder){return function(path){var parts=path.split('.');if(parts[0] === 'this'){parts[0] = null;}return compileRef(parts,builder).evaluate(vm);};}var callback=debugCallback; // For testing purposes | |
function setDebuggerCallback(cb){callback = cb;}function resetDebuggerCallback(){callback = debugCallback;}var Compilers=(function(){function Compilers(){this.names = _glimmerUtil.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[0];var index=this.names[name];var func=this.funcs[index];_glimmerUtil.assert(!!func,'expected an implementation for ' + sexp[0]);return func(sexp,builder);};return Compilers;})();var Ops$1=_glimmerWireFormat.Ops;var STATEMENTS=new Compilers();STATEMENTS.add(Ops$1.Text,function(sexp,builder){builder.text(sexp[1]);});STATEMENTS.add(Ops$1.Comment,function(sexp,builder){builder.comment(sexp[1]);});STATEMENTS.add(Ops$1.CloseElement,function(_sexp,builder){_glimmerUtil.LOGGER.trace('close-element statement');builder.closeElement();});STATEMENTS.add(Ops$1.FlushElement,function(_sexp,builder){builder.flushElement();});STATEMENTS.add(Ops$1.Modifier,function(sexp,builder){var path=sexp[1];var params=sexp[2];var hash=sexp[3];var args=compileArgs(params,hash,builder);if(builder.env.hasModifier(path[0],builder.symbolTable)){builder.modifier(path[0],args);}else {throw new Error('Compile Error ' + path.join('.') + ' is not a modifier: Helpers may not be used in the element form.');}});STATEMENTS.add(Ops$1.StaticAttr,function(sexp,builder){var name=sexp[1];var value=sexp[2];var namespace=sexp[3];builder.staticAttr(name,namespace,value);});STATEMENTS.add(Ops$1.AnyDynamicAttr,function(sexp,builder){var name=sexp[1];var value=sexp[2];var namespace=sexp[3];var trusting=sexp[4];builder.putValue(value);if(namespace){builder.dynamicAttrNS(name,namespace,trusting);}else {builder.dynamicAttr(name,trusting);}});STATEMENTS.add(Ops$1.OpenElement,function(sexp,builder){_glimmerUtil.LOGGER.trace('open-element statement');builder.openPrimitiveElement(sexp[1]);});STATEMENTS.add(Ops$1.OptimizedAppend,function(sexp,builder){var value=sexp[1];var trustingMorph=sexp[2];var _builder$env$macros=builder.env.macros();var inlines=_builder$env$macros.inlines;var returned=inlines.compile(sexp,builder) || value;if(returned === true)return;builder.putValue(returned[1]);if(trustingMorph){builder.trustingAppend();}else {builder.cautiousAppend();}});STATEMENTS.add(Ops$1.UnoptimizedAppend,function(sexp,builder){var value=sexp[1];var trustingMorph=sexp[2];var _builder$env$macros2=builder.env.macros();var inlines=_builder$env$macros2.inlines;var returned=inlines.compile(sexp,builder) || value;if(returned === true)return;if(trustingMorph){builder.guardedTrustingAppend(returned[1]);}else {builder.guardedCautiousAppend(returned[1]);}});STATEMENTS.add(Ops$1.NestedBlock,function(sexp,builder){var _builder$env$macros3=builder.env.macros();var blocks=_builder$env$macros3.blocks;blocks.compile(sexp,builder);});STATEMENTS.add(Ops$1.ScannedBlock,function(sexp,builder){var path=sexp[1];var params=sexp[2];var hash=sexp[3];var template=sexp[4];var inverse=sexp[5];var templateBlock=template && template.scan();var inverseBlock=inverse && inverse.scan();var _builder$env$macros4=builder.env.macros();var blocks=_builder$env$macros4.blocks;blocks.compile([Ops$1.NestedBlock,path,params,hash,templateBlock,inverseBlock],builder);});STATEMENTS.add(Ops$1.ScannedComponent,function(sexp,builder){var tag=sexp[1];var attrs=sexp[2];var rawArgs=sexp[3];var rawBlock=sexp[4];var block=rawBlock && rawBlock.scan();var args=compileBlockArgs(null,rawArgs,{default:block,inverse:null},builder);var definition=builder.env.getComponentDefinition(tag,builder.symbolTable);builder.putComponentDefinition(definition);builder.openComponent(args,attrs.scan());builder.closeComponent();});STATEMENTS.add(Ops$1.StaticPartial,function(sexp,builder){var name=sexp[1];if(!builder.env.hasPartial(name,builder.symbolTable)){throw new Error('Compile Error: Could not find a partial named "' + name + '"');}var definition=builder.env.lookupPartial(name,builder.symbolTable);builder.putPartialDefinition(definition);builder.evaluatePartial();});STATEMENTS.add(Ops$1.DynamicPartial,function(sexp,builder){var name=sexp[1];builder.startLabels();builder.putValue(name);builder.test('simple');builder.enter('BEGIN','END');builder.label('BEGIN');builder.jumpUnless('END');builder.putDynamicPartialDefinition();builder.evaluatePartial();builder.label('END');builder.exit();builder.stopLabels();});STATEMENTS.add(Ops$1.Yield,function(sexp,builder){var to=sexp[1];var params=sexp[2];var args=compileArgs(params,null,builder);builder.yield(args,to);});STATEMENTS.add(Ops$1.Debugger,function(sexp,builder){builder.putValue([Ops$1.Function,function(vm){var context=vm.getSelf().value();var get=function(path){return getter(vm,builder)(path).value();};callback(context,get);}]);return sexp;});var EXPRESSIONS=new Compilers();function expr(expression,builder){if(Array.isArray(expression)){return EXPRESSIONS.compile(expression,builder);}else {return new CompiledValue(expression);}}EXPRESSIONS.add(Ops$1.Unknown,function(sexp,builder){var path=sexp[1];var name=path[0];if(builder.env.hasHelper(name,builder.symbolTable)){return new CompiledHelper(name,builder.env.lookupHelper(name,builder.symbolTable),CompiledArgs.empty(),builder.symbolTable);}else {return compileRef(path,builder);}});EXPRESSIONS.add(Ops$1.Concat,function(sexp,builder){var params=sexp[1].map(function(p){return expr(p,builder);});return new CompiledConcat(params);});EXPRESSIONS.add(Ops$1.Function,function(sexp,builder){return new CompiledFunctionExpression(sexp[1],builder.symbolTable);});EXPRESSIONS.add(Ops$1.Helper,function(sexp,builder){var env=builder.env;var symbolTable=builder.symbolTable;var _sexp$1=sexp[1];var name=_sexp$1[0];var params=sexp[2];var hash=sexp[3];if(env.hasHelper(name,symbolTable)){var args=compileArgs(params,hash,builder);return new CompiledHelper(name,env.lookupHelper(name,symbolTable),args,symbolTable);}else {throw new Error('Compile Error: ' + name + ' is not a helper');}});EXPRESSIONS.add(Ops$1.Get,function(sexp,builder){return compileRef(sexp[1],builder);});EXPRESSIONS.add(Ops$1.Undefined,function(_sexp,_builder){return new CompiledValue(undefined);});EXPRESSIONS.add(Ops$1.Arg,function(sexp,builder){var parts=sexp[1];var head=parts[0];var named=undefined,partial=undefined;if(named = builder.symbolTable.getSymbol('named',head)){var path=parts.slice(1);var inner=new CompiledSymbol(named,head);return CompiledLookup.create(inner,path);}else if(partial = builder.symbolTable.getPartialArgs()){var path=parts.slice(1);var inner=new CompiledInPartialName(partial,head);return CompiledLookup.create(inner,path);}else {throw new Error('[BUG] @' + parts.join('.') + ' is not a valid lookup path.');}});EXPRESSIONS.add(Ops$1.HasBlock,function(sexp,builder){var blockName=sexp[1];var yields=undefined,partial=undefined;if(yields = builder.symbolTable.getSymbol('yields',blockName)){var inner=new CompiledGetBlockBySymbol(yields,blockName);return new CompiledHasBlock(inner);}else if(partial = builder.symbolTable.getPartialArgs()){var inner=new CompiledInPartialGetBlock(partial,blockName);return new CompiledHasBlock(inner);}else {throw new Error('[BUG] ${blockName} is not a valid block name.');}});EXPRESSIONS.add(Ops$1.HasBlockParams,function(sexp,builder){var blockName=sexp[1];var yields=undefined,partial=undefined;if(yields = builder.symbolTable.getSymbol('yields',blockName)){var inner=new CompiledGetBlockBySymbol(yields,blockName);return new CompiledHasBlockParams(inner);}else if(partial = builder.symbolTable.getPartialArgs()){var inner=new CompiledInPartialGetBlock(partial,blockName);return new CompiledHasBlockParams(inner);}else {throw new Error('[BUG] ${blockName} is not a valid block name.');}});function compileArgs(params,hash,builder){var compiledParams=compileParams(params,builder);var compiledHash=compileHash(hash,builder);return CompiledArgs.create(compiledParams,compiledHash,EMPTY_BLOCKS);}function compileBlockArgs(params,hash,blocks,builder){var compiledParams=compileParams(params,builder);var compiledHash=compileHash(hash,builder);return CompiledArgs.create(compiledParams,compiledHash,blocks);}function compileBaselineArgs(args,builder){var params=args[0];var hash=args[1];var _default=args[2];var inverse=args[3];return CompiledArgs.create(compileParams(params,builder),compileHash(hash,builder),{default:_default,inverse:inverse});}function compileParams(params,builder){if(!params || params.length === 0)return COMPILED_EMPTY_POSITIONAL_ARGS;var compiled=new Array(params.length);for(var i=0;i < params.length;i++) {compiled[i] = expr(params[i],builder);}return CompiledPositionalArgs.create(compiled);}function compileHash(hash,builder){if(!hash)return COMPILED_EMPTY_NAMED_ARGS;var keys=hash[0];var values=hash[1];if(keys.length === 0)return COMPILED_EMPTY_NAMED_ARGS;var compiled=new Array(values.length);for(var i=0;i < values.length;i++) {compiled[i] = expr(values[i],builder);}return new CompiledNamedArgs(keys,compiled);}function compileRef(parts,builder){var head=parts[0];var local=undefined;if(head === null){var inner=new CompiledSelf();var path=parts.slice(1);return CompiledLookup.create(inner,path);}else if(local = builder.symbolTable.getSymbol('local',head)){var path=parts.slice(1);var inner=new CompiledSymbol(local,head);return CompiledLookup.create(inner,path);}else {var inner=new CompiledSelf();return CompiledLookup.create(inner,parts);}}var Blocks=(function(){function Blocks(){this.names = _glimmerUtil.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(sexp,builder){ // assert(sexp[1].length === 1, 'paths in blocks are not supported'); | |
var name=sexp[1][0];var index=this.names[name];if(index === undefined){_glimmerUtil.assert(!!this.missing,name + ' not found, and no catch-all block handler was registered');var func=this.missing;var handled=func(sexp,builder);_glimmerUtil.assert(!!handled,name + ' not found, and the catch-all block handler didn\'t handle it');}else {var func=this.funcs[index];func(sexp,builder);}};return Blocks;})();var BLOCKS=new Blocks();var Inlines=(function(){function Inlines(){this.names = _glimmerUtil.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 path=undefined;var params=undefined;var hash=undefined;if(value[0] === Ops$1.Helper){path = value[1];params = value[2];hash = value[3];}else if(value[0] === Ops$1.Unknown){path = value[1];params = hash = null;}else {return ['expr',value];}if(path.length > 1 && !params && !hash){return ['expr',value];}var name=path[0];var index=this.names[name];if(index === undefined && this.missing){var func=this.missing;var returned=func(path,params,hash,builder);return returned === false?['expr',value]:returned;}else if(index !== undefined){var func=this.funcs[index];var returned=func(path,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?new Blocks():arguments[0];var inlines=arguments.length <= 1 || arguments[1] === undefined?new Inlines():arguments[1];blocks.add('if',function(sexp,builder){ // PutArgs | |
// Test(Environment) | |
// Enter(BEGIN, END) | |
// BEGIN: Noop | |
// JumpUnless(ELSE) | |
// Evaluate(default) | |
// Jump(END) | |
// ELSE: Noop | |
// Evalulate(inverse) | |
// END: Noop | |
// Exit | |
var params=sexp[2];var hash=sexp[3];var _default=sexp[4];var inverse=sexp[5];var args=compileArgs(params,hash,builder);builder.putArgs(args);builder.test('environment');builder.labelled(null,function(b){if(_default && inverse){b.jumpUnless('ELSE');b.evaluate(_default);b.jump('END');b.label('ELSE');b.evaluate(inverse);}else if(_default){b.jumpUnless('END');b.evaluate(_default);}else {throw _glimmerUtil.unreachable();}});});blocks.add('-in-element',function(sexp,builder){var block=defaultBlock(sexp);var args=compileArgs(params(sexp),null,builder);builder.putArgs(args);builder.test('simple');builder.labelled(null,function(b){b.jumpUnless('END');b.pushRemoteElement();b.evaluate(_glimmerUtil.unwrap(block));b.popRemoteElement();});});blocks.add('-with-dynamic-vars',function(sexp,builder){var block=defaultBlock(sexp);var args=compileArgs(params(sexp),hash(sexp),builder);builder.unit(function(b){b.putArgs(args);b.pushDynamicScope();b.bindDynamicScope(args.named.keys);b.evaluate(_glimmerUtil.unwrap(block));b.popDynamicScope();});});blocks.add('unless',function(sexp,builder){ // PutArgs | |
// Test(Environment) | |
// Enter(BEGIN, END) | |
// BEGIN: Noop | |
// JumpUnless(ELSE) | |
// Evaluate(default) | |
// Jump(END) | |
// ELSE: Noop | |
// Evalulate(inverse) | |
// END: Noop | |
// Exit | |
var params=sexp[2];var hash=sexp[3];var _default=sexp[4];var inverse=sexp[5];var args=compileArgs(params,hash,builder);builder.putArgs(args);builder.test('environment');builder.labelled(null,function(b){if(_default && inverse){b.jumpIf('ELSE');b.evaluate(_default);b.jump('END');b.label('ELSE');b.evaluate(inverse);}else if(_default){b.jumpIf('END');b.evaluate(_default);}else {throw _glimmerUtil.unreachable();}});});blocks.add('with',function(sexp,builder){ // PutArgs | |
// Test(Environment) | |
// Enter(BEGIN, END) | |
// BEGIN: Noop | |
// JumpUnless(ELSE) | |
// Evaluate(default) | |
// Jump(END) | |
// ELSE: Noop | |
// Evalulate(inverse) | |
// END: Noop | |
// Exit | |
var params=sexp[2];var hash=sexp[3];var _default=sexp[4];var inverse=sexp[5];var args=compileArgs(params,hash,builder);builder.putArgs(args);builder.test('environment');builder.labelled(null,function(b){if(_default && inverse){b.jumpUnless('ELSE');b.evaluate(_default);b.jump('END');b.label('ELSE');b.evaluate(inverse);}else if(_default){b.jumpUnless('END');b.evaluate(_default);}else {throw _glimmerUtil.unreachable();}});});blocks.add('each',function(sexp,builder){ // Enter(BEGIN, END) | |
// BEGIN: Noop | |
// PutArgs | |
// PutIterable | |
// JumpUnless(ELSE) | |
// EnterList(BEGIN2, END2) | |
// ITER: Noop | |
// NextIter(BREAK) | |
// EnterWithKey(BEGIN2, END2) | |
// BEGIN2: Noop | |
// PushChildScope | |
// Evaluate(default) | |
// PopScope | |
// END2: Noop | |
// Exit | |
// Jump(ITER) | |
// BREAK: Noop | |
// ExitList | |
// Jump(END) | |
// ELSE: Noop | |
// Evalulate(inverse) | |
// END: Noop | |
// Exit | |
var params=sexp[2];var hash=sexp[3];var _default=sexp[4];var inverse=sexp[5];var args=compileArgs(params,hash,builder);builder.labelled(args,function(b){b.putIterator();if(inverse){b.jumpUnless('ELSE');}else {b.jumpUnless('END');}b.iter(function(b){b.evaluate(_glimmerUtil.unwrap(_default));});if(inverse){b.jump('END');b.label('ELSE');b.evaluate(inverse);}});});return {blocks:blocks,inlines:inlines};}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=undefined,normalized=undefined;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;}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){babelHelpers.inherits(DOMChangesWithInnerHTMLFix,_DOMChangesClass);function DOMChangesWithInnerHTMLFix(){_DOMChangesClass.apply(this,arguments);}DOMChangesWithInnerHTMLFix.prototype.insertHTMLBefore = function insertHTMLBefore(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(_DOMTreeConstructionClass){babelHelpers.inherits(DOMTreeConstructionWithInnerHTMLFix,_DOMTreeConstructionClass);function DOMTreeConstructionWithInnerHTMLFix(){_DOMTreeConstructionClass.apply(this,arguments);}DOMTreeConstructionWithInnerHTMLFix.prototype.insertHTMLBefore = function insertHTMLBefore(parent,html,reference){if(html === null || html === ''){return _DOMTreeConstructionClass.prototype.insertHTMLBefore.call(this,parent,html,reference);}var parentTag=parent.tagName.toLowerCase();var wrapper=innerHTMLWrapper[parentTag];if(wrapper === undefined){return _DOMTreeConstructionClass.prototype.insertHTMLBefore.call(this,parent,html,reference);}return fixInnerHTML(parent,wrapper,div,html,reference);};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);var first=_moveNodesBefore[0];var 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;}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(_DOMChangesClass2){babelHelpers.inherits(DOMChangesWithSVGInnerHTMLFix,_DOMChangesClass2);function DOMChangesWithSVGInnerHTMLFix(){_DOMChangesClass2.apply(this,arguments);}DOMChangesWithSVGInnerHTMLFix.prototype.insertHTMLBefore = function insertHTMLBefore(parent,nextSibling,html){if(html === null || html === ''){return _DOMChangesClass2.prototype.insertHTMLBefore.call(this,parent,nextSibling,html);}if(parent.namespaceURI !== svgNamespace){return _DOMChangesClass2.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(_TreeConstructionClass){babelHelpers.inherits(TreeConstructionWithSVGInnerHTMLFix,_TreeConstructionClass);function TreeConstructionWithSVGInnerHTMLFix(){_TreeConstructionClass.apply(this,arguments);}TreeConstructionWithSVGInnerHTMLFix.prototype.insertHTMLBefore = function insertHTMLBefore(parent,html,reference){if(html === null || html === ''){return _TreeConstructionClass.prototype.insertHTMLBefore.call(this,parent,html,reference);}if(parent.namespaceURI !== svgNamespace){return _TreeConstructionClass.prototype.insertHTMLBefore.call(this,parent,html,reference);}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 _moveNodesBefore2=moveNodesBefore(div.firstChild,parent,reference);var first=_moveNodesBefore2[0];var last=_moveNodesBefore2[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 && _glimmerUtil.unwrap(svg.firstChild).namespaceURI === SVG_NAMESPACE$1){ // The test worked as expected, no fix required | |
return false;}return true;}} // 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(_DOMChangesClass3){babelHelpers.inherits(DOMChangesWithTextNodeMergingFix,_DOMChangesClass3);function DOMChangesWithTextNodeMergingFix(document){_DOMChangesClass3.call(this,document);this.uselessComment = document.createComment('');}DOMChangesWithTextNodeMergingFix.prototype.insertHTMLBefore = function insertHTMLBefore(parent,nextSibling,html){if(html === null){return _DOMChangesClass3.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=_DOMChangesClass3.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(_TreeConstructionClass2){babelHelpers.inherits(TreeConstructionWithTextNodeMergingFix,_TreeConstructionClass2);function TreeConstructionWithTextNodeMergingFix(document){_TreeConstructionClass2.call(this,document);this.uselessComment = this.createComment('');}TreeConstructionWithTextNodeMergingFix.prototype.insertHTMLBefore = function insertHTMLBefore(parent,html,reference){if(html === null){return _TreeConstructionClass2.prototype.insertHTMLBefore.call(this,parent,html,reference);}var didSetUselessComment=false;var nextPrevious=reference?reference.previousSibling:parent.lastChild;if(nextPrevious && nextPrevious instanceof Text){didSetUselessComment = true;parent.insertBefore(this.uselessComment,reference);}var bounds=_TreeConstructionClass2.prototype.insertHTMLBefore.call(this,parent,html,reference);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;}var SVG_NAMESPACE='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 DOM;(function(DOM){var TreeConstruction=(function(){function TreeConstruction(document){this.document = document;this.setupUselessElement();}TreeConstruction.prototype.setupUselessElement = function setupUselessElement(){this.uselessElement = this.document.createElement('div');};TreeConstruction.prototype.createElement = function createElement(tag,context){var isElementInSVGNamespace=undefined,isHTMLIntegrationPoint=undefined;if(context){isElementInSVGNamespace = context.namespaceURI === SVG_NAMESPACE || 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,tag);}else {return this.document.createElement(tag);}};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);}};TreeConstruction.prototype.createTextNode = function createTextNode(text){return this.document.createTextNode(text);};TreeConstruction.prototype.createComment = function createComment(data){return this.document.createComment(data);};TreeConstruction.prototype.insertBefore = function insertBefore(parent,node,reference){parent.insertBefore(node,reference);};TreeConstruction.prototype.insertHTMLBefore = function insertHTMLBefore(parent,html,reference){return _insertHTMLBefore(this.uselessElement,parent,reference,html);};return TreeConstruction;})();DOM.TreeConstruction = TreeConstruction;var appliedTreeContruction=TreeConstruction;appliedTreeContruction = treeConstruction$2(doc,appliedTreeContruction);appliedTreeContruction = treeConstruction(doc,appliedTreeContruction);appliedTreeContruction = treeConstruction$1(doc,appliedTreeContruction,SVG_NAMESPACE);DOM.DOMTreeConstruction = appliedTreeContruction;})(DOM || (DOM = {}));var DOMChanges=(function(){function DOMChanges(document){this.document = document;this.namespace = null;this.uselessElement = this.document.createElement('div');}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.createTextNode = function createTextNode(text){return this.document.createTextNode(text);};DOMChanges.prototype.createComment = function createComment(data){return this.document.createComment(data);};DOMChanges.prototype.createElement = function createElement(tag,context){var isElementInSVGNamespace=undefined,isHTMLIntegrationPoint=undefined;if(context){isElementInSVGNamespace = context.namespaceURI === SVG_NAMESPACE || 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,tag);}else {return this.document.createElement(tag);}};DOMChanges.prototype.insertHTMLBefore = function insertHTMLBefore(_parent,nextSibling,html){return _insertHTMLBefore(this.uselessElement,_parent,nextSibling,html);};DOMChanges.prototype.insertNodeBefore = function insertNodeBefore(parent,node,reference){if(isDocumentFragment(node)){var firstChild=node.firstChild;var 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;})();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=undefined;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);var helper$1=helper;var DOMTreeConstruction=DOM.DOMTreeConstruction;function defaultManagers(element,attr,_isTrusting,_namespace){var tagName=element.tagName;var isSVG=element.namespaceURI === SVG_NAMESPACE;if(isSVG){return defaultAttributeManagers(tagName,attr);}var _normalizeProperty=normalizeProperty(element,attr);var type=_normalizeProperty.type;var 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;var _normalizeProperty2=normalizeProperty(element,attr);var type=_normalizeProperty2.type;var 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){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){babelHelpers.inherits(PropertyManager,_AttributeManager);function PropertyManager(){_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){babelHelpers.inherits(SafePropertyManager,_PropertyManager);function SafePropertyManager(){_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){babelHelpers.inherits(InputValuePropertyManager,_AttributeManager2);function InputValuePropertyManager(){_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){babelHelpers.inherits(OptionSelectedManager,_PropertyManager2);function OptionSelectedManager(){_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){babelHelpers.inherits(SafeAttributeManager,_AttributeManager3);function SafeAttributeManager(){_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 Scope=(function(){function Scope(references){var callerScope=arguments.length <= 1 || arguments[1] === undefined?null:arguments[1];this.callerScope = null;this.slots = references;this.callerScope = callerScope;}Scope.root = function root(self){var size=arguments.length <= 1 || arguments[1] === undefined?0:arguments[1];var refs=new Array(size + 1);for(var i=0;i <= size;i++) {refs[i] = UNDEFINED_REFERENCE;}return new Scope(refs).init({self:self});};Scope.prototype.init = function init(_ref27){var self=_ref27.self;this.slots[0] = self;return this;};Scope.prototype.getSelf = function getSelf(){return this.slots[0];};Scope.prototype.getSymbol = function getSymbol(symbol){return this.slots[symbol];};Scope.prototype.getBlock = function getBlock(symbol){return this.slots[symbol];};Scope.prototype.getPartialArgs = function getPartialArgs(symbol){return this.slots[symbol];};Scope.prototype.bindSymbol = function bindSymbol(symbol,value){this.slots[symbol] = value;};Scope.prototype.bindBlock = function bindBlock(symbol,value){this.slots[symbol] = value;};Scope.prototype.bindPartialArgs = function bindPartialArgs(symbol,value){this.slots[symbol] = value;};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);};return Scope;})();var Transaction=(function(){function 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;var 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;var 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 i=0;i < destructors.length;i++) {destructors[i].destroy();}var scheduledInstallManagers=this.scheduledInstallManagers;var scheduledInstallModifiers=this.scheduledInstallModifiers;for(var i=0;i < scheduledInstallManagers.length;i++) {var manager=scheduledInstallManagers[i];var modifier=scheduledInstallModifiers[i];manager.install(modifier);}var scheduledUpdateModifierManagers=this.scheduledUpdateModifierManagers;var scheduledUpdateModifiers=this.scheduledUpdateModifiers;for(var i=0;i < scheduledUpdateModifierManagers.length;i++) {var manager=scheduledUpdateModifierManagers[i];var modifier=scheduledUpdateModifiers[i];manager.update(modifier);}};return Transaction;})();var Opcode=(function(){function Opcode(array){this.array = array;this.offset = 0;}babelHelpers.createClass(Opcode,[{key:'type',get:function(){return this.array[this.offset];}},{key:'op1',get:function(){return this.array[this.offset + 1];}},{key:'op2',get:function(){return this.array[this.offset + 2];}},{key:'op3',get:function(){return this.array[this.offset + 3];}}]);return Opcode;})();var Program=(function(){function Program(){this.opcodes = [];this._offset = 0;this._opcode = new Opcode(this.opcodes);}Program.prototype.opcode = function opcode(offset){this._opcode.offset = offset;return this._opcode;};Program.prototype.set = function set(pos,type){var op1=arguments.length <= 2 || arguments[2] === undefined?0:arguments[2];var op2=arguments.length <= 3 || arguments[3] === undefined?0:arguments[3];var op3=arguments.length <= 4 || arguments[4] === undefined?0:arguments[4];this.opcodes[pos] = type;this.opcodes[pos + 1] = op1;this.opcodes[pos + 2] = op2;this.opcodes[pos + 3] = op3;};Program.prototype.push = function push(type){var op1=arguments.length <= 1 || arguments[1] === undefined?0:arguments[1];var op2=arguments.length <= 2 || arguments[2] === undefined?0:arguments[2];var op3=arguments.length <= 3 || arguments[3] === undefined?0:arguments[3];var offset=this._offset;this.opcodes[this._offset++] = type;this.opcodes[this._offset++] = op1;this.opcodes[this._offset++] = op2;this.opcodes[this._offset++] = op3;return offset;};babelHelpers.createClass(Program,[{key:'next',get:function(){return this._offset;}},{key:'current',get:function(){return this._offset - 4;}}]);return Program;})();var Environment=(function(){function Environment(_ref28){var appendOperations=_ref28.appendOperations;var updateOperations=_ref28.updateOperations;this._macros = null;this._transaction = null;this.constants = new Constants();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 _glimmerUtil.ensureGuid(object) + '';};Environment.prototype.begin = function begin(){_glimmerUtil.assert(!this._transaction,'Cannot start 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(){this.transaction.commit();this._transaction = null;};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 = populateBuiltins();}return macros;};babelHelpers.createClass(Environment,[{key:'transaction',get:function(){return _glimmerUtil.expect(this._transaction,'must be in a transaction');}}]);return Environment;})();var RenderResult=(function(){function RenderResult(env,updating,bounds){this.env = env;this.updating = updating;this.bounds = bounds;}RenderResult.prototype.rerender = function rerender(){var _ref29=arguments.length <= 0 || arguments[0] === undefined?{alwaysRevalidate:false}:arguments[0];var _ref29$alwaysRevalidate=_ref29.alwaysRevalidate;var alwaysRevalidate=_ref29$alwaysRevalidate === undefined?false:_ref29$alwaysRevalidate;var env=this.env;var 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 CapturedFrame=function CapturedFrame(operand,args,condition){this.operand = operand;this.args = args;this.condition = condition;};var Frame=(function(){function Frame(start,end){var component=arguments.length <= 2 || arguments[2] === undefined?null:arguments[2];var manager=arguments.length <= 3 || arguments[3] === undefined?null:arguments[3];var shadow=arguments.length <= 4 || arguments[4] === undefined?null:arguments[4];this.start = start;this.end = end;this.component = component;this.manager = manager;this.shadow = shadow;this.operand = null;this.immediate = null;this.args = null;this.callerScope = null;this.blocks = null;this.condition = null;this.iterator = null;this.key = null;this.ip = start;}Frame.prototype.capture = function capture(){return new CapturedFrame(this.operand,this.args,this.condition);};Frame.prototype.restore = function restore(frame){this.operand = frame.operand;this.args = frame.args;this.condition = frame.condition;};return Frame;})();var FrameStack=(function(){function FrameStack(){this.frames = [];this.frame = -1;}FrameStack.prototype.push = function push(start,end){var component=arguments.length <= 2 || arguments[2] === undefined?null:arguments[2];var manager=arguments.length <= 3 || arguments[3] === undefined?null:arguments[3];var shadow=arguments.length <= 4 || arguments[4] === undefined?null:arguments[4];var pos=++this.frame;if(pos < this.frames.length){var frame=this.frames[pos];frame.start = frame.ip = start;frame.end = end;frame.component = component;frame.manager = manager;frame.shadow = shadow;frame.operand = null;frame.immediate = null;frame.args = null;frame.callerScope = null;frame.blocks = null;frame.condition = null;frame.iterator = null;frame.key = null;}else {this.frames[pos] = new Frame(start,end,component,manager,shadow);}};FrameStack.prototype.pop = function pop(){this.frame--;};FrameStack.prototype.capture = function capture(){return this.currentFrame.capture();};FrameStack.prototype.restore = function restore(frame){this.currentFrame.restore(frame);};FrameStack.prototype.getStart = function getStart(){return this.currentFrame.start;};FrameStack.prototype.getEnd = function getEnd(){return this.currentFrame.end;};FrameStack.prototype.getCurrent = function getCurrent(){return this.currentFrame.ip;};FrameStack.prototype.setCurrent = function setCurrent(ip){return this.currentFrame.ip = ip;};FrameStack.prototype.getOperand = function getOperand(){return _glimmerUtil.unwrap(this.currentFrame.operand);};FrameStack.prototype.setOperand = function setOperand(operand){return this.currentFrame.operand = operand;};FrameStack.prototype.getImmediate = function getImmediate(){return this.currentFrame.immediate;};FrameStack.prototype.setImmediate = function setImmediate(value){return this.currentFrame.immediate = value;}; // FIXME: These options are required in practice by the existing code, but | |
// figure out why. | |
FrameStack.prototype.getArgs = function getArgs(){return this.currentFrame.args;};FrameStack.prototype.setArgs = function setArgs(args){return this.currentFrame.args = args;};FrameStack.prototype.getCondition = function getCondition(){return _glimmerUtil.unwrap(this.currentFrame.condition);};FrameStack.prototype.setCondition = function setCondition(condition){return this.currentFrame.condition = condition;};FrameStack.prototype.getIterator = function getIterator(){return _glimmerUtil.unwrap(this.currentFrame.iterator);};FrameStack.prototype.setIterator = function setIterator(iterator){return this.currentFrame.iterator = iterator;};FrameStack.prototype.getKey = function getKey(){return this.currentFrame.key;};FrameStack.prototype.setKey = function setKey(key){return this.currentFrame.key = key;};FrameStack.prototype.getBlocks = function getBlocks(){return _glimmerUtil.unwrap(this.currentFrame.blocks);};FrameStack.prototype.setBlocks = function setBlocks(blocks){return this.currentFrame.blocks = blocks;};FrameStack.prototype.getCallerScope = function getCallerScope(){return _glimmerUtil.unwrap(this.currentFrame.callerScope);};FrameStack.prototype.setCallerScope = function setCallerScope(callerScope){return this.currentFrame.callerScope = callerScope;};FrameStack.prototype.getComponent = function getComponent(){return _glimmerUtil.unwrap(this.currentFrame.component);};FrameStack.prototype.getManager = function getManager(){return _glimmerUtil.unwrap(this.currentFrame.manager);};FrameStack.prototype.getShadow = function getShadow(){return this.currentFrame.shadow;};FrameStack.prototype.goto = function goto(ip){this.setCurrent(ip);};FrameStack.prototype.nextStatement = function nextStatement(env){while(this.frame !== -1) {var frame=this.frames[this.frame];var ip=frame.ip;var end=frame.end;if(ip < end){var program=env.program;frame.ip += 4;return program.opcode(ip);}else {this.pop();}}return null;};babelHelpers.createClass(FrameStack,[{key:'currentFrame',get:function(){return this.frames[this.frame];}}]);return FrameStack;})();var VM=(function(){function VM(env,scope,dynamicScope,elementStack){this.env = env;this.elementStack = elementStack;this.dynamicScopeStack = new _glimmerUtil.Stack();this.scopeStack = new _glimmerUtil.Stack();this.updatingOpcodeStack = new _glimmerUtil.Stack();this.cacheGroups = new _glimmerUtil.Stack();this.listBlockStack = new _glimmerUtil.Stack();this.frame = new FrameStack();this.env = env;this.constants = env.constants;this.elementStack = elementStack;this.scopeStack.push(scope);this.dynamicScopeStack.push(dynamicScope);}VM.initial = function initial(env,self,dynamicScope,elementStack,compiledProgram){var size=compiledProgram.symbols;var start=compiledProgram.start;var end=compiledProgram.end;var scope=Scope.root(self,size);var vm=new VM(env,scope,dynamicScope,elementStack);vm.prepare(start,end);return vm;};VM.prototype.capture = function capture(){return {env:this.env,scope:this.scope(),dynamicScope:this.dynamicScope(),frame:this.frame.capture()};};VM.prototype.goto = function goto(ip){this.frame.goto(ip);};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=_glimmerReference.combineSlice(new _glimmerUtil.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(start,end){var updating=new _glimmerUtil.LinkedList();var tracker=this.stack().pushUpdatableBlock();var state=this.capture();var tryOpcode=new TryOpcode(start,end,state,tracker,updating);this.didEnter(tryOpcode,updating);};VM.prototype.enterWithKey = function enterWithKey(key,start,end){var updating=new _glimmerUtil.LinkedList();var tracker=this.stack().pushUpdatableBlock();var state=this.capture();var tryOpcode=new TryOpcode(start,end,state,tracker,updating);this.listBlock().map[key] = tryOpcode;this.didEnter(tryOpcode,updating);};VM.prototype.enterList = function enterList(start,end){var updating=new _glimmerUtil.LinkedList();var tracker=this.stack().pushBlockList(updating);var state=this.capture();var artifacts=this.frame.getIterator().artifacts;var opcode=new ListBlockOpcode(start,end,state,tracker,updating,artifacts);this.listBlockStack.push(opcode);this.didEnter(opcode,updating);};VM.prototype.didEnter = function didEnter(opcode,updating){this.updateWith(opcode);this.updatingOpcodeStack.push(updating);};VM.prototype.exit = function exit(){this.stack().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 _glimmerUtil.expect(this.listBlockStack.current,'expected a list block');};VM.prototype.updating = function updating(){return _glimmerUtil.expect(this.updatingOpcodeStack.current,'expected updating opcode on the updating opcode stack');};VM.prototype.stack = function stack(){return this.elementStack;};VM.prototype.scope = function scope(){return _glimmerUtil.expect(this.scopeStack.current,'expected scope on the scope stack');};VM.prototype.dynamicScope = function dynamicScope(){return _glimmerUtil.expect(this.dynamicScopeStack.current,'expected dynamic scope on the dynamic scope stack');};VM.prototype.pushFrame = function pushFrame(block,args,callerScope){this.frame.push(block.start,block.end);if(args)this.frame.setArgs(args);if(args && args.blocks)this.frame.setBlocks(args.blocks);if(callerScope)this.frame.setCallerScope(callerScope);};VM.prototype.pushComponentFrame = function pushComponentFrame(layout,args,callerScope,component,manager,shadow){this.frame.push(layout.start,layout.end,component,manager,shadow);if(args)this.frame.setArgs(args);if(args && args.blocks)this.frame.setBlocks(args.blocks);if(callerScope)this.frame.setCallerScope(callerScope);};VM.prototype.pushEvalFrame = function pushEvalFrame(start,end){this.frame.push(start,end);};VM.prototype.pushChildScope = function pushChildScope(){this.scopeStack.push(this.scope().child());};VM.prototype.pushCallerScope = function pushCallerScope(){this.scopeStack.push(_glimmerUtil.expect(this.scope().getCallerScope(),'pushCallerScope is called when a caller scope is present'));};VM.prototype.pushDynamicScope = function pushDynamicScope(){var child=this.dynamicScope().child();this.dynamicScopeStack.push(child);return child;};VM.prototype.pushRootScope = function pushRootScope(self,size){var scope=Scope.root(self,size);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.stack().newDestroyable(d);}; /// SCOPE HELPERS | |
VM.prototype.getSelf = function getSelf(){return this.scope().getSelf();};VM.prototype.referenceForSymbol = function referenceForSymbol(symbol){return this.scope().getSymbol(symbol);};VM.prototype.getArgs = function getArgs(){return this.frame.getArgs();}; /// EXECUTION | |
VM.prototype.resume = function resume(start,end,frame){return this.execute(start,end,function(vm){return vm.frame.restore(frame);});};VM.prototype.execute = function execute(start,end,initialize){this.prepare(start,end,initialize);var result=undefined;while(true) {result = this.next();if(result.done)break;}return result.value;};VM.prototype.prepare = function prepare(start,end,initialize){var elementStack=this.elementStack;var frame=this.frame;var updatingOpcodeStack=this.updatingOpcodeStack;elementStack.pushSimpleBlock();updatingOpcodeStack.push(new _glimmerUtil.LinkedList());frame.push(start,end);if(initialize)initialize(this);};VM.prototype.next = function next(){var frame=this.frame;var env=this.env;var updatingOpcodeStack=this.updatingOpcodeStack;var elementStack=this.elementStack;var opcode=undefined;if(opcode = frame.nextStatement(env)){APPEND_OPCODES.evaluate(this,opcode);return {done:false,value:null};}return {done:true,value:new RenderResult(env,_glimmerUtil.expect(updatingOpcodeStack.pop(),'there should be a final updating opcode stack'),elementStack.popBlock())};};VM.prototype.evaluateOpcode = function evaluateOpcode(opcode){APPEND_OPCODES.evaluate(this,opcode);}; // Make sure you have opcodes that push and pop a scope around this opcode | |
// if you need to change the scope. | |
VM.prototype.invokeBlock = function invokeBlock(block,args){var compiled=block.compile(this.env);this.pushFrame(compiled,args);};VM.prototype.invokePartial = function invokePartial(block){var compiled=block.compile(this.env);this.pushFrame(compiled);};VM.prototype.invokeLayout = function invokeLayout(args,layout,callerScope,component,manager,shadow){this.pushComponentFrame(layout,args,callerScope,component,manager,shadow);};VM.prototype.evaluateOperand = function evaluateOperand(expr){this.frame.setOperand(expr.evaluate(this));};VM.prototype.evaluateArgs = function evaluateArgs(args){var evaledArgs=this.frame.setArgs(args.evaluate(this));this.frame.setOperand(evaledArgs.positional.at(0));};VM.prototype.bindPositionalArgs = function bindPositionalArgs(symbols){var args=_glimmerUtil.expect(this.frame.getArgs(),'bindPositionalArgs assumes a previous setArgs');var positional=args.positional;var scope=this.scope();for(var i=0;i < symbols.length;i++) {scope.bindSymbol(symbols[i],positional.at(i));}};VM.prototype.bindNamedArgs = function bindNamedArgs(names,symbols){var args=_glimmerUtil.expect(this.frame.getArgs(),'bindNamedArgs assumes a previous setArgs');var scope=this.scope();var named=args.named;for(var i=0;i < names.length;i++) {var _name2=this.constants.getString(names[i]);scope.bindSymbol(symbols[i],named.get(_name2));}};VM.prototype.bindBlocks = function bindBlocks(names,symbols){var blocks=this.frame.getBlocks();var scope=this.scope();for(var i=0;i < names.length;i++) {var _name3=this.constants.getString(names[i]);scope.bindBlock(symbols[i],blocks && blocks[_name3] || null);}};VM.prototype.bindPartialArgs = function bindPartialArgs(symbol){var args=_glimmerUtil.expect(this.frame.getArgs(),'bindPartialArgs assumes a previous setArgs');var scope=this.scope();_glimmerUtil.assert(args,"Cannot bind named args");scope.bindPartialArgs(symbol,args);};VM.prototype.bindCallerScope = function bindCallerScope(){var callerScope=this.frame.getCallerScope();var scope=this.scope();_glimmerUtil.assert(callerScope,"Cannot bind caller scope");scope.bindCallerScope(callerScope);};VM.prototype.bindDynamicScope = function bindDynamicScope(names){var args=_glimmerUtil.expect(this.frame.getArgs(),'bindDynamicScope assumes a previous setArgs');var scope=this.dynamicScope();_glimmerUtil.assert(args,"Cannot bind dynamic scope");for(var i=0;i < names.length;i++) {var _name4=this.constants.getString(names[i]);scope.set(_name4,args.named.get(_name4));}};return VM;})();var UpdatingVM=(function(){function UpdatingVM(env,_ref30){var _ref30$alwaysRevalidate=_ref30.alwaysRevalidate;var alwaysRevalidate=_ref30$alwaysRevalidate === undefined?false:_ref30$alwaysRevalidate;this.frameStack = new _glimmerUtil.Stack();this.env = env;this.constants = env.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);};babelHelpers.createClass(UpdatingVM,[{key:'frame',get:function(){return _glimmerUtil.expect(this.frameStack.current,'bug: expected a frame');}}]);return UpdatingVM;})();var BlockOpcode=(function(_UpdatingOpcode8){babelHelpers.inherits(BlockOpcode,_UpdatingOpcode8);function BlockOpcode(start,end,state,bounds,children){_UpdatingOpcode8.call(this);this.start = start;this.end = end;this.type = "block";this.next = null;this.prev = null;var env=state.env;var scope=state.scope;var dynamicScope=state.dynamicScope;var frame=state.frame;this.children = children;this.env = env;this.scope = scope;this.dynamicScope = dynamicScope;this.frame = frame;this.bounds = bounds;}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=_glimmerUtil.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){babelHelpers.inherits(TryOpcode,_BlockOpcode);function TryOpcode(start,end,state,bounds,children){_BlockOpcode.call(this,start,end,state,bounds,children);this.type = "try";this.tag = this._tag = new _glimmerReference.UpdatableTag(_glimmerReference.CONSTANT_TAG);}TryOpcode.prototype.didInitializeChildren = function didInitializeChildren(){this._tag.update(_glimmerReference.combineSlice(this.children));};TryOpcode.prototype.evaluate = function evaluate(vm){vm.try(this.children,this);};TryOpcode.prototype.handleException = function handleException(){var env=this.env;var scope=this.scope;var start=this.start;var end=this.end;var dynamicScope=this.dynamicScope;var frame=this.frame;var elementStack=ElementStack.resume(this.env,this.bounds,this.bounds.reset(env));var vm=new VM(env,scope,dynamicScope,elementStack);var result=vm.resume(start,end,frame);this.children = result.opcodes();this.didInitializeChildren();};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){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=this.map;var opcode=this.opcode;var updating=this.updating;var nextSibling=null;var reference=null;if(before){reference = map[before];nextSibling = reference['bounds'].firstNode();}else {nextSibling = this.marker;}var vm=opcode.vmForInsertion(nextSibling);var tryOpcode=null;vm.execute(opcode.start,opcode.end,function(vm){vm.frame.setArgs(EvaluatedArgs.positional([item,memo]));vm.frame.setOperand(item);vm.frame.setCondition(new _glimmerReference.ConstReference(true));vm.frame.setKey(key);var state=vm.capture();var tracker=vm.stack().pushUpdatableBlock();tryOpcode = new TryOpcode(opcode.start,opcode.end,state,tracker,vm.updating());});tryOpcode.didInitializeChildren();updating.insertBefore(tryOpcode,reference);map[key] = tryOpcode;this.didInsert = true;};ListRevalidationDelegate.prototype.retain = function retain(_key,_item,_memo){};ListRevalidationDelegate.prototype.move = function move(key,_item,_memo,before){var map=this.map;var updating=this.updating;var entry=map[key];var reference=map[before] || null;if(before){moveBounds(entry,reference.firstNode());}else {moveBounds(entry,this.marker);}updating.remove(entry);updating.insertBefore(entry,reference);};ListRevalidationDelegate.prototype.delete = function _delete(key){var map=this.map;var opcode=map[key];opcode.didDestroy();clear(opcode);this.updating.remove(opcode);delete map[key];this.didDelete = true;};ListRevalidationDelegate.prototype.done = function done(){this.opcode.didInitializeChildren(this.didInsert || this.didDelete);};return ListRevalidationDelegate;})();var ListBlockOpcode=(function(_BlockOpcode2){babelHelpers.inherits(ListBlockOpcode,_BlockOpcode2);function ListBlockOpcode(start,end,state,bounds,children,artifacts){_BlockOpcode2.call(this,start,end,state,bounds,children);this.type = "list-block";this.map = _glimmerUtil.dict();this.lastIterated = _glimmerReference.INITIAL;this.artifacts = artifacts;var _tag=this._tag = new _glimmerReference.UpdatableTag(_glimmerReference.CONSTANT_TAG);this.tag = _glimmerReference.combine([artifacts.tag,_tag]);}ListBlockOpcode.prototype.didInitializeChildren = function didInitializeChildren(){var listDidChange=arguments.length <= 0 || arguments[0] === undefined?true:arguments[0];this.lastIterated = this.artifacts.tag.value();if(listDidChange){this._tag.update(_glimmerReference.combineSlice(this.children));}};ListBlockOpcode.prototype.evaluate = function evaluate(vm){var artifacts=this.artifacts;var lastIterated=this.lastIterated;if(!artifacts.tag.validate(lastIterated)){var bounds=this.bounds;var dom=vm.dom;var marker=dom.createComment('');dom.insertAfter(bounds.parentElement(),marker,_glimmerUtil.expect(bounds.lastNode(),"can't insert after an empty bounds"));var target=new ListRevalidationDelegate(this,marker);var synchronizer=new _glimmerReference.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;var scope=this.scope;var 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=this.map;var inner=Object.keys(map).map(function(key){return JSON.stringify(key) + ': ' + map[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){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;var 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;})();APPEND_OPCODES.add(31, /* DynamicContent */function(vm,_ref31){var append=_ref31.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(){}AppendDynamicOpcode.prototype.evaluate = function evaluate(vm){var reference=vm.frame.getOperand();var normalized=this.normalize(reference);var value=undefined,cache=undefined;if(_glimmerReference.isConst(reference)){value = normalized.value();}else {cache = new _glimmerReference.ReferenceCache(normalized);value = cache.peek();}var stack=vm.stack();var upsert=this.insert(vm.env.getAppendOperations(),stack,value);var bounds=new Fragment(upsert.bounds);stack.newBounds(bounds);if(cache /* i.e. !isConst(reference) */){vm.updateWith(this.updateWith(vm,reference,cache,bounds,upsert));}};return AppendDynamicOpcode;})();var GuardedAppendOpcode=(function(_AppendDynamicOpcode){babelHelpers.inherits(GuardedAppendOpcode,_AppendDynamicOpcode);function GuardedAppendOpcode(expression,symbolTable){_AppendDynamicOpcode.call(this);this.expression = expression;this.symbolTable = symbolTable;this.start = -1;this.end = -1;}GuardedAppendOpcode.prototype.evaluate = function evaluate(vm){if(this.start === -1){vm.evaluateOperand(this.expression);var value=vm.frame.getOperand().value();if(isComponentDefinition(value)){this.deopt(vm.env);vm.pushEvalFrame(this.start,this.end);}else {_AppendDynamicOpcode.prototype.evaluate.call(this,vm);}}else {vm.pushEvalFrame(this.start,this.end);}};GuardedAppendOpcode.prototype.deopt = function deopt(env){var _this3=this; // At compile time, we determined that this append callsite might refer | |
// to a local variable/property lookup that resolves to a component | |
// definition at runtime. | |
// | |
// We could have eagerly compiled this callsite into something like this: | |
// | |
// {{#if (is-component-definition foo)}} | |
// {{component foo}} | |
// {{else}} | |
// {{foo}} | |
// {{/if}} | |
// | |
// However, in practice, there might be a large amout of these callsites | |
// and most of them would resolve to a simple value lookup. Therefore, we | |
// tried to be optimistic and assumed that the callsite will resolve to | |
// appending a simple value. | |
// | |
// However, we have reached here because at runtime, the guard conditional | |
// have detected that this callsite is indeed referring to a component | |
// definition object. Since this is likely going to be true for other | |
// instances of the same callsite, it is now appropiate to deopt into the | |
// expanded version that handles both cases. The compilation would look | |
// like this: | |
// | |
// PutValue(expression) | |
// Test(is-component-definition) | |
// Enter(BEGIN, END) | |
// BEGIN: Noop | |
// JumpUnless(VALUE) | |
// PutDynamicComponentDefinitionOpcode | |
// OpenComponent | |
// CloseComponent | |
// Jump(END) | |
// VALUE: Noop | |
// OptimizedAppend | |
// END: Noop | |
// Exit | |
// | |
// Keep in mind that even if we *don't* reach here at initial render time, | |
// it is still possible (although quite rare) that the simple value we | |
// encounter during initial render could later change into a component | |
// definition object at update time. That is handled by the "lazy deopt" | |
// code on the update side (scroll down for the next big block of comment). | |
var dsl=new OpcodeBuilder(this.symbolTable,env);dsl.putValue(this.expression);dsl.test(IsComponentDefinitionReference.create);dsl.labelled(null,function(dsl,_BEGIN,END){dsl.jumpUnless('VALUE');dsl.putDynamicComponentDefinition();dsl.openComponent(CompiledArgs.empty());dsl.closeComponent();dsl.jump(END);dsl.label('VALUE');dsl.dynamicContent(new _this3.AppendOpcode());});this.start = dsl.start;this.end = dsl.end; // From this point on, we have essentially replaced ourselves with a new set | |
// of opcodes. Since we will always be executing the new/deopted code, it's | |
// a good idea (as a pattern) to null out any unneeded fields here to avoid | |
// holding on to unneeded/stale objects: | |
// QUESTION: Shouldn't this whole object be GCed? If not, why not? | |
this.expression = null;return dsl.start;};return GuardedAppendOpcode;})(AppendDynamicOpcode);var IsComponentDefinitionReference=(function(_ConditionalReference){babelHelpers.inherits(IsComponentDefinitionReference,_ConditionalReference);function IsComponentDefinitionReference(){_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(_UpdatingOpcode9){babelHelpers.inherits(UpdateOpcode,_UpdatingOpcode9);function UpdateOpcode(cache,bounds,upsert){_UpdatingOpcode9.call(this);this.cache = cache;this.bounds = bounds;this.upsert = upsert;this.tag = cache.tag;}UpdateOpcode.prototype.evaluate = function evaluate(vm){var value=this.cache.revalidate();if(_glimmerReference.isModified(value)){var bounds=this.bounds;var upsert=this.upsert;var dom=vm.dom;if(!this.upsert.update(dom,value)){var cursor=new Cursor(bounds.parentElement(),clear(bounds));upsert = this.upsert = this.insert(vm.env.getAppendOperations(),cursor,value);}bounds.update(upsert.bounds);}};UpdateOpcode.prototype.toJSON = function toJSON(){var guid=this._guid;var type=this.type;var cache=this.cache;return {guid:guid,type:type,details:{lastValue:JSON.stringify(cache.peek())}};};return UpdateOpcode;})(UpdatingOpcode);var GuardedUpdateOpcode=(function(_UpdateOpcode){babelHelpers.inherits(GuardedUpdateOpcode,_UpdateOpcode);function GuardedUpdateOpcode(reference,cache,bounds,upsert,appendOpcode,state){_UpdateOpcode.call(this,cache,bounds,upsert);this.reference = reference;this.appendOpcode = appendOpcode;this.state = state;this.deopted = null;this.tag = this._tag = new _glimmerReference.UpdatableTag(this.tag);}GuardedUpdateOpcode.prototype.evaluate = function evaluate(vm){if(this.deopted){vm.evaluateOpcode(this.deopted);}else {if(isComponentDefinition(this.reference.value())){this.lazyDeopt(vm);}else {_UpdateOpcode.prototype.evaluate.call(this,vm);}}};GuardedUpdateOpcode.prototype.lazyDeopt = function lazyDeopt(vm){ // Durign initial render, we know that the reference does not contain a | |
// component definition, so we optimistically assumed that this append | |
// is just a normal append. However, at update time, we discovered that | |
// the reference has switched into containing a component definition, so | |
// we need to do a "lazy deopt", simulating what would have happened if | |
// we had decided to perform the deopt in the first place during initial | |
// render. | |
// | |
// More concretely, we would have expanded the curly into a if/else, and | |
// based on whether the value is a component definition or not, we would | |
// have entered either the dynamic component branch or the simple value | |
// branch. | |
// | |
// Since we rendered a simple value during initial render (and all the | |
// updates up until this point), we need to pretend that the result is | |
// produced by the "VALUE" branch of the deopted append opcode: | |
// | |
// Try(BEGIN, END) | |
// Assert(IsComponentDefinition, expected=false) | |
// OptimizedUpdate | |
// | |
// In this case, because the reference has switched from being a simple | |
// value into a component definition, what would have happened is that | |
// the assert would throw, causing the Try opcode to teardown the bounds | |
// and rerun the original append opcode. | |
// | |
// Since the Try opcode would have nuked the updating opcodes anyway, we | |
// wouldn't have to worry about simulating those. All we have to do is to | |
// execute the Try opcode and immediately throw. | |
var bounds=this.bounds;var appendOpcode=this.appendOpcode;var state=this.state;var env=vm.env;var deoptStart=appendOpcode.deopt(env);var enter=_glimmerUtil.expect(env.program.opcode(deoptStart + 8),'hardcoded deopt location');var start=enter.op1;var end=enter.op2;var tracker=new UpdatableBlockTracker(bounds.parentElement());tracker.newBounds(this.bounds);var children=new _glimmerUtil.LinkedList();state.frame.condition = IsComponentDefinitionReference.create(_glimmerUtil.expect(state.frame['operand'],'operand should be populated'));var deopted=this.deopted = new TryOpcode(start,end,state,tracker,children);this._tag.update(deopted.tag);vm.evaluateOpcode(deopted);vm.throw(); // From this point on, we have essentially replaced ourselve with a new | |
// opcode. Since we will always be executing the new/deopted code, it's a | |
// good idea (as a pattern) to null out any unneeded fields here to avoid | |
// holding on to unneeded/stale objects: | |
// QUESTION: Shouldn't this whole object be GCed? If not, why not? | |
this._tag = null;this.reference = null;this.cache = null;this.bounds = null;this.upsert = null;this.appendOpcode = null;this.state = null;};GuardedUpdateOpcode.prototype.toJSON = function toJSON(){var guid=this._guid;var type=this.type;var deopted=this.deopted;if(deopted){return {guid:guid,type:type,deopted:true,children:[deopted.toJSON()]};}else {return _UpdateOpcode.prototype.toJSON.call(this);}};return GuardedUpdateOpcode;})(UpdateOpcode);var OptimizedCautiousAppendOpcode=(function(_AppendDynamicOpcode2){babelHelpers.inherits(OptimizedCautiousAppendOpcode,_AppendDynamicOpcode2);function OptimizedCautiousAppendOpcode(){_AppendDynamicOpcode2.apply(this,arguments);this.type = 'optimized-cautious-append';}OptimizedCautiousAppendOpcode.prototype.normalize = function normalize(reference){return _glimmerReference.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,upsert){return new OptimizedCautiousUpdateOpcode(cache,bounds,upsert);};return OptimizedCautiousAppendOpcode;})(AppendDynamicOpcode);var OptimizedCautiousUpdateOpcode=(function(_UpdateOpcode2){babelHelpers.inherits(OptimizedCautiousUpdateOpcode,_UpdateOpcode2);function OptimizedCautiousUpdateOpcode(){_UpdateOpcode2.apply(this,arguments);this.type = 'optimized-cautious-update';}OptimizedCautiousUpdateOpcode.prototype.insert = function insert(dom,cursor,value){return cautiousInsert(dom,cursor,value);};return OptimizedCautiousUpdateOpcode;})(UpdateOpcode);var GuardedCautiousAppendOpcode=(function(_GuardedAppendOpcode){babelHelpers.inherits(GuardedCautiousAppendOpcode,_GuardedAppendOpcode);function GuardedCautiousAppendOpcode(){_GuardedAppendOpcode.apply(this,arguments);this.type = 'guarded-cautious-append';this.AppendOpcode = OptimizedCautiousAppendOpcode;}GuardedCautiousAppendOpcode.prototype.normalize = function normalize(reference){return _glimmerReference.map(reference,normalizeValue);};GuardedCautiousAppendOpcode.prototype.insert = function insert(dom,cursor,value){return cautiousInsert(dom,cursor,value);};GuardedCautiousAppendOpcode.prototype.updateWith = function updateWith(vm,reference,cache,bounds,upsert){return new GuardedCautiousUpdateOpcode(reference,cache,bounds,upsert,this,vm.capture());};return GuardedCautiousAppendOpcode;})(GuardedAppendOpcode);var GuardedCautiousUpdateOpcode=(function(_GuardedUpdateOpcode){babelHelpers.inherits(GuardedCautiousUpdateOpcode,_GuardedUpdateOpcode);function GuardedCautiousUpdateOpcode(){_GuardedUpdateOpcode.apply(this,arguments);this.type = 'guarded-cautious-update';}GuardedCautiousUpdateOpcode.prototype.insert = function insert(dom,cursor,value){return cautiousInsert(dom,cursor,value);};return GuardedCautiousUpdateOpcode;})(GuardedUpdateOpcode);var OptimizedTrustingAppendOpcode=(function(_AppendDynamicOpcode3){babelHelpers.inherits(OptimizedTrustingAppendOpcode,_AppendDynamicOpcode3);function OptimizedTrustingAppendOpcode(){_AppendDynamicOpcode3.apply(this,arguments);this.type = 'optimized-trusting-append';}OptimizedTrustingAppendOpcode.prototype.normalize = function normalize(reference){return _glimmerReference.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,upsert){return new OptimizedTrustingUpdateOpcode(cache,bounds,upsert);};return OptimizedTrustingAppendOpcode;})(AppendDynamicOpcode);var OptimizedTrustingUpdateOpcode=(function(_UpdateOpcode3){babelHelpers.inherits(OptimizedTrustingUpdateOpcode,_UpdateOpcode3);function OptimizedTrustingUpdateOpcode(){_UpdateOpcode3.apply(this,arguments);this.type = 'optimized-trusting-update';}OptimizedTrustingUpdateOpcode.prototype.insert = function insert(dom,cursor,value){return trustingInsert(dom,cursor,value);};return OptimizedTrustingUpdateOpcode;})(UpdateOpcode);var GuardedTrustingAppendOpcode=(function(_GuardedAppendOpcode2){babelHelpers.inherits(GuardedTrustingAppendOpcode,_GuardedAppendOpcode2);function GuardedTrustingAppendOpcode(){_GuardedAppendOpcode2.apply(this,arguments);this.type = 'guarded-trusting-append';this.AppendOpcode = OptimizedTrustingAppendOpcode;}GuardedTrustingAppendOpcode.prototype.normalize = function normalize(reference){return _glimmerReference.map(reference,normalizeTrustedValue);};GuardedTrustingAppendOpcode.prototype.insert = function insert(dom,cursor,value){return trustingInsert(dom,cursor,value);};GuardedTrustingAppendOpcode.prototype.updateWith = function updateWith(vm,reference,cache,bounds,upsert){return new GuardedTrustingUpdateOpcode(reference,cache,bounds,upsert,this,vm.capture());};return GuardedTrustingAppendOpcode;})(GuardedAppendOpcode);var GuardedTrustingUpdateOpcode=(function(_GuardedUpdateOpcode2){babelHelpers.inherits(GuardedTrustingUpdateOpcode,_GuardedUpdateOpcode2);function GuardedTrustingUpdateOpcode(){_GuardedUpdateOpcode2.apply(this,arguments);this.type = 'trusting-update';}GuardedTrustingUpdateOpcode.prototype.insert = function insert(dom,cursor,value){return trustingInsert(dom,cursor,value);};return GuardedTrustingUpdateOpcode;})(GuardedUpdateOpcode);APPEND_OPCODES.add(49, /* PutDynamicPartial */function(vm,_ref32){var _symbolTable=_ref32.op1;var env=vm.env;var symbolTable=vm.constants.getOther(_symbolTable);function lookupPartial(name){var normalized=String(name);if(!env.hasPartial(normalized,symbolTable)){throw new Error('Could not find a partial named "' + normalized + '"');}return env.lookupPartial(normalized,symbolTable);}var reference=_glimmerReference.map(vm.frame.getOperand(),lookupPartial);var cache=_glimmerReference.isConst(reference)?undefined:new _glimmerReference.ReferenceCache(reference);var definition=cache?cache.peek():reference.value();vm.frame.setImmediate(definition);if(cache){vm.updateWith(new Assert(cache));}});APPEND_OPCODES.add(50, /* PutPartial */function(vm,_ref33){var _definition=_ref33.op1;var definition=vm.constants.getOther(_definition);vm.frame.setImmediate(definition);});APPEND_OPCODES.add(51, /* EvaluatePartial */function(vm,_ref34){var _symbolTable=_ref34.op1;var _cache=_ref34.op2;var symbolTable=vm.constants.getOther(_symbolTable);var cache=vm.constants.getOther(_cache);var _vm$frame$getImmediate=vm.frame.getImmediate();var template=_vm$frame$getImmediate.template;var block=cache[template.id];if(!block){block = template.asPartial(symbolTable);}vm.invokePartial(block);});var IterablePresenceReference=(function(){function IterablePresenceReference(artifacts){this.tag = artifacts.tag;this.artifacts = artifacts;}IterablePresenceReference.prototype.value = function value(){return !this.artifacts.isEmpty();};return IterablePresenceReference;})();APPEND_OPCODES.add(44, /* PutIterator */function(vm){var listRef=vm.frame.getOperand();var args=_glimmerUtil.expect(vm.frame.getArgs(),'PutIteratorOpcode expects a populated args register');var iterable=vm.env.iterableFor(listRef,args);var iterator=new _glimmerReference.ReferenceIterator(iterable);vm.frame.setIterator(iterator);vm.frame.setCondition(new IterablePresenceReference(iterator.artifacts));});APPEND_OPCODES.add(45, /* EnterList */function(vm,_ref35){var start=_ref35.op1;var end=_ref35.op2;vm.enterList(start,end);});APPEND_OPCODES.add(46, /* ExitList */function(vm){return vm.exitList();});APPEND_OPCODES.add(47, /* EnterWithKey */function(vm,_ref36){var start=_ref36.op1;var end=_ref36.op2;var key=_glimmerUtil.expect(vm.frame.getKey(),'EnterWithKeyOpcode expects a populated key register');vm.enterWithKey(key,start,end);});var TRUE_REF=new _glimmerReference.ConstReference(true);var FALSE_REF=new _glimmerReference.ConstReference(false);APPEND_OPCODES.add(48, /* NextIter */function(vm,_ref37){var end=_ref37.op1;var item=vm.frame.getIterator().next();if(item){vm.frame.setCondition(TRUE_REF);vm.frame.setKey(item.key);vm.frame.setOperand(item.value);vm.frame.setArgs(EvaluatedArgs.positional([item.value,item.memo]));}else {vm.frame.setCondition(FALSE_REF);vm.goto(end);}});var TemplateIterator=(function(){function TemplateIterator(vm){this.vm = vm;}TemplateIterator.prototype.next = function next(){return this.vm.next();};return TemplateIterator;})();var clientId=0;function templateFactory(_ref38){var templateId=_ref38.id;var meta=_ref38.meta;var block=_ref38.block;var parsedBlock=undefined;var id=templateId || 'client-' + clientId++;var create=function(env,envMeta){var newMeta=envMeta?_glimmerUtil.assign({},envMeta,meta):meta;if(!parsedBlock){parsedBlock = JSON.parse(block);}return template(parsedBlock,id,newMeta,env);};return {id:id,meta:meta,create:create};}function template(block,id,meta,env){var scanner=new Scanner(block,meta,env);var entryPoint=undefined;var asEntryPoint=function(){if(!entryPoint)entryPoint = scanner.scanEntryPoint();return entryPoint;};var layout=undefined;var asLayout=function(){if(!layout)layout = scanner.scanLayout();return layout;};var asPartial=function(symbols){return scanner.scanPartial(symbols);};var render=function(self,appendTo,dynamicScope){var elementStack=ElementStack.forInitialRender(env,appendTo,null);var compiled=asEntryPoint().compile(env);var vm=VM.initial(env,self,dynamicScope,elementStack,compiled);return new TemplateIterator(vm);};return {id:id,meta:meta,_block:block,asEntryPoint:asEntryPoint,asLayout:asLayout,asPartial:asPartial,render:render};}var DynamicVarReference=(function(){function DynamicVarReference(scope,nameRef){this.scope = scope;this.nameRef = nameRef;var varTag=this.varTag = new _glimmerReference.UpdatableTag(_glimmerReference.CONSTANT_TAG);this.tag = _glimmerReference.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.update(ref.tag);return ref;};return DynamicVarReference;})();function getDynamicVar(vm,args,_symbolTable){var scope=vm.dynamicScope();var nameRef=args.positional.at(0);return new DynamicVarReference(scope,nameRef);}var PartialDefinition=function PartialDefinition(name,template){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 Simple=Object.freeze({get NodeType(){return NodeType;}});exports.Simple = Simple;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.CompiledBlock = CompiledBlock;exports.CompiledProgram = CompiledProgram;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.normalizeTextValue = normalizeTextValue;exports.CompiledExpression = CompiledExpression;exports.CompiledArgs = CompiledArgs;exports.CompiledNamedArgs = CompiledNamedArgs;exports.CompiledPositionalArgs = CompiledPositionalArgs;exports.EvaluatedArgs = EvaluatedArgs;exports.EvaluatedNamedArgs = EvaluatedNamedArgs;exports.EvaluatedPositionalArgs = EvaluatedPositionalArgs;exports.getDynamicVar = getDynamicVar;exports.BlockMacros = Blocks;exports.InlineMacros = Inlines;exports.compileArgs = compileArgs;exports.setDebuggerCallback = setDebuggerCallback;exports.resetDebuggerCallback = resetDebuggerCallback;exports.BaselineSyntax = BaselineSyntax;exports.Layout = Layout;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) { | |
// 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. | |
'use strict'; | |
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; | |
} | |
// tslint:disable-line | |
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'); | |
} | |
// 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"); | |
} | |
} | |
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() {} | |
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 = undefined; | |
var Logger = (function () { | |
function Logger(_ref) { | |
var console = _ref.console; | |
var level = _ref.level; | |
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]; | |
var _ref2$stackTrace = _ref2.stackTrace; | |
var 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]; | |
var _ref3$stackTrace = _ref3.stackTrace; | |
var 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]; | |
var _ref4$stackTrace = _ref4.stackTrace; | |
var 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.Warn; | |
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); | |
} | |
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() { | |
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; | |
Object.keys(dict).forEach(function (key) { | |
return callback(dict[key]); | |
}); | |
}; | |
DictSet.prototype.toArray = function toArray() { | |
return Object.keys(this.dict); | |
}; | |
return DictSet; | |
})(); | |
var Stack = (function () { | |
function 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; | |
})(); | |
var ListNode = function ListNode(value) { | |
this.next = null; | |
this.prev = null; | |
this.value = value; | |
}; | |
var LinkedList = (function () { | |
function 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 = undefined; | |
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 ? null : arguments[1]; | |
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) { | |
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_TYPED_ARRAYS = typeof Uint32Array !== 'undefined'; | |
var A = undefined; | |
if (HAS_TYPED_ARRAYS) { | |
A = Uint32Array; | |
} else { | |
A = Array; | |
} | |
var A$1 = A; | |
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]'; | |
})(); | |
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.HAS_NATIVE_WEAKMAP = HAS_NATIVE_WEAKMAP; | |
exports.unwrap = unwrap; | |
exports.expect = expect; | |
exports.unreachable = unreachable; | |
}); | |
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["UnoptimizedAppend"] = 2] = "UnoptimizedAppend"; | |
Opcodes[Opcodes["OptimizedAppend"] = 3] = "OptimizedAppend"; | |
Opcodes[Opcodes["Comment"] = 4] = "Comment"; | |
Opcodes[Opcodes["Modifier"] = 5] = "Modifier"; | |
Opcodes[Opcodes["Block"] = 6] = "Block"; | |
Opcodes[Opcodes["ScannedBlock"] = 7] = "ScannedBlock"; | |
Opcodes[Opcodes["NestedBlock"] = 8] = "NestedBlock"; | |
Opcodes[Opcodes["Component"] = 9] = "Component"; | |
Opcodes[Opcodes["ScannedComponent"] = 10] = "ScannedComponent"; | |
Opcodes[Opcodes["OpenElement"] = 11] = "OpenElement"; | |
Opcodes[Opcodes["OpenPrimitiveElement"] = 12] = "OpenPrimitiveElement"; | |
Opcodes[Opcodes["FlushElement"] = 13] = "FlushElement"; | |
Opcodes[Opcodes["CloseElement"] = 14] = "CloseElement"; | |
Opcodes[Opcodes["StaticAttr"] = 15] = "StaticAttr"; | |
Opcodes[Opcodes["DynamicAttr"] = 16] = "DynamicAttr"; | |
Opcodes[Opcodes["AnyDynamicAttr"] = 17] = "AnyDynamicAttr"; | |
Opcodes[Opcodes["Yield"] = 18] = "Yield"; | |
Opcodes[Opcodes["Partial"] = 19] = "Partial"; | |
Opcodes[Opcodes["StaticPartial"] = 20] = "StaticPartial"; | |
Opcodes[Opcodes["DynamicPartial"] = 21] = "DynamicPartial"; | |
Opcodes[Opcodes["DynamicArg"] = 22] = "DynamicArg"; | |
Opcodes[Opcodes["StaticArg"] = 23] = "StaticArg"; | |
Opcodes[Opcodes["TrustingAttr"] = 24] = "TrustingAttr"; | |
Opcodes[Opcodes["Debugger"] = 25] = "Debugger"; | |
// Expressions | |
Opcodes[Opcodes["Unknown"] = 26] = "Unknown"; | |
Opcodes[Opcodes["Arg"] = 27] = "Arg"; | |
Opcodes[Opcodes["Get"] = 28] = "Get"; | |
Opcodes[Opcodes["HasBlock"] = 29] = "HasBlock"; | |
Opcodes[Opcodes["HasBlockParams"] = 30] = "HasBlockParams"; | |
Opcodes[Opcodes["Undefined"] = 31] = "Undefined"; | |
Opcodes[Opcodes["Function"] = 32] = "Function"; | |
Opcodes[Opcodes["Helper"] = 33] = "Helper"; | |
Opcodes[Opcodes["Concat"] = 34] = "Concat"; | |
})(Opcodes || (exports.Ops = Opcodes = {})); | |
function is(variant) { | |
return function (value) { | |
return value[0] === variant; | |
}; | |
} | |
var Expressions; | |
(function (Expressions) { | |
Expressions.isUnknown = is(Opcodes.Unknown); | |
Expressions.isArg = is(Opcodes.Arg); | |
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); | |
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); | |
function isAttribute(val) { | |
return val[0] === Opcodes.StaticAttr || val[0] === Opcodes.DynamicAttr; | |
} | |
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'], function (exports) { 'use strict'; | |
var NUMBER = /\d+/; | |
function each(collection, callback) { | |
for (var i = 0; i < collection.length; i++) { | |
callback(collection[i]); | |
} | |
} | |
function isString(suspect) { | |
return typeof suspect === 'string'; | |
} | |
function isFunction(suspect) { | |
return typeof suspect === 'function'; | |
} | |
function isNumber(suspect) { | |
return typeof suspect === 'number'; | |
} | |
function isCoercableNumber(number) { | |
return isNumber(number) || NUMBER.test(number); | |
} | |
function binarySearch(time, timers) { | |
var start = 0; | |
var end = timers.length - 2; | |
var middle, l; | |
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; | |
} | |
function Queue(name, options, globalOptions) { | |
this.name = name; | |
this.globalOptions = globalOptions || {}; | |
this.options = options; | |
this._queue = []; | |
this.targetQueues = {}; | |
this._queueBeingFlushed = undefined; | |
} | |
Queue.prototype = { | |
push: function(target, method, args, stack) { | |
var queue = this._queue; | |
queue.push(target, method, args, stack); | |
return { | |
queue: this, | |
target: target, | |
method: method | |
}; | |
}, | |
pushUniqueWithoutGuid: function(target, method, args, stack) { | |
var queue = this._queue; | |
for (var i = 0, l = queue.length; i < l; i += 4) { | |
var currentTarget = queue[i]; | |
var currentMethod = queue[i+1]; | |
if (currentTarget === target && currentMethod === method) { | |
queue[i+2] = args; // replace args | |
queue[i+3] = stack; // replace stack | |
return; | |
} | |
} | |
queue.push(target, method, args, stack); | |
}, | |
targetQueue: function(targetQueue, target, method, args, stack) { | |
var queue = this._queue; | |
for (var i = 0, l = targetQueue.length; i < l; i += 2) { | |
var currentMethod = targetQueue[i]; | |
var currentIndex = targetQueue[i + 1]; | |
if (currentMethod === method) { | |
queue[currentIndex + 2] = args; // replace args | |
queue[currentIndex + 3] = stack; // replace stack | |
return; | |
} | |
} | |
targetQueue.push( | |
method, | |
queue.push(target, method, args, stack) - 4 | |
); | |
}, | |
pushUniqueWithGuid: function(guid, target, method, args, stack) { | |
var hasLocalQueue = this.targetQueues[guid]; | |
if (hasLocalQueue) { | |
this.targetQueue(hasLocalQueue, target, method, args, stack); | |
} else { | |
this.targetQueues[guid] = [ | |
method, | |
this._queue.push(target, method, args, stack) - 4 | |
]; | |
} | |
return { | |
queue: this, | |
target: target, | |
method: method | |
}; | |
}, | |
pushUnique: function(target, method, args, stack) { | |
var KEY = this.globalOptions.GUID_KEY; | |
if (target && KEY) { | |
var guid = target[KEY]; | |
if (guid) { | |
return this.pushUniqueWithGuid(guid, target, method, args, stack); | |
} | |
} | |
this.pushUniqueWithoutGuid(target, method, args, stack); | |
return { | |
queue: this, | |
target: target, | |
method: method | |
}; | |
}, | |
invoke: function(target, method, args /*, onError, errorRecordedForStack */) { | |
if (args && args.length > 0) { | |
method.apply(target, args); | |
} else { | |
method.call(target); | |
} | |
}, | |
invokeWithOnError: function(target, method, args, onError, errorRecordedForStack) { | |
try { | |
if (args && args.length > 0) { | |
method.apply(target, args); | |
} else { | |
method.call(target); | |
} | |
} catch(error) { | |
onError(error, errorRecordedForStack); | |
} | |
}, | |
flush: function(sync) { | |
var queue = this._queue; | |
var length = queue.length; | |
if (length === 0) { | |
return; | |
} | |
var globalOptions = this.globalOptions; | |
var options = this.options; | |
var before = options && options.before; | |
var after = options && options.after; | |
var onError = globalOptions.onError || (globalOptions.onErrorTarget && | |
globalOptions.onErrorTarget[globalOptions.onErrorMethod]); | |
var target, method, args, errorRecordedForStack; | |
var invoke = onError ? this.invokeWithOnError : this.invoke; | |
this.targetQueues = Object.create(null); | |
var queueItems = this._queueBeingFlushed = this._queue.slice(); | |
this._queue = []; | |
if (before) { | |
before(); | |
} | |
for (var i = 0; i < length; i += 4) { | |
target = queueItems[i]; | |
method = queueItems[i+1]; | |
args = queueItems[i+2]; | |
errorRecordedForStack = queueItems[i+3]; // Debugging assistance | |
if (isString(method)) { | |
method = target[method]; | |
} | |
// method could have been nullified / canceled during flush | |
if (method) { | |
// | |
// ** 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 | |
// | |
invoke(target, method, args, onError, errorRecordedForStack); | |
} | |
} | |
if (after) { | |
after(); | |
} | |
this._queueBeingFlushed = undefined; | |
if (sync !== false && | |
this._queue.length > 0) { | |
// check if new items have been added | |
this.flush(true); | |
} | |
}, | |
cancel: function(actionToCancel) { | |
var queue = this._queue, currentTarget, currentMethod, i, l; | |
var target = actionToCancel.target; | |
var method = actionToCancel.method; | |
var GUID_KEY = this.globalOptions.GUID_KEY; | |
if (GUID_KEY && this.targetQueues && target) { | |
var targetQueue = this.targetQueues[target[GUID_KEY]]; | |
if (targetQueue) { | |
for (i = 0, l = targetQueue.length; i < l; i++) { | |
if (targetQueue[i] === method) { | |
targetQueue.splice(i, 1); | |
} | |
} | |
} | |
} | |
for (i = 0, l = queue.length; i < l; i += 4) { | |
currentTarget = queue[i]; | |
currentMethod = queue[i+1]; | |
if (currentTarget === target && | |
currentMethod === method) { | |
queue.splice(i, 4); | |
return true; | |
} | |
} | |
// if not found in current queue | |
// could be in the queue that is being flushed | |
queue = this._queueBeingFlushed; | |
if (!queue) { | |
return; | |
} | |
for (i = 0, l = queue.length; i < l; i += 4) { | |
currentTarget = queue[i]; | |
currentMethod = queue[i+1]; | |
if (currentTarget === target && | |
currentMethod === method) { | |
// don't mess with array during flush | |
// just nullify the method | |
queue[i+1] = null; | |
return true; | |
} | |
} | |
} | |
}; | |
function DeferredActionQueues(queueNames, options) { | |
var queues = this.queues = {}; | |
this.queueNames = queueNames = queueNames || []; | |
this.options = options; | |
each(queueNames, function(queueName) { | |
queues[queueName] = new Queue(queueName, options[queueName], options); | |
}); | |
} | |
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'); | |
} | |
DeferredActionQueues.prototype = { | |
schedule: function(name, target, method, args, onceFlag, stack) { | |
var queues = this.queues; | |
var queue = queues[name]; | |
if (!queue) { | |
noSuchQueue(name); | |
} | |
if (!method) { | |
noSuchMethod(name); | |
} | |
if (onceFlag) { | |
return queue.pushUnique(target, method, args, stack); | |
} else { | |
return queue.push(target, method, args, stack); | |
} | |
}, | |
flush: function() { | |
var queues = this.queues; | |
var queueNames = this.queueNames; | |
var queueName, queue; | |
var queueNameIndex = 0; | |
var numberOfQueues = queueNames.length; | |
while (queueNameIndex < numberOfQueues) { | |
queueName = queueNames[queueNameIndex]; | |
queue = queues[queueName]; | |
var numberOfQueueItems = queue._queue.length; | |
if (numberOfQueueItems === 0) { | |
queueNameIndex++; | |
} else { | |
queue.flush(false /* async */); | |
queueNameIndex = 0; | |
} | |
} | |
} | |
}; | |
function Backburner(queueNames, options) { | |
this.queueNames = queueNames; | |
this.options = options || {}; | |
if (!this.options.defaultQueue) { | |
this.options.defaultQueue = queueNames[0]; | |
} | |
this.instanceStack = []; | |
this._debouncees = []; | |
this._throttlers = []; | |
this._eventCallbacks = { | |
end: [], | |
begin: [] | |
}; | |
var _this = this; | |
this._boundClearItems = function() { | |
clearItems(); | |
}; | |
this._timerTimeoutId = undefined; | |
this._timers = []; | |
this._platform = this.options._platform || { | |
setTimeout: function (fn, ms) { | |
return setTimeout(fn, ms); | |
}, | |
clearTimeout: function (id) { | |
clearTimeout(id); | |
} | |
}; | |
this._boundRunExpiredTimers = function () { | |
_this._runExpiredTimers(); | |
}; | |
} | |
Backburner.prototype = { | |
begin: function() { | |
var options = this.options; | |
var onBegin = options && options.onBegin; | |
var previousInstance = this.currentInstance; | |
if (previousInstance) { | |
this.instanceStack.push(previousInstance); | |
} | |
this.currentInstance = new DeferredActionQueues(this.queueNames, options); | |
this._trigger('begin', this.currentInstance, previousInstance); | |
if (onBegin) { | |
onBegin(this.currentInstance, previousInstance); | |
} | |
}, | |
end: function() { | |
var options = this.options; | |
var onEnd = options && options.onEnd; | |
var currentInstance = this.currentInstance; | |
var nextInstance = null; | |
// 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; | |
try { | |
currentInstance.flush(); | |
} finally { | |
if (!finallyAlreadyCalled) { | |
finallyAlreadyCalled = true; | |
this.currentInstance = null; | |
if (this.instanceStack.length) { | |
nextInstance = this.instanceStack.pop(); | |
this.currentInstance = nextInstance; | |
} | |
this._trigger('end', currentInstance, nextInstance); | |
if (onEnd) { | |
onEnd(currentInstance, nextInstance); | |
} | |
} | |
} | |
}, | |
/** | |
Trigger an event. Supports up to two arguments. Designed around | |
triggering transition events from one run loop instance to the | |
next, which requires an argument for the first instance and then | |
an argument for the next instance. | |
@private | |
@method _trigger | |
@param {String} eventName | |
@param {any} arg1 | |
@param {any} arg2 | |
*/ | |
_trigger: function(eventName, arg1, arg2) { | |
var callbacks = this._eventCallbacks[eventName]; | |
if (callbacks) { | |
for (var i = 0; i < callbacks.length; i++) { | |
callbacks[i](arg1, arg2); | |
} | |
} | |
}, | |
on: function(eventName, callback) { | |
if (typeof callback !== 'function') { | |
throw new TypeError('Callback must be a function'); | |
} | |
var callbacks = this._eventCallbacks[eventName]; | |
if (callbacks) { | |
callbacks.push(callback); | |
} else { | |
throw new TypeError('Cannot on() event "' + eventName + '" because it does not exist'); | |
} | |
}, | |
off: function(eventName, callback) { | |
if (eventName) { | |
var callbacks = this._eventCallbacks[eventName]; | |
var callbackFound = false; | |
if (!callbacks) return; | |
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'); | |
} | |
} else { | |
throw new TypeError('Cannot off() event "' + eventName + '" because it does not exist'); | |
} | |
}, | |
run: function(/* target, method, args */) { | |
var length = arguments.length; | |
var method, target, args; | |
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]; | |
} | |
} else { | |
args = []; | |
} | |
var onError = getOnError(this.options); | |
this.begin(); | |
// guard against Safari 6's double-finally bug | |
var didFinally = false; | |
if (onError) { | |
try { | |
return method.apply(target, args); | |
} catch(error) { | |
onError(error); | |
} finally { | |
if (!didFinally) { | |
didFinally = true; | |
this.end(); | |
} | |
} | |
} else { | |
try { | |
return method.apply(target, args); | |
} finally { | |
if (!didFinally) { | |
didFinally = true; | |
this.end(); | |
} | |
} | |
} | |
}, | |
/* | |
Join the passed method with an existing queue and execute immediately, | |
if there isn't one use `Backburner#run`. | |
The join method is like the run method except that it will schedule into | |
an existing queue if one already exists. In either case, the join method will | |
immediately execute the passed in function and return its result. | |
@method join | |
@param {Object} target | |
@param {Function} method The method to be executed | |
@param {any} args The method arguments | |
@return method result | |
*/ | |
join: function(/* target, method, args */) { | |
if (!this.currentInstance) { | |
return this.run.apply(this, arguments); | |
} | |
var length = arguments.length; | |
var method, target; | |
if (length === 1) { | |
method = arguments[0]; | |
target = null; | |
} else { | |
target = arguments[0]; | |
method = arguments[1]; | |
} | |
if (isString(method)) { | |
method = target[method]; | |
} | |
if (length === 1) { | |
return method(); | |
} else if (length === 2) { | |
return method.call(target); | |
} else { | |
var args = new Array(length - 2); | |
for (var i = 0, l = length - 2; i < l; i++) { | |
args[i] = arguments[i + 2]; | |
} | |
return method.apply(target, args); | |
} | |
}, | |
/* | |
Defer the passed function to run inside the specified queue. | |
@method defer | |
@param {String} queueName | |
@param {Object} target | |
@param {Function|String} method The method or method name to be executed | |
@param {any} args The method arguments | |
@return method result | |
*/ | |
defer: function(queueName /* , target, method, args */) { | |
var length = arguments.length; | |
var method, target, args; | |
if (length === 2) { | |
method = arguments[1]; | |
target = null; | |
} else { | |
target = arguments[1]; | |
method = arguments[2]; | |
} | |
if (isString(method)) { | |
method = target[method]; | |
} | |
var stack = this.DEBUG ? new Error() : undefined; | |
if (length > 3) { | |
args = new Array(length - 3); | |
for (var i = 3; i < length; i++) { | |
args[i-3] = arguments[i]; | |
} | |
} else { | |
args = undefined; | |
} | |
if (!this.currentInstance) { createAutorun(this); } | |
return this.currentInstance.schedule(queueName, target, method, args, false, stack); | |
}, | |
deferOnce: function(queueName /* , target, method, args */) { | |
var length = arguments.length; | |
var method, target, args; | |
if (length === 2) { | |
method = arguments[1]; | |
target = null; | |
} else { | |
target = arguments[1]; | |
method = arguments[2]; | |
} | |
if (isString(method)) { | |
method = target[method]; | |
} | |
var stack = this.DEBUG ? new Error() : undefined; | |
if (length > 3) { | |
args = new Array(length - 3); | |
for (var i = 3; i < length; i++) { | |
args[i-3] = arguments[i]; | |
} | |
} else { | |
args = undefined; | |
} | |
if (!this.currentInstance) { | |
createAutorun(this); | |
} | |
return this.currentInstance.schedule(queueName, target, method, args, true, stack); | |
}, | |
setTimeout: function() { | |
var l = arguments.length; | |
var args = new Array(l); | |
for (var x = 0; x < l; x++) { | |
args[x] = arguments[x]; | |
} | |
var length = args.length, | |
method, wait, target, | |
methodOrTarget, methodOrWait, methodOrArgs; | |
if (length === 0) { | |
return; | |
} else if (length === 1) { | |
method = args.shift(); | |
wait = 0; | |
} else if (length === 2) { | |
methodOrTarget = args[0]; | |
methodOrWait = args[1]; | |
if (isFunction(methodOrWait) || isFunction(methodOrTarget[methodOrWait])) { | |
target = args.shift(); | |
method = args.shift(); | |
wait = 0; | |
} else if (isCoercableNumber(methodOrWait)) { | |
method = args.shift(); | |
wait = args.shift(); | |
} else { | |
method = args.shift(); | |
wait = 0; | |
} | |
} else { | |
var last = args[args.length - 1]; | |
if (isCoercableNumber(last)) { | |
wait = args.pop(); | |
} else { | |
wait = 0; | |
} | |
methodOrTarget = args[0]; | |
methodOrArgs = args[1]; | |
if (isFunction(methodOrArgs) || (isString(methodOrArgs) && | |
methodOrTarget !== null && | |
methodOrArgs in methodOrTarget)) { | |
target = args.shift(); | |
method = args.shift(); | |
} else { | |
method = args.shift(); | |
} | |
} | |
var executeAt = Date.now() + parseInt(wait !== wait ? 0 : wait, 10); | |
if (isString(method)) { | |
method = target[method]; | |
} | |
var onError = getOnError(this.options); | |
function fn() { | |
if (onError) { | |
try { | |
method.apply(target, args); | |
} catch (e) { | |
onError(e); | |
} | |
} else { | |
method.apply(target, args); | |
} | |
} | |
return this._setTimeout(fn, executeAt); | |
}, | |
_setTimeout: function (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; | |
}, | |
throttle: function(target, method /* , args, wait, [immediate] */) { | |
var backburner = this; | |
var args = new Array(arguments.length); | |
for (var i = 0; i < arguments.length; i++) { | |
args[i] = arguments[i]; | |
} | |
var immediate = args.pop(); | |
var wait, throttler, index, timer; | |
if (isNumber(immediate) || isString(immediate)) { | |
wait = immediate; | |
immediate = true; | |
} else { | |
wait = args.pop(); | |
} | |
wait = parseInt(wait, 10); | |
index = findThrottler(target, method, this._throttlers); | |
if (index > -1) { return this._throttlers[index]; } // throttled | |
timer = this._platform.setTimeout(function() { | |
if (!immediate) { | |
backburner.run.apply(backburner, args); | |
} | |
var index = findThrottler(target, method, backburner._throttlers); | |
if (index > -1) { | |
backburner._throttlers.splice(index, 1); | |
} | |
}, wait); | |
if (immediate) { | |
this.run.apply(this, args); | |
} | |
throttler = [target, method, timer]; | |
this._throttlers.push(throttler); | |
return throttler; | |
}, | |
debounce: function(target, method /* , args, wait, [immediate] */) { | |
var backburner = this; | |
var args = new Array(arguments.length); | |
for (var i = 0; i < arguments.length; i++) { | |
args[i] = arguments[i]; | |
} | |
var immediate = args.pop(); | |
var wait, index, debouncee, timer; | |
if (isNumber(immediate) || isString(immediate)) { | |
wait = immediate; | |
immediate = false; | |
} else { | |
wait = args.pop(); | |
} | |
wait = parseInt(wait, 10); | |
// Remove debouncee | |
index = findDebouncee(target, method, this._debouncees); | |
if (index > -1) { | |
debouncee = this._debouncees[index]; | |
this._debouncees.splice(index, 1); | |
this._platform.clearTimeout(debouncee[2]); | |
} | |
timer = this._platform.setTimeout(function() { | |
if (!immediate) { | |
backburner.run.apply(backburner, args); | |
} | |
var index = findDebouncee(target, method, backburner._debouncees); | |
if (index > -1) { | |
backburner._debouncees.splice(index, 1); | |
} | |
}, wait); | |
if (immediate && index === -1) { | |
backburner.run.apply(backburner, args); | |
} | |
debouncee = [ | |
target, | |
method, | |
timer | |
]; | |
backburner._debouncees.push(debouncee); | |
return debouncee; | |
}, | |
cancelTimers: function() { | |
each(this._throttlers, this._boundClearItems); | |
this._throttlers = []; | |
each(this._debouncees, this._boundClearItems); | |
this._debouncees = []; | |
this._clearTimerTimeout(); | |
this._timers = []; | |
if (this._autorun) { | |
this._platform.clearTimeout(this._autorun); | |
this._autorun = null; | |
} | |
}, | |
hasTimers: function() { | |
return !!this._timers.length || !!this._debouncees.length || !!this._throttlers.length || this._autorun; | |
}, | |
cancel: function (timer) { | |
var timerType = typeof timer; | |
if (timer && timerType === 'object' && timer.queue && timer.method) { // we're cancelling a deferOnce | |
return timer.queue.cancel(timer); | |
} else if (timerType === 'function') { // we're cancelling a setTimeout | |
for (var i = 0, l = this._timers.length; i < l; i += 2) { | |
if (this._timers[i + 1] === timer) { | |
this._timers.splice(i, 2); // remove the two elements | |
if (i === 0) { | |
this._reinstallTimerTimeout(); | |
} | |
return true; | |
} | |
} | |
} else if (Object.prototype.toString.call(timer) === '[object Array]'){ // we're cancelling a throttle or debounce | |
return this._cancelItem(findThrottler, this._throttlers, timer) || | |
this._cancelItem(findDebouncee, this._debouncees, timer); | |
} else { | |
return; // timer was null or not a timer | |
} | |
}, | |
_cancelItem: function(findMethod, array, timer){ | |
var item, index; | |
if (timer.length < 3) { return false; } | |
index = findMethod(timer[0], timer[1], array); | |
if (index > -1) { | |
item = array[index]; | |
if (item[2] === timer[2]) { | |
array.splice(index, 1); | |
this._platform.clearTimeout(timer[2]); | |
return true; | |
} | |
} | |
return false; | |
}, | |
_runExpiredTimers: function () { | |
this._timerTimeoutId = undefined; | |
this.run(this, this._scheduleExpiredTimers); | |
}, | |
_scheduleExpiredTimers: function () { | |
var n = Date.now(); | |
var timers = this._timers; | |
var i = 0; | |
var l = timers.length; | |
for (; i < l; i += 2) { | |
var executeAt = timers[i]; | |
var fn = timers[i+1]; | |
if (executeAt <= n) { | |
this.schedule(this.options.defaultQueue, null, fn); | |
} else { | |
break; | |
} | |
} | |
timers.splice(0, i); | |
this._installTimerTimeout(); | |
}, | |
_reinstallTimerTimeout: function () { | |
this._clearTimerTimeout(); | |
this._installTimerTimeout(); | |
}, | |
_clearTimerTimeout: function () { | |
if (!this._timerTimeoutId) { | |
return; | |
} | |
this._platform.clearTimeout(this._timerTimeoutId); | |
this._timerTimeoutId = undefined; | |
}, | |
_installTimerTimeout: function () { | |
if (!this._timers.length) { | |
return; | |
} | |
var minExpiresAt = this._timers[0]; | |
var n = Date.now(); | |
var wait = Math.max(0, minExpiresAt - n); | |
this._timerTimeoutId = this._platform.setTimeout(this._boundRunExpiredTimers, wait); | |
} | |
}; | |
Backburner.prototype.schedule = Backburner.prototype.defer; | |
Backburner.prototype.scheduleOnce = Backburner.prototype.deferOnce; | |
Backburner.prototype.later = Backburner.prototype.setTimeout; | |
function getOnError(options) { | |
return options.onError || (options.onErrorTarget && options.onErrorTarget[options.onErrorMethod]); | |
} | |
function createAutorun(backburner) { | |
var setTimeout = backburner._platform.setTimeout; | |
backburner.begin(); | |
backburner._autorun = setTimeout(function() { | |
backburner._autorun = null; | |
backburner.end(); | |
}, 0); | |
} | |
function findDebouncee(target, method, debouncees) { | |
return findItem(target, method, debouncees); | |
} | |
function findThrottler(target, method, throttlers) { | |
return findItem(target, method, throttlers); | |
} | |
function findItem(target, method, collection) { | |
var item; | |
var index = -1; | |
for (var i = 0, l = collection.length; i < l; i++) { | |
item = collection[i]; | |
if (item[0] === target && item[1] === method) { | |
index = i; | |
break; | |
} | |
} | |
return index; | |
} | |
function clearItems(item) { | |
this._platform.clearTimeout(item[2]); | |
} | |
exports['default'] = Backburner; | |
Object.defineProperty(exports, '__esModule', { value: true }); | |
}); | |
enifed('container/container', ['exports', 'ember-debug', 'ember-utils', 'ember-environment'], function (exports, _emberDebug, _emberUtils, _emberEnvironment) { | |
'use strict'; | |
var _Container$prototype; | |
exports.default = Container; | |
exports.buildFakeContainerWithDeprecations = buildFakeContainerWithDeprecations; | |
var CONTAINER_OVERRIDE = _emberUtils.symbol('CONTAINER_OVERRIDE'); | |
var FACTORY_FOR = _emberUtils.symbol('FACTORY_FOR'); | |
exports.FACTORY_FOR = FACTORY_FOR; | |
var LOOKUP_FACTORY = _emberUtils.symbol('LOOKUP_FACTORY'); | |
exports.LOOKUP_FACTORY = LOOKUP_FACTORY; | |
/** | |
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 | |
*/ | |
function Container(registry, options) { | |
this.registry = registry; | |
this.owner = options && options.owner ? options.owner : null; | |
this.cache = _emberUtils.dictionary(options && options.cache ? options.cache : null); | |
this.factoryCache = _emberUtils.dictionary(options && options.factoryCache ? options.factoryCache : null); | |
this.factoryManagerCache = _emberUtils.dictionary(options && options.factoryManagerCache ? options.factoryManagerCache : null); | |
this.validationCache = _emberUtils.dictionary(options && options.validationCache ? options.validationCache : null); | |
this._fakeContainerToInject = buildFakeContainerWithDeprecations(this); | |
this[CONTAINER_OVERRIDE] = undefined; | |
this.isDestroyed = false; | |
} | |
Container.prototype = (_Container$prototype = { | |
/** | |
@private | |
@property owner | |
@type Object | |
*/ | |
owner: null, | |
/** | |
@private | |
@property registry | |
@type Registry | |
@since 1.11.0 | |
*/ | |
registry: null, | |
/** | |
@private | |
@property cache | |
@type InheritingDict | |
*/ | |
cache: null, | |
/** | |
@private | |
@property factoryCache | |
@type InheritingDict | |
*/ | |
factoryCache: null, | |
/** | |
@private | |
@property validationCache | |
@type InheritingDict | |
*/ | |
validationCache: null, | |
/** | |
Given a fullName return a corresponding instance. | |
The default behaviour 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} | |
*/ | |
lookup: function (fullName, options) { | |
_emberDebug.assert('fullName must be a proper full name', this.registry.validateFullName(fullName)); | |
return lookup(this, this.registry.normalize(fullName), options); | |
}, | |
/** | |
Given a fullName, return the corresponding factory. | |
@private | |
@method lookupFactory | |
@param {String} fullName | |
@param {Object} [options] | |
@param {String} [options.source] The fullname of the request source (used for local lookup) | |
@return {any} | |
*/ | |
lookupFactory: function (fullName, options) { | |
_emberDebug.assert('fullName must be a proper full name', this.registry.validateFullName(fullName)); | |
_emberDebug.deprecate('Using "_lookupFactory" is deprecated. Please use container.factoryFor instead.', !true, { id: 'container-lookupFactory', until: '2.13.0', url: 'http://emberjs.com/deprecations/v2.x/#toc_migrating-from-_lookupfactory-to-factoryfor' }); | |
return deprecatedFactoryFor(this, this.registry.normalize(fullName), options); | |
} | |
}, _Container$prototype[LOOKUP_FACTORY] = function (fullName, options) { | |
_emberDebug.assert('fullName must be a proper full name', this.registry.validateFullName(fullName)); | |
return deprecatedFactoryFor(this, this.registry.normalize(fullName), options); | |
}, _Container$prototype[FACTORY_FOR] = function (fullName) { | |
var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; | |
if (true) { | |
if (true) { | |
return this.factoryFor(fullName, options); | |
} else { | |
/* This throws in case of a poorly designed build */ | |
throw new Error('If ember-no-double-extend is enabled, ember-factory-for must also be enabled'); | |
} | |
} | |
var factory = this[LOOKUP_FACTORY](fullName, options); | |
if (factory === undefined) { | |
return; | |
} | |
var manager = new DeprecatedFactoryManager(this, factory, fullName); | |
_emberDebug.runInDebug(function () { | |
manager = wrapManagerInDeprecationProxy(manager); | |
}); | |
return manager; | |
}, _Container$prototype.destroy = function () { | |
destroyDestroyables(this); | |
this.isDestroyed = true; | |
}, _Container$prototype.reset = function (fullName) { | |
if (arguments.length > 0) { | |
resetMember(this, this.registry.normalize(fullName)); | |
} else { | |
resetCache(this); | |
} | |
}, _Container$prototype.ownerInjection = function () { | |
var _ref; | |
return _ref = {}, _ref[_emberUtils.OWNER] = this.owner, _ref; | |
}, _Container$prototype); | |
/* | |
* 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 _ret = (function () { | |
var validator = { | |
get: function (obj, prop) { | |
if (prop !== 'class' && prop !== 'create') { | |
throw new Error('You attempted to access "' + prop + '" on a factory manager created by container#factoryFor. "' + prop + '" is not a member of a factory manager."'); | |
} | |
return obj[prop]; | |
}, | |
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 { | |
v: new Proxy(proxiedManager, validator) | |
}; | |
})(); | |
if (typeof _ret === 'object') return _ret.v; | |
} | |
return manager; | |
} | |
if (true) { | |
/** | |
Given a fullName, return the corresponding factory. The consumer of the factory | |
is responsible for the destruction of any factory instances, as there is no | |
way for the container to ensure instances are destroyed when it itself is | |
destroyed. | |
@public | |
@method factoryFor | |
@param {String} fullName | |
@param {Object} [options] | |
@param {String} [options.source] The fullname of the request source (used for local lookup) | |
@return {any} | |
*/ | |
Container.prototype.factoryFor = function _factoryFor(fullName) { | |
var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; | |
var normalizedName = this.registry.normalize(fullName); | |
_emberDebug.assert('fullName must be a proper full name', this.registry.validateFullName(normalizedName)); | |
if (options.source) { | |
normalizedName = this.registry.expandLocalLookup(fullName, options); | |
// if expandLocalLookup returns falsey, we do not support local lookup | |
if (!normalizedName) { | |
return; | |
} | |
} | |
var cached = this.factoryManagerCache[normalizedName]; | |
if (cached) { | |
return cached; | |
} | |
var factory = this.registry.resolve(normalizedName); | |
if (factory === undefined) { | |
return; | |
} | |
var manager = new FactoryManager(this, factory, fullName, normalizedName); | |
_emberDebug.runInDebug(function () { | |
manager = wrapManagerInDeprecationProxy(manager); | |
}); | |
this.factoryManagerCache[normalizedName] = manager; | |
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) { | |
fullName = container.registry.expandLocalLookup(fullName, options); | |
// if expandLocalLookup returns falsey, we do not support local lookup | |
if (!fullName) { | |
return; | |
} | |
} | |
if (container.cache[fullName] !== undefined && options.singleton !== false) { | |
return container.cache[fullName]; | |
} | |
if (true) { | |
return instantiateFactory(container, fullName, options); | |
} else { | |
var factory = deprecatedFactoryFor(container, fullName); | |
var value = instantiate(factory, {}, container, fullName); | |
if (value === undefined) { | |
return; | |
} | |
if (isSingleton(container, fullName) && options.singleton !== false) { | |
container.cache[fullName] = value; | |
} | |
return value; | |
} | |
} | |
function isSingletonClass(container, fullName, _ref2) { | |
var instantiate = _ref2.instantiate; | |
var singleton = _ref2.singleton; | |
return singleton !== false && isSingleton(container, fullName) && !instantiate && !isInstantiatable(container, fullName); | |
} | |
function isSingletonInstance(container, fullName, _ref3) { | |
var instantiate = _ref3.instantiate; | |
var singleton = _ref3.singleton; | |
return singleton !== false && isSingleton(container, fullName) && instantiate !== false && isInstantiatable(container, fullName); | |
} | |
function isFactoryClass(container, fullname, _ref4) { | |
var instantiate = _ref4.instantiate; | |
var singleton = _ref4.singleton; | |
return (singleton === false || !isSingleton(container, fullname)) && instantiate === false && !isInstantiatable(container, fullname); | |
} | |
function isFactoryInstance(container, fullName, _ref5) { | |
var instantiate = _ref5.instantiate; | |
var singleton = _ref5.singleton; | |
return (singleton !== false || isSingleton(container, fullName)) && instantiate !== false && isInstantiatable(container, fullName); | |
} | |
function instantiateFactory(container, fullName, options) { | |
var factoryManager = container[FACTORY_FOR](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)) { | |
return container.cache[fullName] = 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 markInjectionsAsDynamic(injections) { | |
injections._dynamic = true; | |
} | |
function areInjectionsDynamic(injections) { | |
return !!injections._dynamic; | |
} | |
function buildInjections() /* container, ...injections */{ | |
var _arguments = arguments; | |
var hash = {}; | |
if (arguments.length > 1) { | |
(function () { | |
var container = _arguments[0]; | |
var injections = []; | |
var injection = undefined; | |
for (var i = 1; i < _arguments.length; i++) { | |
if (_arguments[i]) { | |
injections = injections.concat(_arguments[i]); | |
} | |
} | |
_emberDebug.runInDebug(function () { | |
container.registry.validateInjections(injections); | |
}); | |
for (var i = 0; i < injections.length; i++) { | |
injection = injections[i]; | |
hash[injection.property] = lookup(container, injection.fullName); | |
if (!isSingleton(container, injection.fullName)) { | |
markInjectionsAsDynamic(hash); | |
} | |
} | |
})(); | |
} | |
return hash; | |
} | |
function deprecatedFactoryFor(container, fullName) { | |
var options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2]; | |
var registry = container.registry; | |
if (options.source) { | |
fullName = registry.expandLocalLookup(fullName, options); | |
// if expandLocalLookup returns falsey, we do not support local lookup | |
if (!fullName) { | |
return; | |
} | |
} | |
var cache = container.factoryCache; | |
if (cache[fullName]) { | |
return cache[fullName]; | |
} | |
var factory = registry.resolve(fullName); | |
if (factory === undefined) { | |
return; | |
} | |
var type = fullName.split(':')[0]; | |
if (!factory || typeof factory.extend !== 'function' || !_emberEnvironment.ENV.MODEL_FACTORY_INJECTIONS && type === 'model') { | |
if (factory && typeof factory._onLookup === 'function') { | |
factory._onLookup(fullName); | |
} | |
// TODO: think about a 'safe' merge style extension | |
// for now just fallback to create time injection | |
cache[fullName] = factory; | |
return factory; | |
} else { | |
var injections = injectionsFor(container, fullName); | |
var factoryInjections = factoryInjectionsFor(container, fullName); | |
var cacheable = !areInjectionsDynamic(injections) && !areInjectionsDynamic(factoryInjections); | |
factoryInjections[_emberUtils.NAME_KEY] = registry.makeToString(factory, fullName); | |
injections._debugContainerKey = fullName; | |
_emberUtils.setOwner(injections, container.owner); | |
var injectedFactory = factory.extend(injections); | |
// TODO - remove all `container` injections when Ember reaches v3.0.0 | |
injectDeprecatedContainer(injectedFactory.prototype, container); | |
injectedFactory.reopenClass(factoryInjections); | |
if (factory && typeof factory._onLookup === 'function') { | |
factory._onLookup(fullName); | |
} | |
if (cacheable) { | |
cache[fullName] = injectedFactory; | |
} | |
return injectedFactory; | |
} | |
} | |
function injectionsFor(container, fullName) { | |
var registry = container.registry; | |
var splitName = fullName.split(':'); | |
var type = splitName[0]; | |
var injections = buildInjections(container, registry.getTypeInjections(type), registry.getInjections(fullName)); | |
return injections; | |
} | |
function instantiate(factory, props, container, fullName) { | |
var lazyInjections = undefined, | |
validationCache = undefined; | |
props = props || {}; | |
if (container.registry.getOption(fullName, 'instantiate') === false) { | |
return factory; | |
} | |
if (factory) { | |
if (typeof factory.create !== 'function') { | |
throw new Error('Failed to create an instance of \'' + fullName + '\'. Most likely an improperly defined class or' + ' an invalid module export.'); | |
} | |
validationCache = container.validationCache; | |
_emberDebug.runInDebug(function () { | |
// Ensure that all lazy injections are valid at instantiation time | |
if (!validationCache[fullName] && typeof factory._lazyInjections === 'function') { | |
lazyInjections = factory._lazyInjections(); | |
lazyInjections = container.registry.normalizeInjectionsHash(lazyInjections); | |
container.registry.validateInjections(lazyInjections); | |
} | |
}); | |
validationCache[fullName] = true; | |
var obj = undefined; | |
if (typeof factory.extend === 'function') { | |
// assume the factory was extendable and is already injected | |
obj = factory.create(props); | |
} else { | |
// assume the factory was extendable | |
// to create time injections | |
// TODO: support new'ing for instantiation and merge injections for pure JS Functions | |
var injections = injectionsFor(container, fullName); | |
injections._debugContainerKey = fullName; | |
// Ensure that a container is available to an object during instantiation. | |
// TODO - remove when Ember reaches v3.0.0 | |
// This "fake" container will be replaced after instantiation with a | |
// property that raises deprecations every time it is accessed. | |
injections.container = container._fakeContainerToInject; | |
obj = factory.create(_emberUtils.assign({}, injections, props)); | |
// TODO - remove when Ember reaches v3.0.0 | |
if (!Object.isFrozen(obj)) { | |
injectDeprecatedContainer(obj, container); | |
} | |
} | |
return obj; | |
} | |
} | |
function factoryInjectionsFor(container, fullName) { | |
var registry = container.registry; | |
var splitName = fullName.split(':'); | |
var type = splitName[0]; | |
var factoryInjections = buildInjections(container, registry.getFactoryTypeInjections(type), registry.getFactoryInjections(fullName)); | |
factoryInjections._debugContainerKey = fullName; | |
return factoryInjections; | |
} | |
var INJECTED_DEPRECATED_CONTAINER_DESC = { | |
configurable: true, | |
enumerable: false, | |
get: function () { | |
_emberDebug.deprecate('Using the injected `container` is deprecated. Please use the `getOwner` helper instead to access the owner of this object.', false, { id: 'ember-application.injected-container', until: '2.13.0', url: 'http://emberjs.com/deprecations/v2.x#toc_injected-container-access' }); | |
return this[CONTAINER_OVERRIDE] || _emberUtils.getOwner(this).__container__; | |
}, | |
set: function (value) { | |
_emberDebug.deprecate('Providing the `container` property to ' + this + ' is deprecated. Please use `Ember.setOwner` or `owner.ownerInjection()` instead to provide an owner to the instance being created.', false, { id: 'ember-application.injected-container', until: '2.13.0', url: 'http://emberjs.com/deprecations/v2.x#toc_injected-container-access' }); | |
this[CONTAINER_OVERRIDE] = value; | |
return value; | |
} | |
}; | |
// TODO - remove when Ember reaches v3.0.0 | |
function injectDeprecatedContainer(object, container) { | |
if ('container' in object) { | |
return; | |
} | |
Object.defineProperty(object, 'container', INJECTED_DEPRECATED_CONTAINER_DESC); | |
} | |
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 (isInstantiatable(container, key) && value.destroy) { | |
value.destroy(); | |
} | |
} | |
} | |
function resetCache(container) { | |
destroyDestroyables(container); | |
container.cache.dict = _emberUtils.dictionary(null); | |
} | |
function resetMember(container, fullName) { | |
var member = container.cache[fullName]; | |
delete container.factoryCache[fullName]; | |
if (member) { | |
delete container.cache[fullName]; | |
if (member.destroy) { | |
member.destroy(); | |
} | |
} | |
} | |
function buildFakeContainerWithDeprecations(container) { | |
var fakeContainer = {}; | |
var propertyMappings = { | |
lookup: 'lookup', | |
lookupFactory: '_lookupFactory' | |
}; | |
for (var containerProperty in propertyMappings) { | |
fakeContainer[containerProperty] = buildFakeContainerFunction(container, containerProperty, propertyMappings[containerProperty]); | |
} | |
return fakeContainer; | |
} | |
function buildFakeContainerFunction(container, containerProperty, ownerProperty) { | |
return function () { | |
_emberDebug.deprecate('Using the injected `container` is deprecated. Please use the `getOwner` helper to access the owner of this object and then call `' + ownerProperty + '` instead.', false, { | |
id: 'ember-application.injected-container', | |
until: '2.13.0', | |
url: 'http://emberjs.com/deprecations/v2.x#toc_injected-container-access' | |
}); | |
return container[containerProperty].apply(container, arguments); | |
}; | |
} | |
var DeprecatedFactoryManager = (function () { | |
function DeprecatedFactoryManager(container, factory, fullName) { | |
babelHelpers.classCallCheck(this, DeprecatedFactoryManager); | |
this.container = container; | |
this.class = factory; | |
this.fullName = fullName; | |
} | |
DeprecatedFactoryManager.prototype.create = function create() { | |
var props = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; | |
return instantiate(this.class, props, this.container, this.fullName); | |
}; | |
return DeprecatedFactoryManager; | |
})(); | |
var FactoryManager = (function () { | |
function FactoryManager(container, factory, fullName, normalizedName) { | |
babelHelpers.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) { | |
this.madeToString = this.container.registry.makeToString(this.class, this.fullName); | |
} | |
return this.madeToString; | |
}; | |
FactoryManager.prototype.create = function create() { | |
var _this = this; | |
var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; | |
var injections = this.injections; | |
if (injections === undefined) { | |
injections = injectionsFor(this.container, this.normalizedName); | |
if (areInjectionsDynamic(injections) === false) { | |
this.injections = injections; | |
} | |
} | |
var props = _emberUtils.assign({}, injections, options); | |
_emberDebug.runInDebug(function () { | |
var lazyInjections = undefined; | |
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.'); | |
} | |
var prototype = this.class.prototype; | |
if (prototype) { | |
injectDeprecatedContainer(prototype, this.container); | |
} | |
// 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-Ember.Object 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 | |
_emberUtils.setOwner(props, this.owner); | |
} | |
return this.class.create(props); | |
}; | |
return FactoryManager; | |
})(); | |
}); | |
/* globals Proxy */ | |
/* | |
* This internal version of factoryFor swaps between the public API for | |
* factoryFor (class is the registered class) and a transition implementation | |
* (class is the double-extended class). It is *not* the public API version | |
* of factoryFor, which always returns the registered class. | |
*/ | |
/** | |
A depth first traversal, destroying the container, its descendant containers and all | |
their managed objects. | |
@private | |
@method destroy | |
*/ | |
/** | |
Clear either the entire cache or just the cache for a particular key. | |
@private | |
@method reset | |
@param {String} fullName optional key to reset; if missing, resets everything | |
*/ | |
/** | |
Returns an object that can be used to provide an owner to a | |
manually created instance. | |
@private | |
@method ownerInjection | |
@returns { Object } | |
*/ | |
enifed('container/index', ['exports', 'container/registry', 'container/container'], function (exports, _containerRegistry, _containerContainer) { | |
/* | |
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 | |
*/ | |
'use strict'; | |
exports.Registry = _containerRegistry.default; | |
exports.privatize = _containerRegistry.privatize; | |
exports.Container = _containerContainer.default; | |
exports.buildFakeContainerWithDeprecations = _containerContainer.buildFakeContainerWithDeprecations; | |
exports.FACTORY_FOR = _containerContainer.FACTORY_FOR; | |
exports.LOOKUP_FACTORY = _containerContainer.LOOKUP_FACTORY; | |
}); | |
enifed('container/registry', ['exports', 'ember-utils', 'ember-debug', 'container/container'], function (exports, _emberUtils, _emberDebug, _containerContainer) { | |
'use strict'; | |
exports.default = Registry; | |
exports.privatize = privatize; | |
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 | |
*/ | |
function Registry(options) { | |
this.fallback = options && options.fallback ? options.fallback : null; | |
if (options && options.resolver) { | |
this.resolver = options.resolver; | |
if (typeof this.resolver === 'function') { | |
deprecateResolverFunction(this); | |
} | |
} | |
this.registrations = _emberUtils.dictionary(options && options.registrations ? options.registrations : null); | |
this._typeInjections = _emberUtils.dictionary(null); | |
this._injections = _emberUtils.dictionary(null); | |
this._factoryTypeInjections = _emberUtils.dictionary(null); | |
this._factoryInjections = _emberUtils.dictionary(null); | |
this._localLookupCache = Object.create(null); | |
this._normalizeCache = _emberUtils.dictionary(null); | |
this._resolveCache = _emberUtils.dictionary(null); | |
this._failCache = _emberUtils.dictionary(null); | |
this._options = _emberUtils.dictionary(null); | |
this._typeOptions = _emberUtils.dictionary(null); | |
} | |
Registry.prototype = { | |
/** | |
A backup registry for resolving registrations when no matches can be found. | |
@private | |
@property fallback | |
@type Registry | |
*/ | |
fallback: null, | |
/** | |
An object that has a `resolve` method that resolves a name. | |
@private | |
@property resolver | |
@type Resolver | |
*/ | |
resolver: null, | |
/** | |
@private | |
@property registrations | |
@type InheritingDict | |
*/ | |
registrations: null, | |
/** | |
@private | |
@property _typeInjections | |
@type InheritingDict | |
*/ | |
_typeInjections: null, | |
/** | |
@private | |
@property _injections | |
@type InheritingDict | |
*/ | |
_injections: null, | |
/** | |
@private | |
@property _factoryTypeInjections | |
@type InheritingDict | |
*/ | |
_factoryTypeInjections: null, | |
/** | |
@private | |
@property _factoryInjections | |
@type InheritingDict | |
*/ | |
_factoryInjections: null, | |
/** | |
@private | |
@property _normalizeCache | |
@type InheritingDict | |
*/ | |
_normalizeCache: null, | |
/** | |
@private | |
@property _resolveCache | |
@type InheritingDict | |
*/ | |
_resolveCache: null, | |
/** | |
@private | |
@property _options | |
@type InheritingDict | |
*/ | |
_options: null, | |
/** | |
@private | |
@property _typeOptions | |
@type InheritingDict | |
*/ | |
_typeOptions: null, | |
/** | |
Creates a container based on this registry. | |
@private | |
@method container | |
@param {Object} options | |
@return {Container} created container | |
*/ | |
container: function (options) { | |
return new _containerContainer.default(this, options); | |
}, | |
/** | |
Registers a factory for later injection. | |
Example: | |
```javascript | |
let registry = new Registry(); | |
registry.register('model:user', Person, {singleton: false }); | |
registry.register('fruit:favorite', Orange); | |
registry.register('communication:main', Email, {singleton: false}); | |
``` | |
@private | |
@method register | |
@param {String} fullName | |
@param {Function} factory | |
@param {Object} options | |
*/ | |
register: function (fullName, factory) { | |
var options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2]; | |
_emberDebug.assert('fullName must be a proper full name', this.validateFullName(fullName)); | |
if (factory === undefined) { | |
throw new TypeError('Attempting to register an unknown factory: \'' + fullName + '\''); | |
} | |
var normalizedName = this.normalize(fullName); | |
if (this._resolveCache[normalizedName]) { | |
throw new Error('Cannot re-register: \'' + fullName + '\', as it has already been resolved.'); | |
} | |
delete this._failCache[normalizedName]; | |
this.registrations[normalizedName] = factory; | |
this._options[normalizedName] = options; | |
}, | |
/** | |
Unregister a fullName | |
```javascript | |
let registry = new Registry(); | |
registry.register('model:user', User); | |
registry.resolve('model:user').create() instanceof User //=> true | |
registry.unregister('model:user') | |
registry.resolve('model:user') === undefined //=> true | |
``` | |
@private | |
@method unregister | |
@param {String} fullName | |
*/ | |
unregister: function (fullName) { | |
_emberDebug.assert('fullName must be a proper full name', this.validateFullName(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]; | |
}, | |
/** | |
Given a fullName return the corresponding factory. | |
By default `resolve` will retrieve the factory from | |
the registry. | |
```javascript | |
let registry = new Registry(); | |
registry.register('api:twitter', Twitter); | |
registry.resolve('api:twitter') // => Twitter | |
``` | |
Optionally the registry can be provided with a custom resolver. | |
If provided, `resolve` will first provide the custom resolver | |
the opportunity to resolve the fullName, otherwise it will fallback | |
to the registry. | |
```javascript | |
let registry = new Registry(); | |
registry.resolver = function(fullName) { | |
// lookup via the module system of choice | |
}; | |
// the twitter factory is added to the module system | |
registry.resolve('api:twitter') // => Twitter | |
``` | |
@private | |
@method resolve | |
@param {String} fullName | |
@param {Object} [options] | |
@param {String} [options.source] the fullname of the request source (used for local lookups) | |
@return {Function} fullName's factory | |
*/ | |
resolve: function (fullName, options) { | |
_emberDebug.assert('fullName must be a proper full name', this.validateFullName(fullName)); | |
var factory = resolve(this, this.normalize(fullName), options); | |
if (factory === undefined && this.fallback) { | |
var _fallback; | |
factory = (_fallback = this.fallback).resolve.apply(_fallback, arguments); | |
} | |
return factory; | |
}, | |
/** | |
A hook that can be used to describe how the resolver will | |
attempt to find the factory. | |
For example, the default Ember `.describe` returns the full | |
class name (including namespace) where Ember's resolver expects | |
to find the `fullName`. | |
@private | |
@method describe | |
@param {String} fullName | |
@return {string} described fullName | |
*/ | |
describe: function (fullName) { | |
if (this.resolver && this.resolver.lookupDescription) { | |
return this.resolver.lookupDescription(fullName); | |
} else if (this.fallback) { | |
return this.fallback.describe(fullName); | |
} else { | |
return fullName; | |
} | |
}, | |
/** | |
A hook to enable custom fullName normalization behaviour | |
@private | |
@method normalizeFullName | |
@param {String} fullName | |
@return {string} normalized fullName | |
*/ | |
normalizeFullName: function (fullName) { | |
if (this.resolver && this.resolver.normalize) { | |
return this.resolver.normalize(fullName); | |
} else if (this.fallback) { | |
return this.fallback.normalizeFullName(fullName); | |
} else { | |
return fullName; | |
} | |
}, | |
/** | |
Normalize a fullName based on the application's conventions | |
@private | |
@method normalize | |
@param {String} fullName | |
@return {string} normalized fullName | |
*/ | |
normalize: function (fullName) { | |
return this._normalizeCache[fullName] || (this._normalizeCache[fullName] = this.normalizeFullName(fullName)); | |
}, | |
/** | |
@method makeToString | |
@private | |
@param {any} factory | |
@param {string} fullName | |
@return {function} toString function | |
*/ | |
makeToString: function (factory, fullName) { | |
if (this.resolver && this.resolver.makeToString) { | |
return this.resolver.makeToString(factory, fullName); | |
} else if (this.fallback) { | |
return this.fallback.makeToString(factory, fullName); | |
} else { | |
return factory.toString(); | |
} | |
}, | |
/** | |
Given a fullName check if the container is aware of its factory | |
or singleton instance. | |
@private | |
@method has | |
@param {String} fullName | |
@param {Object} [options] | |
@param {String} [options.source] the fullname of the request source (used for local lookups) | |
@return {Boolean} | |
*/ | |
has: function (fullName, options) { | |
if (!this.isValidFullName(fullName)) { | |
return false; | |
} | |
var source = options && options.source && this.normalize(options.source); | |
return has(this, this.normalize(fullName), source); | |
}, | |
/** | |
Allow registering options for all factories of a type. | |
```javascript | |
let registry = new Registry(); | |
let container = registry.container(); | |
// if all of type `connection` must not be singletons | |
registry.optionsForType('connection', { singleton: false }); | |
registry.register('connection:twitter', TwitterConnection); | |
registry.register('connection:facebook', FacebookConnection); | |
let twitter = container.lookup('connection:twitter'); | |
let twitter2 = container.lookup('connection:twitter'); | |
twitter === twitter2; // => false | |
let facebook = container.lookup('connection:facebook'); | |
let facebook2 = container.lookup('connection:facebook'); | |
facebook === facebook2; // => false | |
``` | |
@private | |
@method optionsForType | |
@param {String} type | |
@param {Object} options | |
*/ | |
optionsForType: function (type, options) { | |
this._typeOptions[type] = options; | |
}, | |
getOptionsForType: function (type) { | |
var optionsForType = this._typeOptions[type]; | |
if (optionsForType === undefined && this.fallback) { | |
optionsForType = this.fallback.getOptionsForType(type); | |
} | |
return optionsForType; | |
}, | |
/** | |
@private | |
@method options | |
@param {String} fullName | |
@param {Object} options | |
*/ | |
options: function (fullName) { | |
var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; | |
var normalizedName = this.normalize(fullName); | |
this._options[normalizedName] = options; | |
}, | |
getOptions: function (fullName) { | |
var normalizedName = this.normalize(fullName); | |
var options = this._options[normalizedName]; | |
if (options === undefined && this.fallback) { | |
options = this.fallback.getOptions(fullName); | |
} | |
return options; | |
}, | |
getOption: function (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) { | |
return this.fallback.getOption(fullName, optionName); | |
} | |
}, | |
/** | |
Used only via `injection`. | |
Provides a specialized form of injection, specifically enabling | |
all objects of one type to be injected with a reference to another | |
object. | |
For example, provided each object of type `controller` needed a `router`. | |
one would do the following: | |
```javascript | |
let registry = new Registry(); | |
let container = registry.container(); | |
registry.register('router:main', Router); | |
registry.register('controller:user', UserController); | |
registry.register('controller:post', PostController); | |
registry.typeInjection('controller', 'router', 'router:main'); | |
let user = container.lookup('controller:user'); | |
let post = container.lookup('controller:post'); | |
user.router instanceof Router; //=> true | |
post.router instanceof Router; //=> true | |
// both controllers share the same router | |
user.router === post.router; //=> true | |
``` | |
@private | |
@method typeInjection | |
@param {String} type | |
@param {String} property | |
@param {String} fullName | |
*/ | |
typeInjection: function (type, property, fullName) { | |
_emberDebug.assert('fullName must be a proper full name', this.validateFullName(fullName)); | |
var fullNameType = fullName.split(':')[0]; | |
if (fullNameType === type) { | |
throw new Error('Cannot inject a \'' + fullName + '\' on other ' + type + '(s).'); | |
} | |
var injections = this._typeInjections[type] || (this._typeInjections[type] = []); | |
injections.push({ | |
property: property, | |
fullName: fullName | |
}); | |
}, | |
/** | |
Defines injection rules. | |
These rules are used to inject dependencies onto objects when they | |
are instantiated. | |
Two forms of injections are possible: | |
* Injecting one fullName on another fullName | |
* Injecting one fullName on a type | |
Example: | |
```javascript | |
let registry = new Registry(); | |
let container = registry.container(); | |
registry.register('source:main', Source); | |
registry.register('model:user', User); | |
registry.register('model:post', Post); | |
// injecting one fullName on another fullName | |
// eg. each user model gets a post model | |
registry.injection('model:user', 'post', 'model:post'); | |
// injecting one fullName on another type | |
registry.injection('model', 'source', 'source:main'); | |
let user = container.lookup('model:user'); | |
let post = container.lookup('model:post'); | |
user.source instanceof Source; //=> true | |
post.source instanceof Source; //=> true | |
user.post instanceof Post; //=> true | |
// and both models share the same source | |
user.source === post.source; //=> true | |
``` | |
@private | |
@method injection | |
@param {String} factoryName | |
@param {String} property | |
@param {String} injectionName | |
*/ | |
injection: function (fullName, property, injectionName) { | |
this.validateFullName(injectionName); | |
var normalizedInjectionName = this.normalize(injectionName); | |
if (fullName.indexOf(':') === -1) { | |
return this.typeInjection(fullName, property, normalizedInjectionName); | |
} | |
_emberDebug.assert('fullName must be a proper full name', this.validateFullName(fullName)); | |
var normalizedName = this.normalize(fullName); | |
var injections = this._injections[normalizedName] || (this._injections[normalizedName] = []); | |
injections.push({ | |
property: property, | |
fullName: normalizedInjectionName | |
}); | |
}, | |
/** | |
Used only via `factoryInjection`. | |
Provides a specialized form of injection, specifically enabling | |
all factory of one type to be injected with a reference to another | |
object. | |
For example, provided each factory of type `model` needed a `store`. | |
one would do the following: | |
```javascript | |
let registry = new Registry(); | |
registry.register('store:main', SomeStore); | |
registry.factoryTypeInjection('model', 'store', 'store:main'); | |
let store = registry.lookup('store:main'); | |
let UserFactory = registry.lookupFactory('model:user'); | |
UserFactory.store instanceof SomeStore; //=> true | |
``` | |
@private | |
@method factoryTypeInjection | |
@param {String} type | |
@param {String} property | |
@param {String} fullName | |
*/ | |
factoryTypeInjection: function (type, property, fullName) { | |
var injections = this._factoryTypeInjections[type] || (this._factoryTypeInjections[type] = []); | |
injections.push({ | |
property: property, | |
fullName: this.normalize(fullName) | |
}); | |
}, | |
/** | |
Defines factory injection rules. | |
Similar to regular injection rules, but are run against factories, via | |
`Registry#lookupFactory`. | |
These rules are used to inject objects onto factories when they | |
are looked up. | |
Two forms of injections are possible: | |
* Injecting one fullName on another fullName | |
* Injecting one fullName on a type | |
Example: | |
```javascript | |
let registry = new Registry(); | |
let container = registry.container(); | |
registry.register('store:main', Store); | |
registry.register('store:secondary', OtherStore); | |
registry.register('model:user', User); | |
registry.register('model:post', Post); | |
// injecting one fullName on another type | |
registry.factoryInjection('model', 'store', 'store:main'); | |
// injecting one fullName on another fullName | |
registry.factoryInjection('model:post', 'secondaryStore', 'store:secondary'); | |
let UserFactory = container.lookupFactory('model:user'); | |
let PostFactory = container.lookupFactory('model:post'); | |
let store = container.lookup('store:main'); | |
UserFactory.store instanceof Store; //=> true | |
UserFactory.secondaryStore instanceof OtherStore; //=> false | |
PostFactory.store instanceof Store; //=> true | |
PostFactory.secondaryStore instanceof OtherStore; //=> true | |
// and both models share the same source instance | |
UserFactory.store === PostFactory.store; //=> true | |
``` | |
@private | |
@method factoryInjection | |
@param {String} factoryName | |
@param {String} property | |
@param {String} injectionName | |
*/ | |
factoryInjection: function (fullName, property, injectionName) { | |
var normalizedName = this.normalize(fullName); | |
var normalizedInjectionName = this.normalize(injectionName); | |
this.validateFullName(injectionName); | |
if (fullName.indexOf(':') === -1) { | |
return this.factoryTypeInjection(normalizedName, property, normalizedInjectionName); | |
} | |
var injections = this._factoryInjections[normalizedName] || (this._factoryInjections[normalizedName] = []); | |
injections.push({ | |
property: property, | |
fullName: normalizedInjectionName | |
}); | |
}, | |
/** | |
@private | |
@method knownForType | |
@param {String} type the type to iterate over | |
*/ | |
knownForType: function (type) { | |
var fallbackKnown = undefined, | |
resolverKnown = undefined; | |
var localKnown = _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) { | |
fallbackKnown = this.fallback.knownForType(type); | |
} | |
if (this.resolver && this.resolver.knownForType) { | |
resolverKnown = this.resolver.knownForType(type); | |
} | |
return _emberUtils.assign({}, fallbackKnown, localKnown, resolverKnown); | |
}, | |
validateFullName: function (fullName) { | |
if (!this.isValidFullName(fullName)) { | |
throw new TypeError('Invalid Fullname, expected: \'type:name\' got: ' + fullName); | |
} | |
return true; | |
}, | |
isValidFullName: function (fullName) { | |
return !!VALID_FULL_NAME_REGEXP.test(fullName); | |
}, | |
validateInjections: function (injections) { | |
if (!injections) { | |
return; | |
} | |
var fullName = undefined; | |
for (var i = 0; i < injections.length; i++) { | |
fullName = injections[i].fullName; | |
_emberDebug.assert('Attempting to inject an unknown injection: \'' + fullName + '\'', this.has(fullName)); | |
} | |
}, | |
normalizeInjectionsHash: function (hash) { | |
var injections = []; | |
for (var key in hash) { | |
if (hash.hasOwnProperty(key)) { | |
_emberDebug.assert('Expected a proper full name, given \'' + hash[key] + '\'', this.validateFullName(hash[key])); | |
injections.push({ | |
property: key, | |
fullName: hash[key] | |
}); | |
} | |
} | |
return injections; | |
}, | |
getInjections: function (fullName) { | |
var injections = this._injections[fullName] || []; | |
if (this.fallback) { | |
injections = injections.concat(this.fallback.getInjections(fullName)); | |
} | |
return injections; | |
}, | |
getTypeInjections: function (type) { | |
var injections = this._typeInjections[type] || []; | |
if (this.fallback) { | |
injections = injections.concat(this.fallback.getTypeInjections(type)); | |
} | |
return injections; | |
}, | |
getFactoryInjections: function (fullName) { | |
var injections = this._factoryInjections[fullName] || []; | |
if (this.fallback) { | |
injections = injections.concat(this.fallback.getFactoryInjections(fullName)); | |
} | |
return injections; | |
}, | |
getFactoryTypeInjections: function (type) { | |
var injections = this._factoryTypeInjections[type] || []; | |
if (this.fallback) { | |
injections = injections.concat(this.fallback.getFactoryTypeInjections(type)); | |
} | |
return injections; | |
} | |
}; | |
function deprecateResolverFunction(registry) { | |
_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: 'http://emberjs.com/deprecations/v2.x#toc_registry-resolver-as-function' }); | |
registry.resolver = { | |
resolve: registry.resolver | |
}; | |
} | |
/** | |
Given a fullName and a source fullName returns the fully resolved | |
fullName. Used to allow for local lookup. | |
```javascript | |
let registry = new Registry(); | |
// the twitter factory is added to the module system | |
registry.expandLocalLookup('component:post-title', { source: 'template:post' }) // => component:post/post-title | |
``` | |
@private | |
@method expandLocalLookup | |
@param {String} fullName | |
@param {Object} [options] | |
@param {String} [options.source] the fullname of the request source (used for local lookups) | |
@return {String} fullName | |
*/ | |
Registry.prototype.expandLocalLookup = function Registry_expandLocalLookup(fullName, options) { | |
if (this.resolver && this.resolver.expandLocalLookup) { | |
_emberDebug.assert('fullName must be a proper full name', this.validateFullName(fullName)); | |
_emberDebug.assert('options.source must be provided to expandLocalLookup', options && options.source); | |
_emberDebug.assert('options.source must be a proper full name', this.validateFullName(options.source)); | |
var normalizedFullName = this.normalize(fullName); | |
var normalizedSource = this.normalize(options.source); | |
return expandLocalLookup(this, normalizedFullName, normalizedSource); | |
} else if (this.fallback) { | |
return this.fallback.expandLocalLookup(fullName, options); | |
} else { | |
return null; | |
} | |
}; | |
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 | |
normalizedName = registry.expandLocalLookup(normalizedName, options); | |
// if expandLocalLookup returns falsey, we do not support local lookup | |
if (!normalizedName) { | |
return; | |
} | |
} | |
var cached = registry._resolveCache[normalizedName]; | |
if (cached !== undefined) { | |
return cached; | |
} | |
if (registry._failCache[normalizedName]) { | |
return; | |
} | |
var resolved = undefined; | |
if (registry.resolver) { | |
resolved = registry.resolver.resolve(normalizedName); | |
} | |
if (resolved === undefined) { | |
resolved = registry.registrations[normalizedName]; | |
} | |
if (resolved === undefined) { | |
registry._failCache[normalizedName] = true; | |
} else { | |
registry._resolveCache[normalizedName] = resolved; | |
} | |
return resolved; | |
} | |
function has(registry, fullName, source) { | |
return registry.resolve(fullName, { source: source }) !== undefined; | |
} | |
var privateNames = _emberUtils.dictionary(null); | |
var privateSuffix = '' + Math.random() + Date.now(); | |
function privatize(_ref) { | |
var fullName = _ref[0]; | |
var name = privateNames[fullName]; | |
if (name) { | |
return name; | |
} | |
var _fullName$split = fullName.split(':'); | |
var type = _fullName$split[0]; | |
var rawName = _fullName$split[1]; | |
return privateNames[fullName] = _emberUtils.intern(type + ':' + rawName + '-' + privateSuffix); | |
} | |
}); | |
enifed('dag-map', ['exports'], function (exports) { 'use strict'; | |
/** | |
* A map of key/value pairs with dependencies contraints that can be traversed | |
* in topological order and is checked for cycles. | |
* | |
* @class DAG | |
* @constructor | |
*/ | |
var DAG = (function () { | |
function DAG() { | |
this._vertices = new Vertices(); | |
} | |
/** | |
* Adds a key/value pair with dependencies on other key/value pairs. | |
* | |
* @public | |
* @method addEdges | |
* @param {string[]} key The key of the vertex to be added. | |
* @param {any} value The value of that vertex. | |
* @param {string[]|string|undefined} before A key or array of keys of the vertices that must | |
* be visited before this vertex. | |
* @param {string[]|string|undefined} 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) { | |
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); | |
} | |
} | |
} | |
}; | |
/** | |
* Visits key/value pairs in topological order. | |
* | |
* @public | |
* @method topsort | |
* @param {Function} fn The function to be invoked with each key/value. | |
*/ | |
DAG.prototype.topsort = function (callback) { | |
this._vertices.topsort(callback); | |
}; | |
return DAG; | |
}()); | |
var Vertices = (function () { | |
function Vertices() { | |
this.stack = new IntStack(); | |
this.result = new IntStack(); | |
this.vertices = []; | |
} | |
Vertices.prototype.add = function (key) { | |
if (!key) | |
throw new Error("missing key"); | |
var vertices = this.vertices; | |
var i = 0; | |
var vertex; | |
for (; i < vertices.length; i++) { | |
vertex = vertices[i]; | |
if (vertex.key === key) | |
return vertex; | |
} | |
return vertices[i] = { | |
id: i, | |
key: key, | |
val: null, | |
inc: null, | |
out: false, | |
mark: false | |
}; | |
}; | |
Vertices.prototype.addEdge = function (v, w) { | |
this.check(v, w.key); | |
var inc = w.inc; | |
if (!inc) { | |
w.inc = [v.id]; | |
} | |
else { | |
var i = 0; | |
for (; i < inc.length; i++) { | |
if (inc[i] === v.id) | |
return; | |
} | |
inc[i] = v.id; | |
} | |
v.out = true; | |
}; | |
Vertices.prototype.topsort = function (cb) { | |
this.reset(); | |
var vertices = this.vertices; | |
for (var i = 0; i < vertices.length; i++) { | |
var vertex = vertices[i]; | |
if (vertex.out) | |
continue; | |
this.visit(vertex, undefined); | |
} | |
this.each(cb); | |
}; | |
Vertices.prototype.check = function (v, w) { | |
if (v.key === w) { | |
throw new Error("cycle detected: " + w + " <- " + w); | |
} | |
var inc = v.inc; | |
// quick check | |
if (!inc || inc.length === 0) | |
return; | |
var vertices = this.vertices; | |
// shallow check | |
for (var i = 0; i < inc.length; i++) { | |
var key = vertices[inc[i]].key; | |
if (key === w) { | |
throw new Error("cycle detected: " + w + " <- " + v.key + " <- " + w); | |
} | |
} | |
// deep check | |
this.reset(); | |
this.visit(v, w); | |
if (this.result.len > 0) { | |
var msg_1 = "cycle detected: " + w; | |
this.each(function (key) { | |
msg_1 += " <- " + key; | |
}); | |
throw new Error(msg_1); | |
} | |
}; | |
Vertices.prototype.each = function (cb) { | |
var _a = this, result = _a.result, vertices = _a.vertices; | |
for (var i = 0; i < result.len; i++) { | |
var vertex = vertices[result.stack[i]]; | |
cb(vertex.key, vertex.val); | |
} | |
}; | |
// reuse between cycle check and topsort | |
Vertices.prototype.reset = function () { | |
this.stack.len = 0; | |
this.result.len = 0; | |
var vertices = this.vertices; | |
for (var i = 0; i < vertices.length; i++) { | |
vertices[i].mark = false; | |
} | |
}; | |
Vertices.prototype.visit = function (start, search) { | |
var _a = this, stack = _a.stack, result = _a.result, vertices = _a.vertices; | |
stack.push(start.id); | |
while (stack.len) { | |
var index = stack.pop(); | |
if (index < 0) { | |
index = ~index; | |
if (search) { | |
result.pop(); | |
} | |
else { | |
result.push(index); | |
} | |
} | |
else { | |
var vertex = vertices[index]; | |
if (vertex.mark) { | |
continue; | |
} | |
if (search) { | |
result.push(index); | |
if (search === vertex.key) { | |
return; | |
} | |
} | |
vertex.mark = true; | |
stack.push(~index); | |
var incoming = vertex.inc; | |
if (incoming) { | |
var i = incoming.length; | |
while (i--) { | |
index = incoming[i]; | |
if (!vertices[index].mark) { | |
stack.push(index); | |
} | |
} | |
} | |
} | |
} | |
}; | |
return Vertices; | |
}()); | |
var IntStack = (function () { | |
function IntStack() { | |
this.stack = [0, 0, 0, 0, 0, 0]; | |
this.len = 0; | |
} | |
IntStack.prototype.push = function (n) { | |
this.stack[this.len++] = n; | |
}; | |
IntStack.prototype.pop = function () { | |
return this.stack[--this.len]; | |
}; | |
return IntStack; | |
}()); | |
exports['default'] = DAG; | |
Object.defineProperty(exports, '__esModule', { value: true }); | |
}); | |
enifed('ember-application/index', ['exports', 'ember-application/initializers/dom-templates', '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'], function (exports, _emberApplicationInitializersDomTemplates, _emberApplicationSystemApplication, _emberApplicationSystemApplicationInstance, _emberApplicationSystemResolver, _emberApplicationSystemEngine, _emberApplicationSystemEngineInstance, _emberApplicationSystemEngineParent) { | |
/** | |
@module ember | |
@submodule ember-application | |
*/ | |
'use strict'; | |
exports.Application = _emberApplicationSystemApplication.default; | |
exports.ApplicationInstance = _emberApplicationSystemApplicationInstance.default; | |
exports.Resolver = _emberApplicationSystemResolver.default; | |
exports.Engine = _emberApplicationSystemEngine.default; | |
exports.EngineInstance = _emberApplicationSystemEngineInstance.default; | |
exports.getEngineParent = _emberApplicationSystemEngineParent.getEngineParent; | |
exports.setEngineParent = _emberApplicationSystemEngineParent.setEngineParent; | |
// add domTemplates initializer (only does something if `ember-template-compiler` | |
// is loaded already) | |
}); | |
enifed('ember-application/initializers/dom-templates', ['exports', 'require', 'ember-glimmer', 'ember-environment', 'ember-application/system/application'], function (exports, _require, _emberGlimmer, _emberEnvironment, _emberApplicationSystemApplication) { | |
'use strict'; | |
var bootstrap = function () {}; | |
_emberApplicationSystemApplication.default.initializer({ | |
name: 'domTemplates', | |
initialize: function () { | |
var bootstrapModuleId = 'ember-template-compiler/system/bootstrap'; | |
var context = undefined; | |
if (_emberEnvironment.environment.hasDOM && _require.has(bootstrapModuleId)) { | |
bootstrap = _require.default(bootstrapModuleId).default; | |
context = document; | |
} | |
bootstrap({ context: context, hasTemplate: _emberGlimmer.hasTemplate, setTemplate: _emberGlimmer.setTemplate }); | |
} | |
}); | |
}); | |
enifed('ember-application/system/application-instance', ['exports', 'ember-utils', 'ember-debug', 'ember-metal', 'ember-runtime', 'ember-environment', 'ember-views', 'ember-application/system/engine-instance'], function (exports, _emberUtils, _emberDebug, _emberMetal, _emberRuntime, _emberEnvironment, _emberViews, _emberApplicationSystemEngineInstance) { | |
/** | |
@module ember | |
@submodule ember-application | |
*/ | |
'use strict'; | |
var BootOptions = undefined; | |
/** | |
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 Ember.ApplicationInstance | |
@extends Ember.EngineInstance | |
*/ | |
var ApplicationInstance = _emberApplicationSystemEngineInstance.default.extend({ | |
/** | |
The `Application` for which this is an instance. | |
@property {Ember.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 }); | |
}, | |
/** | |
Overrides the base `EngineInstance._bootSync` method with concerns relevant | |
to booting application (instead of engine) instances. | |
This method should only contain synchronous boot concerns. Asynchronous | |
boot concerns should eventually be moved to the `boot` method, which | |
returns a promise. | |
Until all boot code has been made asynchronous, we need to continue to | |
expose this method for use *internally* in places where we need to boot an | |
instance synchronously. | |
@private | |
*/ | |
_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 = _emberMetal.get(this, 'router'); | |
_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: _emberMetal.computed(function () { | |
return this.lookup('router:main'); | |
}).readOnly(), | |
/** | |
This hook is called by the root-most Route (a.k.a. the ApplicationRoute) | |
when it has finished creating the root View. By default, we simply take the | |
view and append it to the `rootElement` specified on the Application. | |
In cases like FastBoot and testing, we can override this hook and implement | |
custom behavior, such as serializing to a string and sending over an HTTP | |
socket rather than appending to DOM. | |
@param view {Ember.View} the root-most view | |
@private | |
*/ | |
didCreateRootView: function (view) { | |
view.appendTo(this.rootElement); | |
}, | |
/** | |
Tells the router to start routing. The router will ask the location for the | |
current URL of the page to determine the initial URL to start routing to. | |
To start the app at a specific URL, call `handleURL` instead. | |
@private | |
*/ | |
startRouting: function () { | |
var router = _emberMetal.get(this, 'router'); | |
router.startRouting(); | |
this._didSetupRouter = true; | |
}, | |
/** | |
@private | |
Sets up the router, initializing the child router and configuring the | |
location before routing begins. | |
Because setup should only occur once, multiple calls to `setupRouter` | |
beyond the first call have no effect. | |
*/ | |
setupRouter: function () { | |
if (this._didSetupRouter) { | |
return; | |
} | |
this._didSetupRouter = true; | |
var router = _emberMetal.get(this, 'router'); | |
router.setupRouter(); | |
}, | |
/** | |
Directs the router to route to a particular URL. This is useful in tests, | |
for example, to tell the app to start at a particular URL. | |
@param url {String} the URL the router should route to | |
@private | |
*/ | |
handleURL: function (url) { | |
var router = _emberMetal.get(this, 'router'); | |
this.setupRouter(); | |
return router.handleURL(url); | |
}, | |
/** | |
@private | |
*/ | |
setupEventDispatcher: function () { | |
var dispatcher = this.lookup('event_dispatcher:main'); | |
var applicationCustomEvents = _emberMetal.get(this.application, 'customEvents'); | |
var instanceCustomEvents = _emberMetal.get(this, 'customEvents'); | |
var customEvents = _emberUtils.assign({}, applicationCustomEvents, instanceCustomEvents); | |
dispatcher.setup(customEvents, this.rootElement); | |
return dispatcher; | |
}, | |
/** | |
Returns the current URL of the app instance. This is useful when your | |
app does not update the browsers URL bar (i.e. it uses the `'none'` | |
location adapter). | |
@public | |
@return {String} the current URL | |
*/ | |
getURL: function () { | |
var router = _emberMetal.get(this, 'router'); | |
return _emberMetal.get(router, 'url'); | |
}, | |
// `instance.visit(url)` should eventually replace `instance.handleURL()`; | |
// the test helpers can probably be switched to use this implementation too | |
/** | |
Navigate the instance to a particular URL. This is useful in tests, for | |
example, or to tell the app to start at a particular URL. This method | |
returns a promise that resolves with the app instance when the transition | |
is complete, or rejects if the transion was aborted due to an error. | |
@public | |
@param url {String} the destination URL | |
@return {Promise} | |
*/ | |
visit: function (url) { | |
var _this = this; | |
this.setupRouter(); | |
var bootOptions = this.__container__.lookup('-environment:main'); | |
var router = _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 = _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({ | |
/** | |
@private | |
@method setupRegistry | |
@param {Registry} registry | |
@param {BootOptions} options | |
*/ | |
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 Ember.ApplicationInstance | |
@public | |
*/ | |
BootOptions = 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 = _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, 'container', { | |
configurable: true, | |
enumerable: false, | |
get: function () { | |
var instance = this; | |
return { | |
lookup: function () { | |
_emberDebug.deprecate('Using `ApplicationInstance.container.lookup` is deprecated. Please use `ApplicationInstance.lookup` instead.', false, { | |
id: 'ember-application.app-instance-container', | |
until: '2.13.0', | |
url: 'http://emberjs.com/deprecations/v2.x/#toc_ember-applicationinstance-container' | |
}); | |
return instance.lookup.apply(instance, arguments); | |
} | |
}; | |
} | |
}); | |
Object.defineProperty(ApplicationInstance.prototype, 'registry', { | |
configurable: true, | |
enumerable: false, | |
get: function () { | |
return _emberRuntime.buildFakeRegistryWithDeprecations(this, 'ApplicationInstance'); | |
} | |
}); | |
exports.default = ApplicationInstance; | |
}); | |
enifed('ember-application/system/application', ['exports', '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'], function (exports, _emberUtils, _emberEnvironment, _emberDebug, _emberMetal, _emberRuntime, _emberViews, _emberRouting, _emberApplicationSystemApplicationInstance, _container, _emberApplicationSystemEngine, _emberGlimmer) { | |
/** | |
@module ember | |
@submodule ember-application | |
*/ | |
'use strict'; | |
var _templateObject = babelHelpers.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 | |
@namespace Ember | |
@extends Ember.Engine | |
@uses RegistryProxyMixin | |
@public | |
*/ | |
var Application = _emberApplicationSystemEngine.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(); | |
_emberDebug.runInDebug(function () { | |
return 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(); | |
} | |
}, | |
/** | |
Create an ApplicationInstance for this application. | |
@private | |
@method buildInstance | |
@return {Ember.ApplicationInstance} the application instance | |
*/ | |
buildInstance: function () { | |
var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; | |
options.base = this; | |
options.application = this; | |
return _emberApplicationSystemApplicationInstance.default.create(options); | |
}, | |
/** | |
Enable the legacy globals mode by allowing this application to act | |
as a global namespace. See the docs on the `_globalsMode` property | |
for details. | |
Most of these features are already deprecated in 1.x, so we can | |
stop using them internally and try to remove them. | |
@private | |
@method _prepareForGlobalsMode | |
*/ | |
_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(); | |
}, | |
/* | |
Build the deprecated instance for legacy globals mode support. | |
Called when creating and resetting the application. | |
This is orthogonal to autoboot: the deprecated instance needs to | |
be created at Application construction (not boot) time to expose | |
App.__container__. If autoboot sees that this instance exists, | |
it will continue booting it to avoid doing unncessary work (as | |
opposed to building a new instance at boot time), but they are | |
otherwise unrelated. | |
@private | |
@method _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__; | |
}, | |
/** | |
Automatically kick-off the boot process for the application once the | |
DOM has become ready. | |
The initialization itself is scheduled on the actions queue which | |
ensures that code-loading finishes before booting. | |
If you are asynchronously loading code, you should call `deferReadiness()` | |
to defer booting, and then call `advanceReadiness()` once all of your code | |
has finished loading. | |
@private | |
@method waitForDOMReady | |
*/ | |
waitForDOMReady: function () { | |
if (!this.$ || this.$.isReady) { | |
_emberMetal.run.schedule('actions', this, 'domReady'); | |
} else { | |
this.$().ready(_emberMetal.run.bind(this, 'domReady')); | |
} | |
}, | |
/** | |
This is the autoboot flow: | |
1. Boot the app by calling `this.boot()` | |
2. Create an instance (or use the `__deprecatedInstance__` in globals mode) | |
3. Boot the instance by calling `instance.boot()` | |
4. Invoke the `App.ready()` callback | |
5. Kick-off routing on the instance | |
Ideally, this is all we would need to do: | |
```javascript | |
_autoBoot() { | |
this.boot().then(() => { | |
let instance = (this._globalsMode) ? this.__deprecatedInstance__ : this.buildInstance(); | |
return instance.boot(); | |
}).then((instance) => { | |
App.ready(); | |
instance.startRouting(); | |
}); | |
} | |
``` | |
Unfortunately, we cannot actually write this because we need to participate | |
in the "synchronous" boot process. While the code above would work fine on | |
the initial boot (i.e. DOM ready), when `App.reset()` is called, we need to | |
boot a new instance synchronously (see the documentation on `_bootSync()` | |
for details). | |
Because of this restriction, the actual logic of this method is located | |
inside `didBecomeReady()`. | |
@private | |
@method domReady | |
*/ | |
domReady: function () { | |
if (this.isDestroyed) { | |
return; | |
} | |
this._bootSync(); | |
// Continues to `didBecomeReady` | |
}, | |
/** | |
Use this to defer readiness until some condition is true. | |
Example: | |
```javascript | |
let App = Ember.Application.create(); | |
App.deferReadiness(); | |
// Ember.$ is a reference to the jQuery object/function | |
Ember.$.getJSON('/auth-token', function(token) { | |
App.token = token; | |
App.advanceReadiness(); | |
}); | |
``` | |
This allows you to perform asynchronous setup logic and defer | |
booting your application until the setup has finished. | |
However, if the setup requires a loading UI, it might be better | |
to use the router for this purpose. | |
@method deferReadiness | |
@public | |
*/ | |
deferReadiness: function () { | |
_emberDebug.assert('You must call deferReadiness on an instance of Ember.Application', this instanceof Application); | |
_emberDebug.assert('You cannot defer readiness since the `ready()` hook has already been called.', this._readinessDeferrals > 0); | |
this._readinessDeferrals++; | |
}, | |
/** | |
Call `advanceReadiness` after any asynchronous setup logic has completed. | |
Each call to `deferReadiness` must be matched by a call to `advanceReadiness` | |
or the application will never become ready and routing will not begin. | |
@method advanceReadiness | |
@see {Ember.Application#deferReadiness} | |
@public | |
*/ | |
advanceReadiness: function () { | |
_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); | |
} | |
}, | |
/** | |
Initialize the application and return a promise that resolves with the `Ember.Application` | |
object when the boot process is complete. | |
Run any application initializers and run the application load hook. These hooks may | |
choose to defer readiness. For example, an authentication hook might want to defer | |
readiness until the auth token has been retrieved. | |
By default, this method is called automatically on "DOM ready"; however, if autoboot | |
is disabled, this is automatically called when the first application instance is | |
created via `visit`. | |
@private | |
@method boot | |
@return {Promise<Ember.Application,Error>} | |
*/ | |
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; | |
}, | |
/** | |
Unfortunately, a lot of existing code assumes the booting process is | |
"synchronous". Specifically, a lot of tests assumes the last call to | |
`app.advanceReadiness()` or `app.reset()` will result in the app being | |
fully-booted when the current runloop completes. | |
We would like new code (like the `visit` API) to stop making this assumption, | |
so we created the asynchronous version above that returns a promise. But until | |
we have migrated all the code, we would have to expose this method for use | |
*internally* in places where we need to boot an app "synchronously". | |
@private | |
*/ | |
_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 = new _emberRuntime.RSVP.defer(); | |
this._bootPromise = defer.promise; | |
try { | |
this.runInitializers(); | |
_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 the application. This is typically used only in tests. It cleans up | |
the application in the following order: | |
1. Deactivate existing routes | |
2. Destroy all objects in the container | |
3. Create a new application container | |
4. Re-route to the existing url | |
Typical Example: | |
```javascript | |
let App; | |
run(function() { | |
App = Ember.Application.create(); | |
}); | |
module('acceptance test', { | |
setup: function() { | |
App.reset(); | |
} | |
}); | |
test('first test', function() { | |
// App is freshly reset | |
}); | |
test('second test', function() { | |
// App is again freshly reset | |
}); | |
``` | |
Advanced Example: | |
Occasionally you may want to prevent the app from initializing during | |
setup. This could enable extra configuration, or enable asserting prior | |
to the app becoming ready. | |
```javascript | |
let App; | |
run(function() { | |
App = Ember.Application.create(); | |
}); | |
module('acceptance test', { | |
setup: function() { | |
run(function() { | |
App.reset(); | |
App.deferReadiness(); | |
}); | |
} | |
}); | |
test('first test', function() { | |
ok(true, 'something before app is initialized'); | |
run(function() { | |
App.advanceReadiness(); | |
}); | |
ok(true, 'something after app is initialized'); | |
}); | |
``` | |
@method reset | |
@public | |
*/ | |
reset: function () { | |
_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() { | |
_emberMetal.run(instance, 'destroy'); | |
this._buildDeprecatedInstance(); | |
_emberMetal.run.schedule('actions', this, '_bootSync'); | |
} | |
_emberMetal.run.join(this, handleReset); | |
}, | |
/** | |
@private | |
@method didBecomeReady | |
*/ | |
didBecomeReady: function () { | |
try { | |
// TODO: Is this still needed for _globalsMode = false? | |
if (!_emberDebug.isTesting()) { | |
// Eagerly name all classes that are already loaded | |
_emberRuntime.Namespace.processAll(); | |
_emberRuntime.setNamespaceSearchDisabled(true); | |
} | |
// See documentation on `_autoboot()` for details | |
if (this.autoboot) { | |
var instance = undefined; | |
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; | |
} | |
}, | |
/** | |
Called when the Application has become ready, immediately before routing | |
begins. The call will be delayed until the DOM has become ready. | |
@event ready | |
@public | |
*/ | |
ready: function () { | |
return this; | |
}, | |
// This method must be moved to the application instance object | |
willDestroy: function () { | |
this._super.apply(this, arguments); | |
_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(); | |
} | |
}, | |
/** | |
Boot a new instance of `Ember.ApplicationInstance` for the current | |
application and navigate it to the given `url`. Returns a `Promise` that | |
resolves with the instance when the initial routing and rendering is | |
complete, or rejects with any error that occured during the boot process. | |
When `autoboot` is disabled, calling `visit` would first cause the | |
application to boot, which runs the application initializers. | |
This method also takes a hash of boot-time configuration options for | |
customizing the instance's behavior. See the documentation on | |
`Ember.ApplicationInstance.BootOptions` for details. | |
`Ember.ApplicationInstance.BootOptions` 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 of the | |
desired options: | |
```javascript | |
MyApp.visit("/", { location: "none", rootElement: "#container" }); | |
``` | |
### Supported Scenarios | |
While the `BootOptions` class exposes a large number of knobs, not all | |
combinations of them are valid; certain incompatible combinations might | |
result in unexpected behavior. | |
For example, booting the instance in the full browser environment | |
while specifying a foriegn `document` object (e.g. `{ isBrowser: true, | |
document: iframe.contentDocument }`) does not work correctly today, | |
largely due to Ember's jQuery dependency. | |
Currently, there are three officially supported scenarios/configurations. | |
Usages outside of these scenarios are not guaranteed to work, but please | |
feel free to file bug reports documenting your experience and any issues | |
you encountered to help expand support. | |
#### Browser Applications (Manual Boot) | |
The setup is largely similar to how Ember works out-of-the-box. Normally, | |
Ember will boot a default instance for your Application on "DOM ready". | |
However, you can customize this behavior by disabling `autoboot`. | |
For example, this allows you to render a miniture demo of your application | |
into a specific area on your marketing website: | |
```javascript | |
import MyApp from 'my-app'; | |
$(function() { | |
let App = MyApp.create({ autoboot: false }); | |
let options = { | |
// Override the router's location adapter to prevent it from updating | |
// the URL in the address bar | |
location: 'none', | |
// Override the default `rootElement` on the app to render into a | |
// specific `div` on the page | |
rootElement: '#demo' | |
}; | |
// Start the app at the special demo URL | |
App.visit('/demo', options); | |
}); | |
```` | |
Or perhaps you might want to boot two instances of your app on the same | |
page for a split-screen multiplayer experience: | |
```javascript | |
import MyApp from 'my-app'; | |
$(function() { | |
let App = MyApp.create({ autoboot: false }); | |
let sessionId = MyApp.generateSessionID(); | |
let player1 = App.visit(`/matches/join?name=Player+1&session=${sessionId}`, { rootElement: '#left', location: 'none' }); | |
let player2 = App.visit(`/matches/join?name=Player+2&session=${sessionId}`, { rootElement: '#right', location: 'none' }); | |
Promise.all([player1, player2]).then(() => { | |
// Both apps have completed the initial render | |
$('#loading').fadeOut(); | |
}); | |
}); | |
``` | |
Do note that each app instance maintains their own registry/container, so | |
they will run in complete isolation by default. | |
#### Server-Side Rendering (also known as FastBoot) | |
This setup allows you to run your Ember app in a server environment using | |
Node.js and render its content into static HTML for SEO purposes. | |
```javascript | |
const HTMLSerializer = new SimpleDOM.HTMLSerializer(SimpleDOM.voidMap); | |
function renderURL(url) { | |
let dom = new SimpleDOM.Document(); | |
let rootElement = dom.body; | |
let options = { isBrowser: false, document: dom, rootElement: rootElement }; | |
return MyApp.visit(options).then(instance => { | |
try { | |
return HTMLSerializer.serialize(rootElement.firstChild); | |
} finally { | |
instance.destroy(); | |
} | |
}); | |
} | |
``` | |
In this scenario, because Ember does not have access to a global `document` | |
object in the Node.js environment, you must provide one explicitly. In practice, | |
in the non-browser environment, the stand-in `document` object only need to | |
implement a limited subset of the full DOM API. The `SimpleDOM` library is known | |
to work. | |
Since there is no access to jQuery in the non-browser environment, you must also | |
specify a DOM `Element` object in the same `document` for the `rootElement` option | |
(as opposed to a selector string like `"body"`). | |
See the documentation on the `isBrowser`, `document` and `rootElement` properties | |
on `Ember.ApplicationInstance.BootOptions` for details. | |
#### Server-Side Resource Discovery | |
This setup allows you to run the routing layer of your Ember app in a server | |
environment using Node.js and completely disable rendering. This allows you | |
to simulate and discover the resources (i.e. AJAX requests) needed to fufill | |
a given request and eagerly "push" these resources to the client. | |
```app/initializers/network-service.js | |
import BrowserNetworkService from 'app/services/network/browser'; | |
import NodeNetworkService from 'app/services/network/node'; | |
// Inject a (hypothetical) service for abstracting all AJAX calls and use | |
// the appropiate implementaion on the client/server. This also allows the | |
// server to log all the AJAX calls made during a particular request and use | |
// that for resource-discovery purpose. | |
export function initialize(application) { | |
if (window) { // browser | |
application.register('service:network', BrowserNetworkService); | |
} else { // node | |
application.register('service:network', NodeNetworkService); | |
} | |
application.inject('route', 'network', 'service:network'); | |
}; | |
export default { | |
name: 'network-service', | |
initialize: initialize | |
}; | |
``` | |
```app/routes/post.js | |
import Ember from 'ember'; | |
// An example of how the (hypothetical) service is used in routes. | |
export default Ember.Route.extend({ | |
model(params) { | |
return this.network.fetch(`/api/posts/${params.post_id}.json`); | |
}, | |
afterModel(post) { | |
if (post.isExternalContent) { | |
return this.network.fetch(`/api/external/?url=${post.externalURL}`); | |
} else { | |
return post; | |
} | |
} | |
}); | |
``` | |
```javascript | |
// Finally, put all the pieces together | |
function discoverResourcesFor(url) { | |
return MyApp.visit(url, { isBrowser: false, shouldRender: false }).then(instance => { | |
let networkService = instance.lookup('service:network'); | |
return networkService.requests; // => { "/api/posts/123.json": "..." } | |
}); | |
} | |
``` | |
@public | |
@method visit | |
@param url {String} The initial URL to navigate to | |
@param options {Ember.ApplicationInstance.BootOptions} | |
@return {Promise<Ember.ApplicationInstance, Error>} | |
*/ | |
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) { | |
_emberMetal.run(instance, 'destroy'); | |
throw error; | |
}); | |
}); | |
} | |
}); | |
Object.defineProperty(Application.prototype, 'registry', { | |
configurable: true, | |
enumerable: false, | |
get: function () { | |
return _emberRuntime.buildFakeRegistryWithDeprecations(this, 'Application'); | |
} | |
}); | |
Application.reopenClass({ | |
/** | |
This creates a registry with the default Ember naming conventions. | |
It also configures the registry: | |
* registered views are created every time they are looked up (they are | |
not singletons) | |
* registered templates are not factories; the registered value is | |
returned directly. | |
* the router receives the application as its `namespace` property | |
* all controllers receive the router as their `target` and `controllers` | |
properties | |
* all controllers receive the application as their `namespace` property | |
* the application view receives the application controller as its | |
`controller` property | |
* the application view receives the application template as its | |
`defaultTemplate` property | |
@method buildRegistry | |
@static | |
@param {Ember.Application} namespace the application for which to | |
build the registry | |
@return {Ember.Registry} the built registry | |
@private | |
*/ | |
buildRegistry: function (application) { | |
var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; | |
var registry = this._super.apply(this, arguments); | |
commonSetupRegistry(registry); | |
_emberGlimmer.setupApplicationRegistry(registry); | |
return registry; | |
} | |
}); | |
function commonSetupRegistry(registry) { | |
registry.register('-view-registry:main', { create: function () { | |
return _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(_container.privatize(_templateObject), _emberRouting.BucketCache); | |
if (false) { | |
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', _emberViews.jQuery().jquery); | |
} | |
} | |
} | |
function logLibraryVersions() { | |
var _this2 = this; | |
_emberDebug.runInDebug(function () { | |
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 _emberMetal.get(item, 'name.length'); | |
}); | |
var maxNameLength = Math.max.apply(_this2, nameLengths); | |
_emberDebug.debug('-------------------------------'); | |
for (var i = 0; i < libs.length; i++) { | |
var lib = libs[i]; | |
var spaces = new Array(maxNameLength - lib.name.length + 1).join(' '); | |
_emberDebug.debug([lib.name, spaces, ' : ', lib.version].join('')); | |
} | |
_emberDebug.debug('-------------------------------'); | |
} | |
}); | |
} | |
exports.default = Application; | |
}); | |
enifed('ember-application/system/engine-instance', ['exports', 'ember-utils', 'ember-runtime', 'ember-debug', 'ember-metal', 'container', 'ember-application/system/engine-parent'], function (exports, _emberUtils, _emberRuntime, _emberDebug, _emberMetal, _container, _emberApplicationSystemEngineParent) { | |
/** | |
@module ember | |
@submodule ember-application | |
*/ | |
'use strict'; | |
var _EmberObject$extend; | |
var _templateObject = babelHelpers.taggedTemplateLiteralLoose(['-bucket-cache:main'], ['-bucket-cache:main']); | |
/** | |
The `EngineInstance` encapsulates all of the stateful aspects of a | |
running `Engine`. | |
@public | |
@class Ember.EngineInstance | |
@extends Ember.Object | |
@uses RegistryProxyMixin | |
@uses ContainerProxyMixin | |
*/ | |
var EngineInstance = _emberRuntime.Object.extend(_emberRuntime.RegistryProxyMixin, _emberRuntime.ContainerProxyMixin, (_EmberObject$extend = { | |
/** | |
The base `Engine` for which this is an instance. | |
@property {Ember.Engine} engine | |
@private | |
*/ | |
base: null, | |
init: function () { | |
this._super.apply(this, arguments); | |
_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; | |
}, | |
/** | |
Initialize the `Ember.EngineInstance` and return a promise that resolves | |
with the instance itself when the boot process is complete. | |
The primary task here is to run any registered instance initializers. | |
See the documentation on `BootOptions` for the options it takes. | |
@private | |
@method boot | |
@param options {Object} | |
@return {Promise<Ember.EngineInstance,Error>} | |
*/ | |
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; | |
}, | |
/** | |
Unfortunately, a lot of existing code assumes booting an instance is | |
synchronous – specifically, a lot of tests assume the last call to | |
`app.advanceReadiness()` or `app.reset()` will result in a new instance | |
being fully-booted when the current runloop completes. | |
We would like new code (like the `visit` API) to stop making this | |
assumption, so we created the asynchronous version above that returns a | |
promise. But until we have migrated all the code, we would have to expose | |
this method for use *internally* in places where we need to boot an instance | |
synchronously. | |
@private | |
*/ | |
_bootSync: function (options) { | |
if (this._booted) { | |
return this; | |
} | |
_emberDebug.assert('An engine instance\'s parent must be set via `setEngineParent(engine, parent)` prior to calling `engine.boot()`.', _emberApplicationSystemEngineParent.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 ? this.__container__.lookup('-environment:main') : arguments[0]; | |
this.constructor.setupRegistry(this.__registry__, options); | |
}, | |
/** | |
Unregister a factory. | |
Overrides `RegistryProxy#unregister` in order to clear any cached instances | |
of the unregistered factory. | |
@public | |
@method unregister | |
@param {String} fullName | |
*/ | |
unregister: function (fullName) { | |
this.__container__.reset(fullName); | |
this._super.apply(this, arguments); | |
}, | |
/** | |
@private | |
*/ | |
willDestroy: function () { | |
this._super.apply(this, arguments); | |
_emberMetal.run(this.__container__, 'destroy'); | |
}, | |
/** | |
Build a new `Ember.EngineInstance` that's a child of this instance. | |
Engines must be registered by name with their parent engine | |
(or application). | |
@private | |
@method buildChildEngineInstance | |
@param name {String} the registered name of the engine. | |
@param options {Object} options provided to the engine instance. | |
@return {Ember.EngineInstance,Error} | |
*/ | |
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); | |
_emberApplicationSystemEngineParent.setEngineParent(engineInstance, this); | |
return engineInstance; | |
}, | |
/** | |
Clone dependencies shared between an engine instance and its parent. | |
@private | |
@method cloneParentDependencies | |
*/ | |
cloneParentDependencies: function () { | |
var _this2 = this; | |
var parent = _emberApplicationSystemEngineParent.getEngineParent(this); | |
var registrations = ['route:basic', 'event_dispatcher:main', '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', _container.privatize(_templateObject), '-view-registry:main', 'renderer:-' + (env.isInteractive ? 'dom' : 'inert')]; | |
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'); | |
} | |
}, _EmberObject$extend[_container.FACTORY_FOR] = function (fullName, options) { | |
return this.__container__[_container.FACTORY_FOR](fullName, options); | |
}, _EmberObject$extend[_container.LOOKUP_FACTORY] = function (fullName, options) { | |
return this.__container__[_container.LOOKUP_FACTORY](fullName, options); | |
}, _EmberObject$extend)); | |
EngineInstance.reopenClass({ | |
/** | |
@private | |
@method setupRegistry | |
@param {Registry} registry | |
@param {BootOptions} options | |
*/ | |
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.getEngineParent = getEngineParent; | |
exports.setEngineParent = setEngineParent; | |
var ENGINE_PARENT = _emberUtils.symbol('ENGINE_PARENT'); | |
exports.ENGINE_PARENT = 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 | |
@public | |
*/ | |
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-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, _emberUtils, _emberRuntime, _container, _dagMap, _emberDebug, _emberMetal, _emberApplicationSystemResolver, _emberApplicationSystemEngineInstance, _emberRouting, _emberExtensionSupport, _emberViews, _emberGlimmer) { | |
/** | |
@module ember | |
@submodule ember-application | |
*/ | |
'use strict'; | |
var _templateObject = babelHelpers.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 | |
@namespace Ember | |
@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, | |
/** | |
Ensure that initializers are run once, and only once, per engine. | |
@private | |
@method ensureInitializers | |
*/ | |
ensureInitializers: function () { | |
if (!this._initializersRan) { | |
this.runInitializers(); | |
this._initializersRan = true; | |
} | |
}, | |
/** | |
Create an EngineInstance for this engine. | |
@private | |
@method buildInstance | |
@return {Ember.EngineInstance} the engine instance | |
*/ | |
buildInstance: function () { | |
var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; | |
this.ensureInitializers(); | |
options.base = this; | |
return _emberApplicationSystemEngineInstance.default.create(options); | |
}, | |
/** | |
Build and configure the registry for the current engine. | |
@private | |
@method buildRegistry | |
@return {Ember.Registry} the configured registry | |
*/ | |
buildRegistry: function () { | |
var registry = this.__registry__ = this.constructor.buildRegistry(this); | |
return registry; | |
}, | |
/** | |
@private | |
@method initializer | |
*/ | |
initializer: function (options) { | |
this.constructor.initializer(options); | |
}, | |
/** | |
@private | |
@method instanceInitializer | |
*/ | |
instanceInitializer: function (options) { | |
this.constructor.instanceInitializer(options); | |
}, | |
/** | |
@private | |
@method runInitializers | |
*/ | |
runInitializers: function () { | |
var _this = this; | |
this._runInitializer('initializers', function (name, initializer) { | |
_emberDebug.assert('No application initializer named \'' + name + '\'', !!initializer); | |
if (initializer.initialize.length === 2) { | |
_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: 'http://emberjs.com/deprecations/v2.x/#toc_initializer-arity' | |
}); | |
initializer.initialize(_this.__registry__, _this); | |
} else { | |
initializer.initialize(_this); | |
} | |
}); | |
}, | |
/** | |
@private | |
@since 1.12.0 | |
@method runInstanceInitializers | |
*/ | |
runInstanceInitializers: function (instance) { | |
this._runInitializer('instanceInitializers', function (name, initializer) { | |
_emberDebug.assert('No instance initializer named \'' + name + '\'', !!initializer); | |
initializer.initialize(instance); | |
}); | |
}, | |
_runInitializer: function (bucketName, cb) { | |
var initializersByName = _emberMetal.get(this.constructor, bucketName); | |
var initializers = props(initializersByName); | |
var graph = new _dagMap.default(); | |
var initializer = undefined; | |
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. | |
```javascript | |
Ember.Application.initializer({ | |
name: 'namedInitializer', | |
initialize: function(application) { | |
Ember.debug('Running namedInitializer!'); | |
} | |
}); | |
``` | |
* `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`: | |
```javascript | |
Ember.Application.initializer({ | |
name: 'first', | |
initialize: function(application) { | |
Ember.debug('First initializer!'); | |
} | |
}); | |
// DEBUG: First initializer! | |
``` | |
We add another initializer named `second`, specifying that it should run | |
after the initializer named `first`: | |
```javascript | |
Ember.Application.initializer({ | |
name: 'second', | |
after: 'first', | |
initialize: function(application) { | |
Ember.debug('Second initializer!'); | |
} | |
}); | |
// 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`: | |
```javascript | |
Ember.Application.initializer({ | |
name: 'pre', | |
before: 'first', | |
initialize: function(application) { | |
Ember.debug('Pre initializer!'); | |
} | |
}); | |
// 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: | |
```javascript | |
Ember.Application.initializer({ | |
name: 'post', | |
after: ['first', 'second'], | |
initialize: function(application) { | |
Ember.debug('Post initializer!'); | |
} | |
}); | |
// 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: | |
```javascript | |
Ember.Application.initializer({ | |
name: 'api-adapter', | |
initialize: function(application) { | |
application.register('api-adapter:main', ApiAdapter); | |
} | |
}); | |
``` | |
@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. | |
```javascript | |
Ember.Application.instanceInitializer({ | |
name: 'namedinstanceInitializer', | |
initialize: function(application) { | |
Ember.debug('Running namedInitializer!'); | |
} | |
}); | |
``` | |
* `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. | |
```javascript | |
Ember.Application.initializer({ | |
name: 'preload-data', | |
initialize: function(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 = Ember.$('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); | |
} | |
}); | |
``` | |
@method instanceInitializer | |
@param instanceInitializer | |
@public | |
*/ | |
instanceInitializer: buildInitializerMethod('instanceInitializers', 'instance initializer'), | |
/** | |
This creates a registry with the default Ember naming conventions. | |
It also configures the registry: | |
* registered views are created every time they are looked up (they are | |
not singletons) | |
* registered templates are not factories; the registered value is | |
returned directly. | |
* the router receives the application as its `namespace` property | |
* all controllers receive the router as their `target` and `controllers` | |
properties | |
* all controllers receive the application as their `namespace` property | |
* the application view receives the application controller as its | |
`controller` property | |
* the application view receives the application template as its | |
`defaultTemplate` property | |
@method buildRegistry | |
@static | |
@param {Ember.Application} namespace the application for which to | |
build the registry | |
@return {Ember.Registry} the built registry | |
@private | |
*/ | |
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); | |
_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') || _emberApplicationSystemResolver.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); | |
} | |
_emberDebug.assert('The ' + humanName + ' \'' + initializer.name + '\' has already been registered', !this[bucketName][initializer.name]); | |
_emberDebug.assert('An ' + humanName + ' cannot be registered without an initialize function', _emberUtils.canInvoke(initializer, 'initialize')); | |
_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', _container.privatize(_templateObject)); | |
registry.injection('route', '_bucketCache', _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, _emberApplicationUtilsValidateType, _emberGlimmer) { | |
/** | |
@module ember | |
@submodule ember-application | |
*/ | |
'use strict'; | |
var 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 | |
}); | |
exports.Resolver = Resolver; | |
/** | |
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: | |
```javascript | |
App = Ember.Application.create({ | |
Resolver: Ember.DefaultResolver.extend({ | |
resolveTemplate: function(parsedName) { | |
let resolvedTemplate = this._super(parsedName); | |
if (resolvedTemplate) { return resolvedTemplate; } | |
return Ember.TEMPLATES['not_found']; | |
} | |
}) | |
}); | |
``` | |
Some examples of how names are resolved: | |
``` | |
'template:post' //=> Ember.TEMPLATES['post'] | |
'template:posts/byline' //=> Ember.TEMPLATES['posts/byline'] | |
'template:posts.byline' //=> Ember.TEMPLATES['posts/byline'] | |
'template:blogPost' //=> Ember.TEMPLATES['blogPost'] | |
// OR | |
// Ember.TEMPLATES['blog_post'] | |
'controller:post' //=> App.PostController | |
'controller:posts.index' //=> App.PostsIndexController | |
'controller:blog/post' //=> Blog.PostController | |
'controller:basic' //=> Ember.Controller | |
'route:post' //=> App.PostRoute | |
'route:posts.index' //=> App.PostsIndexRoute | |
'route:blog/post' //=> Blog.PostRoute | |
'route:basic' //=> Ember.Route | |
'view:post' //=> App.PostView | |
'view:posts.index' //=> App.PostsIndexView | |
'view:blog/post' //=> Blog.PostView | |
'view:basic' //=> Ember.View | |
'foo:post' //=> App.PostFoo | |
'model:post' //=> App.Post | |
``` | |
@class DefaultResolver | |
@namespace Ember | |
@extends Ember.Object | |
@public | |
*/ | |
exports.default = _emberRuntime.Object.extend({ | |
/** | |
This will be set to the Application instance when it is | |
created. | |
@property namespace | |
@public | |
*/ | |
namespace: null, | |
init: function () { | |
this._parseNameCache = _emberUtils.dictionary(null); | |
}, | |
normalize: function (fullName) { | |
var _fullName$split = fullName.split(':', 2); | |
var type = _fullName$split[0]; | |
var name = _fullName$split[1]; | |
_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; | |
if (result.indexOf('.') > -1) { | |
result = result.replace(/\.(.)/g, function (m) { | |
return m.charAt(1).toUpperCase(); | |
}); | |
} | |
if (name.indexOf('_') > -1) { | |
result = result.replace(/_(.)/g, function (m) { | |
return m.charAt(1).toUpperCase(); | |
}); | |
} | |
if (name.indexOf('-') > -1) { | |
result = result.replace(/-(.)/g, function (m) { | |
return m.charAt(1).toUpperCase(); | |
}); | |
} | |
return type + ':' + result; | |
} else { | |
return fullName; | |
} | |
}, | |
/** | |
This method is called via the container's resolver method. | |
It parses the provided `fullName` and then looks up and | |
returns the appropriate template or class. | |
@method resolve | |
@param {String} fullName the lookup string | |
@return {Object} the resolved factory | |
@public | |
*/ | |
resolve: function (fullName) { | |
var _this = this; | |
var parsedName = this.parseName(fullName); | |
var resolveMethodName = parsedName.resolveMethodName; | |
var resolved = undefined; | |
if (this[resolveMethodName]) { | |
resolved = this[resolveMethodName](parsedName); | |
} | |
resolved = resolved || this.resolveOther(parsedName); | |
_emberDebug.runInDebug(function () { | |
if (parsedName.root && parsedName.root.LOG_RESOLVER) { | |
_this._logLookup(resolved, parsedName); | |
} | |
}); | |
if (resolved) { | |
_emberApplicationUtilsValidateType.default(resolved, parsedName); | |
} | |
return resolved; | |
}, | |
/** | |
Convert the string name of the form 'type:name' to | |
a Javascript object with the parsed aspects of the name | |
broken out. | |
@param {String} fullName the lookup string | |
@method parseName | |
@protected | |
*/ | |
parseName: function (fullName) { | |
return this._parseNameCache[fullName] || (this._parseNameCache[fullName] = this._parseName(fullName)); | |
}, | |
_parseName: function (fullName) { | |
var _fullName$split2 = fullName.split(':'); | |
var type = _fullName$split2[0]; | |
var fullNameWithoutType = _fullName$split2[1]; | |
var name = fullNameWithoutType; | |
var namespace = _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); | |
_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 | |
}; | |
}, | |
/** | |
Returns a human-readable description for a fullName. Used by the | |
Application namespace in assertions to describe the | |
precise name of the class that Ember is looking for, rather than | |
container keys. | |
@param {String} fullName the lookup string | |
@method lookupDescription | |
@protected | |
*/ | |
lookupDescription: function (fullName) { | |
var parsedName = this.parseName(fullName); | |
var description = undefined; | |
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(); | |
}, | |
/** | |
Given a parseName object (output from `parseName`), apply | |
the conventions expected by `Ember.Router` | |
@param {Object} parsedName a parseName object with the parsed | |
fullName lookup string | |
@method useRouterNaming | |
@protected | |
*/ | |
useRouterNaming: function (parsedName) { | |
parsedName.name = parsedName.name.replace(/\./g, '_'); | |
if (parsedName.name === 'basic') { | |
parsedName.name = ''; | |
} | |
}, | |
/** | |
Look up the template in Ember.TEMPLATES | |
@param {Object} parsedName a parseName object with the parsed | |
fullName lookup string | |
@method resolveTemplate | |
@protected | |
*/ | |
resolveTemplate: function (parsedName) { | |
var templateName = parsedName.fullNameWithoutType.replace(/\./g, '/'); | |
return _emberGlimmer.getTemplate(templateName) || _emberGlimmer.getTemplate(_emberRuntime.String.decamelize(templateName)); | |
}, | |
/** | |
Lookup the view using `resolveOther` | |
@param {Object} parsedName a parseName object with the parsed | |
fullName lookup string | |
@method resolveView | |
@protected | |
*/ | |
resolveView: function (parsedName) { | |
this.useRouterNaming(parsedName); | |
return this.resolveOther(parsedName); | |
}, | |
/** | |
Lookup the controller using `resolveOther` | |
@param {Object} parsedName a parseName object with the parsed | |
fullName lookup string | |
@method resolveController | |
@protected | |
*/ | |
resolveController: function (parsedName) { | |
this.useRouterNaming(parsedName); | |
return this.resolveOther(parsedName); | |
}, | |
/** | |
Lookup the route using `resolveOther` | |
@param {Object} parsedName a parseName object with the parsed | |
fullName lookup string | |
@method resolveRoute | |
@protected | |
*/ | |
resolveRoute: function (parsedName) { | |
this.useRouterNaming(parsedName); | |
return this.resolveOther(parsedName); | |
}, | |
/** | |
Lookup the model on the Application namespace | |
@param {Object} parsedName a parseName object with the parsed | |
fullName lookup string | |
@method resolveModel | |
@protected | |
*/ | |
resolveModel: function (parsedName) { | |
var className = _emberRuntime.String.classify(parsedName.name); | |
var factory = _emberMetal.get(parsedName.root, className); | |
return factory; | |
}, | |
/** | |
Look up the specified object (from parsedName) on the appropriate | |
namespace (usually on the Application) | |
@param {Object} parsedName a parseName object with the parsed | |
fullName lookup string | |
@method resolveHelper | |
@protected | |
*/ | |
resolveHelper: function (parsedName) { | |
return this.resolveOther(parsedName); | |
}, | |
/** | |
Look up the specified object (from parsedName) on the appropriate | |
namespace (usually on the Application) | |
@param {Object} parsedName a parseName object with the parsed | |
fullName lookup string | |
@method resolveOther | |
@protected | |
*/ | |
resolveOther: function (parsedName) { | |
var className = _emberRuntime.String.classify(parsedName.name) + _emberRuntime.String.classify(parsedName.type); | |
var factory = _emberMetal.get(parsedName.root, className); | |
return factory; | |
}, | |
resolveMain: function (parsedName) { | |
var className = _emberRuntime.String.classify(parsedName.type); | |
return _emberMetal.get(parsedName.root, className); | |
}, | |
/** | |
@method _logLookup | |
@param {Boolean} found | |
@param {Object} parsedName | |
@private | |
*/ | |
_logLookup: function (found, parsedName) { | |
var symbol = undefined, | |
padding = undefined; | |
if (found) { | |
symbol = '[✓]'; | |
} else { | |
symbol = '[ ]'; | |
} | |
if (parsedName.fullName.length > 60) { | |
padding = '.'; | |
} else { | |
padding = new Array(60 - parsedName.fullName.length).join('.'); | |
} | |
_emberDebug.info(symbol, parsedName.fullName, padding, this.lookupDescription(parsedName.fullName)); | |
}, | |
/** | |
Used to iterate all items of a given type. | |
@method knownForType | |
@param {String} type the type to search for | |
@private | |
*/ | |
knownForType: function (type) { | |
var namespace = _emberMetal.get(this, 'namespace'); | |
var suffix = _emberRuntime.String.classify(type); | |
var typeRegexp = new RegExp(suffix + '$'); | |
var known = _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; | |
}, | |
/** | |
Converts provided name from the backing namespace into a container lookup name. | |
Examples: | |
App.FooBarHelper -> helper:foo-bar | |
App.THelper -> helper:t | |
@method translateToContainerFullname | |
@param {String} type | |
@param {String} name | |
@private | |
*/ | |
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; | |
} | |
}); | |
}); | |
enifed('ember-application/utils/validate-type', ['exports', 'ember-debug'], function (exports, _emberDebug) { | |
/** | |
@module ember | |
@submodule ember-application | |
*/ | |
'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]; | |
var factoryFlag = validationAttributes[1]; | |
var expectedType = validationAttributes[2]; | |
if (action === 'deprecate') { | |
_emberDebug.deprecate('In Ember 2.0 ' + parsedName.type + ' factories must have an `' + factoryFlag + '` ' + ('property set to true. You registered ' + resolvedType + ' as a ' + parsedName.type + ' ') + ('factory. Either add the `' + factoryFlag + '` property to this factory or ') + ('extend from ' + expectedType + '.'), !!resolvedType[factoryFlag], { id: 'ember-application.validate-type', until: '3.0.0' }); | |
} else { | |
_emberDebug.assert('Expected ' + parsedName.fullName + ' to resolve to an ' + expectedType + ' but ' + ('instead it was ' + resolvedType + '.'), !!resolvedType[factoryFlag]); | |
} | |
} | |
}); | |
enifed('ember-console/index', ['exports', 'ember-environment'], function (exports, _emberEnvironment) { | |
'use strict'; | |
function K() {} | |
function consoleMethod(name) { | |
var consoleObj = undefined; | |
if (_emberEnvironment.context.imports.console) { | |
consoleObj = _emberEnvironment.context.imports.console; | |
} else if (typeof console !== 'undefined') { | |
consoleObj = console; | |
} | |
var method = typeof consoleObj === 'object' ? consoleObj[name] : null; | |
if (typeof method !== 'function') { | |
return; | |
} | |
if (typeof method.bind === 'function') { | |
return method.bind(consoleObj); | |
} | |
return function () { | |
method.apply(consoleObj, arguments); | |
}; | |
} | |
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 | |
*/ | |
exports.default = { | |
/** | |
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 | |
}; | |
}); | |
enifed('ember-debug/deprecate', ['exports', 'ember-debug/error', 'ember-console', 'ember-environment', 'ember-debug/handlers'], function (exports, _emberDebugError, _emberConsole, _emberEnvironment, _emberDebugHandlers) { | |
/*global __fail__*/ | |
'use strict'; | |
exports.registerHandler = registerHandler; | |
exports.default = deprecate; | |
/** | |
Allows for runtime registration of handler functions that override the default deprecation behavior. | |
Deprecations are invoked by calls to [Ember.deprecate](http://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 | |
@param handler {Function} A function to handle deprecation calls. | |
@since 2.1.0 | |
*/ | |
function registerHandler(handler) { | |
_emberDebugHandlers.registerHandler('deprecate', handler); | |
} | |
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 = undefined; | |
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 = undefined; | |
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 _emberDebugError.default(updatedMessage); | |
} else { | |
next.apply(undefined, arguments); | |
} | |
}); | |
var missingOptionsDeprecation = 'When calling `Ember.deprecate` you ' + 'must provide an `options` hash as the third parameter. ' + '`options` should include `id` and `until` properties.'; | |
exports.missingOptionsDeprecation = missingOptionsDeprecation; | |
var missingOptionsIdDeprecation = 'When calling `Ember.deprecate` you must provide `id` in options.'; | |
exports.missingOptionsIdDeprecation = missingOptionsIdDeprecation; | |
var missingOptionsUntilDeprecation = 'When calling `Ember.deprecate` you must provide `until` in options.'; | |
exports.missingOptionsUntilDeprecation = missingOptionsUntilDeprecation; | |
/** | |
@module ember | |
@submodule ember-debug | |
*/ | |
/** | |
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 | |
@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. | |
@for Ember | |
@public | |
@since 1.0.0 | |
*/ | |
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: 'http://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: 'http://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: 'http://emberjs.com/deprecations/v2.x/#toc_ember-debug-function-options' | |
}); | |
} | |
_emberDebugHandlers.invoke.apply(undefined, ['deprecate'].concat(babelHelpers.slice.call(arguments))); | |
} | |
}); | |
enifed("ember-debug/error", ["exports"], function (exports) { | |
/** | |
A subclass of the JavaScript Error object for use in Ember. | |
@class Error | |
@namespace Ember | |
@extends Error | |
@constructor | |
@public | |
*/ | |
"use strict"; | |
var EmberError = (function (_Error) { | |
babelHelpers.inherits(EmberError, _Error); | |
function EmberError(message) { | |
babelHelpers.classCallCheck(this, EmberError); | |
_Error.call(this); | |
if (!(this instanceof EmberError)) { | |
return new EmberError(message); | |
} | |
var error = Error.call(this, message); | |
if (Error.captureStackTrace) { | |
Error.captureStackTrace(this, EmberError); | |
} else { | |
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 EmberError; | |
})(Error); | |
exports.default = EmberError; | |
}); | |
enifed('ember-debug/features', ['exports', 'ember-utils', 'ember-environment', 'ember/features'], function (exports, _emberUtils, _emberEnvironment, _emberFeatures) { | |
'use strict'; | |
exports.default = isEnabled; | |
/** | |
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 | |
*/ | |
var FEATURES = _emberUtils.assign(_emberFeatures.default, _emberEnvironment.ENV.FEATURES); | |
exports.FEATURES = FEATURES; | |
/** | |
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; | |
} | |
} | |
exports.DEFAULT_FEATURES = _emberFeatures.default; | |
}); | |
enifed("ember-debug/handlers", ["exports"], function (exports) { | |
"use strict"; | |
exports.registerHandler = registerHandler; | |
exports.invoke = invoke; | |
var HANDLERS = {}; | |
exports.HANDLERS = HANDLERS; | |
function registerHandler(type, callback) { | |
var nextHandler = HANDLERS[type] || function () {}; | |
HANDLERS[type] = function (message, options) { | |
callback(message, options, nextHandler); | |
}; | |
} | |
function invoke(type, message, test, options) { | |
if (test) { | |
return; | |
} | |
var handlerForType = HANDLERS[type]; | |
if (!handlerForType) { | |
return; | |
} | |
if (handlerForType) { | |
handlerForType(message, options); | |
} | |
} | |
}); | |
enifed('ember-debug/index', ['exports', 'ember/features', 'ember-environment', 'ember-console', 'ember-debug/testing', 'ember-debug/error', 'ember-debug/features', 'ember-debug/deprecate', 'ember-debug/warn'], function (exports, _emberFeatures, _emberEnvironment, _emberConsole, _emberDebugTesting, _emberDebugError, _emberDebugFeatures, _emberDebugDeprecate, _emberDebugWarn) { | |
'use strict'; | |
exports._warnIfUsingStrippedFeatureFlags = _warnIfUsingStrippedFeatureFlags; | |
exports.getDebugFunction = getDebugFunction; | |
exports.setDebugFunction = setDebugFunction; | |
exports.assert = assert; | |
exports.info = info; | |
exports.warn = warn; | |
exports.debug = debug; | |
exports.deprecate = deprecate; | |
exports.deprecateFunc = deprecateFunc; | |
exports.runInDebug = runInDebug; | |
exports.debugSeal = debugSeal; | |
exports.debugFreeze = debugFreeze; | |
exports.registerWarnHandler = _emberDebugWarn.registerHandler; | |
exports.registerDeprecationHandler = _emberDebugDeprecate.registerHandler; | |
exports.isFeatureEnabled = _emberDebugFeatures.default; | |
exports.FEATURES = _emberDebugFeatures.FEATURES; | |
exports.Error = _emberDebugError.default; | |
exports.isTesting = _emberDebugTesting.isTesting; | |
exports.setTesting = _emberDebugTesting.setTesting; | |
var debugFunctions = { | |
assert: function () {}, | |
info: function () {}, | |
warn: function () {}, | |
debug: function () {}, | |
deprecate: function () {}, | |
deprecateFunc: function () { | |
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { | |
args[_key] = arguments[_key]; | |
} | |
return args[args.length - 1]; | |
}, | |
runInDebug: function () {}, | |
debugSeal: function () {}, | |
debugFreeze: function () {} | |
}; | |
exports.debugFunctions = debugFunctions; | |
/** | |
@module ember | |
@submodule ember-debug | |
*/ | |
/** | |
@class Ember | |
@public | |
*/ | |
/** | |
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 | |
// Test for truthiness | |
Ember.assert('Must pass a valid object', obj); | |
// Fail unconditionally | |
Ember.assert('This code path should never be run'); | |
``` | |
@method assert | |
@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 _emberDebugError.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 | |
Ember.debug('I\'m a debug notice!'); | |
``` | |
@method debug | |
@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); | |
}); | |
/** | |
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 | |
@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 _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { | |
args[_key2] = arguments[_key2]; | |
} | |
if (args.length === 3) { | |
var _ret = (function () { | |
var message = args[0]; | |
var options = args[1]; | |
var func = args[2]; | |
return { | |
v: function () { | |
deprecate(message, false, options); | |
return func.apply(this, arguments); | |
} | |
}; | |
})(); | |
if (typeof _ret === 'object') return _ret.v; | |
} else { | |
var _ret2 = (function () { | |
var message = args[0]; | |
var func = args[1]; | |
return { | |
v: function () { | |
deprecate(message); | |
return func.apply(this, arguments); | |
} | |
}; | |
})(); | |
if (typeof _ret2 === 'object') return _ret2.v; | |
} | |
}); | |
/** | |
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 | |
Ember.runInDebug(() => { | |
Ember.Component.reopen({ | |
didInsertElement() { | |
console.log("I'm happy"); | |
} | |
}); | |
}); | |
``` | |
@method runInDebug | |
@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', _emberDebugDeprecate.default); | |
setDebugFunction('warn', _emberDebugWarn.default); | |
/** | |
Will call `Ember.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} | |
*/ | |
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' }); | |
} | |
} | |
} | |
if (!_emberDebugTesting.isTesting()) { | |
(function () { | |
// Complain if they're using FEATURE flags in builds other than canary | |
_emberDebugFeatures.FEATURES['features-stripped-test'] = true; | |
var featuresWereStripped = true; | |
if (false) { | |
featuresWereStripped = false; | |
} | |
delete _emberDebugFeatures.FEATURES['features-stripped-test']; | |
_warnIfUsingStrippedFeatureFlags(_emberEnvironment.ENV.FEATURES, _emberFeatures.default, 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 = undefined; | |
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); | |
} | |
})(); | |
} | |
/* | |
We are transitioning away from `ember.js` to `ember.debug.js` to make | |
it much clearer that it is only for local development purposes. | |
This flag value is changed by the tooling (by a simple string replacement) | |
so that if `ember.js` (which must be output for backwards compat reasons) is | |
used a nice helpful warning message will be printed out. | |
*/ | |
var runningNonEmberDebugJS = false; | |
exports.runningNonEmberDebugJS = runningNonEmberDebugJS; | |
if (runningNonEmberDebugJS) { | |
warn('Please use `ember.debug.js` instead of `ember.js` for development and debugging.'); | |
} | |
function getDebugFunction(name) { | |
return debugFunctions[name]; | |
} | |
function setDebugFunction(name, fn) { | |
debugFunctions[name] = fn; | |
} | |
function assert() { | |
return debugFunctions.assert.apply(undefined, arguments); | |
} | |
function info() { | |
return debugFunctions.info.apply(undefined, arguments); | |
} | |
function warn() { | |
return debugFunctions.warn.apply(undefined, arguments); | |
} | |
function debug() { | |
return debugFunctions.debug.apply(undefined, arguments); | |
} | |
function deprecate() { | |
return debugFunctions.deprecate.apply(undefined, arguments); | |
} | |
function deprecateFunc() { | |
return debugFunctions.deprecateFunc.apply(undefined, arguments); | |
} | |
function runInDebug() { | |
return debugFunctions.runInDebug.apply(undefined, arguments); | |
} | |
function debugSeal() { | |
return debugFunctions.debugSeal.apply(undefined, arguments); | |
} | |
function debugFreeze() { | |
return debugFunctions.debugFreeze.apply(undefined, arguments); | |
} | |
}); | |
enifed("ember-debug/run-in-debug", ["exports"], function (exports) { | |
"use strict"; | |
}); | |
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, _emberDebugDeprecate, _emberDebugHandlers) { | |
'use strict'; | |
exports.registerHandler = registerHandler; | |
exports.default = warn; | |
/** | |
Allows for runtime registration of handler functions that override the default warning behavior. | |
Warnings are invoked by calls made to [Ember.warn](http://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 | |
// next is not called, so no warnings get the default behavior | |
Ember.Debug.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 | |
@param handler {Function} A function to handle warnings. | |
@since 2.1.0 | |
*/ | |
function registerHandler(handler) { | |
_emberDebugHandlers.registerHandler('warn', handler); | |
} | |
registerHandler(function logWarning(message, options) { | |
_emberConsole.default.warn('WARNING: ' + message); | |
if ('trace' in _emberConsole.default) { | |
_emberConsole.default.trace(); | |
} | |
}); | |
var missingOptionsDeprecation = 'When calling `Ember.warn` you ' + 'must provide an `options` hash as the third parameter. ' + '`options` should include an `id` property.'; | |
exports.missingOptionsDeprecation = missingOptionsDeprecation; | |
var missingOptionsIdDeprecation = 'When calling `Ember.warn` you must provide `id` in options.'; | |
exports.missingOptionsIdDeprecation = missingOptionsIdDeprecation; | |
/** | |
@module ember | |
@submodule ember-debug | |
*/ | |
/** | |
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 | |
@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" | |
@for Ember | |
@public | |
@since 1.0.0 | |
*/ | |
function warn(message, test, options) { | |
if (arguments.length === 2 && typeof test === 'object') { | |
options = test; | |
test = false; | |
} | |
if (!options) { | |
_emberDebugDeprecate.default(missingOptionsDeprecation, false, { | |
id: 'ember-debug.warn-options-missing', | |
until: '3.0.0', | |
url: 'http://emberjs.com/deprecations/v2.x/#toc_ember-debug-function-options' | |
}); | |
} | |
if (options && !options.id) { | |
_emberDebugDeprecate.default(missingOptionsIdDeprecation, false, { | |
id: 'ember-debug.warn-id-missing', | |
until: '3.0.0', | |
url: 'http://emberjs.com/deprecations/v2.x/#toc_ember-debug-function-options' | |
}); | |
} | |
_emberDebugHandlers.invoke('warn', message, test, options); | |
} | |
}); | |
enifed('ember-environment/global', ['exports'], function (exports) { | |
/* globals global, window, self, mainContext */ | |
// from lodash to catch fake globals | |
'use strict'; | |
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 | |
exports.default = 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 | |
}); | |
enifed('ember-environment/index', ['exports', 'ember-environment/global', 'ember-environment/utils'], function (exports, _emberEnvironmentGlobal, _emberEnvironmentUtils) { | |
/* globals module */ | |
'use strict'; | |
/** | |
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 _emberEnvironmentGlobal.default.EmberENV === 'object' && _emberEnvironmentGlobal.default.EmberENV || typeof _emberEnvironmentGlobal.default.ENV === 'object' && _emberEnvironmentGlobal.default.ENV || {}; | |
exports.ENV = 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 = _emberEnvironmentUtils.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 = _emberEnvironmentUtils.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 = _emberEnvironmentUtils.defaultTrue(ENV.LOG_VERSION); | |
// default false | |
ENV.MODEL_FACTORY_INJECTIONS = _emberEnvironmentUtils.defaultFalse(ENV.MODEL_FACTORY_INJECTIONS); | |
/** | |
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 = _emberEnvironmentUtils.defaultFalse(ENV.LOG_BINDINGS); | |
ENV.RAISE_ON_DEPRECATION = _emberEnvironmentUtils.defaultFalse(ENV.RAISE_ON_DEPRECATION); | |
// check if window exists and actually is the global | |
var hasDOM = typeof window !== 'undefined' && window === _emberEnvironmentGlobal.default && window.document && window.document.createElement && !ENV.disableBrowserEnvironment; // is this a public thing? | |
// legacy imports/exports/lookup stuff (should we keep this??) | |
var originalContext = _emberEnvironmentGlobal.default.Ember || {}; | |
var context = { | |
// import jQuery | |
imports: originalContext.imports || _emberEnvironmentGlobal.default, | |
// export Ember | |
exports: originalContext.exports || _emberEnvironmentGlobal.default, | |
// search for Namespaces | |
lookup: originalContext.lookup || _emberEnvironmentGlobal.default | |
}; | |
exports.context = context; | |
// 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.environment = environment; | |
}); | |
enifed("ember-environment/utils", ["exports"], function (exports) { | |
"use strict"; | |
exports.defaultTrue = defaultTrue; | |
exports.defaultFalse = defaultFalse; | |
exports.normalizeExtendPrototypes = normalizeExtendPrototypes; | |
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) | |
}; | |
} | |
} | |
}); | |
enifed('ember-extension-support/container_debug_adapter', ['exports', 'ember-metal', 'ember-runtime'], function (exports, _emberMetal, _emberRuntime) { | |
'use strict'; | |
/** | |
@module ember | |
@submodule ember-extension-support | |
*/ | |
/** | |
The `ContainerDebugAdapter` helps the container and resolver interface | |
with tools that debug Ember such as the | |
[Ember Inspector](https://github.com/emberjs/ember-inspector) | |
for Chrome and Firefox. | |
This class can be extended by a custom resolver implementer | |
to override some of the methods with library-specific code. | |
The methods likely to be overridden are: | |
* `canCatalogEntriesByType` | |
* `catalogEntriesByType` | |
The adapter will need to be registered | |
in the application's container as `container-debug-adapter:main`. | |
Example: | |
```javascript | |
Application.initializer({ | |
name: "containerDebugAdapter", | |
initialize(application) { | |
application.register('container-debug-adapter:main', require('app/container-debug-adapter')); | |
} | |
}); | |
``` | |
@class ContainerDebugAdapter | |
@namespace Ember | |
@extends Ember.Object | |
@since 1.5.0 | |
@public | |
*/ | |
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 = _emberRuntime.A(_emberRuntime.Namespace.NAMESPACES); | |
var types = _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 (_emberRuntime.typeOf(klass) === 'class') { | |
types.push(_emberRuntime.String.dasherize(key.replace(typeSuffixRegex, ''))); | |
} | |
} | |
} | |
} | |
}); | |
return types; | |
} | |
}); | |
}); | |
// Ember as namespace | |
enifed('ember-extension-support/data_adapter', ['exports', 'ember-utils', 'ember-metal', 'ember-runtime', 'container', 'ember-application'], function (exports, _emberUtils, _emberMetal, _emberRuntime, _container, _emberApplication) { | |
'use strict'; | |
/** | |
@module ember | |
@submodule ember-extension-support | |
*/ | |
/** | |
The `DataAdapter` helps a data persistence library | |
interface with tools that debug Ember such | |
as the [Ember Extension](https://github.com/tildeio/ember-extension) | |
for Chrome and Firefox. | |
This class will be extended by a persistence library | |
which will override some of the methods with | |
library-specific code. | |
The methods likely to be overridden are: | |
* `getFilters` | |
* `detect` | |
* `columnsForType` | |
* `getRecords` | |
* `getRecordColumnValues` | |
* `getRecordKeywords` | |
* `getRecordFilterValues` | |
* `getRecordColor` | |
* `observeRecord` | |
The adapter will need to be registered | |
in the application's container as `dataAdapter:main`. | |
Example: | |
```javascript | |
Application.initializer({ | |
name: "data-adapter", | |
initialize: function(application) { | |
application.register('data-adapter:main', DS.DataAdapter); | |
} | |
}); | |
``` | |
@class DataAdapter | |
@namespace Ember | |
@extends EmberObject | |
@public | |
*/ | |
exports.default = _emberRuntime.Object.extend({ | |
init: function () { | |
this._super.apply(this, arguments); | |
this.releaseMethods = _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: _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 _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 = _emberRuntime.A(); | |
var typesToSend = undefined; | |
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 = _emberUtils.getOwner(this); | |
var Factory = owner[_container.FACTORY_FOR]('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 = _emberRuntime.A(); | |
var klass = this._nameToClass(modelName); | |
var records = this.getRecords(klass, modelName); | |
var release = undefined; | |
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 = _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; | |
} }; | |
_emberRuntime.addArrayObserver(records, this, observer); | |
release = function () { | |
releaseMethods.forEach(function (fn) { | |
return fn(); | |
}); | |
_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 _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 () { | |
_emberMetal.run.scheduleOnce('actions', this, onChange); | |
}, | |
willChange: function () { | |
return this; | |
} | |
}; | |
_emberRuntime.addArrayObserver(records, this, observer); | |
var release = function () { | |
return _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 = undefined; | |
typeToSend = { | |
name: name, | |
count: _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 = undefined; | |
if (containerDebugAdapter.canCatalogEntriesByType('model')) { | |
types = containerDebugAdapter.catalogEntriesByType('model'); | |
} else { | |
types = this._getObjectsOnNamespaces(); | |
} | |
// New adapters return strings instead of classes. | |
types = _emberRuntime.A(types).map(function (name) { | |
return { | |
klass: _this4._nameToClass(name), | |
name: name | |
}; | |
}); | |
types = _emberRuntime.A(types).filter(function (type) { | |
return _this4.detect(type.klass); | |
}); | |
return _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 = _emberRuntime.A(_emberRuntime.Namespace.NAMESPACES); | |
var types = _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 | |
// (especially when `EmberENV.MODEL_FACTORY_INJECTIONS` is `true`) | |
if (!_this5.detect(namespace[key])) { | |
continue; | |
} | |
var _name = _emberRuntime.String.dasherize(key); | |
if (!(namespace instanceof _emberApplication.Application) && namespace.toString()) { | |
_name = namespace + '/' + _name; | |
} | |
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 _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 _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, _emberExtensionSupportData_adapter, _emberExtensionSupportContainer_debug_adapter) { | |
/** | |
@module ember | |
@submodule ember-extension-support | |
*/ | |
'use strict'; | |
exports.DataAdapter = _emberExtensionSupportData_adapter.default; | |
exports.ContainerDebugAdapter = _emberExtensionSupportContainer_debug_adapter.default; | |
}); | |
enifed('ember-glimmer/component', ['exports', 'ember-utils', 'ember-views', 'ember-runtime', 'ember-debug', 'ember-metal', 'ember-glimmer/utils/references', '@glimmer/reference', '@glimmer/runtime'], function (exports, _emberUtils, _emberViews, _emberRuntime, _emberDebug, _emberMetal, _emberGlimmerUtilsReferences, _glimmerReference, _glimmerRuntime) { | |
'use strict'; | |
var _CoreView$extend; | |
var DIRTY_TAG = _emberUtils.symbol('DIRTY_TAG'); | |
exports.DIRTY_TAG = DIRTY_TAG; | |
var ARGS = _emberUtils.symbol('ARGS'); | |
exports.ARGS = ARGS; | |
var ROOT_REF = _emberUtils.symbol('ROOT_REF'); | |
exports.ROOT_REF = ROOT_REF; | |
var IS_DISPATCHING_ATTRS = _emberUtils.symbol('IS_DISPATCHING_ATTRS'); | |
exports.IS_DISPATCHING_ATTRS = IS_DISPATCHING_ATTRS; | |
var HAS_BLOCK = _emberUtils.symbol('HAS_BLOCK'); | |
exports.HAS_BLOCK = HAS_BLOCK; | |
var BOUNDS = _emberUtils.symbol('BOUNDS'); | |
exports.BOUNDS = BOUNDS; | |
/** | |
@module ember | |
@submodule ember-glimmer | |
*/ | |
/** | |
An `Ember.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 an `Ember.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 `Ember.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 Ember from 'ember'; | |
export default Ember.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 Ember from 'ember'; | |
export default Ember.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 Ember from 'ember'; | |
export default Ember.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 Ember from 'ember'; | |
export default Ember.Component.extend({ | |
classNameBindings: ['propertyA', 'propertyB'], | |
propertyA: 'from-a', | |
propertyB: Ember.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 Ember from 'ember'; | |
export default Ember.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 Ember from 'ember'; | |
export default Ember.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 Ember from 'ember'; | |
export default Ember.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 Ember from 'ember'; | |
export default Ember.Component.extend({ | |
classNameBindings: ['messages.empty'], | |
messages: Ember.Object.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 Ember from 'ember'; | |
export default Ember.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 Ember from 'ember'; | |
// Applies no class when isEnabled is true and class 'disabled' when isEnabled is false | |
export default Ember.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 | |
[Ember.Object](/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 Ember from 'ember'; | |
export default Ember.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 Ember from 'ember'; | |
export default Ember.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 Ember from 'ember'; | |
export default Ember.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 Ember from 'ember'; | |
export default Ember.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 Ember from 'ember'; | |
export default Ember.Component.extend({ | |
tagName: 'input', | |
attributeBindings: ['disabled'], | |
disabled: Ember.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 Ember from 'ember'; | |
export default Ember.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 [Ember.Object](/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. | |
## 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 Ember from 'ember'; | |
export default Ember.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 | |
@namespace Ember | |
@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 _glimmerReference.DirtyableTag(); | |
this[ROOT_REF] = new _emberGlimmerUtilsReferences.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) { | |
_emberDebug.deprecate('Specifying `defaultLayout` to ' + this + ' is deprecated. Please use `layout` instead.', false, { | |
id: 'ember-views.component.defaultLayout', | |
until: '3.0.0', | |
url: 'http://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 | |
_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 = _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; // indicate that the assertion should be triggered | |
} | |
} | |
})()); | |
_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 = undefined, | |
reference = undefined; | |
if ((args = this[ARGS]) && (reference = args[key])) { | |
if (reference[_emberGlimmerUtilsReferences.UPDATE]) { | |
reference[_emberGlimmerUtilsReferences.UPDATE](_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 = _emberViews.getViewElement(this); | |
return _glimmerRuntime.readDOMAttr(element, name); | |
}, _CoreView$extend)); | |
/** | |
The WAI-ARIA role of the control represented by this view. For example, a | |
button may have a role of type 'button', or a pane may have a role of | |
type 'alertdialog'. This property is used by assistive software to help | |
visually challenged users navigate rich web applications. | |
The full list of valid WAI-ARIA roles is available at: | |
[http://www.w3.org/TR/wai-aria/roles#roles_categorization](http://www.w3.org/TR/wai-aria/roles#roles_categorization) | |
@property ariaRole | |
@type String | |
@default null | |
@public | |
*/ | |
/** | |
Enables components to take a list of parameters as arguments. | |
For example, a component that takes two parameters with the names | |
`name` and `age`: | |
```javascript | |
let MyComponent = Ember.Component.extend; | |
MyComponent.reopenClass({ | |
positionalParams: ['name', 'age'] | |
}); | |
``` | |
It can then be invoked like this: | |
```hbs | |
{{my-component "John" 38}} | |
``` | |
The parameters can be referred to just like named parameters: | |
```hbs | |
Name: {{name}}, Age: {{age}}. | |
``` | |
Using a string instead of an array allows for an arbitrary number of | |
parameters: | |
```javascript | |
let MyComponent = Ember.Component.extend; | |
MyComponent.reopenClass({ | |
positionalParams: 'names' | |
}); | |
``` | |
It can then be invoked like this: | |
```hbs | |
{{my-component "John" "Michael" "Scott"}} | |
``` | |
The parameters can then be referred to by enumerating over the list: | |
```hbs | |
{{#each names as |name|}}{{name}}{{/each}} | |
``` | |
@static | |
@public | |
@property positionalParams | |
@since 1.13.0 | |
*/ | |
/** | |
Called when the attributes passed into the component have been updated. | |
Called both during the initial render of a container and during a rerender. | |
Can be used in place of an observer; code placed here will be executed | |
every time any attribute updates. | |
@method didReceiveAttrs | |
@public | |
@since 1.13.0 | |
*/ | |
/** | |
Called when the attributes passed into the component have been updated. | |
Called both during the initial render of a container and during a rerender. | |
Can be used in place of an observer; code placed here will be executed | |
every time any attribute updates. | |
@event didReceiveAttrs | |
@public | |
@since 1.13.0 | |
*/ | |
/** | |
Called after a component has been rendered, both on initial render and | |
in subsequent rerenders. | |
@method didRender | |
@public | |
@since 1.13.0 | |
*/ | |
/** | |
Called after a component has been rendered, both on initial render and | |
in subsequent rerenders. | |
@event didRender | |
@public | |
@since 1.13.0 | |
*/ | |
/** | |
Called before a component has been rendered, both on initial render and | |
in subsequent rerenders. | |
@method willRender | |
@public | |
@since 1.13.0 | |
*/ | |
/** | |
Called before a component has been rendered, both on initial render and | |
in subsequent rerenders. | |
@event willRender | |
@public | |
@since 1.13.0 | |
*/ | |
/** | |
Called when the attributes passed into the component have been changed. | |
Called only during a rerender, not during an initial render. | |
@method didUpdateAttrs | |
@public | |
@since 1.13.0 | |
*/ | |
/** | |
Called when the attributes passed into the component have been changed. | |
Called only during a rerender, not during an initial render. | |
@event didUpdateAttrs | |
@public | |
@since 1.13.0 | |
*/ | |
/** | |
Called when the component is about to update and rerender itself. | |
Called only during a rerender, not during an initial render. | |
@method willUpdate | |
@public | |
@since 1.13.0 | |
*/ | |
/** | |
Called when the component is about to update and rerender itself. | |
Called only during a rerender, not during an initial render. | |
@event willUpdate | |
@public | |
@since 1.13.0 | |
*/ | |
/** | |
Called when the component has updated and rerendered itself. | |
Called only during a rerender, not during an initial render. | |
@method didUpdate | |
@public | |
@since 1.13.0 | |
*/ | |
/** | |
Called when the component has updated and rerendered itself. | |
Called only during a rerender, not during an initial render. | |
@event didUpdate | |
@public | |
@since 1.13.0 | |
*/ | |
/** | |
A component may contain a layout. A layout is a regular template but | |
supersedes the `template` property during rendering. It is the | |
responsibility of the layout template to retrieve the `template` | |
property from the component (or alternatively, call `Handlebars.helpers.yield`, | |
`{{yield}}`) to render it in the correct location. | |
This is useful for a component that has a shared wrapper, but which delegates | |
the rendering of the contents of the wrapper to the `template` property | |
on a subclass. | |
@property layout | |
@type Function | |
@public | |
*/ | |
/** | |
The name of the layout to lookup if no layout is provided. | |
By default `Ember.Component` will lookup a template with this name in | |
`Ember.TEMPLATES` (a shared global object). | |
@property layoutName | |
@type String | |
@default null | |
@private | |
*/ | |
/** | |
Returns a jQuery object for this component's element. If you pass in a selector | |
string, this method will return a jQuery object, using the current element | |
as its buffer. | |
For example, calling `component.$('li')` will return a jQuery object containing | |
all of the `li` elements inside the DOM element of this component. | |
@method $ | |
@param {String} [selector] a jQuery-compatible selector string | |
@return {jQuery} the jQuery object for the DOM node | |
@public | |
*/ | |
/** | |
The HTML `id` of the component's element in the DOM. You can provide this | |
value yourself but it must be unique (just as in HTML): | |
```handlebars | |
{{my-component elementId="a-really-cool-id"}} | |
``` | |
If not manually set a default value will be provided by the framework. | |
Once rendered an element's `elementId` is considered immutable and you | |
should never change it. If you need to compute a dynamic value for the | |
`elementId`, you should do this when the component or element is being | |
instantiated: | |
```javascript | |
export default Ember.Component.extend({ | |
init() { | |
this._super(...arguments); | |
var index = this.get('index'); | |
this.set('elementId', `component-id${index}`); | |
} | |
}); | |
``` | |
@property elementId | |
@type String | |
@public | |
*/ | |
/** | |
If `false`, the view will appear hidden in DOM. | |
@property isVisible | |
@type Boolean | |
@default null | |
@public | |
*/ | |
Component[_emberUtils.NAME_KEY] = 'Ember.Component'; | |
Component.reopenClass({ | |
isComponentFactory: true, | |
positionalParams: [] | |
}); | |
exports.default = Component; | |
}); | |
/** | |
Normally, Ember's component model is "write-only". The component takes a | |
bunch of attributes that it got passed in, and uses them to render its | |
template. | |
One nice thing about this model is that if you try to set a value to the | |
same thing as last time, Ember (through HTMLBars) will avoid doing any | |
work on the DOM. | |
This is not just a performance optimization. If an attribute has not | |
changed, it is important not to clobber the element's "hidden state". | |
For example, if you set an input's `value` to the same value as before, | |
it will clobber selection state and cursor position. In other words, | |
setting an attribute is not **always** idempotent. | |
This method provides a way to read an element's attribute and also | |
update the last value Ember knows about at the same time. This makes | |
setting an attribute idempotent. | |
In particular, what this means is that if you get an `<input>` element's | |
`value` attribute and then re-render the template with the same value, | |
it will avoid clobbering the cursor and selection position. | |
Since most attribute sets are idempotent in the browser, you typically | |
can get away with reading attributes using jQuery, but the most reliable | |
way to do so is through this method. | |
@method readDOMAttr | |
@param {String} name the name of the attribute | |
@return String | |
@public | |
*/ | |
enifed('ember-glimmer/components/checkbox', ['exports', 'ember-metal', 'ember-glimmer/component', 'ember-glimmer/templates/empty'], function (exports, _emberMetal, _emberGlimmerComponent, _emberGlimmerTemplatesEmpty) { | |
'use strict'; | |
/** | |
@module ember | |
@submodule ember-views | |
*/ | |
/** | |
The internal class used to create text inputs when the `{{input}}` | |
helper is used with `type` of `checkbox`. | |
See [Ember.Templates.helpers.input](/api/classes/Ember.Templates.helpers.html#method_input) for usage details. | |
## Direct manipulation of `checked` | |
The `checked` attribute of an `Ember.Checkbox` object should always be set | |
through the Ember object or by interacting with its rendered element | |
representation via the mouse, keyboard, or touch. Updating the value of the | |
checkbox via jQuery will result in the checked value of the object and its | |
element losing synchronization. | |
## Layout and LayoutName properties | |
Because HTML `input` elements are self closing `layout` and `layoutName` | |
properties will not be applied. See [Ember.View](/api/classes/Ember.View.html)'s | |
layout section for more information. | |
@class Checkbox | |
@namespace Ember | |
@extends Ember.Component | |
@public | |
*/ | |
exports.default = _emberGlimmerComponent.default.extend({ | |
layout: _emberGlimmerTemplatesEmpty.default, | |
classNames: ['ember-checkbox'], | |
tagName: 'input', | |
attributeBindings: ['type', 'checked', 'indeterminate', 'disabled', 'tabindex', 'name', 'autofocus', 'required', 'form'], | |
type: 'checkbox', | |
checked: false, | |
disabled: false, | |
indeterminate: false, | |
didInsertElement: function () { | |
this._super.apply(this, arguments); | |
_emberMetal.get(this, 'element').indeterminate = !!_emberMetal.get(this, 'indeterminate'); | |
}, | |
change: function () { | |
_emberMetal.set(this, 'checked', this.$().prop('checked')); | |
} | |
}); | |
}); | |
enifed('ember-glimmer/components/link-to', ['exports', 'ember-console', 'ember-debug', 'ember-metal', 'ember-runtime', 'ember-views', 'ember-glimmer/templates/link-to', 'ember-glimmer/component'], function (exports, _emberConsole, _emberDebug, _emberMetal, _emberRuntime, _emberViews, _emberGlimmerTemplatesLinkTo, _emberGlimmerComponent) { | |
/** | |
@module ember | |
@submodule ember-glimmer | |
*/ | |
/** | |
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 passed value to `disabled` will disable it except `undefined`. | |
to ensure that only `true` disable the `link-to` component you can | |
override the global behaviour of `Ember.LinkComponent`. | |
```javascript | |
Ember.LinkComponent.reopen({ | |
disabled: Ember.computed(function(key, value) { | |
if (value !== undefined) { | |
this.set('_isDisabled', value === true); | |
} | |
return value === true ? get(this, 'disabledClass') : false; | |
}) | |
}); | |
``` | |
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 Ember.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 `Ember.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 [Ember.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 `Ember.LinkComponent` | |
for rendering. To override options for your entire | |
application, reopen `Ember.LinkComponent` and supply the | |
desired values: | |
``` javascript | |
Ember.LinkComponent.reopen({ | |
activeClass: "is-active", | |
tagName: 'li' | |
}) | |
``` | |
It is also possible to override the default event in | |
this manner: | |
``` javascript | |
Ember.LinkComponent.reopen({ | |
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 {Ember.LinkComponent} | |
@public | |
*/ | |
'use strict'; | |
/** | |
`Ember.LinkComponent` renders an element whose `click` event triggers a | |
transition of the application's instance of `Ember.Router` to | |
a supplied route by name. | |
`Ember.LinkComponent` components are invoked with {{#link-to}}. Properties | |
of this class can be overridden with `reopen` to customize application-wide | |
behavior. | |
@class LinkComponent | |
@namespace Ember | |
@extends Ember.Component | |
@see {Ember.Templates.helpers.link-to} | |
@public | |
**/ | |
var LinkComponent = _emberGlimmerComponent.default.extend({ | |
layout: _emberGlimmerTemplatesLinkTo.default, | |
tagName: 'a', | |
/** | |
@deprecated Use current-when instead. | |
@property currentWhen | |
@private | |
*/ | |
currentWhen: _emberRuntime.deprecatingAlias('current-when', { id: 'ember-routing-view.deprecated-current-when', until: '3.0.0' }), | |
/** | |
Used to determine when this `LinkComponent` is active. | |
@property currentWhen | |
@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', | |
_isDisabled: false, | |
/** | |
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', | |
// this is doc'ed here so it shows up in the events | |
// section of the API documentation, which is where | |
// people will likely go looking for it. | |
/** | |
Triggers the `LinkComponent`'s routing behavior. If | |
`eventName` is changed to a value other than `click` | |
the routing behavior will trigger on that custom event | |
instead. | |
@event click | |
@private | |
*/ | |
/** | |
An overridable method called when `LinkComponent` objects are instantiated. | |
Example: | |
```javascript | |
App.MyLinkComponent = Ember.LinkComponent.extend({ | |
init: function() { | |
this._super(...arguments); | |
Ember.Logger.log('Event is ' + this.get('eventName')); | |
} | |
}); | |
``` | |
NOTE: If you do override `init` for a framework class like `Ember.View`, | |
be sure to call `this._super(...arguments)` in your | |
`init` declaration! If you don't, Ember may not have an opportunity to | |
do important setup work, and you'll see strange behavior in your | |
application. | |
@method init | |
@private | |
*/ | |
init: function () { | |
this._super.apply(this, arguments); | |
// Map desired event name to invoke function | |
var eventName = _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: _emberMetal.computed({ | |
get: function (key, value) { | |
return false; | |
}, | |
set: function (key, value) { | |
if (value !== undefined) { | |
this.set('_isDisabled', value); | |
} | |
return value ? _emberMetal.get(this, 'disabledClass') : false; | |
} | |
}), | |
_computeActive: function (routerState) { | |
if (_emberMetal.get(this, 'loading')) { | |
return false; | |
} | |
var routing = _emberMetal.get(this, '_routing'); | |
var models = _emberMetal.get(this, 'models'); | |
var resolvedQueryParams = _emberMetal.get(this, 'resolvedQueryParams'); | |
var currentWhen = _emberMetal.get(this, 'current-when'); | |
var isCurrentWhenSpecified = !!currentWhen; | |
currentWhen = currentWhen || _emberMetal.get(this, 'qualifiedRouteName'); | |
currentWhen = currentWhen.split(' '); | |
for (var i = 0; i < currentWhen.length; i++) { | |
if (routing.isActiveForRoute(models, resolvedQueryParams, currentWhen[i], routerState, isCurrentWhenSpecified)) { | |
return _emberMetal.get(this, 'activeClass'); | |
} | |
} | |
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: _emberMetal.computed('attrs.params', '_routing.currentState', function computeLinkToComponentActive() { | |
var currentState = _emberMetal.get(this, '_routing.currentState'); | |
if (!currentState) { | |
return false; | |
} | |
return this._computeActive(currentState); | |
}), | |
willBeActive: _emberMetal.computed('_routing.targetState', function computeLinkToComponentWillBeActive() { | |
var routing = _emberMetal.get(this, '_routing'); | |
var targetState = _emberMetal.get(routing, 'targetState'); | |
if (_emberMetal.get(routing, 'currentState') === targetState) { | |
return; | |
} | |
return !!this._computeActive(targetState); | |
}), | |
transitioningIn: _emberMetal.computed('active', 'willBeActive', function computeLinkToComponentTransitioningIn() { | |
var willBeActive = _emberMetal.get(this, 'willBeActive'); | |
if (typeof willBeActive === 'undefined') { | |
return false; | |
} | |
return !_emberMetal.get(this, 'active') && willBeActive && 'ember-transitioning-in'; | |
}), | |
transitioningOut: _emberMetal.computed('active', 'willBeActive', function computeLinkToComponentTransitioningOut() { | |
var willBeActive = _emberMetal.get(this, 'willBeActive'); | |
if (typeof willBeActive === 'undefined') { | |
return false; | |
} | |
return _emberMetal.get(this, 'active') && !willBeActive && 'ember-transitioning-out'; | |
}), | |
/** | |
Event handler that invokes the link, activating the associated route. | |
@method _invoke | |
@param {Event} event | |
@private | |
*/ | |
_invoke: function (event) { | |
if (!_emberViews.isSimpleClick(event)) { | |
return true; | |
} | |
var preventDefault = _emberMetal.get(this, 'preventDefault'); | |
var targetAttribute = _emberMetal.get(this, 'target'); | |
if (preventDefault !== false) { | |
if (!targetAttribute || targetAttribute === '_self') { | |
event.preventDefault(); | |
} | |
} | |
if (_emberMetal.get(this, 'bubbles') === false) { | |
event.stopPropagation(); | |
} | |
if (_emberMetal.get(this, '_isDisabled')) { | |
return false; | |
} | |
if (_emberMetal.get(this, 'loading')) { | |
_emberConsole.default.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.'); | |
return false; | |
} | |
if (targetAttribute && targetAttribute !== '_self') { | |
return false; | |
} | |
var qualifiedRouteName = _emberMetal.get(this, 'qualifiedRouteName'); | |
var models = _emberMetal.get(this, 'models'); | |
var queryParams = _emberMetal.get(this, 'queryParams.values'); | |
var shouldReplace = _emberMetal.get(this, 'replace'); | |
var payload = { | |
queryParams: queryParams, | |
routeName: qualifiedRouteName | |
}; | |
_emberMetal.flaggedInstrument('interaction.link-to', payload, this._generateTransition(payload, qualifiedRouteName, models, queryParams, shouldReplace)); | |
}, | |
_generateTransition: function (payload, qualifiedRouteName, models, queryParams, shouldReplace) { | |
var routing = _emberMetal.get(this, '_routing'); | |
return function () { | |
payload.transition = routing.transitionTo(qualifiedRouteName, models, queryParams, shouldReplace); | |
}; | |
}, | |
queryParams: null, | |
qualifiedRouteName: _emberMetal.computed('targetRouteName', '_routing.currentState', function computeLinkToComponentQualifiedRouteName() { | |
var params = _emberMetal.get(this, 'params').slice(); | |
var lastParam = params[params.length - 1]; | |
if (lastParam && lastParam.isQueryParams) { | |
params.pop(); | |
} | |
var onlyQueryParamsSupplied = this[_emberGlimmerComponent.HAS_BLOCK] ? params.length === 0 : params.length === 1; | |
if (onlyQueryParamsSupplied) { | |
return _emberMetal.get(this, '_routing.currentRouteName'); | |
} | |
return _emberMetal.get(this, 'targetRouteName'); | |
}), | |
resolvedQueryParams: _emberMetal.computed('queryParams', function computeLinkToComponentResolvedQueryParams() { | |
var resolvedQueryParams = {}; | |
var queryParams = _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: _emberMetal.computed('models', 'qualifiedRouteName', function computeLinkToComponentHref() { | |
if (_emberMetal.get(this, 'tagName') !== 'a') { | |
return; | |
} | |
var qualifiedRouteName = _emberMetal.get(this, 'qualifiedRouteName'); | |
var models = _emberMetal.get(this, 'models'); | |
if (_emberMetal.get(this, 'loading')) { | |
return _emberMetal.get(this, 'loadingHref'); | |
} | |
var routing = _emberMetal.get(this, '_routing'); | |
var queryParams = _emberMetal.get(this, 'queryParams.values'); | |
_emberDebug.runInDebug(function () { | |
/* | |
* 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) { | |
_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: _emberMetal.computed('_modelsAreLoaded', 'qualifiedRouteName', function computeLinkToComponentLoading() { | |
var qualifiedRouteName = _emberMetal.get(this, 'qualifiedRouteName'); | |
var modelsAreLoaded = _emberMetal.get(this, '_modelsAreLoaded'); | |
if (!modelsAreLoaded || qualifiedRouteName == null) { | |
return _emberMetal.get(this, 'loadingClass'); | |
} | |
}), | |
_modelsAreLoaded: _emberMetal.computed('models', function computeLinkToComponentModelsAreLoaded() { | |
var models = _emberMetal.get(this, 'models'); | |
for (var i = 0; i < models.length; i++) { | |
if (models[i] == null) { | |
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)) { | |
_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 = undefined; | |
var params = _emberMetal.get(this, 'params'); | |
if (params) { | |
// Do not mutate params in place | |
params = params.slice(); | |
} | |
_emberDebug.assert('You must provide one or more parameters to the link-to component.', (function () { | |
if (!params) { | |
return false; | |
} | |
return params.length; | |
})()); | |
var disabledWhen = _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[_emberGlimmerComponent.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', []); | |
} | |
} | |
}); | |
LinkComponent.toString = function () { | |
return 'LinkComponent'; | |
}; | |
LinkComponent.reopenClass({ | |
positionalParams: 'params' | |
}); | |
exports.default = LinkComponent; | |
}); | |
enifed('ember-glimmer/components/text_area', ['exports', 'ember-glimmer/component', 'ember-views', 'ember-glimmer/templates/empty'], function (exports, _emberGlimmerComponent, _emberViews, _emberGlimmerTemplatesEmpty) { | |
/** | |
@module ember | |
@submodule ember-glimmer | |
*/ | |
'use strict'; | |
/** | |
`{{textarea}}` inserts a new instance of `<textarea>` tag into the template. | |
The attributes of `{{textarea}}` match those of the native HTML tags as | |
closely as possible. | |
The following HTML attributes can be set: | |
* `value` | |
* `name` | |
* `rows` | |
* `cols` | |
* `placeholder` | |
* `disabled` | |
* `maxlength` | |
* `tabindex` | |
* `selectionEnd` | |
* `selectionStart` | |
* `selectionDirection` | |
* `wrap` | |
* `readonly` | |
* `autofocus` | |
* `form` | |
* `spellcheck` | |
* `required` | |
When set to a quoted string, these value 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). | |
Unbound: | |
```handlebars | |
{{textarea value="Lots of static text that ISN'T bound"}} | |
``` | |
Would result in the following HTML: | |
```html | |
<textarea class="ember-text-area"> | |
Lots of static text that ISN'T bound | |
</textarea> | |
``` | |
Bound: | |
In the following example, the `writtenWords` property on `App.ApplicationController` | |
will be updated live as the user types 'Lots of text that IS bound' into | |
the text area of their browser's window. | |
```javascript | |
App.ApplicationController = Ember.Controller.extend({ | |
writtenWords: "Lots of text that IS bound" | |
}); | |
``` | |
```handlebars | |
{{textarea value=writtenWords}} | |
``` | |
Would result in the following HTML: | |
```html | |
<textarea class="ember-text-area"> | |
Lots of text that IS bound | |
</textarea> | |
``` | |
If you wanted a one way binding between the text area and a div tag | |
somewhere else on your screen, you could use `Ember.computed.oneWay`: | |
```javascript | |
App.ApplicationController = Ember.Controller.extend({ | |
writtenWords: "Lots of text that IS bound", | |
outputWrittenWords: Ember.computed.oneWay("writtenWords") | |
}); | |
``` | |
```handlebars | |
{{textarea value=writtenWords}} | |
<div> | |
{{outputWrittenWords}} | |
</div> | |
``` | |
Would result in the following HTML: | |
```html | |
<textarea class="ember-text-area"> | |
Lots of text that IS bound | |
</textarea> | |
<-- the following div will be updated in real time as you type --> | |
<div> | |
Lots of text that IS bound | |
</div> | |
``` | |
Finally, this example really shows the power and ease of Ember when two | |
properties are bound to eachother via `Ember.computed.alias`. Type into | |
either text area box and they'll both stay in sync. Note that | |
`Ember.computed.alias` costs more in terms of performance, so only use it when | |
your really binding in both directions: | |
```javascript | |
App.ApplicationController = Ember.Controller.extend({ | |
writtenWords: "Lots of text that IS bound", | |
twoWayWrittenWords: Ember.computed.alias("writtenWords") | |
}); | |
``` | |
```handlebars | |
{{textarea value=writtenWords}} | |
{{textarea value=twoWayWrittenWords}} | |
``` | |
```html | |
<textarea id="ember1" class="ember-text-area"> | |
Lots of text that IS bound | |
</textarea> | |
<-- both updated in real time --> | |
<textarea id="ember2" class="ember-text-area"> | |
Lots of text that IS bound | |
</textarea> | |
``` | |
### Actions | |
The helper can send multiple actions based on user events. | |
The action property defines the action which is send 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` | |
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 | |
{{textarea focus-out="alertMessage"}} | |
``` | |
See more about [Text Support Actions](/api/classes/Ember.TextArea.html) | |
### Extension | |
Internally, `{{textarea}}` creates an instance of `Ember.TextArea`, passing | |
arguments from the helper to `Ember.TextArea`'s `create` method. You can | |
extend the capabilities of text areas in your application by reopening this | |
class. For example, if you are building a Bootstrap project where `data-*` | |
attributes are used, you can globally add support for a `data-*` attribute | |
on all `{{textarea}}`s' in your app by reopening `Ember.TextArea` or | |
`Ember.TextSupport` and adding it to the `attributeBindings` concatenated | |
property: | |
```javascript | |
Ember.TextArea.reopen({ | |
attributeBindings: ['data-error'] | |
}); | |
``` | |
Keep in mind when writing `Ember.TextArea` subclasses that `Ember.TextArea` | |
itself extends `Ember.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) | |
@method textarea | |
@for Ember.Templates.helpers | |
@param {Hash} options | |
@public | |
*/ | |
/** | |
The internal class used to create textarea element when the `{{textarea}}` | |
helper is used. | |
See [Ember.Templates.helpers.textarea](/api/classes/Ember.Templates.helpers.html#method_textarea) for usage details. | |
## Layout and LayoutName properties | |
Because HTML `textarea` elements do not contain inner HTML the `layout` and | |
`layoutName` properties will not be applied. See [Ember.View](/api/classes/Ember.View.html)'s | |
layout section for more information. | |
@class TextArea | |
@namespace Ember | |
@extends Ember.Component | |
@uses Ember.TextSupport | |
@public | |
*/ | |
exports.default = _emberGlimmerComponent.default.extend(_emberViews.TextSupport, { | |
classNames: ['ember-text-area'], | |
layout: _emberGlimmerTemplatesEmpty.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-metal', 'ember-environment', 'ember-glimmer/component', 'ember-glimmer/templates/empty', 'ember-views'], function (exports, _emberMetal, _emberEnvironment, _emberGlimmerComponent, _emberGlimmerTemplatesEmpty, _emberViews) { | |
/** | |
@module ember | |
@submodule ember-views | |
*/ | |
'use strict'; | |
var inputTypeTestElement = undefined; | |
var inputTypes = Object.create(null); | |
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; | |
} | |
if (!inputTypeTestElement) { | |
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. See [Ember.View](/api/classes/Ember.View.html)'s | |
layout section for more information. | |
@class TextField | |
@namespace Ember | |
@extends Ember.Component | |
@uses Ember.TextSupport | |
@public | |
*/ | |
exports.default = _emberGlimmerComponent.default.extend(_emberViews.TextSupport, { | |
layout: _emberGlimmerTemplatesEmpty.default, | |
classNames: ['ember-text-field'], | |
tagName: 'input', | |
attributeBindings: ['accept', 'autocomplete', 'autosave', 'dir', 'formaction', 'formenctype', 'formmethod', 'formnovalidate', 'formtarget', 'height', 'inputmode', 'lang', 'list', 'max', 'min', 'multiple', 'name', 'pattern', 'size', 'step', 'type', '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: _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, _glimmerRuntime, _glimmerNode) { | |
'use strict'; | |
exports.DOMChanges = _glimmerRuntime.DOMChanges; | |
exports.DOMTreeConstruction = _glimmerRuntime.DOMTreeConstruction; | |
exports.NodeDOMTreeConstruction = _glimmerNode.NodeDOMTreeConstruction; | |
}); | |
enifed('ember-glimmer/environment', ['exports', 'ember-utils', 'ember-metal', 'ember-debug', 'ember-views', '@glimmer/runtime', 'ember-glimmer/syntax/curly-component', 'ember-glimmer/syntax', 'ember-glimmer/utils/iterable', 'ember-glimmer/utils/references', 'ember-glimmer/utils/debug-stack', 'ember-glimmer/helpers/if-unless', 'ember-glimmer/helpers/action', 'ember-glimmer/helpers/component', 'ember-glimmer/helpers/concat', 'ember-glimmer/helpers/get', 'ember-glimmer/helpers/hash', 'ember-glimmer/helpers/loc', 'ember-glimmer/helpers/log', 'ember-glimmer/helpers/mut', 'ember-glimmer/helpers/readonly', 'ember-glimmer/helpers/unbound', 'ember-glimmer/helpers/-class', 'ember-glimmer/helpers/-input-type', 'ember-glimmer/helpers/query-param', 'ember-glimmer/helpers/each-in', 'ember-glimmer/helpers/-normalize-class', 'ember-glimmer/helpers/-html-safe', 'ember-glimmer/protocol-for-url', 'container', 'ember-glimmer/modifiers/action'], function (exports, _emberUtils, _emberMetal, _emberDebug, _emberViews, _glimmerRuntime, _emberGlimmerSyntaxCurlyComponent, _emberGlimmerSyntax, _emberGlimmerUtilsIterable, _emberGlimmerUtilsReferences, _emberGlimmerUtilsDebugStack, _emberGlimmerHelpersIfUnless, _emberGlimmerHelpersAction, _emberGlimmerHelpersComponent, _emberGlimmerHelpersConcat, _emberGlimmerHelpersGet, _emberGlimmerHelpersHash, _emberGlimmerHelpersLoc, _emberGlimmerHelpersLog, _emberGlimmerHelpersMut, _emberGlimmerHelpersReadonly, _emberGlimmerHelpersUnbound, _emberGlimmerHelpersClass, _emberGlimmerHelpersInputType, _emberGlimmerHelpersQueryParam, _emberGlimmerHelpersEachIn, _emberGlimmerHelpersNormalizeClass, _emberGlimmerHelpersHtmlSafe, _emberGlimmerProtocolForUrl, _container, _emberGlimmerModifiersAction) { | |
'use strict'; | |
var Environment = (function (_GlimmerEnvironment) { | |
babelHelpers.inherits(Environment, _GlimmerEnvironment); | |
Environment.create = function create(options) { | |
return new Environment(options); | |
}; | |
function Environment(_ref) { | |
var _this = this; | |
var owner = _ref[_emberUtils.OWNER]; | |
babelHelpers.classCallCheck(this, Environment); | |
_GlimmerEnvironment.apply(this, arguments); | |
this.owner = owner; | |
this.isInteractive = owner.lookup('-environment:main').isInteractive; | |
// can be removed once https://github.com/tildeio/glimmer/pull/305 lands | |
this.destroyedComponents = []; | |
_emberGlimmerProtocolForUrl.default(this); | |
this._definitionCache = new _emberMetal.Cache(2000, function (_ref2) { | |
var name = _ref2.name; | |
var source = _ref2.source; | |
var owner = _ref2.owner; | |
var _lookupComponent = _emberViews.lookupComponent(owner, name, { source: source }); | |
var componentFactory = _lookupComponent.component; | |
var layout = _lookupComponent.layout; | |
if (componentFactory || layout) { | |
return new _emberGlimmerSyntaxCurlyComponent.CurlyComponentDefinition(name, componentFactory, layout); | |
} | |
}, function (_ref3) { | |
var name = _ref3.name; | |
var source = _ref3.source; | |
var owner = _ref3.owner; | |
var expandedName = source && owner._resolveLocalLookupName(name, source) || name; | |
var ownerGuid = _emberUtils.guidFor(owner); | |
return ownerGuid + '|' + expandedName; | |
}); | |
this._templateCache = new _emberMetal.Cache(1000, function (_ref4) { | |
var Template = _ref4.Template; | |
var owner = _ref4.owner; | |
if (Template.create) { | |
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 (_ref5) { | |
var Template = _ref5.Template; | |
var owner = _ref5.owner; | |
return _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 _glimmerRuntime.compileLayout(compilable, _this); | |
}, function (template) { | |
var owner = template.meta.owner; | |
return _emberUtils.guidFor(owner) + '|' + template.id; | |
}); | |
}, function (Compiler) { | |
return Compiler.id; | |
}); | |
this.builtInModifiers = { | |
action: new _emberGlimmerModifiersAction.default() | |
}; | |
this.builtInHelpers = { | |
if: _emberGlimmerHelpersIfUnless.inlineIf, | |
action: _emberGlimmerHelpersAction.default, | |
component: _emberGlimmerHelpersComponent.default, | |
concat: _emberGlimmerHelpersConcat.default, | |
get: _emberGlimmerHelpersGet.default, | |
hash: _emberGlimmerHelpersHash.default, | |
loc: _emberGlimmerHelpersLoc.default, | |
log: _emberGlimmerHelpersLog.default, | |
mut: _emberGlimmerHelpersMut.default, | |
'query-params': _emberGlimmerHelpersQueryParam.default, | |
readonly: _emberGlimmerHelpersReadonly.default, | |
unbound: _emberGlimmerHelpersUnbound.default, | |
unless: _emberGlimmerHelpersIfUnless.inlineUnless, | |
'-class': _emberGlimmerHelpersClass.default, | |
'-each-in': _emberGlimmerHelpersEachIn.default, | |
'-input-type': _emberGlimmerHelpersInputType.default, | |
'-normalize-class': _emberGlimmerHelpersNormalizeClass.default, | |
'-html-safe': _emberGlimmerHelpersHtmlSafe.default, | |
'-get-dynamic-var': _glimmerRuntime.getDynamicVar | |
}; | |
_emberDebug.runInDebug(function () { | |
return _this.debugStack = new _emberGlimmerUtilsDebugStack.default(); | |
}); | |
} | |
Environment.prototype.macros = function macros() { | |
var macros = _GlimmerEnvironment.prototype.macros.call(this); | |
_emberGlimmerSyntax.populateMacros(macros.blocks, macros.inlines); | |
return macros; | |
}; | |
Environment.prototype.hasComponentDefinition = function hasComponentDefinition() { | |
return false; | |
}; | |
Environment.prototype.getComponentDefinition = function getComponentDefinition(path, symbolTable) { | |
var name = path[0]; | |
var blockMeta = symbolTable.getMeta(); | |
var owner = blockMeta.owner; | |
var source = blockMeta.moduleName && 'template:' + blockMeta.moduleName; | |
return this._definitionCache.get({ name: name, source: source, owner: owner }); | |
}; | |
// normally templates should be exported at the proper module name | |
// and cached in the container, but this cache supports templates | |
// that have been set directly on the component's layout property | |
Environment.prototype.getTemplate = function getTemplate(Template, owner) { | |
return this._templateCache.get({ Template: Template, owner: owner }); | |
}; | |
// a Compiler can wrap the template so it needs its own cache | |
Environment.prototype.getCompiledBlock = function getCompiledBlock(Compiler, template) { | |
var compilerCache = this._compilerCache.get(Compiler); | |
return compilerCache.get(template); | |
}; | |
Environment.prototype.hasPartial = function hasPartial(name, symbolTable) { | |
var _symbolTable$getMeta = symbolTable.getMeta(); | |
var owner = _symbolTable$getMeta.owner; | |
return _emberViews.hasPartial(name, owner); | |
}; | |
Environment.prototype.lookupPartial = function lookupPartial(name, symbolTable) { | |
var _symbolTable$getMeta2 = symbolTable.getMeta(); | |
var owner = _symbolTable$getMeta2.owner; | |
var partial = { | |
template: _emberViews.lookupPartial(name, owner) | |
}; | |
if (partial.template) { | |
return partial; | |
} else { | |
throw new Error(name + ' is not a partial'); | |
} | |
}; | |
Environment.prototype.hasHelper = function hasHelper(name, symbolTable) { | |
if (this.builtInHelpers[name]) { | |
return true; | |
} | |
var blockMeta = symbolTable.getMeta(); | |
var owner = blockMeta.owner; | |
var options = { source: 'template:' + blockMeta.moduleName }; | |
return owner.hasRegistration('helper:' + name, options) || owner.hasRegistration('helper:' + name); | |
}; | |
Environment.prototype.lookupHelper = function lookupHelper(name, symbolTable) { | |
var helper = this.builtInHelpers[name]; | |
if (helper) { | |
return helper; | |
} | |
var blockMeta = symbolTable.getMeta(); | |
var owner = blockMeta.owner; | |
var options = blockMeta.moduleName && { source: 'template:' + blockMeta.moduleName } || {}; | |
if (true) { | |
var _ret = (function () { | |
var helperFactory = owner[_container.FACTORY_FOR]('helper:' + name, options) || owner[_container.FACTORY_FOR]('helper:' + name); | |
// TODO: try to unify this into a consistent protocol to avoid wasteful closure allocations | |
if (helperFactory.class.isHelperInstance) { | |
return { | |
v: function (vm, args) { | |
return _emberGlimmerUtilsReferences.SimpleHelperReference.create(helperFactory.class.compute, args); | |
} | |
}; | |
} else if (helperFactory.class.isHelperFactory) { | |
if (!true) { | |
helperFactory = helperFactory.create(); | |
} | |
return { | |
v: function (vm, args) { | |
return _emberGlimmerUtilsReferences.ClassBasedHelperReference.create(helperFactory, vm, args); | |
} | |
}; | |
} else { | |
throw new Error(name + ' is not a helper'); | |
} | |
})(); | |
if (typeof _ret === 'object') return _ret.v; | |
} else { | |
var _ret2 = (function () { | |
var helperFactory = owner.lookup('helper:' + name, options) || owner.lookup('helper:' + name); | |
// TODO: try to unify this into a consistent protocol to avoid wasteful closure allocations | |
if (helperFactory.isHelperInstance) { | |
return { | |
v: function (vm, args) { | |
return _emberGlimmerUtilsReferences.SimpleHelperReference.create(helperFactory.compute, args); | |
} | |
}; | |
} else if (helperFactory.isHelperFactory) { | |
return { | |
v: function (vm, args) { | |
return _emberGlimmerUtilsReferences.ClassBasedHelperReference.create(helperFactory, vm, args); | |
} | |
}; | |
} else { | |
throw new Error(name + ' is not a helper'); | |
} | |
})(); | |
if (typeof _ret2 === 'object') return _ret2.v; | |
} | |
}; | |
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 _emberGlimmerUtilsReferences.ConditionalReference.create(reference); | |
}; | |
Environment.prototype.iterableFor = function iterableFor(ref, args) { | |
var keyPath = args.named.get('key').value(); | |
return _emberGlimmerUtilsIterable.default(ref, keyPath); | |
}; | |
Environment.prototype.scheduleInstallModifier = function scheduleInstallModifier() { | |
if (this.isInteractive) { | |
var _GlimmerEnvironment$prototype$scheduleInstallModifier; | |
(_GlimmerEnvironment$prototype$scheduleInstallModifier = _GlimmerEnvironment.prototype.scheduleInstallModifier).call.apply(_GlimmerEnvironment$prototype$scheduleInstallModifier, [this].concat(babelHelpers.slice.call(arguments))); | |
} | |
}; | |
Environment.prototype.scheduleUpdateModifier = function scheduleUpdateModifier() { | |
if (this.isInteractive) { | |
var _GlimmerEnvironment$prototype$scheduleUpdateModifier; | |
(_GlimmerEnvironment$prototype$scheduleUpdateModifier = _GlimmerEnvironment.prototype.scheduleUpdateModifier).call.apply(_GlimmerEnvironment$prototype$scheduleUpdateModifier, [this].concat(babelHelpers.slice.call(arguments))); | |
} | |
}; | |
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; | |
})(_glimmerRuntime.Environment); | |
exports.default = Environment; | |
_emberDebug.runInDebug(function () { | |
var StyleAttributeManager = (function (_AttributeManager) { | |
babelHelpers.inherits(StyleAttributeManager, _AttributeManager); | |
function StyleAttributeManager() { | |
babelHelpers.classCallCheck(this, StyleAttributeManager); | |
_AttributeManager.apply(this, arguments); | |
} | |
StyleAttributeManager.prototype.setAttribute = function setAttribute(dom, element, value) { | |
var _AttributeManager$prototype$setAttribute; | |
_emberDebug.warn(_emberViews.constructStyleDeprecationMessage(value), (function () { | |
if (value === null || value === undefined || _glimmerRuntime.isSafeString(value)) { | |
return true; | |
} | |
return false; | |
})(), { id: 'ember-htmlbars.style-xss-warning' }); | |
(_AttributeManager$prototype$setAttribute = _AttributeManager.prototype.setAttribute).call.apply(_AttributeManager$prototype$setAttribute, [this].concat(babelHelpers.slice.call(arguments))); | |
}; | |
StyleAttributeManager.prototype.updateAttribute = function updateAttribute(dom, element, value) { | |
var _AttributeManager$prototype$updateAttribute; | |
_emberDebug.warn(_emberViews.constructStyleDeprecationMessage(value), (function () { | |
if (value === null || value === undefined || _glimmerRuntime.isSafeString(value)) { | |
return true; | |
} | |
return false; | |
})(), { id: 'ember-htmlbars.style-xss-warning' }); | |
(_AttributeManager$prototype$updateAttribute = _AttributeManager.prototype.updateAttribute).call.apply(_AttributeManager$prototype$updateAttribute, [this].concat(babelHelpers.slice.call(arguments))); | |
}; | |
return StyleAttributeManager; | |
})(_glimmerRuntime.AttributeManager); | |
var STYLE_ATTRIBUTE_MANANGER = new StyleAttributeManager('style'); | |
Environment.prototype.attributeFor = function (element, attribute, isTrusting, namespace) { | |
if (attribute === 'style' && !isTrusting) { | |
return STYLE_ATTRIBUTE_MANANGER; | |
} | |
return _glimmerRuntime.Environment.prototype.attributeFor.call(this, element, attribute, isTrusting); | |
}; | |
}); | |
}); | |
enifed('ember-glimmer/helper', ['exports', 'ember-utils', 'ember-runtime', '@glimmer/reference'], function (exports, _emberUtils, _emberRuntime, _glimmerReference) { | |
/** | |
@module ember | |
@submodule ember-glimmer | |
*/ | |
'use strict'; | |
exports.helper = helper; | |
var RECOMPUTE_TAG = _emberUtils.symbol('RECOMPUTE_TAG'); | |
exports.RECOMPUTE_TAG = 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: | |
```js | |
export default Ember.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 Ember.Helper | |
@public | |
@since 1.13.0 | |
*/ | |
var Helper = _emberRuntime.FrameworkObject.extend({ | |
isHelperInstance: true, | |
init: function () { | |
this._super.apply(this, arguments); | |
this[RECOMPUTE_TAG] = new _glimmerReference.DirtyableTag(); | |
}, | |
/** | |
On a class-based helper, it may be useful to force a recomputation of that | |
helpers value. This is akin to `rerender` on a component. | |
For example, this component will rerender when the `currentUser` on a | |
session service changes: | |
```js | |
// app/helpers/current-user-email.js | |
export default Ember.Helper.extend({ | |
session: Ember.inject.service(), | |
onNewUser: Ember.observer('session.currentUser', function() { | |
this.recompute(); | |
}), | |
compute() { | |
return this.get('session.currentUser.email'); | |
} | |
}); | |
``` | |
@method recompute | |
@public | |
@since 1.13.0 | |
*/ | |
recompute: function () { | |
this[RECOMPUTE_TAG].dirty(); | |
} | |
/** | |
Override this function when writing a class-based helper. | |
@method compute | |
@param {Array} params The positional arguments to the helper | |
@param {Object} hash The named arguments to the helper | |
@public | |
@since 1.13.0 | |
*/ | |
}); | |
Helper.reopenClass({ | |
isHelperFactory: true | |
}); | |
/** | |
In many cases, the ceremony of a full `Ember.Helper` class is not required. | |
The `helper` method create pure-function helpers without instances. For | |
example: | |
```js | |
// app/helpers/format-currency.js | |
export default Ember.Helper.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 | |
@public | |
@since 1.13.0 | |
*/ | |
function helper(helperFn) { | |
return { | |
isHelperInstance: true, | |
compute: helperFn | |
}; | |
} | |
exports.default = Helper; | |
}); | |
enifed('ember-glimmer/helpers/-class', ['exports', 'ember-glimmer/utils/references', 'ember-runtime'], function (exports, _emberGlimmerUtilsReferences, _emberRuntime) { | |
'use strict'; | |
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; | |
} | |
exports.default = function (vm, args) { | |
return new _emberGlimmerUtilsReferences.InternalHelperReference(classHelper, args); | |
}; | |
}); | |
enifed('ember-glimmer/helpers/-html-safe', ['exports', 'ember-glimmer/utils/references', 'ember-glimmer/utils/string'], function (exports, _emberGlimmerUtilsReferences, _emberGlimmerUtilsString) { | |
'use strict'; | |
function htmlSafe(_ref) { | |
var positional = _ref.positional; | |
var path = positional.at(0); | |
return new _emberGlimmerUtilsString.SafeString(path.value()); | |
} | |
exports.default = function (vm, args) { | |
return new _emberGlimmerUtilsReferences.InternalHelperReference(htmlSafe, args); | |
}; | |
}); | |
enifed('ember-glimmer/helpers/-input-type', ['exports', 'ember-glimmer/utils/references'], function (exports, _emberGlimmerUtilsReferences) { | |
'use strict'; | |
function inputTypeHelper(_ref) { | |
var positional = _ref.positional; | |
var named = _ref.named; | |
var type = positional.at(0).value(); | |
if (type === 'checkbox') { | |
return '-checkbox'; | |
} | |
return '-text-field'; | |
} | |
exports.default = function (vm, args) { | |
return new _emberGlimmerUtilsReferences.InternalHelperReference(inputTypeHelper, args); | |
}; | |
}); | |
enifed('ember-glimmer/helpers/-normalize-class', ['exports', 'ember-glimmer/utils/references', 'ember-runtime'], function (exports, _emberGlimmerUtilsReferences, _emberRuntime) { | |
'use strict'; | |
function normalizeClass(_ref) { | |
var positional = _ref.positional; | |
var named = _ref.named; | |
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); | |
} | |
} | |
exports.default = function (vm, args) { | |
return new _emberGlimmerUtilsReferences.InternalHelperReference(normalizeClass, args); | |
}; | |
}); | |
enifed('ember-glimmer/helpers/action', ['exports', 'ember-utils', 'ember-metal', 'ember-glimmer/utils/references', '@glimmer/runtime', '@glimmer/reference', 'ember-debug'], function (exports, _emberUtils, _emberMetal, _emberGlimmerUtilsReferences, _glimmerRuntime, _glimmerReference, _emberDebug) { | |
/** | |
@module ember | |
@submodule ember-glimmer | |
*/ | |
'use strict'; | |
var INVOKE = _emberUtils.symbol('INVOKE'); | |
exports.INVOKE = INVOKE; | |
var ACTION = _emberUtils.symbol('ACTION'); | |
exports.ACTION = 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: | |
```js | |
import Ember from 'ember'; | |
export default Ember.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 targetting 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: | |
```js | |
export default Ember.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 Ember from 'ember'; | |
export default Ember.Component.extend({ | |
actions: { | |
setName(model, name) { | |
model.set('name', name); | |
} | |
} | |
}); | |
``` | |
```handlebars | |
{{my-input submit=(action 'setName' model)}} | |
``` | |
```app/components/my-component.js | |
import Ember from 'ember'; | |
export default Ember.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 Ember from 'ember'; | |
export function disableBubbling([action]) { | |
return function(event) { | |
event.stopPropagation(); | |
return action(event); | |
}; | |
} | |
export default Ember.Helper.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.View.html#toc_responding-to-browser-events) | |
in the documentation for Ember.View 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.View.html#toc_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 Ember from 'ember'; | |
export default Ember.Controller.extend({ | |
someService: Ember.inject.service() | |
}); | |
``` | |
@method action | |
@for Ember.Templates.helpers | |
@public | |
*/ | |
exports.default = function (vm, args) { | |
var named = args.named; | |
var positional = args.positional; | |
// 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 context = positional.at(0); | |
var action = positional.at(1); | |
// TODO: Is there a better way of doing this? | |
var debugKey = action._propertyKey; | |
var restArgs = undefined; | |
if (positional.length === 2) { | |
restArgs = _glimmerRuntime.EvaluatedPositionalArgs.empty(); | |
} else { | |
restArgs = _glimmerRuntime.EvaluatedPositionalArgs.create(positional.values.slice(2)); | |
} | |
var target = named.has('target') ? named.get('target') : context; | |
var processArgs = makeArgsProcessor(named.has('value') && named.get('value'), restArgs); | |
var fn = undefined; | |
if (typeof action[INVOKE] === 'function') { | |
fn = makeClosureAction(action, action, action[INVOKE], processArgs, debugKey); | |
} else if (_glimmerReference.isConst(target) && _glimmerReference.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 _emberGlimmerUtilsReferences.UnboundReference(fn); | |
}; | |
function NOOP(args) { | |
return args; | |
} | |
function makeArgsProcessor(valuePathRef, actionArgsRef) { | |
var mergeArgs = null; | |
if (actionArgsRef.length > 0) { | |
mergeArgs = function (args) { | |
return actionArgsRef.value().concat(args); | |
}; | |
} | |
var readValue = null; | |
if (valuePathRef) { | |
readValue = function (args) { | |
var valuePath = valuePathRef.value(); | |
if (valuePath && args.length > 0) { | |
args[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 | |
_emberDebug.runInDebug(function () { | |
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 = undefined, | |
fn = undefined; | |
_emberDebug.assert('Action passed is null or undefined in (action) from ' + target + '.', !_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]; | |
_emberDebug.assert('An action named \'' + action + '\' was not found in ' + target, fn); | |
} else if (typeofAction === 'function') { | |
self = context; | |
fn = action; | |
} else { | |
_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 _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-utils', 'ember-glimmer/utils/references', 'ember-glimmer/syntax/curly-component', '@glimmer/runtime', 'ember-debug'], function (exports, _emberUtils, _emberGlimmerUtilsReferences, _emberGlimmerSyntaxCurlyComponent, _glimmerRuntime, _emberDebug) { | |
/** | |
@module ember | |
@submodule ember-glimmer | |
*/ | |
'use strict'; | |
/** | |
The `{{component}}` helper lets you add instances of `Ember.Component` to a | |
template. See [Ember.Component](/api/classes/Ember.Component.html) for | |
additional information on how a `Component` functions. | |
`{{component}}`'s primary use is for cases where you want to dynamically | |
change which type of component is rendered as the state of your application | |
changes. This helper has three modes: inline, block, and nested. | |
### Inline Form | |
Given the following template: | |
```app/application.hbs | |
{{component infographicComponentName}} | |
``` | |
And the following application code: | |
```app/controllers/application.js | |
export default Ember.Controller.extend({ | |
infographicComponentName: computed('isMarketOpen', { | |
get() { | |
if (this.get('isMarketOpen')) { | |
return 'live-updating-chart'; | |
} else { | |
return 'market-close-summary'; | |
} | |
} | |
}) | |
}); | |
``` | |
The `live-updating-chart` component will be appended when `isMarketOpen` is | |
`true`, and the `market-close-summary` component will be appended when | |
`isMarketOpen` is `false`. If the value changes while the app is running, | |
the component will be automatically swapped out accordingly. | |
Note: You should not use this helper when you are consistently rendering the same | |
component. In that case, use standard component syntax, for example: | |
```app/templates/application.hbs | |
{{live-updating-chart}} | |
``` | |
### Block Form | |
Using the block form of this helper is similar to using the block form | |
of a component. Given the following application template: | |
```app/templates/application.hbs | |
{{#component infographicComponentName}} | |
Last update: {{lastUpdateTimestamp}} | |
{{/component}} | |
``` | |
The following controller code: | |
```app/controllers/application.js | |
export default Ember.Controller.extend({ | |
lastUpdateTimestamp: computed(function() { | |
return new Date(); | |
}), | |
infographicComponentName: computed('isMarketOpen', { | |
get() { | |
if (this.get('isMarketOpen')) { | |
return 'live-updating-chart'; | |
} else { | |
return 'market-close-summary'; | |
} | |
} | |
}) | |
}); | |
``` | |
And the following component template: | |
```app/templates/components/live-updating-chart.hbs | |
{{! chart }} | |
{{yield}} | |
``` | |
The `Last Update: {{lastUpdateTimestamp}}` will be rendered in place of the `{{yield}}`. | |
### Nested Usage | |
The `component` helper can be used to package a component path with initial attrs. | |
The included attrs can then be merged during the final invocation. | |
For example, given a `person-form` component with the following template: | |
```app/templates/components/person-form.hbs | |
{{yield (hash | |
nameInput=(component "my-input-component" value=model.name placeholder="First Name") | |
)}} | |
``` | |
When yielding the component via the `hash` helper, the component is invoked directly. | |
See the following snippet: | |
``` | |
{{#person-form as |form|}} | |
{{form.nameInput placeholder="Username"}} | |
{{/person-form}} | |
``` | |
Which outputs an input whose value is already bound to `model.name` and `placeholder` | |
is "Username". | |
When yielding the component without the hash helper use the `component` helper. | |
For example, below is a `full-name` component template: | |
```handlebars | |
{{yield (component "my-input-component" value=model.name placeholder="Name")}} | |
``` | |
``` | |
{{#full-name as |field|}} | |
{{component field placeholder="Full name"}} | |
{{/full-name}} | |
``` | |
@method component | |
@since 1.11.0 | |
@for Ember.Templates.helpers | |
@public | |
*/ | |
var ClosureComponentReference = (function (_CachedReference) { | |
babelHelpers.inherits(ClosureComponentReference, _CachedReference); | |
ClosureComponentReference.create = function create(args, symbolTable, env) { | |
return new ClosureComponentReference(args, symbolTable, env); | |
}; | |
function ClosureComponentReference(args, symbolTable, env) { | |
babelHelpers.classCallCheck(this, ClosureComponentReference); | |
_CachedReference.call(this); | |
var firstArg = args.positional.at(0); | |
this.defRef = firstArg; | |
this.tag = firstArg.tag; | |
this.env = env; | |
this.symbolTable = symbolTable; | |
this.args = args; | |
this.lastDefinition = undefined; | |
this.lastName = undefined; | |
} | |
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; | |
var defRef = this.defRef; | |
var env = this.env; | |
var symbolTable = this.symbolTable; | |
var lastDefinition = this.lastDefinition; | |
var lastName = this.lastName; | |
var nameOrDef = defRef.value(); | |
var definition = null; | |
if (nameOrDef && nameOrDef === lastName) { | |
return lastDefinition; | |
} | |
this.lastName = nameOrDef; | |
if (typeof nameOrDef === 'string') { | |
_emberDebug.assert('You cannot use the input helper as a contextual helper. Please extend Ember.TextField or Ember.Checkbox to use it as a contextual component.', nameOrDef !== 'input'); | |
_emberDebug.assert('You cannot use the textarea helper as a contextual helper. Please extend Ember.TextArea to use it as a contextual component.', nameOrDef !== 'textarea'); | |
definition = env.getComponentDefinition([nameOrDef], symbolTable); | |
_emberDebug.assert('The component helper cannot be used without a valid component name. You used "' + nameOrDef + '" via (component "' + nameOrDef + '")', definition); | |
} else if (_glimmerRuntime.isComponentDefinition(nameOrDef)) { | |
definition = nameOrDef; | |
} else { | |
_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; | |
})(_emberGlimmerUtilsReferences.CachedReference); | |
exports.ClosureComponentReference = ClosureComponentReference; | |
function createCurriedDefinition(definition, args) { | |
var curriedArgs = curryArgs(definition, args); | |
return new _emberGlimmerSyntaxCurlyComponent.CurlyComponentDefinition(definition.name, definition.ComponentClass, definition.template, curriedArgs); | |
} | |
var EMPTY_BLOCKS = { | |
default: null, | |
inverse: null | |
}; | |
_emberDebug.runInDebug(function () { | |
EMPTY_BLOCKS = Object.freeze(EMPTY_BLOCKS); | |
}); | |
function curryArgs(definition, newArgs) { | |
var args = definition.args; | |
var 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$values = newArgs.positional.values; | |
var slicedPositionalArgs = _newArgs$positional$values.slice(1); | |
if (positionalParams && slicedPositionalArgs.length) { | |
_emberGlimmerSyntaxCurlyComponent.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 && 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 && args.named.map || {}; | |
var oldPositional = args && args.positional && args.positional.values || []; | |
// Merge positional arrays | |
var mergedPositional = new Array(Math.max(oldPositional.length, slicedPositionalArgs.length)); | |
mergedPositional.splice.apply(mergedPositional, [0, oldPositional.length].concat(oldPositional)); | |
mergedPositional.splice.apply(mergedPositional, [0, slicedPositionalArgs.length].concat(slicedPositionalArgs)); | |
// Merge named maps | |
var mergedNamed = _emberUtils.assign({}, oldNamed, positionalToNamedParams, newArgs.named.map); | |
var mergedArgs = _glimmerRuntime.EvaluatedArgs.create(_glimmerRuntime.EvaluatedPositionalArgs.create(mergedPositional), _glimmerRuntime.EvaluatedNamedArgs.create(mergedNamed), EMPTY_BLOCKS); | |
return mergedArgs; | |
} | |
exports.default = function (vm, args, symbolTable) { | |
return ClosureComponentReference.create(args, symbolTable, vm.env); | |
}; | |
}); | |
enifed('ember-glimmer/helpers/concat', ['exports', 'ember-glimmer/utils/references', '@glimmer/runtime'], function (exports, _emberGlimmerUtilsReferences, _glimmerRuntime) { | |
'use strict'; | |
/** | |
@module ember | |
@submodule ember-glimmer | |
*/ | |
/** | |
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(_glimmerRuntime.normalizeTextValue).join(''); | |
} | |
exports.default = function (vm, args) { | |
return new _emberGlimmerUtilsReferences.InternalHelperReference(concat, args); | |
}; | |
}); | |
enifed('ember-glimmer/helpers/each-in', ['exports', 'ember-utils'], function (exports, _emberUtils) { | |
/** | |
@module ember | |
@submodule ember-glimmer | |
*/ | |
'use strict'; | |
exports.isEachIn = isEachIn; | |
/** | |
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 = _emberUtils.symbol('EACH_IN'); | |
function isEachIn(ref) { | |
return ref && ref[EACH_IN_REFERENCE]; | |
} | |
exports.default = function (vm, args) { | |
var ref = Object.create(args.positional.at(0)); | |
ref[EACH_IN_REFERENCE] = true; | |
return ref; | |
}; | |
}); | |
enifed('ember-glimmer/helpers/get', ['exports', 'ember-metal', 'ember-glimmer/utils/references', '@glimmer/reference'], function (exports, _emberMetal, _emberGlimmerUtilsReferences, _glimmerReference) { | |
'use strict'; | |
/** | |
@module ember | |
@submodule ember-glimmer | |
*/ | |
/** | |
Dynamically look up a property on an object. The second argument to `{{get}}` | |
should have a string value, although it can be bound. | |
For example, these two usages are equivilent: | |
```handlebars | |
{{person.height}} | |
{{get person "height"}} | |
``` | |
If there were several facts about a person, the `{{get}}` helper can dynamically | |
pick one: | |
```handlebars | |
{{get person factName}} | |
``` | |
For a more complex example, this template would allow the user to switch | |
between showing the user's height and weight with a click: | |
```handlebars | |
{{get person factName}} | |
<button {{action (action (mut factName)) "height"}}>Show height</button> | |
<button {{action (action (mut factName)) "weight"}}>Show weight</button> | |
``` | |
The `{{get}}` helper can also respect mutable values itself. For example: | |
```handlebars | |
{{input value=(mut (get person factName)) type="text"}} | |
<button {{action (action (mut factName)) "height"}}>Show height</button> | |
<button {{action (action (mut factName)) "weight"}}>Show weight</button> | |
``` | |
Would allow the user to swap what fact is being displayed, and also edit | |
that fact via a two-way mutable binding. | |
@public | |
@method get | |
@for Ember.Templates.helpers | |
@since 2.1.0 | |
*/ | |
exports.default = function (vm, args) { | |
return GetHelperReference.create(args.positional.at(0), args.positional.at(1)); | |
}; | |
var GetHelperReference = (function (_CachedReference) { | |
babelHelpers.inherits(GetHelperReference, _CachedReference); | |
GetHelperReference.create = function create(sourceReference, pathReference) { | |
if (_glimmerReference.isConst(pathReference)) { | |
var parts = pathReference.value().split('.'); | |
return _glimmerReference.referenceFromParts(sourceReference, parts); | |
} else { | |
return new GetHelperReference(sourceReference, pathReference); | |
} | |
}; | |
function GetHelperReference(sourceReference, pathReference) { | |
babelHelpers.classCallCheck(this, GetHelperReference); | |
_CachedReference.call(this); | |
this.sourceReference = sourceReference; | |
this.pathReference = pathReference; | |
this.lastPath = null; | |
this.innerReference = null; | |
var innerTag = this.innerTag = new _glimmerReference.UpdatableTag(_glimmerReference.CONSTANT_TAG); | |
this.tag = _glimmerReference.combine([sourceReference.tag, pathReference.tag, innerTag]); | |
} | |
GetHelperReference.prototype.compute = function compute() { | |
var lastPath = this.lastPath; | |
var innerReference = this.innerReference; | |
var innerTag = this.innerTag; | |
var path = this.lastPath = this.pathReference.value(); | |
if (path !== lastPath) { | |
if (path) { | |
var pathType = typeof path; | |
if (pathType === 'string') { | |
innerReference = this.innerReference = _glimmerReference.referenceFromParts(this.sourceReference, path.split('.')); | |
} else if (pathType === 'number') { | |
innerReference = this.innerReference = this.sourceReference.get(path); | |
} | |
innerTag.update(innerReference.tag); | |
} else { | |
innerReference = this.innerReference = null; | |
innerTag.update(_glimmerReference.CONSTANT_TAG); | |
} | |
} | |
return innerReference ? innerReference.value() : null; | |
}; | |
GetHelperReference.prototype[_emberGlimmerUtilsReferences.UPDATE] = function (value) { | |
_emberMetal.set(this.sourceReference.value(), this.pathReference.value(), value); | |
}; | |
return GetHelperReference; | |
})(_emberGlimmerUtilsReferences.CachedReference); | |
}); | |
enifed("ember-glimmer/helpers/hash", ["exports"], function (exports) { | |
/** | |
@module ember | |
@submodule ember-glimmer | |
*/ | |
/** | |
Use the `{{hash}}` helper to create a hash to pass as an option to your | |
components. This is specially useful for contextual components where you can | |
just yield a hash: | |
```handlebars | |
{{yield (hash | |
name='Sarah' | |
title=office | |
)}} | |
``` | |
Would result in an object such as: | |
```js | |
{ name: 'Sarah', title: this.get('office') } | |
``` | |
Where the `title` is bound to updates of the `office` property. | |
@method hash | |
@for Ember.Templates.helpers | |
@param {Object} options | |
@return {Object} Hash | |
@since 2.3.0 | |
@public | |
*/ | |
"use strict"; | |
exports.default = function (vm, args) { | |
return args.named; | |
}; | |
}); | |
enifed('ember-glimmer/helpers/if-unless', ['exports', 'ember-debug', 'ember-glimmer/utils/references', '@glimmer/reference'], function (exports, _emberDebug, _emberGlimmerUtilsReferences, _glimmerReference) { | |
/** | |
@module ember | |
@submodule ember-glimmer | |
*/ | |
'use strict'; | |
exports.inlineIf = inlineIf; | |
exports.inlineUnless = inlineUnless; | |
/** | |
Use the `if` block helper to conditionally render a block depending on a | |
property. If the property is "falsey", for example: `false`, `undefined`, | |
`null`, `""`, `0`, `NaN` or an empty array, the block will not be rendered. | |
```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}} | |
``` | |
You can use `if` inline to conditionally render a single property or string. | |
This helper acts like a ternary operator. If the first property is truthy, | |
the second argument will be displayed, if not, the third argument will be | |
displayed | |
```handlebars | |
{{if useLongGreeting "Hello" "Hi"}} Dave | |
``` | |
Finally, you can use the `if` helper inside another helper as a subexpression. | |
```handlebars | |
{{some-component height=(if isBig "100" "10")}} | |
``` | |
@method if | |
@for Ember.Templates.helpers | |
@public | |
*/ | |
var ConditionalHelperReference = (function (_CachedReference) { | |
babelHelpers.inherits(ConditionalHelperReference, _CachedReference); | |
ConditionalHelperReference.create = function create(_condRef, _truthyRef, _falsyRef) { | |
var condRef = _emberGlimmerUtilsReferences.ConditionalReference.create(_condRef); | |
var truthyRef = _truthyRef || _emberGlimmerUtilsReferences.UNDEFINED_REFERENCE; | |
var falsyRef = _falsyRef || _emberGlimmerUtilsReferences.UNDEFINED_REFERENCE; | |
if (_glimmerReference.isConst(condRef)) { | |
return condRef.value() ? truthyRef : falsyRef; | |
} else { | |
return new ConditionalHelperReference(condRef, truthyRef, falsyRef); | |
} | |
}; | |
function ConditionalHelperReference(cond, truthy, falsy) { | |
babelHelpers.classCallCheck(this, ConditionalHelperReference); | |
_CachedReference.call(this); | |
this.branchTag = new _glimmerReference.UpdatableTag(_glimmerReference.CONSTANT_TAG); | |
this.tag = _glimmerReference.combine([cond.tag, this.branchTag]); | |
this.cond = cond; | |
this.truthy = truthy; | |
this.falsy = falsy; | |
} | |
/** | |
The inline `if` helper conditionally renders a single property or string. | |
This helper acts like a ternary operator. If the first property is truthy, | |
the second argument will be displayed, otherwise, the third argument will be | |
displayed | |
```handlebars | |
{{if useLongGreeting "Hello" "Hi"}} Alex | |
``` | |
You can use the `if` helper inside another helper as a subexpression. | |
```handlebars | |
{{some-component height=(if isBig "100" "10")}} | |
``` | |
@method if | |
@for Ember.Templates.helpers | |
@public | |
*/ | |
ConditionalHelperReference.prototype.compute = function compute() { | |
var cond = this.cond; | |
var truthy = this.truthy; | |
var falsy = this.falsy; | |
var branch = cond.value() ? truthy : falsy; | |
this.branchTag.update(branch.tag); | |
return branch.value(); | |
}; | |
return ConditionalHelperReference; | |
})(_emberGlimmerUtilsReferences.CachedReference); | |
function inlineIf(vm, _ref) { | |
var positional = _ref.positional; | |
switch (positional.length) { | |
case 2: | |
return ConditionalHelperReference.create(positional.at(0), positional.at(1), null); | |
case 3: | |
return ConditionalHelperReference.create(positional.at(0), positional.at(1), positional.at(2)); | |
default: | |
_emberDebug.assert('The inline form of the `if` helper expects two or three arguments, e.g. ' + '`{{if trialExpired "Expired" expiryDate}}`.'); | |
} | |
} | |
/** | |
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; | |
switch (positional.length) { | |
case 2: | |
return ConditionalHelperReference.create(positional.at(0), null, positional.at(1)); | |
case 3: | |
return ConditionalHelperReference.create(positional.at(0), positional.at(2), positional.at(1)); | |
default: | |
_emberDebug.assert('The inline form of the `unless` helper expects two or three arguments, e.g. ' + '`{{unless isFirstLogin "Welcome back!"}}`.'); | |
} | |
} | |
}); | |
enifed('ember-glimmer/helpers/loc', ['exports', 'ember-glimmer/utils/references', 'ember-runtime'], function (exports, _emberGlimmerUtilsReferences, _emberRuntime) { | |
/** | |
@module ember | |
@submodule ember-glimmer | |
*/ | |
'use strict'; | |
/** | |
Calls [Ember.String.loc](/api/classes/Ember.String.html#method_loc) with the | |
provided string. This is a convenient way to localize text within a template. | |
For example: | |
```javascript | |
Ember.STRINGS = { | |
'_welcome_': 'Bonjour' | |
}; | |
``` | |
```handlebars | |
<div class='message'> | |
{{loc '_welcome_'}} | |
</div> | |
``` | |
```html | |
<div class='message'> | |
Bonjour | |
</div> | |
``` | |
See [Ember.String.loc](/api/classes/Ember.String.html#method_loc) for how to | |
set up localized string references. | |
@method loc | |
@for Ember.Templates.helpers | |
@param {String} str The string to format. | |
@see {Ember.String#loc} | |
@public | |
*/ | |
function locHelper(_ref) { | |
var positional = _ref.positional; | |
return _emberRuntime.String.loc.apply(null, positional.value()); | |
} | |
exports.default = function (vm, args) { | |
return new _emberGlimmerUtilsReferences.InternalHelperReference(locHelper, args); | |
}; | |
}); | |
enifed('ember-glimmer/helpers/log', ['exports', 'ember-glimmer/utils/references', 'ember-console'], function (exports, _emberGlimmerUtilsReferences, _emberConsole) { | |
'use strict'; | |
/** | |
`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()); | |
} | |
exports.default = function (vm, args) { | |
return new _emberGlimmerUtilsReferences.InternalHelperReference(log, args); | |
}; | |
}); | |
/** | |
@module ember | |
@submodule ember-glimmer | |
*/ | |
enifed('ember-glimmer/helpers/mut', ['exports', 'ember-utils', 'ember-debug', 'ember-glimmer/utils/references', 'ember-glimmer/helpers/action'], function (exports, _emberUtils, _emberDebug, _emberGlimmerUtilsReferences, _emberGlimmerHelpersAction) { | |
/** | |
@module ember | |
@submodule ember-glimmer | |
*/ | |
'use strict'; | |
exports.isMut = isMut; | |
exports.unMut = unMut; | |
/** | |
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 = _emberUtils.symbol('MUT'); | |
var SOURCE = _emberUtils.symbol('SOURCE'); | |
function isMut(ref) { | |
return ref && ref[MUT_REFERENCE]; | |
} | |
function unMut(ref) { | |
return ref[SOURCE] || ref; | |
} | |
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. | |
_emberDebug.assert('You can only pass a path to mut', rawRef[_emberGlimmerUtilsReferences.UPDATE]); | |
var wrappedRef = Object.create(rawRef); | |
wrappedRef[SOURCE] = rawRef; | |
wrappedRef[_emberGlimmerHelpersAction.INVOKE] = rawRef[_emberGlimmerUtilsReferences.UPDATE]; | |
wrappedRef[MUT_REFERENCE] = true; | |
return wrappedRef; | |
}; | |
}); | |
enifed('ember-glimmer/helpers/query-param', ['exports', 'ember-utils', 'ember-glimmer/utils/references', 'ember-debug', 'ember-routing'], function (exports, _emberUtils, _emberGlimmerUtilsReferences, _emberDebug, _emberRouting) { | |
/** | |
@module ember | |
@submodule ember-glimmer | |
*/ | |
'use strict'; | |
/** | |
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; | |
var named = _ref.named; | |
_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: _emberUtils.assign({}, named.value()) | |
}); | |
} | |
exports.default = function (vm, args) { | |
return new _emberGlimmerUtilsReferences.InternalHelperReference(queryParams, args); | |
}; | |
}); | |
enifed('ember-glimmer/helpers/readonly', ['exports', 'ember-glimmer/utils/references', 'ember-glimmer/helpers/mut'], function (exports, _emberGlimmerUtilsReferences, _emberGlimmerHelpersMut) { | |
/** | |
@module ember | |
@submodule ember-glimmer | |
*/ | |
'use strict'; | |
/** | |
The `readonly` helper let's you specify that a binding is one-way only, | |
instead of two-way. | |
When you pass a `readonly` binding from an outer context (e.g. parent component), | |
to to an inner context (e.g. child component), you are saying that changing that | |
property in the inner context does not change the value in the outer context. | |
To specify that a binding is read-only, when invoking the child `Component`: | |
```app/components/my-parent.js | |
export default Component.extend({ | |
totalClicks: 3 | |
}); | |
``` | |
```app/templates/components/my-parent.hbs | |
{{log totalClicks}} // -> 3 | |
{{my-child childClickCount=(readonly totalClicks)}} | |
``` | |
Now, when you update `childClickCount`: | |
```app/components/my-child.js | |
export default Component.extend({ | |
click() { | |
this.incrementProperty('childClickCount'); | |
} | |
}); | |
``` | |
The value updates in the child component, but not the parent component: | |
```app/templates/components/my-child.hbs | |
{{log childClickCount}} //-> 4 | |
``` | |
```app/templates/components/my-parent.hbs | |
{{log totalClicks}} //-> 3 | |
{{my-child childClickCount=(readonly totalClicks)}} | |
``` | |
### Objects and Arrays | |
When passing a property that is a complex object (e.g. object, array) instead of a primitive object (e.g. number, string), | |
only the reference to the object is protected using the readonly helper. | |
This means that you can change properties of the object both on the parent component, as well as the child component. | |
The `readonly` binding behaves similar to the `const` keyword in JavaScript. | |
Let's look at an example: | |
First let's set up the parent component: | |
```app/components/my-parent.js | |
export default Ember.Component.extend({ | |
clicks: null, | |
init() { | |
this._super(...arguments); | |
this.set('clicks', { total: 3 }); | |
} | |
}); | |
``` | |
```app/templates/components/my-parent.hbs | |
{{log clicks.total}} //-> 3 | |
{{my-child childClicks=(readonly clicks)}} | |
``` | |
Now, if you update the `total` property of `childClicks`: | |
```app/components/my-child.js | |
export default Ember.Component.extend({ | |
click() { | |
this.get('clicks').incrementProperty('total'); | |
} | |
}); | |
``` | |
You will see the following happen: | |
```app/templates/components/my-parent.hbs | |
{{log clicks.total}} //-> 4 | |
{{my-child childClicks=(readonly clicks)}} | |
``` | |
```app/templates/components/my-child.hbs | |
{{log childClicks.total}} //-> 4 | |
``` | |
@method readonly | |
@param {Object} [attr] the read-only attribute. | |
@for Ember.Templates.helpers | |
@private | |
*/ | |
exports.default = function (vm, args) { | |
var ref = _emberGlimmerHelpersMut.unMut(args.positional.at(0)); | |
var wrapped = Object.create(ref); | |
wrapped[_emberGlimmerUtilsReferences.UPDATE] = undefined; | |
return wrapped; | |
}; | |
}); | |
enifed('ember-glimmer/helpers/unbound', ['exports', 'ember-debug', 'ember-glimmer/utils/references'], function (exports, _emberDebug, _emberGlimmerUtilsReferences) { | |
/** | |
@module ember | |
@submodule ember-glimmer | |
*/ | |
'use strict'; | |
/** | |
The `{{unbound}}` helper disconnects the one-way binding of a property, | |
essentially freezing its value at the moment of rendering. For example, | |
in this example the display of the variable `name` will not change even | |
if it is set with a new value: | |
```handlebars | |
{{unbound name}} | |
``` | |
Like any helper, the `unbound` helper can accept a nested helper expression. | |
This allows for custom helpers to be rendered unbound: | |
```handlebars | |
{{unbound (some-custom-helper)}} | |
{{unbound (capitalize name)}} | |
{{! You can use any helper, including unbound, in a nested expression }} | |
{{capitalize (unbound name)}} | |
``` | |
The `unbound` helper only accepts a single argument, and it return an | |
unbound value. | |
@method unbound | |
@for Ember.Templates.helpers | |
@public | |
*/ | |
exports.default = function (vm, args) { | |
_emberDebug.assert('unbound helper cannot be called with multiple params or hash params', args.positional.values.length === 1 && args.named.keys.length === 0); | |
return _emberGlimmerUtilsReferences.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/make-bound-helper', 'ember-glimmer/utils/string', 'ember-glimmer/renderer', 'ember-glimmer/template_registry', 'ember-glimmer/setup-registry', 'ember-glimmer/dom'], function (exports, _emberGlimmerHelpersAction, _emberGlimmerTemplatesRoot, _emberGlimmerTemplate, _emberGlimmerComponentsCheckbox, _emberGlimmerComponentsText_field, _emberGlimmerComponentsText_area, _emberGlimmerComponentsLinkTo, _emberGlimmerComponent, _emberGlimmerHelper, _emberGlimmerEnvironment, _emberGlimmerMakeBoundHelper, _emberGlimmerUtilsString, _emberGlimmerRenderer, _emberGlimmerTemplate_registry, _emberGlimmerSetupRegistry, _emberGlimmerDom) { | |
/** | |
[Glimmer](https://github.com/tildeio/glimmer) is a templating engine used by Ember.js that is compatible with a subset of the [Handlebars](http://handlebarsjs.com/) syntax. | |
### Showing a property | |
Templates manage the flow of an application's UI, and display state (through | |
the DOM) to a user. For example, given a component with the property "name", | |
that component's template can use the name in several ways: | |
```app/components/person.js | |
export default Ember.Component.extend({ | |
name: 'Jill' | |
}); | |
``` | |
```app/components/person.hbs | |
{{name}} | |
<div>{{name}}</div> | |
<span data-name={{name}}></span> | |
``` | |
Any time the "name" property on the component changes, the DOM will be | |
updated. | |
Properties can be chained as well: | |
```handlebars | |
{{aUserModel.name}} | |
<div>{{listOfUsers.firstObject.name}}</div> | |
``` | |
### Using Ember helpers | |
When content is passed in mustaches `{{}}`, Ember will first try to find a helper | |
or component with that name. For example, the `if` helper: | |
```handlebars | |
{{if name "I have a name" "I have no name"}} | |
<span data-has-name={{if name true}}></span> | |
``` | |
The returned value is placed where the `{{}}` is called. The above style is | |
called "inline". A second style of helper usage is called "block". For example: | |
```handlebars | |
{{#if name}} | |
I have a name | |
{{else}} | |
I have no name | |
{{/if}} | |
``` | |
The block form of helpers allows you to control how the UI is created based | |
on the values of properties. | |
A third form of helper is called "nested". For example here the concat | |
helper will add " Doe" to a displayed name if the person has no last name: | |
```handlebars | |
<span data-name={{concat firstName ( | |
if lastName (concat " " lastName) "Doe" | |
)}}></span> | |
``` | |
Ember's built-in helpers are described under the [Ember.Templates.helpers](/api/classes/Ember.Templates.helpers.html) | |
namespace. Documentation on creating custom helpers can be found under | |
[Ember.Helper](/api/classes/Ember.Helper.html). | |
### Invoking a Component | |
Ember components represent state to the UI of an application. Further | |
reading on components can be found under [Ember.Component](/api/classes/Ember.Component.html). | |
@module ember | |
@submodule ember-glimmer | |
@main ember-glimmer | |
@public | |
*/ | |
/** | |
Use the `{{with}}` helper when you want to alias a property to a new name. This is helpful | |
for semantic clarity as it allows you to retain default scope or to reference a property from another | |
`{{with}}` block. | |
If the aliased property is "falsey", for example: `false`, `undefined` `null`, `""`, `0`, NaN or | |
an empty array, the block will not be rendered. | |
```handlebars | |
{{! Will only render if user.posts contains items}} | |
{{#with user.posts as |blogPosts|}} | |
<div class="notice"> | |
There are {{blogPosts.length}} blog posts written by {{user.name}}. | |
</div> | |
{{#each blogPosts as |post|}} | |
<li>{{post.title}}</li> | |
{{/each}} | |
{{/with}} | |
``` | |
Without the `as` operator, it would be impossible to reference `user.name` in the example above. | |
NOTE: The alias should not reuse a name from the bound property path. | |
For example: `{{#with foo.bar as |foo|}}` is not supported because it attempts to alias using | |
the first part of the property path, `foo`. Instead, use `{{#with foo.bar as |baz|}}`. | |
@method with | |
@for Ember.Templates.helpers | |
@param {Object} options | |
@return {String} HTML string | |
@public | |
*/ | |
/** | |
Execute the `debugger` statement in the current template's context. | |
```handlebars | |
{{debugger}} | |
``` | |
When using the debugger helper you will have access to a `get` function. This | |
function retrieves values available in the context of the template. | |
For example, if you're wondering why a value `{{foo}}` isn't rendering as | |
expected within a template, you could place a `{{debugger}}` statement and, | |
when the `debugger;` breakpoint is hit, you can attempt to retrieve this value: | |
``` | |
> get('foo') | |
``` | |
`get` is also aware of keywords. So in this situation | |
```handlebars | |
{{#each items as |item|}} | |
{{debugger}} | |
{{/each}} | |
``` | |
You'll be able to get values from the current item: | |
``` | |
> get('item.name') | |
``` | |
You can also access the context of the view to make sure it is the object that | |
you expect: | |
``` | |
> context | |
``` | |
@method debugger | |
@for Ember.Templates.helpers | |
@public | |
*/ | |
/** | |
The `partial` helper renders another template without | |
changing the template context: | |
```handlebars | |
{{foo}} | |
{{partial "nav"}} | |
``` | |
The above example template will render a template named | |
"-nav", which has the same context as the parent template | |
it's rendered into, so if the "-nav" template also referenced | |
`{{foo}}`, it would print the same thing as the `{{foo}}` | |
in the above example. | |
If a "-nav" template isn't found, the `partial` helper will | |
fall back to a template named "nav". | |
### Bound template names | |
The parameter supplied to `partial` can also be a path | |
to a property containing a template name, e.g.: | |
```handlebars | |
{{partial someTemplateName}} | |
``` | |
The above example will look up the value of `someTemplateName` | |
on the template context (e.g. a controller) and use that | |
value as the name of the template to render. If the resolved | |
value is falsy, nothing will be rendered. If `someTemplateName` | |
changes, the partial will be re-rendered using the new template | |
name. | |
@method partial | |
@for Ember.Templates.helpers | |
@param {String} partialName The name of the template to render minus the leading underscore. | |
@public | |
*/ | |
'use strict'; | |
exports.INVOKE = _emberGlimmerHelpersAction.INVOKE; | |
exports.RootTemplate = _emberGlimmerTemplatesRoot.default; | |
exports.template = _emberGlimmerTemplate.default; | |
exports.Checkbox = _emberGlimmerComponentsCheckbox.default; | |
exports.TextField = _emberGlimmerComponentsText_field.default; | |
exports.TextArea = _emberGlimmerComponentsText_area.default; | |
exports.LinkComponent = _emberGlimmerComponentsLinkTo.default; | |
exports.Component = _emberGlimmerComponent.default; | |
exports.Helper = _emberGlimmerHelper.default; | |
exports.helper = _emberGlimmerHelper.helper; | |
exports.Environment = _emberGlimmerEnvironment.default; | |
exports.makeBoundHelper = _emberGlimmerMakeBoundHelper.default; | |
exports.SafeString = _emberGlimmerUtilsString.SafeString; | |
exports.escapeExpression = _emberGlimmerUtilsString.escapeExpression; | |
exports.htmlSafe = _emberGlimmerUtilsString.htmlSafe; | |
exports.isHTMLSafe = _emberGlimmerUtilsString.isHTMLSafe; | |
exports._getSafeString = _emberGlimmerUtilsString.getSafeString; | |
exports.Renderer = _emberGlimmerRenderer.Renderer; | |
exports.InertRenderer = _emberGlimmerRenderer.InertRenderer; | |
exports.InteractiveRenderer = _emberGlimmerRenderer.InteractiveRenderer; | |
exports.getTemplate = _emberGlimmerTemplate_registry.getTemplate; | |
exports.setTemplate = _emberGlimmerTemplate_registry.setTemplate; | |
exports.hasTemplate = _emberGlimmerTemplate_registry.hasTemplate; | |
exports.getTemplates = _emberGlimmerTemplate_registry.getTemplates; | |
exports.setTemplates = _emberGlimmerTemplate_registry.setTemplates; | |
exports.setupEngineRegistry = _emberGlimmerSetupRegistry.setupEngineRegistry; | |
exports.setupApplicationRegistry = _emberGlimmerSetupRegistry.setupApplicationRegistry; | |
exports.DOMChanges = _emberGlimmerDom.DOMChanges; | |
exports.NodeDOMTreeConstruction = _emberGlimmerDom.NodeDOMTreeConstruction; | |
exports.DOMTreeConstruction = _emberGlimmerDom.DOMTreeConstruction; | |
}); | |
enifed('ember-glimmer/make-bound-helper', ['exports', 'ember-debug', 'ember-glimmer/helper'], function (exports, _emberDebug, _emberGlimmerHelper) { | |
/** | |
@module ember | |
@submodule ember-glimmer | |
*/ | |
'use strict'; | |
exports.default = makeBoundHelper; | |
/** | |
Create a bound helper. Accepts a function that receives the ordered and hash parameters | |
from the template. If a bound property was provided in the template, it will be resolved to its | |
value and any changes to the bound property cause the helper function to be re-run with the updated | |
values. | |
* `params` - An array of resolved ordered parameters. | |
* `hash` - An object containing the hash parameters. | |
For example: | |
* With an unquoted ordered parameter: | |
```javascript | |
{{x-capitalize foo}} | |
``` | |
Assuming `foo` was set to `"bar"`, the bound helper would receive `["bar"]` as its first argument, and | |
an empty hash as its second. | |
* With a quoted ordered parameter: | |
```javascript | |
{{x-capitalize "foo"}} | |
``` | |
The bound helper would receive `["foo"]` as its first argument, and an empty hash as its second. | |
* With an unquoted hash parameter: | |
```javascript | |
{{x-repeat "foo" count=repeatCount}} | |
``` | |
Assuming that `repeatCount` resolved to 2, the bound helper would receive `["foo"]` as its first argument, | |
and { count: 2 } as its second. | |
@private | |
@method makeBoundHelper | |
@for Ember.HTMLBars | |
@param {Function} fn | |
@since 1.10.0 | |
*/ | |
function makeBoundHelper(fn) { | |
_emberDebug.deprecate('Using `Ember.HTMLBars.makeBoundHelper` is deprecated. Please refactor to use `Ember.Helper` or `Ember.Helper.helper`.', false, { id: 'ember-htmlbars.make-bound-helper', until: '3.0.0' }); | |
return _emberGlimmerHelper.helper(fn); | |
} | |
}); | |
enifed('ember-glimmer/modifiers/action', ['exports', 'ember-utils', 'ember-metal', 'ember-debug', 'ember-views', 'ember-glimmer/helpers/action'], function (exports, _emberUtils, _emberMetal, _emberDebug, _emberViews, _emberGlimmerHelpersAction) { | |
'use strict'; | |
var MODIFIERS = ['alt', 'shift', 'meta', 'ctrl']; | |
var POINTER_EVENT_TYPE_REGEX = /^click|mouse|touch/; | |
function isAllowedEvent(event, allowedKeys) { | |
if (allowedKeys === null || typeof allowedKeys === 'undefined') { | |
if (POINTER_EVENT_TYPE_REGEX.test(event.type)) { | |
return _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 = { | |
// 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]; | |
} | |
}; | |
exports.ActionHelper = ActionHelper; | |
var ActionState = (function () { | |
function ActionState(element, actionId, actionName, actionArgs, namedArgs, positionalArgs, implicitTarget, dom) { | |
babelHelpers.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(); | |
} | |
// implements ModifierManager<Action> | |
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; | |
var namedArgs = this.namedArgs; | |
var target = undefined; | |
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; | |
var 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(); | |
} | |
_emberMetal.run(function () { | |
var args = _this.getActionArgs(); | |
var payload = { | |
args: args, | |
target: target | |
}; | |
if (typeof actionName[_emberGlimmerHelpersAction.INVOKE] === 'function') { | |
_emberMetal.flaggedInstrument('interaction.ember-action', payload, function () { | |
actionName[_emberGlimmerHelpersAction.INVOKE].apply(actionName, args); | |
}); | |
return; | |
} | |
if (typeof actionName === 'function') { | |
_emberMetal.flaggedInstrument('interaction.ember-action', payload, function () { | |
actionName.apply(target, args); | |
}); | |
return; | |
} | |
payload.name = actionName; | |
if (target.send) { | |
_emberMetal.flaggedInstrument('interaction.ember-action', payload, function () { | |
target.send.apply(target, [actionName].concat(args)); | |
}); | |
} else { | |
_emberDebug.assert('The action \'' + actionName + '\' did not exist on ' + target, typeof target[actionName] === 'function'); | |
_emberMetal.flaggedInstrument('interaction.ember-action', payload, function () { | |
target[actionName].apply(target, args); | |
}); | |
} | |
}); | |
}; | |
ActionState.prototype.destroy = function destroy() { | |
ActionHelper.unregisterAction(this); | |
}; | |
return ActionState; | |
})(); | |
exports.ActionState = ActionState; | |
var ActionModifierManager = (function () { | |
function ActionModifierManager() { | |
babelHelpers.classCallCheck(this, ActionModifierManager); | |
} | |
ActionModifierManager.prototype.create = function create(element, args, dynamicScope, dom) { | |
var named = args.named; | |
var positional = args.positional; | |
var implicitTarget = undefined; | |
var actionName = undefined; | |
var actionNameRef = undefined; | |
if (positional.length > 1) { | |
implicitTarget = positional.at(0); | |
actionNameRef = positional.at(1); | |
if (actionNameRef[_emberGlimmerHelpersAction.INVOKE]) { | |
actionName = actionNameRef; | |
} else { | |
var actionLabel = actionNameRef._propertyKey; | |
actionName = actionNameRef.value(); | |
_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 = _emberUtils.uuid(); | |
return new ActionState(element, actionId, actionName, actionArgs, named, positional, implicitTarget, dom); | |
}; | |
ActionModifierManager.prototype.install = function install(actionState) { | |
var dom = actionState.dom; | |
var element = actionState.element; | |
var 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[_emberGlimmerHelpersAction.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'], function (exports, _emberEnvironment) { | |
/* globals module, URL */ | |
'use strict'; | |
exports.default = installProtocolForURL; | |
var nodeURL = undefined; | |
var parsingNode = undefined; | |
function installProtocolForURL(environment) { | |
var protocol = undefined; | |
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 (typeof module === 'object' && typeof module.require === 'function') { | |
// 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`. | |
nodeURL = module.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-glimmer/utils/references', 'ember-metal', '@glimmer/reference', 'ember-views', 'ember-glimmer/component', 'ember-glimmer/syntax/curly-component', 'ember-glimmer/syntax/outlet', 'ember-debug'], function (exports, _emberGlimmerUtilsReferences, _emberMetal, _glimmerReference, _emberViews, _emberGlimmerComponent, _emberGlimmerSyntaxCurlyComponent, _emberGlimmerSyntaxOutlet, _emberDebug) { | |
'use strict'; | |
var backburner = _emberMetal.run.backburner; | |
var DynamicScope = (function () { | |
function DynamicScope(view, outletState, rootOutletState, targetObject) { | |
babelHelpers.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) { | |
_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) { | |
_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; | |
babelHelpers.classCallCheck(this, RootState); | |
_emberDebug.assert('You cannot render `' + self.value() + '` without a template.', template); | |
this.id = _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 = undefined; | |
do { | |
iteratorResult = iterator.next(); | |
} while (!iteratorResult.done); | |
var result = _this.result = iteratorResult.value; | |
// override .render function after initial render | |
_this.render = function () { | |
result.rerender(options); | |
}; | |
}; | |
} | |
RootState.prototype.isFor = function isFor(possibleRoot) { | |
return this.root === possibleRoot; | |
}; | |
RootState.prototype.destroy = function destroy() { | |
var result = this.result; | |
var env = this.env; | |
this.destroyed = true; | |
this.env = null; | |
this.root = null; | |
this.result = null; | |
this.render = null; | |
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 = []; | |
_emberMetal.setHasViews(function () { | |
return renderers.length > 0; | |
}); | |
function register(renderer) { | |
_emberDebug.assert('Cannot register the same renderer twice', renderers.indexOf(renderer) === -1); | |
renderers.push(renderer); | |
} | |
function deregister(renderer) { | |
var index = renderers.indexOf(renderer); | |
_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(current, next) { | |
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 = (function () { | |
function Renderer(env, rootTemplate) { | |
var _viewRegistry = arguments.length <= 2 || arguments[2] === undefined ? _emberViews.fallbackViewRegistry : arguments[2]; | |
var destinedForDOM = arguments.length <= 3 || arguments[3] === undefined ? false : arguments[3]; | |
babelHelpers.classCallCheck(this, Renderer); | |
this._env = env; | |
this._rootTemplate = rootTemplate; | |
this._viewRegistry = _viewRegistry; | |
this._destinedForDOM = destinedForDOM; | |
this._destroyed = false; | |
this._roots = []; | |
this._lastRevision = null; | |
this._isRenderingRoots = false; | |
this._removedRoots = []; | |
} | |
// renderer HOOKS | |
Renderer.prototype.appendOutletView = function appendOutletView(view, target) { | |
var definition = new _emberGlimmerSyntaxOutlet.TopLevelOutletComponentDefinition(view); | |
var outletStateReference = view.toReference(); | |
var targetObject = view.outletState.render.controller; | |
this._appendDefinition(view, definition, target, outletStateReference, targetObject); | |
}; | |
Renderer.prototype.appendTo = function appendTo(view, target) { | |
var rootDef = new _emberGlimmerSyntaxCurlyComponent.RootComponentDefinition(view); | |
this._appendDefinition(view, rootDef, target); | |
}; | |
Renderer.prototype._appendDefinition = function _appendDefinition(root, definition, target) { | |
var outletStateReference = arguments.length <= 3 || arguments[3] === undefined ? _glimmerReference.UNDEFINED_REFERENCE : arguments[3]; | |
var targetObject = arguments.length <= 4 || arguments[4] === undefined ? null : arguments[4]; | |
var self = new _emberGlimmerUtilsReferences.RootReference(definition); | |
var dynamicScope = new DynamicScope(null, outletStateReference, outletStateReference, true, targetObject); | |
var rootState = new RootState(root, this._env, this._rootTemplate, self, target, dynamicScope); | |
this._renderRoot(rootState); | |
}; | |
Renderer.prototype.rerender = function rerender(view) { | |
this._scheduleRevalidate(); | |
}; | |
Renderer.prototype.register = function register(view) { | |
var id = _emberViews.getViewId(view); | |
_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[_emberViews.getViewId(view)]; | |
}; | |
Renderer.prototype.remove = function remove(view) { | |
view._transitionTo('destroying'); | |
this.cleanupRootFor(view); | |
_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(); | |
} | |
} | |
}; | |
Renderer.prototype.destroy = function destroy() { | |
if (this._destroyed) { | |
return; | |
} | |
this._destroyed = true; | |
this._clearAllRoots(); | |
}; | |
Renderer.prototype.getElement = function getElement(view) { | |
// overriden in the subclasses | |
}; | |
Renderer.prototype.getBounds = function getBounds(view) { | |
var bounds = view[_emberGlimmerComponent.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; | |
var env = this._env; | |
var removedRoots = this._removedRoots; | |
var globalShouldReflush = undefined, | |
initialRootsLength = undefined; | |
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 = _emberMetal.runInTransaction(root, 'render'); | |
// globalShouldReflush should be `true` if *any* of | |
// the roots need to reflush | |
globalShouldReflush = globalShouldReflush || shouldReflush; | |
} | |
this._lastRevision = _glimmerReference.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 = _glimmerReference.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 = null; | |
// 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 || _glimmerReference.CURRENT_TAG.validate(this._lastRevisi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment